query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Return the changelog as a list of tuples of the form (time, author, field, oldvalue, newvalue).
def get_changelog(self, when=0, db=None): if not db: db = self.env.get_db_cnx() cursor = db.cursor() if when: cursor.execute("SELECT time,author,field,oldvalue,newvalue " "FROM ticket_change WHERE ticket=%s AND time=%s " ...
[ "def changelog_entries():\n changelog_entries = comments or []\n for o in options or self._DEFAULT_PORT_OPTIONS:\n changelog_entries.append(\"{keyword}: {option}\".format(keyword=mini_buildd.changes.Changes.Options.KEYWORD, option=o))\n return changelog_entries", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method writes in assembler the push/pop command
def writePushPop(self, command_type, m_segment, index): #This list contains the traduction of the vm command assemblerTraduction = [] #We get the adress where we going to push/pop self.getAdressaAndStore(m_segment,index) #Then we do the push or pop if co...
[ "def writePushPop(self, command):\n\n command, segment, index = command\n\n if command == 'push':\n\n if segment == 'constant':\n \"\"\" This segment is virtual, as it does not occupy any physical space\n on the target architecture. Instead, the VM implementati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the assembly code that is the translation of the given "goto" command
def writeGoto(self, label): # Create a list to store all the assembly commands and write them later translated_commands = [] # Unconditional jump to the VM command following the label. translated_commands.append("@{}:{}".format(self.actualFile.upper(), label.upper())) tr...
[ "def write_goto(self, label):\n if self.curr_function:\n self.file.write('@{}${}\\n'\n '0;JMP\\n'.format(self.curr_function, label))\n else:\n self.file.write('@{}\\n'\n '0;JMP\\n'.format(label))", "def cg_goto(self, cmd):\n label = self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the assembly code that is the translation of the given "ifgoto" command
def writeIf(self, label): # Create a list to store all the assembly commands and write them later translated_commands = [] # Pops the topmost stack element. # If it's not zero, jumps to the VM command following the label translated_commands.append("@SP") transla...
[ "def writeIf(self, label):\n self.outputFile.write(\"if-goto {}\\n\".format(label))", "def WriteIf(self, label):\n if (debug):\n self.file.write(' // if-goto %s\\n' % (label))\n target = self._LocalLabel(label)\n\n #TODO: Write the code to complete the if-goto assuming th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the assembly code that is the translation of the given "call" command
def writeCall(self, function_name, num_args): # Update the current function. self.setFunctionName(function_name) # Create a list to store all the assembly commands and write them later translated_commands = [] # Store the return address in a local variable to use later...
[ "def _WriteCallCommon(self):\n if debug:\n self.file.write(' // call common code\\n')\n self.callLabel = self._UniqueLabel()\n self._WriteCode('(%s)' % self.callLabel)\n\n # TODO: Write the code below to handle the call, as specified in the book and notes.\n # Minus ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the assembly code that is the translation of the given "return" command
def writeReturn(self): # Create a list to store all the assembly commands and write them later translated_commands = [] # FRAME = LCL --> R14 translated_commands.append("@LCL") translated_commands.append("D=M") translated_commands.append("@R14") # FRAME ...
[ "def writeReturn(self):\n self.outputFile.write(\"return\\n\")", "def write_return(self) -> None:\n end_frame = 'R13'\n ret_address = 'R14'\n\n self._write(['@'+CodeWriter.memory_prefixes[\"local\"], \"D=M\", '@'+end_frame, \"M=D\"]) # end_frame = LCL\n self._write(['@5', 'D=D-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the assembly code that is the translation of the given "Function" command.
def writeFunction(self, function_name, num_locals): # Create a list to store all the assembly commands and write them later translated_commands = [] # Declare label for function entry. translated_commands.append("({})".format(function_name.upper())) # Allocat...
[ "def writeFunction(self, command):\n\n command, fname, numlocals = command\n\n # First update functionName attribute to reflect the name of the\n # function under translation\n self.functionName = fname\n\n # Reset call counter\n self.call_counter = 0\n\n self.code.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively remove the empty fields in the Json until there is no empty fields and subfields.
def recursive_remove_empty(j): # Handle special case where an empty "explanation_spec" "metadata" "outputs" # should not be removed. Introduced for b/245453693. temp_explanation_spec_metadata_outputs = None if ('explanation_spec' in j) and ( 'metadata' in j['explanation_spec'] and 'outputs' in j['ex...
[ "def remove_empty_fields(data_):\n if isinstance(data_, dict):\n for key, value in data_.items():\n\n # Dive into a deeper level.\n if isinstance(value, dict) or isinstance(value, list):\n value = remove_empty_fields(value)\n\n # Delete the field if it's emp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializing name, color and age attributes
def __init__(self, name, color, age): self.name = name self.color = color self.age = age self.breed = "something"
[ "def __init__(self, name, age):\r\n self.__name = name\r\n self.__age = age", "def __init__(self, name, age):\n\t\tself.name = name\n\t\tself.age = age", "def __init__(self, first_name, last_name, age, gender):\n self.first_name = first_name\n self.last_name = last_name\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulating cat to listen to our command sit
def sit(self): print(f"{self.name.title()} is listening to our command and sitting")
[ "def mt_interact(self):\n import _thread\n _thread.start_new_thread(self.listener, ())\n while 1:\n line = sys.stdin.readline()\n if not line:\n break\n self.write(line.encode('ascii'))", "def testEchoCat(self):\n pl = Pipeline(loadInitFi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulating cat to rollover
def roll_over(self): print(f"{self.name.title()} is rolling over")
[ "def doRollover(self):\n if self.stream:\n self.stream.close()\n # get the time that this sequence started at and make it a TimeTuple\n t = self.rolloverAt - self.interval\n if self.utc:\n timeTuple = time.gmtime(t)\n else:\n timeTuple = time.local...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
matches(self, accession) Returns true of accession matches this rule.
def matches(self, accession): pass
[ "def is_compatible_assembly_accession(self, acc):\n # if no filter was configured, it's a match\n if not self.assembly_accessions:\n return True\n\n if not self.fuzzy_accessions:\n return acc in self.assembly_accessions\n else:\n for specified in self.ass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make_range_matcher(spec) spec string (e.g. 'BAAABZZZ') Turns a range specification into a object that can match an accession that falls within that range. Returns a RangeMatcher() object
def make_range_matcher(spec): if '-' in spec: (start, end) = spec.split('-') elif '_' in spec: (start, end) = spec.split('_') else: raise ValueError('require specification with - or _ in it, got: ' + spec) assert end.endswith('Z'), f'Range specifier has unknown format: {spec}' ...
[ "def parseRange(text, start):\n index = start\n char_range = []\n exclude = False\n if text[index] == '^':\n exclude = True\n index += 1\n if text[index] == ']':\n char_range.append(RegexRangeCharacter(']'))\n index += 1\n while index < len(text) and text[index] != ']':...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
build_accession_parser(rules_file) rules_file file object open for reading Builds a rule parse usable by match_accession() in this module from the accession rules described in rules_file. These rules can be downloaded by the scrape_accession_rules script.
def build_accession_parser(rules_file): rules_data = json.load(rules_file) rules_by_prefix_len = {} for prefix_list, database, molecule_type, type_description in rules_data: for prefix in prefix_list: prefix_length = len(prefix) if REFSEQ_PREFIX_RE.match(prefix) is not None:...
[ "def parseFile(file,rules = None):\n if not rules: rules = RuleCollection()\n buf = \"\"\n for line in open(file,'r'):\n if not line[0]=='#':\n buf += line\n try:\n for (ptree,lo,hi) in ruleNT.scanString(buf):\n rules.add(Parser._conver...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
match_accession(accession, rules_by_prefix_len) Returns the tuple (database, accession_type, type_description) for accession using the rules specified by rules_by_prefix_len. The database is one of 'GenBank', 'NCBI', 'GenBank and DDBJ' , 'DDBJ', and 'EMBL', accession_type is one of 'nucleotide', 'protein', 'WGS' and 'M...
def match_accession(accession, rules_by_prefix_len): letter_match = LETTER_RE.match(accession) if letter_match is None: raise ValueError('an accession number must start with at least one capital letter, this does not: ' + accession) letter_prefix = letter_match.group(0) letter_match_length = le...
[ "def build_accession_parser(rules_file):\n\n rules_data = json.load(rules_file)\n rules_by_prefix_len = {}\n for prefix_list, database, molecule_type, type_description in rules_data:\n for prefix in prefix_list:\n prefix_length = len(prefix)\n if REFSEQ_PREFIX_RE.match(prefix) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add hosts to a group
def my_add_group(self, hosts, groupname, groupvars=None): my_group = Group(name=groupname) # if group variables exists, add them to group if groupvars: for key, value in groupvars.iteritems(): my_group.set_variable(key, value) # add hosts to group ...
[ "def add_group(group):", "def add_hosts(self, hosts):\n for host in hosts:\n if host not in self.__hosts__:\n self.__hosts__.append(KnownHostsHost(host))", "def post(self, host_name, group_name): # noqa\n\n valid_parms = ['others']\n group_list = []\n group_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sort dataframe columns by name
def _sort_dataframe(self, dataframe): columns = list(dataframe.columns) columns.sort() dataframe = dataframe[columns] return dataframe
[ "def test_orderby_with_rename(dupcols):\n df = order_by(dupcols, columns=1, reversed=True)\n df.columns = ['A', 'B', 'C']\n assert list(df['B']) == [45, 44, 37, 34, 32, 29, 23]", "def sort_columns_by_list(self, df, cols):\n\n pass", "def sort(df, cols):\n if not df:\n return []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes and returns weighted kappa score from 2 lists or pandas series of scorings.
def compute_kappa_score(self, scorer1, scorer2, items, matrix_weights): #matrice nb items df_n_items = pd.DataFrame(data=0, index=items, columns=items) for score1, score2 in zip(scorer1, scorer2): df_n_items[score1][score2] = df_n_items[score1][score2] + 1 #nb items * to...
[ "def compute_kappa(self):\r\n kappa_res_linear = []\r\n kappa_res_inv_linear = []\r\n kappa_res_quadratic = []\r\n kappa_res_inv_quadratic = []\r\n kappa_idx = []\r\n for score1 in self.scorer1_scoring.columns:\r\n for score2 in self.scorer2_scoring.columns:\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares data for Cohen's kappa score computation, score results and corresponding indexes
def compute_kappa(self): kappa_res_linear = [] kappa_res_inv_linear = [] kappa_res_quadratic = [] kappa_res_inv_quadratic = [] kappa_idx = [] for score1 in self.scorer1_scoring.columns: for score2 in self.scorer2_scoring.columns: if sc...
[ "def Kappa(data):\n ranksX = [row[0] for row in data]\n ranksY = [row[1] for row in data]\n return float(cohen_kappa_score(ranksX, ranksY, weights='linear'))", "def scrap_initial_training_data():\n\tdata_interest_obj = np.zeros((50,3)) #for objective functions\n\tfor i in range(50):\n\t\tdata = pd.read_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses helper functions to get the leaves of a jet, recluster them following some algorithm, create the new tree for the algorithm, make a jet dictionary and save it.
def recluster(input_jet, alpha=None): def _rec(jet, parent, node_id, outers_list): """ Recursive function to get a list of the leaves """ if jet["tree"][node_id, 0] == -1: outers_list.append(jet["content"][node_id]) else: _rec(jet, node_id, jet["tree"][node_id, 0], outers_list) ...
[ "def recluster(particles, Rjet,jetdef_tree):\n # Recluster the jet constituents and access the clustering history\n #set up our jet definition and a jet selector\n if jetdef_tree=='antikt':\n tree_jet_def = fj.JetDefinition(fj.antikt_algorithm, Rjet)\n elif jetdef_tree=='kt':\n tree_jet_de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate all d_ij and get the minimum. Update the constituents list by deleting the constituents that are merged and adding the new pseudojet
def dijMinPair( const_list, var_dij_history, tree_dic, jet_content, idx, alpha=None, Nconst=None, Nparent=None, N_leaves_list=None, linkage_list=None, ): # Get all possible pairings pairs = np.asarray(list(itertools.combinations(np.arange(len(const_list)), 2))) # ...
[ "def _partial_min_solution(self, j):\n beta_without_j = np.delete(self.betas, j, axis=0)\n X_without_j = np.delete(self.X, j, axis=0)\n X_j = self.X[j] # these are the X values for the jth feature in the model\n # Make predictions and obtain residuals on the full set of Ys, without the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filtragem de ranking por score Recebe opção de ordenação (cresc. ou descres.) Retorna informações de score ordenados
def query_by_score(self, data): response = { 'code': 404, 'msg': 'ranking information not found', 'result': [], 'service': 'ranking', 'event': 'query' } if (data['order_by']) == 'high': ranks = list(self.db.find_by_score('h...
[ "async def ranking(self, ctx: commands.Context, role='all'):\n if role == 'all':\n clean_role = role\n else:\n clean_role, score = process.extractOne(role, roles_list)\n if score < 80:\n await ctx.send(self.bot.role_not_understood, delete_after=30)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using 2way BFS, finds the shortest path from start_position to end_position. Returns a list of moves. You can use the rubik.quarter_twists move set. Each move can be applied using rubik.perm_apply
def shortest_path(start, end): moves = rubik.quarter_twists # Parent nodes: (Parent_State, move) startParents = {} startParents[start] = None # Start state has no parent # Parent nodes: (Parent_State, move) endParents = {} endParents[end] = None # End state has no parent startFrontier = [] #...
[ "def shortest_paths(\n board: List[List[int]], start: Tuple[int, int], end: Tuple[int, int], roadblock: Any = None\n) -> List[List[Tuple[int, int]]]:\n if len(board) == 0 or len(board[0]) == 0:\n return [] # empty paths\n\n if not (is_on_board(board, start) and is_on_board(board, end)):\n ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets x over y as a percentage.
def percentage(x, y): try: return 100 * (float(x) / y) except ZeroDivisionError: return "undefined"
[ "def difference_percent(x, y):\n\n if y == 0 or x == 0:\n return 0\n else:\n x = float(x)\n return abs(x - y) / x", "def percent(x):\n return ((max(x)-center(x))/center(x))*100", "def pct_diff(x, y):\r\n pct = round((abs(y - x) / x) * 100, 2)\r\n print(str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find pairs of corresponding files. Gold files are of the form '0001GE.xml'. Corresponding sys files must start with '0001'.
def match_files(gold_folder, sys_folder): print "Compiling files..." # Get a list of files in the folders supplied. gold_files = compile_files(gold_folder) # nnnnG.xml sys_files = compile_files(sys_folder) # nnnnXXN.xml print "%d gold files found in %s" % (len(gold_files), base_name(gold_folder)...
[ "def get_ntuples_from_xml_files(top_directory):\n for (dirpath, dirnames, filenames) in os.walk(top_directory):\n print(\"Looking in\", dirpath)\n for filename in filenames:\n full_filename = os.path.join(dirpath, filename)\n rel_path = os.path.relpath(full_filename, top_direc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Score pairs of files and write result to CSV.
def output_scores(pairs, out_file, bonus=True): print "\nEvaluating system output..." # Retrieve the scores for each pair, maintaining file name. scores = [(file_name(p2), evaluate.process(p1, p2, bonus)) for (p1, p2) in pairs] # Flatten the scores into a single list, keeping file name. flat_score...
[ "def CreateCSV(outputFilename = \"results\"):\n csv = [\"\", \"\"]\n fileList = sorted(os.listdir(pathbase))\n best = [[0, 100], [0, 100]] #variable, rank\n \n prettyWidth = 18\n print(\"%s VARIABLE RANK\" % (\"HEADER\".ljust(prettyWidth)))\n for filename in fileList:\n if filename[-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Score pairs of files and write result to CSV. Outputs by type, the number and proportions of correct detections, recognitions and corrections.
def output_type_scores(pairs, out_file, mode="total"): print "\nEvaluating system output by type..." # Retrieve the scores for each pair, maintaining file name. # score[k] = (total, detections, recogntions, corrections) scores = [evaluate.process_type(p1, p2, mode) for (p1, p2) in pairs] count = d...
[ "def stats_pairs(): \n \n setproctitle(f\"RNANet statistics.py stats_pairs()\")\n\n def line_format(family_data):\n return family_data.apply(partial(format_percentage, sum(family_data)))\n\n if not path.isfile(\"data/pair_counts_{res_thr}.csv\"):\n results = []\n allpairs = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a log() function that assumes the given context parameters by default
def logWithContext(**context): destination = get_destination(context) def _log(message="", **kwargs): myContext = {} myContext.update(context) myContext.update(kwargs) log(message, **myContext) return _log
[ "def logtool(ctx):", "def log_context(context_name):\n def arg_wrapper(func):\n @wraps(func)\n def context_wrapper(*args, **kwargs):\n argspec = inspect.getargspec(func)\n\n # Check if logger was passed as a positional argument\n try:\n l = args[arg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Update' a null primary HDU This actually just checks hdu exists and creates it from hdu_in if it does not.
def update_null_primary(hdu_in, hdu=None): if hdu is None: hdu = fits.PrimaryHDU(header=hdu_in.header) else: hdu = hdu_in hdu.header.remove('FILENAME') return hdu
[ "def update_primary(hdu_in, hdu=None):\n if hdu is None:\n hdu = fits.PrimaryHDU(data=hdu_in.data, header=hdu_in.header)\n else:\n hdu.data += hdu_in.data\n return hdu", "def create_primary_hdu(self, config=None):\n if not config: config = self.config\n t0 = time.time()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Update' a primary HDU This checks hdu exists and creates it from hdu_in if it does not. If hdu does exist, this adds the data in hdu_in to hdu
def update_primary(hdu_in, hdu=None): if hdu is None: hdu = fits.PrimaryHDU(data=hdu_in.data, header=hdu_in.header) else: hdu.data += hdu_in.data return hdu
[ "def update_null_primary(hdu_in, hdu=None):\n if hdu is None:\n hdu = fits.PrimaryHDU(header=hdu_in.header)\n else:\n hdu = hdu_in\n hdu.header.remove('FILENAME')\n return hdu", "def create_primary_hdu(self, config=None):\n if not config: config = self.config\n t0 = tim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Update' an image HDU This checks hdu exists and creates it from hdu_in if it does not. If hdu does exist, this adds the data in hdu_in to hdu
def update_image(hdu_in, hdu=None): if hdu is None: hdu = fits.ImageHDU( data=hdu_in.data, header=hdu_in.header, name=hdu_in.name) else: hdu.data += hdu_in.data return hdu
[ "def update_primary(hdu_in, hdu=None):\n if hdu is None:\n hdu = fits.PrimaryHDU(data=hdu_in.data, header=hdu_in.header)\n else:\n hdu.data += hdu_in.data\n return hdu", "def update_null_primary(hdu_in, hdu=None):\n if hdu is None:\n hdu = fits.PrimaryHDU(header=hdu_in.header)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Update' the EBOUNDS HDU This checks hdu exists and creates it from hdu_in if it does not. If hdu does exist, this raises an exception if it doesn not match hdu_in
def update_ebounds(hdu_in, hdu=None): if hdu is None: hdu = fits.BinTableHDU( data=hdu_in.data, header=hdu_in.header, name=hdu_in.name) else: for col in ['CHANNEL', 'E_MIN', 'E_MAX']: if (hdu.data[col] != hdu_in.data[col]).any(): raise ValueError("Energy b...
[ "def update_energies(hdu_in, hdu=None):\n if hdu is None:\n hdu = fits.BinTableHDU(\n data=hdu_in.data, header=hdu_in.header, name=hdu_in.name)\n else:\n for col in ['Energy']:\n if (hdu.data[col] != hdu_in.data[col]).any():\n raise ValueError(\"Energy values...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Update' the ENERGIES HDU This checks hdu exists and creates it from hdu_in if it does not. If hdu does exist, this raises an exception if it doesn not match hdu_in
def update_energies(hdu_in, hdu=None): if hdu is None: hdu = fits.BinTableHDU( data=hdu_in.data, header=hdu_in.header, name=hdu_in.name) else: for col in ['Energy']: if (hdu.data[col] != hdu_in.data[col]).any(): raise ValueError("Energy values do not match...
[ "def update_primary(hdu_in, hdu=None):\n if hdu is None:\n hdu = fits.PrimaryHDU(data=hdu_in.data, header=hdu_in.header)\n else:\n hdu.data += hdu_in.data\n return hdu", "def update_ebounds(hdu_in, hdu=None):\n if hdu is None:\n hdu = fits.BinTableHDU(\n data=hdu_in.dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract some GTI related data
def extract_gti_data(hdu_in): data = hdu_in.data exposure = hdu_in.header['EXPOSURE'] tstop = hdu_in.header['TSTOP'] return (data, exposure, tstop)
[ "def extract(self, data):", "def extract_gnp_info(response) -> list:\n arr_included_gnp = []\n\n for i in range(1, 101):\n for row in response.css('#example2 tbody tr:nth-child({})'.format(i)):\n arr_included_entity = []\n\n for j in range(0, 4):\n for col in row.css('td:nth-child({})'.forma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Update' a HEALPix skymap This checks map_out exists and creates it from map_in if it does not. If map_out does exist, this adds the data in map_in to map_out
def update_hpx_skymap_allsky(map_in, map_out): if map_out is None: in_hpx = map_in.hpx out_hpx = HPX.create_hpx(in_hpx.nside, in_hpx.nest, in_hpx.coordsys, None, in_hpx.ebins, None, in_hpx.conv, None) data_out = map_in.expanded_counts_map() print(data...
[ "def _createOutputMap(self):\n # reprojection of downloaded data\n if self.proj_srs != self.proj_location: # TODO: do it better\n grass.message(_(\"Reprojecting data...\"))\n temp_warpmap = self._temp()\n \n if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge all the files in filelist, assuming that they WCS counts cubes
def merge_wcs_counts_cubes(filelist): out_prim = None out_ebounds = None datalist_gti = [] exposure_sum = 0. nfiles = len(filelist) ngti = np.zeros(nfiles, int) for i, filename in enumerate(filelist): fin = fits.open(filename) sys.stdout.write('.') sys.stdout.flush(...
[ "def merge_hpx_counts_cubes(filelist):\n out_prim = None\n out_skymap = None\n out_ebounds = None\n\n datalist_gti = []\n exposure_sum = 0.\n nfiles = len(filelist)\n ngti = np.zeros(nfiles, int)\n\n out_name = None\n\n for i, filename in enumerate(filelist):\n fin = fits.open(file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge all the files in filelist, assuming that they HEALPix counts cubes
def merge_hpx_counts_cubes(filelist): out_prim = None out_skymap = None out_ebounds = None datalist_gti = [] exposure_sum = 0. nfiles = len(filelist) ngti = np.zeros(nfiles, int) out_name = None for i, filename in enumerate(filelist): fin = fits.open(filename) sys....
[ "def merge_wcs_counts_cubes(filelist):\n out_prim = None\n out_ebounds = None\n\n datalist_gti = []\n exposure_sum = 0.\n nfiles = len(filelist)\n ngti = np.zeros(nfiles, int)\n\n for i, filename in enumerate(filelist):\n fin = fits.open(filename)\n sys.stdout.write('.')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deregister an event handler from this event. Throws EventError
def unhandle(self, handler): try: self.handlers.remove(handler) except: raise EventError("Can't unhandle handler %s: \ handler %s does not hook into this event!" % (handler, handler))
[ "def deregister(self, event, fn):\n if event in self._handler_dict and fn in self._handler_dict[event]:\n self._handler_dict[event].remove(fn)", "def remove_handler(self, event: str, handler: Callable) -> None:\n self.handlers[event].discard(handler)", "def unregister_aggregate_handler(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the correct padding is applied to unpadded b64 strings
def test_pad_b64(self): test1 = {"value": b"any carnal pleasure.", "unpadded": "YW55IGNhcm5hbCBwbGVhc3VyZS4", "padded": "YW55IGNhcm5hbCBwbGVhc3VyZS4="} test2 = {"value": b"any carnal pleasure", "unpadded": "YW55IGNhcm5hbCBwbGVhc3VyZQ", ...
[ "def _get_2xbase64pad(data: str) -> str:\n pattern = r\"[^a-zA-Z0-9]\"\n regex = re.compile(pattern)\n while True:\n # First run\n ebytes = base64.b64encode(data.encode(\"utf-8\"))\n estring = str(ebytes, \"utf-8\")\n\n # Second run\n ebytes = base64.b64encode(estring.enc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an overview of the system state
def get_system_state(self, path, params): system_summary = self._get_system_summary(path) overview = { 'peer_controller_url': self._get_peer_controller_url(), 'summary_sources': system_summary, 'site_name': self._config.get('site', {}).get('name', 'unknown'), ...
[ "def get_state(self):\n return self.run_cmd('get-state')", "def show_states():\n return render_template('7-states_list.html',\n storage=storage.all(\"State\").values())", "def getState(self):\r\n self._update('getState')\r\n\r\n state = self.supervisord.options....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clean up relevant internal data in all collectors
def cleanup(self): self._faucet_collector.cleanup()
[ "def cleanUp(self):\r\n pass", "def cleanup(self):\n self.msgmap.clear()\n self.droppedmsgs.clear()\n self.chan.stop_receiving_messages()\n\n # TODO: enable\n #self.cmdMap.clear()\n #self.cmdCliSubmitQueue.clear()\n #self.cmdSvrComputeQueue.clear()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the dataplane state overview
def get_dataplane_state(self, path, params): reply = self._faucet_collector.get_dataplane_state() self._augment_state_reply(reply, path) return reply
[ "def get_dataplane_summary(self):\n dplane_state = self._get_dataplane_state()\n return {\n 'state': dplane_state.get('dataplane_state'),\n 'detail': dplane_state.get('dataplane_state_detail'),\n 'change_count': dplane_state.get('dataplane_state_change_count'),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get certain processes state on the controller machine
def get_process_state(self, path, params): reply = self._local_collector.get_process_state() self._augment_state_reply(reply, path) return reply
[ "def list_active_processes():\n return psutil.process_iter()", "def process_state(pid):\n status = LocalPath('/proc').join(str(pid), 'status').read()\n m = re.search('^State:\\s+[A-Z] \\(([a-z]+)\\)$', status, re.MULTILINE)\n return m.group(1)", "def stateipmc(ipmc_name):\n\tcmd = cmd_mmsh.statewd_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get faucet config from facuet config file
def get_faucet_config(self, path, params): try: reply = self._get_faucet_config() self._augment_state_reply(reply, path) return reply except Exception as e: return f"Cannot read faucet config: {e}"
[ "def load_config(self):\r\n\r\n if len(self.args) < 1:\r\n print(\"need config file, use --help for help.\")\r\n sys.exit(1)\r\n conf_file = self.args[0]\r\n return skytools.Config(self.service_name, conf_file,\r\n user_defs = self.cf_defaults...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a sorted order book with offers
def __init__(self, pair, offers=None): self.book = {} self.book[Trade.WAY_BUY] = [] self.book[Trade.WAY_SELL] = [] self.pair = pair self.timestamp = 0 if offers: for offer in offers: self.add(offer) self.sum_up()
[ "def add(self, offer):\n other_offer = self.get(offer.get_price(), offer.get_way())\n if other_offer:\n other_offer.add_quote_amount(offer.get_quote_amount())\n other_offer.add_base_amount(offer.get_base_amount())\n return\n self.book[offer.get_way()].append(off...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get offer at price in trading way. Offers with same price and way are combined to one.
def get(self, price, way): for offer in self.book[way]: if offer.get_price() == price: return offer return None
[ "def getBuyPrice(self):\n legs = self.getStrikes()\n return legs[0].getAsk() + legs[1].getAsk()", "def get_best_offer(self,way):\n if way==\"BUY\":\n return self.book[Trade.WAY_BUY][0].get_price()\n elif way==\"SELL\":\n return self.book[Trade.WAY_SELL][len(self.book[Trad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add offer to offer book. If other offer with same price and way exists, add the amounts to the existing.
def add(self, offer): other_offer = self.get(offer.get_price(), offer.get_way()) if other_offer: other_offer.add_quote_amount(offer.get_quote_amount()) other_offer.add_base_amount(offer.get_base_amount()) return self.book[offer.get_way()].append(offer) ...
[ "def register_offer(self, offer):\n\n offers = self._adaptation_offers.setdefault(\n offer.from_protocol_name, []\n )\n offers.append(offer)\n\n return", "def add_offer(self):\r\n self.add_company_row()\r\n job_title = self.form.job_title.data\r\n pay_of...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the offer book
def reset(self): self.book = {} self.book[Trade.WAY_BUY] = [] self.book[Trade.WAY_SELL] = []
[ "def reset_auctioneer(self):\n self.bidders = []\n self._highest_bid = 0\n\n pass", "def reset_auctioneer(self):\n self.bidders.clear()\n self._highest_bid = 0\n self._highest_bidder = None", "def reset(self):\r\n self.amount = 0", "def reset(self):\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return best offer BUY or SELL
def get_best_offer(self,way): if way=="BUY": return self.book[Trade.WAY_BUY][0].get_price() elif way=="SELL": return self.book[Trade.WAY_SELL][len(self.book[Trade.WAY_SELL])-1].get_price()
[ "def best_buy(self):\n return Library.functions.best_buy(self._book)", "def cmd_bestprice(self, args, msg):\n item = ' '.join(args)\n res = self._item_picker(item)\n if isinstance(res, basestring):\n return res\n type_id, type_name = res\n\n min_sell = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sums each offer up
def sum_up(self): sum_base = 0 sum_quote = 0 for i in range(len(self.book[Trade.WAY_BUY])): offer = self.book[Trade.WAY_BUY][i] sum_base = sum_base + offer.get_base_amount() sum_quote = sum_quote + offer.get_quote_amount() offer.set_sum_base(sum_ba...
[ "def mysum(items) :", "def sum(self):\n return sum(self.items())", "def sum_price(products):\n return round(sum(product['unit_price'] for product in products), 2)", "def compute_bill_11(food):\n assert isinstance(food, (list, tuple, set)), \"{} error enter type\".format(food)\n total = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulates a taker trade with amount of token
def taker(self, amount, token): if self.pair.get_base_token() == token: return self.buy(amount) if self.pair.get_quote_token() == token: return self.sell(amount)
[ "def test_buy_tokens():\n start = 1488294000\n end = 1490112000\n project_dir = DATACOIN_PATH\n project = Project(project_dir, create_config_file=True)\n with project.get_chain('tester') as chain:\n beneficiary = chain.web3.eth.accounts[3]\n multisig = chain.web3.eth.accounts[4]\n customer = chain.web...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulates reversed taker buy trade
def reverse_buy(self, amount): trade_amount = 0 precision = pow(10, self.pair.get_base_token().get_decimals() - self.pair.get_quote_token().get_decimals()) for i in range(len(self.book[Trade.WAY_SELL])): offer = self.book[Trade.WAY_SELL][i] amount_quote = offer.get_quote_...
[ "def Trading(Seller,Buyer):\n if Seller.has_sold == False:\n if Buyer.like_buy >= Seller.like_sell:\n Seller.has_sold = True\n Buyer.has_bought = True\n Seller.sold_objects += 1\n Buyer.bought_objects += 1\n print('A trade has been made')\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simulates reversed taker sell trade
def reverse_sell(self, amount): trade_amount = 0 precision = pow(10, self.pair.get_quote_token().get_decimals() - self.pair.get_base_token().get_decimals()) for i in range(len(self.book[Trade.WAY_BUY])): offer = self.book[Trade.WAY_BUY][i] amount_quote = offer.get_quote_a...
[ "async def on_trade_decline(self, trade: \"steam.TradeOffer\") -> None:", "def Trading(Seller,Buyer):\n if Seller.has_sold == False:\n if Buyer.like_buy >= Seller.like_sell:\n Seller.has_sold = True\n Buyer.has_bought = True\n Seller.sold_objects += 1\n Buye...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the trade way of taker buy offering token
def get_taker_trade_way(self, token): if self.pair.get_base_token() == token: return Trade.WAY_BUY if self.pair.get_quote_token() == token: return Trade.WAY_SELL
[ "def taker(self, amount, token):\n if self.pair.get_base_token() == token:\n return self.buy(amount)\n\n if self.pair.get_quote_token() == token:\n return self.sell(amount)", "def get_maker_trade_way(self, token):\n if self.pair.get_base_token() == token:\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the trade way of maker buy offering token
def get_maker_trade_way(self, token): if self.pair.get_base_token() == token: return Trade.WAY_SELL if self.pair.get_quote_token() == token: return Trade.WAY_BUY
[ "def get_taker_trade_way(self, token):\n if self.pair.get_base_token() == token:\n return Trade.WAY_BUY\n\n if self.pair.get_quote_token() == token:\n return Trade.WAY_SELL", "def taker(self, amount, token):\n if self.pair.get_base_token() == token:\n return s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the sum of all offers til index in trade way of token.
def get_sum(self, index, way, token): if len(self.book[way]) <= index: return None if token == self.pair.get_quote_token(): return self.book[way][index].get_sum_quote() else: return self.book[way][index].get_sum_base()
[ "def get_sum_after_fees(self, index, way, token):\n sum = self.get_sum(index, way, token)\n if not sum:\n return None\n if self.pair.get_exchange().get_fee_token():\n return sum\n else:\n return int(sum * (1-self.pair.get_exchange().get_fees()))", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the sum after fees of all offers til index in trade way of token.
def get_sum_after_fees(self, index, way, token): sum = self.get_sum(index, way, token) if not sum: return None if self.pair.get_exchange().get_fee_token(): return sum else: return int(sum * (1-self.pair.get_exchange().get_fees()))
[ "def calculate_fees(self) :\n total = 0\n for course_code, fee in self._enrolments :\n total += fee\n return total", "def fee(self, prices, fee):\n return self.volume(prices) * fee.value / Config.FEE_TOKEN_PRICE", "def compute_fees(self, fees_rate):\n return 0 if se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return "{city}, {state code} {ZIP code}".
def city_state_zip(**kwargs): result = "{city_name}, {state_code}".format(**kwargs) if kwargs["five_digit_zip_code"]: # RLID for some reason has two spaces between state & ZIP. result += " {five_digit_zip_code}".format(**kwargs) return result
[ "def city_info (city, country, population=2880000) :\n return f\"{city}, {country} - population {population:,}\"", "def ad_rep_city_state(obj):\n return '%s, %s' % (obj.ad_rep.geolocation_object.us_city.name,\n obj.ad_rep.geolocation_object.us_state.abbreviation)", "def get_city_info(country, city,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send message for any recentlyadded address in the Lincoln PSAP area.
def send_new_lincom_address_message(): keys = ["city_name", "concat_address", "geofeat_id", "initial_create_date"] addresses = sorted( addr for addr in arcetl.attributes.as_iters( dataset.SITE_ADDRESS.path("pub"), field_names=keys, dataset_where_sql="ps...
[ "def subscribeAddress(address):", "def _push_message_ip(self, entries: typing.List[str]):\n self._push_message_json(entries, \"APEL Public IP message\", self.version_ip)", "def on_address_status(self, data):\n self.logger.info('got Address Status message: {}'.format(data))\n self.address_qu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send message of issues that affect address publication.
def send_publication_issues_message(): keys = ["description", "city_name", "concat_address", "geofeat_id"] issues = sorted( arcetl.attributes.as_iters( dataset.ADDRESS_ISSUES.path(), field_names=keys, dataset_where_sql="update_publication = 0", ) )...
[ "def email_issues(config, recipient_list, subject, issues):\n logger.info('Send email of issues')\n mailBody = formatHtmlMailBody(issues)\n \n mime_msg = MIMEMultipart('alternate')\n mime_msg['Subject'] = subject\n mime_msg['From'] = config.email_sender\n \n if isinstance(recipient_list,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run ETL for site addresses.
def site_address_etl(): with arcetl.ArcETL("Site Addresses") as etl: etl.extract(dataset.SITE_ADDRESS.path("maint")) # Clean maintenance values. transform.clear_nonpositive(etl, field_names=["house_nbr"]) transform.clean_whitespace( etl, field_names=[ ...
[ "def etl():\n logging.debug(\"Etl process has begun, if error occurs go to GSheetsEtl.\")\n print(\"Start etl process....\")\n etl_instance = GSheetsEtl(config_dict)\n etl_instance.process()", "def AddAddresses(self, per_site=2):\n\n for site_id in self.site_ids:\n for i in range(per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raises error if sheet name is not present in file.
def check_sheet(path, sheet): xl = pd.ExcelFile(path) if sheet not in xl.sheet_names: raise ValueError("Invalid sheet name \'" + sheet +"\'")
[ "def test_check_sheetname():\n with pytest.raises(KeyError):\n io.xlsx_table(filename, 1, None)", "def load_specific_sheet(self, sheet_name):\r\n if sheet_name not in self.all_sheet_names:\r\n logging.error(\"There is no such sheet in xlsx file: %s\"\r\n % shee...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes index column to intergers 0, 1, 2... if first index is NaN
def filter_index_column(df, verbose = False): index_starts_with_nan = pd.isnull(df.index)[0] if index_starts_with_nan: full_row_count = df.shape[0] df.index = list(range(full_row_count)) if verbose is True: print("") print("Index changed. New dataframe index: ", d...
[ "def create_index(gdf):\n\n if gdf.index.isnull().sum() > 0 or gdf.index.is_unique == False:\n gdf.index = range(1, len(gdf) + 1)\n return gdf", "def _set_index_integer(self, index, value):\n index = (_correct_index(index, self.shape[0]),)\n \n if value == self._default:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints head and tail for sort long dataframe, all dataframe for short one.
def print_dataframe(df): print ("") if df.shape[0] > 20: print (df.head()) print (df.tail()) else: print (df)
[ "def print_full(df):\n pandas.set_option('display.max_rows', len(df))\n print df\n pandas.reset_option('display.max_rows')", "def display(df, name=\"\", desc=\"\", tail=1000):\n if type(df) != pd.core.frame.DataFrame:\n _err(\"Given df is not DataFrame (%s)\" % type(df))\n return\n name_htm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify file path using postfix to basename and new file extension.
def make_new_path(path, postfix = "", ext = ""): dir = os.path.split(path)[0] old_basename, old_ext = os.path.splitext(path) new_basename = old_basename + "_" + postfix new_path = os.path.join(dir, new_basename + "." + ext) return new_path
[ "def replace_ext(file_path, new_ext):\n if not new_ext.startswith(os.extsep):\n new_ext = os.extsep + new_ext\n index = file_path.rfind(os.extsep)\n return file_path[:index] + new_ext", "def change_filepath_ext(filepath: str, new_ext: str) -> str:\n return str(pathlib.Path(filepath).with_suffix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Switch focus to a card under given index.
def focus_on(self, card_idx: int) -> None:
[ "def selectCard(self, i):\n self.cardindex = i\n self.dirty = 1", "def set_current_index(self, index):\r\n self.contents_widget.setCurrentRow(index)", "def advanceCard(self):\n self.cardindex += 1\n self.dirty = 1", "def activate(self, index):\n self.tk.call(self._w, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a TensorRT Model. config_path (string) The path to the model config file. checkpoint_path (string) The path to the model checkpoint file(s). graph_path (string) The path to the model graph. returns (Model) The TRT model built or loaded from the input files.
def createModel(config_path, checkpoint_path, graph_path): global build_graph, prev_classes trt_graph = None input_names = None if build_graph: frozen_graph, input_names, output_names = build_detection_graph( config=config_path, checkpoint=checkpoint_path )...
[ "def build_graph_from_config(self, model_config, checkpoint_path):\n tf.logging.info(\"Building model.\")\n self.build_model(model_config)\n saver = tf.train.Saver()\n\n return self._create_restore_fn(checkpoint_path, saver)", "def build_graph_from_config(self, model_config, checkpoint...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds a nested value in `root` by splitting `path` by a `.`.
def find(root, path, default_value=None): if root is None or path is None: return default_value assert isinstance(path, str) tokens = path.split('.') for token in tokens: root = root.get(token) if root is None: return default_value ...
[ "def search(root, path:str, find_one=False):\n\n if not path or not isinstance(path, str) or not isinstance(root, (list, dict)):\n return\n\n if path.startswith('$'):\n path = path.replace('$', '', 1)\n\n # split by `.` and drop `.`, split by `[ ]` and keep `[ ]`\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This class is always instantiated with a DataHandler class instance. This instance should have the pipeline run, with extra columns included that identify the candidate sensors.
def __init__(self, data_handler_obj): self.data_handler = data_handler_obj self.sensor_keys = np.array(list(self.data_handler.extra_matrices.keys())) if len(self.sensor_keys) == 0: print("Please add sensor columns to DataHandler pipeline.") return self.coverage_sc...
[ "def __init__(self, pipe, df_log_for_pipe, channel_mapper, data_dir=None, n_jobs=1, verbose=True, harmonic=3):\n self.channel_mapper = channel_mapper\n self.n_jobs = n_jobs\n self.harmonics = [1, harmonic]\n self.pipe = pipe\n self.data_dir = data_dir\n self.verbose = verbo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the favourite of this UpdateInboxOptions.
def favourite(self, favourite): self._favourite = favourite
[ "def favorite(self, favorite: bool):\n if favorite is None:\n raise ValueError(\"Invalid value for `favorite`, must not be `None`\")\n\n self._favorite = favorite", "def set_favorite(self, favorite):\n\n\t\tif favorite is not None and not isinstance(favorite, int):\n\t\t\traise SDKExcepti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The constructor sets bare essentials for a Task object. See the initialize() and start() methods.
def __init__(self): self.ev_done = threading.Event() self.tag = None self.logger = None self.threadPool = None # Lock for task state critical sections self.tlock = threading.RLock() # Parent task can set this (or add to it) explicitly to determine # which ...
[ "def __init__(self):\n Task.__init__(self)", "def __init__(self, task):\n\t\tthreading.Thread.__init__(self)\n\t\tself.kit = MotorKit()\n\t\tself.task = task\n\t\tself.done = False\n\n\t\t#this defines the two motors in a dictionary for ease of access\n\t\t#and to keep things DRY\n\t\tself.motor = {\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method initializes a task for (re)use. taskParent is the object instance of the parent task, or a 'task environment' (something that runs tasks). If subclass overrides this method, it should call the superclass method at some point. Copy shared data from taskParent, overriding items from _override_ if they are pre...
def initialize(self, taskParent, override=None): # For now, punt if we have no apparent parent if taskParent and hasattr(taskParent, 'shares'): # Copy some variables from our parent task, unless they are being # overridden explicitly. Using this general "contagion" mechanism, ...
[ "def __init__(self):\n self.ev_done = threading.Event()\n self.tag = None\n self.logger = None\n self.threadPool = None\n # Lock for task state critical sections\n self.tlock = threading.RLock()\n # Parent task can set this (or add to it) explicitly to determine\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method resumes an executing task (if possible). Subclass should override this method, should not call super.resume(). Return True if task could be resumed, False if not?
def resume(self): raise TaskError("Task %s: subclass should override resume() method!" % ( self))
[ "def _is_resume(self, message):\n\t\treturn message.lower() in (\"r\", \"resume\")", "def should_resume(self, data_inputs) -> bool:\n for index, (step_name, step) in enumerate(reversed(self.steps_as_tuple)):\n if isinstance(step, ResumableStepMixin) and step.should_resume(data_inputs):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a task has a way of stepping through an operation. It can implement this method. Subclass should not call super.step().
def step(self): raise TaskError("Task %s: subclass should override step() method!" % self)
[ "def resume(self):\n raise TaskError(\"Task %s: subclass should override resume() method!\" % (\n self))", "def timestep(self):\n return NotImplementedError", "def _step(self, whence):\n pass", "def _step_callback(self):\n pass", "def run(self, step: str = None) -> Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
make_tasker takes a callable (function, method, etc.) and returns a new factory function for generating tasks. Each factory function is designed to consume its arguments and return a task that, when executed, will call the function upon the arguments.
def make_tasker(func): def anonFunc(*args, **kwdargs): class anonTask(Task): def execute(self): self.logger.debug("Executing fn %s" % func) try: val = func(*args, **kwdargs) self.logger.debug("Done executing fn %s" % func) ...
[ "def task(self, *args, **options):\n\n def inner_create_task_cls(**options):\n\n def _create_task_cls(fun):\n options[\"app\"] = self\n options.setdefault(\"accept_magic_kwargs\", False)\n base = options.pop(\"base\", None) or self.Task\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interrupt/cancel execution, but will allow current child task to complete.
def stop(self): #self.ev_intr.set() try: self.task.stop() except TaskError as e: self.logger.error("Error cancelling child task: %s" % (str(e)))
[ "def cancelCurrentTask(self) -> None:\n ...", "def hard_cancel(self, exec_info: ExecutionInfo) -> None:\n for task in exec_info.tasks.values():\n if not task.done():\n task.cancel()", "def interrupt(self):\n ident = self.ident()\n print('{} for \"{}\" saw in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run all child tasks concurrently in separate threads. Return last result after all child tasks have completed execution.
def execute(self): with self._lock_c: self.count = 0 self.numtasks = 0 self.taskset = [] self.results = {} self.totaltime = time.time() # Start all tasks for task in self.taskseq: self.taskset.append(task) ...
[ "def run(self):\n tasks = list(self)\n [ task.make_call() for task in self ]\n [ task.wait() for task in self ]\n self[:] = tasks", "def execute(self):\n return [task.run() for task in self._tasks]", "def run_in_parallel(self):\n\t\tfor p in self.parallel_threads:\n\t\t\tp.sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call stop() on all child tasks, and ignore TaskError exceptions. Behavior depends on what the child tasks' stop() method does.
def stop(self): with self._lock_c: for task in self.taskset: try: task.stop() except TaskError as e: # Task does not have a way to stop it. # TODO: notify who? pass # stop oursel...
[ "def _stop_all(self):\n for task in self.discover_tasks:\n if not task.done():\n task.cancel()\n elif not task.cancelled():\n task.exception()", "def stop(self):\n #self.ev_intr.set()\n\n try:\n self.task.stop()\n\n except ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start all of the threads in the thread pool. If _wait_ is True then don't return until all threads are up and running. Any extra keyword arguments are passed to the worker thread constructor.
def startall(self, wait=False, **kwdargs): self.logger.debug("startall called") with self.regcond: while self.status != 'down': if self.status in ('start', 'up') or self.ev_quit.is_set(): # For now, abandon additional request to start s...
[ "def start_workers(self):\n\n for thread in self.threads:\n thread.start()", "def start_threads(self):\r\n assert len(self.all_threads) > 0\r\n for thread in self.all_threads:\r\n thread.start()", "def create_and_start_threads(self):\r\n self.create_threads()\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop all threads in the worker pool. If _wait_ is True then don't return until all threads are down.
def stopall(self, wait=False): self.logger.debug("stopall called") with self.regcond: while self.status != 'up': if self.status in ('stop', 'down') or self.ev_quit.is_set(): # For now, silently abandon additional request to stop self.lo...
[ "def terminate_all(wait=False):\n\r\n\tfor thread in pool:\n\t\t# if thread does not need us to wait\n\t\tif not thread.killwait:\n\t\t\tcontinue\r\n\t\tlogging.debug('Terminating thread ' + str(thread))\r\n\t\tthread.run_flag = 0\r\n\t\t#sleep(1)\r\n\t\tif wait:\r\n\t\t\ttry: thread.join()\r\n\t\t\texcept: pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called by WorkerThread objects to register themselves. Acquire the condition variable for the WorkerThread objects. Increment the runningthread count. If we are the last thread to start, set status to 'up'. This allows startall() to complete if it was called with wait=True.
def register_up(self): with self.regcond: self.runningcount += 1 tid = threading.get_ident() self.tids.append(tid) self.logger.debug("register_up: (%d) count is %d" % (tid, self.runningcount)) if self.runningcount == self....
[ "def startall(self, wait=False, **kwdargs):\n self.logger.debug(\"startall called\")\n with self.regcond:\n while self.status != 'down':\n if self.status in ('start', 'up') or self.ev_quit.is_set():\n # For now, abandon additional request to start\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Da la posicion en cartesianas
def getpos(self): return self.pos.cartesianas()
[ "def positions(self):\n return np.vstack((self.in_circles(), self.out_circles()))", "def get_positions(self):\n return [[a.x, a.y] for a in self.population]", "def position(self):\n return self.atoms.reshape((1,-1))", "def position(self,x):\n cart_x = [x[0][0], x[0][0] + self.dynamics....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns all assigned tasks that are stale
def get_stale_assigned_tasks(): # select t.id from tasks t, actions a where # a.task_id = t.id and t.currentaction = 'assigned' # group by t.id having now() - max(a.timestamp) < interval '1 day'; return db.session.query(Task).filter_by( currentaction='assigned').join(Task.actions).group_by( ...
[ "def list_pending_tasks():\n inspector = current_app.control.inspect()\n\n return inspector.reserved()", "def refreshWaitingList(self):\n RCI.instance().waitingTasks()", "def pullProcessingTasksOlderThan(self, oldTime):\n\n with self.lock:\n expireTasks = [e for (e,t) in self.proc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the character attributes (colors) of the console screen buffer.
def get_text_attr(): csbi = CONSOLE_SCREEN_BUFFER_INFO() GetConsoleScreenBufferInfo(stdout_handle, byref(csbi)) return csbi.wAttributes
[ "def get_colors(cls, font) -> tuple:\n\n return font[BFC]", "def getColors(self):\n _val = self._color\n _r = (_val & 0xff0000) >> 16\n _g = (_val & 0xff00) >> 8\n _b = (_val & 0xff)\n return _r, _g, _b", "def colors(self):\r\n\t\treturn self._colors", "def colorspace...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the character attributes (colors) of the console screen buffer. Color is a combination of foreground and background color, foreground and background intensity.
def set_text_attr(color): SetConsoleTextAttribute(stdout_handle, color)
[ "def init():\n global _default_foreground, _default_background, _default_style\n try:\n attrs = GetConsoleScreenBufferInfo().wAttributes\n except (ArgumentError, WindowsError):\n _default_foreground = GREY\n _default_background = BLACK\n _default_style = NORMAL\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add add two values as unsigned 8bit values.
def _uint8_add(self, a, b): return ((a & 0xFF) + (b & 0xFF)) & 0xFF
[ "def add_binary(a, b):\n return bin(a + b)[2:]", "def add64(a,b):\n return(np.add(a, b, dtype=np.uint64))", "def add(b1, b2):\n n1=bin_to_dec(b1)\n n2 = bin_to_dec(b2)\n b_sum = dec_to_bin(n1+n2)\n return b_sum", "def addition(self, first_value, second_value):\n return bytes(first_val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Busy wait for the specified number of milliseconds.
def _busy_wait_ms(self, ms): start = time.time() delta = ms/1000.0 while (time.time() - start) <= delta: pass
[ "def busyWait(self):\n time.sleep(0.0)", "def wait(time_to_wait: float=0.5):\n sleep(time_to_wait)", "def sleep_ms(milliseconds: int) -> None:\n ...", "def delay(ms):\n ms = int(ms*1000)\n libc.usleep(ms)", "def sleep(self, milliseconds):\n time.sleep(milliseconds / 1000.)", "def sle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a response frame from the PN532 of at most length bytes in size. Returns the data inside the frame if found, otherwise raises an exception if there is an error parsing the frame. Note that less than length bytes might be returned!
def _read_frame(self, length): # Read frame with expected length of data. response = self._read_data(length+8) # Check frame starts with 0x01 and then has 0x00FF (preceeded by optional # zeros). if not (PN532_ACK_FRAME == response.tostring()): if response[0] != 0x00: ...
[ "async def _read_frame(self):\n # Read the Frame start and header\n response = await self.sreader.read(len(_FRAME_START)+2)\n if self.debug:\n print('_read_frame: frame_start + header:', [hex(i) for i in response])\n\n if len(response) < (len(_FRAME_START) + 2) or response[:-2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send specified command to the PN532 and expect up to response_length bytes back in a response. Note that less than the expected bytes might be returned! Params can optionally specify an array of bytes to send as parameters to the function call. Will wait up to timeout_secs seconds for a response and return a bytearray ...
def call_function(self, command, response_length=0, params=[], timeout_sec=1): # Build frame data with command and parameters. data = bytearray(2+len(params)) data[0] = PN532_HOSTTOPN532 data[1] = command & 0xFF data[2:] = params # Send frame and wait for response. ...
[ "def _sendCmdPoll(self, cmd_request, response_size=6, timeout=100):\n # check if this is a comand valid for polling\n if cmd_request[0] < 0x20 or cmd_request[0] > 0x27:\n raise SHT3XError(SHT3XError.WRONG_CMD)\n # try sending the command\n try:\n self.i2c.writeto(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call PN532 GetFirmwareVersion function and return a tuple with the IC, Ver, Rev, and Support values.
def get_firmware_version(self): response = self.call_function(PN532_COMMAND_GETFIRMWAREVERSION, 4) if response is None: raise RuntimeError('Failed to detect the PN532! Make sure there is sufficient power (use a 1 amp or greater power supply), the PN532 is wired correctly to the device, and ...
[ "async def get_firmware_version(self):\n if self.debug:\n print(\"Sending GET_FIRMWARE_VERSION\")\n\n response = await self.call_function(_COMMAND_GETFIRMWAREVERSION)\n if response is None:\n raise RuntimeError('Failed to detect the PN532')\n return tuple(response)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wait for a MiFare card to be available and return its UID when found. Will wait up to timeout_sec seconds and return None if no card is found, otherwise a bytearray with the UID of the found card is returned.
def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1): # Send passive read command for 1 card. Expect at most a 7 byte UUID. response = self.call_function(PN532_COMMAND_INLISTPASSIVETARGET, params=[0x01, card_baud], ...
[ "def WaitForCard(self, interface, timeout, list=[]):\r\n\t\tA = self.a\r\n\t\tINS = 0x5C\r\n\t\t\r\n\t\tif interface != 0xFF:\r\n\t\t\tif interface in range(0,8):\r\n\t\t\t\tP1 = interface\r\n\t\t\telse:\r\n\t\t\t\traise MaximException(\"Invalid interface.\")\r\n\t\telse:\r\n\t\t\tP1 = interface\r\n\t\t\r\n\t\tif t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Authenticate specified block number for a MiFare classic card. Uid should be a byte array with the UID of the card, block number should be the block to authenticate, key number should be the key type (like MIFARE_CMD_AUTH_A or MIFARE_CMD_AUTH_B), and key should be a byte array with the key data. Returns True if the blo...
def mifare_classic_authenticate_block(self, uid, block_number, key_number, key): # Build parameters for InDataExchange command to authenticate MiFare card. uidlen = len(uid) keylen = len(key) params = bytearray(3+uidlen+keylen) params[0] = 0x01 # Max card numbers params[...
[ "def _authenticate(self, block, uid, key = \"\\xff\\xff\\xff\\xff\\xff\\xff\", use_b_key = False):\n if nfc.nfc_device_set_property_bool(self.__device, nfc.NP_EASY_FRAMING, True) < 0:\n raise Exception(\"Error setting Easy Framing property\")\n abttx = (ctypes.c_uint8 * 12)()\n abttx...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a block of data from the card. Block number should be the block to read. If the block is successfully read a bytearray of length 16 with data starting at the specified block will be returned. If the block is not read then None will be returned.
def mifare_classic_read_block(self, block_number): # Send InDataExchange request to read block of MiFare data. response = self.call_function(PN532_COMMAND_INDATAEXCHANGE, params=[0x01, MIFARE_CMD_READ, block_number & 0xFF], resp...
[ "def read_block(self, block):\n return self.values[3 + 4*block: 3 + 4*block + 4]", "def read(self, block_address):\n buf = [self.act_read, block_address]\n crc = self.calculate_crc(buf)\n buf.append(crc[0])\n buf.append(crc[1])\n (error, back_data, back_length) = self.car...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a block of data to the card. Block number should be the block to write and data should be a byte array of length 16 with the data to write. If the data is successfully written then True is returned, otherwise False is returned.
def mifare_classic_write_block(self, block_number, data): assert data is not None and len(data) == 16, 'Data must be an array of 16 bytes!' # Build parameters for InDataExchange command to do MiFare classic write. params = bytearray(19) params[0] = 0x01 # Max card numbers params...
[ "def write_block_data(self, addr, reg, data):\n raise NotImplementedError()", "def write(self, data):\n self.spi_port.xfer2(list(data))\n\n return True", "def _write(self, data):\n\n ret = False\n extended_address = SettingsBase.get_setting(self, \"extended_address\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates and returns accidents counts from data for specific year
def get_counts_for_year(data, year): accidents_counts = list(map(list, zip(*list((filter(lambda x: x[0] == year, data))))))[2] return accidents_counts
[ "def axis_count_by_year(dataFrame, axis_of_interest):\n index_entries = DPI_data[axis_of_interest].unique().tolist()\n\n data_years = sorted(dataFrame[\"Year of Incident\"].unique().tolist())\n removal_list = [2109, 2048, 2013, 2009, 2005] #by analaysis of data\n for x in removal_list:\n data_yea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes and returns dict of years, regions and counts of accidents in data
def parse_counts(data): results = {} region_year = np.stack([data[0], data[4].astype('datetime64[Y]').astype(int) + 1970], axis=0) region_years, counts = np.unique(region_year, return_counts=True, axis=1) region_years_counts = list(zip(region_years[1], region_years[0], counts)) results['y...
[ "def get_counts_for_year(data, year):\r\n \r\n accidents_counts = list(map(list, zip(*list((filter(lambda x: x[0] == year, data))))))[2]\r\n return accidents_counts", "def region_counts(region_list) :\n name_dict = {}\n name_list = [ r.name for r in region_list ]\n for region in region_list :\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots a basic statistics from data_source about how much accidents specific regions in some period of time.
def plot_stat(data_source, fig_location = None, show_figure = False): accidents_counts = parse_counts(data_source[1]) years = list(accidents_counts['years']) fig, axes = plt.subplots(ncols=1, nrows=len(years), sharey=True, constrained_layout=True, figsize=(7, 13)) fig.suptitle("Počet nehôd...
[ "def plot_profile_statistics():", "def plot_observation_stats(self):\n import matplotlib.dates as mdates\n\n df = self.get_observation_stats()[[\"min_date\", \"max_date\"]]\n df = df.sort_values(\"min_date\", ascending=False)\n\n nsats = len(df)\n ysize = max(2.0, 0.45 * nsats)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the Scotvote data and returns a Dataset instance. Returns
def load(): filepath = dirname(abspath(__file__)) data = recfromtxt(filepath + '/scotvote.csv', delimiter=",", names=True, dtype=float, usecols=(1,2,3,4,5,6,7,8)) names = list(data.dtype.names) endog = array(data[names[0]], dtype=float) endog_name = names[0] exog = column_stack(data[...
[ "def load():\n\n # Path for the cache-file.\n cache_path = os.path.join(data_dir, \"data.pkl\")\n\n # If the DataSet-object already exists in a cache-file\n # then load it, otherwise create a new object and save\n # it to the cache-file so it can be loaded the next time.\n dataset = load_cached(ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the NCE scores for predicting r_src>r_trg.
def forward(self, r_src, r_tgt, pos_matrix, neg_matrix): # compute src->trg raw scores for batch # (n_batch, n_keys) raw_scores = torch.mm(r_src, r_tgt.transpose(0, 1)).float() raw_scores /= self.temperature ''' pos_scores includes scores for all the positive samples ...
[ "def nyu_compute_metrics(pred, gt):\n\t# test image pre-processing \n\tpred, gt = nyu_metrics_preprocess(pred, gt)\n\t#print(\"pred:\", pred)\n\t#print(\"gt:\", gt)\n\t#print(\"++++++++++++++++++++++++++++++++==\")\n\n\t## compute MSE and RMSE\n\tmse = ((gt - pred) ** 2).mean()\n\trmse = np.sqrt(mse)\n\n\t#print(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses model to predict the sentiment of a sentence, then uses Integrated Gradients to compute attributions
def interpret_sentence(self, model, sentence, tokenizer, min_len = 32): model = WrapperModel(model) lig = LayerIntegratedGradients(model, model.model.roberta.embeddings) PAD_IND = tokenizer.pad_token_id token_reference = TokenReferenceBase(reference_token_idx=PAD_IND) indexed = t...
[ "def train_model(self):\n for language, tweets in self.data.items():\n for tweet in tweets:\n if self.ngram == '1':\n for i in range(len(tweet) - 1):\n first = tweet[i] # get the first character\n if not first.isspace(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }