query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Test case for the validate_str_substitution function when no specifier is provided for a single value.
def test_single_specifier_missing(self): template = 'missing' value_count = 1 msg = 'The formatter should contain one "{}" specifier.' with six.assertRaisesRegex(self, ValidationError, msg): validate_str_substitution(template, value_count)
[ "def test_single_specifier_needed(self):\n template = '{0} one too many {1}'\n value_count = 1\n msg = ('The formatter should only contain one '\n '\"{}\" specifier for the source field.')\n with six.assertRaisesRegex(self, ValidationError, msg):\n validate_str_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for the validate_str_substitution function when not enough specifiers are provided for multiple values.
def test_mult_specifiers_missing(self): template = '{0} too few {1}' value_count = 3 msg = ('The formatter contains too few "{}" ' 'specifiers for the number of source fields.') with six.assertRaisesRegex(self, ValidationError, msg): validate_str_substitution(t...
[ "def test_too_many_specifiers(self):\n template = '{0} too {1} many {2}'\n value_count = 2\n msg = ('The number of \"{}\" specifiers in the formatter '\n 'exceeds the number of source fields.')\n with six.assertRaisesRegex(self, ValidationError, msg):\n validate_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for the validate_str_substitution function when there is no template and no values.
def test_no_template_or_value(self): template = None value_count = 0 try: validate_str_substitution(template, value_count) except ValidationError: self.fail('Name raised ValidationError unexpectedly')
[ "def test_str_replace_invalid_param_types(self):\n\n snippet = {'str_replace': {'template': 12345,\n 'params': {'var1': 'foo', 'var2': 'bar'}}}\n\n tmpl = parser.Template(hot_tpl_empty)\n\n self.assertRaises(TypeError, tmpl.resolve_replace, snippet)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a timeframe when the start is before the end.
def test_start_before_end(self): start = timezone.now() end = start + timedelta(seconds=1) actual = validate_timeframe(start, end) expected = None self.assertEqual(actual, expected)
[ "def test_end_before_start(self):\n start = timezone.now()\n end = start - timedelta(seconds=1)\n with six.assertRaisesRegex(self, ValidationError, self.msg):\n validate_timeframe(start, end)", "def in_time_frame(startTime, endTime, lowerbound, upperbound):\n arw_lowerbound = ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a timeframe when the start is the same as the end.
def test_start_and_end_equal(self): start = timezone.now() end = start with six.assertRaisesRegex(self, ValidationError, self.msg): validate_timeframe(start, end)
[ "def test_start_before_end(self):\n start = timezone.now()\n end = start + timedelta(seconds=1)\n actual = validate_timeframe(start, end)\n expected = None\n self.assertEqual(actual, expected)", "def test_end_before_start(self):\n start = timezone.now()\n end = sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a timeframe when the end is before the start.
def test_end_before_start(self): start = timezone.now() end = start - timedelta(seconds=1) with six.assertRaisesRegex(self, ValidationError, self.msg): validate_timeframe(start, end)
[ "def test_start_before_end(self):\n start = timezone.now()\n end = start + timedelta(seconds=1)\n actual = validate_timeframe(start, end)\n expected = None\n self.assertEqual(actual, expected)", "def in_time_frame(startTime, endTime, lowerbound, upperbound):\n arw_lowerbound ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a name that starts with '$'.
def test_starts_with_dollar_sign(self): with self.assertRaises(ValidationError): db_name_validator('$id')
[ "def test_ends_with_dollar_sign(self):\n try:\n field_name_validator('id$')\n except ValidationError:\n self.fail('Field name raised ValidationError unexpectedly')", "def test_starts_with_dollar_sign(self):\n with self.assertRaises(ValidationError):\n field_na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a name that ends with '$'.
def test_ends_with_dollar_sign(self): with self.assertRaises(ValidationError): db_name_validator('id$')
[ "def test_ends_with_dollar_sign(self):\n try:\n field_name_validator('id$')\n except ValidationError:\n self.fail('Field name raised ValidationError unexpectedly')", "def have_dollar_symbol(l):\r\n if \"$\" in str(l):\r\n return 1\r\n else:\r\n return 0", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a name that contains an underscore.
def test_underscore(self): try: db_name_validator('logstash_') except ValidationError: self.fail('Name raised ValidationError unexpectedly')
[ "def to_underscore(name):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "def have_underscore_symbol(l):\r\n if \"_\" in str(l):\r\n return 1\r\n else:\r\n return 0", "def _is_sunder(name):\n return (name[0] == name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a field name with an 'at' sign.
def test_at_sign(self): with self.assertRaises(ValidationError): db_name_validator('@timestamp')
[ "def test_at_sign(self):\n try:\n field_name_validator('@timestamp')\n except ValidationError:\n self.fail('Name raised ValidationError unexpectedly')", "def test_asterisk(self):\n with self.assertRaises(ValidationError):\n field_name_validator('logstash*')", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a reserved field name.
def test_reserved_name(self): with self.assertRaises(ValidationError): field_name_validator('_id')
[ "def test_nonreserved_name(self):\n try:\n field_name_validator('_identifier')\n except ValidationError:\n self.fail('Field name raised ValidationError unexpectedly')", "def test_name_mandatory(self):\n field = self.base_field\n del field['name']\n with sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a nonreserved field name.
def test_nonreserved_name(self): try: field_name_validator('_identifier') except ValidationError: self.fail('Field name raised ValidationError unexpectedly')
[ "def test_reserved_name(self):\n with self.assertRaises(ValidationError):\n field_name_validator('_id')", "def test_name_mandatory(self):\n field = self.base_field\n del field['name']\n with self.assertRaises(FieldSchemaError):\n SchemaField(field)\n # no b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a field name that starts with '$'.
def test_starts_with_dollar_sign(self): with self.assertRaises(ValidationError): field_name_validator('$id')
[ "def test_ends_with_dollar_sign(self):\n try:\n field_name_validator('id$')\n except ValidationError:\n self.fail('Field name raised ValidationError unexpectedly')", "def test_starts_with_dollar_sign(self):\n with self.assertRaises(ValidationError):\n db_name_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a field name that ends with '$'.
def test_ends_with_dollar_sign(self): try: field_name_validator('id$') except ValidationError: self.fail('Field name raised ValidationError unexpectedly')
[ "def test_ends_with_dollar_sign(self):\n with self.assertRaises(ValidationError):\n db_name_validator('id$')", "def test_starts_with_dollar_sign(self):\n with self.assertRaises(ValidationError):\n field_name_validator('$id')", "def test_starts_with_dollar_sign(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a field name with an asterisk.
def test_asterisk(self): with self.assertRaises(ValidationError): field_name_validator('logstash*')
[ "def test_should_name_field(self):\n self.assertIn(\"name\", self.fields)", "def field_match(pattern, field):\n if pattern:\n return re.match(pattern, field)\n return True", "def test_normalize_star_name(self):\n self.assertEqual(normalize_star_name(\"RR LYR\"), \"RR LYR\")\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a field name with an 'at' sign.
def test_at_sign(self): try: field_name_validator('@timestamp') except ValidationError: self.fail('Name raised ValidationError unexpectedly')
[ "def test_at_sign(self):\n with self.assertRaises(ValidationError):\n db_name_validator('@timestamp')", "def test_asterisk(self):\n with self.assertRaises(ValidationError):\n field_name_validator('logstash*')", "def have_at_symbol(l):\n if \"@\" in str(l):\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a field name with a space.
def test_white_space(self): with self.assertRaises(ValidationError): field_name_validator('user id')
[ "def test_nonreserved_name(self):\n try:\n field_name_validator('_identifier')\n except ValidationError:\n self.fail('Field name raised ValidationError unexpectedly')", "def test_reserved_name(self):\n with self.assertRaises(ValidationError):\n field_name_vali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a .pem file.
def test_pem(self): mock_fieldfile = Mock() mock_fieldfile.name = 'good_file_name.pem' try: key_file_validator(mock_fieldfile) except ValidationError: self.fail('Key file raised ValidationError unexpectedly')
[ "def is_pem_key(file_path):\n\n p = sp.Popen('file ' + file_path, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE, shell=True)\n o, e = p.communicate()\n if o and 'private key' in o:\n return True\n return False", "def test_load_convert_cert():\n test_pref: str = \"tests/data/test_pref.pref\"\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for a .pub file.
def test_pub(self): mock_fieldfile = Mock() mock_fieldfile.name = 'good_file_name.pem' try: key_file_validator(mock_fieldfile) except ValidationError: self.fail('Field name raised ValidationError unexpectedly')
[ "def test_default_filename():\n out = run(\"pub foo\")\n assert out.status_code == 0\n expect('bananas' * 4, out.std_out)\n\n #make sure we're not dropping pubfilec files\n assert not os.path.isfile(\"pubfilec\")", "def test_pubfile_error():\n pubtext = \"\"\"1/0\"\"\"\n pf = make_pubfile(pub...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalize log_prob over axis
def log_normalize(log_prob, axis): log_sum = logsumexp(log_prob, axis=axis) if not isinstance(log_sum, np.ndarray): log_sum = np.array([log_sum]) if log_prob.shape[0] == log_sum.shape[0]: # column normalize return (log_prob.transpose() - log_sum).transpose() else: #...
[ "def log_normalize(log_vals, axis = 1):\n\n log_vals -= np.expand_dims(np.max(log_vals, axis = axis), axis = axis)\n log_vals = np.exp(log_vals)\n return log_vals/np.expand_dims(np.sum(log_vals, axis = axis), axis = axis)", "def normalize_logprobs(log_probs):\n #log_probs = log_probs - np.min(log_prob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solve the discrete problem for the |Parameter| `mu`.
def solve(self, mu=None, **kwargs): mu = self.parse_parameter(mu) return self.cached_method_call(self._solve, mu=mu, **kwargs)
[ "def evaluate( self, mu ) :\n\n P = 0.\n for l, c_l in enumerate( self.coefficients ) : P += ( l + 0.5 ) * c_l * Legendre( l, mu, checkXRange = False ) \n return( P )", "def reparameterize(self, mu, logvar):\n\t\tlogvar = torch.exp(logvar/2)\n\t\tif self.cuda_flag:\n\t\t\tepsilon = torch.rand...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download film file associated with deviation to working direcotry
def download(self): # os.open *should* give a thread-safe way to exlusivly open files filepath = self.film try: # os.O_BINARY is only avilable and needed on windows flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_BINARY except: flags = os.O_CREAT ...
[ "def download_movie(self, filmid):\n self.logger.debug('download_movie')\n if not self._test_download_path(self.settings.getDownloadPathMovie()):\n return\n film = self.database.retrieve_film_info(filmid)\n if film is None:\n return\n (filmurl, extension,) = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call current tab's activate().
def handle_tab(self, index): self.current_tab = index self.views[index].activate()
[ "def activate_tab(self, prefix):\n activate_tab(prefix)", "def setActive(self):\n self._active = True\n self.updateTab()", "def activate(self):\n self._automation.activate()", "def activate(self, index):\n self.tk.call(self._w, 'activate', index)", "def __openBookmarkInCur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes varexercises using book, and makes varexercise_numbers. Its structure is like structure of exercise_numbers, but varexercises replaces codes.
def make_varexercises(self, number): for group_number in range(len(self.varexercise_numbers)): for item_number in range( 1, len(self.varexercise_numbers[group_number]) ): item = self.varexercise_numbers[group_number][item_number] ...
[ "def test_generate_barcode_ean13(self):\n pass", "def build_decodebook(codebook):\n return dict([(value, key) for key, value in codebook.items()])", "def code_votes(data,test=0,vtype=-1):\n\tfor row in data:\n\t\t# ['cong', 'session', 'year', 'v1ex', 'vote', 'voteview', 'vote', 'issue', 'pres', 'revot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Returns with the text of all variations in one text separated with \newpage
def all(self, frame=0): text = [] for number in range(1, self.number_of_variations+1): text.extend(self.one(number)) text.append('\n\n\\newpage') return text
[ "def generate_new_book(text):\n\n for paragraph in text:\n for sentence in paragraph:\n for word in sentence:\n print(word, end=' ')\n print()\n print()", "def splitPageContents(text):\n\tregex = re.compile(u'\\{\\{([^\\}]*?)\\}\\}', re.MULTILINE | re.DOTALL)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns with the values of the variations of a group as a latex text. If there is no variations, it returns with empty string ("").
def group_list(self, group_number=1): text = [] group = self.varexercise_numbers[group_number-1] group_name = _('Group %s') % group[0] text.append('\n\\subsection*{%s}\n' % group_name) for number in range(1, self.number_of_variations+1): print("---------", number) # ...
[ "def latex_plain(self, num):\n if not self.list:\n return \"\"\n values, erased_elements = self.list[num - 1]\n string_list = self.latex_string_list(values, erased_elements)\n if not string_list:\n raise ValueError('There is not values for the variation')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns with a fancy ASCII format of the groups.
def groups(self): groups_text = '\n' for group in self.exercise_numbers: txt = ' %s:\t' % group[0] for exercise in group[1:]: if isinstance(exercise, int): txt += '%d. ' % exercise else: txt += '\n\t%s\n\t' %...
[ "def print_groups():", "def get_all_groups_formatted():\n return '\\n'.join(f\"{g['groupId']}. {g['groupName']}\" for g in cur.execute('SELECT * FROM groups').fetchall())", "def group_repr(group_keys):\n if len(group_keys) == 0:\n return \"{}\"\n elif len(group_keys) == 1:\n return str(gr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It will give the frame of the testpapers. It makes preambulum and \\begin{document}...
def frame(text, preamble_file='magyarpreambulum', pagesize='a4paper', fontsize=11, lhead='-', rhead='-', lfoot='-', rfoot='-', cfoot=None, definitions=None, doc_type='testpaper', ): preamble_text = [] ...
[ "def show_frame(img):", "def create_frame_start(self):\n self.frame_start = self.create_frame(self.root)", "def frameSet():\n html = '<html>\\n<head>\\n<title>Java Class Index</title>\\n</head>\\n<framese'\n html +='t cols=\"30%,70%\">\\n <frame src=\"start.html\" name=\"tree\" title=\"'\n ht...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Returns with the text in a LaTeX frame (preamble, \begin{document} etc) text can be a string or a list of strings (lines of the file), preamble_text must be list.
def general_frame(text, class_type='article', class_argument="", preamble_text=None ): whole_text = ["\\documentclass%s{%s}\n" % (class_argument, class_type)] whole_text.append('\n') if isinstance(preamble_text, str): preamble...
[ "def frame(text,\n preamble_file='magyarpreambulum',\n pagesize='a4paper',\n fontsize=11,\n lhead='-',\n rhead='-',\n lfoot='-',\n rfoot='-',\n cfoot=None,\n definitions=None,\n doc_type='testpaper',\n ):\n\n pream...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It searches for control words, and append them to the matching list and their names to the self.variable_list if it is empty.
def find_control_words(self): row_number = 0 for row in self.text: row_number += 1 row = delete_remark(row) element_types = { "interval": dict( regexp0=self.intervalp0, regexp=self.intervalp, ...
[ "def add_search_words(self,\r\n index,\r\n entrytext):\r\n\r\n\r\n for a_temp in DELETECHARACTERS:\r\n entrytext = entrytext.replace(a_temp, BLANK)\r\n\r\n for w in set(entrytext.split()):\r\n\r\n w = w.strip()\r\n if sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns with the logical value of 'there is ecChoose(es) in the exercise'.
def is_ecChoose(self): return len(self.ecChoose_list) > 0
[ "def choice() :", "def evaluate(self,gene):\n return prng.choice(gene.allele_set)", "def part1_answer(self):\n suspect_list = set()\n for this_allergen in self.allergen_possibilities:\n suspect_list.update(self.allergen_possibilities[this_allergen])\n print(f\"Final suspec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It creates the text with the values of the numth variation. If full = 0 it writes the values according erased_elements, else writes all the values. If there is no interval in the text, it returns with the base_text.
def vartext(self, num, full=0): if not self.is_interval() and not self.is_ecChoose(): return self.text values, erased_elements = self.list[num] vtext = self.text[:] space = "\spacer" # It is at the place of an erased element. element_list = (self.interval_list + se...
[ "def latex_plain(self, num):\n if not self.list:\n return \"\"\n values, erased_elements = self.list[num - 1]\n string_list = self.latex_string_list(values, erased_elements)\n if not string_list:\n raise ValueError('There is not values for the variation')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns with list of the values of the variables in LaTeX format. The erased_elements are with question mark.
def latex_string_list(self, values, erased_elements=[], sizes=('large', 'small')): if not self.variable_list: return '' string_list = [] large, small = sizes for var in self.variable_list: erased = var in erased_...
[ "def get_explanatory_variables(self):\n return list(self._explanatory_variables)", "def latex_plain(self, num):\n if not self.list:\n return \"\"\n values, erased_elements = self.list[num - 1]\n string_list = self.latex_string_list(values, erased_elements)\n if not st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns with a plain latex format of the nth variation, as latexrow (not in table format).
def latex_plain(self, num): if not self.list: return "" values, erased_elements = self.list[num - 1] string_list = self.latex_string_list(values, erased_elements) if not string_list: raise ValueError('There is not values for the variation') # return '-...
[ "def markdown_row(self, ncol, which):\n if which == 'C':\n dat = self.C\n elif which == 'c':\n dat = self.d1\n elif which == 'f':\n dat = self.d2\n line = '|%d|' % (self.N*2)\n for i in range(1,self.N+1):\n line = line + ' $%s$ |' % (dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It converts a value to LaTeX format.
def latex_number(value): if isinstance(value, str): return value vstring = '%.4g' % value if vstring.find('e+0') > -1: vstring = vstring.replace('e+0', times + '10^{') + '}' elif vstring.find('e-0') > -1: vstring = vstring.replace('e-0', times + '10^{-') + '}' elif 'e' in vs...
[ "def latex_plain(self, num):\n if not self.list:\n return \"\"\n values, erased_elements = self.list[num - 1]\n string_list = self.latex_string_list(values, erased_elements)\n if not string_list:\n raise ValueError('There is not values for the variation')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
yield item i and item i+1 in lst. e.g. (lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[1], None)
def pairwise(lst): if not lst: return for i in range(len(lst)-1): yield lst[i], lst[i+1] yield lst[-1], None
[ "def pairwise(lst):\n if not len(lst): return\n #yield None, lst[0]\n for i in range(len(lst)-1):\n yield lst[i], lst[i+1]\n yield lst[-1], None", "def pairwise(lst):\n if not lst: \n return\n length = len(lst)\n for i in range(length-1):\n yield lst[i], lst[i+1]\n yie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a directed edge pointing from 'tail' to 'head' and assigns 'dist' as its weight.
def add_edge(self, head, tail, dist): if tail not in self.nodes: self.add_node_pairs(head,None) if head not in self.nodes: self.add_node_pairs(head,tail) self.parents_length[head][tail]=dist self.edges += 1
[ "def create_edge(head, *tail):", "def add_edge(self, tail, head):\n\n if tail not in self._vertices or head not in self._vertices:\n raise RuntimeError(\"Destination or source of edge ('{}'\".format(head) +\n \",'{}'\".format(tail) + \") cannot be found as a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Classical Stops, when there is no better neighbor or the number of max iterations was achieved.
def _check_classical_stop_conditions(self, changed): searching = changed and (self._iteration < self._max_iterations) if not changed: self._notify(message=LocalSearchMessage.StoppedPrematurely) elif not searching: self._notify(message=LocalSearchMessage.Stopped) ...
[ "def stop_or_not(self):\n # Stop if maximum iterations reached\n if len(self.fit_history) > self.max_iterations:\n self.stop_reason = \"Algorithm stopped as max iterations reached\"\n self.stop = True\n\n if not self._are_breakpoint_values_far_apart(\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make_parser() just generates the expert_system.py arguments parser.
def make_parser(): parser = argparse.ArgumentParser(description='Inference engine.') subparsers = parser.add_subparsers(dest="subcommand") subparsers.required = True solver_subparser = subparsers.add_parser('run') solver_subparser.add_argument( '-v', '--verbose', help='enable verbose mode.'...
[ "def build_parser(self, parser: ArgumentParser) -> None:", "def create_parser():\n\n # Create the initial parser\n parser = argparse.ArgumentParser(\n description=\"Build project files. Copyright by Rebecca Ann Heineman. \"\n \"Builds *.sln, *.mcp, *.cbp, *.wmk, *.rezscript, *.slicerscript, \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Magnetized cold plasma dielectric permittivity tensor elements. Elements (S, D, P) are given in the "Stix" frame, i.e. with
def cold_plasma_permittivity_SDP(B: u.T, species, n, omega: u.rad / u.s): S, D, P = 1, 0, 1 for s, n_s in zip(species, n): omega_c = gyrofrequency(B=B, particle=s, signed=True) omega_p = plasma_frequency(n=n_s, particle=s) S += -(omega_p ** 2) / (omega ** 2 - omega_c ** 2) D +=...
[ "def calcParticleZe(wls, elvs, mcTable, ndgs=30,\n scatSet={'mode':'full', 'safeTmatrix':False}, K2=0.93):#zeOperator\n \n #calling the function to create output columns\n\n if scatSet['mode'] == 'full':\n print('Full mode Tmatrix calculation')\n ##calculation of the reflect...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Magnetized cold plasma dielectric permittivity tensor elements. Elements (L, R, P) are given in the "rotating" basis, i.e. in the basis
def cold_plasma_permittivity_LRP(B: u.T, species, n, omega: u.rad / u.s): L, R, P = 1, 1, 1 for s, n_s in zip(species, n): omega_c = gyrofrequency(B=B, particle=s, signed=True) omega_p = plasma_frequency(n=n_s, particle=s) L += -(omega_p ** 2) / (omega * (omega - omega_c)) R +=...
[ "def inertia_tensor_partial(self, part, masswt=True, zero=ZERO):\n tensor = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n\n for i in part:\n if masswt:\n # I(alpha, alpha)\n tensor[0][0] += self.mass(i) * (self.y(i) * self.y(i) + self.z(i) * self.z(i))\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Compute the classical dielectric permittivity for a 1D Maxwellian plasma. This function can calculate both the ion and electron permittivities. No additional effects are considered (e.g. magnetic fields, relativistic effects, strongly coupled regime, etc.).
def permittivity_1D_Maxwellian( omega: u.rad / u.s, kWave: u.rad / u.m, T: u.K, n: u.m ** -3, particle, z_mean: u.dimensionless_unscaled = None, ) -> u.dimensionless_unscaled: # thermal velocity vTh = thermal_speed(T=T, particle=particle, method="most_probable") # plasma frequency ...
[ "def get_effective_permittivity(snow_density):\n\n eff = 1 + 1.5995 * snow_density + 1.861 * (snow_density ** 3)\n return eff", "def thermal_conductivity(self):\n return self.fluid.conductivity(self.T_C)", "def electron_collision_deexcitation_rate(self) -> u.cm**3 / u.s:\n c = (const.h**2) /...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare parsed data from 'data/.org' and its correct answer 'data/.py'
def check_data(dataname): oname = data_path(dataname, "org") data = load_data(data_path(dataname, "py")) root = load(oname) for (i, (node, kwds)) in enumerate(zip(root[1:], data)): for key in kwds: val = value_from_data_key(node, key) eq_(kwds[key], val, ...
[ "def protname_compare():\n # import os.path\n \n baitName = \"BTK\"\n \n intactList = intact_parser(\"BTK.txt\",baitName)\n\n \n \n biogridList = biogrid_parser(\"BIOGRID-GENE-107160-3.5.172.tab2.txt\",baitName)\n\n \n# inpF = open(os.path.join(os.path.split(os.path.dirname(__file__))[0], \"data\", \"pst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine several byte values to an integer
def combine_to_int(values): multibyte_value = 0 for byte_id, byte in enumerate(values): multibyte_value += 2**(4 * byte_id) * byte return multibyte_value
[ "def join_bits(byteseq) -> int:\n return reduce(lambda acc, bit: (acc << 1) | int(bit), byteseq)", "def bytes_to_int(bs):\n v = 0\n p = 0\n for b in reversed(bs):\n v += b * (2 ** p)\n p += 8\n return v", "def _pack_bytes(byte_list):\n return int.from_bytes(byte_list, 'big', sign...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read an unsigned integer from stream
def read_uint(stream, indent=INDENT): global _TMP_CACHE value = combine_to_int(streambyte_to_int(stream, 4)) formats = list(convert(value)) _TMP_CACHE = formats[3] output = str(formats[3]) + " (" + formats[0] + ", " + formats[1] if formats[2]: output += ', ascii:"' + formats[2] + '"' ...
[ "def read_unsigned_int(data):\n s_type = \"=%s\" % get_type(\"unsigned_int\")\n return struct.unpack(s_type, data.read(4))[0]", "def readUInt(self) -> int:\n\n self._resetBits()\n s = self.infile.read(4)\n if len(s) != 4:\n raise ValueError(\"ReadBitFile.readUInt error\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a picture file of a specified frame from a movie file. Returns the filename of the picture file and the resolution of the picture.
def get_movie_frame(movie_file, frame=0): movie = cv2.VideoCapture(movie_file) _, image = movie.read() height, width, _ = image.shape filename = os.path.splitext(movie_file)[0] + f'_{frame}.jpg' cv2.imwrite(filename, image) return filename, height, width
[ "def rip_to_frames(movie_file):\r\n movie_directory = os.path.split(movie_file)[0]\r\n movie_filename = os.path.split(movie_file)[-1]\r\n folder_name = (\"_\").join(movie_filename.split(\".\")[:-1])\r\n frame_folder_name = os.path.join(movie_directory, folder_name)\r\n try:\r\n os.makedirs(fra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find user by comment pattern
def find_comment_by_user(self, pat): return [com for th in self for com in th['comment'] if pat in com['user']]
[ "def all_user_comments(username):\n # comment = [\n # comment for comment in commentslist if comment[\"username\"] == username\n # ]\n return commentslist", "def scan_for_author(message):\n if not message:\n return\n\n message = message.strip()\n matches = re.findall(r'^.*?\\s+\\/(.*)\\Z', m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get all title in object.
def get_title(self): return [i['title'] for i in self]
[ "def all_title() -> list:\n return [i[\"title\"] for i in Blogs_Manager.TablePost.all_query()]", "def get_title(self, obj):\n title = obj.habit.title\n return title", "def Titles(self, default=[{}]):\n tmp = self.data.get('metadata', {}).get('titles', default)\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform place name cleanup and optional substitution for bulk edits
def clean_place(place, places): result = place result = result.replace(" ", " ") for match in places: result = result.replace(match, places[match]) return result
[ "def edit_item_name_replace(cls, data):\n while re.search(cls.edit_item_name, data):\n random_name = \"科目名称编辑\" + \"\".join(random.sample(\"1234567890\", 4))\n data = re.sub(cls.edit_item_name, random_name, data)\n return data", "def update_city_name(name,mapping):\n \"\"\"C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read in requested APID files and push on queue until told to exit
def read_apids(local_queue, local_lock, remote_queue, remote_lock): while True: local_lock.acquire() if not local_queue.empty(): file_data = local_queue.get() local_lock.release() else: local_lock.release() time.sleep(0.01) continue...
[ "def recv_loop():\n\n if not os.path.isdir(tq_dir):\n os.mkdir(tq_dir)\n if not os.path.isdir(rq_dir):\n os.mkdir(rq_dir)\n\n while True:\n time.sleep(1)\n #print ('polling')\n try:\n files = os.listdir(rq_dir)\n except:\n print ('Could not ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read in all the APID objects for reference using asynchronous workers
def get_apid_objects(queue, media_base, args, absolute=False): work_lock = Lock() work_queue = Queue() readers = os.cpu_count() read_lock = Lock() read_queue = Queue() read_processes = [] for number in range(readers): read_process = Process( target=read_apids, args=(read...
[ "def read_apids(local_queue, local_lock, remote_queue, remote_lock):\n while True:\n local_lock.acquire()\n if not local_queue.empty():\n file_data = local_queue.get()\n local_lock.release()\n else:\n local_lock.release()\n time.sleep(0.01)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read in all the person URLs for later reference
def get_people_urls(gedcom_data, apid_full_map): people = {} found = False logging.info("Extracting person specific URL information") for line in gedcom_data.split("\n"): if len(line) > 5: tag = line.split(" ")[1] if "@P" in tag: person = tag ...
[ "def __read_urls(self):\n urls = []\n url_counter = 0\n url_url = self.get_form('url-url-'+str(url_counter))\n while url_url is not None:\n if url_url:\n url_name = self.get_form('url-name-'+str(url_counter))\n url = url_entity.Url(name=url_name, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write out a line of Gedcom data insuring it does not exceed allowed length
def emit_line(handle, data): if len(data) > 254: if " PAGE " in data: data = data.replace("Record Group Title", "Record Group") data = data.replace("Series Title", "Series") data = data.replace( "Washington, D.C.; Washington, D.C.;", "Washington, D.C.;" ...
[ "def _skip_line(line):\n return True if len(line) > 10000 else False", "def _write(self, line):\n if self._request != logsutil.RequestID():\n\n\n self._reset()\n self.stream().write(line)\n\n self._lines += 1\n self._bytes += len(line)\n self._autoflush()", "def check_len(file_handle, fh_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the value of two cells and adjusts them accordingly.
def interact(self,cell1,cell2): difference = math.fabs(cell1-cell2) if difference<=self.t: #if both cells are close enough: if cell1>cell2: # print "Case 1" return (cell1-difference/2.0,cell2+difference/2.0) else: # print "Case 2" ...
[ "def adjustRange(self, x1, y1, x2, y2):\n self.tr.setRange(x1, y1, x2, y2)", "def update_cell(self, x, y, value):\n x1, y1 = self.transpose_coordinates(x, y)\n if self.is_in_field(x1, y1):\n self._cells[y1][x1] = value\n return True\n return False", "def switch(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Manager Status Pool Members Enable/Disabled By Pool
def manager_pools(request): try: pool_id = request.DATA.get('server_pool_id') pool_members = request.DATA.get('server_pool_members', []) # List to validate pool member status valid_status = [0, 1, False, True] pool_members_id = [member.get('id') for member in pool_members]...
[ "def pool_status(self, pool_status):\n self._pool_status = pool_status", "def do_monitor_alive_check_enable(client, args):\n item = client.alivecheck.perform_action(args.id, 'enable')\n utils.print_dict(item)", "def pool_status(self):\n return self._pool_status", "def get_nat_pool_status(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the clustering coefficient for each node in the graph. The values are stored in a new attribute named 'cc'.
def calc_cc(graph): clustering_coeffs = {} for node in graph.nodes(): clustering_coeffs[node] = { "cc" : nx.clustering(graph, node)} nx.set_node_attributes(graph, clustering_coeffs)
[ "def cluster_cal(self):\n self.Cluster = []\n for i in range(self.nodenum):\n neighborhood_node = self.neighbor_node(i)\n Node_num = len(neighborhood_node)\n Count = self.neighbor_edge(neighborhood_node)\n if(Node_num == 0 or Node_num == 1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the clustering coefficient for each node in the graph. The values are then plotted as a histogram.
def plot_cc(graph): clustering_coeffs = [] for node in graph.nodes(): clustering_coeffs.append(nx.clustering(graph, node)) plt.axvline(x=np.mean(clustering_coeffs), color='r', linestyle='-') plt.hist(clustering_coeffs, bins=100)
[ "def cluster_cal(self):\n self.Cluster = []\n for i in range(self.nodenum):\n neighborhood_node = self.neighbor_node(i)\n Node_num = len(neighborhood_node)\n Count = self.neighbor_edge(neighborhood_node)\n if(Node_num == 0 or Node_num == 1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Caches OMDb API response json on disk.
def cache_movie_json(title: str, json_response: Dict) -> None: fpath = os.path.join(OMDB_JSONS_DIR, title) with open(fpath, 'a+') as fp: json.dump(json_response, fp)
[ "def set_cached_response(self) -> None:\n if self.get_caching_duration() > 0: # if caching is enabled for this request\n json_response = self._request_result.json()\n with open(self.cache_file_name, 'w') as json_file:\n json.dump(json_response, json_file, indent=4)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches the movie json from disk, if available.
def load_movie_json_from_cache(title: str) -> Optional[Dict]: fpath = os.path.join(OMDB_JSONS_DIR, title) if os.path.exists(fpath): with open(fpath, 'r') as fp: return json.load(fp) return None
[ "def get_and_cache_movie_json(title: str) -> Dict:\n cached = load_movie_json_from_cache(title)\n if cached:\n return cached\n rsp = requests.get(url='http://www.omdbapi.com',\n params={\n 't': title,\n 'plot': 'full',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches json for the movie titled |title| from omdapi.com or from local cache. If the json response is not cached yet, caches it on disk.
def get_and_cache_movie_json(title: str) -> Dict: cached = load_movie_json_from_cache(title) if cached: return cached rsp = requests.get(url='http://www.omdbapi.com', params={ 't': title, 'plot': 'full', ...
[ "def load_movie_json_from_cache(title: str) -> Optional[Dict]:\n fpath = os.path.join(OMDB_JSONS_DIR, title)\n if os.path.exists(fpath):\n with open(fpath, 'r') as fp:\n return json.load(fp)\n return None", "def cache_movie_json(title: str, json_response: Dict) -> None:\n fpath = os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocesses the movie json from OMDb API to optimize the resulting contexts for vectorization.
def preprocess_movie_json(json_dict: Dict) -> Dict: json_dict['Ratings'] = list(map(lambda elem: {elem['Source']: elem['Value']}, json_dict['Ratings'])) for obj in json_dict['Ratings']: if 'Metacritic' in obj: obj['Metacritic'] = ' / '.join(obj['Metacritic'].split('/')) return json_dict
[ "def preprocess(self):\r\n file_name = os.path.join(self.raw_path, \"amazon-amazon-instant-video.json.gz\")\r\n print(f\"file_name: {file_name}\")\r\n if not os.path.exists(file_name):\r\n self.download()\r\n\r\n # parse json data\r\n data = self.get_data_frame_from_gzi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BJONTEGAARD Bjontegaard metric calculation Bjontegaard's metric allows to compute the average gain in psnr between two ratedistortion curves [1]. rate1,psnr1 RD points for curve 1 rate2,psnr2 RD points for curve 2 returns the calculated Bjontegaard metric 'dsnr'
def bdsnr(metric_set1, metric_set2): rate1 = [x[0] for x in metric_set1] psnr1 = [x[1] for x in metric_set1] rate2 = [x[0] for x in metric_set2] psnr2 = [x[1] for x in metric_set2] log_rate1 = map(lambda x: math.log(x), rate1) log_rate2 = map(lambda x: math.log(x), rate2) # Best cubic poly fit for graph...
[ "def bdrate(metric_set1, metric_set2):\n rate1 = [x[0] for x in metric_set1]\n psnr1 = [x[1] for x in metric_set1]\n rate2 = [x[0] for x in metric_set2]\n psnr2 = [x[1] for x in metric_set2]\n\n log_rate1 = map(lambda x: math.log(x), rate1)\n log_rate2 = map(lambda x: math.log(x), rate2)\n\n # Best cubic pol...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BJONTEGAARD Bjontegaard metric calculation Bjontegaard's metric allows to compute the average % saving in bitrate between two ratedistortion curves [1]. rate1,psnr1 RD points for curve 1 rate2,psnr2 RD points for curve 2
def bdrate(metric_set1, metric_set2): rate1 = [x[0] for x in metric_set1] psnr1 = [x[1] for x in metric_set1] rate2 = [x[0] for x in metric_set2] psnr2 = [x[1] for x in metric_set2] log_rate1 = map(lambda x: math.log(x), rate1) log_rate2 = map(lambda x: math.log(x), rate2) # Best cubic poly fit for grap...
[ "def Arrhenius_rate(self, state1, state2 ):\n\n transition1 = (state1,state2 )\n transition2 = (state2,state1)\n rate1 = self.rates.get(transition1)\n \n if rate1:\n return rate1\n try :\n \n left, right = self.transition_structure[state1,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function substitutes all matches of the command string //%% ... %%// with the variable represented by ... .
def FillForm(string_for_substitution, dictionary_of_vars): return_string = string_for_substitution for i in re.findall("//%%(.*)%%//", string_for_substitution): return_string = re.sub("//%%" + i + "%%//", dictionary_of_vars[i], return_string) return return_string
[ "def replace_varibales_in_the_command(command_string):\n variables = re.findall('\\$[a-zA-Z0-9_]*', command_string)\n\n if len(variables) <= 0:\n return command_string\n\n for var in variables:\n if var[1:] not in USER_VARIABLES:\n raise Exception(\"Unknown variable `{var_name}'\"....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares two data files and determines which is better and by how much. Also produces a histogram of how much better, by PSNR. metric_column is the metric.
def FileBetter(file_name_1, file_name_2, metric_column, method): # Store and parse our two files into lists of unique tuples. # Read the two files, parsing out lines starting with bitrate. metric_set1_sorted = ParseMetricFile(file_name_1, metric_column) metric_set2_sorted = ParseMetricFile(file_name_2, metric_...
[ "def summarize(data, verbal=False, using_files=True):\n\n if using_files:\n for file_name in tqdm(data):\n fill_table(pd.read_csv(file_name))\n else:\n for table in tqdm(data):\n fill_table(table)\n\n for cluster in table_summary:\n #total_genes = sum(table_summar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transcribe the given audio file.
def transcribe_file(speech_file): client = speech.SpeechClient() # [START speech_python_migration_sync_request] # [START speech_python_migration_config] with io.open(speech_file, 'rb') as audio_file: content = audio_file.read() audio = types.RecognitionAudio(content=content) config = ty...
[ "def transcribe_audio_file(filename):\n url = 'https://api.nexiwave.com/SpeechIndexing/file/storage/' + USERNAME +'/recording/?authData.passwd=' + PASSWORD + '&auto-redirect=true&response=application/json'\n\n # To receive transcript in plain text, instead of html format, comment this line out (for SMS, for e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send feedback about the bot. ~ {prefix}feedback this bot is very good. {prefix}feedback I have a command idea...
async def feedback(self, ctx, *, feedback): url = os.environ.get("FEEDBACK_WEBHOOK", None) if url: webhook = Webhook.from_url(url, adapter=RequestsWebhookAdapter()) embed = discord.Embed(description=feedback, colour=discord.Colour.teal()) embed.set_author(name=f"{ctx....
[ "async def feedback(self,ctx):\n \n user = await self.bot.fetch_user(363396988672409602)\n modifMsg=ctx.message.content[9:]\n modifMsg=f\"Received feedback from __{ctx.author}__ at **{time.ctime()}** :\\n**{modifMsg}**\"\n await user.send(modifMsg)\n await ctx.message.reply...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simplify potentially variable ways to write out a reference name by lowercasing it and replacing all dashes and spaces with underscores.
def normalize_reference_name(name): return name.strip().lower().replace("-", "_").replace(" ", "_")
[ "def alias(name):\n name = name.strip().replace(\" \", \"_\").replace(\"-\", \"_\")\n while \"__\" in name:\n name = name.replace(\"__\", \"_\")\n return \"\".join(x for x in name if x.isalnum() or x == \"_\").lower()", "def beautify_name(name, patterns):\n\n for pattern, substitution in patter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is the given genome name one of the known UCSC genomes?
def is_ucsc_reference_name(name): return (normalize_reference_name(name) in normalized_ucsc_reference_names)
[ "def is_other_chromosome(chromosome_name):\n if is_cassette_chromosome(chromosome_name): return False\n if chromosome_name.startswith('chr') or chromosome_name.startswith('scaffold'): return False\n else: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine the dictionary of Ensembl reference name aliases with the UCSC reference names (which also get included as aliases). Returns dict
def _merge_ensembl_aliases_with_ucsc(): result = {} for ucsc_name, ensembl_name in ucsc_to_ensembl_reference_names.items(): result[ensembl_name] = [ucsc_name] + \ ensembl_reference_aliases.get(ensembl_name, []) return result
[ "def get_aliases_to_full_name_dict(self):\n aliases_to_full_name = {}\n\n for person in self.people:\n for alias in person.aliases:\n aliases_to_full_name[alias] = str(person)\n return aliases_to_full_name", "def aliases():\n fetch(\"PropertyValueAliases.txt\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given list of (in this case, matched) assemblies, identify the most recent, where "recency" is determined by sorting based on the numeric element of the assembly name.
def most_recent_assembly_name(assembly_names): match_recency = [ int(re.search(r'\d+', assembly_name).group()) for assembly_name in assembly_names ] sorted_list_of_names = [ assembly for (number, assembly) in sorted(zip(match_recency, assembly_names), reverse=True)] ...
[ "def choose_best_assembly_name(assembly_names):\n assembly_names = set(assembly_names)\n\n if len(assembly_names) == 1:\n return list(assembly_names)[0]\n\n assembly_names_ucsc = {\n name for name in assembly_names if is_ucsc_reference_name(name)}\n assembly_names_ensembl = assembly_names....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of reference genome names returns the best according to the
def choose_best_assembly_name(assembly_names): assembly_names = set(assembly_names) if len(assembly_names) == 1: return list(assembly_names)[0] assembly_names_ucsc = { name for name in assembly_names if is_ucsc_reference_name(name)} assembly_names_ensembl = assembly_names.difference(as...
[ "def getBestMatch(foundMinistry, classes):\n maxScore = [0,0] # [score, index]\n\n for i, ministry in enumerate(classes):\n # first see if there are direct similar words in the titles if there is\n # choose that ministry and stop\n ministry = ministry.lower()\n foundMinistry = foun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
First infer a canonical Ensembl or UCSC reference name (e.g. hg19 or GRCh37) and if it's a UCSC genome then map it to the equivalent in Ensembl.
def infer_genome_for_reference_name(reference_name): converted_ucsc_to_ensembl = False reference_name = infer_reference_name(reference_name) if is_ucsc_reference_name(reference_name): if reference_name not in ucsc_to_ensembl_reference_names: raise ValueError( "Unrecognize...
[ "def infer_genome(genome_object_string_or_int):\n converted_ucsc_to_ensembl = False\n if isinstance(genome_object_string_or_int, Genome):\n genome = genome_object_string_or_int\n elif is_integer(genome_object_string_or_int):\n genome = cached_ensembl_release(genome_object_string_or_int)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If given an integer, get the human EnsemblRelease object for that Ensembl version. If given a string, return latest EnsemblRelease which has an equivalent reference. If the given name is a UCSC genome (e.g. hg19) then convert it to the equivalent Ensembl reference (e.g. GRCh37). If given a PyEnsembl Genome, simply use ...
def infer_genome(genome_object_string_or_int): converted_ucsc_to_ensembl = False if isinstance(genome_object_string_or_int, Genome): genome = genome_object_string_or_int elif is_integer(genome_object_string_or_int): genome = cached_ensembl_release(genome_object_string_or_int) elif is_st...
[ "def infer_genome_for_reference_name(reference_name):\n converted_ucsc_to_ensembl = False\n reference_name = infer_reference_name(reference_name)\n if is_ucsc_reference_name(reference_name):\n if reference_name not in ucsc_to_ensembl_reference_names:\n raise ValueError(\n \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine & minify all .css files in supplied dir
def combine_css(directory): composed = fu.lcompose([ partial(get_path_files_with_ext, '.css'), fu.fmap(fu.file_to_str), '\n'.join, ]) return composed(directory)
[ "def minify_css_directory(gen, source, target):\n import rcssmin\n\n plugin_paths = gen.settings['PLUGIN_PATHS']\n for path in plugin_paths:\n source_ = os.path.join(path, 'pelican-btoc', source)\n target_ = os.path.join(path, 'pelican-btoc', target)\n\n if os.path.isdir(source_):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine all .js files in supplied dir
def get_js(directory): composed = fu.lcompose([ partial(get_path_files_with_ext, '.js'), fu.fmap(fu.file_to_str), '\n'.join, ]) return composed(directory)
[ "def get_all_js_files(self, root):\n res = []\n\n for fname in os.listdir(root):\n mo = re.match(r'(\\w+)\\.js$', fname)\n if mo:\n res.append({\n 'name': mo.group(1),\n 'src': file_contents(os.path.join(root, mo.group()))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all files with given extension from directory
def remove_extention(extension, directory): map(os.remove, get_path_files_with_ext(extension, directory))
[ "def _delete_file_by_type(target_dir, file_ext):\n os.chdir(target_dir)\n removal_path = Path.cwd()\n count = 0\n for _file in removal_path.iterdir():\n if _file.suffix == file_ext:\n logger.info(f'Removing {_file.name}.')\n count += 1\n os.remove(_file.name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make cachebusted css & js files, return dict of filenames
def make_static_assets(opts): css_filename = do_css(opts['css_source_dir'], opts['out_dir']) js_filename = do_js(opts['js_source_dir'], opts['out_dir']) return { 'primary_css': css_filename, 'js': js_filename }
[ "def minify_gzip_and_get_css_and_js_files():\n\n print(\"minify and gzip css and js files\")\n\n def path_relative_to_static_css_or_js_dir(path):\n path_str = str(path)\n css_dir_str = str(STATIC_DIR / \"css\")\n js_dir_str = str(STATIC_DIR / \"js\")\n\n if path_str.find(css_dir_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take input css, combine, cachebust, replace
def do_css(css_input_dir, css_output_dir): # primary css css_str = combine_css(css_input_dir) css_name = get_cachebusting_name(css_str) + '.css' # remove and write remove_extention('.css', css_output_dir) fu.str_to_file(css_output_dir + css_name, css_str) return css_name
[ "def process_clevercss(source, filepath):\n return clevercss.convert(source)", "def update_css(self) -> None:\n # Filter all <style> tags\n for style in self.soup.find_all('style'):\n style.string = clean_css(style.string, self.page_url)\n\n # TODO: Convert remote stylesheets to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take input js, combine, cachebust, replace existing output
def do_js(js_input_dir, js_output_dir): remove_extention('.js', js_output_dir) js_str = get_js(js_input_dir) js_name = get_cachebusting_name(js_str) + '.js' fu.str_to_file(js_output_dir + js_name, js_str) return js_name
[ "def make_js(scheme, netloc, host, port, cname, type_):\n js = get_cache(host, port, type_)\n if not js:\n js = TEMPLATE\n js = __replace(js, '$SCHEMA', str(scheme))\n js = __replace(js, '$NETLOC', str(netloc))\n js = __replace(js, '$HOST', str(host))\n js = __replace(js, '$...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Autodiscover INSTALLED_APPS panels.py modules and fail silently when not present. This forces an import on them to register any panels they define. Copied from django/contrib/admin/__init__.py, Thanks!
def _auto_discover(self): if self._initialized: return from django.conf import settings from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule self._initialized = True for app in settings.INSTALLED_APPS:...
[ "def autodiscover():\n from django.utils.importlib import import_module\n global LOADED\n if LOADED:\n return\n LOADED = True\n for app in settings.INSTALLED_APPS:\n try:\n import_module(\"%s.page_widgets\" % app)\n except ImportError, e:\n if \"WidgetModel\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a Panel class with this site. This will create the queue in celery and start routing the events from that queue to the given panel instance.
def register(self, panel): new_instance = panel() new_event_type = new_instance._meta.event_type if new_event_type in self.__class__._panels: raise Exception("Two panels with the same event type: %s" % \ new_event_type) self.__class__._panels[new_event_type] =...
[ "def AddPanel(self, panel):\n self._panels[panel.Id] = panel", "def add_panel(self, panel):\n assert panel.PANEL_ID not in self.panels\n assert not self.tools, \"tools must be added after panels\"\n self.panels[panel.PANEL_ID] = panel\n panel.register_panel(self)", "def push_v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a registered panel instance by the event type it handles.
def get_panel(self, event_type): self._auto_discover() if event_type in self.__class__._panels: return self.__class__._panels[event_type] raise exceptions.PanelDoesNotExist("Panel '%s' does not exist" % event_type)
[ "def register(self, panel):\n new_instance = panel()\n new_event_type = new_instance._meta.event_type\n if new_event_type in self.__class__._panels:\n raise Exception(\"Two panels with the same event type: %s\" % \\\n new_event_type)\n self.__class__._panels[new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the Sequence grammar.
def test__parser__grammar_sequence(seg_list, caplog): bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) g = Sequence(bs, fs) # If running in the test environment, assert that Sequence recognises this if getenv("SQLFLUFF_TESTENV", ""): assert g.test_env gc ...
[ "def test_sequence(self):\n name, prefix, constraints, length = \"name\", \"prefix-\", [(5, \"N\")], None\n sequence = DNA_classes.Sequence(name, prefix, constraints, length)\n self.assertTrue(isinstance(sequence, DNA_classes.Sequence))", "def sequence():\n\tif verbose: print \"sequence\"\n\n\tif found(T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the Sequence grammar when nested.
def test__parser__grammar_sequence_nested(seg_list, caplog): bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) bas = StringParser("baar", KeywordSegment) g = Sequence(Sequence(bs, fs), bas) ctx = ParseContext(dialect=None) with caplog.at_level(logging.DEBUG, logge...
[ "def test__parser__grammar_sequence_indent(seg_list, caplog):\n bs = StringParser(\"bar\", KeywordSegment)\n fs = StringParser(\"foo\", KeywordSegment)\n g = Sequence(Indent, bs, fs)\n ctx = ParseContext(dialect=None)\n with caplog.at_level(logging.DEBUG, logger=\"sqlfluff.parser\"):\n m = g.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the Sequence grammar with indents.
def test__parser__grammar_sequence_indent(seg_list, caplog): bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) g = Sequence(Indent, bs, fs) ctx = ParseContext(dialect=None) with caplog.at_level(logging.DEBUG, logger="sqlfluff.parser"): m = g.match(seg_list, pa...
[ "def test__parser__grammar_sequence_indent_conditional(seg_list, caplog):\n bs = StringParser(\"bar\", KeywordSegment)\n fs = StringParser(\"foo\", KeywordSegment)\n # We will assume the default config has indented_joins = False.\n # We're testing without explicitly setting the `config_type` because\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the Sequence grammar with indents.
def test__parser__grammar_sequence_indent_conditional(seg_list, caplog): bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) # We will assume the default config has indented_joins = False. # We're testing without explicitly setting the `config_type` because # that's the...
[ "def test__parser__grammar_sequence_indent(seg_list, caplog):\n bs = StringParser(\"bar\", KeywordSegment)\n fs = StringParser(\"foo\", KeywordSegment)\n g = Sequence(Indent, bs, fs)\n ctx = ParseContext(dialect=None)\n with caplog.at_level(logging.DEBUG, logger=\"sqlfluff.parser\"):\n m = g.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows an rgb viewer inside a new window Returns as soon as the stream has been terminated.
def show_rgb_viewer(): if not IS_INITIALIZED: print "Device not initialized" return device = openni2.Device.open_any() rgb_stream = _rgb_stream_from_device(device) rgb_stream.start() done = False while not done: key = cv2.waitKey(1) & 255 if key == 27: ...
[ "def show(self, window):\r\n\r\n return", "def show(self, window_name=\"window\"):\n cv2.namedWindow(window_name)\n\n while self.cap.isOpened():\n frame = self.next_frame()\n\n cv2.imshow(window_name, frame)\n\n k = cv2.waitKey(1) & 0xFF\n if k == o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Home page with auth links.
def home(request): if request.user.is_authenticated(): return HttpResponse("{0} <a href='/accounts/logout'>exit</a>".format(request.user)) else: return HttpResponse("<a href='/login/vk-oauth2/'>login with VK</a>")
[ "def home():\n if get_user():\n return redirect(url_for('profile', username=session['user']))\n\n return render_template('home.html')", "def homepage():\n\n user_email = request.args.get('email')\n user_password = request.args.get('password')\n\n return render_template('homepage.html')", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the correct SO term for the given URS ISNDC ncRNA type. The URS may be an Rna object, or a known rna_type. If there is no known mapping then the SO term defined in 'UNKNOWN' will be used (transcript). Generally this will just look up the known rna_type and then using the mapping dict to get the corresponding ...
def assign_term(urs): if isinstance(urs, six.string_types): return MAPPING.get(urs, UNKNOWN) return assign_term(urs.get_rna_type())
[ "def term_type(self, term):\n with qdb.sql_connection.TRN:\n sql = \"\"\"SELECT user_defined FROM\n qiita.term\n WHERE term = %s AND ontology_id = %s\"\"\"\n qdb.sql_connection.TRN.add(sql, [term, self.id])\n result = qdb.sql_connection...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get only the SO label for the given URS. This can effectively cover the label using by ISNDC to the one used by the SO. Most of them are the same, but a few are different. In addition, some terms in ISNDC don't have a clear correspondence to the SO terms.
def get_label(urs): return assign_term(urs)[1]
[ "def get_label(self) -> str:\n if self.found:\n return self.detail['label']\n else:\n logger.warning(\"Return empty for label as fail to find ontology on OLS for term \"+self.short_term)\n return \"\"", "def label(efo):\n url = 'https://www.ebi.ac.uk/ols/api/ontol...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the source of a twiki topic
def get_topic_raw(session, web_topic, twiki_root, timeout=DEFAULT_TIMEOUT_SECONDS, rawmode="debug"): web,topic = web_topic.split(".") rd = session.get("{0}/view/{web}/{topic}?skin=text&raw=debug&contenttype=text/plain".format(twiki_root.rstrip("/"), web=web, topic=topic), timeout=timeout) return rd.content....
[ "def get_topic(self):\n return self.topic", "def _gettopic(self, topic, more_xrefs=''):\n try:\n import pydoc_data.topics\n except ImportError:\n return('''\nSorry, topic and keyword documentation is not available because the\nmodule \"pydoc_data.topics\" could not be fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the webbacklinks page for a twiki topic
def get_topic_webbacklinks(session, web_topic, twiki_root, timeout=DEFAULT_TIMEOUT_SECONDS): web,topic = web_topic.split(".") rd = session.get("{0}/oops/{web}/{topic}?template=backlinksweb".format(twiki_root.rstrip("/"), web=web, topic=topic), timeout=timeout) return rd.content.decode(rd.apparent_encoding)
[ "def scrape_page_related_topics(soup):\n links = [a['href'] for a in soup.find_all('a', class_='submeta__link')]\n return links", "def topic_page_url(module, topic):\n url = module.link_to\n if not url:\n url = module.link\n if not url:\n url = ''\n try:\n if url.find(':topi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the cost of the current route based on adjacency matrix
def calculate_cost(route, adjacency_matrix): route_shifted = np.roll(route,1) cost = np.sum(adjacency_matrix[route, route_shifted]) st_dev = np.std(adjacency_matrix[route, route_shifted]) return st_dev, cost
[ "def calculate_cost_of_route(route, graph):\n if route is None:\n return np.nan\n total_cost = 0\n for i in range(len(route) - 1):\n edge = (route[i], route[i+1])\n total_cost += graph.edges[edge]['weight']\n return total_cost", "def calculate_routes_cost(self):\n total_rou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run function for greedy two_opt function
def run_two_opt(tsp_file, N_sim, max_chain_length): best_routes = [] costs = [] adjacency_matrix = make_matrix(tsp_file) cost_lists = [] for _ in range(N_sim): x = list(range(len(adjacency_matrix))) init_route = random.sample(x,len(x)) best_route, cost_list = two_opt(init_ro...
[ "def run_2opt(route):\n\timprovement = True\n\tbest_route = route\n\tbest_distance = route_distance(route)\n\twhile improvement: \n\t\timprovement = False\n\t\tfor i in range(len(best_route) - 1):\n\t\t\tfor k in range(i+1, len(best_route)):\n\t\t\t\tnew_route = swap_2opt(best_route, i, k)\n\t\t\t\tnew_distance = r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select connectors necessary for circular assemblie(s) in this mix. This method assumes that the parts provided in the mix are the main parts of either a single or a combinatorial assembly (with welldefined slots), and the provided list of ``connector_records`` contains "bridging" parts, some of which may be necessary f...
def autoselect_connectors(self, connectors_records): original_parts = self.parts all_part_ids = [c.id for c in original_parts] connectors_records = [ c for c in connectors_records if c.id not in all_part_ids ] slotted_parts_records = [ self.parts_dict[lis...
[ "def _collapse_selected_overlapping_connectors(self):\n # collect all necessary actions\n actions = []\n # track all unselected connectors on the board\n connectors = {}\n for drawable in self._get_drawables():\n if drawable not in self._selected_drawables:\n for connector in drawable.con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats a list of events according to the user's settings. We can format in JSON, text, or keyvalue pairs. Once the event is formatted, it's passed to writeEventString() to be written to the destination.
def formatEvents(eventList): firstEv = True for ev in eventList: evStr = json.dumps(ev) xmlStr = "<event><data>%s</data></event>" % xml.sax.saxutils.escape(evStr) print xmlStr if (firstEv): firstEv = False logging.info("cphalo: first event in batch...
[ "def format_events(cls, events: List) -> List:\n\n raise EventException('Unimplemented \"format_events\".')", "def write_events(events: list, calendar):\n for event in events:\n location = event[\"location\"]\n vevent_string = str()\n vevent_string += 'BEGIN:VEVENT\\n'\n veve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method runs a host of preparations for the evaluation of the criterion function that are specific to the current RESPY implementation. So, major cleanup as we settle on the revised interface.
def _prepare_evaluate(self): labels = list() labels += ['num_procs', 'num_periods', 'is_debug', 'seed_emax', 'seed_sim'] labels += ['num_draws_emax', 'num_agents_sim', 'num_types', 'edu_spec', 'version'] labels += ['num_draws_prob', 'seed_prob'] num_procs, num_periods, is_debug, ...
[ "def optimize(self):\n self.vbe_step()\n self.compute_responsibilities()\n self.compute_sufficient_stats()\n self.vbmstep()", "def update_preconditioner(self):\n precond = OrderedDict()\n min_s = math.inf\n\n for group in self.param_groups:\n eps = group...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to find the biggest patch size that can be send to GPU for inference without throwing CUDA out of memory
def find_maximum_patch_size(model, device): logger = get_logger('PatchFinder') in_channels = model.in_channels patch_shapes = [(64, 128, 128), (96, 128, 128), (64, 160, 160), (96, 160, 160), (64, 192, 192), (96, 192, 192)] for shape in patch_shapes: # ge...
[ "def find_maximum_patch_size(model, device):\n logger = get_logger('PatchFinder')\n in_channels = model.in_channels\n\n patch_shapes = [(64, 128, 128), (96, 128, 128),\n (64, 160, 160), (96, 160, 160),\n (64, 192, 192), (96, 192, 192)]\n\n for shape in patch_shapes:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to get all user comments based on their usename
def all_user_comments(username): return commentslist
[ "def all_user_comments(username):\n # comment = [\n # comment for comment in commentslist if comment[\"username\"] == username\n # ]\n return commentslist", "def user_comments(request, name):\n\n comments = User.objects.get(username = name).comments.all()\n context_instance=RequestContext(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }