query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Get float value of money. | def GetFloat(self):
return self.Amount / float(Money.HiCost) | [
"def cash_to_float(amount):\n\n suffixes = {\n 'k': 3,\n 'm': 6,\n 'b': 9,\n 't': 12,\n 'p': 15,\n }\n\n if amount:\n try:\n quotient = float(amount)\n #return \"{:.2f}\".format(quotient) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Distribute money value between len(ks) money objects according with given coefficients. | def Distribute(self, ks):
# Count of coefficients.
n = len(ks)
if n == 0:
# No distribution.
raise ValueError("No factors for distribute money.")
if n == 1:
# Only one factor.
return self
# First normalize list.
nks = ut... | [
"def compute_coefficients_ref(ks):\n coeffs = [1]\n for k in ks:\n coeffs = zipWith(lambda x,y:x+y,coeffs+[0],[0]+[-k*c for c in coeffs])\n return coeffs",
"def basis_dk(k, i, p, u, u_list):\n if k > p:\n raise ValueError('k should not exceed p')\n elif k == 0:\n return basis(i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sub another money value. | def __sub__(self, y):
return Money.FromAmount(self.Amount - y.Amount) | [
"def subtractUninvested(self, amount_sub : float) -> float:\n record = self.conn.execute(\"\"\"SELECT amount FROM uninvested\"\"\").fetchone()\n if record:\n amount = float(record[0]) - float(amount_sub)\n self.conn.execute(\"\"\"UPDATE uninvested SET amount=?\"\"\", (amount,))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a cursor for reading the mongo database. | def get_read_cursor(usr=READ_USR,
password=READ_PASS,
db_host=DB_HOST):
return MongoClient(db_host,
username=usr,
password=password,
authSource="mag_db")["mag_db"] | [
"def cursor(self, *args, **kwargs):\n return self.connection.cursor(*args, **kwargs)",
"def get_cursor(fail=True):\n if getattr(_CON, \"con\", None) == None:\n _connect()\n if getattr(_CON, \"con\", None) == None and fail:\n raise Exception(\"No database connection for %s\" % DATABASE_F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
looking for RIR server for specified ip address | def get_rir_server_url(self, ip_address):
data = self.request(ip_address, "whois.iana.org")
for line in [x.strip() for x in data.splitlines()]:
match = re.match("refer:\s*([^\s]+)", line)
if match is None:
continue
return match.group(1), 43
rai... | [
"def find_server(self,key):\n self.check_init()\n for server_index in range(key,len(self.server_table)):\n if(self.server_table[server_index].ip != '-1'):\n return self.server_table[server_index]\n for server_index in range(0,key):\n if(self.server_table[ser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
translate to list of section and write to self._los Each section is a list of lines like [val1, val2,..., val_k] val1, val2, ... val_k1 are strings which represent chain of names val_k is value | def translate_to_los(self):
lines = self.break_to_lines(self._raw_whois)
self._los = [] # list of sections
section = []
new_section = False
for l in lines:
if len(l) == 0 or (len(l) > 0 and l[0] == self._comment_char):
if len(section) > 0:
... | [
"def __init__(self, listSection):\r\n self.listHeader = listSection[0].split('[')[0]\r\n self.afterList = listSection[-1].split(']')[1]\r\n listString = self.buildListString(listSection)\r\n self.values = [value.strip() for value in listString.split(',')]",
"def read_line_list(label):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find first section with name = section_name | def find_first_section(self, section_name):
assert isinstance(section_name, tuple) or isinstance(section_name, list)
for s in self._los:
if self.list_le(section_name, s[0]):
return s
return None | [
"def sectionByName(self, name):\n for section in self._sections:\n if name == section.name:\n return section\n return None",
"def get_section(section):",
"def get_section_by_name(self, name):\r\n # The first time this method is called, construct a name to number\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if ip_address lies in ip_address range | def ip_in_range(self, ip, range):
ip_lst = ip.split('.')
for i1, i2, i3 in zip(range[0], ip_lst, range[1]):
if int(i1) == int(i2) and int(i2) == int(i3):
continue
elif int(i1) <= int(i2) <= int(i3):
return True
else:
ret... | [
"def check_ip_in_subnet(self, ip_address):\n flag = False\n if compare_2_ips(ip_address.ip, self.ip) >=0 and compare_2_ips(ip_address.ip, self.max_ip) <= 0:\n flag = True\n return flag",
"def inIPv4Range(ip: int, ipRange: rules.Ipv4Range) -> bool:\r\n\r\n if ipRange.mask > 32 or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
inetnum section parser. Write org_name and country into nac | def parse_inetnum_sec(self, inetnum_sec, nac):
country_lst = self.find_all_items(inetnum_sec, ('country',))
if len(country_lst) == 0:
self._messanger.send_message("Can't find country in inetnum section")
else:
nac[COUNTRY] = country_lst[0]
org_name_lst = self.fin... | [
"def parse(self):\n nac = [None, [], None] # name, address, country\n\n self.translate_to_los()\n if self.check_simple_org_format():\n org_name = self.parse_simple_org()\n nac[ORGNAME] = org_name\n else:\n inetnum_sec = self.find_first_section(('inetnum'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
organization section parser. Write org_name and address to nac | def parse_org_sec(self, org_section, nac):
org_name_lst = self.find_all_items(org_section, ('org-name',))
if len(org_name_lst) == 0:
self._messanger.send_message("Can't find organisation name in organisation section")
else:
nac[ORGNAME] = org_name_lst[0]
org_addr... | [
"def parse_person_sec(self, person_section, nac):\n person_name = self.find_first_item(person_section, ('person',))\n\n if person_name is None:\n self._messanger.send_message(\"Can't find name in person section\")\n else:\n nac[ORGNAME] = person_name\n\n address_lst... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
role section parser. Write org_name, address to nac | def parse_role_sec(self, role_section, nac):
org_name_lst = self.find_all_items(role_section, ('role',))
if len(org_name_lst) == 0:
self._messanger.send_message("Can't find organisation name in role section")
else:
nac[ORGNAME] = org_name_lst[0]
org_address_lst =... | [
"def parse_role(self, s, nac):\n org_name = self.find_first_item(s, ('role',))\n if org_name is None:\n raise UnknownWhoisFormat('Can not find role in Role section')\n\n address = self.find_all_items(s, ('address',))\n if len(address) == 0:\n raise UnknownWhoisForma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
person section parser. Write peson name, address to nac | def parse_person_sec(self, person_section, nac):
person_name = self.find_first_item(person_section, ('person',))
if person_name is None:
self._messanger.send_message("Can't find name in person section")
else:
nac[ORGNAME] = person_name
address_lst = self.find_al... | [
"def parse_person(self, s, nac):\n org_name = self.find_first_item(s, ('person',))\n if org_name is None:\n raise UnknownWhoisFormat('Can not find person in Person section')\n\n address = self.find_all_items(s, ('address',))\n if len(address) == 0:\n raise UnknownWh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parse whois text and extracts org. name, org. address, country abbreviation | def parse(self):
nac = [None, [], None] # name, address, country
self.translate_to_los()
if self.check_simple_org_format():
org_name = self.parse_arin_simple_org()
nac[ORGNAME] = org_name
else:
ref_ser = self.find_referral_server()
if re... | [
"def parse(self):\n nac = [None, [], None] # name, address, country\n\n self.translate_to_los()\n if self.check_simple_org_format():\n org_name = self.parse_simple_org()\n nac[ORGNAME] = org_name\n else:\n inetnum_sec = self.find_first_section(('inetnum'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check is ReferralServer section exists. That means the ip_address is used another organization | def find_referral_server(self):
s = self.find_first_section(('ReferralServer',))
if s:
server = (s[0][2]).lstrip('/')
port = int(s[0][3])
return server, port
else:
return None | [
"def check_reverse_lookup():\n try:\n host_name = socket.gethostname().lower()\n host_ip = socket.gethostbyname(host_name)\n host_fqdn = socket.getfqdn().lower()\n fqdn_ip = socket.gethostbyname(host_fqdn)\n return host_ip == fqdn_ip\n except socket.error:\n pass\n return False",
"def ip_know... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parse whois text and extracts org. name, org. address, country abbreviation | def parse(self):
nac = [None, [], None] # name, address, country
self.translate_to_los()
if self.check_simple_org_format():
org_name = self.parse_simple_org()
nac[ORGNAME] = org_name
else:
inetnum_sec = self.find_first_section(('inetnum',))
... | [
"def parse(self):\n nac = [None, [], None] # name, address, country\n\n self.translate_to_los()\n\n if self.check_simple_org_format():\n org_name = self.parse_arin_simple_org()\n nac[ORGNAME] = org_name\n else:\n ref_ser = self.find_referral_server()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extracts nac info from role section | def parse_role(self, s, nac):
org_name = self.find_first_item(s, ('role',))
if org_name is None:
raise UnknownWhoisFormat('Can not find role in Role section')
address = self.find_all_items(s, ('address',))
if len(address) == 0:
raise UnknownWhoisFormat('Can not f... | [
"def parse_role_sec(self, role_section, nac):\n org_name_lst = self.find_all_items(role_section, ('role',))\n if len(org_name_lst) == 0:\n self._messanger.send_message(\"Can't find organisation name in role section\")\n else:\n nac[ORGNAME] = org_name_lst[0]\n\n org... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extracts nac info from person section | def parse_person(self, s, nac):
org_name = self.find_first_item(s, ('person',))
if org_name is None:
raise UnknownWhoisFormat('Can not find person in Person section')
address = self.find_all_items(s, ('address',))
if len(address) == 0:
raise UnknownWhoisFormat('C... | [
"def parse_person_sec(self, person_section, nac):\n person_name = self.find_first_item(person_section, ('person',))\n\n if person_name is None:\n self._messanger.send_message(\"Can't find name in person section\")\n else:\n nac[ORGNAME] = person_name\n\n address_lst... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that indicates whether log has any traces of warnings. | def FoundWarnings(self):
return len(self.WarningLines()) > 0 | [
"def has_warnings(self):\n for item in self._content:\n attrs = item[1]\n if attrs.get('warning',False):\n return True\n return False",
"def HasExtractionWarnings(self):\n return self._store.HasExtractionWarnings()",
"def can_log(self):\n return # bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns unique list of compiler and linker warning lines. | def WarningLines(self):
if self.__lines_with_warnings is None:
warnings = set()
for line in self.log_content.splitlines():
match = IbOutputParser.WARNING_LINE_MATCHER.match(line)
if match:
warnings.add(line)
self.__lines_with_warnings = list(warnings)
return self.__l... | [
"def _import_warnings(self):\n warnings = (\n r\"Warning: BMDL computation is at best imprecise for these data\",\n r\"THE MODEL HAS PROBABLY NOT CONVERGED!!!\",\n \"THIS USUALLY MEANS THE MODEL HAS NOT CONVERGED!\",\n r\"BMR value is not in the range of the mean f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts text IB compilation log and creates HTML log with nice error links. | def ErrorLogHtml(self):
content = []
self._ResetState()
for line in self.log_content.splitlines():
content.append('%s\n' % self._ProcessLine(line))
return self._HtmlHeader() + ''.join(content) + '</body></html>' | [
"def compile_log_result(self):\n file = self.source_file[:-4] + \".log\"\n log.info(\"[COMPILE LOG] log file is here: {}\".format(file))\n \n log_line = 'Warning: No build log. Check console for errors.'\n\n try:\n with open(file, encoding=\"utf16\", mode=\"r\") as f:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a hash with project names that appeared as failed in the log with number of errors for that project. | def FailedProjects(self):
if self.__failed_projects is None:
self.__failed_projects = {}
for line in self.log_content.splitlines():
match = IbOutputParser.ERROR_MATCHER.match(line)
if match and int(match.group(2)) > 0:
self.__failed_projects[match.group(1)] = int(match.group(2)... | [
"def get_errors(self, queue_id):\n try:\n errorlog = self._get_stderr_path(queue_id)\n except ValueError, e:\n errors = str(e)\n else:\n if os.path.exists(errorlog):\n err_f = open(errorlog, 'r')\n errors = err_f.read()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes project output lines | def _ProcessProjectOutputLine(self, match):
project_id = int(match.group(1))
if not project_id in self.__project_outputs:
self.__project_outputs[project_id] = []
self.__project_outputs[project_id].append(match.group(2))
self.__project_outputs[project_id].append('\n') | [
"def __processOutputLine(self, line):\n if line[0] in \"ACIMR?!\" and line[1] == \" \":\n status, path = line.strip().split(\" \", 1)\n self.__generateItem(status, path)",
"def _worker_output(self, line):\n line = line.replace('\\n', '')\n self._view.add_to_log(line)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using an unzipped, json package file with full urls, downloads a .deb package Uses the 'Filename' key to download the .deb package | def download_dpkg(package_files, packages, workspace_name, versionsfile):
package_to_rule_map = {}
package_to_version_map = {}
package_file_to_metadata = {}
for pkg_name in set(packages.split(",")):
pkg = {}
for package_file in package_files.split(","):
if package_file not in... | [
"def get_dpkg(name, release, dir):\n\n debian_repo = 'http://ftp.es.debian.org/debian/'\n sources_url = debian_repo + 'dists/' + release + '/source/Sources.gz'\n sources_file = os.path.join(dir, 'Sources.gz')\n urllib.request.urlretrieve(sources_url, sources_file)\n pkg_data = get_dpkg_data(sources_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Downloads a debian package list, expands the relative urls, and saves the metadata as a json file A debian package list is a (xz|gzip)ipped, newline delimited, colon separated file with metadata about all the packages available in that repository. Multiline keys are indented with spaces. | def download_package_list(mirror_url, distro, arch, snapshot, sha256, packages_url, package_prefix):
if bool(packages_url) != bool(package_prefix):
raise Exception("packages_url and package_prefix must be specified or skipped at the same time.")
if (not packages_url) and (not mirror_url or not snapsho... | [
"def download_package_details(input_file: IO[str], out_dir: str):\n os.makedirs(out_dir, exist_ok=True)\n\n package_iterator = map(lambda l: l.strip(), input_file)\n for packages in grouper(package_iterator, BULK_SIZE):\n for package, meta_data in bulk_fetch_details(packages).items():\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get config of the component with the given index in the pipeline. | def component_config_from_pipeline(
index: int,
pipeline: List[Dict[Text, Any]],
defaults: Optional[Dict[Text, Any]] = None,
) -> Dict[Text, Any]:
try:
c = pipeline[index]
return override_defaults(defaults, c)
except IndexError:
raise_warning(
f"Tried to get confi... | [
"def get(self, idx: int) -> ConfigEntity:\n return self._configs[idx]",
"def index_config(self) -> Optional[pulumi.Input['FieldIndexConfigArgs']]:\n return pulumi.get(self, \"index_config\")",
"def get_compartment_by_index(net_index: int, comp_index: int) -> CompartmentData:\n return _translate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test module bthe_b.py by downloading bthe_b.csv and testing shape of extracted data has 100 rows and 8 columns | def test_bthe_b():
test_path = tempfile.mkdtemp()
x_train, metadata = bthe_b(test_path)
try:
assert x_train.shape == (100, 8)
except:
shutil.rmtree(test_path)
raise() | [
"def test_hunt_csv_2():\n ints = rng.integers(0, 100, 8)\n breaks = rng.choice((\"\\r\", \"\\n\", \"\\r\\n\"), 3)\n block = (\n f\"alpha{ints[0]},{ints[1]}{breaks[0]}\"\n f\"{ints[2]},{ints[3]}{breaks[1]}{ints[4]},{ints[5]}{breaks[2]}\"\n f\"{ints[6]},{ints[7]}beta\"\n )\n table ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch a dict of all departments and their numbers. | def _get_department_numbers_and_names() -> Dict[str, str]:
response = CLIENT.get("https://vitemadose.gitlab.io/vitemadose/departements.json")
response.raise_for_status()
return {dep["code_departement"]: dep["nom_departement"] for dep in response.json()} | [
"def create_departments_dict():\n\n departmentsJsonResult = get_deps()\n departmentsDict = dict()\n for row in departmentsJsonResult:\n departmentsDict[row[\"id\"]] = (row[\"name\"], row[\"code\"])\n return departmentsDict",
"def api_all_dep():\n deps =[{\"department\": elem.name} for elem i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve appointments for all queried departments. | def retrieve_all_suitable_appointments() -> Dict[str, List[AppointmentMatch]]:
all_appointments = {}
for department in DEPARTMENTS:
entry = f"{DEPARTMENTS_TABLE[department]} ({department})"
all_appointments[entry] = find_centers_for_department(department)
return all_appointments | [
"def populate_appointments(endpoint, doctor):\n date = timezone.now().strftime('%Y-%m-%d')\n\n appointments = endpoint.list({'doctor': doctor.id, 'date': date})\n for appointment_data in appointments:\n patient = Patient.objects.get(id=appointment_data['patient'])\n\n # si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Abstract method for locking a pokemon on a move | def add_lock(self, pokemon, move):
pass | [
"def remove_lock(self, pokemon, move):\n pass",
"def move(self, action):\n tile_type, from_pile, to_stack, nbr_to_move = action\n\n # Check for errors\n if self.winner is not None:\n raise Exception(\"Game already won\")\n #elif pile < 0 or pile >= len(self.piles):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Abstract method for removing a lock from pokemon's moves | def remove_lock(self, pokemon, move):
pass | [
"def add_lock(self, pokemon, move):\n pass",
"def remove_item(game):\n player = game.player\n item = game.rooms[player.position['next location']].door['unlock']\n player.inventory.remove(item)",
"def unmove(self):\n self.insert(None, self.moves.pop())\n self.legal_moves = self.gene... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience method that will get a top level atdf section, making sure it is singular | def _getTopSection(self, name):
section = self.query(name)
assert len(section) == 1
return section[0] | [
"def get_section(section):",
"def test_get_section_path():\n sp = iniconf.get_section_path(c['sec1'])\n errmsg = \"Section path is not as expected!\"\n assert sp == ['sec1'], errmsg\n sp = iniconf.get_section_path(c['sec1']['sec2'])\n assert sp == ['sec1', 'sec2'], errmsg\n sp = iniconf.get_sect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute the command ceph orch ls . | def ls(self: OrchProtocol, config: Optional[Dict] = None) -> Tuple:
cmd = ["ceph", "orch"]
if config and config.get("base_cmd_args"):
cmd.append(config_dict_to_string(config["base_cmd_args"]))
cmd.append("ls")
if config and config.get("args"):
args = config.get... | [
"def ls():\n\tdata_socket = pack_and_send('ls')\n\tdata = recv(data_socket).decode('utf-8')\n\tshut(data_socket)\n\tstatus = _SOCK.recv(1)\n\tif not status or status == b'F':\n\t\t_log(\"Directory listing failed.\")\n\telif status == b'S':\n\t\t_log(data[:-1])\n\telse:\n\t\t_err_log(\"Unexpected status: {}\".format... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if last sync was ok and happend recently, else False. | def is_notification_sync_ok(self) -> bool:
return (
self.notifications_last_update_ok is True
and self.is_notification_sync_fresh
) | [
"def _should_sync(self, data, last_sync):\n\n # definitely sync if we haven't synced before\n if not last_sync or not last_sync.date:\n return True\n\n # check if any items have been modified since last sync\n for data_item in data:\n # >= used because if they are t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns true if they have been no errors and last syncing occurred within alloted time for all sync categories | def are_all_syncs_ok(self) -> bool:
return (
self.is_structure_sync_ok
and self.is_notification_sync_ok
and self.is_forwarding_sync_ok
and self.is_assets_sync_ok
) | [
"def _should_sync(self, data, last_sync):\n\n # definitely sync if we haven't synced before\n if not last_sync or not last_sync.date:\n return True\n\n # check if any items have been modified since last sync\n for data_item in data:\n # >= used because if they are t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add character to this owner. Raises ValueError when character does not belong to owner's corporation. | def add_character(
self, character_ownership: CharacterOwnership
) -> "OwnerCharacter":
if (
character_ownership.character.corporation_id
!= self.corporation.corporation_id
):
raise ValueError(
f"Character {character_ownership.character} do... | [
"def add_character(self, character, position, name='', symbol='', ):\n if name == '':\n name = character.name\n if symbol == '':\n symbol = character.name.strip()[0].lower()\n self.atlas[name] = position\n self.people[name] = character\n self.symbols[name] = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count of valid owner characters. | def characters_count(self) -> int:
return self.characters.count() | [
"def get_nbr_of_characters():\n\tchars = Character.objects()\n\treturn len(chars)",
"def n_wrong_characters(self):\n return self._n_characters_with_status(STATUS_WRONG)",
"def count_number_of_characters(text):\r\n return len(text)",
"def n_untouched_characters(self):\n return len([x for x in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Notify admin and users about an error with the owner characters. | def notify_error(
error: str, character: CharacterOwnership = None, level="warning"
) -> None:
message_id = f"{__title__}-Owner-fetch_token-{self.pk}"
title = f"{__title__}: Failed to fetch token for {self}"
error = f"{error} Please add a new character to restore ... | [
"def on_register_error_dm_command(self, event):\n if event.author.id in bot.config.exception_dms:\n api_loop(\n event.channel.send_message,\n f\"You're already registered :ok_hand:\",\n )\n else:\n config = bot.get_config()\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates all structures from ESI. | def update_structures_esi(self, user: User = None):
self.structures_last_update_ok = None
self.structures_last_update_at = now()
self.save()
token = self.fetch_token()
is_ok = self._fetch_upwell_structures(token)
if STRUCTURES_FEATURE_CUSTOMS_OFFICES:
is_ok &... | [
"def _fetch_upwell_structures(self, token: Token) -> bool:\n from .eveuniverse import EsiNameLocalization\n\n corporation_id = self.corporation.corporation_id\n structures = list()\n try:\n # fetch all structures incl. localizations for services\n structures_w_lang ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove structures no longer returned from ESI. | def _remove_structures_not_returned_from_esi(
self, structures_qs: models.QuerySet, new_structures: list
):
ids_local = {x.id for x in structures_qs}
ids_from_esi = {x["structure_id"] for x in new_structures}
ids_to_remove = ids_local - ids_from_esi
if len(ids_to_remove) > 0:... | [
"def _removePreviouslyExtractedVessels(self):\n removeNodesFromMRMLScene([self._vesselVolumeNode, self._vesselModelNode])",
"def remove_destroyed_entities (entities):\n entities_to_remove = []\n\n # Adding the entities to remove in the list\n for entity in entities:\n if entities[entity]['type'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch Upwell structures from ESI for self. Return True if successful, else False. | def _fetch_upwell_structures(self, token: Token) -> bool:
from .eveuniverse import EsiNameLocalization
corporation_id = self.corporation.corporation_id
structures = list()
try:
# fetch all structures incl. localizations for services
structures_w_lang = esi_fetch_... | [
"def get_available_structures( self ):\n _check_type(self)\n return _get_available(self, \"structure_\")",
"def update_structures_esi(self, user: User = None):\n self.structures_last_update_ok = None\n self.structures_last_update_at = now()\n self.save()\n token = self.fetch_toke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compress service names localizations for each structure We are assuming that services are returned from ESI in the same order for each language. | def _compress_services_localization(
structures_w_lang: dict, default_lang: str
) -> list:
structures_services = Owner._collect_services_with_localizations(
structures_w_lang, default_lang
)
structures = Owner._condense_services_localizations_into_structures(
... | [
"def _collect_services_with_localizations(structures_w_lang, default_lang):\n structures_services = dict()\n for lang, structures in structures_w_lang.items():\n if lang != default_lang:\n for structure in structures:\n if \"services\" in structure and stru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
collect services with name localizations for all structures | def _collect_services_with_localizations(structures_w_lang, default_lang):
structures_services = dict()
for lang, structures in structures_w_lang.items():
if lang != default_lang:
for structure in structures:
if "services" in structure and structure["servi... | [
"def _condense_services_localizations_into_structures(\n structures_w_lang, default_lang, structures_services\n ):\n structures = structures_w_lang[default_lang]\n for structure in structures:\n if \"services\" in structure and structure[\"services\"]:\n structure_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add corresponding service name localizations to structure's services | def _condense_services_localizations_into_structures(
structures_w_lang, default_lang, structures_services
):
structures = structures_w_lang[default_lang]
for structure in structures:
if "services" in structure and structure["services"]:
structure_id = structure["... | [
"def _collect_services_with_localizations(structures_w_lang, default_lang):\n structures_services = dict()\n for lang, structures in structures_w_lang.items():\n if lang != default_lang:\n for structure in structures:\n if \"services\" in structure and stru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch custom offices from ESI for this owner. Return True when successful, else False. | def _fetch_custom_offices(self, token: Token) -> bool:
corporation_id = self.corporation.corporation_id
structures = dict()
try:
pocos = esi_fetch(
"Planetary_Interaction.get_corporations_corporation_id_customs_offices",
args={"corporation_id": corpor... | [
"def test_corp_party_offices(session): # pylint: disable=unused-argument\n offices = CorpParty.get_offices_held_by_corp_party_id(1)\n assert len(offices) == 2",
"def office_get_all(self):\n\n return self.offices",
"def test_get_all_offices(self):\n with self.app_context():\n resp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract name of planet from assert name for a customs office. | def _extract_planet_name(text: str) -> str:
reg_ex = re.compile(r"Customs Office \((.+)\)")
matches = reg_ex.match(text)
return matches.group(1) if matches else "" | [
"def get_plant_name(self):\n if not self.plant_name:\n self.plant_name = self._search('botanische naam')\n return self.plant_name",
"def extractFromTitle(title):\n # remove trailing period\n period_idx = title.rfind('.')\n if period_idx>0 and period_idx>len(title)-5:\n title = title[:pe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch starbases from ESI for this owner. Return True when successful, else False. | def _fetch_starbases(self, token: Token) -> bool:
structures = list()
corporation_id = self.corporation.corporation_id
try:
starbases = esi_fetch(
"Corporation.get_corporations_corporation_id_starbases",
args={"corporation_id": corporation_id},
... | [
"def repository_is_starred(user, repository):\n try:\n (Star.select().where(Star.repository == repository.id, Star.user == user.id).get())\n return True\n except Star.DoesNotExist:\n return False",
"def query_balances(\n self,\n requested_save_data: bool = False,\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch notifications for this owner from ESI and proceses them. | def fetch_notifications_esi(self, user: User = None) -> None:
notifications_count_all = 0
self.notifications_last_update_ok = None
self.notifications_last_update_at = now()
self.save()
token = self.fetch_token(rotate_characters=True)
try:
notifications = self... | [
"def notifications(self):\r\n from .._impl.notification import Notification\r\n result = []\r\n url = \"%s/community/users/%s/notifications\" % (self._portal.resturl, self._user_id)\r\n params = {\"f\" : \"json\"}\r\n ns = self._portal.con.get(url, params)\r\n if \"notifica... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stores new notifications in database. Returns number of newly created objects. | def _store_notifications(self, notifications: list) -> int:
# identify new notifications
existing_notification_ids = set(
self.notifications.values_list("notification_id", flat=True)
)
new_notifications = [
obj
for obj in notifications
if o... | [
"def _store_notifications(self, notifications: list) -> int:\n # identify new notifications\n existing_notification_ids = set(\n self.notifications.values_list(\"notification_id\", flat=True)\n )\n new_notifications = [\n obj\n for obj in notifications\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
processes notifications for timers if any | def _process_timers_for_notifications(self, token: Token):
if STRUCTURES_ADD_TIMERS:
cutoff_dt_for_stale = now() - timedelta(
hours=STRUCTURES_HOURS_UNTIL_STALE_NOTIFICATION
)
notifications = (
Notification.objects.filter(owner=self)
... | [
"def handle_notifies(self):\n assert threading.current_thread() == self.MAIN_THREAD\n try:\n while True:\n evt_type, evt = self.notifies.get_nowait()\n\n for o in self.observers[evt_type]:\n self.__invoke_observer(o, evt_type, evt)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update all assets from ESI related to active structure for this owner. | def update_asset_esi(self, user: User = None):
self.assets_last_update_ok = None
self.assets_last_update_at = now()
self.save()
token = self.fetch_token()
structure_ids = {x.id for x in Structure.objects.filter(owner=self)}
try:
OwnerAsset.objects.update_or_c... | [
"def update_assets(self):\n assets = merge_assets([script.used_assets for script in self.paths_to_scripts.values()])\n for asset in assets:\n asset.supply(self.path)",
"def _update(self):\n self._update_assets()\n self._update_funds()",
"def update_inplace(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the IntersectionOverUnion metric for the given ground truth and predicted labels. | def evaluate(ground_truth_labels: type_alias.TensorLike,
predicted_labels: type_alias.TensorLike,
grid_size: int = 1,
name: str = "intersection_over_union_evaluate") -> tf.Tensor:
with tf.name_scope(name):
ground_truth_labels = tf.convert_to_tensor(value=ground_truth_labels)... | [
"def IoU(detection1, detection2):\n\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(detection1[0], detection2[0])\n yA = max(detection1[1], detection2[1])\n xB = min(detection1[2], detection2[2])\n yB = min(detection1[3], detection2[3])\n\n # area of intersection\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create list of tuples representing specified number of posts to make | def createPosts(self, numPosts):
allAuthors = self.makeNames(numPosts)
allTitles = self.makeTitles(numPosts)
postDetails, totalsDict = PostMaker.makePostLengths(numPosts)
allSkateParagraphs = self.getSkateParagraphs(totalsDict[PostMaker.skateType])
allWikihowLines = self.getWikih... | [
"def get_posts(off, cnt):\r\n\tposts = mc.get('posts')\r\n\tif(posts == None):\r\n\t\tcursor = db_execute('SELECT * FROM news INNER JOIN users ON news.creator_id = users.id ORDER BY created DESC')\r\n\t\tposts = cursor.fetchall()\r\n\t\tmc.set('posts', posts)\r\n\treturn posts[off:off+cnt]",
"def create_test_post... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create specified amount of post titles from random quote API | def makeTitles(self, number):
quoteUrl = "https://fireflyquotes.p.rapidapi.com/quotes/random"
headers = {
"x-rapidapi-key": self.apiKey,
"x-rapidapi-host": "fireflyquotes.p.rapidapi.com",
}
titles = []
for _ in range(number):
response = reque... | [
"def get_random_quote():\n global tweet_counter\n tag_wheel = ['inspire', 'management', 'life',\n 'love', 'art', 'students', 'funny']\n if tweet_counter == 0:\n week_order = random.sample(range(len(tag_wheel)), len(tag_wheel))\n today_theme = week_order[tweet_counter]\n url = \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the citation(s) for this tool | def citation(**kwargs):
print_citation() | [
"def citations(self):\n\n # concatenate all blocks citations\n citations = []\n for block in self.blocks:\n citations += block.citations\n\n # remove duplicates\n citations = list(set(citations))\n citation_dict = {}\n\n for name in citations:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a unique name for a directory in ./output using current time and script arguments | def make_output_dir_name(args):
prefix = datetime.now().strftime('%Y%m%d-%H%M')
dir_name = f'./output/{prefix}_epochs={args.epochs}_lr={args.lr}'
dir_name += '_with-pretrained-backbone' if args.pretrained_backbone else '_no-pretrained-backbone'
if args.no_geometry_loss:
dir_name += '_no-geometr... | [
"def default_output_dir():\n now = datetime.datetime.now()\n ##output_dir = \"{}-{}-{}.{}-{}-{}.{}\".format(now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond)\n output_dir = \"{}-{}-{}.{}-{}-{}\".format(now.year, now.month, now.day, now.hour, now.minute, now.second)\n logge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints current configuration to a file in the output directory | def print_config_file(output_dir, args):
with open(os.path.join(output_dir, 'config.cfg'), 'w') as f:
for k, v in vars(args).items():
f.write(f'{k}={v}\n')
f.write(f'device={get_device()}') | [
"def print_config_file():\r\n print(CONFIG_FILE_CONTENT, end=\"\")",
"def _display_config_file(self):\n print(f'\\n{ProctorConfig.config_file}:')\n with open(ProctorConfig.config_file) as f:\n print(f.read())",
"def cc_print_cmd(yaml_file):\n data = yaml.safe_load(yaml_file)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a torch.device of type 'cuda' if available, else of type 'cpu' | def get_device() -> torch.device:
return torch.device('cuda' if torch.cuda.is_available() else 'cpu') | [
"def get_device():\n return torch.device('cuda' if torch.cuda.is_available() else 'cpu')",
"def resolve_device(device = None) -> torch.device:\n if device is None or device == 'gpu':\n device = 'cuda'\n if isinstance(device, str):\n device = torch.device(device)\n if not torch.cuda.is_av... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for reading CLIMOD2 csv data into pandas dataframe. Missing data values are converted to NaN Trace values are converted to zero. | def read_climod2(path):
df = pd.read_csv(path, index_col=0, header=0, na_values=['m', 'M'],
parse_dates=True, skipinitialspace=True)
# Get list of columns read
# cols = list(df.columns.values)
# Replace 'T' values with 0.0, for now. (T = trace amount)
df = df.replace('T', 0.0... | [
"def prepare_df(args):\r\n path, column, replace_commas, reverse = args\r\n data = pd.read_csv(path)\r\n data = data[[column]]\r\n if reverse:\r\n data.index = data.index[::-1]\r\n data = data.iloc[::-1]\r\n if replace_commas:\r\n data[column] = data[column].apply(lambda x: float... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is called when somebody on the elevator chooses a floor. This could happen at any time, whether or not the elevator is moving. Any floor could be requested at any time. | def on_floor_selected(self, floor):
if not self.valid_floor(floor):
return
direction_to_floor = self.direction_to(floor)
if direction_to_floor is None:
self.log("missed the boat")
return
# Check the other queue for duplicates
other_directi... | [
"def on_floor_selected(self, floor):\n # Check if oppsite\n has_request = filter(lambda request: request[\"floor\"] == floor, self.queue)\n if self.is_counter(floor) or len(has_request) > 0:\n return\n\n if floor > self.callbacks.current_floor:\n self.last_direction... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the words to the frequency counts. | def add_to_freq(self, words, index):
for word in words:
count = 0
if (word in self.stop_words):
continue
if (self.frequencies[index].has_key(word)):
count = self.frequencies[index][word] + 1
else:
count = 1
... | [
"def update_word_counts(word_counts):\n\tfor word, count in word_counts:\n\t\tredis_wcloud_cli.zadd(WORD_CLOUD_SET,word,count)",
"def add_count(self, word, count=1):\n # word_count = self.histogram.get(word, 0) + count #if word is in words_histogram's keys, count will increment, else equal 1\n # se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the xml files and extracts words from descriptions. | def read_file(self, filename):
tree = ET.parse(filename)
root = tree.getroot()
for child in root:
docDesc = ''
if (child.tag == 'Description'):
docDesc = clean(child.text)
words = docDesc.lower().split()
self.add_to_freq(words, 0)
w... | [
"def english_xml_parser(language,shorts,infile,outfile):\n language_capitalized = language[0].upper() + language[1:] # for matching in text\n tree = ET.parse(infile)\n root = tree.getroot() \n for child in root:\n for child2 in child:\n if child.tag == '{http://www.mediawiki.org/xml/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each outgoing, we add a feature that indicates the total number of packets before it in a sequence. Also, we show the number of incoming packets between outgoing packets This is supposed to indicate burst patterns. We only go up to 300 and pad after that. | def get_packet_ordering(trace, features):
# Number of packets before it in the sequence
count = 0
for i, val in enumerate(trace):
if val[1] > 0:
count += 1
features.append(i)
if count == 300:
break
# Pad
for i in range(count, 300):
feature... | [
"def concentraction_packets(trace, features):\n features_added = 0\n for i in range(0, len(trace), 30):\n if i == 3000: # span_length * max_spans (30 * 100)\n break\n\n count = 0\n try:\n for j in range(30):\n if trace[i + j][1] > 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This measure is supposed to indicate where the outgoing packets are indicated. We divide the trace up into nonoverlapping spans of 30 packets and add the number of outgoing packets in those spans as a feature We only have a maximum of a 100 spans | def concentraction_packets(trace, features):
features_added = 0
for i in range(0, len(trace), 30):
if i == 3000: # span_length * max_spans (30 * 100)
break
count = 0
try:
for j in range(30):
if trace[i + j][1] > 0:
count += 1
... | [
"def analyze_trace(trace, target_number_of_friends, target=0):\n\n ## ADD CODE HERE\n \"\"\"\n print(\"no.rounds:\", len(trace))\n print(\"no:\", target_number_of_friends)\n print(\"target:\", target)\n print(\"trace1\",trace[1])\n print(\"trace10\",trace[1][0])\n print(\"trace101\",trace[1]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract all of the features for the kNN model in the [kNN.py](../attacks/kNN.py) file. trace is a trace of loading a web page in the following format `[(time, incoming)]` where outgoing is 1 is incoming and 1 | def extract_kNN_features(trace):
features = []
get_transmission_size_features(trace, features)
get_packet_ordering(trace, features)
concentraction_packets(trace, features)
bursts(trace, features)
first_20_packets(trace, features)
return features | [
"def get_traces(sampler, nthin):\n # load every nthin'th sample from the walkers and reshape to\n # final dimensions\n traces = sampler.chain[:, ::nthin, :].reshape(-1, sampler.dim).copy()\n # convert from sample space to meaningfull space\n traces[:, [1, 4, 5]] = np.exp(traces[:, [1, 4, 5]])\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor defaultClassName proposed name for the new class (string) defaultFile proposed name for the source file (string) defaultPath default path for the new file (string) parent parent widget if the dialog (QWidget) | def __init__(self, defaultClassName, defaultFile, defaultPath,
parent=None):
super(NewDialogClassDialog, self).__init__(parent)
self.setupUi(self)
self.pathnamePicker.setMode(E5PathPickerModes.DirectoryMode)
self.okButton = self.buttonBox.button(QDialog... | [
"def __init__(self, currentPath, mode, parent=None):\n super(LfConvertDataDialog, self).__init__(parent)\n self.setupUi(self)\n \n self.newProjectPicker.setMode(E5PathPickerModes.DirectoryMode)\n \n self.__defaults = getDefaults()\n self.__currentPath = Utilities.toN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Private slot to set the enable state of theok button. | def __enableOkButton(self):
self.okButton.setEnabled(
self.classnameEdit.text() != "" and
self.filenameEdit.text() != "" and
self.pathnamePicker.text() != "") | [
"def __updateOK(self):\n enabled = True\n if self.noneButton.isChecked():\n enabled = False\n elif self.idButton.isChecked():\n enabled = self.idEdit.text() != \"\"\n elif self.tagButton.isChecked():\n enabled = self.tagCombo.currentText() != \"\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Private slot called, when thext of the classname edit has changed. text changed text (string) | def on_classnameEdit_textChanged(self, text):
self.__enableOkButton() | [
"def text_changed(self):\n self.default = False\n self.emit(SIGNAL('text_changed_at(QString,int)'),\n self.filename, self.editor.get_position('cursor'))",
"def on_text_edited(self, event):\n event.Skip()\n self.shell_obj._field_text_edited()",
"def onTextChange(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Private slot called, when thext of the filename edit has changed. text changed text (string) | def on_filenameEdit_textChanged(self, text):
self.__enableOkButton() | [
"def text_changed(self):\n self.default = False\n self.emit(SIGNAL('text_changed_at(QString,int)'),\n self.filename, self.editor.get_position('cursor'))",
"def on_text_edited(self, event):\n event.Skip()\n self.shell_obj._field_text_edited()",
"def on_edited_e( self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public method to retrieve the data entered into the dialog. tuple giving the classname (string) and the file name (string) | def getData(self):
return (
self.classnameEdit.text(),
os.path.join(self.pathnamePicker.text(),
self.filenameEdit.text())
) | [
"def __init__(self,parent, engname, onames, exts=['dat'], ext_descrips = ['data'],ext_multi=[True]):\n wx.Dialog.__init__(self,parent,-1,title='Export multiple objects to file',\n style=wx.DEFAULT_DIALOG_STYLE| wx.RESIZE_BORDER,\n size=(720,420))\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return flag, refer to times of repetition in poker group | def _get_same_number_flag(self):
flag = 0
for i in range(5):
for j in range(i+1, 5):
if self.poker_group[i].num == self.poker_group[j].num:
flag += 1
return flag | [
"def is_repetition(actions):\n if len(actions) < 9:\n return False\n for i in range(3, round(len(actions) / 3), 3):\n if actions[-3 * i:].count(actions[-i:]) >= 3:\n return True\n return False",
"def test_repetition(token):\n \n parsed = []\n i = 0\n tmp = ''\n con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the given source context can be a possible match, judging only by the files of both contexts. | def isFileSuitable(self, src_ctx):
return src_ctx.file in self.files or self.isLinkerOptimizationCandidate(src_ctx) | [
"def _check_files_match(left, right, base_dir):\n with open(os.path.join(base_dir, left), 'r') as left_file:\n with open(os.path.join(base_dir, right), 'r') as right_file:\n result = (left_file.read() == right_file.read())\n\n return result",
"def isValidContext(self, context: docking.Acti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the given source context can be a possible match for a linker optimized version of our binary function. | def isLinkerOptimizationCandidate(self, src_ctx):
raise NotImplementedError("Subclasses should implement this!") | [
"def isFileSuitable(self, src_ctx):\n return src_ctx.file in self.files or self.isLinkerOptimizationCandidate(src_ctx)",
"def test_is_source_need_build_return_true(self, mock_load, mock_isfile):\n mock_load.return_value = None, _CC_NAME_TO_MODULE_INFO\n mod_info = native_module_info.NativeMod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize all storage arrays based on of stars and targets | def initializeStorageArrays(self):
self.DRM = []
OS = self.OpticalSystem
SU = self.SimulatedUniverse
allModes = OS.observingModes
num_char_modes = len(
list(filter(lambda mode: "spec" in mode["inst"]["name"], allModes))
)
self.fullSpectra = np.zeros((... | [
"def initializeStorageArrays(self):\r\n\r\n self.DRM = []\r\n self.fullSpectra = np.zeros(self.SimulatedUniverse.nPlans, dtype=int)\r\n self.partialSpectra = np.zeros(self.SimulatedUniverse.nPlans, dtype=int)\r\n self.propagTimes = np.zeros(self.TargetList.nStars)*u.d\r\n self.las... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Choose next telescope target based on star completeness and integration time. | def choose_next_target(self, old_sInd, sInds, slewTimes, t_dets):
Comp = self.Completeness
TL = self.TargetList
TK = self.TimeKeeping
# reshape sInds
sInds = np.array(sInds, ndmin=1)
# 1/ Choose next telescope target
comps = Comp.completeness_update(
... | [
"def next_target(self, old_sInd, mode):\r\n OS = self.OpticalSystem\r\n ZL = self.ZodiacalLight\r\n Comp = self.Completeness\r\n TL = self.TargetList\r\n Obs = self.Observatory\r\n TK = self.TimeKeeping\r\n \r\n # create DRM\r\n DRM = {}\r\n \r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the area of the triangle whose two sides are ab and ac | def area_triangle_cross(ab, ac):
return .5 * np.sqrt(np.sum(np.cross(ab, ac)**2, axis=1)) | [
"def get_ab_area(self):\n\t\treturn la.norm(cross(self.a, self.b))",
"def get_ab_area(self):\n\t\treturn la.norm(cross(self.a, self.b))/2",
"def triangle_area(A, B, C):\n area = abs((A.x*(B.y-C.y) + B.x*(C.y-A.y) + C.x*(A.y-B.y)) / 2)\n return area",
"def get_ac_area(self):\n\t\treturn la.norm(cross(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split a path to a list. | def split(path, lst=None):
empty = ("/", "\\", "")
if lst is None:
lst = []
if path in empty:
return lst
new_path, base = os.path.split(path)
if base in empty:
return [new_path] + lst
lst.insert(0, base)
return ComparePaths.spli... | [
"def split(path):\n return os.sep.split(path)",
"def split_path(self, path):\n\n return path.split('/')",
"def _split_all(path):\n result = []\n a = path\n old_a = None\n while a != old_a:\n (old_a, (a, b)) = a, posixpath.split(a)\n\n if a or b:\n result.insert(0, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get size as a string with appropirate unit. | def get_size(self):
units = ("B", "KB", "MB", "GB", "TB")
for i, unit in enumerate(units):
high = 10**(i*3)
if self.size < high*1000:
return f"{round(self.size/high, 3)} {unit}" | [
"def get_display_size(size):\n return \"{} ({}) ({})\".format(\n size, bytes_to_human(size, binary=True),\n bytes_to_human(size, binary=False))",
"def size_unit(self) -> str:\n return pulumi.get(self, \"size_unit\")",
"def size_string(size):\n try:\n return 'x'.join(map... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the bio of this AccountItemUpdate. | def bio(self) -> str:
return self._bio | [
"def __str__(self):\n return self.bio",
"def item_description(self, item):\n return item.summary",
"def description(self):\n return self.data_hash['activity']['description']",
"def description(self):\n return self._book_dict[\"description\"]",
"def get_isni_bio(existing, author):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the bio of this AccountItemUpdate. | def bio(self, bio: str):
self._bio = bio | [
"def italic_bi(self, italic_bi):\n self._italic_bi = italic_bi",
"def load_or_update_bio( conn, journo_id, bio, default_approval=False ):\n\n assert( 'kind' in bio and bio['kind']!='' )\n c = conn.cursor()\n c.execute( \"SELECT * FROM journo_bio WHERE journo_id=%s AND kind=%s\", journo_id, bio['ki... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search method let the AP to search the nearby devices and get the mac address return to system.py | def search(self,num):
while True:
if num ==1:
device_address = None
time.sleep(3) # Sleep three seconds
nearby_devices = bluetooth.discover_devices()
for mac_address in nearby_devices:
device_address = mac_address
... | [
"def search(self,user_name, device_name):\n while True:\n device_address = None\n print(\"Searching for device..\")\n time.sleep(2) #Sleep 2 seconds \n nearby_devices = bluetooth.discover_devices()\n\n for mac_address in nearby_devices:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an example db handle for testing. Returns None if helper packages not present. | def example_handle():
# TODO: parameterize this
assert have_sqlalchemy
db_engine = sqlalchemy.engine.create_engine(
r"postgresql://johnmount@localhost/johnmount"
)
db_handle = PostgreSQLModel().db_handle(conn=db_engine, db_engine=db_engine)
db_handle.db_model.prepare_connection(db_handle... | [
"def getDb():\n return psycopg2.connect(\"dbname='snippets'\")",
"def create_testdata_db(self):\n\n try:\n dsn = CommandlineTool.get_input_option('yoda-db-testdata-dsn')\n force = CommandlineTool.get_input_option('force')\n if (not dsn):\n dsn = self._mh.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load emoji codes from the JSON file. This function tweaks some emojis to avoid Sphinx warnings when generating | def load_emoji_codes():
fname = resource_filename(__name__, 'codes.json')
with open(fname, encoding='utf-8') as fp:
codes = json.load(fp)
# Avoid unexpected warnings
warning_keys = []
for key, value in codes.items():
if value.startswith("*"):
warning_keys.append(key)
... | [
"def load_file(self, file):\n with open(file, \"r\", encoding=\"utf-8\") as fileobj:\n data = json.load(fileobj)\n\n index = dict()\n pattern = re.compile(r\"<(a?):([a-zA-Z0-9\\_]+):([0-9]+)>$\")\n\n for key, value in data.items():\n if not isinstance(key, str):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show all the pets. | def show_pets():
pets = Pet.query.all()
return render_template("pet-list.html", pets=pets) | [
"def list_pets():\n pets = Pet.query.all()\n return render_template('list.html', pets=pets)",
"def display_pets_list():\n\n pets = Pet.query.all()\n\n return render_template('pet_listing.html',\n pets=pets)",
"def show_pets(self):\r\n print(\"The owner of these pets ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add pet form; handle adding and display of form. | def show_and_handle_new_pet_form():
form = AddPetForm()
if form.validate_on_submit():
name = form.name.data
species = form.species.data
img = form.img.data or None
age = form.age.data
notes = form.notes.data
new_pet = Pet(name=name,
species... | [
"def display_add_pet_form():\n form = AddPetForm()\n\n if form.validate_on_submit():\n pet = Pet(\n name=form.name.data,\n species=form.species.data,\n photo_url=form.photo_url.data,\n age=form.age.data,\n notes=form.notes.data)\n db.session... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edit pet details form; handle editing or displaying a form | def edit_pet_details(pet_id):
pet = Pet.query.get_or_404(pet_id)
form = EditPetForm(obj=pet)
if form.validate_on_submit():
pet.img = form.img.data or None
pet.notes = form.notes.data
pet.available = form.available.data
db.session.commit()
flash(f"Successfully edi... | [
"def display_pet_details_and_edit_form(pet_id):\n pet = Pet.query.get_or_404(pet_id)\n form = EditPetForm(obj=pet)\n if form.validate_on_submit():\n print(\"*!*!*!*!*! IT WORKED !*!!\"*10)\n pet.photo_url=form.photo_url.data\n pet.notes=form.notes.data\n pet.available=form.avail... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return bool comparison if "node" is of "node type". | def is_node_of_type(node, node_type):
# type: (nt.DagNode, str) -> bool
return mc.nodeType(str(node)) == node_type | [
"def is_type(node_name, node_type):\n\n if not maya.cmds.objExists(node_name):\n return False\n if maya.cmds.objectType(node_name) != node_type:\n return False\n return True",
"def isPyNode(node):\r\n if re.search('pymel', str(node.__class__)):\r\n return 1\r\n else... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to toggle the visibility of the defined cameras "clipping planes" visibility. | def camera_manip_clipping_toggle(cameras, enable=True):
# type: (Iterable[nt.Camera], bool) -> None
# sets the visibility of the camera component manipulator for "clipping planes"
# ["cycling index", "center of interest", "pivot", "clipping planes", "unused"]
if enable:
manipulators_state = [Fal... | [
"def show_cam_clip_planes():\n for camera in cmds.ls(type=\"camera\"):\n cmds.setAttr(camera + \".nearClipPlane\", channelBox=True)\n cmds.setAttr(camera + \".farClipPlane\", channelBox=True)\n\n # select the perspCamera\n if cmds.objExists(\"persp\"):\n cmds.select(\"persp\")",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
From the sequence of nodes, return nodes that are of a "Camera Type". | def resolve_cameras(nodes):
# type: (Iterable[nt.DagNode]) -> Generator[nt.Camera]
for node in nodes:
if is_node_of_type(node, "transform"):
for cam in node.listRelatives(type="camera"):
yield cam
elif is_node_of_type(node, "camera"):
yield node | [
"def cameraNode(self):\n # update transform with current camera parameters - only default view for now\n viewNode = self.threeDView().mrmlViewNode()\n cameraNodes = slicer.util.getNodes('vtkMRMLCameraNode*')\n for cameraNode in cameraNodes.values():\n if cameraNode.GetActiveTag() == viewNode.GetID(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set defined cameras clip plane values. | def set_cameras_clip_plane(cameras, near, far):
# type: (Iterable[nt.Camera], float, float) -> None
for cam in cameras: # type: nt.Camera
cam.setNearClipPlane(near)
cam.setFarClipPlane(far) | [
"def set_default_clip_plane():\n values = [\n cmds.optionVar(query=\"defaultCameraNearClipValue\"),\n cmds.optionVar(query=\"defaultCameraFarClipValue\"),\n ]\n for camera in cmds.ls(type=\"camera\"):\n for attr in [\"nearClipPlane\", \"farClipPlane\"]:\n plug = \"{}.{}\".fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Destroy a child widget of the specified parent widget. | def destroy_child_widget(parent, child_name):
# type: (QWidget, str) -> None
for widget in parent.children(): # type: QWidget
if widget.objectName() == child_name:
log.info('Closing previous instance of "%s"' % child_name)
widget.close()
widget.deleteLater() | [
"def del_parent(self):\n self.parent = None",
"def child_removed(self, child):\n if isinstance(child, QtContainer):\n self.widget().setPageWidget(self.page_widget())",
"def child_removed(self, child):\n if isinstance(child, WxSplitItem):\n widget = child.widget()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator to inject the function docstring into it's returned object tooltip. Assumes that the returning object is of type QtWidgets.QWidget | def set_return_widget_tooltip_from_docstring(func):
@wraps(func)
def wrapper(*args, **kwargs):
widget = func(*args, **kwargs)
tooltip = func.func_doc # type: QtWidgets.QWidget
widget.setToolTip(tooltip)
return widget
return wrapper | [
"def build_tooltip(function):\n # Get the docstring for the \"function\" argument by using inspect\n docstring = inspect.getdoc(function)\n border = '#' * 28\n return '{}\\n{}\\n{}'.format(border, docstring, border)",
"def add_snippets(func):\n func.__doc__ = inspect.getdoc(func)\n if func.__doc__:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot boxes on an image | def plot_boxes(img=None, boxes=None, normalized=True, labels=None, linewidth=1.5, box_color='g', font_color='w', facecolor=None, fontsize=16, title=None):
#fig, ax = plt.subplots(1, figsize=(fig_size, fig_size))
fig, ax = plt.subplots(1)
if title:
ax.set_title(title, fontsize=20, color=fon... | [
"def plot(self,image=None,figsize=(20,20)):\n all_labels=list(self.all_boxes.keys())\n if not image:\n image=self.original_image.copy()\n\n for k in all_labels:\n box_k=self.all_boxes[k]\n h=self.height[k]\n w=self.width[k]\n\n for pt in bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return function to convert metric values. Tries return a ``int`` type, is not decimal numbers, else return a ``float`` type. The returned function receives a number, ``value``. If ``to_metric`` is defined, only returns the convert ``value``, else returns a tuple with converted ``value`` and ``value`` metric type, for e... | def format_metric_factory(metric=METER, to_metric=None, round_to=None):
get_number = METRIC_TYPES.get
number = get_number(metric)
if number is None:
raise ValueError('Invalid metric type: %s' % metric)
get_type = METRIC_NUMBERS.get
if to_metric:
to_number = get_number(to_metric)
... | [
"def convert_metric(self, metric):\n tpot_metrics = { # dict mapping metric_str to the str used by TPOT:\n 'accuracy': 'accuracy',\n 'f1': 'f1',\n 'log_loss': 'neg_log_loss',\n 'roc_auc': 'roc_auc',\n 'balanced_accuracy': 'balanced_accuracy',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert metric value to ``str`` string. | def metric_to_string(value, metric=METER, to_metric=None, round_to=None):
return metric_to_string_factory(metric, to_metric, round_to)(value) | [
"def metrics_to_str(metrics, prefix=\"\"):\n my_str = \", \".join([\"%s: %.3f\" % (k, v) for k, v in metrics.items()])\n if prefix:\n my_str = prefix + \" \" + my_str\n return my_str",
"def format_constant(self, value):\n return str(value)",
"def c_str(value):\n return str(value)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given data packed into a string, reverse bytes for a given word length and return the byteflipped string | def _flip(self,
dataStr,
numBytes):
out = ""
for i in xrange(len(dataStr)/numBytes):
l = list(dataStr[numBytes*i:numBytes*(i+1)])
l.reverse()
out += (''.join(l))
return out | [
"def swapbytes(data):\n return data[::-1]",
"def reverseByteOrder(self, data):\n # Courtesy Vishal Sapre\n byteCount = len(hex(data)[2:].replace('L','')[::2])\n val = 0\n for i in range(byteCount):\n val = (val << 8) | (data & 0xff)\n data >>= 8\n return val",
"def swapbytes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list, use the input port type to create a string representing the data | def _listToString(self,
listData):
portType = self._sink.port_type
if portType == _BULKIO__POA.dataChar:
string = ''.join(listData)
elif portType == _BULKIO__POA.dataOctet:
string = ''.join(listData)
elif portType == _BULKIO__POA.dataShort:... | [
"def _make_portlist(self, ports, sep=','):\n\n if self.target['ports']:\n self.ports = sep.join([p[0] for p in self.target['ports']])\n else:\n newports = sep.join([str(p) for p in ports])\n\n return newports",
"def _build_ports(ports):\n if ports:\n return \"(\" + \" and \".j... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open the data and/or server sockets based on the current properties | def _openSocket(self):
log.info("Connection Type: " + str(self.connection_type))
log.info("IP Address: " + self.ip_address)
log.info("Port: " + str(self.port))
if self.connection_type == "server":
self._dataSocket = None
self._serverSocket = socket.socket(socket.A... | [
"def open(self):\n self.socket.connect(self.addr)\n logger.info(\"%s socket connected to %s\", self.name, self.addr)",
"def open_connection(self):\n logging.debug(\"Creating socket connection to host: {0}, port: {1}\".format(\n self.hostname, self.port))\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The thread function for collecting data from the sink and pushing it to the socket | def _pushThread(self):
self.settingsAcquired = False
self.threadExited = False
while not self._exitThread:
if self._dataSocket == None:
if self.connection_type == "server":
if self._serverSocket == None:
self._openSocket()
... | [
"async def writer_worker(self):\n try:\n while True:\n data = await self.inbound_queue.get()\n print('SOCKET > ', data)\n self.writer.write(data.encode())\n await self.writer.drain()\n finally:\n self.writer = None",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push data to the current data socket, handling short writes as necessary | def _pushToSocket(self,
data):
if self._dataSocket != None:
dataSent = 0
dataToSend = len(data)
while dataSent != dataToSend:
dataSentTemp = self._dataSocket.send(data[dataSent:])
if dataSentTemp == -1:
... | [
"def write_and_send(self, data):\r\n self.__my_socket.send_(data)\r\n self.recev()",
"def push(self, data):\r\n\r\n self.outbuffer += data",
"def send_data(self, proto_id, data):\n for p in self.socks5_factory.client.server_dict.keys():\n bytes_sent = 0\n while ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subscribe to updates for a specific symbol and field. The callback will be called as 'await callback(symbol, field, value, timestamp)' whenever an update is received. | async def subscribe(self, symbol, field, callback):
async with self.__lock:
# Connect the websocket if necessary
if self.__websocket is None:
await self.__connect()
# Send the subscribe message if we're not already subscribed
if symbol not in self... | [
"def _listen_callback(_, key, value, __):\n print(\"{!r} updated: {!r}\".format(key, value))",
"async def slots_updates_subscribe(self) -> None:\n req = SlotsUpdatesSubscribe()\n await self.send_data(req)",
"def on_update(self, callback):\n self._update_callback.add(callback)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |