query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Restores clipboard and resets sys.stdout back to its default value | def tearDown(self):
pyperclip.copy(self.clipboard_contents)
sys.stdout = sys.__stdout__ | [
"def reset_stdout():\n sys.stdout = original_stdout # return original stdout",
"def RestoreStdOut():\n sys.stdout = PrintMocker.old_stdout",
"def restord_stdout():\n sys.stdout = sys.__stdout__",
"def clear_console():\n get_config().tk_vars[\"consoleclear\"].set(True)",
"def setclipboard():\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that rawoutput limits output only to generated string | def test_raw_output(self):
args = self.parser.parse_args([self.str_len, '--raw-output'])
self.randstr_output(args).process_parsed_args()
output = sys.stdout.getvalue()
self.assertEqual(int(self.str_len), len(output)) | [
"def test_length_limit_override(self):\n\n args = self.parser.parse_args(['1500', '--remove-limit', '--raw-output'])\n self.randstr_output(args).process_parsed_args()\n\n output = sys.stdout.getvalue()\n self.assertEqual(1500, len(output))",
"def test_good_output():\n\n rv, out = ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that use of 'copy' switch copies string to clipboard | def test_copy_operation(self):
args = self.parser.parse_args([self.str_len, '--raw-output', '--copy'])
self.randstr_output(args).process_parsed_args()
output = sys.stdout.getvalue()
clipboard_contents = pyperclip.paste()
self.assertEqual(clipboard_contents, output) | [
"def clipboard_copy(text: str) -> None:\n if pyperclip:\n pyperclip.copy(text)\n elif shutil.which(\"xclip\"):\n subprocess.run(\n [\"xclip\", \"-in\", \"-selection\", \"clipboard\"],\n input=text,\n text=True,\n check=True,\n )\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that providing removelimit switch allows strings exceeding 1000 characters to be generated. | def test_length_limit_override(self):
args = self.parser.parse_args(['1500', '--remove-limit', '--raw-output'])
self.randstr_output(args).process_parsed_args()
output = sys.stdout.getvalue()
self.assertEqual(1500, len(output)) | [
"def _truncate(s, limit): \n\ts = force_unicode(s) \n\tif len(s) <= limit: \n\t\treturn s \n\treturn '%s...' % s[:max(1, limit - 3)] \n\ttruncate = allow_lazy(truncate, unicode)",
"def give_truncator(lim):\n\n def truncator(val):\n \"\"\"this closure based function truncates a string (val)\n to a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets an attribute on a datacode class | def set_class_attr(
self, class_name: str, attr: str, value: Any
) -> "DatacodeOptions":
import datacode as dc
logger.debug(
f"Setting datacode options for class attr {class_name}.{attr} to {value}"
)
klass = getattr(dc, class_name)
self._set_class_attr(... | [
"def set_attribute(self,att,val):\r\n self.attributes[att] = val",
"def add_attr(self, code, value, type):\n attr_len = U_H_LEN\n if type == U_TP_S:\n attr_len = len(value) + U_H_LEN\n elif type == U_TP_I:\n attr_len = U_LEN_I\n value = pack('!l', value... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list of directory files. It is not recursive and it lists FILES ONLY. If the extension argument is given it will filter files that end with the given extension. | def list_dir(dir_path, extension=None):
files = [os.path.join(dir_path, p) for p in os.listdir(dir_path) if
os.path.isfile(os.path.join(dir_path, p))]
if extension:
return list(filter(lambda x: x.endswith(extension), files))
else:
return files | [
"def list_files(path, extension='*'):\n path = path.rstrip('/')\n return glob.glob(path+'/*.'+extension)",
"def _list_files(base_path: str, extension: str):\n if base_path.endswith(os.sep):\n base_path = base_path[:1]\n\n search_path = os.path.join(base_path, \"**\", f\"*.{extension}\")\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the relationship record and update the status. | def _update_relationship(self, origin_url: str = None):
task_model: TaskModel = self._model
current_app.logger.debug('<update_task_relationship ')
is_approved: bool = task_model.relationship_status == TaskRelationshipStatus.ACTIVE.value
is_hold: bool = task_model.status == TaskStatus.HOL... | [
"def select_relationship(self, rel_id: int) -> Relationship:",
"def get_relationship_record(self, relationship_record_type):\n return # osid.relationship.records.RelationshipRecord",
"def get_relationship(self, relationship_id):\r\n return self.get('relationships/{}'.format(relationship_id)).json... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks the winning condition of color, centered on point | def check_winning_condition(_board: SimpleGoBoard, point: int, color: int) -> bool:
consecutive_occurrence = 0
# check horizontal: west to east
for i in range(0, 9):
if _constrained_index(_board, point - 4 + i) == color:
consecutive_occurrence += 1
if consecutive_occurrence ... | [
"def checkWin(self):\n if self.cures[\"blue\"] == 1 and self.cures[\"red\"] == 1 and self.cures[\"yellow\"] == 1 and self.cures[\"black\"] == 1:\n return True\n else:\n return False",
"def is_checkmated(self, color):",
"def find_color(self):\n\n self.sym_mask = cv2.bit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Figure out if the computer has an old or new kernel. OOM killer was rewritten in 2010 and shipped in Linux kernel 2.6.36. Returns the string "new" if the kernel has the new OOM killer, otherwise it will return the string "old". | def kernel_oom_format():
if not os.path.exists('/proc/self/oom_score'):
raise ValueError('oom_score not in proc')
if os.path.exists('/proc/self/oom_score_adj'):
return 'new'
elif os.path.exists('/proc/self/oom_adj'):
return 'old'
raise ValueError('oom_adj or oom_score_adj not in... | [
"def kernel() -> str:\n x = platform.release()\n return x",
"def detect_cluster_system():\n\n try:\n which_output = check_output([\"which\", \"sge_qmaster\"], stderr=DEVNULL).decode(\"utf-8\")\n\n if \"/sge_qmaster\" in which_output:\n return \"SGE\"\n except Exception... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns highest topic score | def get_highest_score(self):
highest_scored_topic = models.Topic.objects.order_by('-score').first()
if not highest_scored_topic:
return 0 + self.HIGHEST_SCORE_ADDITION
else:
return highest_scored_topic.score + self.HIGHEST_SCORE_ADDITION | [
"def highest_score(self):\r\n if len(self.__students) < 5:\r\n raise ValueError(\"at least 5 students are needed\")\r\n self.__students.sort()\r\n return self.__students[:5]",
"def personal_best(self) -> int:\n return max(self._scores)",
"def getBestScore(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get save image name from source image path. | def get_save_image_name(output_dir, image_path):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
image_name = os.path.split(image_path)[-1]
name, ext = os.path.splitext(image_name)
return os.path.join(output_dir, "{}".format(name)) + ext | [
"def get_save_image_name(org_im, org_im_path, output_dir):\n # name prefix of orginal image\n org_im_name = os.path.split(org_im_path)[-1]\n im_prefix = os.path.splitext(org_im_name)[0]\n ext = '.png'\n # save image path\n save_im_path = os.path.join(output_dir, im_prefix + ext)\n if os.path.ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This will be called every time the value of the CurrentTemperature is changed. Use setter_callbacks to react to user actions, e.g. setting the lights On could fire some GPIO code to turn on a LED (see pyhap/accessories/LightBulb.py). | def temperature_changed(self, value):
logger.info('Temperature changed to: ', value) | [
"def setChangedCallback(self, *args):\n return _coin.SoSensorManager_setChangedCallback(self, *args)",
"def setChangedCallback(self, *args) -> \"void\":\n return _coin.SoSensorManager_setChangedCallback(self, *args)",
"def OnTemperature(self,event):\n self.temperature_ramp_panel = Temperatu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This will be called every time the value of the CurrentHumidity is changed. Use setter_callbacks to react to user actions, e.g. setting the lights On could fire some GPIO code to turn on a LED (see pyhap/accessories/LightBulb.py). | def humidity_changed(self, value):
logger.info('Humidity changed to: ', value) | [
"def setChangedCallback(self, *args) -> \"void\":\n return _coin.SoSensorManager_setChangedCallback(self, *args)",
"def setChangedCallback(self, *args):\n return _coin.SoSensorManager_setChangedCallback(self, *args)",
"def setHumidityLevel(self, value):\n\t\tself.humidityLevel.setValue(value)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update a policy profile. | def update_policy_profile(self, profile, body=None):
return self._put(self.policy_profile_path % (profile), body=body) | [
"def update_policy(self, new_policy):\n self.policy = new_policy",
"def update_profile(self):\n pass",
"def UpdateProfile(profile, profileElement):\r\n UpdateRatings(profile.completionRatings, profileElement.find('completionAwards'))\r\n UpdateRatings(profile.moveRatings, profileElement.find... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 1 enemy hp by using API and passes the value to the env | def GetEn1Hp(self):
print("Blizzard") | [
"async def weaponexp(self, ctx, *args):\n\n # check role and channel\n config = self.bot.get_config(ctx.guild)\n ALLOWED_CHANNELS = self.bot.get_allowed_channels(config, \"api\")\n ALLOWED_ROLES = self.bot.get_allowed_roles(config, \"api\")\n if await checks.channels(ctx, ALLOWED_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 2 enemy hp by using API and passes the value to the env | def GetEn2Hp(self):
print("Give") | [
"async def weaponexp(self, ctx, *args):\n\n # check role and channel\n config = self.bot.get_config(ctx.guild)\n ALLOWED_CHANNELS = self.bot.get_allowed_channels(config, \"api\")\n ALLOWED_ROLES = self.bot.get_allowed_roles(config, \"api\")\n if await checks.channels(ctx, ALLOWED_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get self hp by using API and passes the value to the env | def GetSelfHp(self):
print("Access") | [
"def GetEn1Hp(self):\r\n print(\"Blizzard\")",
"def GetSelfCovenant(self):\r\n print(\"/\")",
"def find(key):\n return ItopapiPrototype.find(ItopapiHypervisor, key)",
"def site_hq():\n return Site(name=\"HQ\")",
"def get(self, hyperp_name):\n assert hyperp_name in self.name_to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get allay class by using API and passes the value to the env 1/numder of classes(like on the character creation screen) | def GetAllayClass(self):
print("/") | [
"def get_class():\n # this function lists all classes that are in the knights module\n knight_test = class_tester(knights.Knight)\n available_classes = inspect.getmembers(knights, knight_test)\n\n # if there is only one class available (when bonus task is not implemented)\n # then return that one cla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get self class by using API and passes the value to the env 1/numder of classes(like on the character creation screen) | def GetSelfClass(self):
print("/") | [
"def get_class():\n # this function lists all classes that are in the knights module\n knight_test = class_tester(knights.Knight)\n available_classes = inspect.getmembers(knights, knight_test)\n\n # if there is only one class available (when bonus task is not implemented)\n # then return that one cla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get self race abiliti by using API and passes the value to the env 1/numper of all races(start from human > all standart allience races > allied allience races > horde standart races > horde allied races > pandarens) | def GetSelfRaceAbiliti(self):
print("/") | [
"def race_calc(self):\n if self.race == 0:\n self.physical += 1\n self.subterfuge += 1\n self.knowledge += 1\n self.communication += 1\n elif self.race == 1:\n self.MIND += 2\n self.race = 1\n elif self.race == 2:\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 1 enemy covenant abiliti by using API and passes the value to the env 1/number of all covenant abiliyies(start from Kiriy) | def GetEn1Covenant(self):
print("/") | [
"def GetEn1Covenant2(self):\r\n print(\"/\")",
"def GET_request(action):\n\n # OAuth token of the user that requests will be made on behalf of\n\n\n # Login of the advertising agency client\n # Required parameter if requests are made on behalf of an advertising agency\n clientLogin = 'marketing... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 1 enemy second covenant abiliti by using API and passes the value to the env 1/number of all covenant abiliyies(start from Kiriy) | def GetEn1Covenant2(self):
print("/") | [
"def GetEn1Covenant(self):\r\n print(\"/\")",
"def GetEn2Covenant2(self):\r\n print(\"/\")",
"def choix_ville():\n \n print(\"-------------------------\")\n ville = input(\"Choisissez une ville : \")\n print(\"-------------------------\")\n ville = ville.capitalize()\n \n url ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 2 enemy second covenant abiliti by using API and passes the value to the env 1/number of all covenant abiliyies(start from Kiriy) | def GetEn2Covenant2(self):
print("/") | [
"def GetEn1Covenant2(self):\r\n print(\"/\")",
"def GetEn1Covenant(self):\r\n print(\"/\")",
"def choix_ville():\n \n print(\"-------------------------\")\n ville = input(\"Choisissez une ville : \")\n print(\"-------------------------\")\n ville = ville.capitalize()\n \n url ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get allay covenant abiliti by using API and passes the value to the env 1/number of all covenant abiliyies(start from Kiriy) | def GetAllayCovenant(self):
print("/") | [
"def GetEn1Covenant(self):\r\n print(\"/\")",
"def GetEn1Covenant2(self):\r\n print(\"/\")",
"def GetEn2Covenant2(self):\r\n print(\"/\")",
"def choix_ville():\n \n print(\"-------------------------\")\n ville = input(\"Choisissez une ville : \")\n print(\"--------------------... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get self covenant abiliti by using API and passes the value to the env 1/number of all covenant abiliyies(start from Kiriy) | def GetSelfCovenant(self):
print("/") | [
"def GetEn1Covenant(self):\r\n print(\"/\")",
"def GetSelfCovenant2(self):\r\n print(\"/\")",
"def GetEn1Covenant2(self):\r\n print(\"/\")",
"def GetAllayCovenant(self):\r\n print(\"/\")",
"def GetEn2Covenant2(self):\r\n print(\"/\")",
"def GetSelfRaceAbiliti(self):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get self second covenant abiliti by using API and passes the value to the env 1/number of all covenant abiliyies(start from Kiriy) | def GetSelfCovenant2(self):
print("/") | [
"def GetEn1Covenant2(self):\r\n print(\"/\")",
"def GetEn1Covenant(self):\r\n print(\"/\")",
"def GetEn2Covenant2(self):\r\n print(\"/\")",
"def GetSelfCovenant(self):\r\n print(\"/\")",
"def GetAllayCovenant(self):\r\n print(\"/\")",
"def get_one_ride():",
"def GetSel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 1 safe ability of allay and passes the value to the env 1/number of all safe ability(each class has its own) | def GetAllay1SafeAbility(self):
print("/") | [
"def GetSelf1SafeAbility(self):\r\n print(\"/\")",
"def GetAllay3SafeAbility(self):\r\n print(\"/\")",
"def get_con_ability(con_val: int, ability: int) -> int:\n ability_val = 0\n try:\n if con_val == 19 or con_val == 20:\n ability_val = con_19_20[ability]\n elif con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 3 safe ability of allay and passes the value to the env 1/number of all safe ability(each class has its own) | def GetAllay3SafeAbility(self):
print("/") | [
"def GetSelf3SafeAbility(self):\r\n print(\"/\")",
"def get_ability_definitions():\n\n class_features = {\n\n # BARBARIAN\n 'damage reduction': {\n 'effects': [\n Modifier(['damage reduction'],\n lambda creature, value: creature.level + val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 1 safe self abiliti and passes the value to the env 1/number of all safe ability(each class has its own) | def GetSelf1SafeAbility(self):
print("/") | [
"def GetSelf3SafeAbility(self):\r\n print(\"/\")",
"def GetSelf2SafeAbility(self):\r\n print(\"/\")",
"def GetAllay1SafeAbility(self):\r\n print(\"/\")",
"def ProtectionScenario(self) -> ProtectionScenario:",
"def attack(self):\r\n pass",
"def GetAllay3SafeAbility(self):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 2 safe self abiliti and passes the value to the env 1/number of all safe ability(each class has its own) | def GetSelf2SafeAbility(self):
print("/") | [
"def GetSelf1SafeAbility(self):\r\n print(\"/\")",
"def safes(self):\n safes = []\n all_env_role_acls = []\n my_env_role_acls = []\n for role in self.roles.all():\n for acl in role.safe_acls.filter(safe__vault__all_environments=True):\n all_env_role_acl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get 3 safe self abiliti and passes the value to the env 1/number of all safe ability(each class has its own) | def GetSelf3SafeAbility(self):
print("/") | [
"def safes(self):\n safes = []\n all_env_role_acls = []\n my_env_role_acls = []\n for role in self.roles.all():\n for acl in role.safe_acls.filter(safe__vault__all_environments=True):\n all_env_role_acls.append(acl)\n for acl in role.safe_acls.filter(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get information about self death and passes the value to the env | def GetSelfDeath(self):
print("/") | [
"def deaths(self) -> int:\n pass",
"def observe_death(self,enemy):\n #print 'death: resetting agent to ', self.initial_positions[enemy]\n self.observe_exact(enemy, self.initial_positions[enemy])",
"def fork_sim_env_health() -> 'ExecEnv':\n from tc2.env.ExecEnv import ExecEnv\n from tc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This adds enabled extensions to the INSTALLED_APPS cache so that operations like syncdb and evolve will take extensions into consideration. | def include_enabled_extensions(settings):
from django.db.models.loading import load_app
from django.db import DatabaseError
from reviewboard.extensions.base import get_extension_manager
try:
manager = get_extension_manager()
except DatabaseError:
# This database is from a time befo... | [
"def _refresh_neutron_extensions_cache(self):\n if (not self.last_neutron_extension_sync or\n ((time.time() - self.last_neutron_extension_sync)\n >= CONF.neutron.extension_sync_interval)):\n extensions_list = self.neutron_api.list_extensions()['extensions']\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns criterion by name. | def get_criterion(name, **kwargs):
return {
'bce': loss.BCELoss(),
'bcewithlogits': loss.BCEWithLogitsLoss(),
'cosineembedding': loss.CosineEmbeddingLoss(),
'crossentropy': loss.CrossEntropyLoss(),
'hingeembedding': loss.HingeEmbeddingLoss(),
'kldiv': loss.KLDivLoss()... | [
"def criterion(self) -> str:\n return self._criterion",
"def get_coeff_by_name(self, name):\n if len(self.coefficient_dics) == 0:\n self.find_coefficient_dics()\n if len(self.coeff_order) == 0:\n self.fill_coeff_order()\n return self.coefficient_dics[self.coeff_or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns learning rate scheduler by name. | def get_scheduler(name):
return {
'cosineannealing': CosineAnnealingLR,
'exponential': sched.ExponentialLR,
'lambda': sched.LambdaLR,
'multistep': sched.MultiStepLR,
'reduceonplateau': sched.ReduceLROnPlateau,
'step': sched.StepLR
}[name.strip().lower()] | [
"def get_learning_rate_scheduler(optimizer, args):\n\n # Add linear learning rate scheduler.\n if args.lr_decay_iters is not None:\n num_iters = args.lr_decay_iters\n else:\n num_iters = args.train_iters\n if args.finetune:\n num_iters = num_iters // args.gradient_accumulation_steps... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Places tensor on `device`. | def place(tensor, device=-1):
if device < 0:
return tensor.cpu()
else:
return tensor.cuda(device) | [
"def cuda(tensor):\n\n return tensor.to(args.device)",
"def cuda(self: T, device: Optional[int] = None) -> T:\n return self.to(torch.device(f\"cuda:{device}\" if device is not None else \"cuda\"))",
"def to(self, device='cpu'):\n if device == 'cpu':\n return self.numpy()\n\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the date of a oneday event. Returns a date value | def parse_oneday_get_date(oneday, session=None):
if session is None:
session = get_session()
urlv = "%s.php?%s" % (ONEDAYS, oneday)
one_day_str = get_page_data(urlv, GetDateFromUrl(), session=session)
extract = one_day_str.strip()
if not extract:
return date.today() + timedelta(days=... | [
"def get_event_date(timestamp):\n return datetime.fromtimestamp(timestamp)",
"def get_yesterdays_date():\n\n return date.today() - timedelta(days=1)",
"def get_day(date): \n if date < 7:\n return week[date % 7]\n elif date % 7 == 0: \n return week[7]\n else: \n return wee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imputes missing data using the nearest nonnull neighbors | def knn_impute(data, k_neighbors=3):
# Iterate over rows
for i, row in data.iterrows():
# Find rows that contain nulls
if row.isnull().any():
# Find K nearest neighbors
knn = impute_neighbors(row)
# Find the cell with the null value and fill it
... | [
"def impute_missing_values(X):\n col_means=np.nanmean(X,axis=0)\n inds=np.where(np.isnan(X))\n X[inds]=np.take(col_means,inds[1])\n return X",
"def replace_missing_values(data):\n pixel_grid_dim = data.shape\n missing_coords = missing_coordinates(data)\n original_data = np.copy(data) \n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parameter ``base`` must be a path containing a '.', otherwise an exception is raised. | def __init__(self, base):
logging.debug('Base parameter is %s', base)
if base.rfind('.') < 0:
raise ValueError(f"Expected path to file, received {base}")
self.basename = base[0:base.rfind('.')]
self.reserved = {} | [
"def setBase(self, base):\n if base is None:\n base = ''\n elif not base.endswith('/'):\n base = base + '/'\n\n self.base = str(base)",
"def test_relative_base_upload_path(self):\n base_path = \"tmp\"\n user_supplied_index_name = \"a89933473b2a48948beee2c7e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the near EndPoint of a connection. If either the near or far EndPoint has already been set, this will raise an exception. If successful, the connection's state becomes BOUND. endp the near end Raise IOException if either EndPoint already set | def bind_near_end(self, endp): # endp an EndPoint # raises IOException
pass | [
"def get_near_end(self): # -> EndPoint\n pass",
"def bind_far_end(self, endp): # endp an EndPoint # raises IOException\n pass",
"def end_point(self, end_point: int):\n\n self._end_point = end_point",
"def get_far_end(self): # -> EndPoint\n pass",
"def end_ip(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the far EndPoint of a connection. If the near end point has NOT been set or if the far EndPoint has already been set in other words, if the connection is already beyond state BOUND this will raise an exception. If the operation is successful, the connection's state becomes either PENDING or CONNECTED. XXX The state... | def bind_far_end(self, endp): # endp an EndPoint # raises IOException
pass | [
"def bind_near_end(self, endp): # endp an EndPoint # raises IOException\n pass",
"def get_far_end(self): # -> EndPoint\n pass",
"def get_near_end(self): # -> EndPoint\n pass",
"def end_point(self, end_point: int):\n\n self._end_point = end_point",
"def end_ip(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the near EndPoint of the Connection. | def get_near_end(self): # -> EndPoint
pass | [
"def get_far_end(self): # -> EndPoint\n pass",
"def end_point(self) -> int:\n return self._end_point",
"def bind_near_end(self, endp): # endp an EndPoint # raises IOException\n pass",
"def end_ip_address(self) -> Optional[str]:\n return pulumi.get(self, \"end_ip_address\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the far EndPoint of the Connection. | def get_far_end(self): # -> EndPoint
pass | [
"def end_point(self) -> int:\n return self._end_point",
"def get_near_end(self): # -> EndPoint\n pass",
"def ip_end(self):\n return self._ip_end",
"def _get_end(self):\n return self.Data.End",
"def end_ip_address(self) -> Optional[str]:\n return pulumi.get(self, \"end... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether the Connection is blocking. | def is_blocking(self): # -> bool
pass | [
"def is_blocking(self, user_or_id):\n return self._has_connection_with(user_or_id, ConnectionType.BLOCK)",
"def isNonBlocking(skt):\n return bool(fcntl.fcntl(skt.fileno(), fcntl.F_GETFL) & os.O_NONBLOCK)",
"def block_queue(self):\n # First check if self._active_req is not None and if not, if it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the InputStream associated with the Connection. | def get_input_stream(self): # -> InputStream # raises IOException
pass | [
"def read_stream(self):\n return self.sc.rtm_read()",
"def open(self) -> IO[AnyStr]:\n if self.seek(0) == 0:\n return cast(IO[AnyStr], self._source)\n elif self._url is None:\n raise XMLResourceError(f\"can't open, {self!r} has no URL associated\")\n\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the OutputStream associated with the Connection. | def get_output_stream(self): # -> OutputStream # raises IOException
pass | [
"def GetConsoleWriterStream(self):\n return self.__stream_wrapper.stream",
"def _change_stream(self):\n\n # Creates a new input output stream for the logger\n log_out = StringIO()\n # Changes the output stream to log_out\n self.stream_handler.stream = log_out\n return log_out... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether the connection is encrypted. | def is_encrypted(self): # -> bool
pass | [
"def isEncrypted(self):\n ret = libvirtmod.virConnectIsEncrypted(self._o)\n if ret == -1: raise libvirtError ('virConnectIsEncrypted() failed', conn=self)\n return ret",
"def is_encrypted():\n return False",
"def is_encrypted(self):\n return isinstance(self._message, (SKEData, Int... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Re)negotiate the secret used to encrypt traffic over the connection. myKey this Node's asymmetric key hisKey Peer's def key | def negotiate(self, my_key, his_key):
pass | [
"def establish_connection(conn: socket) -> AESEncrypt:\n key = RSA.generate(2048)\n\n public_key = key.publickey().exportKey('PEM').decode()\n public_key = public_key.replace(\"-----BEGIN PUBLIC KEY-----\", \"\")\n public_key = public_key.replace(\"-----END PUBLIC KEY-----\", \"\")\n public_key = pub... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize client and getting or creating bucket | def __init__(self, json_service_account: str = JSON_KEYS_SERVICE_ACCOUNT,
bucket_name: str = DISEASE_HISTORY_FILES_NAME):
self.client = storage.Client.from_service_account_json(json_service_account)
try:
self.bucket = self.client.get_bucket(bucket_name)
except NotFo... | [
"def create(self, bucket_name):\n bucket = self.gcs_client.get_bucket(bucket_name)\n print('Bucket {} created'.format(bucket.name))",
"def initialize_bucket(key, secret, endpoint, bucket, retries=10):\r\n for retry in range(retries):\r\n try:\r\n authentication = oss.Auth(key, s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields entries from the JSONL files. | def read_jsonl(jsonl_filenames: Union[str, Iterable[str]]) -> Iterator[Example]:
if isinstance(jsonl_filenames, str):
jsonl_filenames = [jsonl_filenames]
for filename in jsonl_filenames:
with tf.io.gfile.GFile(filename) as fin:
for line in fin:
entry = json.loads(line)
yield entry | [
"def jsonl(filename):\n\twith open(filename, 'r') as file_:\n\t\tfor line in file_:\n\t\t\tyield json.loads(line)",
"def iter_jsonl(\n self, f: TextIOWrapper, data_model: Optional[BaseModel] = None\n ) -> Iterable[BaseModel]:\n dm = data_model or self.data_model\n for line in f:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether the neighbor is usable. Optionally, a state can be maintained (e.g., to count how many neighbors so far belong to each intent, for crowding purposes). The state will be given as an argument. | def check_neighbor(self, input_ex: Example, neighbor_ex: Example,
state: Any) -> bool:
raise NotImplementedError | [
"def is_goal(state):\n return sum(sum(state, [])) == 1",
"def is_valid(self, state):\n return True",
"def islive(self, state):\n seen = set([state])\n reachable = [state]\n i = 0\n while i < len(reachable):\n current = reachable[i]\n if current in self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new state after accepting the neighbor. The default behavior is to return the old state unchanged. | def accept_neighbor(self, neighbor_ex: Example, state: Any) -> Any:
del neighbor_ex
return state | [
"def successors(self, new_state):\n return self.graph[new_state]",
"def apply_state(self, state):",
"def get_new_state(old_state):\n if not new_aut.has_state(old_state.number):\n new_state = new_aut.add_new_state(marked = old_state.marked,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the index entry for the specified id. | def get_index_entry(self, index_id: int) -> Example:
raise NotImplementedError | [
"def get_entry_from_id(self, id: int):\n for e in self.container:\n if e.id == id:\n return e",
"def _get_row_entry_by_id(self, id):\n entry = [entry for entry in self._get_row_entries()\n if entry.id.text.split('/')[-1] == id]\n if not entry:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Embeds a batch of examples. | def embed_batch(self, examples: List[Example]) -> np.ndarray:
raise NotImplementedError | [
"def _embed_index(self) -> None:\n batch = []\n results = []\n for i, example in enumerate(self._index_exs):\n if i % self._log_every == 0:\n logging.info(\"Processed %d / %d examples\", i, len(self._index_exs))\n batch.append(example)\n if len(batch) == self._batch_size:\n res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Embeds the entire retrieval index. | def _embed_index(self) -> None:
batch = []
results = []
for i, example in enumerate(self._index_exs):
if i % self._log_every == 0:
logging.info("Processed %d / %d examples", i, len(self._index_exs))
batch.append(example)
if len(batch) == self._batch_size:
results.append(sel... | [
"def index(request):\n return render(request, \"encyclopedia/index.html\", {\"entries\": util.list_entries()})",
"def api_index():\n return render_template('api_docs.html')",
"def notebooks_index():\n return render_template('blog/index.html', posts=[])",
"def show_index(self):\n for directory,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates user list via PanelSearchBox and _start_presence_updates. | def update_user_list(
self,
search_box: Any = None,
new_text: Optional[str] = None,
user_list: Any = None,
) -> None:
assert (user_list is None and search_box is not None) or ( # PanelSearchBox.
user_list is not None and search_box is None and new_text is None
... | [
"def update_user_list():\n\n users_ = bot.client.api_call('users.list')\n users = json.loads(users_.decode('utf8'))['members']\n\n for user in users:\n id_ = user['id']\n name = user['name']\n\n user_obj = session.query(User).get(id_)\n if user_obj is None:\n user_obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns popup height. The popup height is calculated using urwid's .rows method on every widget. | def calculate_popup_height(
body: List[Any],
header: Optional[Any],
footer: Optional[Any],
popup_width: int,
) -> int:
height = sum(widget.rows((popup_width,)) for widget in body)
height += header.rows((popup_width,)) if header else 0
height += footer.rows((po... | [
"def get_height(self):\n return self.driver.get_window_size()['height']",
"def height(self) -> int:\n return self.winfo_height()",
"def _get_height(self) -> \"int\" :\n return _core.Palette__get_height(self)",
"def get_height(self):\n return self.textsurf.get_height()",
"def wind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a tuple that contains the required width for the popup and a list that has column widths. | def calculate_table_widths(
contents: PopUpViewTableContent, title_len: int, dividechars: int = 2
) -> Tuple[int, List[int]]:
# Add 4 (for 2 Unicode characters on either side) to the popup title
# length to make sure that the title gets displayed even when the
# content or the catego... | [
"def calcWidths(self):\n self.popup_width, dum = self.GetClientSizeTuple()\n count = len(self.choices)\n self.widths = [None] * count\n self.heights = [None] * count\n self.largest_width = None\n #print(\"calcWidths: %d items\" % count)\n for i in range(count):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of widgets to render a table with different categories. | def make_table_with_categories(
contents: PopUpViewTableContent, column_widths: List[int], dividechars: int = 2
) -> List[Any]:
widgets: List[Any] = []
for category, content in contents:
if category:
if len(widgets) > 0: # Separate categories with newline.
... | [
"def widgets(self):\n\n widgets = {}\n for f in self.fields():\n widgets[f.getName()] = f.widget\n return widgets",
"def get_widgets(self):\n name = self.__class__.__name__\n if name.endswith('Widget'):\n name = name[:-6]\n yield name",
"def get_wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates emoji list via PanelSearchBox. | def update_emoji_list(
self,
search_box: Any = None,
new_text: Optional[str] = None,
emoji_list: Any = None,
) -> None:
assert (emoji_list is None and search_box is not None) or (
emoji_list is not None and search_box is None and new_text is None
)
... | [
"def __search (self, event):\n self.search_values = self.toolbar.get_search_values ( )\n self.__build_list ( )",
"def _update_autocomplete(self, event):\n self.listbox.delete(0, tk.END)\n self.listbox[\"height\"] = self._listbox_height\n\n text = self.text.get()\n if not self._ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build a duplicate datatype with the _index set to idx When forming a Request that involves a specific item in the UniformList, that item can be specified using this index() method | def index(self, idx):
dt = deepcopy(self.datatype)
dt._index = idx
return dt | [
"def _from_index(cls, index: core.PositionalIndex) -> WordIndex:\n # probably a better way to do this, but this just sets an empty data\n # and overrides the value of `self.index`\n cls_item = cls([])\n cls_item.index = index\n return cls_item",
"def add_itemIdx():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a glTF quaternion to Blender a quaternion. | def convert_quaternion(q):
# xyzw -> wxyz
return Quaternion([q[3], q[0], q[1], q[2]]) | [
"def pyqt_to_tf(q):\n q = q.elements\n return Quaternion(q[1], q[2], q[3], q[0])",
"def quaternionFromTransform(pT):\n return _almathswig.quaternionFromTransform(pT)",
"def transformFromQuaternion(pQua):\n return _almathswig.transformFromQuaternion(pQua)",
"def tf_to_pyqt(q):\n return pyqt.Quat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an empty widget object for a bone, and returns the object. | def create_widget(rig, bone_name, bone_transform_name=None):
assert rig.mode != 'EDIT'
bone = rig.pose.bones[bone_name]
# The bone already has a widget
if bone.custom_shape:
return None
obj_name = WGT_PREFIX + rig.name + '_' + bone_name
scene = bpy.context.scene
collection = ensure... | [
"def create_widget(rig, bone_name):\n obj_name = WGT_PREFIX + bone_name\n scene = bpy.context.scene\n # Check if it already exists\n if obj_name in scene.objects:\n return None\n else:\n mesh = bpy.data.meshes.new(obj_name)\n obj = bpy.data.objects.new(obj_name, mesh)\n sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adjust the generated widget by applying a correction matrix to the mesh. If local is false, the matrix is in world space. If local is True, it's in the local space of the widget. If local is a bone, it's in the local space of the bone. | def adjust_widget_transform_mesh(obj, matrix, local=None):
if obj:
if local is not True:
if local:
assert isinstance(local, bpy.types.PoseBone)
bonemat = local.id_data.matrix_world @ local.bone.matrix_local
matrix = bonemat @ matrix @ bonemat.inver... | [
"def update_world_matrix(self) -> None:\n if self._parent is None:\n self._world_matrix = self.local_matrix\n else:\n self._world_matrix = self.parent.world_matrix * self.local_matrix\n\n for child in self.children:\n child.update_world_matrix()",
"def update(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a mesh object as a python script for widget use. | def write_widget(obj):
script = ""
script += "def create_thing_widget(rig, bone_name, size=1.0, bone_transform_name=None):\n"
script += " obj = create_widget(rig, bone_name, bone_transform_name)\n"
script += " if obj is not None:\n"
# Vertices
script += " verts = ["
for i, v in... | [
"def write(self,mesh,name=None):\n if name is not None:\n self.file.write(\"o %s\\n\" % str(name))\n\n for v in mesh.coords:\n self.file.write(\"v %s %s %s\\n\" % tuple(v))\n\n # element code: p(oint), l(ine) or f(ace)\n nplex = mesh.elems.shape[1]\n code = {... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test equality between packed and unpacked float16 lists. | def assertEqualFP16(self, packed_fp16_data, unpacked_fp16_data):
self.assertEqual(packed_fp16_data, list(unpacked_fp16_data.view(np.int32))) | [
"def test_half_conversions(self):\n # Because the underlying routines preserve the NaN bits, every\n # value is preserved when converting to/from other floats.\n\n # Convert from float32 back to float16\n b = np.array(self.all_f32, dtype=float16)\n assert_equal(self.all_f16.view(d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test tensor attributes with reference backend. | def test_attr_reference(self):
tensor_data = np.random.rand(2, 2, 4, 4).astype(np.float32)
with Graph("test_graph", "Reference") as test_graph:
input_tensor = Tensor(data_layout=types_pb2.NHWC, tensor_data=tensor_data)
act = input_data(input_tensor, "input")
graph_proto, tensor_data_array = test... | [
"def test_meta_const():\n\n with tf.Graph().as_default():\n one_mt = mt.const(1, \"int32\", \"Const\")\n\n with tf.Graph().as_default():\n another_one_mt = mt(1)\n\n assert one_mt == another_one_mt\n assert isinstance(one_mt.reify(), tf.Tensor)\n assert one_mt.reify().op.type == \"Const... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test tensor attributes with SMV backend. No padding is required. | def test_attr_smv_no_padding(self):
tensor_data = np.random.rand(2, 2, 4, 8).astype(np.float16)
with Graph("test_graph", "SMV") as test_graph:
input_tensor = Tensor(data_layout=types_pb2.NCHW, tensor_data=tensor_data)
act = input_data(input_tensor, "input")
graph_proto, tensor_data_array = test_... | [
"def test_attr_smv_padding(self):\n tensor_data = np.array([[1.1, 2.2, 3.3, 4.4], [5.5, 6.6, 7.7, 8.8]],\n dtype=np.float16)\n with Graph(\"test_graph\", \"SMV\") as test_graph:\n input_tensor = Tensor(data_layout=types_pb2.NCHW, tensor_data=tensor_data)\n act = input_data(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test tensor attributes with SMV backend. Additional padding required. | def test_attr_smv_padding(self):
tensor_data = np.array([[1.1, 2.2, 3.3, 4.4], [5.5, 6.6, 7.7, 8.8]],
dtype=np.float16)
with Graph("test_graph", "SMV") as test_graph:
input_tensor = Tensor(data_layout=types_pb2.NCHW, tensor_data=tensor_data)
act = input_data(input_tensor, ... | [
"def test_attr_smv_no_padding(self):\n tensor_data = np.random.rand(2, 2, 4, 8).astype(np.float16)\n with Graph(\"test_graph\", \"SMV\") as test_graph:\n input_tensor = Tensor(data_layout=types_pb2.NCHW, tensor_data=tensor_data)\n act = input_data(input_tensor, \"input\")\n graph_proto, tensor_da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test float16 packing when tensor's last dimension is of even size | def test_fp16_even(self):
tensor_data = np.random.rand(4, 2).astype(np.float16)
with Graph("test_graph", "Reference") as test_graph:
input_tensor = Tensor(tensor_data=tensor_data)
act = input_data(input_tensor, "input")
graph_proto, tensor_data_array = test_graph.to_proto()
node = get_node_p... | [
"def test_fp16_odd(self):\n tensor_data = np.random.rand(4, 3).astype(np.float16)\n with Graph(\"test_graph\", \"Reference\") as test_graph:\n input_tensor = Tensor(tensor_data=tensor_data)\n act = input_data(input_tensor, \"input\")\n graph_proto, tensor_data_array = test_graph.to_proto()\n n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test float16 packing when tensor's last dimension is of odd size | def test_fp16_odd(self):
tensor_data = np.random.rand(4, 3).astype(np.float16)
with Graph("test_graph", "Reference") as test_graph:
input_tensor = Tensor(tensor_data=tensor_data)
act = input_data(input_tensor, "input")
graph_proto, tensor_data_array = test_graph.to_proto()
node = get_node_pr... | [
"def test_fp16_even(self):\n tensor_data = np.random.rand(4, 2).astype(np.float16)\n with Graph(\"test_graph\", \"Reference\") as test_graph:\n input_tensor = Tensor(tensor_data=tensor_data)\n act = input_data(input_tensor, \"input\")\n graph_proto, tensor_data_array = test_graph.to_proto()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
odd_int1(list1) This function returns value, which was in list exactly odd times. | def odd_int1(list1):
count_elements = {i: list1.count(i) for i in list1}
for i in count_elements:
if count_elements[i] % 2 == 0:
return i | [
"def odd_int2(list1):\n\t\n\twhile len(list1) > 0:\n\t\tstart_len = len(list1)\n\t\tcurr_value = list1[0]\n\t\t\n\t\tlist1 = list(filter(lambda elem: elem != curr_value, list1))\n\t\t\n\t\tif (start_len - len(list1)) % 2 == 0:\n\t\t\treturn curr_value",
"def odd_int3(list1):\n\t\n\twhile len(list1) > 0:\n\t\t\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
odd_int2(list1) This function returns value, which was in list exactly odd times. | def odd_int2(list1):
while len(list1) > 0:
start_len = len(list1)
curr_value = list1[0]
list1 = list(filter(lambda elem: elem != curr_value, list1))
if (start_len - len(list1)) % 2 == 0:
return curr_value | [
"def odd_int1(list1):\n\tcount_elements = {i: list1.count(i) for i in list1}\n\t\n\tfor i in count_elements:\n\t\tif count_elements[i] % 2 == 0:\n\t\t\treturn i",
"def odd_int3(list1):\n\t\n\twhile len(list1) > 0:\n\t\t\n\t\tcurr_value = list1[0]\n\t\tcount_curr_value = 1\n\t\tlist1.remove(curr_value)\n\t\t\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
odd_int3(list1) This function returns value, which was in list exactly odd times. | def odd_int3(list1):
while len(list1) > 0:
curr_value = list1[0]
count_curr_value = 1
list1.remove(curr_value)
for x in list1:
if x == curr_value:
list1.remove(curr_value)
count_curr_value += 1
if count_curr_value % 2 == 0:
return curr_value | [
"def odd_int1(list1):\n\tcount_elements = {i: list1.count(i) for i in list1}\n\t\n\tfor i in count_elements:\n\t\tif count_elements[i] % 2 == 0:\n\t\t\treturn i",
"def odd_int2(list1):\n\t\n\twhile len(list1) > 0:\n\t\tstart_len = len(list1)\n\t\tcurr_value = list1[0]\n\t\t\n\t\tlist1 = list(filter(lambda elem: e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure `x_0` is not 0. | def _x_0_validator(self, val):
if np.any(val == 0):
raise InputParameterError("0 is not an allowed value for x_0") | [
"def check_x0_y0(pos):\n import warnings as w\n if not 0.0 in pos[0] and not 0.0 in pos[1]:\n w.warn(\"Your mesh does not contain nodes at (x, y) = (0, 0)! This \"\n \"could lead to poor representation of your ARF focus.\")",
"def _ensure_non_zero(values: np.ndarray) -> np.ndarray:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Circular velocities of the NFW profile. | def circular_velocity(self, r):
# Enforce default units (if parameters are without units)
if hasattr(r, "unit"):
in_r = r
else:
in_r = u.Quantity(r, u.kpc)
# Mass factor defined velocity (i.e. V200c for M200c, Rvir for Mvir)
v_profile = np.sqrt(
... | [
"def apply_radial_velocity(self, v):\n # https://ned.ipac.caltech.edu/level5/Hogg/Hogg3.html\n c = 299792458.0\n return self.apply_redshift(sqrt((1 + v / c) / (1 - v / c)) - 1)",
"def radial_velocity(self):\n return np.sum(self._calculate_radial_velocity(\n self._observer, s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in an array of eda values, returns a list containing one value for the mean, one for the sum, and one for the peak frequency. | def get_simple_vals(eda_array):
if len(eda_array)==0:
return [0,0,0]
eda_array = np.array(eda_array)
x = np.linspace(1, len(eda_array), num=len(eda_array))
y = eda_array
# normalize with log
# and blur with gaussian
y = filters.gaussian_filter(y, 30)
indexes = peakutils.indexes(y... | [
"def collect_reducer_mean(values):\n try:\n return sum(values) / float(len(values))\n except TypeError:\n raise InvalidOperationError(\"Unable to find the mean of that data\")",
"def calculate_mean(ampliture_res):\r\n ampliture_mean = []\r\n for item in ampliture_res:\r\n mean = n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detects if the transformation is required or not based on the defined conditions and the actual values in a record. All conditions in when need to be met for the transformation to be required. | def is_transform_required(record: Dict, when: Optional[List[Dict]]) -> bool:
if not when:
# Transformation is always required if 'when' condition not defined
LOGGER.debug('No conditions, transformations is required')
return True
transform_required = False
# Check if conditional tra... | [
"def checkConditionsSupport(e):\n if mk.vars['FORMAT_SUPPORTS_CONDITIONS'] != '1' and \\\n mk.vars['FORMAT_SUPPORTS_CONFIGURATIONS'] != '1':\n raise ReaderError(e, \n 'output format does not support conditional processing')",
"def checkConditions(self, condFuncs):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the given transformation type to the given value | def _transform_value(value: Any, trans_type: str) -> Any:
# Transforms any input to NULL
if trans_type == "SET-NULL":
return_value = None
# Transforms string input to hash
elif trans_type == "HASH":
return_value = hashlib.sha256(value.encode('utf-8')).hexdigest()
# Transforms strin... | [
"def transform(self, value, arg):\n if value is not None:\n value = self.doTransform(value, arg)\n\n return value",
"def apply_transform_to_type(self, typedef):\n for iconv in self.transform:\n if not iconv.original_datatype:\n iconv.set_original_datatype(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Multiply all the matrices, convert the result to a chimera.CoordFrame and set that as the xform for the target molecule. If precision is set, round them. | def express(self):
matrices = self.allele + (self.to_zero,)
if self.precision > 0:
self.molecule.openState.xform = M.chimera_xform(
M.multiply_matrices(*numpy_around(matrices, self.precision).tolist()))
else:
self.molecule.openState.xform = M.chimera_xform... | [
"def set_grid_coords(self, precision):\n coord = '{:010.2f}'\n utm_e = coord.format(self.utm_e)\n utm_n = coord.format(self.utm_n)\n\n if precision <= 1:\n self.grid_coords = utm_e[-8:-3] + utm_n[-8:-3]\n elif precision <= 10:\n self.grid_coords = utm_e[-8:-4... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset xform to unity matrix. | def unexpress(self):
self.molecule.openState.xform = X() | [
"def reset(self):\n self.matrix.fill(True)\n for cat in range(len(self.categories)):\n s = self.cat_slice(cat)\n self.matrix[s, s] = False\n np.fill_diagonal(self.matrix, True)\n self.assertions.clear()\n self._log(f'Reset matrix with {self.edges} edges\\n')"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes votings for other dossiers and duplicate controversial dossier votings | def clean_voting_results(voting_results, dossier_id):
voting_results_cleaned = []
for voting_result in voting_results:
if str(voting_result.get_dossier_id()) != str(dossier_id):
# this should only happen for controversial voting result lists, example: https://www.tweedekamer.nl/kamerstukken/... | [
"def removeOneKnotInV(*args, **kwargs):\n \n pass",
"def _update_scg_vioses(context, scg_dto, vios_dom_ids, session):\n with session.begin(subtransactions=True):\n vios_pk_ids = []\n for dom_id in vios_dom_ids:\n vios_pk_ids.append(_get_vios_pk_id(context, dom_id, session))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns current access and refresh tokens of the instance. | def get_tokens(self):
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token
} | [
"def refresh_tokens(self) -> str:\n run_coroutine_threadsafe(\n self.session.async_ensure_token_valid(), self.hass.loop\n ).result()\n\n return self.session.token[\"access_token\"] # type: ignore[no-any-return]",
"def get_refresh(self):\n\t\tauth_info = self.__get_refresh__()\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns correct client endpoint even if wasn't provided. | def _resolve_client_endpoint(self):
return self.client_endpoint or self._client_endpoint_template.format(domain=self.domain) | [
"def _resolve_client_endpoint(self) -> str:\n return self.client_endpoint or self._client_endpoint_template.format(domain=self.domain)",
"def _get_endpoint(client, **kwargs):\n return client.service_catalog.url_for(\n service_type=kwargs.get('service_type') or 'sip',\n endpoint_type=kwargs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build an endpoint for webhook with authentication code. | def _resolve_webhook_endpoint(self, code):
return self._webhook_endpoint_template.format(
domain=self.domain,
user_id=self.user_id,
code=code
) | [
"def _resolve_webhook_endpoint(self, code: Optional[str] = None):\n return self._webhook_endpoint_template.format(\n domain=self.domain,\n user_id=self.user_id,\n code=code or self.webhook_code\n )",
"def webhook():\n return slack_webhook",
"def webhook_handler(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert level_name (debug, WARNING...) to level number. | def level_name_to_level_no(level_name):
ulevel_name = level_name.upper()
if ulevel_name == "DEBUG" or ulevel_name == "NOTSET":
return logging.DEBUG
elif ulevel_name == "INFO":
return logging.INFO
elif ulevel_name == "WARNING":
return logging.WARNING
elif ulevel_name == "ERROR... | [
"def level_num(name, default_level):\n level_mapping = dict(\n ERROR=logging.ERROR,\n INFO=logging.INFO,\n WARNING=logging.WARNING,\n DEBUG=logging.DEBUG,\n )\n return level_mapping.get(name.upper(), default_level)",
"def get_log_level_name(log_level):\n return LOG_LEVEL_MA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an extra context by calling an external configured python func. | def get_extra_context():
extra_context_f = Config.extra_context_func
if extra_context_f is None:
return {}
extra_context = extra_context_f() # pylint: disable=E1120
if not isinstance(extra_context, dict):
print("bad extra_context (not a dict) => ignoring", file=sys.stderr)
retur... | [
"def user_context(function):\n\n @functools.wraps(function)\n def wrapper(*func_args, **func_kwargs):\n context = _get_context()\n func_kwargs['user_context'] = context\n return function(*func_args, **func_kwargs)\n\n return wrapper",
"def get_wrapped_response_function(ext):\n arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tempesta must separate response body because it is larger than SETTINGS_MAX_FRAME_SIZE. Client must receive several DATA frames. | def test_large_data_frame_in_response(self):
self.start_all_services()
client: deproxy_client.DeproxyClientH2 = self.get_client("deproxy")
server: deproxy_server.StaticDeproxyServer = self.get_server("deproxy")
client.update_initial_settings(max_frame_size=16384)
response_body ... | [
"def test_large_headers_frame_in_response(self):\n self.start_all_services()\n client: deproxy_client.DeproxyClientH2 = self.get_client(\"deproxy\")\n server: deproxy_server.StaticDeproxyServer = self.get_server(\"deproxy\")\n\n client.update_initial_settings(max_frame_size=16384)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tempesta must separate response headers to HEADERS and CONTINUATION frames because it is larger than SETTINGS_MAX_FRAME_SIZE. | def test_large_headers_frame_in_response(self):
self.start_all_services()
client: deproxy_client.DeproxyClientH2 = self.get_client("deproxy")
server: deproxy_server.StaticDeproxyServer = self.get_server("deproxy")
client.update_initial_settings(max_frame_size=16384)
large_heade... | [
"def test_headers_frame_is_large_than_max_frame_size(self):\n self.start_all_services()\n\n client: deproxy_client.DeproxyClientH2 = self.get_client(\"deproxy\")\n\n client.update_initial_settings()\n # We set SETTINGS_MAX_FRAME_SIZE = 20000 that H2Connection does not raise error,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An endpoint MUST send an error code of FRAME_SIZE_ERROR if a frame exceeds the size defined in SETTINGS_MAX_FRAME_SIZE. RFC 9113 4.2 | def test_headers_frame_is_large_than_max_frame_size(self):
self.start_all_services()
client: deproxy_client.DeproxyClientH2 = self.get_client("deproxy")
client.update_initial_settings()
# We set SETTINGS_MAX_FRAME_SIZE = 20000 that H2Connection does not raise error,
# but Tempe... | [
"def test_reject_overlarge_stream_window_settings(self, frame_factory):\n c = h2.connection.H2Connection()\n c.initiate_connection()\n c.send_headers(1, self.example_request_headers)\n\n # Go one byte smaller than the limit.\n increment = 2**31 - 1 - c.outbound_flow_control_window... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test the MSE function | def testCalculateMSE(self):
## matching case
actual = torch.tensor(np.array([[1,0,1], [1,1,1], [0,0,0]]))
predicted = torch.tensor(np.array([[1,0,1], [1,1,1], [0,0,0]]))
self.assertEqual(calculateMSE(actual, predicted),0)
## non-matching case with error
actual = torch.ten... | [
"def Get_MSE(self, test_y, pre_result):\n diff = []\n for i in range(len(test_y)):\n diff.append(pow(test_y[i] - pre_result[i],2))\n result = np.sum(diff) / len(test_y)\n print 'MSE: ',result",
"def test_mse_examples():\n\n rmse = smlb.MeanSquaredError()\n\n assert rms... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test the accuracy of the custom negative pearson loss function | def testPearsonCorrLoss(self):
## perfect prediction
actual = torch.FloatTensor(np.array([[.9,.9], [1,1]]))
predicted = torch.FloatTensor(np.array([[.9,.9],[1,1]]))
self.assertEqual(pearsonCorrLoss(actual, predicted), -1)
## imperfect prediction
actual = torch.FloatTensor... | [
"def rmspe_loss(y_true, y_pred):\n sum = K.sqrt(K.mean(K.square((y_true - y_pred) /\n K.clip(K.abs(y_true), K.epsilon(), None) + 1e-6), axis=-1))\n return sum*100",
"def correlation_coefficient_loss(labels, predictions):\n return 1 - pearsonr(labels, predictions) ** 2",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test the getMetrics() function's correctness | def testGetMetrics(self):
## case with nonzero true positives, true negatives, and false negatives
actual = torch.FloatTensor(np.array([[[1.1, 1.1], [0, .99]]]))
predicted = torch.FloatTensor(np.array([[[1.05, .99],[.99, 1.1]]]))
self.assertEqual(getMetrics(predicted, actual, lab_thresh=... | [
"def test_get_metrics(self):\n pass",
"def test_metric_function(self):\n model = FakeSemanticSegmentationModel()\n batch, output, _ = get_fake_batch_output()\n batch_replicated, outputs_replicated = (jax_utils.replicate(batch),\n jax_utils.replicate(outpu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make sure train and test indices do not overlap | def testTrainTestSplit(self):
self.assertEqual(len(set(self.train_indices).intersection(self.test_indices)), 0) | [
"def test_inputing_invalid_train_indices(full_no_reset_inst):\n # Only 5 data points so can choose from: [0, 1, 2, 3, 4]\n with pytest.raises(QAutoencoderError):\n full_no_reset_inst.train_test_split(train_indices=[5, 2])\n \n with pytest.raises(QAutoencoderError):\n full_no_reset_inst.tra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test the DAPI Dataset object used for to train DAPI > AT8 (supplement) | def testDAPIDataset(self):
csv_name = "csvs/raw_dataset_1_thru_6_full_images_gpu2.csv"
meanSTDStats = "stats/raw_dataset_1_thru_6_stats.npy"
minMaxStats = "stats/raw_1_thru_6_min_max.npy" #stats for min max values
if "keiser" in hostname:
DATA_DIR = "/srv/nas/mk3/users/dwong... | [
"def test_datasource():\n ds = AircallDataSource(\n name='mah_ds',\n domain='test_domain',\n limit=1,\n )\n assert ds.dataset == 'calls'",
"def getTestingData(self):",
"def test_read_dataset_selection(self):\n \n print(\"started: test_read_dataset_selection\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test the Dataset used for the osteosarcoma dataset | def testOsteosarcomaDataset(self):
if "keiser" in hostname:
DATA_DIR = "/srv/nas/mk1/users/dwong/tifs/" #where the raw images are located
else:
DATA_DIR = "/data1/wongd/tifs/"
csvName = "csvs/cyclin_dataset.csv"
dataset = OsteosarcomaDataset(csvName, DATA_DIR)
... | [
"def testOsteosarcomaAblationDataset(self):\n csvName = \"csvs/cyclin_dataset.csv\"\n if \"keiser\" in hostname:\n DATA_DIR = \"/srv/nas/mk1/users/dwong/tifs/\" #where the raw images are located\n else:\n DATA_DIR = \"/data1/wongd/tifs/\"\n dataset = OsteosarcomaAbl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test the Dataset used for training the ablated osteosarcoma model | def testOsteosarcomaAblationDataset(self):
csvName = "csvs/cyclin_dataset.csv"
if "keiser" in hostname:
DATA_DIR = "/srv/nas/mk1/users/dwong/tifs/" #where the raw images are located
else:
DATA_DIR = "/data1/wongd/tifs/"
dataset = OsteosarcomaAblationDataset(csvNam... | [
"def testOsteosarcomaDataset(self):\n if \"keiser\" in hostname:\n DATA_DIR = \"/srv/nas/mk1/users/dwong/tifs/\" #where the raw images are located\n else:\n DATA_DIR = \"/data1/wongd/tifs/\"\n csvName = \"csvs/cyclin_dataset.csv\"\n dataset = OsteosarcomaDataset(csv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
moves mouse in a sine wave from the left edge to the right of the screen. | def sine_mouse_wave():
width, height = autoy.screen.get_size()
height /=2
height -= 10 #stay within screen
for x in xrange(width):
y = int(height*math.sin((TWO_Pi * x) / width) + height)
autopy.mouse.move(x, y)
time.sleep(random.uniform(0.001, 0.003)) | [
"def right(x):\r\n turtle.right(x)",
"def left(x):\r\n turtle.left(x)",
"def move_paddle(self, mouse):\n self.paddle.x = mouse.x - self.paddle.width / 2\n if self.paddle.x <= 0:\n self.paddle.x = 0\n if self.paddle.x + self.paddle.width >= self.window.width:\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate Tisserand's parameter used to identify potential comets. For example, objects with Tisserand parameter's with respect to Jupiter greater than 3 are typically asteroids, whereas Jupiter family comets may have Tisserand's parameter between 2 and 3. Damocloids have Jupiter Tisserand's parameter of less than 2. | def calcTisserandParameter(a, e, i, third_body="jupiter"):
i_rad = np.radians(i)
major_bodies = MAJOR_BODIES.keys()
if third_body not in major_bodies:
err = f"third_body should be one of {','.join(major_bodies)}"
raise ValueError(err)
ap = MAJOR_BODIES[third_body]
Tp = ap / a + 2 *... | [
"def var_criteria(post_mu_t,post_mu_d,post_va_t,post_va_d):\n\treturn (post_mu_t-post_mu_d)/(post_va_t+post_va_d)",
"def calc_cooling(self, species=None, n=[], T=[], verbose=0):\n if species is None and len(self.species) > 0:\n species = list(self.species.keys())[0]\n if species is not No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the `tf.keras.Model` of a Q network. | def create_q_model(
state_shape: typing.Tuple[int, ...],
layer_configs: typing.Iterable[LayerConfig],
state_dtype=tf.float32,
is_target_network=False,
name=None,
**kwargs
) -> tf.keras.Model:
kwargs["trainable"] = (False if is_target_network else True)
if name is None:
name = "Q... | [
"def _build_model(self):\n input = layers.Input(shape=self.input_shape)\n model = tf.keras.Model(\n inputs=input, outputs=self.network_function(input)\n )\n return model",
"def build_non_linear_quantized_model(units, num_bits=4, activation='relu', optimizer='adam'):\n model... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |