query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Find a specific event by `type`, `start_index` and `data` When matching the event `data`, it assumes `data` is JSON encoded dictionary, and returns the event if the `kwargs` is subset of the dictionary decoded from event `data` field. | async def find_event(self, event_type: str, start_index: int = 0, **kwargs: Any) -> Optional[Event]:
events = await self.events(start_index)
events = [e for e in events if e.type == event_type]
for e in events:
if _match(json.loads(e.data), **kwargs):
return e | [
"def find_event(self,resource,events,start,end):\n tpast = end + datetime.timedelta(0, 1) #after end\n t = tpast\n for log_time in events:\n # need to abstract in_sync comparison, should the events be dicts or\n # Resource objects?\n if (log_time>=start and log_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log account events as INFO Does nothing if get events API is not implemented. | async def log_events(self) -> None:
events = await self.dump_events()
if events:
self.client.logger.info("account(%s) events: %s", self.id, events) | [
"def info(self, *args: Any, **kwargs: Any) -> None:\n\n self.client.logger.info(*args, **kwargs)",
"def cmd_info(self):\r\n self.log.setLevel(logging.INFO)\r\n self.log.info('Switching to INFO threshold')",
"def on_account(self, account: AccountData) -> None:\n self.on_event(EVENT_AC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dump account events as JSON encoded string (well formatted, and indent=2) Returns empty string if get events API is not implemented. | async def dump_events(self) -> str:
try:
return json.dumps(list(map(self.event_asdict, await self.events())), indent=2)
except ClientError:
return "" | [
"def to_str(self):\n import json\n from JsonEncoder import JSONEncoder\n\n self._add_meta()\n return json.dumps(self.events, cls=JSONEncoder)",
"def get_events():\n\n #immplementation\n\n return json.dumps(events)",
"def events(self):\n r = requests.get(self.uri+'events'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns `Event` as dictionary object. As we use JSONencoded string field, this function tries to decoding all JSONencoded string as dictionary for pretty print event data in log. | def event_asdict(self, event: Event) -> Dict[str, Any]:
ret = asdict(event)
try:
ret["data"] = json.loads(event.data)
except json.decoder.JSONDecodeError:
pass
return ret | [
"def __decode(self, message):\n message = message.decode(\"UTF-8\")\n try:\n data = json.loads(message)\n except ValueError:\n data = None\n\n if type(data) is dict and 'event' in data:\n return data['event']\n\n return None",
"def from_json(cls,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log info to `client.logger` | def info(self, *args: Any, **kwargs: Any) -> None:
self.client.logger.info(*args, **kwargs) | [
"def info(self,msg):\n self.logger.info(msg)",
"def log() -> None:\n logging.basicConfig(level=logging.INFO)\n logger = logging.getLogger('discord')\n logger.setLevel(logging.DEBUG)\n handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\n handler.setFormatter(log... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the player's choice of token. | def get_player_token_choice():
# This function should make use of raw_input to ask the player what
# token they'd like to use. The only valid tokens are 'x' and 'o', so
# make sure to handle other inputs gracefully.
while True :
tokenchoice = raw_input('Which icon would you like to use? Enter "... | [
"def choice(self):\n return self.__choice",
"def player_choose(self) -> None:\n print(\"(1) Rock\\n(2) Paper\\n(3) Scissors\")\n self.human_choice = OPTIONS[int(input(\"Enter the number of your choice: \")) - 1]",
"def get_user_choice():\n\n return input('Your choice: ')",
"def playerS... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks the player where they want to place their token 19 and returns that answer. | def get_player_move(board, player_token):
# Make use of the raw_input to ask the user a question. Make sure only
# valid inputs work (use is_space_free function). The question should be
# asked until the player gives a correct place for their token (a while
# loop can help do that). | [
"def get_player_token_choice():\n\n # This function should make use of raw_input to ask the player what\n # token they'd like to use. The only valid tokens are 'x' and 'o', so\n # make sure to handle other inputs gracefully.\n while True :\n tokenchoice = raw_input('Which icon would you like to u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True or False to determine if the board is full or not. | def is_board_full(board):
# Review the board and check if it is full. | [
"def isFull(board):\n pass",
"def is_full(self):\r\n for row in range(BOARD_ROWS):\r\n for col in range(BOARD_COLUMNS):\r\n if self.__board[row][col] == EMPTY:\r\n return False\r\n return True",
"def is_board_full():\n num_pieces = np.sum(np.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the function to create an edifact section representing the beginning of a message | def test_create_message_beginning(self):
with self.subTest("Message beginning for a death registration"):
expected = MessageBeginning(party_id="XX1", date_time="201904230900",
ref_number="G5").segments
op_def = fixtures.create_operation_defin... | [
"def create_message_segment_beginning(message_beginning_dict: EdifactDict) -> MessageSegmentBeginningDetails:\r\n reference_segment = get_value_in_dict(dict_to_search=message_beginning_dict, key_to_find=\"RFF\")\r\n reference_values = reference_segment.split(SUB_SECTION_SEPARATOR)\r\n reference_number = re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the text for this menu item. | def text(self) -> "str": # type: ignore
if callable(self.text_generator):
text = self.text_generator()
else:
text = self.text_generator
if self.toggler is not None:
text += " ✓" if self.toggler() else ""
# Check if this menu item should be disabled, ... | [
"def _get_text(self) -> \"std::string\" :\n return _core.RadialMarkingMenu__get_text(self)",
"def text(self) -> str:\n attr_text = self.separator.join(self.values)\n return f'{self.name}=\"{attr_text}\"'",
"def get_item_text(self, widget, index):\n return widget.GetString(index)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats a command from the base command with class variables and adds them the the batches' command list | def format_command(self, unique_item=None):
inserts = {}
if '{exe}' in self.command_base:
inserts["exe"] = self.executable
if '{out}' in self.command_base:
inserts["out"] = '{out}'
if '{mod}' in self.command_base:
inserts["mod"] = self.model_path
... | [
"def getCmdString(self,cmd):\n if hasattr(cmd,\"command\") and isinstance(cmd.command, Command):\n cmd.command = cmd.command.composeCmdString()\n return super(self.__class__,self).getCmdString(cmd)\n elif isinstance(cmd,list):\n cmdarr = []\n for c in cmd:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds the path to the desired URLs dataset | def build_urls_path(dataset):
this_file = os.path.abspath(__file__)
this_folder = os.path.dirname(this_file)
datasets_path = pathlib.Path(this_folder) / ".." / 'datasets'
if dataset == 'inventory':
return datasets_path / 'inv_urls.csv'
if dataset == 'repatriation':
return datasets_... | [
"def build_dataset_url(app, uuid, basename, aset, extension):\n return '/apps/%s/datasets/%s/%s.%s.%s' % (app, uuid, basename, aset, extension)",
"def _generate_urls(self):\n if self.ssl is True:\n self.schema = \"https\"\n else:\n self.schema = \"http\"\n self.read_u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts a data retrieval job, with the desired function set of urls and keys | def start_parallel_job(func, urls, keys):
job_input = list(zip(urls, keys))
job_workers = multiprocessing.cpu_count() * 2
job_chunksize = len(job_input) // job_workers
with multiprocessing.Pool(job_workers) as p:
p.starmap(func, job_input, job_chunksize) | [
"def run_job():",
"def _worker_fn(url, dataset_fn, sampler_fn):\n dataset = dataset_fn(url)\n sampler = sampler_fn(dataset)\n return (dataset, sampler)",
"async def fetch_policy_data(self, urls: Dict[str, FetcherConfig] = None) -> Dict[str, Any]:\n # return value - /fetch-results mapped by url\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads a WAV from bytes. | def from_bytes(wav_bytes: bytes,
dtype: Optional[np.dtype] = None) -> Tuple[np.ndarray, int]:
return wav_io_python_bindings.read_wav_impl(io.BytesIO(wav_bytes), dtype) | [
"def read_wave(path):\n with contextlib.closing(wave.open(path, \"rb\")) as wf:\n num_channels = wf.getnchannels()\n assert num_channels == 1\n sample_width = wf.getsampwidth()\n assert sample_width == 2\n sample_rate = wf.getframerate()\n assert sample_rate in (8000, 16... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defining the placeholders for (batch) observations, actions and advantage values. | def define_placeholders(self):
sy_ob_no = tf.placeholder(shape=[None, self.ob_dim], name="ob", dtype=tf.float32)
if self.discrete:
sy_ac_na = tf.placeholder(shape=[None], name="ac", dtype=tf.int32)
else:
sy_ac_na = tf.placeholder(shape=[None, self.ac_dim], name="ac", dtyp... | [
"def _create_placeholders(self):\n self._observations_ph = tf.placeholder(\n tf.float32,\n shape=[None, self._observation_dim],\n name='observations')\n\n self._next_observations_ph = tf.placeholder(\n tf.float32,\n shape=[None, self._observation_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sampling an action from policy distribution. For discrete action space, we sample from the categorical distribution. For continuous action space, we sample from a normal distribution and construct the action with mean and log_std(taking an exp) parameters. | def sample_action(self, policy_parameters):
if self.discrete:
sy_logits_na = policy_parameters
sy_sampled_ac = tf.squeeze(tf.multinomial(sy_logits_na, num_samples=1), axis=1)
else:
sy_mean, sy_logstd = policy_parameters
z = tf.random_normal(shape=tf.shape(... | [
"def sample_action(self,policy):\n action_indx = bernoulli.rvs(policy[2])\n return policy[action_indx]",
"def sample_actions(available_actions, policy):\n\n def sample(probs, name):\n dist = Categorical(\n probs=probs,\n allow_nan_stats=False,\n name=name) # XXX Categorical... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Building computation graph for policy gradient algorithm. | def build_computation_graph(self):
# Defining placeholders for obs/states, actions and advantage values.
self.sy_ob_no, self.sy_ac_na, self.sy_adv_n = self.define_placeholders()
# Computing the logits.
self.policy_parameters = self.policy_forward_pass(self.sy_ob_no)
# Sampling a... | [
"def _setup_connected_gradients(self):\n # Index relevant variables based on self.goal_indices\n meta_obs0 = self.crop_to_goal(self.policy[0].obs_ph)\n meta_obs1 = self.crop_to_goal(self.policy[0].obs1_ph)\n worker_obs0 = self.crop_to_goal(self.policy[-1].obs_ph)\n worker_obs1 = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes advantages by (possibly) subtracting a baseline from the estimated Q values. If not nn_baseline, we just return q_n. | def compute_advantage(self, ob_no, q_n):
if self.nn_baseline:
b_n = self.sess.run(self.baseline_prediction, feed_dict={self.sy_ob_no: ob_no})
# Match the statistics.
b_n = np.mean(q_n) + np.std(q_n) * b_n
adv_n = q_n - b_n
else:
adv_n = q_n.co... | [
"def estimate_advantage(self, obs, q_values):\n\n # Estimate the advantage when nn_baseline is True,\n # by querying the neural network that you're using to learn the baseline\n if self.nn_baseline:\n baselines_normalized = self.actor.run_baseline_prediction(obs)\n # ensur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updating parameters of policy and value function(if nn_baseline). | def update_parameters(self, ob_no, ac_na, q_n, adv_n, epoch):
if self.nn_baseline:
# Computing targets for value function.
target_n = (q_n - np.mean(q_n)) / (np.std(q_n) + self.eps)
# Updating the value function.
self.sess.run(self.baseline_update_op, feed_dict={s... | [
"def update_policy(self):\n # get indexes wrt policy to retrieve appropriate reward and\n # transition matrix\n indexes = [np.arange(self.n_states_), self.policy_]\n\n reward = self.reward_[indexes]\n transition_proba = self.transition_proba_[indexes]\n\n # Compute updated ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test address breakpoints set with shared library of SBAddress work correctly. | def test_address_breakpoints (self):
self.build()
self.address_breakpoints() | [
"async def test_addressable_light(hass: HomeAssistant) -> None:\n config_entry = MockConfigEntry(\n domain=DOMAIN,\n data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE},\n unique_id=MAC_ADDRESS,\n )\n config_entry.add_to_hass(hass)\n bulb = _mocked_bulb()\n bulb.raw_stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lock and open the Grailfile at the given path. | def _open_grailfile(path):
# if the Grailfile is foobar/Grailfile, store a lock at foobar/.grail/LOCK
dotdir_path = _get_dotgrail_dir(path)
lock_path = dotdir_path / 'LOCK'
# Don't sit there waiting for the Grailfile to be unlocked
lock = fasteners.InterProcessLock(str(lock_path))
with fastener... | [
"def fileLocked(self, the_file, ctx=None):\n pass",
"def _lock( self, fileref=None, filehash=None ):\n\t\treturn self.__setlock( True, fileref=fileref, filehash=filehash )",
"def __enter__(self):\n self._rpc_lock()\n old_mask = os.umask(0o077)\n try:\n trial_count = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search up from the current directory for a Grailfile. | def find():
try:
grailfile_dir = next(filter(_grailfile_exists, _search_path()))
with _open_grailfile(grailfile_dir / 'Grailfile') as grailfile:
yield grailfile
except StopIteration as exc:
raise utils.GrailError("No Grailfile found") from exc | [
"def search_file(filename, search_path):\n for path in string.split(search_path, \":\"):\n candidate = os.path.join(path, filename)\n if os.path.exists(candidate):\n return os.path.abspath(candidate)\n return None",
"def search_file(filename, search_path):\n file_found = 0\n pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether or not a Grailfile exists in the given directory. | def _grailfile_exists(path):
grailfile = path / 'Grailfile'
return grailfile.exists() and not grailfile.is_dir() | [
"def check_files_in_directory(self, path):\n if os.path.exists(path):\n return os.path.isfile(path)",
"def file_exists(file_path):\n if not os.path.isfile(file_path):\n print(\"Could not find file under:\", file_path)\n return False\n return True",
"def file_exists(file_pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the optimal weights for the neural network with a step activation function. This function will not be graded if there are no optimal weights. See the PDF for instructions on what each weight represents. The hidden layer weights are notated by [1] on the problem set and the output layer weights are notated by [2]... | def optimal_step_weights():
w = example_weights()
# *** START CODE HERE ***
w["hidden_layer_0_1"] = 0.5
w["hidden_layer_1_1"] = 0
w["hidden_layer_2_1"] = -1
w["hidden_layer_0_2"] = 0.5
w["hidden_layer_1_2"] = -1
w["hidden_layer_2_2"] = 0
w["hidden_layer_0_3"] = -4
w["hidden_laye... | [
"def getWeightDict():\n \n weightDict = {}\n ## A list with weights in the same order as the suit factors above\n weightDict[8] = [0.29,0.22,0.21,0.28] \n weightDict[6] = [0.22,0.14,0.11,0.23,0.30]\n weightDict[5] = [0.29,0.34,0.37]\n weightDict[9] = [0.53,0.45,0.02]\n weightDict[4] = [0.46,0.35,0.19]\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Trivial helper to collect and return all nonmesons. | def _get_non_mesons(PDGIDs):
return [pid for pid in PDGIDs if pid not in _get_mesons(PDGIDs)] | [
"def obtener_notas(self):\n return list(self.notas)",
"def findnonc(self):\n # some aliases\n assert (self.stimuli!=None and self.signals!=None)\n\n dist = nx.algorithms.floyd_warshall(self)\n\n namesNONC = []\n for node in self.nodes():\n # search for paths fr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obviously all pentaquarks are baryons! | def test_pentaquarks_are_baryons(PDGIDs):
_pentaquarks = (PDGIDs.UCbarCUDPentaquark, PDGIDs.AntiUCbarCUDPentaquark)
for pid in _pentaquarks:
assert is_baryon(pid) | [
"def test_breed(self):\n\t\tpass",
"def mood():",
"def dummy_no_ephem():",
"def test_aromaticity_perception_benzene(self):\n mol = Molecule(smiles='c1ccccc1')\n aromatic_atoms, aromatic_bonds = mol.get_aromatic_rings()\n self.assertEqual(len(aromatic_atoms), 1)\n self.assertEqual(l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start the http server | def start(self):
self.log('Server started...')
self.httpd.serve_forever() | [
"async def start(self):\n self._app = web.Application(\n loop=self._loop, middlewares=self._middlewares\n )\n for resource in self._nyuki.HTTP_RESOURCES:\n resource.RESOURCE_CLASS.register(self._nyuki, self._app.router)\n log.info(\"Starting the http server on {}:{}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a file from the assets directory | def read_asset_file(self, file_name):
this_dir = os.path.dirname(os.path.realpath(__file__))
asset_file = os.path.join(this_dir, 'assets', file_name)
if not os.path.exists(asset_file):
raise Exception('The asset file \'{0}\' does not exist in {1}'.format(file_name, this_dir))
... | [
"def get_contents(filename):\n return resources.GetResource(os.path.join(_ASSETS_DIR, filename))",
"def read_asset_file(self, asset_file):\n assets_data = {}\n execfile(asset_file, assets_data)\n return assets_data",
"def _read_file(self):\n with open(self.file, 'r') as the_file:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a value to the HTTP session | def add_session(self, key, value):
global http_session
if not session_disabled:
http_session[key] = value
print('Add to session: {0}={1}'.format(key, value)) | [
"def session(self, value):\n self.AUTH_ARGS[\"session\"] = value\n self._SESSION_DT = datetime.datetime.utcnow() if value else None",
"def add_message_to_session(request, message):\n i = 0\n\n if 'messages' in request.session:\n while str(i) in request.session['messages']:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Output a JSON error message to the response stream | def output_error_json(self, message):
error = {
'result': 'error',
'error': [message]
}
self.write(json.dumps(error)) | [
"def send_json_error(err, code):\n msg = str(err).split(': ')[1]\n context = {'error': msg}\n return make_response(jsonify(**context), code)",
"def render_JSON_Error(message, data={}):\n res = {\n 'status': 'Error',\n 'err': message,\n }\n res.update(data)\n return HttpRespo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checking parameter list of numbers, if list is empty raise ValueError | def if_list_of_numbers_empty(self, list_of_numbers):
if len(list_of_numbers) != 0:
return list_of_numbers
else:
raise ValueError('List of numbers is empty') | [
"def validate_integers(*nums):\n for num in nums:\n if not isinstance(num, int):\n raise TypeError(\"Sorry. The function only works with integers.\")",
"def _checkInputList(self, inputValue, defaultValue, inputValName, headerValName):\n checkData = False\n finalVals = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes a list of integers and returns it without positive numbers | def remove_positives(self, list_of_numbers):
self.if_list_of_numbers_empty(list_of_numbers)
remove_positives_list = []
for i in list_of_numbers:
if i < 0:
remove_positives_list.append(i)
return remove_positives_list | [
"def remove_from_list_all_negative_numbers(in_list) -> list:\n i = 0\n while i < len(in_list):\n if in_list[i] < 0:\n del in_list[i]\n else:\n i = i + 1\n return in_list",
"def afisareNumereNegativeNenule(lst):\n rezultat = []\n for i in lst:\n if i < 0:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes a list of dates (integers) and removes those that are not 'leap years' | def filter_leaps(self, list_of_numbers):
self.if_list_of_numbers_empty(list_of_numbers)
leap_years_list = []
for i in list_of_numbers:
if (i % 4 == 0) and (i % 100 != 0) or (i % 400 == 0):
leap_years_list.append(i)
return leap_years_list | [
"def find_leap_years(year):",
"def leap_years(y1, y2):\r\n leaps = []\r\n takeouts = []\r\n for y in range(y1, y2, 1):\r\n if y % 4 == 0:\r\n leaps.append(True)\r\n if y % 400 != 0 and y % 100 == 0:\r\n takeouts.append(True)\r\n else:\r\n leaps.append... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> running_line(LOREM_IPSUM, 11, 0) ' ' >>> running_line(LOREM_IPSUM, 11, 5) ' Lorem' >>> running_line(LOREM_IPSUM, 11, 11) 'Lorem ipsum' >>> running_line(LOREM_IPSUM, 11, 22) ' dolor sit ' >>> running_line(LOREM_IPSUM, 11, 127) 'aliqua. ' >>> running_line(LOREM_IPSUM, 11, 138) ' Lore' | def running_line(text, window_size, tick):
return '' | [
"def returnMemopsLine(value):\n \n if value:\n \n wordString = value.replace(os.linesep,' ')\n wordString = wordString[:80]\n \n return wordString\n \n else:\n \n return value",
"def __manage_lines(message: str, color: str, first_line_start: str, new_line_start: str):\n index = 0\n out... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instance method on LinkedList. Add a new node with value newVal immediately after node with value val. | def insert_after(self, val, newVal):
current = self.head
while current._next:
if current.val == val:
new_node = Node(newVal, current._next)
current._next = new_node
self._size += 1
return
current = current._next | [
"def insert_after(self, val, newVal):\n current = self.head\n while current:\n if current.val == val:\n position = current._next\n current._next = Node(newVal)\n current._next._next = position\n self._size += 1\n bre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the UserOptions object from the supplied config file. If no filename is supplied, look in the default location (see importlinter.cli.lint_imports). | def read_user_options(config_filename: Optional[str] = None) -> UserOptions:
readers = settings.USER_OPTION_READERS.values()
if config_filename:
if config_filename.endswith(".toml"):
readers = [settings.USER_OPTION_READERS["toml"]]
else:
readers = [settings.USER_OPTION_RE... | [
"def _read_config_file():\n json_file_path = os.path.join(os.path.dirname(__file__),\n 'users-settings.json')\n with open(json_file_path) as settings:\n return json.load(settings)",
"def _load_user_config(self):\n config = RawConfigParser()\n config.add_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a string into a Python class. | def _string_to_class(string: str) -> Type:
components = string.split(".")
class_name = components[-1]
module_name = ".".join(components[:-1])
module = importlib.import_module(module_name)
cls = getattr(module, class_name)
assert isinstance(cls, type)
return cls | [
"def parse(cls, string):\n obj, i = cls.match(string, 0)\n if i != len(string):\n raise NotParseable(f\"Found unexpected {string[i]}.\", i + 1)\n return obj",
"def stringToClass(cls_str):\n import_stg1 = cls_str.split(\" \")[1]\n import_stg2 = import_stg1.replace(\"'\", \"\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a boolean (or None) for the include_external_packages option in user_options. | def _get_include_external_packages(user_options: UserOptions) -> Optional[bool]:
try:
include_external_packages_str = user_options.session_options["include_external_packages"]
except KeyError:
return None
# Cast the string to a boolean.
return include_external_packages_str in ("True", "t... | [
"def verify_use_incredibuild(ctx, option_name, value):\t\t\n\tif not _is_user_option_true(value):\n\t\treturn (True,\"\",\"\")\t\n\t(res, warning, error) = _verify_incredibuild_licence('Make && Build Tools Extension Package', 'All Platforms')\t\n\treturn (res, warning, error)",
"def toolHasOptions():\n pass",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a boolean (or None) for the show_timings option in user_options. | def _get_show_timings(user_options: UserOptions) -> bool:
try:
show_timings_str = user_options.session_options["show_timings"]
except KeyError:
return False
# Cast the string to a boolean.
return show_timings_str in ("True", "true") | [
"def test_get_option_strikes_realtime(self):\n pass",
"def test_get_option(self, debug_session, tdevice):\n debug_session.connect()\n\n result = debug_session.get_option(tdevice[\"option\"])\n assert result == False",
"def _get_areTipsAndTricksShown(self) -> \"bool\" :\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
End point for test response | def test():
return "Test Response", 201 | [
"def test_send_result(self):\n pass",
"def test_ok_returned_ticket(self):\n process_result = process_response(self.resp_ok)\n self.assertEqual(process_result[\"detail\"], self.sample_ok)",
"def test_get_responce(self):\n self.assertEqual(self.r.status_code, 200)",
"def end_test(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a generic printer that can handle a list of text and print that to screen or a single string | def multi_printer(text, player_name=None):
if isinstance(text, list):
for line in text:
if line == ' ': print ''
if player_name is not None: line = replace_player_name(line, player_name)
lines = textwrap.wrap(line, CHARS_PER_LINE)
for wrapped_line in lines: print wrapped_line
elif isinstance(text, bases... | [
"def ansiprint(self, *args: str, **kwargs):\n\n new_args = (str(i) if not isinstance(i, str) else i for i in args)\n parts = self.parse(*new_args, aslist=True)\n builtins.print(*parts, **kwargs)",
"def print_text(txt):\n print(txt)",
"def w(text=''):\n if printing:\n print(text... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
searchs the string for and inserts the player_name passed in returns the string | def replace_player_name(text, player_name):
sub_string = "<playername>"
return string.replace(text, sub_string, player_name) | [
"def find_player(search_str, ap, pp):\n # clean periods, since they aren't consistent between sources\n search_str = search_str.replace(\".\", \"\")\n # check if any of the search words are in the full name\n # TODO: incorporate the close matches in here as well\n checkfunc = (\n lambda name: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initializes the game windows as new windows and initializes some color pairs | def init_windows(self, stdscr):
if USE_CURSES and self.terminal_size():
self.back_win = stdscr
self.fill_back()
self.main_win = curses.newwin(MAIN_WIN_ROWS, MAIN_WIN_COLS, 2, 2)
self.input_win = curses.newwin(INPUT_WIN_ROWS, INPUT_WIN_COLS, 33, 2)
self.stat_win = curses.newwin(STAT_WIN_ROWS, STAT_WIN_C... | [
"def setup(self):\n self.nog = nog.NumberOfGames(self.window)\n self.sd = sd.SavedData()\n self.create()\n self.window.geometry('265x350')\n self.window.config(bg='White')\n self.window.title('Tic-Tac-Toe')\n self.window.mainloop()",
"def init_colors(self):\n\t\tcu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
erases the main game window, then either writes the list or the string to the main window wrapping the text to fit the last row written to is stored in self | def write_main(self, text, player_name=None, row=1, col=1):
self.main_win.erase()
if isinstance(text, list):
for line in text:
if line == " ": row += 1
if player_name is not None: line = replace_player_name(line, player_name)
self.main_win.addstr(row, col, line, curses.A_BOLD)
row +=1
if row ... | [
"def display(self):\n self.window.erase()\n for idx, item in enumerate(self.items[self.top:self.top + self.max_lines]):\n # Highlight the current cursor line\n if idx == self.current:\n self.window.addstr(idx, 0, item, curses.color_pair(2))\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
one row below the most recent row written to writes out a list of strings to the main window | def write_main_artifact(self, text):
row = self.main_row + 1
if isinstance(text, list):
for line in text:
if line == " ": row += 1
self.main_win.addstr(row, ui.COL, line, curses.A_BOLD)
row +=1
if row >= MAIN_WIN_ROWS: break | [
"def write_main(self, text, player_name=None, row=1, col=1):\n\t\tself.main_win.erase()\n\t\tif isinstance(text, list):\n\t\t\tfor line in text:\n\t\t\t\tif line == \" \": row += 1\n\t\t\t\tif player_name is not None: line = replace_player_name(line, player_name)\n\t\t\t\tself.main_win.addstr(row, col, line, curses... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handles writting a string to middle of the main window starting 1 row below the main body of text | def write_main_mid(self, text):
row = self.main_row + 1
lines = textwrap.wrap(text, CHARS_PER_LINE)
for line in lines:
self.main_win.addstr(row, ui.COL, line, curses.A_BOLD)
row += 1
if row >= MAIN_WIN_ROWS: break
if row < MAIN_WIN_ROWS:
blank_line = " "*int(MAIN_WIN_COLS-2)
for _ in range(row, M... | [
"def write_main_bottom(self, text):\n\t\tif len(text) > MAIN_WIN_COLS-2: text = text[:MAIN_WIN_COLS-2]\n\t\tblank_line = ' '*40\n\t\tself.main_win.addstr(MAIN_WIN_ROWS-1, ui.COL, blank_line)\n\t\tself.main_win.addstr(MAIN_WIN_ROWS-1, ui.COL, text, curses.color_pair(4))\n\t\tself.main_win.refresh()",
"def write_ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
writes a signle line of text less that the length of the main window to the last row of the main window | def write_main_bottom(self, text):
if len(text) > MAIN_WIN_COLS-2: text = text[:MAIN_WIN_COLS-2]
blank_line = ' '*40
self.main_win.addstr(MAIN_WIN_ROWS-1, ui.COL, blank_line)
self.main_win.addstr(MAIN_WIN_ROWS-1, ui.COL, text, curses.color_pair(4))
self.main_win.refresh() | [
"def write_main_mid(self, text):\n\t\trow = self.main_row + 1\n\t\tlines = textwrap.wrap(text, CHARS_PER_LINE)\n\t\tfor line in lines:\n\t\t\tself.main_win.addstr(row, ui.COL, line, curses.A_BOLD)\n\t\t\trow += 1\n\t\t\tif row >= MAIN_WIN_ROWS: break\n\t\tif row < MAIN_WIN_ROWS:\n\t\t\tblank_line = \" \"*int(MAIN_W... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
writes to the stat window that typically contains the character's illness, hunger and cold. Inventory also gets written to this window stores the last row written to in this window stops if we get to the last row | def write_stat(self, text):
self.stat_win.erase()
row = 1
lines = textwrap.wrap(text, 26)
for line in lines:
line = line[:STAT_WIN_COLS-1]
self.stat_win.addstr(row, ui.COL, line, curses.color_pair(2))
row += 1
if row >= STAT_WIN_ROWS:
self.stat_win.refresh()
break
self.stat_win.refresh()
... | [
"def write_stat_append(self, text):\n\t\trow = self.stat_row\n\t\tlines = textwrap.wrap(text, 26)\n\t\tfor line in lines:\n\t\t\tself.stat_win.addstr(row, ui.COL, line, curses.color_pair(3))\n\t\t\trow += 1\n\t\t\tif row >= STAT_WIN_ROWS: \n\t\t\t\tself.stat_win.refresh()\n\t\t\t\tbreak\n\t\tself.stat_win.refresh()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
appends to what is currently in the stat window. This function is not currently called anywhere | def write_stat_append(self, text):
row = self.stat_row
lines = textwrap.wrap(text, 26)
for line in lines:
self.stat_win.addstr(row, ui.COL, line, curses.color_pair(3))
row += 1
if row >= STAT_WIN_ROWS:
self.stat_win.refresh()
break
self.stat_win.refresh() | [
"def write_stat(self, text):\n\t\tself.stat_win.erase()\n\t\trow = 1\n\t\tlines = textwrap.wrap(text, 26)\n\t\tfor line in lines:\n\t\t\tline = line[:STAT_WIN_COLS-1]\n\t\t\tself.stat_win.addstr(row, ui.COL, line, curses.color_pair(2))\n\t\t\trow += 1\n\t\t\tif row >= STAT_WIN_ROWS: \n\t\t\t\tself.stat_win.refresh(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
writes a list or string to the time window stops when we get to the bottom of the window | def write_time(self, text):
self.time_win.erase()
row = 1
for line in text:
self.time_win.addstr(row, ui.COL, line, curses.color_pair(4))
row += 1
if row >= TIME_WIN_ROWS:
break | [
"def test_sliding_time_window(self):\n dst = \"ngc5921.split.sliding_time_window.ms\"\n ref = 'ngc5921_statwt_ref_test_sliding_time_window.ms'\n timebin = \"300s\"\n \"\"\"\n row_to_rows = []\n row_to_rows.append([0, 6])\n row_to_rows.append([0, 7])\n row_to_r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
refreshes all screens except the back window | def refresh_all(self):
self.stat_win.refresh()
self.input_win.refresh()
self.time_win.refresh()
self.main_win.refresh() | [
"def refresh(self):\n\n for win in self.get_window():\n win.refresh()\n self.scr.refresh()",
"def _refresh_all(self) -> None:\n self._window_all.refresh()",
"def back_to_home_gui(self):\n self.forget_non_home_gui()\n self.seeds_path.set(\"\")\n self.initilize... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates that the terminal is a large enough size to play the game in curses | def terminal_size(self):
# rows, columns = os.popen('stty size', 'r').read().split()
try:
rows, columns = subprocess.check_output(['stty','size']).decode().split()
if int(rows) >= int(MIN_ROWS) and int(columns) >= int(MIN_COLS):
return True
return False
except Exception:
return False | [
"def screenSizeAdjust(): \n cls()\n printNow(\"RESIZE JES COMMAND WINDOW TO HERE\\n\" + '-'*70 + '\\n'* 18 +\n \"For the best experience, please resize the JES command window so \" +\n \"that the message\\n'RESIZE JES COMMAND WINDOW TO HERE' above \" +\n \"is visible on your screen.\\n\\n\" + \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initializes some colors pairs for curses to be used when printing text | def init_colors(self):
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_CYAN, curses.COL... | [
"def __init__(self, stdscr, pair_number, fg_color, bg_color = -1):\n self.pair_number = pair_number\n curses.init_pair(pair_number, fg_color, bg_color)\n self.stdscr = stdscr",
"def init_colors():\n curses.initscr()\n curses.start_color()\n curses.use_default_colors()\n # default ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
prints the actual help menu in curses in the main window | def print_help(self):
self.main_win.erase()
x, y = self.print_text(4,2,"Verb ", curses.A_BOLD)
x, y = self.print_text(x,y,"::", curses.color_pair(2))
x, y = self.print_text(x,y," Explanation of verb usage")
for key in VERB_DICT:
y += 2
x = 4
self.print_text(x,y,key, curses.A_BOLD)
self.prin... | [
"def help_menu(self):\r\n self.game_help()\r\n title_screen()",
"def printHelp():\n cls() # clear the screen\n printNow(help_msg_1)\n requestString(\"Press ENTER for the next page of help.\")\n cls()\n printNow(help_msg_2)",
"def on_helpAboutMenuItem_activate(self,*args):\n print \"He... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
prints the final credits in curses in the main window | def roll_credits(self):
self.main_win.erase()
x, y = self.print_text(4,2,"Credits ", curses.A_BOLD)
for key in CREDITS:
y += 2
x = 25
self.print_text(x,y,key, curses.A_BOLD)
self.write_main_artifact(PAVO) | [
"def print_credits(self):\n # Get header messages\n message = '\\n' + self.prefix + plugin_strings[\n 'Credits'\n ].get_string() + '\\n' + '=' * 61 + '\\n\\n'\n\n # Loop through all groups in the credits\n for group in gungame_credits:\n\n # Add the current g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
orthogonalize features with an ensemble of estimators using precomputed set of ensemble weights (following Chernozhukov et al., 2017) | def _two_step_orthogonalization(
nfolds: int,
tsize: int,
df_folds: list,
fold_combinations: tuple,
nuisance_estim: list,
ensemble_weights: np.array,
in_ensemble_weights=False,
) -> tuple:
# initiate the list storage for orthogonalized features
orthogonalized_target_and_treatment = [... | [
"def ensemble_weights_cv(\n X: np.array,\n y: np.array,\n nuisance_estimators: list,\n ensemble_estimator: object,\n nfolds=5,\n) -> np.array:\n # stack features together for consistent splitting in cross-validation\n df = np.hstack([y, X])\n\n # create sum(nfolds) combinations of folds so t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
orthogonalize features with an average over ensembles of estimators which are computed using an extra fold (hence 3 steps); this is a similar procedure as DML in Chernozhukov et al. (2017) but with an extra step in the middle instead of crossvalidation prior to estimation | def _three_step_orthogonalization(
nfolds: int,
tsize: int,
df_folds: list,
fold_combinations: tuple,
nuisance_estim: list,
ensemble_estim: list,
) -> tuple:
# initiate the list storage for orthogonalized features
orthogonalized_target_and_treatment = []
# routine is rerun nfold tim... | [
"def _two_step_orthogonalization(\n nfolds: int,\n tsize: int,\n df_folds: list,\n fold_combinations: tuple,\n nuisance_estim: list,\n ensemble_weights: np.array,\n in_ensemble_weights=False,\n) -> tuple:\n # initiate the list storage for orthogonalized features\n orthogonalized_target_an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper function to preestimate ensemble weights for k features in Double Machine Learning algorithm using nfolds crossvalidation | def ensemble_weights_cv(
X: np.array,
y: np.array,
nuisance_estimators: list,
ensemble_estimator: object,
nfolds=5,
) -> np.array:
# stack features together for consistent splitting in cross-validation
df = np.hstack([y, X])
# create sum(nfolds) combinations of folds so that each piece ... | [
"def kfolds_making(dataset,label,K=10):\n #data = dataset-1\n #label = dataset-1\n dataset, label = shuffle(dataset, label, random_state=0)\n print(label)\n kfold_DT = KFold(K)\n\n performances_DT = 0\n performances_NN = 0\n performances_SVM = 0\n performances_KNN = 0\n #print()\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the component graph that shows all component connections | def component_graph(self):
packages = self.packages()
return self.graph_generator.generate(packages, self.services(packages)).export() | [
"def get_connected_components(self):\r\n # Reset the network.\r\n self.reset_network()\r\n\r\n # Keep track of the number of nodes visited.\r\n num_visited = 0\r\n\r\n # Make the result list of lists.\r\n components = []\r\n\r\n # Repeat until all nodes are in a conn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a sliding window (of width n) over data from the iterable s > (s0,s1,...s[n1]), (s1,s2,...,sn), ... | def window(seq, n):
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result | [
"def sliding_window(iterable, window_size=3, padded=False):\n\n # get an iterator from the iterable (df row)\n i = iter(iterable.index)\n\n # prepare an empty array for the window\n win = [0] if padded else []\n\n # fill the window with prev, current and next elements\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert user normal attributes in "normal_users" table | def insertNormalUserAttrsQuery(self,user_id,normal_username,normal_password):
return ibs_db.createFunctionCallQuery("insert_normal_user",(user_id, dbText(normal_username), dbText(normal_password))) | [
"def updateNormalUserAttrsQuery(self,user_id,normal_username,normal_password):\n return ibs_db.createFunctionCallQuery(\"update_normal_user\",(user_id, dbText(normal_username), dbText(normal_password)))",
"def insert_info(self):\n\t\tself.get_connection()\n\t\tc = self.conn.cursor()\n\t\t#For every USER in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update user normal attributes in "normal_users" table | def updateNormalUserAttrsQuery(self,user_id,normal_username,normal_password):
return ibs_db.createFunctionCallQuery("update_normal_user",(user_id, dbText(normal_username), dbText(normal_password))) | [
"def insertNormalUserAttrsQuery(self,user_id,normal_username,normal_password):\n return ibs_db.createFunctionCallQuery(\"insert_normal_user\",(user_id, dbText(normal_username), dbText(normal_password)))",
"def update_users():\n\tfor user in User.query.all():\n\t\tadd_or_update_user( user.name)",
"def set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete user normal attributes from "normal_users" table | def deleteNormalUserAttrsQuery(self,user_id):
return ibs_db.createFunctionCallQuery("delete_normal_user",(user_id,)) | [
"def remove_all_attributes_user(self, username):\n request = Request(\n method=\"delete\", endpoint=\"/user/{}/attributes/truncate\".format(username)\n )\n\n def response_handler(resp):\n if not resp.is_success:\n raise RemoveAllAttributes(resp, request)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if normal_username multi str arg is exists, and doesn't contain invalid characters current_username shows current usernames, so we don't run into situation that we print an error for username that belongs to this username | def checkNormalUsernameForAdd(self,request):
request.needAuthType(request.ADMIN)
request.checkArgs("normal_username","current_username")
request.getAuthNameObj().canChangeNormalAttrs(None)
usernames=self.__filterCurrentUsernames(request)
bad_usernames=filter(lambda username: not ... | [
"def clean_username(self):\n if not alnum_re.search(self.cleaned_data['username']):\n raise forms.ValidationError('Usernames can only contain letters, numbers and underscores')\n try:\n user = User.objects.get(username__exact=self.cleaned_data['username'])\n except User.Do... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create_batches loader = DataLoader(dataset=self, batch_size=batch_size, shuffle=shuffle, collate_fn=self.collate_fn(device), pin_memory=False) | def create_batches(self, batch_size=128, shuffle=True):
loader = DataLoader(dataset=self,
batch_size=batch_size,
shuffle=shuffle, collate_fn=self.collate_fn)
return loader | [
"def create_loaders(self):\n self.spam_data.text_to_tensors()\n print('creating dataloaders')\n train_data = TensorDataset(self.spam_data.train_inputs, \n self.spam_data.train_masks, \n self.spam_data.train_labels)\n t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is a fix for correcting the RETN address based on IDA Pro's function "length" This is done by rewinding 3 bytes from the current retnAddress to find 0xC2, 0xC3, 0xEB, 0xE9. It's no way near pefect, but most addresses are corrected. A new copy of the addresses will be saved, and returns a new function list... | def __correctIDAProRETNs(self, dbg, functions): | [
"def correctFips(stateCodes, FIPS):\n return [str(stateCode) + str(fcode).zfill(3) for stateCode,fcode in zip(stateCodes,FIPS)]",
"def _check_lfn2pfn(self):\n for lfn in SE_PROBES_BYTYPE[self.rsetype]:\n\n # this is what rucio does\n pfn = self.proto['scheme'] + '://' + self.proto[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will create breakpoints.txt for InMemoryFuzzer.py | def createBreakpoints(self): | [
"def create_fuzzer(out):\n with open(fuzzer_filename, 'r') as fuzzer_file:\n for line in fuzzer_file:\n out.write(line)",
"def setUp(self):\n for patch_name in ['a', 'b', 'c']:\n open(os.path.join(self.STASH_PATH, patch_name), 'w').write(patch_name.upper())",
"def load_bre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main function for class Tracer pid process ID (for pydbg.attach()) functions an array of modified/corrected function list | def run(self, pid, functions):
raw_input("[*] When you're ready, press [ENTER] to continue...")
dbg = pydbg()
dbg.attach(pid)
try:
functions = self.__correctIDAProRETNs(dbg, functions) #Correct RETN addresses - IDA specific problem
except:
print "[*] Error: Either you don't have the right functio... | [
"def updatePidList(self):",
"def frompointer(*args) -> \"tid_array *\":\n return _ida_pro.tid_array_frompointer(*args)",
"def advapi32_ProcessTrace(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"HandleArray\", \"HandleCount\", \"StartTime\", \"EndTime\"])\n raise RuntimeError('API not implem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The interface for selecting the process to monitor | def selectProcessID():
processes = []
dbg = pydbg()
#Gather an array of active processes
for (pid, pname) in dbg.enumerate_processes():
processes.append([pid, pname])
print "\n=== Please pick a process to monitor ===\n"
print "Choice Process Name"
counter = 0
#Prepare a choice list for the user
... | [
"def launch(self):\n self.processdev.start()\n pid = self.processdev.pid\n p = psutil.Process(self.processdev.pid)\n p.nice(psutil.HIGH_PRIORITY_CLASS)\n print(str(pid) + \"est le pid\")",
"def monitor(self, listener=None):\r\n\r\n if not self._process_watcher:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read portfolio from JSON file. | def read_json_portfolio(portfolio_file: str) -> dict:
with open(portfolio_file, "r") as p_file:
return json.load(p_file) | [
"def load_json(path):\n with open(path, 'r') as f:\n new_projects = json.load(f)\n\n return new_projects",
"def _read_json(self,fname):\n\n with open(fname) as f:\n data = json.load(f)\n\n return data",
"def read_impact_data_json(self):\n try:\n json_file ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Store a rebalanced portfolio. | def store_rebalanced_portfolio(portfolio: dict, path: str):
# Sort stocks by WKN
portfolio["Stocks"] = sorted(portfolio["Stocks"], key=lambda x: x["WKN"])
with open(path, "w") as file_:
json.dump(portfolio, file_, indent=4) | [
"def backtest_portfolio(self):\n\n # Construct the portfolio DataFrame to use the same index\n # as 'positions' and with a set of 'trading orders' in the\n # 'pos_diff' object, assuming market open prices.\n portfolio = self.positions*self.bars['Open']\n pos_diff = self.positions.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a portfolio is valid. | def valid_portfolio(portfolio: dict) -> bool:
ratio_sum = sum([stock["GoalRatio"] for stock in portfolio["Stocks"]])
if abs(1.0 - ratio_sum) > 1e-4:
print(f"Goal ratios of stocks sum up to {ratio_sum} instead of 1.0")
return False
if any(
[
stock["Price"] is None or stoc... | [
"def enough_assets(portfolio, log=True):\n\n nb_assets = len(portfolio.values[\"2016-06-01\"])\n\n if nb_assets > 15 and nb_assets < 40:\n if log:\n print(\"La quantité d'action pour ce portfolio est correcte\")\n return True\n\n if log:\n print(\"La quantité d'action pour c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adjust the number of new stocks to the target investment value. | def _adjust_new_stocks_to_target(portfolio: dict, portf_goal_val: float):
# Compute current total value (including reinvest)
portf_total_val = _calc_total_val(portfolio)
# Get sorted list of DeltaRatio for all stocks
ascending_ppp = sorted(portfolio["Stocks"], key=lambda x: x["DeltaRatio"])
if por... | [
"def update(self, target):\n change = (self.coeff * (target - self.price) +\n self.momentum * self.last_change)\n self.last_change = change\n \n limiter = self.buyer and min or max\n self.price = int(limiter(self.price + change, self.limit))",
"def increment_sto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate the rebalanced ratio of stocks in a portfolio. | def _eval_rebalanced_ratio(portfolio: dict, portf_total_val: float):
for stock in portfolio["Stocks"]:
stock["RebalancedRatio"] = (
(stock["Shares"] + stock["NewShares"]) * stock["Price"]
) / portf_total_val | [
"def calculate_portfolio_return(self, price_df: pd.DataFrame) -> None:\n # Keep only data of stocks in the portfolio\n select_query = ' or '.join(f\"symbol == '{val[1]}'\" for val in self.stocks)\n self.price_df = price_df.query(select_query) \n # Calculate returns\n self.pri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate current portfolio value. | def _calc_current_val(portfolio: dict) -> float:
return sum([stock["Shares"] * stock["Price"] for stock in portfolio["Stocks"]]) | [
"def _calc_total_val(portfolio: dict) -> float:\n if \"NewShares\" in portfolio[\"Stocks\"][0]:\n return _calc_current_val(portfolio) + _calc_reinvest_val(portfolio)\n\n return _calc_current_val(portfolio)",
"def current_values(self):\n\t\t# remove duplicate tickers\n\t\tsymbs = list(set(np.array(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate total value of the portfolio. | def _calc_total_val(portfolio: dict) -> float:
if "NewShares" in portfolio["Stocks"][0]:
return _calc_current_val(portfolio) + _calc_reinvest_val(portfolio)
return _calc_current_val(portfolio) | [
"def __calculate_total_portfolio_val(self, df):\n result = df.sum(axis=1)\n return result",
"def _calc_current_val(portfolio: dict) -> float:\n return sum([stock[\"Shares\"] * stock[\"Price\"] for stock in portfolio[\"Stocks\"]])",
"def total(self):\n return self.sum.value",
"def total... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for interface BDD complexity. Returns true if above threshold | def condition(iface: Interface) -> bool:
if len(iface.pred) > maxnodes:
print("Interface # nodes {} exceeds maximum {}".format(len(iface.pred), maxnodes))
return True
return False | [
"def __check_constraints_feasibility(self):\n pass",
"def should_hit(self):\n \n return self.hand.compute_bj_count() < 17",
"def __check_objective_feasibility(self):\n pass",
"def testable(self):\n return len(self.outputs) > 0",
"def assert_numbers_of_calls_within_limits(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolves a (parametrized) strategy to a tuple of strategy and the new field name. | def resolve_strategy(
self, strategy: FieldStrategy | ParametrizedFieldStrategy
) -> Tuple[FieldStrategy, FieldNameFunc]:
if isinstance(strategy, dict):
return (strategy["strategy"], self.get_name_func_from_parameters(strategy))
else:
return (strategy, self.get_name_f... | [
"def addStrategy(self, s) -> None:\n ...",
"def _set_strategy(strategy: str) -> StrategyFunction:\n if strategy == \"all_perm\":\n return create_all_permutations\n if strategy == \"step\":\n return step_values\n if strategy == \"random\":\n return rando... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a ZClass for 'base_class' in 'pack' (before a ProductContext is available). 'pack' may be either the module which is to contain the ZClass or its 'globals()'. If 'nice_name' is passed, use it as the name for the created class, and create the "ugly" '_ZClass_for_...' name as an alias; otherwise, just use the "ugl... | def createZClassForBase( base_class, pack, nice_name=None, meta_type=None ):
d = {}
zname = '_ZClass_for_' + base_class.__name__
if nice_name is None:
nice_name = zname
exec 'class %s: pass' % nice_name in d
Z = d[nice_name]
Z.propertysheets... | [
"def manage_addZClass(self, id, title='', baseclasses=[],\n meta_type='', CreateAFactory=0, REQUEST=None,\n zope_object=0):\n if bad_id(id) is not None:\n raise 'Bad Request', (\n 'The id %s is invalid as a class name.' % id)\n if not meta_type: meta_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a Z Class | def manage_addZClass(self, id, title='', baseclasses=[],
meta_type='', CreateAFactory=0, REQUEST=None,
zope_object=0):
if bad_id(id) is not None:
raise 'Bad Request', (
'The id %s is invalid as a class name.' % id)
if not meta_type: meta_type=id
... | [
"def add_class(self, class_):\n self.classes.append(class_)",
"def AddZLayer(self, *args):\n return _Graphic3d.Graphic3d_StructureManager_AddZLayer(self, *args)",
"def add_object_class(self, parsername, kind) :\n self.object_classes[parsername] = kind",
"def newClass(self, name = None):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create Z instance. If called with a RESPONSE, the RESPONSE will be redirected to the management screen of the new instance's parent Folder. Otherwise, the instance will be returned. | def createInObjectManager(self, id, REQUEST, RESPONSE=None):
i=mapply(self._zclass_, (), REQUEST)
try: i._setId(id)
except AttributeError:
i.id=id
folder=durl=None
if hasattr(self, 'Destination'):
d=self.Destination
if d.im_self.__class__ is Fa... | [
"def create_project():\n data = {'name': 'new project', 'id': 123}\n headers = {'location': 'http://chen.rotemlevy.name/project/123'}\n return Response(data, status=201, headers=headers)",
"def create(self) -> None:\n url = f\"{self.base_url()}/loop/create/{self.name}?templateName={self.template}\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edit an existing Workspace. | def edit(self, name=UNSPECIFIED, extraParams={}):
import labstep.entities.workspace.repository as workspaceRepository
return workspaceRepository.editWorkspace(self, name, extraParams=extraParams) | [
"def workspace(string, projectPath=\"string\", updateAll=bool, fileRuleList=bool, fileRuleEntry=\"string\", renderTypeEntry=\"string\", renderType=\"string\", active=bool, expandName=\"string\", objectType=\"string\", saveWorkspace=bool, shortName=bool, objectTypeList=bool, fileRule=\"string\", filter=bool, newWork... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a list of Order Requests within this specific Workspace, | def getOrderRequests(
self, count=UNSPECIFIED, name=UNSPECIFIED, status=UNSPECIFIED, tag_id=UNSPECIFIED, extraParams={}
):
import labstep.entities.orderRequest.repository as orderRequestRepository
extraParams = {"group_id": self.id, **extraParams}
return orderRequestRepository.getO... | [
"def get_requests(self):\n return self._make_request('GET', '/requests')",
"def open_orders():\n return _make_request('orders/own', private=True)['orders']",
"def list_orders(self):\n return self._orders",
"def get_orders(client, sheet_id):\r\n return client.get(f'/api/orders/sheet/{sheet_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the sharelink for the workspace. Returns | def getSharelink(self):
import labstep.entities.sharelink.repository as shareLinkRepository
return shareLinkRepository.getSharelink(self) | [
"def get_share(self, workspace_id, share_id):\n _op = fresh_operation('get_share')\n _op['method'] = 'GET'\n _op['path'] = '/workspaces/' + str(workspace_id) + '/shares/' + str(\n share_id)\n\n expected = 'Share'\n prepped_request = self._base.prepare_request(_op)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new Collection within the Workspace for Experiments or Protocols. | def newCollection(self, name, type="experiment"):
import labstep.entities.collection.repository as collectionRepository
return collectionRepository.newCollection(
self.__user__, name=name, type=type, extraParams={
"group_id": self.id}
) | [
"def _create_collection(cls):\n\n col_type = api.EDGE_COLLECTION if isinstance(cls, MetaEdgeBase) else api.DOCUMENT_COLLECTION\n\n col = cls.client.collections.get(cls.__collection_name__)\n if col is None:\n cls.client.collections.create(cls.__collection_name__, type=col_type)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets this workspace as the default workspace for the active user. | def setHome(self):
member = WorkspaceMember(self.logged_user_user_group, self.__user__)
import labstep.generic.entity.repository as entityRepository
return entityRepository.editEntity(member, {"is_home": True}) | [
"def user_default(self, user_default: ConfigNodePropertyString):\n\n self._user_default = user_default",
"def setWorkspace(self, workspaceName):\n if not self.contextHelper.isAccessibleWorkspaceName(workspaceName):\n raise Exception('Specified workspace not valid for your credentials')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a list of a User's Device Categorys across all Workspaces on Labstep, | def getDeviceCategorys(
self, count=UNSPECIFIED, search_query=UNSPECIFIED, tag_id=UNSPECIFIED, extraParams={}
):
import labstep.entities.deviceCategory.repository as deviceCategoryRepository
extraParams = {"group_id": self.id, **extraParams}
return deviceCategoryRepository.getDevic... | [
"def show_device_groups(login):\n url = login.server + \"/api/running/devices/device-group\"\n headers = {\n 'accept': \"application/vnd.yang.collection+json\",\n 'cache-control': \"no-cache\",\n }\n results = requests.request(\"GET\",\n url, headers=heade... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build the widget based on the dictionary from the data source | def build(self, data_dict):
# The widgets are part of every instance
self.ques_image.source = data_dict["image"]
self.header_label.text = data_dict["header"]
# But this content is generated dynamically
self.box_container.add_widget(self.get_content(data_dict)) | [
"def create_widgets(self):\n\n self.create_label(\"Pick Date\")\n self.create_lbox(40, 15)\n\n self.filtentry = tk.Entry(self.parent)\n self.filtentry.grid(row = 2, column = 0, columnspan = 2, sticky = tk.EW)\n self.fbutt = tk.Button(self.parent, text = 'Filter', command = lambda:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
objective function for lightgbm. | def objective(params):
# hyperopt casts as float
params['num_boost_round'] = int(params['num_boost_round'])
params['num_leaves'] = int(params['num_leaves'])
# need to be passed as parameter
if self.is_unbalance:
params['is_unbalance'] = True
params['verbose'] = -1
params['seed'] = 1
if sel... | [
"def run_optuna2():\n # rf_params = {\"max_depth\": [5, 15, None],\n # \"max_features\": [5, 9, \"auto\"],\n # \"min_samples_split\": [6, 8, 15],\n # \"n_estimators\": [150, 200, 300]}\n import optuna\n import lightgbm as lgb\n import sklearn.datasets\n import skle... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Waits to verify the bucket reflects the encryption settings | def wait_for_update(bucket, key_arn):
response = client.get_bucket_encryption(Bucket=bucket)
failure_counter = 0
while not 'ServerSideEncryptionConfiguration' in response and \
'Rules' in response['ServerSideEncryptionConfiguration'] and \
'ApplyServerSideEncryptionByDefault' in resp... | [
"def aws_s3_bucket_encryption_check(cache: dict, session, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict:\n s3 = session.client(\"s3\")\n # ISO Time\n iso8601Time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()\n for buckets in list_buckets(cache, session):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop our generator loop when we've exceeded our temperature boundary | def stopGeneratorLoop(temp, start, stop):
if start > stop and temp < stop:
return True
elif start < stop and temp > stop:
return True
return False | [
"def stopping_condition_is_met(self) -> bool:\n return self.iter >= self.max_iter",
"def stop(self, iterations):\n self.stop_count += iterations",
"def _end_condition(self):\n return self._num_iters >= self._max_iter",
"def wait_temperature(trigTemp):\n previous = preTemp\n while ((... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a command, mode, and a PATH string, return the path which conforms to the given mode on the PATH, or None if there is no such file. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result of os.environ.get("PATH"), or can be overridden with a custom search path. | def which(cmd, mode=os.F_OK | os.X_OK, path=None):
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(f... | [
"def which(cmd, mode=os.F_OK | os.X_OK, path=None):\n def _access_check(fn, mode):\n return (os.path.exists(fn) and os.access(fn, mode)\n and not os.path.isdir(fn))\n\n # If we're given a path with a directory part, look it up directly rather\n # than referring to PATH directories. This i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of all `Card`s held by this object. | def GetCards(self):
return self.cards | [
"def get_all_cards(self):\n\t\tquery_str = [\n\t\t\t\"SELECT * FROM cards;\"\n\t\t]\n\t\tself.c.execute(\n\t\t\tstr.join(\" \", query_str)\n\t\t)\n\t\tcardsData = self.c.fetchall()\n\t\tcards = []\n\t\tfor row in cardsData:\n\t\t\tcard = RFIDCard(str(row[0]), row[2], row[1] == 1)\n\t\t\tcards.append(card)\n\t\tretu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of all `Header` `Card`s. | def GetHeaders(self):
return [h for h in self.cards if isinstance(h, Header)] | [
"def raw_header_cards(self):\n return []",
"def raw_header_cards(self):\n return ['DISPERSE', 'TILTPOS', 'INSFILTE']",
"def get_all_cards(self):\n\t\tquery_str = [\n\t\t\t\"SELECT * FROM cards;\"\n\t\t]\n\t\tself.c.execute(\n\t\t\tstr.join(\" \", query_str)\n\t\t)\n\t\tcardsData = self.c.fetchall(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of all `Content` `Card`s. | def GetContents(self):
return [h for h in self.cards if isinstance(h, Content)] | [
"def GetCards(self):\n return self.cards",
"def get_cards(soup):\n return soup.findAll(\"div\", {\"class\": \"card\"})",
"def get_cards(self, token):\n cards = display(CustomerCard.get_all_cards(customer_id=token.customer_id))\n return {'cards': cards}",
"def get_all_cards(self):\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of all Content cards of the `kind`. | def GetContentsByKind(self, kind):
return [c for c in self.GetContents() if c.GetKind() == kind or c.GetKind(long=True) == kind] | [
"def GetContents(self):\n return [h for h in self.cards if isinstance(h, Content)]",
"def children_of_kind(content, kind, **kwargs):\n content_instance = get_instance_with_pk_or_uuid(content)\n return content_instance.get_descendants(include_self=False).filter(kind=kind)",
"def get_cards(self, expa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the nearest `Card` to `card` in the direction `direc`. | def GetNextCard(self, card, direc):
# depending on the direction we compare a different side
# of the cards, as well as get the points whose distance
# we're going to calculate in a different way
if direc == Deck.LEFT:
side = lambda x: x.right
getp1 = lambda x:... | [
"def find_closest(catalogue, ra, dec):\n output = [float('inf'), float('inf')]\n for row in catalogue:\n dist = angular_dist(row[1], row[2], ra, dec)\n if dist < output[1]:\n output = [row[0], dist]\n\n return output[0], output[1]",
"def nearest_point(self, relative: tuple):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns `self.CARD_PADDING`, fixed for scale. | def GetPadding(self):
return self.CARD_PADDING * self.scale | [
"def _get_padding(self):\n return self.pt, self.pr, self.pb, self.pl",
"def padding_width(self):\r\n return self.width + self.padding_left + self.padding_right",
"def padding_height(self):\r\n return self.height + self.padding_top + self.padding_bottom",
"def _get_padding(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new `Card` of type `subclass` at `pos`. | def NewCard(self, subclass, pos=wx.DefaultPosition, scroll=False):
# never use labels, always let Deck set its own
label = len(self.cards)
# create the new card with the unscaled position
# so that we can just call new.Stretch() afterward
# to set both position and size
... | [
"def __init__(self, pos, card=None):\n self.pos = pos\n self.card = card",
"def test_make_surface__subclassed_surface(self):\n expected_size = (3, 5)\n expected_flags = 0\n expected_depth = 32\n original_surface = SurfaceSubclass(\n expected_size, expected_flag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select the specified `Card`. | def SelectCard(self, card, new_sel=False):
self.selec.SelectCard(card, new_sel) | [
"def UnselectCard(self, card):\n self.selec.UnselectCard(card)",
"def SelectNext(self, direc, new_sel=False):\n nxt = self.GetParent().GetNextCard(self.last, direc)\n if nxt:\n self.SelectCard(nxt, new_sel)",
"def UnselectCard(self, card):\n if card in self.cards:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |