query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Initializes an instance from number of times to try, and lower and upper bounds to sleep (in seconds). | def __init__ (self, times, lower, upper):
self.times = times
self.lower = lower
self.upper = upper
self.counter = 0 | [
"def __init__(self, number, sleepMax):\n Thread.__init__(self, name = \"Thread \" + str(number))\n self._sleepInterval = random.randint(1, sleepMax)",
"def __init__(self, retry_count):\n self.retry_count = retry_count",
"def retry(self, times):\n return Retry((requests.ConnectionErro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the ids of the registered engines. This method always blocks. | def remote_get_ids(self):
return self.smultiengine.get_ids() | [
"def engines(self):\n return ENGINE_LIST",
"def getIDs(self):\n return self.multiengine.getIDs()",
"def _get_bot_ids(self):\n bot_ids = self.redis_client.keys(self.namespace + '*')\n return bot_ids",
"def engineList(self, targets):\n if isinstance(targets, int):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn a list of deferred_ids into a final result or failure. | def process_did_list(did_list):
new_d_list = [self.get_pending_deferred(did, True) for did in did_list]
final_d = gatherBoth(new_d_list,
fireOnOneErrback=0,
consumeErrors=1,
log... | [
"def aggregateResult(deferred_list):\n return defer.DeferredList(deferred_list, fireOnOneErrback=True, consumeErrors=True)",
"def gather_results( # type: ignore[misc]\n deferredList: Tuple[\"defer.Deferred[T1]\", ...],\n consumeErrors: bool = False,\n) -> \"defer.Deferred[Tuple[T1, ...]]\":\n # The `... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A parallelized version of Python's builtin map. This has a slightly different syntax than the builtin `map`. This is needed because we need to have keyword arguments and thus can't use args to capture all the sequences. Instead, they must be passed in a list or tuple. raw_map(func, seqs) > map(func, seqs[0], seqs[1], .... | def raw_map(self, func, sequences, dist='b', targets='all', block=True):
if not isinstance(sequences, (list, tuple)):
raise TypeError('sequences must be a list or tuple')
max_len = max(len(s) for s in sequences)
for s in sequences:
if len(s)!=max_len:
rais... | [
"def map_async(function, iterable, *args, **kwargs):\n return _map_or_starmap_async(function, iterable, args, kwargs, \"map\")",
"def python_map(func, *arglist, **kwds):\n #print \"ignoring: %s\" % kwds #XXX: should allow use of **kwds\n result = map(func, *arglist) # see pathos.pyina.ez_map\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A parallel version of Python's builtin `map` function. This method applies a function to sequences of arguments. It follows the same syntax as the builtin `map`. This method creates a mapper objects by calling `self.mapper` with no arguments and then uses that mapper to do the mapping. See the documentation of `mapper`... | def map(self, func, *sequences):
return self.mapper().map(func, *sequences) | [
"def map_async(function, iterable, *args, **kwargs):\n return _map_or_starmap_async(function, iterable, args, kwargs, \"map\")",
"def python_map(func, *arglist, **kwds):\n #print \"ignoring: %s\" % kwds #XXX: should allow use of **kwds\n result = map(func, *arglist) # see pathos.pyina.ez_map\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Demonstrates using the pager. | def pager():
lines = []
for x in range(200):
lines.append('%s. Hello World!' % click.style(str(x), fg='green'))
click.echo_via_pager('\n'.join(lines)) | [
"def pager():\n lines = []\n for x in range_type(200):\n lines.append('%s. Hello World!' % click.style(str(x), fg='green'))\n click.echo_via_pager('\\n'.join(lines))",
"def do_pager(self, pager):\n self.pager = pager\n print(\"Pager set: %s\" % self.pager)",
"def pager(lines):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read data (document / collection) from Firestore recursively and save to local file system | def read(cred, output, depth, type, exclude, path):
click.echo('Reading from firetore, credential file: %s' % (cred))
cred = os.path.abspath(cred)
output = os.path.abspath(output)
click.echo('Document path: %s' % path)
click.echo('Output path: %s' % output)
if depth<0:
depth = 1000000
... | [
"def write(cred, folder, depth, path):\n click.echo('Writing to Firetore, credential file: %s' % (cred))\n cred = os.path.abspath(cred)\n data_folder = os.path.abspath(folder)\n click.echo('Document path: %s' % path)\n click.echo('Data folder path: %s' % data_folder)\n\n if depth < 0:\n dep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read data (document / collection) from local folder and write to Firestore recursively \b | def write(cred, folder, depth, path):
click.echo('Writing to Firetore, credential file: %s' % (cred))
cred = os.path.abspath(cred)
data_folder = os.path.abspath(folder)
click.echo('Document path: %s' % path)
click.echo('Data folder path: %s' % data_folder)
if depth < 0:
depth = 1000000
... | [
"def read(cred, output, depth, type, exclude, path):\n click.echo('Reading from firetore, credential file: %s' % (cred))\n cred = os.path.abspath(cred)\n output = os.path.abspath(output)\n click.echo('Document path: %s' % path)\n click.echo('Output path: %s' % output)\n\n if depth<0:\n dept... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create config file with OXE connection parameters | def oxe_configure(host, login, password, proxies):
config = ConfigParser()
full_path = join(gettempdir(), 'pyoxeconf.ini')
if exists(full_path):
config.read(full_path)
if config.has_section('default') is False:
config.add_section('default')
if config.has_section(str(host)) is Fal... | [
"def createConfig():\n config = ConfigParser()\n config.add_section(\"database\")\n config.set(\"database\", \"url\", \"../pos.db\")\n\n\n config.add_section(\"firsttime\")\n config.set(\"firsttime\" , \"db-installed\" , \"0\")\n\n\n with open(\"settings.ini\", \"w\") as config_file:\n conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builder for requests headers depending on request method | def oxe_set_headers(token, method=None):
# basic method GET
headers = {
'Authorization': 'Bearer ' + token,
'accept': 'application/json'
}
# addition for POST & PUT
if method in ('POST', 'PUT'):
headers.update({'Content-Type': 'application/json'})
# addition for DELETE
... | [
"def _make_headers(self, url, http_method): \n\n hmac = \"%s:%s\" % (\n self.username, self._create_hmac(url, http_method)\n )\n headers = { 'Authorization': hmac }\n if http_method == Action.POST:\n headers['Content-type'] = 'application/json'\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that actual_list and expected_list are almost equal. ie. assertAlmostEqual(actual_elem, expected_elem) in each list. | def assertListAlmostEqual(self, actual_list, expected_list):
self.assertTrue(len(actual_list) == len(expected_list))
for i in xrange(len(actual_list)):
self.assertAlmostEqual(actual_list[i], expected_list[i]) | [
"def assertListItemEqual(self, expected, actual):\n self.assertEqual(len(expected), len(actual))\n for item_expected, item_actual in zip(expected, actual):\n self.assertItemEqual(item_expected, item_actual)",
"def assertDeepAlmostEqual(self, expected, actual, *args, **kwargs):\n kw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sample n_samples from the model. Sample from prior and create ldj. Then invert the flow and invert the logit_normalize. | def sample(self, n_samples):
z = sample_prior((n_samples,) + self.flow.z_shape)
ldj = torch.zeros(z.size(0))
z, ldj = self.flow (z, ldj, reverse=True)
z, ldj = self.logit_normalize(z, ldj, reverse=True)
return z | [
"def sample_from_prior(self, n_samples):\n pass",
"def _sample_without_replacement(logits, n_samples):\n z = -K.log(-K.log(K.random_uniform(K.shape(logits))))\n return K.tf.nn.top_k(logits+z, k=n_samples)[1]",
"def sample_prior(self, n_samples):\n return np.random.normal(size=[n_samples, sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a train and validation epoch and return average bpd for each. | def run_epoch(model, data, optimizer, epoch):
traindata, valdata = data
model.train()
train_bpd = epoch_iter(model, traindata, optimizer, epoch)
model.eval()
val_bpd = epoch_iter(model, valdata, optimizer, epoch)
return train_bpd, val_bpd | [
"def run_epoch(self):\n self.train()\n return self.test()",
"def run_epoch(model, data, optimizer):\n traindata, valdata = data\n\n model.train()\n train_elbo = epoch_iter(model, traindata, optimizer)\n\n model.eval()\n val_elbo = epoch_iter(model, valdata, optimizer)\n\n return tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an adjacency matrix and starting node, traverse the graph | def dfsIterative(m, start):
s = [start] # list, use as stack
visited = {start} # set
out = []
while len(s) > 0:
cur = s.pop()
pr('cur')
out.append(cur)
for vertex, connected in enumerate(m[cur]):
# vertex is column in matrix (i)
... | [
"def A_MST(matrix, start):\n num_of_nodes_expanded = 1\n queue = [] # Frontier\n\n \"\"\" The queue structure holds (heuristic, path, path_cost) where\n\n :heuristic: path_cost + weight of MST on remaining edge\n :path: path to current from start\n :path_cost: cost of path from start to current n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an image upload_job and return an UploadJob instance | def create_job(self, image_name, image_checksum, project, cloud_account_names=None):
self._log.debug("Project {}: Create image upload job for image {} to {}".
format(project, image_name, cloud_account_names))
create_job_msg = RwImageMgmtYang.YangInput_RwImageMgmt_CreateUploadJob... | [
"def create_job_object(message, environment_image):\n\n PYTHONUNBUFFERED_ENV = client.V1EnvVar(name=\"PYTHONUNBUFFERED\", value=\"1\")\n AUTH_TOKEN_ENV = client.V1EnvVar(name=\"AUTH_TOKEN\", value=AUTH_TOKEN)\n EVALAI_API_SERVER_ENV = client.V1EnvVar(\n name=\"EVALAI_API_SERVER\", value=EVALAI_API_S... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait until the upload job reaches a terminal state | def wait_until_complete(self):
self._log.debug("waiting for upload job %s to complete", self._job_id)
xpath = ManoProject.prefix_project("D,/rw-image-mgmt:upload-jobs/" +
"rw-image-mgmt:job[rw-image-mgmt:id={}]".
forma... | [
"def wait_complete(jobname_synthax):\n # time.sleep(120)\n while not check_complete(jobname_synthax):\n time.sleep(120)",
"async def wait_until_done(self) -> None:\n ...",
"def wait_for_operation(self):\n self.command('*WAI')",
"def wait_step(self):\n pass",
"def waitTillUp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A simpler version of exit_based_on_results(); this function causes the script to exit normally with return value of zero if and only if all tests within the script passed and had no errors. Otherwise it returns the number of failures plus the number of errors | def simple_exit(results):
if results.wasSuccessful():
_exit(0)
else:
nfail = len(results.errors)+len(results.failures)
_exit(nfail) | [
"def exit_based_on_results(results):\n NotImpErrors = 0\n for error in results.errors:\n for errormsg in error:\n if type(errormsg) is str:\n if 'NotImplemented' in errormsg:\n NotImpErrors +=1\n break\n if results.wasSuccessful():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A probablyobsolete function to exit from a unit testscript with a status that depends on whether or not the only errors or failures were NotImplemented errors. Specifically, | def exit_based_on_results(results):
NotImpErrors = 0
for error in results.errors:
for errormsg in error:
if type(errormsg) is str:
if 'NotImplemented' in errormsg:
NotImpErrors +=1
break
if results.wasSuccessful():
_exit(0)
... | [
"def check_exit_code(results):\n assert results[\"metrics\"][\"Exit code\"] == 0",
"def simple_exit(results):\n if results.wasSuccessful():\n _exit(0)\n else:\n nfail = len(results.errors)+len(results.failures)\n _exit(nfail)",
"def error_test():\n checkresult(lib.ErrorTest())",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper function to respond json with the given status code and the given data | def respond(code, data):
return {
'statusCode': code,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps(data)
} | [
"def data_response( data, code = 200 ):\n return jsonify( { 'data' : data } ), code",
"def jsonify_status_code(status_code, *args, **kw):\n response = jsonify(*args, **kw)\n response.status_code = status_code\n return response",
"def get_response(data):\n response = {\n \"status\": data.ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a series of known mnemonics and their generated addresses on account 0, index 0. | def mnemonics(tdd):
return load_data(tdd, "mnemonics.json") | [
"def validate_mnemonics(ops: lib.objects.OpsState, path: str) -> None:\n\n logger = ops.g_logger\n\n mnemonics = validate_file(logger, path, read=True)\n if len(mnemonics.strip().split()) != 12:\n logger.error(\n f\"ERROR: There are not 12 mnemonics for a Byron random address in the mnemo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mocks the Terra instance before a request is made. | def mock_terra():
terra = Terra("soju-0013", "")
terra.lcd.request_middlewares.append(lcd_request_test_middleware)
return terra | [
"def _mock_request():\r\n return _MockRequestClient().request()",
"def default_setup(self, mocker):\n # pylama: ignore=W0201\n session_cls = mocker.patch.object(requests, 'Session')\n self.session = mocker.MagicMock()\n self.session.__enter__.return_value = self.session\n ses... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a screenshot of all screens. | def grab_screens() -> QPixmap:
# grab all screens
screens = QtWidgets.QApplication.screens()
pixmaps = []
w = 0
h = 0
for screen in screens:
pix = screen.grabWindow(0)
w += pix.width()
h = max(h, pix.height())
pixmaps.append(pix)
# merge all pixmaps
final... | [
"def get_screens(self) -> list[dict[str, Any]]:\n lst = [\n dict(\n index=i.index,\n group=i.group.name if i.group is not None else None,\n x=i.x,\n y=i.y,\n width=i.width,\n height=i.height,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return only unique elements of a list of names. | def unique_names(names):
return sorted(set(names)) | [
"def make_unique(names: Any) -> List[str]:\n return make_names(names, unique=True)",
"def get_distinct(self, elements):\n names = sorted(set(elements))\n n_elements = len(names)\n return (names, n_elements)",
"def uniq(listinput):\n\t\"\"\" This will be provided for the student. \"\"\"\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Counts the element/attribute usage based on the information found in fileinfos. | def count_items(fileinfos, type, name=""):
names = []
if is_filename(name):
# count all elements/attributes for one text
for nodeName in fileinfos[name]["usage_" + type].keys():
names.append(nodeName)
elif name == "":
# count all elements/attributes for all texts
... | [
"def count_and_draw(fileinfos, args, name=\"\"):\n els_counted = count_items(fileinfos,\"el\",name)\n atts_counted = count_items(fileinfos,\"att\",name)\n draw_figure(els_counted, atts_counted, args, name)",
"def file_stats(file_pairs):\n loc = 0\n nfiles = 0\n nsuites = 0\n ntests = 0\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dump the fileinfos to a JSON file. | def dump_to_json(fileinfos, out):
jsonarray = json.dumps(fileinfos)
json_filename = "all_elements_used.json"
text_file = open(os.path.join(out,out_dir_name,json_filename), "w")
text_file.write(jsonarray)
text_file.close()
stdout.write("... "+json_filename+" created\n") | [
"def write_json(self, data, fichier):",
"def write_info_json(path: Path, data: dict) -> None:\n\n info_json = path / 'info.json'\n\n with info_json.open('w') as output:\n json.dump(data, output)",
"def write_json(self):\n print \"writing json file...\",\n JsonDumper(self.data,\"absorp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dump the fileinfos to a CSV file. | def dump_to_csv(fileinfos, out, all_el_names, all_att_names):
uni_el_names = unique_names(all_el_names)
uni_att_names = unique_names(all_att_names)
att_names_prefixed = ["@%s" % item for item in uni_att_names]
csv_filename = "all_elements_used.csv"
# transform information from dictionary to... | [
"def output_csv(infos):\n logging.debug(\"Beginning output_csv\")\n\n for info in infos:\n print \"{};{};{};{};{};{};{};{};{}\".format(\n info[\"backup_label\"]\n ,info[\"backup_type\"]\n ,info[\"backup_timestamp_start_ts\"]\n ,info[\"backup_timestamp_stop_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the collection and XML files can be found. | def check_paths(coll_path, out):
pathpattern = os.path.join(coll_path,"*.xml")
try:
if not os.path.exists(coll_path):
raise ValueError("Error: The collection could not be found.")
except ValueError as err:
print(err)
exit(1)
try:
if not os.path.exists(out):
... | [
"def _check_integrity(self):\n root = self.root\n for scene_name in self.scene_list:\n if not(os.path.isdir(os.path.join(root,scene_name)) and \n os.path.isdir(os.path.join(root,scene_name, images_dir)) and\n os.path.isfile(os.path.join(root,scene_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if the input string is an XML filename | def is_filename(name):
test = re.search("[A-Za-z0-9_-]+\.xml$", name)
if test:
return True
else:
return False | [
"def isxml(file_name):\n # если подать json формат в файле bb.xml, то упадёт\n if file_name.endswith('.xml'):\n return True\n else:\n return False",
"def is_ooxml(filename):\n try:\n get_type(filename)\n except BadZipfile:\n return False\n except IOError: # one of t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds subplots to the figure. | def add_subplots(fig, els_counted, atts_counted, chart_info, name="", log=False):
if name != "":
if is_filename(name):
# overview of element/attribute usage for a single text
draw_chart(els_counted, fig, chart_info["elements_used_text"], log)
draw_chart(atts_counted, fig,... | [
"def addSubplot(self):\n\n ### increase the number of subplots in the figure\n\n self.totcnt += 1\n\n ### get indices of the subplot in the figure\n\n self.nx = self.totcnt%(self.tot)\n self.ny = self.totcnt/(self.tot)\n\n self.xbeg = self.beg + self.nx*self.length + self.n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count elements and attributes and draw figure | def count_and_draw(fileinfos, args, name=""):
els_counted = count_items(fileinfos,"el",name)
atts_counted = count_items(fileinfos,"att",name)
draw_figure(els_counted, atts_counted, args, name) | [
"def visualize():",
"def display_how_many():\n name = graphics.Text(graphics.Point(100, 430), 'SETS REMAINING')\n name.setSize(14)\n name.draw(window)\n box = graphics.Rectangle(graphics.Point(25, 417), graphics.Point(175, 460))\n box.setOutline('red')\n box.draw(window)",
"def figure(self) ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reduce the size of an image to the indicated maximum dimensions This function takes a PIL.Image object and integer values for the maximum allowed width and height (a zero value means no maximum constraint), calculates the size that meets those constraints and resizes the image. The resize is done in place, changing the... | def downsize_img(img: Image.Image,
max_width: int,
max_height: int) -> Tuple[Image.Image, bool]:
width, height = img.size
# Assume 0 as current size
if not max_width:
max_width = width
if not max_height:
max_height = height
if (max_width, max_height... | [
"def resizeImage(image, maxW, maxH):\n\timageW, imageH = image.size\n\tif imageW == maxW and imageH == maxH:\n\t\treturn image\n\t# find which axis requires the biggest zoom (smallest relative max dimension)\n\tzoomW = float(imageW) / float(maxW)\n\tzoomH = float(imageH) / float(maxH)\n\tzoom = max(zoomW, zoomH)\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reduce the number of colors of an Image object It takes a PIL image object and tries to reduce the total number of colors, converting it to an indexed color (mode P) image. If the input image is in mode 1, it cannot be further reduced, so it's returned back with no changes. | def do_reduce_colors(img: Image.Image,
max_colors: int) -> Tuple[Image.Image, int, int]:
orig_mode = img.mode
if orig_mode == "1":
return img, 2, 2
colors = img.getcolors()
if colors:
orig_colors = len(colors)
else:
orig_colors = 0
# Intermediate c... | [
"def reduce_color(image):\n\n # http://stackoverflow.com/questions/5906693/how-to-reduce-the-number-of-colors-in-an-image-with-opencv-in-python\n w, h, _ = image.shape\n for row in xrange(h-1):\n for col in xrange(w-1):\n #pi = row * w * 3 + col * 3\n pixel = image[col][row]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and return a sample quizz | def sample_quizz(**params):
defaults = {
'title': 'Boomer WW II Quizz',
'description': 'Are You A World War II Whiz?'
}
defaults.update(params)
return Quizz.objects.create(**defaults) | [
"def test_create_quizes(self):\n driver = self.driver\n wait = self.wait\n\n create_quizz_name(driver, wait, quiz_name)\n\n create_textual_question(driver, wait, textual_question_1)\n create_textual_question(driver, wait, textual_question_2)\n create_textual_question(driver... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves specific league matchday fixtures from API | async def _get_league_fixtures_matchday(self, server_id: str, league_id: str, matchday: str):
params = {'matchday': matchday}
url = self.api_url + 'competitions/{}/fixtures'.format(league_id)
return await self._make_request(url, params, server_id) | [
"async def _matchdayfixtures(self, ctx: commands.Context, league_id: str, matchday: str='1'):\n headers = ['ID', 'Home', ' ', ' ', 'Away']\n data = await self._get_league_fixtures_matchday(ctx.message.server.id, league_id, matchday)\n\n await self.bot.say('```diff\\n+ Matchday ' + matchday + ' ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves specific league leaderboard from API | async def _get_league_leaderboard(self, server_id: str, league_id: str, matchday: str):
if matchday is None:
matchday = ''
params = {'matchday': matchday}
url = self.api_url + 'competitions/{}/leagueTable'.format(league_id)
return await self._make_request(url, params, server... | [
"def get_player_leaderboard(timeframe=None):\n if timeframe is None:\n timeframe = 'alltime'\n\n return list(ObjectFromDict(request_legacy(\n 'https://api.wynncraft.com/public_api.php?action=statsLeaderboard&type=player&timeframe={0}',\n timeframe\n )).data)",
"def get_league(id_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves specific team info | async def _get_team_info(self, server_id: str, team_id: str):
params = {}
url = self.api_url + 'teams/{}'.format(team_id)
return await self._make_request(url, params, server_id) | [
"def get_team(self):\n try:\n team_id = self.request.GET.get('team')\n if team_id is not None:\n team_id = int(team_id)\n return self.get_available_teams().get(pk=team_id)\n return self.get_available_teams().latest()\n except (Team.DoesNot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets token for footballdata.org API | async def _tokenset(self, ctx: commands.Context, token: str):
self.config[ctx.message.server.id] = token
dataIO.save_json('data/football/config.json', self.config)
await self.bot.say('football-data API token set') | [
"def set_token(token):\n os.environ[\"DS_AUTH_TOKEN\"] = token",
"def api_token(self, api_token):\n\n self._api_token = api_token",
"def api_token(self, api_token: str):\n\n self._api_token = api_token",
"def set_token(self, token):\n if token:\n self.token = token",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets last matchday fixtures | async def _lastfixtures(self, ctx: commands.Context, league_id: str):
headers = ['ID', 'Home', 'G', ' ', 'G', 'Away']
data = await self._get_league_fixtures_timeframe(ctx.message.server.id, league_id, 'p7')
await self.bot.say('```diff\n+ Last fixtures```')
pretty_data = []
for f... | [
"async def _get_league_fixtures_matchday(self, server_id: str, league_id: str, matchday: str):\n params = {'matchday': matchday}\n url = self.api_url + 'competitions/{}/fixtures'.format(league_id)\n\n return await self._make_request(url, params, server_id)",
"async def _matchdayfixtures(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets specific matchday fixtures Defaults to matchday 1 | async def _matchdayfixtures(self, ctx: commands.Context, league_id: str, matchday: str='1'):
headers = ['ID', 'Home', ' ', ' ', 'Away']
data = await self._get_league_fixtures_matchday(ctx.message.server.id, league_id, matchday)
await self.bot.say('```diff\n+ Matchday ' + matchday + ' fixtures``... | [
"async def _get_league_fixtures_matchday(self, server_id: str, league_id: str, matchday: str):\n params = {'matchday': matchday}\n url = self.api_url + 'competitions/{}/fixtures'.format(league_id)\n\n return await self._make_request(url, params, server_id)",
"def getDayfromCityForecasts(cityF... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator for each file and directory | def files_and_folders(self):
yield from self._root.files_and_folders(0) | [
"def file_generator(self):\n for root, sub_dir, files in os.walk(self.input_dir):\n for file in files:\n yield os.path.join(root, file)",
"def iterate_dir(data_dir):\n for child in os.listdir(data_dir):\n child_path = os.path.join(data_dir, child)\n if os.path.isd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read and parse RARC from buffer. | def read(buffer) -> RARC:
# TODO: Add error checking
header = struct.unpack('>IIIIIIII', buffer[:32])
info = struct.unpack('>IIIIIIHHI', buffer[32:][:32])
rarc = RARC(*header, *info)
data = buffer[32:]
file_data = data[rarc.file_offset:][:rarc.file_length]
read_string_table(rarc, data)
... | [
"def _parseReadInfo(rr):\n desc = rr.description\n dict_start = desc.find('{')\n desc = desc[dict_start:]\n return json.loads(desc)",
"def _read_from_buffer(self, pos):\r\n self._read_bytes = self._read_delimiter = self._read_regex = None\r\n self._read_partial = False\r\n self._r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the Longest Proper Prefix which is also a Suffix (LPS) array. | def compute_lsp(pattern, patt_len, lps):
pointer = 0
lps[0] = 0
i = 1
while i < patt_len:
if pattern[i] == pattern[pointer]:
pointer += 1
lps[i] = pointer
i += 1
else:
if pointer != 0:
pointer = lps[pointer - 1]
... | [
"def get_lcp(s,sa):\n lcp = list()\n lcp.append(0)\n for i in range(1,len(sa)):\n lcp.append( longest_prefix_length(s, sa[i], sa[i-1]) )\n return lcp",
"def _longest_common_prefix_length(s1: np.ndarray, s2: np.ndarray, previous_best: Optional[float] = None) -> float:\n min_len = min(len(s1),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test adding a credential to MongoDB credential store. | def test_mdb_add_credential(self):
cred = vccs_auth.credential.from_dict(self.cred_data, None)
id_ = self.mdb.add_credential(cred)
print("Added credential -> id : {!r}".format(id_))
cred2 = self.mdb.get_credential(self.cred_data['credential_id'])
print("Fetched credential :\n{}"... | [
"def save_credential_test(self):\n self.new_credential.save_details()\n self.assertEqual(len(Credentials.credentials_list),1)",
"def test_save_creds(self):\n self.new_credentials.save_creds()\n self.assertEqual(len(Credentials.credential_list),1)",
"def save_credential_test(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test adding a duplicate credential to MongoDB credential store. | def test_mdb_add_duplicate_credential(self):
this_id = 9797
data = self.cred_data
data['credential_id'] = this_id
cred = vccs_auth.credential.from_dict(data, None)
self.mdb.add_credential(cred)
cred.derived_key(new='bb' * (512 / 8))
print cred.to_dict()
se... | [
"def test_mdb_add_credential(self):\n cred = vccs_auth.credential.from_dict(self.cred_data, None)\n id_ = self.mdb.add_credential(cred)\n print(\"Added credential -> id : {!r}\".format(id_))\n\n cred2 = self.mdb.get_credential(self.cred_data['credential_id'])\n print(\"Fetched cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test fetching unknown credential. | def test_mdb_get_unknown_credential(self):
res = self.mdb.get_credential(1234567890)
self.assertEqual(res, None) | [
"async def test_invalid_credential(mock_get, mock_post, hass: HomeAssistant) -> None:\n config = {\n DOMAIN: xiaomi.PLATFORM_SCHEMA(\n {\n CONF_PLATFORM: xiaomi.DOMAIN,\n CONF_HOST: \"192.168.0.1\",\n CONF_USERNAME: INVALID_USERNAME,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test revoking a credential. | def test_mdb_revoking_credential(self):
this_id = 9898
data = self.cred_data
data['credential_id'] = this_id
cred = vccs_auth.credential.from_dict(data, None)
self.mdb.add_credential(cred)
# assert no exception
cred2 = self.mdb.get_credential(this_id)
pr... | [
"def test_revoke(client):\n responses.add(responses.POST,\n '%s/oauth/token/revoke' % settings.API_BASE_URL,\n status=200,\n content_type='application/json'\n )\n client.revoke_authorization()\n assert client.auth.access_token == None\n assert client.auth.refresh_token == None\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the __repr__ method of a credential. | def test_mdb_credential_repr(self):
cred = vccs_auth.credential.from_dict(self.cred_data, None)
res = repr(cred)
print "Credential : {!r}".format(res)
self.assertTrue(hex(self.cred_data['key_handle']) in res)
self.assertTrue(self.cred_data['type'] in res) | [
"def test_repr(self):\n dummy = DummyCryptographicObject()\n repr(dummy)",
"def test_repr(self):\n self.assertEqual(\n repr(userbase.Preauthenticated('foo@bar')),\n '<Preauthenticated: foo@bar>')",
"def test_display_cred(self):\n self.assertEqual(Credentials.dis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This snippet to decided what type of task is given for evaluation. This is really experiment specific and needs to be updated if things change. The only use for the task types is to make the evaluation on the classes with more than 100 samples at training for the epic evaluation. If actions are trained explicitly then ... | def get_task_type_epic(action_classes, verb_classes, noun_classes):
task_types = []
if action_classes > 0:
task_types.append("EpicActions")
if verb_classes > 0:
task_types.append("EpicVerbs")
if noun_classes > 0:
task_types.append("EpicNouns")
return task_types | [
"def task_type(self):\n pass",
"def train_expert_policies(num_tasks):\n goal_env = PointMassEnv(n=num_tasks)\n goals = goal_env.goals\n which_goal = 0\n\n # for i, goal in enumerate(goals):\n train_singletask_policy(goal=goals[which_goal], idx_str=str(which_goal))",
"def test_pyt_multitask... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits a model state dictionary in subcheckpoints so that the final size of each subcheckpoint does not exceed a given size. The subcheckpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no optimization made to make each subcheckpoint as close as possible to the maximum s... | def flax_shard_checkpoint(params, max_shard_size="10GB"):
max_shard_size = convert_file_size_to_int(max_shard_size)
sharded_state_dicts = []
current_block = {}
current_block_size = 0
total_size = 0
# flatten the weights to chunk
weights = flatten_dict(params, sep="/")
for item in weigh... | [
"def test_partition_on_target_size_vertex_than_has_to_be_split(self):\n self.setup()\n large_vertex = TestVertex(1000, \"Large vertex\")\n large_vertex.add_constraint(PartitionerMaximumSizeConstraint(10))\n self.graph = ApplicationGraph(\n \"Graph with large vertex\", [large_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Cast the floatingpoint `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast the `params` in place. This method can be used on TPU to explicitly convert the model parameters to bfloat16 precision to do full halfprecision training or to save weights in bfloat16 for inference in order ... | def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):
return self._cast_floating_to(params, jnp.bfloat16, mask) | [
"def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n return self._cast_floating_to(params, jnp.float16, mask)",
"def cast_parameters_to_bf16(place, program, scope=None, to_bf16_var_names=None):\n all_parameters = []\n for block in program.blocks:\n all_parameters.extend(blo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Cast the floatingpoint `parmas` to `jax.numpy.float32`. This method can be used to explicitly convert the model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place. | def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):
return self._cast_floating_to(params, jnp.float32, mask) | [
"def data_convert2float32 (self, data):\r\n data = data.astype(np.float32)\r\n\r\n return data",
"def fp16_to_fp32(val):\n def float_conversion(val):\n val_typecheck = val\n if isinstance(val_typecheck, (Parameter, Variable)):\n val_typecheck = val.data\n if isinst... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Cast the floatingpoint `parmas` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the `params` in place. This method can be used on GPU to explicitly convert the model parameters to float16 precision to do full halfprecision training or to save weights in float16 for inference in order to ... | def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):
return self._cast_floating_to(params, jnp.float16, mask) | [
"def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):\n return self._cast_floating_to(params, jnp.bfloat16, mask)",
"def cast_parameters_to_bf16(place, program, scope=None, to_bf16_var_names=None):\n all_parameters = []\n for block in program.blocks:\n all_parameters.extend(bl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class. This API is experimental and may have some slight breaking changes in the next releases. | def register_for_auto_class(cls, auto_class="FlaxAutoModel"):
if not isinstance(auto_class, str):
auto_class = auto_class.__name__
import transformers.models.auto as auto_module
if not hasattr(auto_module, auto_class):
raise ValueError(f"{auto_class} is not a valid auto... | [
"def register(cls):\n register(cls, cls.provided_class)",
"def register(cls, class_):\n cls._registered[class_.tag()] = class_",
"def register(cls):\n activations[cls.__name__] = cls\n\n return cls",
"def register_model(cls, model_class: BaseModelParamsT) -> BaseModelParamsT:\n key = cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
values as a dictionary is not hashable and hence cannot be used directly in the explored/visited set. This function changes values dict into a unique hashable string which can be used in the explored set. You may or may not use this | def convertStateToHash(values):
l = list(sorted(values.items()))
modl = [a+b for (a, b) in l]
return ''.join(modl) | [
"def value_set(d):\n return set(d.itervalues())",
"def hash_locale_dictionary(dictionary):\n hash_value = 0\n \n for key, value in dictionary.items():\n hash_value ^= hash(key.value) & hash(value)\n \n return hash_value",
"def hash_values(self, key):\n return juxt(self.hash_funct... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is used by '/book/search/' it can check whether the inputs are keyword of a book or isbn | def is_isbn_or_keyword(inputs):
isbn_or_keyword='keyword'
if len(inputs)==13 and inputs.isdigit():
isbn_or_keyword='isbn'
short_inputs=inputs.strip('-')
if '-' in inputs and short_inputs.isdigit() and len(short_inputs)==10:
isbn_or_keyword='isbn'
return isbn_or_keyword | [
"def book_search():\r\n load_book_data()\r\n criteria, book_to_search = input('Enter Book to search (use format : isbn/author/title detail) : ').split(' ')\r\n if criteria == 'isbn':\r\n for _ in book.book_list:\r\n if _.isbn == int(book_to_search):\r\n print('BOOK FOUND !'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes rows where 'DESC' == 'RECOVR AUD' (not 'REGULAR'). These caused duplicate entries when grouping by turnstile & datetime. Removes DESC column. Fixes EXITS column name. | def clean_data(df_turnstiles):
# sort values in a such a way that the duplicate values sit directly below the originals, so they will be removed.
df_turnstiles.sort_values(
["C/A", "UNIT", "SCP", "STATION", "DATE_TIME"],
inplace=True,
ascending=False,
)
... | [
"def filter_has_description(self):\n\t\tself.df = self.df[self.df[\"descriptions\"] != \"\"] \n\t\tself._update_dictionaries()",
"def removeSortCriterion():",
"def clean_recs(self):\n to_remove = [] # indices of recs to remove\n for index, rec in enumerate(self.recs):\n rec['text'] = r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds 'AMPM' and 'DAY_NAME' columns to the dataFrame. | def add_dt_cols(df_turnstiles):
df_turnstiles["AMPM"] = (
pd.DatetimeIndex(df_turnstiles["TIME"]).strftime("%r").str[-2:]
)
df_turnstiles["DAY_NAME"] = pd.to_datetime(df_turnstiles["DATE"]).dt.day_name()
return df_turnstiles | [
"def __append_columns(self, new_dataframe):\n self.dataframe = pd.merge(self.dataframe, new_dataframe)",
"def augment_dataframe(self, df: pd.DataFrame) -> pd.DataFrame:",
"def set_forecast_columns (self):\n years = range(self.start_year,self.end_year)\n self.forecast.add_heating_fuel_column... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function adds ZIPCODE and ZIPCODE_AGI columns to the dataFrame. | def merge_zipcode_agi(df_turnstiles):
# define URLs for MTA Station data & IRS Income Info
mta_url = "http://web.mta.info/developers/data/nyct/subway/Stations.csv"
irs_url = "https://www.irs.gov/pub/irs-soi/18zpallagi.csv"
# collect & clean MTA station info
mta_station_info = p... | [
"def add_loc_cols(df):\r\n\r\n\tdf['STATE'] = [int(i[1:3]) for i in df.gisjoin]\r\n\tdf['COUNTY'] = [int(i[4:7]) for i in df.gisjoin]\r\n\tdf['TRACT'] = [int(i[7:-4]) for i in df.gisjoin]\r\n\tdf['BLOCK'] = [int(i[-4:]) for i in df.gisjoin]\r\n\r\n\tif df.STATE[0] > 9:\r\n\t\traise Exception(\"Warning! Code might b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean entries and exits column. Returns a dataFrame grouped by individual turnstile and AM/PM. Entries & exit columns converted from cumulative > change from previous value | def fixup_entries_exits(df_turnstiles):
# group data by AMPM, taking the maximum entries/exits for each date
ampm_station_group = df_turnstiles.groupby(
["C/A", "UNIT", "SCP", "STATION", "DATE", "AMPM", "DAY_NAME",],
as_index=False,
)
df_ampm = ampm_station_group... | [
"def clean_data(df_turnstiles):\n\n # sort values in a such a way that the duplicate values sit directly below the originals, so they will be removed.\n df_turnstiles.sort_values(\n [\"C/A\", \"UNIT\", \"SCP\", \"STATION\", \"DATE_TIME\"],\n inplace=True,\n ascending=F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Proxy function for the tracking pts logger service. Used to start and stop logging. | def tracking_pts_logger_proxy(namespace,cmd,filename):
srv = '{0}/logging_cmd'.format(namespace)
proxy = rospy.ServiceProxy(srv,LoggingCmd)
try:
resp = proxy(cmd,filename)
flag = resp.flag
except rospy.ServiceException, e:
flag = False
return flag | [
"def _start_logging(self, *args, **kwargs):\n self._do_cmd_resp(Command.STARTNOW, *args, **kwargs)",
"def log_service(func):\n\n @wraps(func)\n def service_logger(*args, **kwargs):\n servicename = func.__name__\n logger.info(f\"Starting {servicename} dodola service\")\n func(*arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path to the small test database. | def db_small_path():
return os.path.join(_here, 'fixtures/databases/db-small/database') | [
"def get_test_database_path() -> str:\n test_suite_dir = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(test_suite_dir, \"testDb.sqlite\")",
"def db_path_with_improper_files():\n return os.path.join(_here, 'fixtures/databases/db-improper/database')",
"def database_files_path(test_tmpd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path to the test database with improper files. | def db_path_with_improper_files():
return os.path.join(_here, 'fixtures/databases/db-improper/database') | [
"def db_python_only():\n return os.path.join(_here, 'fixtures/databases/db-python-only/database')",
"def get_test_database_path() -> str:\n test_suite_dir = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(test_suite_dir, \"testDb.sqlite\")",
"def test_unknown_database_path(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path to the pythononly test database. | def db_python_only():
return os.path.join(_here, 'fixtures/databases/db-python-only/database') | [
"def get_test_database_path() -> str:\n test_suite_dir = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(test_suite_dir, \"testDb.sqlite\")",
"def db_path_with_improper_files():\n return os.path.join(_here, 'fixtures/databases/db-improper/database')",
"def get_db_path():\n return os... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path to the Java CVE record. | def java_record_path():
return os.path.join(_here, 'fixtures/records/java-2018-10237.yaml') | [
"def get_eve_path():\n return '{}\\\\CCP\\\\EVE'.format(get_appdata())",
"def python_record_path():\n return os.path.join(_here, 'fixtures/records/python-2016-10516.yaml')",
"def pvi_path(self):\n pvi_name = next(self._metadata.iter(\"PVI_FILENAME\")).text\n pvi_name = pvi_name.split(\"/\")\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path to the Python CVE record. | def python_record_path():
return os.path.join(_here, 'fixtures/records/python-2016-10516.yaml') | [
"def java_record_path():\n return os.path.join(_here, 'fixtures/records/java-2018-10237.yaml')",
"def get_eve_path():\n return '{}\\\\CCP\\\\EVE'.format(get_appdata())",
"def version_file_path() -> str:\n return os.path.join(HERE, \"version.json\")",
"def api_key_file_path(self):\n return self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path to the invalid CVE record. | def invalid_record_path():
return os.path.join(_here, 'fixtures/records/invalid.yaml') | [
"def get_err_file_path(self) -> str:\n return self._err_file.name if self._err_file is not None else \"\"",
"def get_eve_path():\n return '{}\\\\CCP\\\\EVE'.format(get_appdata())",
"def InvalidEvcReferenceId(self):\n return self._get_attribute('invalidEvcReferenceId')",
"def __get_path_from_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Path to the unparseable CVE record. | def unparseable_record_path():
return os.path.join(_here, 'fixtures/records/unparseable.yaml') | [
"def get_eve_path():\n return '{}\\\\CCP\\\\EVE'.format(get_appdata())",
"def __get_path_from_vuln(self, vuln):\n path_search = re.search(\"(?P<url>https?://[^\\s]+)\", vuln)\n path = path_search.group('url') if path_search else \"\"\n return path",
"def invalid_record_path():\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GIT URL with YAML data. | def git_url():
return "https://github.com/tisnik/victimsdb-sample-data.git" | [
"def get_api_url(self):\n\n url = 'https://api.{}/repos/{}/{}/git/'.format(HOST_GITHUB, \\\n self.repo, self.product)\n return url",
"def format_url(self, data):\n git_url = urlparse(data[\"git_url\"])\n\n url = \"oauth2:{0}@{1}\".format(data[\"token\"], git_url.netloc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mock hue entry setup. | def hue_setup_fixture():
with patch("homeassistant.components.hue.async_setup_entry", return_value=True):
yield | [
"async def test_setup_zha(hass: HomeAssistant) -> None:\n mock_integration(hass, MockModule(\"hassio\"))\n\n # Setup the config entry\n config_entry = MockConfigEntry(\n data={},\n domain=DOMAIN,\n options={},\n title=\"Home Assistant Yellow\",\n )\n config_entry.add_to_ha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a mocked Discovered Bridge. | def get_discovered_bridge(bridge_id="aabbccddeeff", host="1.2.3.4", supports_v2=False):
return Mock(host=host, id=bridge_id, supports_v2=supports_v2) | [
"def mock_bridge(hass):\n return create_mock_bridge(hass)",
"def mock_bridge(hass):\n return create_mock_bridge()",
"def create_mock_bridge():\n bridge = Mock(\n available=True,\n allow_unreachable=False,\n allow_groups=False,\n api=Mock(),\n spec=hue.HueBridge\n )... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test config flow discovers two bridges. | async def test_flow_two_bridges_discovered_one_new(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
create_mock_api_discovery(aioclient_mock, [("1.2.3.4", "bla"), ("5.6.7.8", "beer")])
MockConfigEntry(
domain="hue", unique_id="bla", data={"host": "1.2.3.4"}
).add_to_hass(hass... | [
"async def test_flow_discovered_bridges(opp, aioclient_mock):\n aioclient_mock.get(\n pydeconz.utils.URL_DISCOVER,\n json=[\n {\"id\": BRIDGEID, \"internalipaddress\": \"1.2.3.4\", \"internalport\": 80},\n {\"id\": \"1234E567890A\", \"internalipaddress\": \"5.6.7.8\", \"intern... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if a unknown error happened during the linking processes. | async def test_flow_link_unknown_error(hass: HomeAssistant) -> None:
disc_bridge = get_discovered_bridge()
with patch(
"homeassistant.components.hue.config_flow.discover_nupnp",
return_value=[disc_bridge],
):
result = await hass.config_entries.flow.async_init(
const.DOMAI... | [
"def _errcheck_link(value, func, args): # pylint: disable=W0613\n # The windows api returns nonzero if the call was successful\n if value != 0:\n return\n\n last_error = ctypes.windll.kernel32.GetLastError()\n # Somehow CreateSymbolicLinkW and CreateHardLinkW retuns zero\n # and the last erro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that we clean up entries for same host and bridge. An IP can only hold a single bridge and a single bridge can only be accessible via a single IP. So when we create a new entry, we'll remove all existing entries that either have same IP or same bridge_id. | async def test_creating_entry_removes_entries_for_same_host_or_bridge(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
create_mock_api_discovery(aioclient_mock, [("2.2.2.2", "id-1234")])
orig_entry = MockConfigEntry(
domain="hue",
data={"host": "0.0.0.0", "api_key": "1234... | [
"def test_delete_collection_host_subnet(self):\n pass",
"def test_delete_host_subnet(self):\n pass",
"def test_delete_all_bank_connections(self):\n pass",
"def test_duplicates(self):\n\n for i in xrange(0, 99):\n inventory = get_inventory()\n ips = collections... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a bridge being discovered via HomeKit. | async def test_bridge_homekit(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
create_mock_api_discovery(aioclient_mock, [("0.0.0.0", "bla")])
result = await hass.config_entries.flow.async_init(
const.DOMAIN,
context={"source": config_entries.SOURCE_HOMEKIT},
dat... | [
"def test_home_bridge(mock_pre_serv):\n bridge = HomeBridge('TestBridge', 'test.bridge', b'123-45-678')\n\n assert bridge.display_name == 'TestBridge'\n assert bridge.pincode == b'123-45-678'\n assert len(bridge.services) == 2\n\n assert bridge.services[0].display_name == SERV_ACCESSORY_INFO\n ass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if a HomeKit discovered bridge has already been configured. | async def test_bridge_homekit_already_configured(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
create_mock_api_discovery(aioclient_mock, [("0.0.0.0", "aabbccddeeff")])
MockConfigEntry(
domain="hue", unique_id="aabbccddeeff", data={"host": "0.0.0.0"}
).add_to_hass(hass)
... | [
"def _is_ifc_attached_elsewhere(ifc, bridge):\n br_list = subprocess.check_output(['bash', '-c', 'brctl show']).splitlines()\n output = []\n for line in br_list[1:]:\n if line.startswith('\\t'):\n output[len(output) - 1] = output[len(output) - 1] + line\n else:\n output.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test options config flow for a V1 bridge. | async def test_options_flow_v1(hass: HomeAssistant) -> None:
entry = MockConfigEntry(
domain="hue",
unique_id="aabbccddeeff",
data={"host": "0.0.0.0"},
)
entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] == "... | [
"async def test_simple_option_flow(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n config_entry = await setup_unifi_integration(\n hass,\n aioclient_mock,\n clients_response=CLIENTS,\n wlans_response=WLANS,\n dpigroup_response=DPI_GROUPS,\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test options config flow for a V2 bridge. | async def test_options_flow_v2(hass: HomeAssistant) -> None:
entry = MockConfigEntry(
domain="hue",
unique_id="aabbccddeeff",
data={"host": "0.0.0.0", "api_version": 2},
)
entry.add_to_hass(hass)
dev_reg = dr.async_get(hass)
mock_dev_id = "aabbccddee"
dev_reg.async_get_o... | [
"def test_config_options(flowserv_cli):\n result = flowserv_cli.invoke(cli, ['config'])\n assert result.exit_code == 0",
"async def test_options_flow_live_tv_in_apps(\n hass: HomeAssistant, client, apps, inputs\n) -> None:\n client.apps = apps\n client.inputs = inputs\n entry = await setup_webos... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a bridge being discovered by zeroconf already exists. | async def test_bridge_zeroconf_already_exists(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
create_mock_api_discovery(
aioclient_mock, [("0.0.0.0", "ecb5faabcabc"), ("192.168.1.217", "ecb5faabcabc")]
)
entry = MockConfigEntry(
domain="hue",
source=config_en... | [
"def bridge_exists(br):\n cmd = \"ovs-vsctl br-exists {}\".format(br)\n result = __salt__[\"cmd.run_all\"](cmd)\n retcode = result[\"retcode\"]\n return _retcode_to_bool(retcode)",
"async def test_bridge_homekit_already_configured(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test a bridge being discovered by zeroconf and ipv6 address. | async def test_bridge_zeroconf_ipv6(hass: HomeAssistant) -> None:
result = await hass.config_entries.flow.async_init(
const.DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
data=zeroconf.ZeroconfServiceInfo(
host="fd00::eeb5:faff:fe84:b17d",
addresses=["fd0... | [
"def SupportsIPv6(self) -> bool:",
"def test_ipv6_in_net(self):\n test_ip = ip_address.IPAddress(\"2001:0db8:85a3:08d3:1319:8a2e:0370:7344/24\")\n assert test_ip.in_network(\"2001:0d00::/24\")\n assert test_ip.in_network(\"2001:0d00::/29\")",
"def bridge_network_check(ip, bridge_ip, bridge_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an error for given Y and T. Differs for classification and multiclass. | def _error(self, Y, T):
err = np.mean((Y - T)**2)
return err | [
"def _error(self, T, Y, R=None):\n if R is None: # normal classification error\n if self.classification == \"c\":\n err = np.not_equal(Y.argmax(1), T.argmax(1)).mean()\n elif self.classification == \"wc\": # weighted classification\n c = T.shape[1]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Leave only neurons with the given indexes. | def _prune(self, idx):
idx = list(idx)
neurons = []
for nold in self.neurons:
k = nold[1] # number of neurons
ix1 = [i for i in idx if i < k] # index for current neuron type
idx = [i-k for i in idx if i >= k]
func = nold[0]
number = l... | [
"def remove_indexes(self, indexes):\n # Create a set of the rows (as int) to delete\n selected_rows = set()\n for index in indexes:\n selected_rows.add(index.row())\n\n # Delete all of them one by one (easy but maybe not the best performance-wise)\n for index, row in en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to transform dataframe to array | def df_to_array(datasample):
return np.array(datasample) | [
"def transform(self, data_frame: pd.DataFrame) -> np.array:\n pass",
"def transform_to_matrix(df):\n return np.array(df)",
"def column_as_array(df, column_name):\n return np.array(df[column_name])",
"def get_data_matrix(df):\n return df[[\"Open\", \"High\", 'Low', \"Close\"]].to_numpy()",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the full PDS path for a given HRSC data file | def generatePdsPath(filePrefix):
# File prefix looks like this: hHXXX_DDDD_SSS
fileType = '.img'
# Extract the run number --> HXXX
runNum = filePrefix[1:5]
filename = filePrefix + fileType
baseUrl = "http://pds-geosciences.wustl.edu/mex/mex-m-hrsc-5-refdr-mapprojected-v2/me... | [
"def _get_data_path(data_file):\n this_file_dir = os.path.dirname(__file__)\n return this_file_dir + \"/data/{}\".format(data_file)",
"def getDataPath():\n\treturn \"..\" + os.sep + \"data\" + os.sep",
"def get_path_to_partitioned_data():\n return abspath(os.path.join(path, \"../data/partitioned/\"))",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Numpy version of vplane_2_vparam | def np_vplane_2_vparam(vplane):
vparam = np.cross(
vplane,
np.stack([-vplane[...,1], vplane[...,0], np.zeros_like(vplane[...,0])], axis=-1),
axis=-1)
return vparam[..., :2] / vparam[..., [2]] | [
"def np_vparam_2_vplane(vparam):\n d = np.linalg.norm(vparam, ord=2, axis=-1, keepdims=True)\n a = vparam[..., [0]] / d\n b = vparam[..., [1]] / d\n neg_sign = (a < 0)\n a[neg_sign] = -a[neg_sign]\n b[neg_sign] = -b[neg_sign]\n c = -(a * vparam[..., [0]] + b * vparam[..., [1]])\n vplane = np... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Numpy version of vparam_2_vplane | def np_vparam_2_vplane(vparam):
d = np.linalg.norm(vparam, ord=2, axis=-1, keepdims=True)
a = vparam[..., [0]] / d
b = vparam[..., [1]] / d
neg_sign = (a < 0)
a[neg_sign] = -a[neg_sign]
b[neg_sign] = -b[neg_sign]
c = -(a * vparam[..., [0]] + b * vparam[..., [1]])
vplane = np.concatenate(... | [
"def np_vplane_2_vparam(vplane):\n vparam = np.cross(\n vplane,\n np.stack([-vplane[...,1], vplane[...,0], np.zeros_like(vplane[...,0])], axis=-1),\n axis=-1)\n return vparam[..., :2] / vparam[..., [2]]",
"def hyperplane_projection(params, args):\n beta, coefs = args\n return np.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override private function that sets all the links for the contents to download on FOMC website from from_year (=min(2015, from_year)) to the current most recent year | def _get_links(self, from_year):
self.links = []
self.titles = []
self.speakers = []
self.dates = []
r = requests.get(self.calendar_url)
soup = BeautifulSoup(r.text, "html.parser")
if self.verbose:
print("Getting links for press conference scripts...... | [
"def _get_links(self, from_year):\n self.links = []\n self.titles = []\n self.speakers = []\n self.dates = []\n\n if self.verbose:\n print(\"Getting links for testimony...\")\n to_year = datetime.today().strftime(\"%Y\")\n\n if from_year < 1996:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the folder contain the expected number of episodes and if they are complete. | def check_folder(env_name, number_episodes):
path = os.path.join(os.environ["SRL_DATASET_PATH"], 'sample_benchmark2', env_name)
# List number of folders check if match expected
environments_count = 0
for filename in os.listdir(path):
try:
int_filename = int(filename)
en... | [
"def has_finished_episode(self):\n if self.num_steps_taken == 0:\n return False\n\n if self.evaluating:\n return False\n\n done = self.num_steps_taken % self.episode_length == 0\n if done:\n self.finished_episode_tasks()\n\n # We evaluate our greed... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform all useful analysis and direct the output via the Analysis'formatter. It analyses the scratch memory usage in DM1, DM2 and none, per priority and per task. [in] self Pointer to the current object | def run_all(self):
self.formatter.section_start('Scratch Memory Info')
self.formatter.section_start('Per priority')
self.analyse_per_priority()
self.formatter.section_end()
self.formatter.section_start('Per task')
self.analyse_per_task()
self.formatter.section_end... | [
"def analyse_per_priority(self):\n dm1_total = 0\n dm2_total = 0\n none_total = 0\n dm1_size = []\n dm2_size = []\n none_size = []\n users = []\n pdd = self.chipdata.get_var_strict('$_per_prio_data')\n num_entries = len(pdd.members)\n\n for curre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
analyse_per_priority() displays the total scratch memory allocations in DM1, DM2 and none and their values per each priority level. Furthermore, it also displays the total number of users per each priority level. The function reads and stores the allocations info from per_prio_data in the first for loop in order to dis... | def analyse_per_priority(self):
dm1_total = 0
dm2_total = 0
none_total = 0
dm1_size = []
dm2_size = []
none_size = []
users = []
pdd = self.chipdata.get_var_strict('$_per_prio_data')
num_entries = len(pdd.members)
for current in range(0, n... | [
"def run_all(self):\n self.formatter.section_start('Scratch Memory Info')\n self.formatter.section_start('Per priority')\n self.analyse_per_priority()\n self.formatter.section_end()\n self.formatter.section_start('Per task')\n self.analyse_per_task()\n self.formatter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
analyse_per_task() displays the scratch memory info per task. It can take one parameter that represents the task id and it will display the info for it. The function goes through the linked list and if no value is passed to it, it displays the complete list. Otherwise, it displays the info for the task with the id inpu... | def analyse_per_task(self, task_id=None):
per_task = self.chipdata.cast(
self.chipdata.get_var_strict('$_first_scratch_mem').address,
'scratch_per_task_data'
)
matching_id = False
for sc_table in self.parse_linked_list(per_task.address, 'next'):
if (ta... | [
"def _show_task(task, depth=0):\n indent = \" \"*depth\n # get people associated with this task\n people = query_with_results(\"select person.name from (person inner join task_person_pair on person.id = task_person_pair.person) where task_person_pair.task = ?\", [task[0]])\n people_string = \", \".join(map(lam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates confusion matrix with true labels along rows and predicted labels along columns. Assumes df contains columns "label"=>True labels and "classification"=>Predicted labels | def confusion_matrix(df):
rows, true_counts = np.unique(df["label"].values, return_counts=True)
cols, predicted_counts = np.unique(df["label"].values, return_counts=True)
matrix = np.ndarray(shape=(len(rows), len(cols)), dtype=float)
for ri, row in enumerate(rows):
for ci, col in enumerate(cols... | [
"def Confusion_Matrix(predicted_labels: list, actual_labels: list):\n labels = set(actual_labels)\n\n predicted_labels = list(map(custom_round, predicted_labels))\n\n matrix = pd.DataFrame(index=labels, columns=labels)\n\n matrix = matrix.fillna(0)\n\n for i in range(len(actual_labels)):\n mat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the current process already has a CUDA context created. Returns ``False`` if current process has no CUDA context created, otherwise returns the index of the device for which there's a CUDA context. | def has_cuda_context():
init_once()
if not nvmlInitialized:
return False
for index in range(device_get_count()):
handle = pynvml.nvmlDeviceGetHandleByIndex(index)
if hasattr(pynvml, "nvmlDeviceGetComputeRunningProcesses_v2"):
running_processes = pynvml.nvmlDeviceGetComput... | [
"def is_cuda(self):\n return self.share.is_cuda",
"def is_cuda(self):\n return self._tensor.is_cuda",
"def cuda_support(self):\n return self._ctx.context.cuda_support",
"def _current_device_index(self) -> int:\n device = PArray._get_current_device()\n if device is None: # n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that NewickTokenizer without arg raises ValueError. | def test_no_arg(self):
self.assertRaises(ValueError, NewickTokenizer) | [
"def test_label(self):\n nt = NewickTokenizer(newick=\"(a\\n'b',(b,c),(d,e));\")\n self.assertRaises(ValueError, nt.tokens)",
"def test_extra_closed(self):\n nt = NewickTokenizer(newick='(a,(b,c)));')\n self.assertRaises(ValueError, nt.tokens)",
"def test_tokenize_bad_input(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests Newick with extra close parens generate errors. | def test_extra_closed(self):
nt = NewickTokenizer(newick='(a,(b,c)));')
self.assertRaises(ValueError, nt.tokens) | [
"def test_bad_parens(self):\r\n with self.assertRaisesRegexp(Exception, 'Unknown parenthesis'):\r\n preview.LatexRendered('x^2', parens='not parens')",
"def test_parse_newick(self):\r\n # confirm that it works without escaped names\r\n t1 = ('((((tax7:0.1,tax3:0.2):.98,tax8:.3, tax... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests behavior of peek when there are no more tokens. | def test_peek_none(self):
nt = NewickTokenizer(newick='(a,(b,c));')
nt.tokens()
self.assertIsNone(nt._peek()) | [
"def peek(self):\n peek_at = self.pos - 1\n return None if peek_at < 0 else self.tokens[peek_at].type",
"def _peek(tokens, n=0):\n return tokens.peek(n=n, skip=_is_comment, drop=True)",
"def test_cant_peek_empty(empty_deque):\n assert empty_deque.peek() is None",
"def test_deque_peek(sampl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that unclosed [] comments generate errors. | def test_unclosed_comment(self):
nt = NewickTokenizer(newick='(a,(b,c),[(d,e));')
self.assertRaises(ValueError, nt.tokens) | [
"def test_mixed_comments(self):\n self.assert_okay(\"mixed-comments\")",
"def test_unicode_comments(self):\n self._do_test(\n ['Hi there!', 'This is an element in a list of strings.'],\n ensure_binary(dedent(u\"\"\"\n [\n 'Hi there!',\n # This is a comment with ‘sneaky‘ unic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that terminating ; is not preceded by ,. | def test_comma_bef_semicolon(self):
nt = NewickTokenizer(newick='(a,(b,c),(d,e)),;')
self.assertRaises(ValueError, nt.tokens) | [
"def test_trailing_semicolon(self):\n self._test_transform('1 + 2; 3 + 4;', \"[BinOpCode('OP_ADD', Push(0x01), Push(0x02)), BinOpCode('OP_ADD', Push(0x03), Push(0x04))]\")",
"def _check_semicolon_else_skip(self, symbol):\n if symbol.type == self.scanner.SEMICOLON:\n pass\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that unquoted labels with newline character generate errors. | def test_label(self):
nt = NewickTokenizer(newick="(a\n'b',(b,c),(d,e));")
self.assertRaises(ValueError, nt.tokens) | [
"def test_on_no_newlines(self):\n assert len(lint(self.text_with_no_newline)) == 1",
"def CheckLabel(Line): \n for i in Line:\n if i == '\\t': #can't detect leading tabs, stops at the first \\ \n raise InputError(Line,\"malformed input\") \n elif i != ' ':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that quoting edge info generates no error and string edge length. | def test_quoted_edge_info(self):
exp = ['(', 'a', ',', '(', 'b', ',', 'c', ')', ':', '4', ',',
'(', 'd', ',', 'e', ')', ')', ';']
self._do_test("(a,(b,c):'4',(d,e));", exp) | [
"def test_same_length_emtpy_strings_2(self):\n self.assertFalse(hw4.same_length('','a',''))",
"def test_general_subset_invalid_space():\n pass",
"def test_rectangle_has_string_width():\n with pytest.raises(ValueError):\n Rectangle(name=\"прямоугольник\", length=1, width='abc').check_values()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Part of the testing harness. Writes `content`, the parses and compares to `expected`. | def _do_test(self, content, expected):
self.assertEqual(list(NewickTokenizer(StringIO(content))), expected)
self.assertEqual(list(NewickTokenizer(newick=content)), expected)
fp = path_map.next_unique_scratch_filepath('tok_test')
try:
write_to_filepath(content, fp)
... | [
"def test_content():\n # PREPARE\n expected_f = open(\n 'tests/pages/expected/stepanenkoartem-github-io.html',\n 'rb',\n )\n expected_dom = BeautifulSoup(\n expected_f.read(),\n 'html.parser',\n )\n\n actual_f = open(\n os.path.join(TEMP_DIR, path.for_page(URL)),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |