query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Create permvm if not exist and insert into FAB security model for alldags.
def create_perm_vm_for_all_dag(self) -> None: # create perm for global logical dag for resource_name in self.DAG_RESOURCES: for action_name in self.DAG_ACTIONS: self._merge_perm(action_name, resource_name)
[ "def pensum_postsave_handler(sender, instance, **kwargs):\n if kwargs[\"created\"] and instance.editable:\n directores = Usuario.objects.filter(funcionario__autoridad__activo=True,\n funcionario__autoridad__autoridadprogramaestudio__programa_estudio__pensums=inst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a primative parser.
def __init__(self): self.prim_parser = parser.Parser()
[ "def test_init(self):\n from Perspectives import NotaryParser\n parser = NotaryParser()", "def __init__(self):\n\n self.statement_parser = statement_parser.StatementParser()\n self.program = Program()", "def __init__(self, parser_params):\n self.parser_params = parser_params",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the PRINT statement. The arguments of print can be a primative or arithmetic expression.
def parse_print(self, words): print_obj = Print() input_str = ' '.join(words) obj = self.prim_parser.parse_arith_expr(input_str) if obj: print_obj.arg = obj else: obj = self.prim_parser.parse_primative_obj(input_str) if obj: p...
[ "def print_expr(expr):\n return PBA.print_expr(expr)", "def visit_Print(self, node):\n node = self.generic_visit(node)\n new = PonyConsole.NodeHelper(node)\n return new.Expr(\n value=new.Call(\n func=new.Name(id='_pony_print'),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the LET statement args. The arguments are a variable, "=", and an expression.
def parse_let(self, words): let_obj = Let() obj_var = self.prim_parser.parse_var(words[0]) if obj_var: let_obj.var = obj_var if words[1] == '=': rest = words[2:] rest_str = ' '.join(words[2:]) arith_expr_obj = self.prim_par...
[ "def parse_arguments(args):", "def parse(s:str,nonterms:List[Nonterminal], nt_of_name=None, names=None) -> Expr:\n if names is None:\n names = [nonterm.name_noargc for nonterm in nonterms]\n if nt_of_name is None:\n nt_of_name = {(nt.name_noargc,nt.argc):nt for nt in nonterms}\n\n # fn call...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the GOTO statement. The argument can be anything that evaluates to a number label.
def parse_goto(self, words): goto_obj = Goto() input_str = ' '.join(words) obj = self.prim_parser.parse_arith_expr(input_str) if obj: goto_obj.label = obj else: obj = self.prim_parser.parse_num(input_str) if obj: goto_obj.labe...
[ "def goto(self, label):\n\t\treturn LowLevelILExpr(core.BNLowLevelILGoto(self.handle, label.handle))", "def cg_goto(self, cmd):\n label = self.makeLabel(cmd)\n self.asm(unindent(f\"\"\"\n @{label}\n 0;JMP\n \"\"\"))", "def _ifgoto(self, label):\n code = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the NEXT statement.
def parse_next(self, words): next_obj = Next() if len(words) == 1: var_obj = self.prim_parser.parse_var(words[0]) if var_obj: next_obj.var = var_obj else: raise StatementParseError( 'Invalid NEXT statement var {0}....
[ "def _next(tokens):\n return tokens.next(skip=_is_comment)", "def next(self):\n return self._statcmd('NEXT')", "def parse_next_instruction(self) -> None:\n instruction = self.program[self.pointer]\n opcode = instruction % 100\n if opcode == 99:\n self.halt = True\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the IFTHEN statement.
def parse_ifthen(self, words): ifthen_obj = IfThen() if len(words) == 5: arg1_obj = self.prim_parser.parse_primative_obj(words[0]) bool_op_obj = self.prim_parser.parse_bool_op(words[1]) arg2_obj = self.prim_parser.parse_primative_obj(words[2]) then_flag =...
[ "def parseIfStatement( ): # parse rountine for the if and uses the if class to print out the appropriate string\n\n\ttok = tokens.peek( )\n\tif debug: print( \"ifStatement: \", tok )\n\tstart = match( \"if\" )\n\texpr = expression( )\n\tblk = parseBlock( )\n\telseblk = None\n\ttok = tokens.peek( )\n\tif tok == \"el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the END statement.
def parse_end(self, words): end_obj = End() if words: raise StatementParseError( 'The END statement should have no extra words: {0}.'.format( words)) return end_obj
[ "def end() -> Parser:\n return End()", "def end():\n return EndBlock()", "def fix_end(self, node):\n if node.header.tokens[0].type == Token.SEPARATOR:\n indent = node.header.tokens[0]\n else:\n indent = Token(Token.SEPARATOR, self.formatting_config.separator)\n n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a set of statement words. The label line number has already been removed and the first word is the statement keyword. The rest of the words are the statement arguments.
def parse_statement(self, words): keyword = words[0] rest = words[1:] if keyword == 'PRINT': obj = self.parse_print(rest) elif keyword == 'LET': obj = self.parse_let(rest) elif keyword == 'GOTO': obj = self.parse_goto(rest) elif keywo...
[ "def parseStmt(line):\n print(\"Statement\")\n index=0\n if line[0] == 's':\n print(\"Set\")\n index += 4\n rest = line[index:]\n cmds = str.split(rest, ',')\n parseSet(cmds)\n elif line[0] == 'h':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trap JSON decoding failures and provide more detailed errors Remove ')]}' XSS prefix from data if it is present, then decode it as JSON and return the results.
def decode_json(raw): # Gerrit's REST API prepends a JSON-breaker to avoid XSS vulnerabilities if raw.text.startswith(")]}'"): trimmed = raw.text[4:] else: trimmed = raw.text # Try to decode and bail with much detail if it fails try: decoded = json.loads(trimmed) except...
[ "def _reject_invalid_json(val: Any) -> None:\n raise ValueError(f\"Invalid JSON value: {val!r}\")", "def test_cli_format_error_handler_broken_json():\n resp = MagicMock()\n resp.json.side_effect = ValueError(\"\")\n resp.text = \"Not JSON\"\n output = format_utils.cli_format_error_handler(resp)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the Gerrit REST API
def query_gerrit(offset=0): url = 'https://review.opendev.org/changes/' LOG.debug('fetching %s', url) raw = requests.get( url, params={ 'n': '100', 'start': offset, 'q': 'project:openstack/governance is:open', 'o': [ 'ALL_REVISI...
[ "def query_gerrit(method, params={}, verbose=0):\n\n return decode_json(requester(\"%s/%s\" % (GERRIT_BASE, method),\n params=params,\n headers={'Accept': 'application/json'},\n verbose=verbose))", "def CallGerritAp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the satellite number for a given date.
def _get_goes_sat_num(self, date): goes_operational = { 2: TimeRange("1981-01-01", "1983-04-30"), 5: TimeRange("1983-05-02", "1984-07-31"), 6: TimeRange("1983-06-01", "1994-08-18"), 7: TimeRange("1994-01-01", "1996-08-13"), 8: TimeRange("1996-03-21", "...
[ "def _get_goes_sat_num(self, date):\n\n # GOES-17 is operational but currently does not provide Level 2 data\n # GOES-16 start date is based on the availability of regular level 1b data\n suvi_operational = {\n 16: TimeRange(\"2018-06-01\", parse_time(\"now\")),\n }\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the best satellite number for a given date.
def _get_goes_sat_num(self, date): # GOES-17 is operational but currently does not provide Level 2 data # GOES-16 start date is based on the availability of regular level 1b data suvi_operational = { 16: TimeRange("2018-06-01", parse_time("now")), } results = [] ...
[ "def _get_goes_sat_num(self, date):\n goes_operational = {\n 2: TimeRange(\"1981-01-01\", \"1983-04-30\"),\n 5: TimeRange(\"1983-05-02\", \"1984-07-31\"),\n 6: TimeRange(\"1983-06-01\", \"1994-08-18\"),\n 7: TimeRange(\"1994-01-01\", \"1996-08-13\"),\n 8...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the loglikelihood of neighboring solutions of a batch of nodes by changing their membership. If a higher loglikelihood was achieved the best solution will be returned, else a tuple of three np.nan is returned.
def calc_node_neigh_solutions(event_dict, n_classes, duration, node_membership, log_lik_init, node_batch): best_neigh = (np.nan, np.nan, np.nan) log_lik = log_lik_init # node_membership = node_membership.copy() for n_i in node_batch: n_i_class = node_membership[n_i] # Adding a constra...
[ "def loglikelihood(self, net):\n\n adjmat = net.edges.adjacency_matrix\n\n # if any of the mustexist or mustnotexist constraints are violated,\n # return negative infinity\n if (not (adjmat | self.mustexist).all()) or \\\n (adjmat & self.mustnotexist).any():\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs local search / hill climbing to increase loglikelihood of the model by switching the community of a single node at a time.
def block_local_search(event_dict, n_classes, node_membership_init, duration, max_iter=100, n_cores=-1, return_fitted_param=False, verbose=False): n_nodes = len(node_membership_init) nodes = np.arange(n_nodes) node_membership = node_membership_init # estimate initial params of bl...
[ "def find_local_community(G, seed_node, weight, debug_log=False):\n nodes_in_community = seed_node if isinstance(seed_node, list) else [seed_node]\n modularity = edge_modularity(G, nodes_in_community=nodes_in_community, weight=weight)\n neighbor_edges = get_neighbor_edges(G, nodes_in_community=nodes_in_com...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make Status comparable with self by code
def __eq__(self, other: Union[int, Status]): if isinstance(other, int): return self.code == other return isinstance(other, self.__class__) and self.code == other.code
[ "def test_status_comparison(self):\n\n a = Status('OK',0)\n b = Status('OK',0)\n assert a == b\n assert not a is b\n assert Status('Test',0) < Status('Test',1)\n assert Status('Test',1) > Status('Test',0)", "def __eq__(self: \"Status\", other: \"Status\") -> bool: # type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
failed reason of the bulk insert task.
def failed_reason(self): return self._infos.get(BulkInsertState.FAILED_REASON, "")
[ "def import_failure_reason(self) -> str:\n return pulumi.get(self, \"import_failure_reason\")", "def insert_failed():\n return JsonResponse({'code': '4037', 'message': status_code['4037']}, safe=False)", "def _raise_bulk_write_error(full_result):\n ...", "def testBulkAddTaskResultErrors(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
target collection's name of the bulk insert task.
def collection_name(self): return self._infos.get(BulkInsertState.IMPORT_COLLECTION, "")
[ "def name(cls):\n if cls.__collection_name__ is None:\n return inflection.underscore(cls.__name__)\n return cls.__collection_name__", "def get_collection_filename(collection: str) -> str:\n return os.path.join(data_dir, f\"{collection}_data_source.pbtxt\")", "def task_name(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
target partition's name of the bulk insert task.
def partition_name(self): return self._infos.get(BulkInsertState.IMPORT_PARTITION, "")
[ "def task_name(self):\n return self._task_name", "def task_name(self):\n if self.__pb.has_task_name():\n return self.__pb.task_name()", "def task_name(self) -> str:\n return self._task_name", "def _staging_hll_sketches_tbl_name(self):\n return 'staging_hll_sketches_import_{0}'.for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A readable string converted from the timestamp when this task is created.
def create_time_str(self): ts = time.localtime(self._create_ts) return time.strftime("%Y-%m-%d %H:%M:%S", ts)
[ "def creation_time_str(self):\n return \"%Y/%m/%d %I:%M:%S\".format(self.creation_time)", "def creation_timestamp(self) -> str:\n return pulumi.get(self, \"creation_timestamp\")", "def creation_time(self) -> str:\n return pulumi.get(self, \"creation_time\")", "def _get_timestamp():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Возвращает кодировку текста внешнему потребителю
def get_text_coding(self): return self.text_coding
[ "def get_text():", "def get_coding(text):\r\n for line in text.splitlines()[:2]:\r\n result = CODING_RE.search(line)\r\n if result:\r\n return result.group(1)\r\n return None", "def code_display(self):\r\n return u'%s-%s-%s' % (self.code[:3], self.code[3:6], self.code[6:])"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a User based on input from HTML page, returns a confirmation of their login and what is currently in their pantry.
def make_user(): names = request.args.get('names', 1, type=str) #raw text input from HTML page global db global current_user current_user = User(names, db) # Adding the user to the db occurs in the user class, # only in the get_pantry method str_pantry = current_user.get_pantry() if str_pantry == "": ...
[ "def make_new_user():\n return render_template('users/new_user_form.html')", "def goto_make_new_user():\n\n return render_template('users/new.html')", "def create_new_user(self):\n self.create_new_user_dialog = Registration()\n self.create_new_user_dialog.show()", "def input_and_create_use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of ingredients, adds these ingredients to current user's pantry.
def update_pantry(): pantry_ingredients = request.args.get('pantry', '', type=str) #raw input from HTML page of ingredients global current_user current_user.pantry.make_pantry(pantry_ingredients) #calls recipe_program function make_pantry() current_user.pantry.save_pantry() return jsonify(pantry = pantry_ingr...
[ "def populate_ingredients(self, ingredients_list: IngredientsPage) -> None:\n logger.debug(\"Writing ingredients to 'ingredients' table in the database.\")\n with DatabaseConnect(self.host) as cursor:\n for ingredient in ingredients_list.ingredients:\n name = ingredient.name\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the max total cook time from html, returns a confirmation of this time, and sets global time variable
def timed_recipes(): time = request.args.get('time', 0, type=int) #raw input from HTML page global time_global time_global = time #sets global time to inputted time, for use in search function return jsonify(cooktime=time_global) #returns a confirmation of the input tiime
[ "def max_cook_time():\n unformated_time = str(search_object.get_max_cooking_time())\n time_minutes = int(unformated_time.split(\":\")[0]) * 60 + int(\n unformated_time.split(\":\")[1]\n )\n return time_minutes", "def setSubmitTime(t):", "def get_recipe_time(soup_recipe):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract topk entities given seeds.
def get_topk_extracted_ent(self, seeds, alpha, topk): #tf.logging.info('Start ppr') ppr_scores = csr_personalized_pagerank(seeds, self.data.adj_mat_t_csr, alpha) #tf.logging.info('End ppr') sorted_idx = np.argsort(ppr_scores)[::-1] e...
[ "def search_top_k(self, query, k):\r\n result = []\r\n for item in self.training_set:\r\n d = utilities.calculate_distance(query, item[:-1])\r\n result.append((d, item))\r\n if len(result) > k:\r\n # replace\r\n result.sort(key = lambda (x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sorts urls into groups based on shared url directory paths.
def group_by_dir(urlist): dir_groups = {} for url in urlist: net_subdir, filename = url_unquote(url).rsplit('/',1) if net_subdir in dir_groups: dir_groups[net_subdir].append((url, filename)) else: dir_groups[net_subdir] = [(url, filename)] return dir_groups
[ "def group_urls(urls):\n for (score, group) in itertools.groupby(urls, operator.itemgetter(0)):\n yield (score, [url for score, url in group])", "def group_urls(urls):\r\n for (score, group) in itertools.groupby(urls, operator.itemgetter(0)):\r\n yield (score, [url for score, url in group])", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute and return some property from the config options. Use in a template as config. {{ '{{' }} config.computed_some_property {{ '}}' }}
def computed_some_property(config): return config.something + 10
[ "def property(self, config):\n if self.var_type == VarType.cpp_bool:\n return '@property (nonatomic, getter=is{1}) BOOL {0};'\\\n .format(self.__objc_name(), string_utils.first_char_to_upper(self.__objc_name()))\n elif self.var_type == VarType.cpp_string or self.var_type == V...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate that the driver configuration is sane/complete Return (status, message) if there is a problem or (None, None) if there are no issues. Delete this function if it's not needed.
def custom_assess_status_check(self): options = self.options # can check options.thing to ensure that it makes sense # if wrong return 'blocked', "The driver is badly configured ..." return None, None
[ "def validate_driver_configuration(self, driver_config):\n pass", "def _validate_config(self):\n pass", "def validate_config(self):\n pass", "def _validate_config(self):\n logger.info('Validating charm config')\n config = self.model.config\n required = ['product-id']\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assuming that the configuration data is valid, return the configuration data for the principal charm.
def get_config_for_principal(self, auth_data): # If there is no auth_data yet, then we can't write our config. if not auth_data: return {} # If the state from the assess_status is not None then we're blocked, # so don't send any config to the principal. state, message...
[ "def get_config(self):\n return self.full_config", "def config_data(self):\n return self.__config_data", "def config_data(self):\n if self._key not in self._user_keys():\n raise CouldNotFindUserException(self._key, self._user_keys())\n return next(data for data in self.CON...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test requesting an empty, default node using a Component.
def testInfoEmptyDefaultNodeComponent(self): self.stream_start(mode='component', jid='tester.localhost', plugins=['xep_0030']) self.recv(""" <iq type="get" id="test"> <query xmlns="http://jabber.org/protocol/disco#info" /> ...
[ "def test_default_node_no_children():\n a_node = Node(5)\n assert a_node.left is None\n assert a_node.right is None", "def test_empty_node():\n try:\n Node({})\n except Exception as e:\n assert str(e) == 'input info has more than 1 entry!'\n # create node with empty connection\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Results for info queries directed to a particular node MUST include the node in the query response.
def testInfoIncludeNode(self): self.stream_start(mode='client', plugins=['xep_0030']) self.xmpp['xep_0030'].static.add_node(node='testing') self.recv(""" <iq to="tester@localhost/resource" type="get" id="test"> <query xmlns="http://jabber.org/pr...
[ "def __disco_info(self,iq):\n q=iq.get_query()\n if q.hasProp(\"node\"):\n node=from_utf8(q.prop(\"node\"))\n else:\n node=None\n info=self.disco_get_info(node,iq)\n if isinstance(info,DiscoInfo):\n resp=iq.make_result_response()\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Results for items queries directed to a particular node MUST include the node in the query response.
def testItemsIncludeNode(self): self.stream_start(mode='client', plugins=['xep_0030']) self.xmpp['xep_0030'].static.add_node(node='testing') self.recv(""" <iq to="tester@localhost/resource" type="get" id="test"> <query xmlns="http://jabber.org/p...
[ "def __disco_items(self,iq):\n q=iq.get_query()\n if q.hasProp(\"node\"):\n node=from_utf8(q.prop(\"node\"))\n else:\n node=None\n items=self.disco_get_items(node,iq)\n if isinstance(items,DiscoItems):\n resp=iq.make_result_response()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test using a dynamic info handler for a particular JID.
def testDynamicInfoJID(self): self.stream_start(mode='client', plugins=['xep_0030']) def dynamic_jid(jid, node, ifrom, iq): result = self.xmpp['xep_0030'].stanza.DiscoInfo() result['node'] = node result.add_identity('client', 'console', name...
[ "def testOverrideJIDInfoHandler(self):\n self.stream_start(mode='client',\n plugins=['xep_0030'])\n\n def dynamic_jid(jid, node, ifrom, iq):\n result = self.xmpp['xep_0030'].stanza.DiscoInfo()\n result['node'] = node\n result.add_identity('clie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test overriding a JID info handler.
def testOverrideJIDInfoHandler(self): self.stream_start(mode='client', plugins=['xep_0030']) def dynamic_jid(jid, node, ifrom, iq): result = self.xmpp['xep_0030'].stanza.DiscoInfo() result['node'] = node result.add_identity('client', 'consol...
[ "def testDynamicInfoJID(self):\n self.stream_start(mode='client',\n plugins=['xep_0030'])\n\n def dynamic_jid(jid, node, ifrom, iq):\n result = self.xmpp['xep_0030'].stanza.DiscoInfo()\n result['node'] = node\n result.add_identity('client', 'co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test overriding the global JID info handler.
def testOverrideGlobalInfoHandler(self): self.stream_start(mode='component', jid='tester.localhost', plugins=['xep_0030']) def dynamic_global(jid, node, ifrom, iq): result = self.xmpp['xep_0030'].stanza.DiscoInfo() result['node...
[ "def testOverrideJIDInfoHandler(self):\n self.stream_start(mode='client',\n plugins=['xep_0030'])\n\n def dynamic_jid(jid, node, ifrom, iq):\n result = self.xmpp['xep_0030'].stanza.DiscoInfo()\n result['node'] = node\n result.add_identity('clie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test sending a discoinfo query to another entity and receiving the result.
def testGetInfoRemote(self): self.stream_start(mode='client', plugins=['xep_0030']) events = set() def handle_disco_info(iq): events.add('disco_info') self.xmpp.add_event_handler('disco_info', handle_disco_info) self.xmpp.wrap(self.xmpp...
[ "def __disco_info(self,iq):\n q=iq.get_query()\n if q.hasProp(\"node\"):\n node=from_utf8(q.prop(\"node\"))\n else:\n node=None\n info=self.disco_get_info(node,iq)\n if isinstance(info,DiscoInfo):\n resp=iq.make_result_response()\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test using a dynamic items handler for a particular JID.
def testDynamicItemsJID(self): self.stream_start(mode='client', plugins=['xep_0030']) def dynamic_jid(jid, node, ifrom, iq): result = self.xmpp['xep_0030'].stanza.DiscoItems() result['node'] = node result.add_item('tester@localhost', node='f...
[ "def testOverrideJIDItemsHandler(self):\n self.stream_start(mode='client',\n plugins=['xep_0030'])\n\n def dynamic_jid(jid, node, ifrom, iq):\n result = self.xmpp['xep_0030'].stanza.DiscoItems()\n result['node'] = node\n result.add_item('tester...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test overriding a JID items handler.
def testOverrideJIDItemsHandler(self): self.stream_start(mode='client', plugins=['xep_0030']) def dynamic_jid(jid, node, ifrom, iq): result = self.xmpp['xep_0030'].stanza.DiscoItems() result['node'] = node result.add_item('tester@localhost',...
[ "def testOverrideGlobalItemsHandler(self):\n self.stream_start(mode='component',\n jid='tester.localhost',\n plugins=['xep_0030'])\n\n def dynamic_global(jid, node, ifrom, iq):\n result = self.xmpp['xep_0030'].stanza.DiscoItems()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test overriding the global JID items handler.
def testOverrideGlobalItemsHandler(self): self.stream_start(mode='component', jid='tester.localhost', plugins=['xep_0030']) def dynamic_global(jid, node, ifrom, iq): result = self.xmpp['xep_0030'].stanza.DiscoItems() result['no...
[ "def testOverrideJIDItemsHandler(self):\n self.stream_start(mode='client',\n plugins=['xep_0030'])\n\n def dynamic_jid(jid, node, ifrom, iq):\n result = self.xmpp['xep_0030'].stanza.DiscoItems()\n result['node'] = node\n result.add_item('tester...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test sending a discoitems query to another entity and receiving the result.
def testGetItemsRemote(self): self.stream_start(mode='client', plugins=['xep_0030']) events = set() results = set() def handle_disco_items(iq): events.add('disco_items') results.update(iq['disco_items']['items']) self.xmpp.add...
[ "def test_search_transaction_dispute_item(self):\n pass", "def test_get_items_peas_get(self):\n pass", "def test_search_charge_item(self):\n pass", "def __disco_items(self,iq):\n q=iq.get_query()\n if q.hasProp(\"node\"):\n node=from_utf8(q.prop(\"node\"))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use nlp to find nouns
def get_nouns(self): blob = TextBlob(self.raw_string) for word, tag in blob.tags: if tag in ['NNP', 'NN']: self.nouns.append(word.lemmatize())
[ "def parse(sentence):\n return nlp(sentence)", "def extract_nouns(article_content):\r\n #load spacy for English\r\n doc = nlp(article_content)\r\n compound_val = '';#For compound words, Ex: First token is Donald, and second token is Trump.\r\n #It would be better to do a wiki search for \"Donald Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Petty prints using custom pprint class, formatting unicode characters
def pprint(self): PrettyPrintUnicode().pprint(self.data)
[ "def pprint_color(obj):\n print(highlight(pformat(obj), Python3Lexer(), Terminal256Formatter()))", "def pformat(object):\r\n return PrettyPrinter().pformat(object)", "def pretty_p(x):\n if 'P' in x:\n x = x.replace('P', '𝔓')\n return x", "def pprint(object, stream=None):\r\n printer = P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform rankbased inverse normal transform to a numeric Pandas series
def inverse_rank_norm(values): #values = pd.Series([5, 7, 2, 1, 1]) quantiles = (values.rank()-0.5)/(len(values)) return ss.norm.ppf(quantiles)
[ "def rank_transform(X):\n return np.apply_along_axis(scipy.stats.rankdata, 0, X)", "def normalize_series(series):\n return (series - series.mean()) / (series.max() - series.min())", "def invcov_index(indicators):\n df = indicators.copy()\n df = (df-df.mean())/df.std()\n I = np.ones(df.shape[1])\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log `engine.state.metrics` with given `engine` and `tag`.
def log_metrics(engine: Engine, tag: str) -> None: metrics_format = "{0} [{1}/{2}]: {3}".format( tag, engine.state.epoch, engine.state.iteration, engine.state.metrics ) engine.logger.info(metrics_format)
[ "def log_metrics(self, mode='train'):\n if mode == 'train':\n augs = {\n 'value': self.logger_utils['train_metrics'](), \n 'on_step':True, \n 'on_epoch':True, \n 'prog_bar':True}\n else:\n augs = {\n 'valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup logger with `ignite.utils.setup_logger()`.
def setup_logging(config: Any) -> Logger: green = "\033[32m" reset = "\033[0m" logger = setup_logger( name=f"{green}[ignite]{reset}", level=logging.DEBUG if config.debug else logging.INFO, format="%(name)s: %(message)s", filepath=config.output_dir / "training-info.log", )...
[ "def setup_logging():\n log.setup('keystone')", "def setup_logger():\n log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n log_file = os.path.join(log_dir, 'management.log')\n project_logger.setup_logger(log_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If something is not a list already make it one, otherwise simply return something
def aslist(something): return something if isinstance(something, list) else [something]
[ "def listify(list_or_value):\n if isinstance(list_or_value, list):\n return list_or_value\n else:\n return [list_or_value]", "def listify(value):\n if isinstance(value, list):\n return value\n else:\n return [value]", "def listify(arg):\n if isinstance(arg, list):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a schema name like DISCOVER_SCHEMA_ROWSETS into a method name like getSchemaRowsets. 1. split into parts by _
def schemaNameToMethodName(schemaName): parts = schemaName.split("_") def replace(what): if what == "DBSCHEMA": return "DBSchema" elif what == "MDSCHEMA": return "MDSchema" elif what == "DISCOVER": return "" return what.lower().capitalize() return "get" ...
[ "def resolver(schema):\n name = schema.__name__\n if name.endswith(\"Schema\"):\n return name[:-6] or name\n return name", "def make_get_schema_func(schema):\n def get_schema():\n # Iterate over all tables\n return schema.get_create_sql()\n return get_schema", "def type_name(name):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform linting of the source code
def lint(ctx): print('Running linting...') ctx.run('pylint metrics')
[ "def lint(session):\n session.install(\"pre-commit\")\n session.run(\"pre-commit\", \"run\", \"--all-files\")", "def lint(session):\n session.install(\"flake8\")\n session.run(\"flake8\", \"\")", "def commands_lint():\n lint()", "def lint(context):\n context.run(\" \".join([\n \"a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the build metrics
def metrics(_): collector = BuildsCollector() build_metrics, headers = collector.get_metrics_table() print(tabulate(build_metrics, headers=headers))
[ "def _print_metrics(self, *args, **kwargs):\n pass", "def print_metric(self):\r\n print(f'\\n\\n{self.sort} metric of size {self.n}')\r\n print(f'algorithm: {self.algo}')\r\n print(f'number of comparisons: {self.comps}')\r\n print(f'number of exchanges: {self.exs}')\r\n p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A hypothesis decorator to return a list of strategies
def strategy_lists( draw, strategies=axl.short_run_time_strategies, min_size=1, max_size=len(axl.short_run_time_strategies), ): strategies = draw( lists(sampled_from(strategies), min_size=min_size, max_size=max_size) ) return strategies
[ "def strategies():\n strategies = []\n\n # Add RFind strategies (2 meta-strategies P0 and P'0 for each)\n limits=[50, 35, 20, 10]\n sources = ['his', 'our', 'dna']\n for limit in limits:\n for source in sources:\n strategies.extend(\n generate_meta_strategy_pair(RFindStrategy,\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A hypothesis decorator to return a probabilistic ending spatial tournament.
def prob_end_spatial_tournaments( draw, strategies=axl.short_run_time_strategies, min_size=1, max_size=10, min_prob_end=0, max_prob_end=1, min_noise=0, max_noise=1, min_repetitions=1, max_repetitions=20, ): strategies = draw( strategy_lists( strategies=str...
[ "def generate_full_hypothesis(self):\n return SimHypothesis(self.trgt_sentence, self.score,\n self.score_breakdown, self.actions, self.lst_id)", "def test_end_to_end():\n strat1 = RandomStrategy()\n strat2 = RandomStrategy()\n games = 10\n point_cap = 100\n df = simul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the todo file and returns a list of Todos. The "id" of each todo refers to the zeroindexed line number of that todo.
def read_file(filename) -> List[Todo]: with pathlib.Path(filename).expanduser().open('r') as fp: return [Todo(_id, line) for _id, line in enumerate(fp)]
[ "def read_todo_file(self):\n\n todo = []\n in_progress = []\n done = []\n if os.path.exists('TODO.txt'):\n todo_fp = open('TODO.txt', 'r')\n state = 0\n line = todo_fp.readline()\n while line:\n line = line.strip()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a streaming pull and process alerts through the `callback`. The streaming pull happens in a background thread. A `queue.Queue` is used to communicate between threads and enforce the stopping condition(s).
def stream_alerts( self, user_filter=None, user_callback=None, **user_kwargs ): # callback doesn't accept kwargs. set attribute instead. kwargs = self._add_default_kwargs(**user_kwargs) self.callback_kwargs = { "user_filter": user_filter, "user_callback": user...
[ "def start_streaming(self, callback):\n\n self.twitter_listener = TwitterListener(\n callback=callback, logs_to_cloud=self.logs_to_cloud)\n twitter_stream = Stream(self.twitter_auth, self.twitter_listener)\n\n self.logs.debug(\"Starting stream.\")\n twitter_stream.filter(follo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shutdown the streaming pull in the background thread gracefully.
def _stop(self): self.streaming_pull_future.cancel() # Trigger the shutdown. self.streaming_pull_future.result() # Block until the shutdown is complete.
[ "def stream_shutdown(self):\n if self._stream_listener:\n if self._debug:\n self._log.debug('shutdown packet streaming')\n self.stream_pause()\n self._kill_stream_listener()", "def stop(self):\n self.stream.stop()\n self.running = False", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process a single alert; run user filter; save alert; acknowledge Pub/Sub msg. Used as the callback for the streaming pull.
def callback(self, message): kwargs = self.callback_kwargs if kwargs['return_msg']: self._callback_return_full_message(message) return # unpack try: alert_dict, metadata_dict = self._unpack(message) except Exception as e: self._lo...
[ "def stream_alerts(\n self, user_filter=None, user_callback=None, **user_kwargs\n ):\n # callback doesn't accept kwargs. set attribute instead.\n kwargs = self._add_default_kwargs(**user_kwargs)\n self.callback_kwargs = {\n \"user_filter\": user_filter,\n \"user_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save the alert to a database.
def save_alert(self, alert): self.database_list.append(alert) # fake database for demo
[ "def write(self, alert: AlertModel):\n try:\n self.session.add(alert)\n self.session.commit()\n except Exception as e:\n self.session.rollback()\n raise e\n finally:\n self.session.close()", "def _save_alert(self, alert):\n with co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to create the subscription.
def _create_subscription(self): try: self.client.create_subscription( name=self.subscription_path, topic=self.topic_path ) except NotFound: # suitable topic does not exist in the Pitt-Google project raise ValueError( ( ...
[ "def test_create_a_new_subscription(self):\n pass", "def test_create_subscription(self):\n pass", "def create_subscription(self, query):\n pass", "def create_subscription(self):\n\n self.clear_subscriptions()\n\n # creating new subscription\n r = self.fitbit_service.post('http://...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete the subscription. This is provided for the user's convenience, but it is not necessary and is not automatically called. Storage of unacknowledged Pub/Sub messages does not result in fees. Unused subscriptions automatically expire; default is 31 days.
def delete_subscription(self): try: self.client.delete_subscription(subscription=self.subscription_path) except NotFound: pass else: self._log_and_print(f'Deleted subscription: {self.subscription_path}')
[ "def push_subscription_delete(self):\r\n self.__api_request('DELETE', '/api/v1/push/subscription')", "def delete(self):\n entity_manager.delete_subscription(self)", "def delete_event_subscription(SubscriptionName=None):\n pass", "def delete_subscription(self, subscriptionId):\n\n r = self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should return a list of title cased names, each name appears only once
def dedup_and_title_case_names(names): return list(set(name.title() for name in names))
[ "def dedup_and_title_case_names(names):\n names1 =[]\n for n in names:\n if n.title() not in names1:\n names1.append(n.title())\n return names1\n # return [n.title() for n in names if n.title() not in names1]\n pass", "def dedup_and_title_case_names(names):\n title_names = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns names list sorted desc by surname
def sort_by_surname_desc(names): names = dedup_and_title_case_names(names) return sorted(names, key=lambda name: name.split(' ')[-1], reverse=True)
[ "def sort_by_surname_desc(names):\n names = dedup_and_title_case_names(names)\n # ...\n last_names = []\n surname_desc = []\n for name in names:\n last_names.append(name.split()[-1])\n for last_name in sorted(last_names, reverse=True):\n for name in names:\n if name.endswi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the shortest first name (str). You can assume there is only one shortest name.
def shortest_first_name(names): names = dedup_and_title_case_names(names) return sorted([name.split()[0] for name in names], key=len)[0]
[ "def shortest_first_name(names):\n names = dedup_and_title_case_names(names)\n shortest = min(names, key=lambda n: len(n.split()[0]))\n shortest_name = shortest.split()[0]\n return shortest_name\n\n assert shortest == 'Dan'", "def shortest_first_name(names):\n names = dedup_and_title_case_names(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gname points to a graph stored (pickled) on disk.
def load_graph( gname ): return NX.read_gpickle( gname )
[ "def save_graph(self, path):\n if path.split('.')[-1]=='gexf':\n nx.write_gexf(self.graph, path)\n else:\n nx.write_gpickle(self.graph, path)", "def read_neighbor_graph_pickle(gname, graph_dir):\n graph_path = os.path.join(graph_dir, gname+\".pickle\")\n if os.path.exists...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates min, max, total with the given value
def update(self, value): if value < self.min: self.min = value if value > self.max: self.max = value self.total += value self.instances += 1 self.values.append(value)
[ "def update_value(self, value: int, min_value: 'Optional[int]' = None,\n max_value: 'Optional[int]' = None) -> None:\n self.value.set(value)\n self._initial_value = value\n if min_value is not None:\n self._min_value = min_value\n if max_value is not None:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that causal convolutions only operate on leftward inputs
def test_causal_convolution(conv1d_placeholder, spatial_onehot, output_size, width): conv_layer = Convolution((3, output_size), lambda x: 1, padding="causal") output = conv_layer(conv1d_placeholder) output_width = output.axes.find_by_name("W")[0].length assert output_width == width, "Causal convolution ...
[ "def test_simple_convolution(self):\n t = np.arange(0, 100, 0.01)\n x = (np.ones(len(t))-np.exp(-1000*t))\n waves = vf. windowConv(x, np.array([-1, -2]), t)\n\n testing.assert_allclose(waves[1],\n (np.ones(len(t))-np.exp(-2*t))/2, rtol=1e-2, atol=0.01,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that axes into a conv are the same as axes out
def test_axis_preservation(conv1d_placeholder, output_size): conv_layer = Convolution((3, output_size), lambda x: 1) output = conv_layer(conv1d_placeholder) assert output.axes == conv1d_placeholder.axes, ("Output axes are not the same as input axes: " "{} ...
[ "def test_channel_axis_introduction(conv1d_no_channel_axis, output_size, channel_axis):\n conv_layer = Convolution((3, output_size), lambda x: 1)\n output = conv_layer(conv1d_no_channel_axis)\n t_axes = conv1d_no_channel_axis.axes + channel_axis\n assert output.axes.is_equal_set(t_axes), (\"Output axes ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a channel axis is added when it doesn't exist in the input
def test_channel_axis_introduction(conv1d_no_channel_axis, output_size, channel_axis): conv_layer = Convolution((3, output_size), lambda x: 1) output = conv_layer(conv1d_no_channel_axis) t_axes = conv1d_no_channel_axis.axes + channel_axis assert output.axes.is_equal_set(t_axes), ("Output axes are not in...
[ "def test_alternate_channel_axes(conv1d_placeholder, output_size, channel_axis):\n channel_axis.name = \"channel\"\n assert len(conv1d_placeholder.axes.find_by_name(\"channel\")) == 1\n\n conv_layer = Convolution((3, output_size), lambda x: 1)\n with pytest.raises(IncompatibleAxesError):\n conv_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that spatial axis names are modifiable
def test_alternate_spatial_axes(conv1d_placeholder, output_size, width_axis): width_axis.name = "time" assert len(conv1d_placeholder.axes.find_by_name("time")) == 1 conv_layer = Convolution((3, output_size), lambda x: 1) with pytest.raises(IncompatibleAxesError): conv_layer(conv1d_placeholder) ...
[ "def test_preserve_equal_name_coordinates(equal_names):\n all_names = ['var_name', 'standard_name', 'long_name']\n cubes = CubeList(generate_cube_from_dates('monthly') for _ in range(5))\n\n # Prepare names of coordinates of input cubes accordingly\n for (idx, cube) in enumerate(cubes):\n time_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that channel axis names are modifiable
def test_alternate_channel_axes(conv1d_placeholder, output_size, channel_axis): channel_axis.name = "channel" assert len(conv1d_placeholder.axes.find_by_name("channel")) == 1 conv_layer = Convolution((3, output_size), lambda x: 1) with pytest.raises(IncompatibleAxesError): conv_layer(conv1d_pla...
[ "def test_channel_axis_introduction(conv1d_no_channel_axis, output_size, channel_axis):\n conv_layer = Convolution((3, output_size), lambda x: 1)\n output = conv_layer(conv1d_no_channel_axis)\n t_axes = conv1d_no_channel_axis.axes + channel_axis\n assert output.axes.is_equal_set(t_axes), (\"Output axes ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the dilated convolution layer output matches expected. This test compares the maximum output value to an expected max output value. The expected value is computed based on the dilation parameter. The test also checks that the output size matches the expected size based on the dilaton parameter value.
def test_dilated_conv(dilation): image_size = 3 batch_size = 1 init_val = 0.1 conv_size = 3 pad = 3 N_filters = 1 image_channels = 3 model = Sequential([Convolution((conv_size, conv_size, N_filters), filter_init=ConstantInit(val=init_val), ...
[ "def test_conv2d_failure(shape, pad, stride, dilation, err_msg):\n np.random.seed(0)\n\n kernel_size = (2, 2)\n groups = 1\n dtype = \"uint8\"\n out_channels = 8\n weight_format = \"HWIO\"\n\n model, _ = _get_model(\n shape,\n kernel_size[0],\n kernel_size[1],\n 0,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
basic test of deconv fprop. ngraph/tests/test_conv.py tests ng.deconvolution bprop
def test_deconv(): # filter params R, S = 5, 5 fshape = (R, S, 1) strides = 2 filter_val_nz = np.arange(1, R * S + 1).reshape(R, S) filter_val = np.zeros(fshape) filter_val[:, :, 0] = filter_val_nz deconv = Deconvolution(fshape, filter_init=ConstantInit(filte...
[ "def test_conv_inverts_deconv(transformer_factory, input_size, filter_size, padding, stride):\n\n # convolutions whose output size are not an even multiple of stride cannot be exactly inverted\n a = (input_size + sum(padding) - filter_size) % stride\n conv_output = utils.conv_output_dim(input_size, filter_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that conv and deconv are inverse operations given the same parameters
def test_conv_inverts_deconv(transformer_factory, input_size, filter_size, padding, stride): # convolutions whose output size are not an even multiple of stride cannot be exactly inverted a = (input_size + sum(padding) - filter_size) % stride conv_output = utils.conv_output_dim(input_size, filter_size, pad...
[ "def test__inverse_transform_continuous(self):", "def test_functional_inverse(self, dim):\n M = np.random.rand(dim, dim)\n assert np.all(M == symplectic.xxpp_to_xpxp(symplectic.xpxp_to_xxpp(M)))\n assert np.all(M == symplectic.xpxp_to_xxpp(symplectic.xxpp_to_xpxp(M)))\n\n v = np.random...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new receiver object.
def __new__(cls, rtype, cluster_id=None, action=None, **kwargs): if rtype == consts.RECEIVER_WEBHOOK: from senlin.engine.receivers import webhook ReceiverClass = webhook.Webhook elif rtype == consts.RECEIVER_MESSAGE: from senlin.engine.receivers import message ...
[ "def _from_object(cls, receiver):\n kwargs = {\n 'id': receiver.id,\n 'name': receiver.name,\n 'user': receiver.user,\n 'project': receiver.project,\n 'domain': receiver.domain,\n 'created_at': receiver.created_at,\n 'updated_at': r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store the receiver in database and return its ID.
def store(self, context, update=False): timestamp = timeutils.utcnow(True) self.created_at = timeutils.utcnow(True) values = { 'id': self.id, 'name': self.name, 'type': self.type, 'user': self.user, 'project': self.project, ...
[ "def store(self, context):\n self.created_time = timeutils.utcnow()\n values = {\n 'id': self.id,\n 'name': self.name,\n 'type': self.type,\n 'user': self.user,\n 'project': self.project,\n 'domain': self.domain,\n 'created_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a receiver from receiver object.
def _from_object(cls, receiver): kwargs = { 'id': receiver.id, 'name': receiver.name, 'user': receiver.user, 'project': receiver.project, 'domain': receiver.domain, 'created_at': receiver.created_at, 'updated_at': receiver.updat...
[ "def __new__(cls, rtype, cluster_id=None, action=None, **kwargs):\n if rtype == consts.RECEIVER_WEBHOOK:\n from senlin.engine.receivers import webhook\n ReceiverClass = webhook.Webhook\n elif rtype == consts.RECEIVER_MESSAGE:\n from senlin.engine.receivers import messa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build connection params for specific user and project.
def _build_conn_params(self, user, project): service_creds = senlin_context.get_service_credentials() params = { 'username': service_creds.get('username'), 'password': service_creds.get('password'), 'auth_url': service_creds.get('auth_url'), 'user_domain_n...
[ "def _build_conn_params(self, user, project):\n cred = co.Credential.get(oslo_context.get_current(), user, project)\n if cred is None:\n raise exc.TrustNotFound(trustor=user)\n\n trust_id = cred.cred['openstack']['trust']\n\n # This is supposed to be trust-based authentication...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers an obj to this registry When locked, a RuntimeError is raised When an object with the name exists, and overwrite_existing is False, a RuntimeError is raised When the object does not extend IRegistryContent, a ValueError is raised When the object NAMEattribute is not set, a ValueError is raised
def register( self, obj: typing.Union[IRegistryContent, typing.Type[IRegistryContent]], overwrite_existing=True, ): if self.locked: raise RuntimeError(f"registry {self.name} is locked!") if not ( isinstance(obj, IRegistryContent) if not s...
[ "def register(self, obj, name=None):\n if not name:\n name = obj.__name__\n if name in self._registry:\n raise KeyError(\"Name '%s' has been registered in '%s'!\" %\n (name, self._name))\n\n # logging.vlog(1, \"Registering %s (%s) in %s.\", name, obj, self._name)\n self._re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts individual C01 file to TIF using bfconvert.
def cellomics2tiff((file_in,dir_out)): file_out = cutils.getTifPath(file_in,dir_out) # don't repeat conversion if converted file exists # and is newer than the original data if os.path.isfile(file_out) \ and os.stat(file_out).st_mtime > os.stat(file_in).st_mtime: return if plat...
[ "def read_cfin_t1():\n files, folder = fetch_cfin_multib()\n img = nib.load(pjoin(folder, 'T1.nii'))\n return img # , gtab", "def asc_to_gtif(i_dir):\n\n # Set search for all files with suffix in specified folder\n q = join(i_dir, \"*.asc\")\n # List of all TIF files\n asc_fps = glob.glob(q)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a shortened representation of a PdObject.
def short_repr(obj: PdObject, length_guide: int = 8) -> str: if isinstance(obj, list): lower_length_guide = (length_guide + 1) // 2 if len(obj) > 2 * length_guide: return "[{}, ({} more), {}]".format( ", ".join(short_repr(e, lower_length_guide) for e in obj[:length_gu...
[ "def _short_repr(obj):\n stringified = pprint.saferepr(obj)\n if len(stringified) > 200:\n return '%s... (%d bytes)' % (stringified[:200], len(stringified))\n return stringified", "def pformat(object):\r\n return PrettyPrinter().pformat(object)", "def stringReco(obj):\n name = obj.get_name()\n na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the count, sum, and sum of squares, deeply accumulated over the object.
def pd_deep_stats(obj: PdObject) -> Tuple[int, Union[int, float, complex], Union[int, float, complex]]: if isinstance(obj, Block): raise TypeError('Cannot deeply accumulate stats over block ' + repr(obj)) if isinstance(obj, (Char, int, float, complex)): v = num.numerify(obj) ...
[ "def measure(obj, depth=0):\n nodes = 0\n properties = 0\n max_depth = depth\n for (_, child) in obj.items():\n # ensure this is a node that is not a histogram\n if type(child) is dict and 'buckets' not in child:\n (child_nodes, child_properties, child_depth) = measure(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate and return the acceptance rate of the proposal. Returns
def get_acceptance(self): return self.count_accepted / self.count_proposed
[ "def _calculate_acceptance_ratio(self):\n self.candidates_nlp = self.closure()\n return torch.exp(self.params_nlp - self.candidates_nlp)", "def acceptance_fraction(self):\n return self.naccepted / self.iterations", "def _calculate_acceptance_ratio(self):\n return torch.exp(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate and return the illegal proposal rate of this proposal. (Proposing values outside the support of the parameter space e.g covariances < 0) Returns
def get_illegal(self): return self.count_illegal / self.count_proposed
[ "def emission_rate_per_aerosol_per_person_when_present(self) -> _VectorisedFloat:\n return self.known_individual_emission_rate", "def proton_collision_deexcitation_rate(self) -> u.cm**3 / u.s:\n kBTE = np.outer(const.k_B * self.temperature, 1.0 / self._psplups['delta_energy'])\n omega_upper =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Propose a new set of gmm parameters. Calls each proposal function one after another.
def propose(self, X, gmm, target, n_jobs=1): new_gmm = gmm for _ in xrange(self.propose_iterations): if self.propose_mean is not None: new_gmm = self.propose_mean.propose(X, new_gmm, target, n_jobs) if self.propose_covars is not None: new_gmm = se...
[ "def propose(self, X, gmm, target, n_jobs=1):\n num_mixtures, dimension = gmm.means.shape\n\n #sample new momentums for each mixture\n if dimension == 1:\n updated_momentum = np.array([[multivariate_normal(np.zeros(dimension), np.diag(np.ones((dimension,)))).rvs()]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the current node to the given data and assigns the node as a leaf node
def setData(self,data): self.data=data self.leaf=True
[ "def add(self, data):\n self.leaves.append(Node(data))", "def node_data(self, node_data):\n\n self._node_data = node_data", "def add_node(self, data):\n\n if self.root == None:\n self.root = AVLNode(data)\n self.root.height = 1\n return \n self.__priv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the split attribute and split value to the current node
def setSplit(self,split): self.split=split
[ "def split(self, attribute):\n if attribute not in self.attributes:\n raise KeyError('Attribute not present in node')\n \n self.split_attr = attribute\n \n # list() is used to make a copy of the list instead of pointing to the same list\n child_attributes = list(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the given node to greater value of the current node
def setGreater(self,Node): self.greater=Node
[ "def setGreater(self, node):\r\n self.greater = node", "def __gt__(self, other: 'MaxNode') -> bool:\n if self.priority == other.priority:\n return self.value < other.value\n return self.priority < other.priority", "def __gt__(self, other: 'MinNode') -> bool:\n if self.prio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the given node to lesser link of the current node
def setLesser(self,Node): self.lesser=Node
[ "def setLesser(self, node):\r\n self.lesser = node", "def stable_link_left(self, left, right):\n if left.rightChild is not None:\n right.nextSibling = left.rightChild.nextSibling\n self.updates += 1\n left.rightChild.nextSibling = right\n self.updates += 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the given csv file of a tree into list
def treeList(tree): with open(tree) as fp: line = fp.read() nodesList = line.strip().split(',') return nodesList
[ "def generate_tree(csv_data: List[List[str]], order: List[str]) -> List[NodeList]:\n tree = []\n\n for row in csv_data:\n branch = generate_branch(row, order)\n if not branch:\n continue\n\n branch[0], root_result = level_exists(branch[0], tree)\n\n for i in range(len(br...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It plots a graph of decision boundary for all the data samples in the classes
def decisionBoundary(root, figure, fileName): stepValue = 0.001 classClassification = [1, 2, 3, 4] colorClassification = ['b', 'g', 'r', 'm'] markerClassification = ['x', '+', '*', 'o'] classesList = ["Bolts", "Nuts", "Rings", "Scraps"] decisionPlot = figure.add_subplot(111) attributeValues,...
[ "def plot_decision_boundary(predict,\n classes=2,\n x_range=[0, 1],\n y_range=[0, 1],\n th=0.5):\n\n # Generate a grid with 200 points in each dimension\n hx = (x_range[1]-x_range[0])/200\n xx, yy = np.m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method for padding the input number so that program can maintain symmetry in tables
def padding(input_value, value): padding_value = str(input_value) for i in range(value - len(str(input_value))): padding_value += " " return padding_value
[ "def padding(input_num, digit):\n padded=str(input_num)\n for pedding_counter in range(digit-len(str(input_num))):\n padded+=\" \"\n return padded", "def pad_number(self, num):\n num_str = str(num)\n return '0' * (3-len(num_str)) + num_str", "def padded(row, pad_to):\n num_zeros...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the profit from the confusion matrix
def profitCalculation(confusion_matrix): numberofClasses = 4 profits = [[20, -7, -7, -7], [-7, 15, -7, -7], [-7, -7, 5, -7], [-3, -3, -3, -3]] totalProfit = 0 for count in range(numberofClasses): for counter in range(numberofClasses): totalProfit += confusion_matrix[count][counter] *...
[ "def profit_curve(cost_benefit_mat, y_pred_proba, y_true):\n n_obs = float(len(y_true))\n # Make sure that 1 is going to be one of our thresholds\n\n thresholds = np.linspace(0,1,101)\n profits = []\n for threshold in thresholds:\n y_predict = y_pred_proba >= threshold\n confusion_matri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The lines are getting split and parsed to gather the required information. a Edge with the data of lines is getting created. The list is appended by this edge
def createEdge(lines, list): res = lines.split('\\n') mains = res[0].split(' ') sid = mains[3] sid = sid[4:-1] ssource = mains[4] ssource = ssource[8:-1] starget = mains[5] starget = starget[8:-2] slabel = '' i = 2 while ('key=' in res[i]): i = i + 1 if ('EdgeLa...
[ "def convertLineData(self):\n rows = []\n currentRoute = None\n\n for line in self.tfp.lines:\n # Each line is a 3-tuple: key, value, list-of-children.\n\n # Add comments as simple strings\n if line[0] == 'smcw':\n cmt = line[1].strip()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a Relation with the given parameter
def createRelation(rid, rlabel, list, x, y): relation = Relation(rid, rlabel, x, y) list.append(relation)
[ "def create_relation(self, source, dest, rt):\n # Get the id from the idgenerator\n p=self.controller.package\n id_=self.controller.package._idgenerator.get_id(Relation)\n relation=p.create_relation(id=id_,\n members=(source, dest),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
kmeans压缩的主方法: 由于图像数据量较大,传统的kmeans方法会很慢,故选择mini batch kmeans方法。 将图像的(R,G,B)像素组合聚类后,使用每个聚类中心的像素数据代替整个聚类的像素数据。 假设k为16,那一张38比特表示的图像就被压缩为4比特表示,压缩率还是可以的。
def k_compress(img, filepath, k): img_copy = img.copy() data = np.array(img_copy).astype(np.uint8) data = data / 255. data = data.reshape((data.shape[0] * data.shape[1], 3)) kmeans = MiniBatchKMeans(n_clusters=k, init_size=3*k, batch_size=2000) kmeans.fit(data) new_colors = kmeans.cluster_ce...
[ "def kmeans_image_compression():\n im = plt.imread('colorful_img.jpg')\n N, M = im.shape[:2]\n im = im / 255 # Easier, more powerful to process images with a continuous scale.\n\n # convert to RGB array\n data = im.reshape(N * M, 3)\n\n k_means = KMeans(n_cluster=16, max_iter=100, e=1e-6)\n cen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hydrate a ViewIO into the constructor arguments for View.
def hydrate_arguments(cls, view_io: ViewIO) -> Dict: return { **super().hydrate_arguments(view_io), # TODO: should we add this here? probably not: "software_system" "paper_size": view_io.paper_size, "automatic_layout": AutomaticLayout.hydrate(view_io.automatic_lay...
[ "def hydrate_arguments(cls, static_view_io: StaticViewIO) -> Dict:\n return {\n **super().hydrate_arguments(static_view_io),\n \"animations\": map(Animation.hydrate, static_view_io.animations),\n }", "def hydrate_arguments(cls, model_item_io: ModelItemIO) -> dict:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the relationship views contained by this view.
def relationship_views(self) -> Iterable[RelationshipView]: return set(self._relationship_views)
[ "def views(self):\n return self._views", "def getViews(self):\n return list(self.__views)", "def relations(self):\n return self._relations", "def child_views(self):\n return self.children", "def getViews(self):\n return list(self.__views.keys())", "def other_views(cls):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a single relationship to this view.
def _add_relationship( self, relationship: Relationship, *, description: Optional[str] = None, order: Optional[str] = None, response: bool = False, ) -> RelationshipView: if self.is_element_in_view(relationship.source) and self.is_element_in_view( ...
[ "def add_relationship(self, relationship):\n self.relationships[relationship.parent].append(relationship)", "def add_relationship(self, rel: ResourceRelationshipDescriptor) -> None:\n self._relationships[assert_not_none(rel.name)] = rel.bind(self)", "def addRelationship(self, rel):\n _rels ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add all relationships involving the given element to this view.
def _add_relationships(self, element: Element) -> None: elements: Set[str] = {v.id for v in self.element_views} for relationship in element.get_efferent_relationships(): if relationship.destination.id in elements: self._relationship_views.add( Relationshi...
[ "def relationships(self):", "def add_relationship(self, relationship):\n self.relationships[relationship.parent].append(relationship)", "def add_relations(self, relations):\n for relation in relations:\n self.add_relation(relation)", "def addRelationship(self, rel):\n _rels = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy the layout information from another view, including child views.
def copy_layout_information_from(self, source: "View") -> None: if not self.paper_size: self.paper_size = source.paper_size for source_element_view in source.element_views: destination_element_view = self.find_element_view( element=source_element_view.element ...
[ "def copy(self):\n layout = Layout(self.g, _create=False)\n layout.copy_from(self)\n\n return layout", "def test_copying_dynamic_view_layout(empty_viewset):\n source_viewset = empty_viewset\n source_view = source_viewset.create_dynamic_view(key=\"dyn1\", description=\"test\")\n sourc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the given element is in this view.
def is_element_in_view(self, element: Element) -> bool: return self.find_element_view(element=element) is not None
[ "def __contains__(self, element: Element):\n return element in self.get_elements()", "def contains(self, element) -> bool:\n\n return self.__find_node(element) is not None", "def belongs_to(self, element, page):\n parent = element.parentNode\n\n while \"jahia:page\" != parent.nodeNam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a child element view matching a given element.
def find_element_view( self, *, element: Optional[Element] = None, ) -> Optional[ElementView]: return next( (view for view in self.element_views if view.element.id == element.id), None )
[ "def __getChildView(self, parentId, childSeq):\n # child_view = None\n # str_getChildView = \"self.vc.findViewById('\" + parentId + \"')\"\n # for index in childSeq:\n # str_getChildView += ('.children[' + str(index) + ']')\n # printLog(self.threadName + \"executing child_view...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }