query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Reads radio URLS and names from text file | def readRadioList():
global names, preset_list
names=[]
listFile = open('/home/pi/WoodStream/radio_list.txt', 'r')
line = listFile.readlines()
for r in range(len(line)):
names.append(line[r].replace('\n','').split('|'))
if names[r][0][1] == "." and names[r][0][0].isdigit():... | [
"def read():\n videos=[]\n f=open('links.txt','r')\n for line in f:\n line = line.strip().split(\"~|\")\n videos.append(line)\n return videos #2D array [[title,channel_name,link]]",
"def read_urls(file):\r\n with open(file, \"r+\") as url_file:\r\n url_list = url_file.readline... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for a WPSenabled wireless lan and connects to it | def wpsConnect():
SSID = "none"
# scan networks on interface wlan0, to see some nice networks
subprocess.check_output(["wpa_cli", "-i", "wlan0", "scan"])
sleep(1);
#get and decode results
wpa = subprocess.check_output(["wpa_cli", "-i", "wlan0", "scan_results"]).decode("UTF-8")
... | [
"def connectToLAN(self):\n\t\tprint(\"Connect to LAN\")\n\t\t#stationary mode for connecting ESP8266 module to the router\n\t\tsta_if = network.WLAN(network.STA_IF)\n\t\tprint(\"Check connection....\")\n\t\tif not sta_if.isconnected():\n\t\t\t#connect to the router when no connected after startup\n\t\t\tprint(\"Con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws radio list with a sliding window of 6 rows | def radioList(dev, draw, index):
global menuindex
global listMenuStart, listMenuEnd
global names
font = ImageFont.load_default()
draw.rectangle(dev.bounding_box, outline="white", fill="black")
if index > listMenuEnd:
listMenuEnd += 1
listMenuStart += 1
elif index < listM... | [
"def radio_filler( group_caption, labels, buttons_per_row = None, tool_tips = None):\n \n group_box = QGroupBox(group_caption)\n grid = QGridLayout()\n bname = re.split(\"[\\'\\/ ,.]+\", group_caption)\n bname = ' '.join(bname).title().replace(' ', '')\n bname = 'bgrp' + bname\n button_group... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows current song info (over multiple lines if needed) | def songInfo():
global songFile, currentRadio
lines = songFile.readlines()
if len(lines) > 0:
songFile.seek(0)
title = formatSong(lines[0]).strip()
with canvas(device) as draw:
invert(draw, 0, 0, names[currentRadio][0], True)
if len(title)<... | [
"def show_track(self):\n s = self.mpc.currentsong()\n if s != {}:\n place_text(s['artist'], 0)\n place_text(s['title'], 1)\n else:\n place_text(' '*16, 0)\n place_text(' -= END =- ', 1)",
"def printinfo(song):\n print(\"%9s %s %-5s %-30s %-30... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Radio list rotary encoder reading Function is duplicated from the volume one because code and store variables must be kept separated for each rotary | def list_rotary():
global listPrevNextCode
global listStore
global rot_enc_table
global list_dt, list_clk
listPrevNextCode <<= 2;
if (GPIO.input(list_dt)):
listPrevNextCode |= 0x02
if (GPIO.input(list_clk)):
listPrevNextCode |= 0x01
listPrevNextCode &= 0x0f
# I... | [
"def __init__(self):\n\t\tself.keys = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\",\n\t\t\t\t\t \"q\", \"w\", \"e\", \"r\", \"t\", \"y\", \"u\"]\n\t\tself.notes = [\"c4\", \"d4\", \"e4\", \"f4\", \"g4\", \"a4\", \"b4\", \"c5\",\n\t\t\t\t\t \"d5\", \"e5\", \"f5\", \"g5\", \"a5\", \"b5\", \"c6\"]\n\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Radio button switch interrupt callback Select preset | def preset_callback(channel):
global currentRadio
global preset_sw, preset_list
for i in range(6):
preset_sw[i][1] = GPIO.input(preset_sw[i][0])
sleep(2)
for i in range(6):
if (preset_sw[i][1]) == 0:
if preset_list[i] != currentRadio:
curren... | [
"def set_radio(self): \n\t\tself._radio = True",
"def _gc_setAllRadioButtonsState(self, switchCtrlWord):\n if switchCtrlWord == 'OFF':\n self.radioButton.setChecked(True) # default is off\n self.radioButton_2.setChecked(False)\n self.radioButton_3.setChecked(True) # defau... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Song information thread. It is the prevalent one. | def showSong():
while True:
if not settingsMode:
sem.acquire()
songInfo()
sem.release()
sleep(10) | [
"def play(self, song):\n pass",
"def nowplaying(self,song):\n\n submission = \"s=\"+self.md5hash\n submission += \"&a=\"+urllib.quote(song['artist'].encode(\"utf-8\"))\n submission += \"&t=\"+urllib.quote(song['name'].encode(\"utf-8\"))\n if song['album'] != \"\":\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expects a string of order information, where each coffee order type is separated by commas, and each order information element is separated by semicolons. Returns a list with a nested list for each coffee order type, with separated information elements in each list. Validation of a proper string is not done here, but b... | def parse_order_info(self):
list_parse = self.info.strip().split(',')
orders_list = []
for single_order in list_parse:
single_order_array = single_order.split(';')
orders_list.append(single_order_array)
single_order_list = []
return orders_list | [
"def make_list_from_str(self, s, type=None):\n ret = []\n for item in s.split():\n if not item:\n continue\n if type is not None:\n try:\n item = item.strip('[](),')\n item = type(item)\n except Va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepare should skip datasets older than the given date | def test_skips_old_datasets(l1_ls7_tarball):
expected_metadata_path = (
l1_ls7_tarball.parent
/ "LE07_L1TP_104078_20130429_20161124_01_T1.odc-metadata.yaml"
)
run_prepare_cli(
landsat_l1_prepare.main,
# Can't be newer than right now.
"--newer-than",
datetime.... | [
"def check_dataset_dates(self):\n # TODO: graph traverse and date checking\n pass",
"def test_load_data_filter_date(self):\n test_instance = LoadDataFromPostSQl('BTCUSD', \"2021-08-01\")\n test_instance.load_data()\n loaded_data = test_instance.get_response()\n started_da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the country code of the user company. If not exists, return XX. | def _get_country_code(self, cr, uid, context=None):
context = context or {}
user_company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
return user_company.partner_id and user_company.partner_id.country_id \
and user_company.partner_id.country_id.co... | [
"def country_code(self) -> str:\n return pulumi.get(self, \"country_code\")",
"def get_country_code(self):\n name=self.country_name.upper()\n # The following is necessary for compatibility with sql syntax\n name=\"'\"+re.sub(\"'\",\"''\",name)+\"'\"\n cursor=self.conn.cursor()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if the partner is a company of Venezuela and if the address is for billing. | def _check_partner_invoice_addr(self,cr,uid,ids,context={}):
partner_obj = self.browse(cr,uid,ids[0])
if partner_obj.vat and partner_obj.vat[:2].upper() == 'VE' and not partner_obj.parent_id:
res = partner_obj.type == 'invoice'
if res:
return True
... | [
"def test_13_company_1_address(self):\n with mock_api(company_1_address):\n import_record(self.session, 'magento.res.partner',\n self.backend_id, '9999256')\n cr, uid = self.cr, self.uid\n partner_ids = self.model.search(cr, uid,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the vat is unique in the level where the partner in the tree | def _check_vat_uniqueness(self, cr, uid, ids, context=None):
if context is None: context = {}
user_company = self.pool.get('res.users').browse(cr, uid, uid).company_id
acc_part_brw = self._find_accounting_partner(user_company.partner_id)
#User must be of VE
... | [
"def no_vat_duplicates(self):\n if not self.vat:\n return\n\n partner_obj = self.env['res.partner']\n partners = partner_obj.search([\n ('vat', '=', self.vat),\n ('company_id', '=', self.company_id.id),\n ])\n\n partners -= partners.mapped('child_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method will check the vat mandatoriness in partners for those user logged on with a Venezuelan Company | def _check_vat_mandatory(self, cr, uid, ids, context=None):
if context is None: context = {}
# Avoiding Egg-Chicken Syndrome
# TODO: Refine this approach this is big exception
# One that can be handle by end user, I hope so!!!
if context.get('create_company',False):
r... | [
"def _check_vat_uniqueness(self, cr, uid, ids, context=None):\n if context is None: context = {}\n \n user_company = self.pool.get('res.users').browse(cr, uid, uid).company_id\n acc_part_brw = self._find_accounting_partner(user_company.partner_id)\n \n #User must be of VE ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check Venezuelan VAT number, locally called RIF. | def check_vat_ve(self, vat, context = None):
if context is None:
context={}
if re.search(r'^[VJEGP][0-9]{9}$', vat):
return True
if re.search(r'^([VE][0-9]{1,8}|[D][0-9]{9})$', vat):
return True
return False | [
"def vies_vat_check(self, cr, uid, country_code, vat_number, context=None):\n if country_code.upper() != \"VE\":\n return super(res_partner, self).vies_vat_check(cr, uid, country_code, vat_number,context=context)\n else:\n return super(res_partner, self).simple_vat_check(cr, uid,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate against VAT Information Exchange System (VIES) | def vies_vat_check(self, cr, uid, country_code, vat_number, context=None):
if country_code.upper() != "VE":
return super(res_partner, self).vies_vat_check(cr, uid, country_code, vat_number,context=context)
else:
return super(res_partner, self).simple_vat_check(cr, uid, country_co... | [
"def check_vat_ve(self, vat, context = None):\n\n if context is None:\n context={}\n if re.search(r'^[VJEGP][0-9]{9}$', vat):\n return True\n if re.search(r'^([VE][0-9]{1,8}|[D][0-9]{9})$', vat):\n return True\n return False",
"def test_non_compliant_vi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. | def _get_rotation_matrix(axis, theta):
#import math
axis = np.asarray(axis)
theta = np.asarray(theta)
axis = axis/np.sqrt(np.dot(axis, axis))
a = np.cos(theta/2)
b, c, d = -axis*np.sin(theta/2)
aa, bb, cc, dd = a*a, b*b, c*c, d*d
bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d
... | [
"def _get_rotation_matrix(self, axis, theta):\n\n #import math\n axis = np.asarray(axis)\n theta = np.asarray(theta)\n axis = axis/np.sqrt(np.dot(axis, axis))\n a = np.cos(theta/2)\n b, c, d = -axis*np.sin(theta/2)\n aa, bb, cc, dd = a*a, b*b, c*c, d*d\n bc, a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expands list to a given length by repeating the last element. | def expand_list(
l: List, length: int, with_value: Any = None, with_none: bool = False
) -> List:
if with_none:
l.extend([None] * (length - len(l)))
elif with_value is not None:
l.extend([with_value] * (length - len(l)))
else:
l.extend([l... | [
"def repeat_to_length(string_to_expand, length):\n return (string_to_expand * ((length / len(string_to_expand)) + 1))[:length]",
"def shorten_list(l, max_length=15):\n length = len(l)\n if length > max_length:\n sl = l[0:max_length]\n sl.append(\"...%i total\" % length)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a object which can be used as legend_labels and a list of the values as integers (after mapping strings to integers). | def create_categories(values: List[str]) -> Tuple[List[Tuple[int, str]], List[int]]:
string_map = {}
for i, value in enumerate(sorted(set(values))):
string_map[value] = i
legend_labels = []
for key, value in string_map.items():
legend_labels.append((value,... | [
"def create_label_dict(self, labels):\n labels = set(labels)\n for index, label in enumerate(labels):\n self.label_id_dict[label] = index",
"def labels_to_int(labels):\n\n current_name = \"\"\n current_int = 0\n int_labels = []\n int_label_dict = {}\n int_label_dict_reverse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Script to convert Duplex Sequencing .mutpos file formats into valid VCF files. Currently VCF format v4.2 is outputted. A .mutpos file is | def convert_mutpos_to_vcf(
mutpos_file: str,
sample: str,
vcf_file: str,
ref_file: str,
dict_file: str,
min_depth: int,
verbose: bool,
) -> None:
header = 'CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{sample}\n'
reference = pyfaidx.Fasta(ref_file)
# .mutpos file does n... | [
"def write_VCF_translation(prot_dict, vcf_file_name, ref_file_name, compress=False):\n\n #for the header\n seqNames = prot_dict[prot_dict.keys()[0]]['sequences'].keys()\n\n #prepare the header of the VCF & write out\n header=[\"#CHROM\",\"POS\",\"ID\",\"REF\",\"ALT\",\"QUAL\",\"FILTER\",\"INFO\",\"FORMA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Divide the group in subgroups using the characteristic | def get_subgroups(group, characteristic):
# Get the dataframe and group by the characteristic
dataframe = group['dataframe']
groupby = dataframe.groupby(by=characteristic)
# Create the new subgroups
subgroups = []
hca = OntologyConversorHCA()
scea = OntologyConversorSCAE()
for value, su... | [
"def divisor_subgroups(self):\n return [Gamma0_constructor(M) for M in self.level().divisors()]",
"def group(df, dvmin, dvmax, step):\n\tr = step/2\n\tres = []\n\n\tfor ticker in range(dvmin, dvmax, step):\n\t\t#select values by left-right difference in sum in range (x-r, x+r). x is the middle value of a ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new row with the combinations of the characteristics. | def create_row(project_ID, subgroups, characteristics_used, metadata_cells, number_genes):
cells = 0
for subgroup in subgroups:
cells += len(subgroup['dataframe'])
n_subgroups = len(subgroups)
combination_name = combiation_to_name(characteristics_used)
row = {
'project_ID':... | [
"def generate_table(self, rows):\n ...",
"def _build_rows_struct(self):\n struct = []\n # Step 1 - See docstring for details\n for row in itertools.izip_longest(*self.columns, fillvalue=(\"\",)):\n # Step 2\n row_list = [dict(itertools.izip((\"v\",\"f\",\"p\"), it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a list of FileParse objects for the files listed in the listfile | def mk_parses(listfile, corenlp_host):
# if not listfile.endswith('.listfile'):
# filetype = 'Co-Reference List file'
# error = 'has incorrect file type'
# raise FilenameException("Error: %s %s" % (filetype, error))
try:
with open(listfile) as f:
pserver ... | [
"def populate_file_list(self):\n\n\t\ttry:\n\t\t\tself.logger.debug('\\t\\tReading {0}'.format(fw.resource_path(__file__,self.fpath)))\n\t\t\tfor f in os.listdir(self.fpath):\n\t\t\t\tself.file_list.append([f,fw.resource_path(__file__,'{0}/{1}'.format(self.fpath,f))])\n\t\texcept:\n\t\t\traise",
"def extend_file_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tags given parse tree with coreferences | def tag_ptree(ptree, coreflist):
pattern = r"""(?P<lp>\(?\s*) # left parenthesis
(?P<tg>[a-zA-Z$]+)? # POS tag
(?P<data>\s*%s) # subtree of tag
(?P<rp>(?:\s*\))*) # right parenthesis
"""
for cid, coref in coreflist[::-1]:
... | [
"def extract_entities_from_dependency_parse(dtrees, postag):\n sents = []\n for x in range(0,len(dtrees)):\n tok_list = []\n for node_index in dtrees[x].nodes:\n if node_index != 0:\n node = dtrees[x].nodes[node_index]\n if node['ctag'] == postag:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses xml to find all tagged coreferences contained in COREF tags | def get_tagged_corefs(xml, ordered=False):
nps = {}
if ordered:
nps = []
xml = _normalize_malformed_xml(xml)
try:
corefs = parseString(xml).getElementsByTagName('COREF')
except ExpatError:
return nps
for coref in corefs:
try:
cid = coref.attributes[... | [
"def parse_corenlp_coref_xml_doc(input_dir = 'CoreNLP_coref_anno/dev'):\n\n\tmentions = []\n\tfor file in os.listdir(input_dir):\n\t\ttree = ET.parse(input_dir + '/' + file)\n\t\tdocument = tree.getroot()[0]\n\t\t# sentences_node = document.find('sentences')\n\n\t\t# for sentence in enumerate(sentences_node):\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tags parse tree with corefs and returns the tree, lexicon, dependencies and raw text as tuple | def _process_parse(parse, coreflist):
sentence = parse.get('sentences')
if sentence:
ptree = Tree.parse(tag_ptree(sentence[0]['parsetree'], coreflist))
words = [(w[0], w[1]) for w in sentence[0]['words']]
depends = [(d[0], d[1], d[2]) for d in sentence[0]['dependencies']]
text = ... | [
"def tag_ptree(ptree, coreflist):\n pattern = r\"\"\"(?P<lp>\\(?\\s*) # left parenthesis\n (?P<tg>[a-zA-Z$]+)? # POS tag\n (?P<data>\\s*%s) # subtree of tag\n (?P<rp>(?:\\s*\\))*) # right parenthesis\n \"\"\"\n for cid, coref in co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns sets of cognitive synonyms for each of the input words | def get_synsets(words):
synsets = {}
for word in words:
for syn in wn.synsets(word):
synsets[syn.name] = tuple([lemma.name for lemma in syn.lemmas])
return synsets | [
"def get_synonyms(self, words):\n\n\t\t\t\treturn tuple([self.get_all(word) for word in words])",
"def getSynonyms(self, wordSet):\n synonyms = {}\n for w in wordSet:\n # find synonyms\n synsets = wn.synsets(w, pos=wn.NOUN)\n if len(synsets) > 0: \n # there are noun senses for this word, g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a unique coreference id tag | def _mk_coref_id():
num, alpha = int(_mk_coref_id.id[:-1]), _mk_coref_id.id[-1]
if alpha == 'Z':
alpha = 'A'
num += 1
else:
alpha = chr(ord(alpha) + 1)
_mk_coref_id.id = '%s%s' % (num, alpha)
return _mk_coref_id.id | [
"def _createIdTag(self, value, tag_name=None):\n\t\tif value is None or value == '' or value == ' ':\n\t\t\tself._returnToUser(reason='empty_field')\n\t\t\tsys.exit()\n\t\tif tag_name is not self.REQUIRED_COLUMNS['id']:\n\t\t\ttag_name = self.REQUIRED_COLUMNS['id']\n\t\ttag = etree.Element(tag_name)\n\t\ttag.text =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test for get_file_map length | def test_get_file_map_len():
file_map = sd.get_file_map("resources/")
files = glob.glob("resources/" + "/**" + ".txt", recursive=True)
assert len(file_map) == len(files) | [
"def n_maps(self) -> int:\n with fits.open(self.path, memmap=self.memmap) as file:\n for f in file:\n if type(f) is BinTableHDU:\n return f.header['TFIELDS']\n raise TypeError(f\"Is {self.path} really contains CMB maps?\")",
"def _determine_len(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test for get_file_map filetypes | def test_get_file_map_type():
for file in sd.get_file_map("resources/"):
assert file.endswith(".txt") | [
"def test_get_content_types(filetype, expected):\n filename = os.path.join(CURRENT_FOLDER, f\"testdata.{filetype}\")\n assert get_content_types(filename) == expected",
"def test_get_file_type(self):\n file_list = {'events': 'monol_testA_nustar_fpma_ev',\n 'lc': 'monol_testA_E3-50_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test for texts ignorechars | def test_get_texts_ignores():
file_map = sd.get_file_map(".")
texts = sd.get_texts(file_map)
ingnores = "[:.,;:!?\"-()]\n".split()
for text in texts:
for char in ingnores:
assert text.find(char) == -1 | [
"def ISNONTEXT(value):\n return not ISTEXT(value)",
"def extract_non_ascii_words(text):\r\n return [word for word in text.split() if not word.isascii()]",
"def extract_non_ascii_words(text):\n return [w for w in text.split() if not all(ord(c) < 128 for c in w)]",
"def _isyelling(text):\n\n lette... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test get_stopwords if there are any loaded | def test_get_stopwords():
stopwords = sd.get_stopwords("resources/stopwords.de.json")
assert len(stopwords) > 0 | [
"def test_stopwords():\n assert TextNormalizer().transform([[\"a b\"]])[\"corpus\"][0] == [\"b\"]",
"def test_rm_stop_words(self):\n wanted = [u\"allions\", u\"plage\"]\n\n get = self.ctu.rm_stop_words(self.words)\n self.assertEquals(get, wanted) # 1",
"def setStopwords(self, stopwords):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert() == and != | def equality():
Assert(1) == 1
Assert(1) != 0
with Assert.raises(AssertionError):
Assert(1) == 0
with Assert.raises(AssertionError):
Assert(1) != 1 | [
"def equality():\r\n\r\n Assert(1) == 1\r\n Assert(1) != 0\r\n\r\n with Assert.raises(AssertionError):\r\n Assert(1) == 0\r\n\r\n with Assert.raises(AssertionError):\r\n Assert(1) != 1",
"def test_a_better_way_of_asserting_equality(self):\n expected_value = __\n actual_valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert() in boolean context | def boolean():
bool(Assert(1))
with Assert.raises(AssertionError):
bool(Assert(0)) | [
"def boolean():\r\n\r\n bool(Assert(1))\r\n\r\n with Assert.raises(AssertionError):\r\n bool(Assert(0))",
"def test_assert_verdad(self):\n\n self.assertTrue(_____) # Esto debe ser igual a True",
"def assertIsTrue(self, result):\n\t\treturn self.assertEqual(result, True)",
"def test_true_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check status of game (turn, tie, win) | def check_game_status(self):
for player in ("1", "2"):
row_win = np.apply_along_axis(
lambda x: set(x) == {player}, 1, self.board
).any()
col_win = np.apply_along_axis(
lambda x: set(x) == {player}, 0, self.board
).any()
... | [
"def check_if_game_over():\n check_if_win()\n check_if_tie()",
"def check_game_over(self):\n red, blue = self.board.count_piece()\n if blue == 0:\n self.ui.show_result(\"RED WIN!\")\n self.turn = RED\n elif red == 0:\n self.ui.show_result(\"BLUE WIN!\")\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate full game tree from initial state | def gen_game_tree(state_init):
current_path = [state_init]
game_tree = {}
while current_path:
cur_state = current_path[-1]
if cur_state not in game_tree:
ttt = TicTacToe(cur_state)
game_tree[cur_state] = {
"unexplored": ttt.next_states,
... | [
"def expand_tree(self, state: GameState) -> None:\r\n return None",
"def build_tree(root, n_sim=1000):\n for i in range(n_sim):\n # selection\n leaf = selection(root)\n\n # expand\n # check if leaf node is terminal state\n # if not true, expand it\n if leaf.game... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build game tree and export given initial state | def learn(state="_________"):
game_tree = gen_game_tree(state)
with open(GAME_TREE_FILE, "w") as gt_file:
json.dump(game_tree, gt_file, indent=4) | [
"def gen_game_tree(state_init):\n current_path = [state_init]\n game_tree = {}\n while current_path:\n cur_state = current_path[-1]\n if cur_state not in game_tree:\n ttt = TicTacToe(cur_state)\n game_tree[cur_state] = {\n \"unexplored\": ttt.next_states,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints junctions and their read counts to a specified file This is a striped down version of Beryl Cummings' printSplices() | def printSplices(path, spliceDict):
for key in spliceDict:
chrom, junctionStart, junctionEnd = key
timesSeenInSample = str(spliceDict[key])
with open(path, "a") as out:
out.write("\t".join([str(chrom),str(junctionStart),str(junctionEnd),timesSeenInSample])+"\n") | [
"def display_enumerated_lines(filename):",
"def PrintWiggle(reads,name):\n\tglobal chrlist,chrlen,region\n\t\n\tprint 'Printing the %s wiggle file' % name\n\tf = open('%s.%s-%s.%s-11.wig' % (name,args.o,args.reg,args.g),'w')\n\tf.write('track type=bedGraph name=\"%s-%s_%s-11\" description=\"%s-%s_%s-11\" visibili... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a CIGAR string and returns values which can used to determine an intron's 3' and 5' splice sites | def parseCIGARForIntrons(cigar):
if 'N' in cigar:
cigar = cigar.split('N')[0] + 'N' #remove all information after intron
else:
raise Exception('No intron detected')
offset = 0
matchedExon = 0
intronLength = 0
for c in list(Cigar(cigar).items()): # returns list of tuples : [(20, 'N')]
if c[1] == 'N':
... | [
"def fromString(cls, string):\n # From SAM specification v1.5, slightly adapted for single-token parsing\n pattern = r\"^[0-9]+[MIDNSHPX=]\" \n string = string.strip()\n if string == '*':\n return CIGAR.fromList(['*'])\n parsed = []\n s = string\n # Parse ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a microvm builder. | def vm_builder_fxt(bin_cloner_path):
return MicrovmBuilder(bin_cloner_path) | [
"def __class__(self):\n return _Builder",
"def _get_model_builder(use_t2t_decoder=True):\n config_json = {\n \"hidden_size\": 4,\n \"intermediate_size\": 8,\n \"max_position_embeddings\": 8,\n \"num_attention_heads\": 1,\n \"num_hidden_layers\": 1,\n \"vocab_size\": 8,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CPU template fixture for instruction set feature parity templates | def inst_set_cpu_template_fxt(request):
return request.param | [
"def inst_set_cpu_template_ext_fxt(request):\n return request.param",
"def test_create_with_1_5_cpu_template(uvm_plain):\n\n # We remove KVM_CAP_IOEVENTFD from kvm checks just for testing purpose.\n custom_cpu_template = json.loads('{\"kvm_capabilities\": [\"!36\"]}')\n\n test_microvm = uvm_plain\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CPU template fixture for instruction set feature parity templates plus T2 | def inst_set_cpu_template_ext_fxt(request):
return request.param | [
"def inst_set_cpu_template_fxt(request):\n return request.param",
"def test_create_with_1_5_cpu_template(uvm_plain):\n\n # We remove KVM_CAP_IOEVENTFD from kvm checks just for testing purpose.\n custom_cpu_template = json.loads('{\"kvm_capabilities\": [\"!36\"]}')\n\n test_microvm = uvm_plain\n tes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that CPUID feature flag are set and unset as expected. | def check_cpuid_feat_flags(
vm_builder, cpu_template, microvm, kernel, disk, must_be_set, must_be_unset
):
vm = create_vm(vm_builder, cpu_template, microvm, kernel, disk)
vm.start()
cpuid = cpuid_utils.get_guest_cpuid(vm)
allowed_regs = ["eax", "ebx", "ecx", "edx"]
for leaf, subleaf, reg, flag... | [
"def test_checkFlags(self):\n self.failUnlessEqual(self.nice.opts['aflag'], 1)\n self.failUnlessEqual(self.nice.opts['flout'], 0)",
"def test_feat_parity_cpuid_mpx(vm_builder, cpu_template, microvm, guest_kernel, disk):\n # fmt: off\n must_be_set = []\n must_be_unset = [\n (0x7, 0x0,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that MPX (Memory Protection Extensions) is not enabled in any of the supported CPU templates. | def test_feat_parity_cpuid_mpx(vm_builder, cpu_template, microvm, guest_kernel, disk):
# fmt: off
must_be_set = []
must_be_unset = [
(0x7, 0x0, "ebx",
(1 << 14) # MPX
),
]
# fmt: on
check_cpuid_feat_flags(
vm_builder,
cpu_template,
microvm,
... | [
"def check_xpu(use_xpu):\n err = \"Config use_xpu cannot be set as true while you are \" \\\n \"using paddlepaddle cpu/gpu/npu version ! \\nPlease try: \\n\" \\\n \"\\t1. Install paddlepaddle-xpu to run model on XPU \\n\" \\\n \"\\t2. Set use_xpu as false in config file to run \" \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that securityrelated CPUID feature flags are properly set for T2CL and T2A CPU templates. | def test_feat_parity_cpuid_sec(
vm_builder, inst_set_cpu_template, microvm, guest_kernel, disk
):
# fmt: off
must_be_set_common = [
(0x7, 0x0, "edx",
(1 << 26) | # IBRS/IBPB
(1 << 27) | # STIBP
(1 << 31) # SSBD
)
# Security feature bits in 0x80000... | [
"def check_cpuid_feat_flags(\n vm_builder, cpu_template, microvm, kernel, disk, must_be_set, must_be_unset\n):\n vm = create_vm(vm_builder, cpu_template, microvm, kernel, disk)\n vm.start()\n\n cpuid = cpuid_utils.get_guest_cpuid(vm)\n allowed_regs = [\"eax\", \"ebx\", \"ecx\", \"edx\"]\n\n for le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify availability and value of the IA32_ARCH_CAPABILITIES MSR for T2CL and T2A CPU templates. | def test_feat_parity_msr_arch_cap(
vm_builder, inst_set_cpu_template, microvm, guest_kernel, disk
):
vm = create_vm(vm_builder, inst_set_cpu_template, microvm, guest_kernel, disk)
vm.start()
ssh_conn = net_tools.SSHConnection(vm.ssh_config)
arch_capabilities_addr = "0x10a"
rdmsr_cmd = f"rdmsr {... | [
"def _CheckMsrKernelModule():\n proc = subprocess.Popen('/sbin/lsmod', stdout=subprocess.PIPE)\n stdout = proc.communicate()[0]\n ret = proc.wait()\n if ret != 0:\n raise OSError('lsmod failed')\n\n if not any([line.startswith('msr ') for line in stdout.splitlines()]):\n print('Error: MSR module not load... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that getting the household information fails. | def test_get_household_not_successful(self):
res = self.client.get(HOUSEHOLD_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | [
"def test_getHousehold_invalidId(self):\n self.assertTrue(self.z.getHousehold(None) is None, \"An invalid value passed to getHousehold returns None.\")\n self.assertTrue(self.z.getHousehold('') is None, \"An invalid value passed to getHousehold returns None.\")\n self.assertTrue(self.z.getHouse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that creating a new household fails. | def test_create_household_not_successful(self):
payload = {
'name': 'Test Household 1'
}
res = self.client.post(HOUSEHOLD_URL, payload)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | [
"def test_validate_household_member_create_invalid(self):\n household_structure = HouseholdStructureFactory(survey=SurveyFactory(), household=self.household)\n RepresentativeEligibilityFactory(household_structure=household_structure)\n hhm = HouseholdMemberFactory(household_structure=household_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that getting the household information succeeds. | def test_get_household_successful(self):
res = self.client.get(HOUSEHOLD_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(self.user.household.id, res.data[0]['id']) | [
"def test_get_household_not_successful(self):\n res = self.client.get(HOUSEHOLD_URL)\n\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)",
"def test_createHousehold_single(self):\n h = self.z.createHousehold(\"testHousehold\")\n self.assertTrue(self.z.getHousehold(\"tes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that creating a new household is successful. | def test_create_new_household(self):
user = get_user_model().objects.create_user(
email='test1@test.com',
password='TestPass1',
name='Test User 1',
)
self.client.force_authenticate(user)
payload = {
'name': 'Test Household 1'
}
... | [
"def test_create_household(self):\n\n testhouse = create_household()\n self.assertEqual(type(testhouse), Household)",
"def test_create_household_not_successful(self):\n payload = {\n 'name': 'Test Household 1'\n }\n res = self.client.post(HOUSEHOLD_URL, payload)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests partial household update (PATCH). | def test_patch_household(self):
payload = {
'name': 'Test Household Changed'
}
res = self.client.patch(get_household_detail_url(
self.user.household.id), payload)
self.assertEqual(res.status_code, status.HTTP_200_OK) | [
"def test_partial_update_bill(self):\n pass",
"def test_partial_update(self):\n\n action = ActionFactory.create(id=22)\n data = {\n 'name': 'Ação para Melhorar',\n 'institution': 'Vamos Ajudar',\n }\n self.assertNotEqual(action.name, data['name'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect tweets from account in `acc` and save them in the file `path` | def scrape_from_user(acc, num, path='data/tweet_ids.txt'):
print('Collecting tweets from {}'.format(acc[num]))
tweets = []
new_tweets = []
new_tweets = _api.user_timeline(screen_name=acc[num], count=200)
tweets.extend(new_tweets)
oldest = tweets[-1].id - 1
while len(new_tweets) > 0:
... | [
"def archive_tweets(user_account_name, keys_path):\n import time\n import datetime\n st = datetime.datetime.fromtimestamp(time.time()).strftime('%m-%d-%Y___%H-%M-%S')\n save_path = \"archived_tweets/{}___{}.pkl\".format(user_account_name, st)\n tweets = download_recent_tweets_by_user(user_account_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the graph's output node. | def get_output_node(self) -> WillumpGraphNode:
return self.output_node | [
"def output_node(self, port: int):\n return self._output_nodes_map[port]",
"def output(self, name: str) -> bpy.types.NodeSocket:\n\t\treturn self.outputs[name]",
"def get_output(id):\n global G\n node = G.node[id]\n keys = node.keys()\n node_type = node[\"node_type\"]\n log('get output for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find closest point from a list of points. | def closest_point(point, points):
return points[cdist([point], points).argmin()] | [
"def closest(point, points):\n pts = [(Point.distance(point, p), p) for p in points]\n pts.sort()\n return pts[0][1]",
"def closest( point, points):\n da = dist_array(point, points)\n return numpy.argmin(da)",
"def _find_closest_point(target, points):\n result = None\n min_dista... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot forgetting curve, ie, memory capacity (MC) vs lag. | def plot_forgetting_curve(
lags: Union[List, np.ndarray],
forgetting_curve: np.ndarray,
ax: plt.Axes = None,
**kwargs,
) -> None:
if ax is None:
fig, ax = plt.subplots()
ax.plot(lags, forgetting_curve, **kwargs)
ax.set_xlabel("$k$")
ax.set_ylabel(r"$MC_k$") | [
"def plotLoss():\n # ssr\n ssr = np.log(gradientDescent(X, y)[1])\n # number of iterations \n iterations = np.log(np.arange(1, len(ssr) + 1, 1))\n # plot reduction of ssr\n plt.plot(iterations, ssr)\n # xlabel\n plt.xlabel(\"Iteration\")\n # ylabel\n plt.ylabel(\"SSR\")\n # title\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Freeze layers in model that starts with keyworks in keys. | def freeze_named_layers(model, keys: Tuple = ()):
for key in keys:
for name, param in model.named_parameters():
if name.startswith(key):
param.requires_grad = False | [
"def unfreeze_named_layers(model, keys: Tuple = ()):\n for key in keys:\n for name, param in model.named_parameters():\n if name.startswith(key):\n param.requires_grad = True",
"def _set_freeze_layers(self):\n for layer in self.encoder.layers[:self.freeze_layers]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unfreeze layers in model that starts with keyworks in keys. | def unfreeze_named_layers(model, keys: Tuple = ()):
for key in keys:
for name, param in model.named_parameters():
if name.startswith(key):
param.requires_grad = True | [
"def unfreeeze_all_layers(self):\n # Unfreeeze\n logger.info('MODEL: Unfreeze all layers.')\n for i in range(len(self.model.layers)):\n self.model.layers[i].trainable = True\n \n # Compile model\n logger.info('MODEL: Compiling...')\n self.model.compile... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pad framewise_output to the same length as input frames. The pad value is the same as the value of the last frame. | def pad_framewise_output(framewise_output, frames_num):
pad = framewise_output[:, -1:, :].repeat(1, frames_num - framewise_output.shape[1], 1)
"""tensor for padding"""
output = torch.cat((framewise_output, pad), dim=1)
"""(batch_size, frames_num, classes_num)"""
return output | [
"def pad_framewise_output(framewise_output: torch.Tensor, frames_num: int):\n pad = framewise_output[:, -1:, :].repeat(\n 1, frames_num - framewise_output.shape[1], 1)\n \"\"\"tensor for padding\"\"\"\n\n output = torch.cat((framewise_output, pad), dim=1)\n \"\"\"(batch_size, frames_num, classes_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Virtually private constructor which initializes the Game scene. It is responsible for controlling the game features. Here all the game objects are initialized and used in one combined environment. That way we can use the physics engine behind Pymunk (chipmunk) together with the images, surfaces and userinput handlers p... | def __init__(self):
# TODO: !!! EXPLAIN ALL THE TODO's in this file in the report !!!
# Call the super class (SceneBase) initialization method. This
# statement ensures that this class inherits its behaviour from its Superclass.
# Abstract methods of all scenes (process_input(), update()... | [
"def __init__(self) -> None:\n print_log(\"STARTING PYGAME\", \"STARTUP\")\n pg.init()\n mixer.init()\n self.screen = pg.display.set_mode((WIDTH, HEIGHT))\n pg.display.set_caption(TITLE)\n self.clock = time.Clock()\n self.running = True\n self.load_data()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This adds all the components of the antispacecraft (cannon, wheels, chassis, pin joints), the spacecraft body and shape and the landing pad body to the Pymunk space | def add_objects_to_space(self):
self.anti_spacecraft.add_to_space(self.space) # Anti-spacecraft Parts (represent the whole vehicle)
self.space.add(self.spacecraft.body, self.spacecraft.shape) # Spacecraft body and shape
self.space.add(self.pm_landing_pad) # Landing pad | [
"def assembleMatrices(self):\n # All nodes informations\n self.aircraftNodesPoints = []\n self.aircraftMassPoints = []\n self.aircraftMassDistances = []\n self.aircraftSegmentsLengths = []\n self.aircraftNodesNames = []\n self.aircraftInitNodesAreas = []\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize all the collision handlers between different Pymunk objects. | def start_collision_handlers(self):
self.missile_and_terrain.begin = self.missile_terrain_collision_begin
self.missile_and_spacecraft_handler.begin = self.missile_spacecraft_collision_begin
self.spacecraft_and_terrain_handler.begin = self.spacecraft_terrain_collision_begin
self.missile_... | [
"def initCollision(self):\n base.cTrav = CollisionTraverser()\n base.cTrav.setRespectPrevTransform(True)\n base.pusher = CollisionHandlerPusher()",
"def setupCollisions(self):\n\t\tbase.cTrav = CollisionTraverser()\n\t\tself.cHandler = CollisionHandlerEvent()\n\t\t#self.cHandler.setInPattern(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pause the game after a player crash, correct landing or the spacecraft is out of HP. Display a message, till the 'Return' key is pressed | def pause_game(self, msg_type, screen):
msg = ''
if msg_type == 'landed':
msg = FONT_WARNING.render("Successful Landing!", False, (13, 109, 24))
elif msg_type == 'crashed':
msg = FONT_WARNING.render("The spacecraft has crashed!", False, (255, 0, 6))
elif msg_type... | [
"def player_win():\n print_pause(\n \"Excellent! You've successfully completed 'Spell Check'!\\n\"\n \"Thank you for playing!\")\n play_again()",
"def input(self, event):\n # If the window is quit.\n if event.type == pygame.QUIT:\n # Exit the game.\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a random terrain from a sequence of linked Pymunk segment objects. | def random_terrain(self):
terrain_segments = [] # To hold the list of segments that will be added to the space as a terrain
# Generate the point tuples
points = [(i, random.randint(self.screen_height // 20, self.screen_height // 7))
for i in range(0, self.screen_width + SEGME... | [
"def generate_dungeon(x, y, height, **options):\n terrain = np.zeros([x, y], dtype=int)\n rooms = generate_rooms(x, y)\n yield rooms\n for room in rooms:\n carve(room, terrain)\n yield net_from_points([r.centre for r in rooms],\n Triangle((0, 0), (0, x+y), (x+y, 0)))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and place the Game scene borders (Pymunk segments). | def borders(self):
border_left = pm.Segment(self.space.static_body, (-5, 0), (-5, self.screen_height), 10)
border_right = pm.Segment(self.space.static_body, (self.screen_width + 5, 0),
(self.screen_width + 5, self.screen_height), 10)
border_top = pm.Segment(self... | [
"def drawBorders(self):\n width = 1\n color = colors.BLACK\n x0, y0 = self.grid[0].x0 - width, self.grid[0].y0 - width\n h_end = self.grid[-1].y0 + Node.size\n v_end = self.grid[-1].x0 + Node.size\n \n points = [(x0, y0), (x0, h_end), (v_end, h_end), (v_end, y0)]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a BugState that contains copies of all this BugState's columns, except for id. | def copy(self):
# Unfortunately we can't just import copy because this comes with all kinds
# of nasty SQLA internals
kwargs = {}
for col in self.__table__.columns:
if col.name == 'id':
continue
kwargs[col.name] = getattr(self, col.name)
re... | [
"def copy(self):\n copyBS = BoardState()\n copyBS.state = [[self.state[i][j] for j in range(3)] for i in range(3)]\n return copyBS",
"def copy(self):\n tmp = Column(format=\"I\") # just use a throw-away format\n tmp.__dict__ = self.__dict__.copy()\n return tmp",
"def c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a BugState corresponding to a bug page (an object representing the results of scraping the current state of a bug on Bugzilla). | def from_bugpage(cls, bp):
# Have to do this because of utterly bizarre way attr getter methods are done in BugPage...
status, importance, platform, product = map(
lambda att: bp._parse_attr(att),
(bp.att_status(), bp.att_importance(), bp.att_platform(), bp.att_product())
... | [
"def get(self, bug_number, include_fields=None):\n fields = include_fields if include_fields else self.DEFAULT_SEARCH\n bug = self.request(\n 'bug/%s' % bug_number,\n params={\"include_fields\": fields}\n )\n return Bug(self, **bug['bugs'][0])",
"def parse_buginfo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the id of a duplicate bug, create and return a delta from the perspective of the original (duplicated) bug, reflecting the addition of a new duplicate. | def from_dupid(dupid):
duppage = bs.BugPage(dupid)
res = Delta()
res.what = 'Duplicates'
res.removed = None
res.added = dupid
res.date = utils.datify(duppage.att_resolved())
res.datetime = utils.datetimeify(duppage.att_resolved())
res.who = None
re... | [
"def _add_dup(self, author, dup, master_id):\n self.env.log.debug(\"dup: dupping %s to %s\" % (dup.id, master_id))\n self._add_master(author, dup.id, master_id)\n\n # tag this ticket and close it\n cmt = u\"Duplicate of ticket #%s.\" % master_id\n self.env.log.debug(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populate the bugstates tables. Go through each bug in All_bugs.csv and scrape its status and history from bugzilla. Then walk backwards through the history, saving a "snapshot" of the bug's status for each month in the month table that the bug existed at. If Abbrev is true, we only attempt 1 bug. | def populate_bugstates(session, abbrev=False, commit_interval=None):
# This code is really, really tricky. I don't know how I could have written it more clearly.
# Maybe it should have been broken up more into subroutines.
bugs = utils.open_data_file('All_bugs.csv')
bugs.readline()
bzids = [line.s... | [
"def bz_search_handler():\n bugs = []\n try:\n bugs = bz.get_matching_bugs('whiteboard', '\\[autoland.*\\]')\n except (urllib2.HTTPError, urllib2.URLError), e:\n log.error(\"Error while polling bugzilla: %s\" % (e))\n return\n if not bugs:\n return\n\n for (bug_id, whitebo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill a mock cache object with some keys and values. | def fill_cache(cache, values_dict):
cache.get.side_effect = lambda k, d=None: values_dict.get(k, d) | [
"def createCacheObj(self, key, value):",
"def test_cache_set_without_timeout(self):\n self.cache.set('superman', 'clark kent')\n self.cache.set('recipe', {'sugar': 2, 'wine': 5})\n\n self.assertEqual(self.cache.get('superman'), 'clark kent')\n self.assertEqual(self.cache.get('recipe'),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup a mock http object with some responses to given URLs. ``response_dict`` should map full URLs (including query string) to the (response, content) tuple that will be returned (equivalent to the return value of the httplib2.Http.request method). | def setup_responses(http, response_dict):
url_dict = dict((Url(k), v) for k, v in response_dict.iteritems())
def request(*args, **kwargs):
uri = Url(kwargs["uri"])
try:
return url_dict[uri]
except KeyError:
return response(
make_error(
... | [
"def _AddMockJSONResponse(mock_client, url, response_dict):\r\n def _CreateResponse(request):\r\n return httpclient.HTTPResponse(request, 200,\r\n headers={'Content-Type': 'application/json'},\r\n buffer=StringIO(json.dumps(response_dict)))\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A version of ``setup_responses`` intended for endtoend requestresponse testing. Automatically knows how to respond to the StaticCompanyMiddleware query for the current company, and to static data requests. | def setup_common_responses(http, response_dict):
new_dict = COMMON_RESPONSES.copy()
new_dict.update(response_dict)
return setup_responses(http, new_dict) | [
"def setup_service_responses():\n\n from .data.test_my_service_data import \\\n URL_1, RESPONSE_1, \\\n URL_2, RESPONSE_2\n\n # for packet_count in range(len(RESPONSE_1)):\n responses.add(\n responses.GET,\n URL_1,\n json=RESPONSE_1,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Example Hello Redis Program | def hello_redis():
# step 3: create the Redis Connection object
try:
# The decode_repsonses flag here directs the client to convert the responses from Redis into Python strings
# using the default encoding utf-8. This is client specific.
r = redis.StrictRedis(host=redis_host, port=redis... | [
"def run_redis_example():\n\n try:\n r = redis.StrictRedis(host=host, port=port, password=pw,\n decode_responses=True)\n except Exception as e:\n print(f'Error connecting to Redis DB: {e}')\n\n return r",
"def connect(*args, **kwargs):\n global client\n cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancel all unfilled/pending orders. | def cancel_pending_orders(self):
raise NotImplementedError("Broker must implement \
`cancel_pending_orders()`") | [
"def cancel_orders(self) -> None:\n for order in list(self.orders):\n order.cancel()",
"def cancel_all_open_orders(self):\n self._awaiting_orders.clear()",
"def cancel_all_orders(self):\n payload = {\n 'request': '/v1//order/cancel/all',\n 'nonce': self._non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get geocode results from Google Maps Geocoding API. Note, that in the case of multiple google geocode reuslts, this function returns details of the FIRST result. | def get_google_results(address):
# Set up your Geocoding url
logging.info("[GOOGLE URL]: init")
params = {
"address":address,
"key":GEOPY.get('AQUEDUCT_GOOGLE_PLACES_PRIVATE_KEY')
}
# Ping google for the reuslts:
try:
with requests.Session() as s:
s.mount('https://',HTTPAdapter(max_retries=Retry(2, backo... | [
"def get_google_results(address, api_key=None, return_full_response=False):\n # Set up your Geocoding url\n geocode_url = \"https://maps.googleapis.com/maps/api/geocode/json?address={}\".format(address) + \"&sensor=false\"\n # if api_key is not None:\n # geocode_url = geocode_url + \"&key={}\".forma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List the job submission history. Normal users can only look at their own submissions. | def list_history(request):
history = History.objects
if not is_admin(request.user):
history = history.filter(submitter=request.user)
history = history.order_by('-submission_date')
return render('editor/list_history.mako', request, {
'history': history,
}) | [
"def getJobHistory(self,jobname):\n\t\tpass",
"def get_recent_submissions(self):\n logging.info(\"Retrieving submissions from the last hour\")\n submissions = list(self.subreddit.search('subreddit:{0}'.format(self.subreddit.display_name), time_filter='hour', syntax='lucene', sort='new'))\n lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
new_session Start a new API session via vspk an return the corresponding 'vspk.NUVSDSession` object. Note that this object is also exposed as `self()` | def new_session(self):
self._session = self.vspk.NUVSDSession(
username=self.user,
password=self.password,
enterprise=self.enterprise,
api_url=self.uri)
self._session.start()
if not self.default_enterprise:
self.default_enterprise = se... | [
"def new_session(self):\n return self.Session()",
"def new_session(self):\n return LiveFixtureServerSession(self.url)",
"def open_vdu_session(self, vnf_session_id, vdu):\n url = BASE_URL + '/openVduSession'\n payload = {\n 'timestamp_sec': time(),\n 'flavorCpuCo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly generate a token, given prev_tokens. prev_tokens the previous n1 tokens (optional only if n = 1). | def generate_token(self, prev_tokens=None):
n = self._n
if not prev_tokens:
prev_tokens = ()
assert len(prev_tokens) == n - 1
r = random()
probs = self._sorted_probs[prev_tokens]
# WORK HERE!!
token = self.sample(probs)
return token | [
"def generate_token(self, prev_tokens=None):\n n = self._n\n if not prev_tokens:\n prev_tokens = ()\n assert len(prev_tokens) == n - 1\n\n r = random.random()\n probs = self._sorted_probs[prev_tokens]\n token = self.sample(probs)\n\n return token",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test global service, invalid device ID. | async def test_global_service_bad_device(
hass: HomeAssistant, ufp: MockUFPFixture
) -> None:
nvr = ufp.api.bootstrap.nvr
nvr.__fields__["add_custom_doorbell_message"] = Mock(final=False)
nvr.add_custom_doorbell_message = AsyncMock()
with pytest.raises(HomeAssistantError):
await hass.servi... | [
"async def test_service_invalid_device_id(\n hass: HomeAssistant, config_entry: ConfigEntry\n) -> None:\n await hass.config_entries.async_setup(config_entry.entry_id)\n await hass.async_block_till_done()\n\n data = {ATTR_VEHICLE: \"VF1AAAAA555777999\"}\n\n with pytest.raises(ValueError):\n awa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an ANN corresponding to with given partioning, domains. Code corresponding to the AbstractLayerWise algorithm, Algorithm 3 in [1]. Arguments ========= should be a list of twotuples (weight_matrix, activation_fn) with weight_matrix a Numpy array of shape (out_dims, in_dims) and activation_function a Python funct... | def abstract_layer_wise(network, partitionings, abstract_domains):
abstract_network = []
iterate = zip(network, partitionings, partitionings[1:], abstract_domains)
for layer, partitions_from, partitions_to, domain in iterate:
abstract_weights = alpha_hat(
layer[0], partitions_from, parti... | [
"def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu,method = \"xavier\"):\n # Adding a name scope ensures logical grouping of the layers in the graph.\n with tf.name_scope(layer_name):\n # This Variable will hold the state of the weights for the layer\n with tf.name_scope('weights'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes a columnscaled version of with given scales. See Definition 17 in [1]. | def scale_columns(matrix, scales):
return np.einsum("ij,j->ij", matrix, scales) | [
"def col_scale(x, s):\n\n if x.format == \"csc\":\n return ColScaleCSC()(x, s)\n elif x.format == \"csr\":\n return RowScaleCSC()(x.T, s).T\n else:\n raise NotImplementedError()",
"def col_scale(x, s):\r\n\r\n if x.format == 'csc':\r\n return ColScaleCSC()(x, s)\r\n elif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields the partitioning combination matrices for . If =True, yields only the binary PCMs, i.e., acts like BinPCMs in [1]. | def PCMs(partitioning, only_binary=False):
if only_binary:
dimensions = 1 + max(
n for partition in partitioning for n in partition)
for assignment in itertools.product(*partitioning):
PCM = np.zeros((dimensions, len(partitioning)))
for partition, partition_assign... | [
"def listBundles(m = 5):\n return numpy.atleast_2d([b for b in itertools.product([False,True],repeat=m)]).astype(bool)",
"def yieldAllCombos(items):",
"def items():\n for point in boolfunc.iter_points(inputs):\n # pylint: disable=C0103\n ab = self.restrict(point).pcda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the MIC values for one set of the SCN trajectories in question | def mic_of_simulation(trajectories):
avpvipsol = trajectories[:, 1:(160+1)]
navsol = trajectories[:, (160+1):]
per2 = np.hstack([avpvipsol[:, ::4], navsol[:, ::3]])
numcells = per2.shape[1]
# set up mic calculator
mic = mp.MINE(alpha=0.6, c=15, est='mic_approx')
... | [
"def get_measured_outputs_values(self):\n obsOut = numpy.zeros(self.get_num_measured_outputs())\n i = 0\n for o in self.outputs:\n if o.is_measured_output():\n obsOut[i] = o.read_value_in_fmu(self.fmu)\n i += 1\n return obsOut",
"def getMeasures... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Monta a imagem novamente e imprime | def imprime_imagem(tipo, imagem):
cv.imshow(tipo, imagem)
cv.waitKey(0)
cv.destroyAllWindows() | [
"def recarregar_imagem(self):\n self.salvar_imagem(caminho_imagem=self.caminho_temp)\n self.carregar_imagem(caminho_imagem=self.caminho_temp)",
"def ima(self):\r\n self.image_bateau=[]\r\n self.orientation=[1,1,1,1,1]\r\n self.image_bateau.append(self.create_image(self.img[1][0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return True if is instance of AbsoluteFormula | def is_absolute(self) -> bool:
return isinstance(self, AbsoluteFormula) | [
"def is_absolute(self):\r\n \r\n # FIXME(Ole): It is unfortunate that decision about whether points\r\n # are absolute or not lies with the georeference object. Ross pointed this out.\r\n # Moreover, this little function is responsible for a large fraction of the time\r\n # using ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read in the classification data from a json file. | def read_classification_json(fn):
with open(fn) as f:
classification_data = json.load(f)
f.close()
return classification_data | [
"def load_classifications(filename, json_columns=None):\n json_columns = json_columns or ['metadata', 'annotations', 'subject_data']\n converters = {i: JSONParser for i in json_columns}\n\n return pd.read_csv(filename, converters=converters)",
"def read_json(self, json_files):\n self.file_access.w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test default product stealability isn't so stealable. | def test_default_product_stealability(self):
prod = Product('Test Product')
self.assertEqual(prod.stealability(), "Kinda stealable.") | [
"def test_stealable(self):\r\n prod = Product(name='Test Product',\r\n weight=100, price=1,\r\n flammability=0.5)\r\n self.assertEqual(prod.stealability(), \"Not so stealable...\")",
"def test_itar_restrict_software_asset(self):\n pass",
"def stea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test default number of products generated being 30. | def test_default_num_products(self):
products = generate_products()
self.assertEqual(len(products), 30) | [
"def test_default_num_products(self):\n assert len(generate_products()) == 30",
"def test_default_num_products(self):\n prod = generate_products()\n self.assertEqual(len(prod), 30)",
"def test_default_num_products(self):\n products = acme_report.generate_products()\n self.assertEq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select and render a random student group. | def home(request):
group = Group.objects.random()
return render_to_response('group.html',
locals(),
context_instance=RequestContext(request)) | [
"def pickonestudent():\n pick = random.choice(students)\n print(pick)",
"def group_selection(request):\n\n groups = get_user_groups(request.user)\n count = len(groups)\n if count == 1:\n # Redirect to the detail page for this group\n return redirect(groups[0])\n context = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the latest release revision for a job. | def _get_latest_job_revision(job):
job_environment = job.get_environment()
release_build_bucket_path = job_environment.get('RELEASE_BUILD_BUCKET_PATH')
if not release_build_bucket_path:
logs.log_error('Failed to get release build url pattern for %s.' % job.name)
return None
revisions = build_manager.ge... | [
"def get_revision():\n try:\n process = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], shell=False,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out = process.communicate()\n\n if not out[0]:\n print(\"WARNING: error occured extracting rev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Schedule the corpus pruning tasks. | def get(self):
for job in data_types.Job.query():
if not utils.string_is_true(job.get_environment().get('CORPUS_PRUNE')):
continue
latest_revision = _get_latest_job_revision(job)
if not latest_revision:
continue
queue = tasks.queue_for_job(job.name)
for target_job in ... | [
"def perform_timestep_prune(self, center):\n if self.timestep >= self.prune_delay:\n self.prune_sector_center(center)",
"def garbage_collector(self):\n\n def _gc(self):\n while True:\n self.mutex.acquire()\n if PRINT_THREAD:\n lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retract a fact from the KB | def kb_retract(self, fact_or_rule):
printv("Retracting {!r}", 0, verbose, [fact_or_rule])
####################################################
# Student code goes here
if isinstance(fact_or_rule, Fact):
if fact_or_rule not in self.facts:
#print("fact not in b... | [
"def kb_retract(self, fact):\n printv(\"Retracting {!r}\", 0, verbose, [fact])\n ####################################################\n # Student code goes here\n\n fact = self._get_fact(fact)\n if not isinstance(fact, Fact):\n return\n\n #Therefore, when you ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Forwardchaining to infer new facts and rules | def fc_infer(self, fact, rule, kb):
printv('Attempting to infer from {!r} and {!r} => {!r}', 1, verbose,
[fact.statement, rule.lhs, rule.rhs])
####################################################
# Student code goes here
binds = match(fact.statement, rule.lhs[0])
... | [
"def fc_infer(self, fact, rule, kb):\n printv('Attempting to infer from {!r} and {!r} => {!r}', 1, verbose,\n [fact.statement, rule.lhs, rule.rhs])\n ####################################################\n # //--\n bindings = match(rule.lhs[0],fact.statement)\n if bindin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the websocket URI using the `plexapi` library. | def _get_uri(plex_server):
return plex_server.url(
"/:/websockets/notifications", includeToken=True
).replace("http", "ws") | [
"def build_websocket_url(self):\n\n r = requests.get(constants.WS_HOST, headers=constants.HTTP_HEADERS)\n ws_info = r.json()\n ws_info[\"securePort\"] = str(ws_info[\"securePort\"])\n ws_uri = constants.WS_URI + ws_info[\"token\"]\n ws_url = f\"wss://{ws_info['ip']}:{ws_info['secu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of size (qs_size x db_size) where arr[i,j] = similarity between ith image in queryset and jth image in database | def calc_similarities(measure, db, qs, show_progress=False):
def compute_one(hist):
result = [measure(hist, db_hist) for db_hist in db]
return result
generator = tqdm(qs) if show_progress else qs
return np.array([compute_one(hist) for hist in generator]) | [
"def cal_similarity(query_feat, gallery_feat, q_pids, g_pids, q_camids, g_camids):\n # The larger the cosine distance, the more similar it is\n distmat = -np.matmul(query_feat, np.transpose(gallery_feat))\n num_q = query_feat.shape[0]\n num_g = gallery_feat.shape[0]\n max_rank = 10\n if num_g < ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna el score de un robot dentro de la fase score es una nupla de la forma (jugados, triunfos, empates, derrotas, a favor, en contra, diferencia, puntos) | def score(self, robot):
scores = [grupo.score(robot) for grupo in self.get_grupos()]
return reduce(lambda acumulador, score: tuple([ a + b for a, b in zip(acumulador, score)]), scores, (0, 0, 0, 0, 0, 0, 0, 0)) | [
"def score(self, robot):\n scores = [ronda.score(robot) for ronda in self.get_rondas()]\n return reduce(lambda acumulador, score: tuple([ a + b for a, b in zip(acumulador, score)]), scores, (0, 0, 0, 0, 0, 0, 0, 0))",
"def get_score(plateau):\n i = 0 # initialisation de i\n s = 0 # initialis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the currently used cmd line argument string. This way the 'active' arguments can be changed at runtime. | def set_argv(self, string):
try:
self.argv = string.split(' ')
except AttributeError:
if string:
self.argv = string
else:
self.argv = [] | [
"def set_active_arguments(self, **kwargs):\n self.active_arguments = kwargs",
"def set_cmdline(self, arg_list):\n sys.argv[1:] = arg_list",
"def set_global_arg(self, key, value):\n self.args[key] = value",
"def set_run_arg(self, arg: str, value: t.Optional[str] = None) -> None:\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a molecule representing not a model compound to the DATA instance. DEPRECATED | def add_molecule(self, name, cell=None):
print 'DATA.add_molecule is deprecated. Please use DATA.give_molecule'
self[name] = MOLECULE(name=name, cell=cell) | [
"def add_molecule(self, molecule: off.Molecule) -> None:\n self.molecules.append(\n molecule.to_smiles(isomeric=True, explicit_hydrogens=True)\n )",
"def addMetaMolecule (self,metaMolecule):\r\n self.metaMolecule = metaMolecule",
"def add_molecule(self, molecule):\n number... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines wether an atom is prochiral and determines the atom's side if necessary. | def _get_prochirality(self):
for atom in self.invarioms:
atom.get_prochirality()
atom.invariom.get_prochirality() | [
"def is_aromatic(atom: Atom) -> int:\n return int(atom.GetIsAromatic())",
"def _is_chiral_atom(graph, atom_index):\n neighbours = list(graph.neighbors(atom_index))\n\n if len(neighbours) != 4:\n return False\n\n graphs = []\n for neighbour in neighbours:\n _graph = graph.copy()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transfers the ADP from the modelcompounds to the 'exp' molecule. | def _transfer_adp(self):
toleratedAtoms = []
for atom in self['exp'].atoms:
tolerated = atom.transfer_adp()
if tolerated:
toleratedAtoms.append(tolerated)
for atom in toleratedAtoms:
atom.averageADP() | [
"def export_model(config: EasyDict, exp_path: Path) -> None:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(\"Loading Model\")\n model = get_model(config.model).to(device)\n\n for filename in os.listdir(exp_path):\n if filename.endswith(\"_latest.pth\"):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines the orientation vectors of all atoms in self.invarioms. | def _get_orientations(self):
for atom in self.invarioms:
atom.get_orientation() | [
"def orientation(self):\n directions = self._directions_of_edges()[0]\n orientation = []\n for C in self.pd_code():\n if C[0] == C[1] or C[2] == C[3]:\n orientation.append(-1)\n elif C[1] == C[2] or C[0] == C[3]:\n orientation.append(1)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Links all atoms in 'exp' to their invarioms. | def _link(self):
for exp_atom in self['exp'].atoms:
if exp_atom.isTolerated():
continue
for model_atom in self[exp_atom.model_compound.name].atoms:
inv = exp_atom.get_active_invariom()
if inv in model_atom.invarioms.keys():
... | [
"def add_exp_to_sym_table(self, ins_node, std_node):\n if not isinstance(std_node, CaitNode):\n raise TypeError\n self.exp_table[ins_node.astNode.id] = std_node",
"def _get_atoms(self):\n atoms = []\n invarioms = []\n\n for molecule in self.values():\n atom... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |