content
stringlengths
42
6.51k
def extract_instance_name(url): """Given instance URL returns instance name.""" return url.rsplit('/', 1)[-1]
def addr(registers, a, b, c): """(add register) stores into register C the result of adding register A and register B.""" registers[c] = registers[a] + registers[b] return registers
def _convert_data_string_to_int(s : str): """ Transform the data string extracted from the webpage and return the corresponding int Parameters: s(str) : String of the data extracted from the webpage Return : n(int) : Reformatted integer value extracted from the string s """ ...
def find_phrase(phrase, lines): """Find a phrase in a given list of lines. Given a list of lines, find the first one that contains the given phrase. Keyword arguments: phrase -- the phrase to search for lines -- the list of lines in which to search """ found_phrase = [(index, word) ...
def as_list(x): """Convert x to a list if it is an iterable; otherwise, wrap it in a list.""" try: return list(x) except TypeError: return [x]
def GetOSMallocTagSummary(malloc_tag): """ Summarize the given OSMalloc tag. params: malloc_tag : value - value representing a _OSMallocTag_ * in kernel returns: out_str - string summary of the OSMalloc tag. """ if not malloc_tag: return "Invalid malloc tag value:...
def Klein(z): """Klein's icosahedral invariants.""" return ( 1728 * (z * (z ** 10 + 11 * z ** 5 - 1)) ** 5 / (-(z ** 20 + 1) + 228 * (z ** 15 - z ** 5) - 494 * z ** 10) ** 3 )
def check_for_blanks(variable_object): """Check for blanks.""" if variable_object.strip() == '': return 'All fields are required' return None
def normalize(data, mean, std): """ Zero-mean, one standard dev. normalization :param data: :param mean: :param std: :return: normalized data """ return (data - mean) / std
def sort_by_value(d): """ Returns the keys of dictionary d sorted by their values """ items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() return [ backitems[i][1] for i in range(0,len(backitems))]
def prev(address, step=2): """Take vPC two bytes back, wrap around if needed to stay on page""" return (address & 0xff00) | ((address-step) & 0x00ff)
def tail_avg(timeseries, use_full_duration): """ This is a utility function used to calculate the average of the last three datapoints in the series as a measure, instead of just the last datapoint. It reduces noise, but it also reduces sensitivity and increases the delay to detection. """ t...
def parse_json_information(json_dict): """ Parse the content of the JSON dictionary and grep the variables of interest for the summary statistics. :param json_dict: dictionary with the content of a tool JSON descriptor file :type json_dict: dict :return: dictionary with the variables of interest ...
def addInteger2String(value, val_len, front): """ Function for parsing a integer into a correct string format. Front works as the parser character which tells the program how the string has to be formatted. **Examples**:: >> addInteger2String(3, 5, 0) "00003" :param int value: int...
def extract_properties(pdict): """ Remove _keys from property dictionary. Args: pdict (dict): raw dictionary Returns: dict: clean property dictionary """ clean_dict = dict() for key, val in pdict.items(): if key.startswith("_"): continue clean_d...
def _check_hdf5_file_keys(key_list): """I guess there should be a main key. 10X uses 'matrix' for at least some h5 outputs. """ if len(key_list) == 1: return key_list[0] elif len(key_list) == 0: print("No keys found... check file.") else: print("Too many keys identifi...
def subst(s, x): """ Substitute the substitution s into the expression x. >>> subst({'?x': 42, '?y':0}, ('+', ('F', '?x'), '?y')) ('+', ('F', 42), 0) """ if x in s: return s[x] elif isinstance(x, tuple): return tuple(subst(s, xi) for xi in x) else: return x
def cint(s): """Convert to integer""" try: num = int(float(s)) except: num = 0 return num
def _unfinished_as_map(unfinished_hashes): """ Utility to turn the "unfinished hashes" list into a map. Args: unfinished_hashes (list): The list returned from get_unfinished_hashes(). Returns: dict: The same hash expressed as a map. """ return_value = {} for val in unfinis...
def minsec2dec(old): """ convert latlon from DMS (minute second) to DD (decimal) Parameters ---------- old : string format : DMS format Example ------- >>> from pylayers.gis.gisutil import minsec2dec >>> minsec2dec('50 03 59 N') -50.06638888888889 ...
def isRCS(filename): """ Checks whether a file an RCS data set of form: """ # if a unique pattern (e.g. in first line or filename or content) is recognized: # return True # else: return False
def string_empty(string): """Return True if the input string is None or whitespace.""" return (string is None) or not (string and string.strip())
def page(title, contents): """Format an HTML page.""" return ''' <!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head><title>RSF: %s</title> <style type="text/css"><!-- TT { font-family: lucidatypewriter, lucida console, courier } --></style></head><body bgcolor="#f0f0f...
def unique_common_chains(similar_chains, verbose=False): """ Given a dictionary of pairwise sequence-similar chains (output of the similar_chains function), returns a "unique-common" chains-type dictionary, in which the keys are those chains to which most of the chains in the model are common-to, and as...
def clean_null_from_list(ls): """Cleans elements with value None in a given list.""" return [i for i in ls if i is not None]
def contains(first, second): """Returns True if any item in `first` matches an item in `second`.""" return any(i in first for i in second)
def split_text_by_delims(text): """Splits the string by special characters specified. Filters out empty strings (as a result of the splitting) before returning. """ for ch in [":", ".", "/", "'", "\"", "(", ")", "\\", "[", "]", ",", "\t", "\n", "*", "-"]: text = text.replace...
def compute_min_distance_mendelian(proband_allele, parent_alleles): """Commute the smallest distance between the given proband STR expansion size, and parental STR expansion size. Args: proband_allele (int): the proband's allele length. parent_alleles (list of allele sizes): list of parental a...
def remove_oclcNo_prefix(oclcNo): """ removes OCLC Number prefix for example: ocm00012345 => 00012345 (8 digits numbers 1-99999999) ocn00012345 => 00012345 (9 digits numbers 100000000 to 999999999) on000123456 => 000123456 (10+ digits numbers 1000000000 and higher) args: ...
def get_path_to_radio_sfr_dir(name: str, data_directory: str) -> str: """Get the path to the directory where the star formation data should be stored Args: name (str): Name of the galaxy data_directory (str): dr2 data directory Returns: str: Path to SFR dir """ return f"{da...
def get_longest_substring(a, b): """ This fuction is used to get the longest substring of two strings Args: a & b Return: c: longest substring """ a_len, b_len = len(a), len(b) dy_map = [[0 for j in range(b_len + 1)] for i in range(a_len + 1)] longest = 0 for idx, ite...
def floatable(st: str) -> bool: """ Allows filtering column contents by numeric-ness. """ try: float(st) return True except: return False
def make_id(problem): """Convert problem description in to human-readable id.""" key_value_strs = [] for key, value in problem.items(): if key == "input_fn": key_value_strs.append(f"input_shape={value().shape}") else: key_value_strs.append(f"{key}={value}") retu...
def build_matrix(width, height): """Build a matrix of given width and height""" matrix = [] row = [0] * width for i in range(height): matrix.append(list(row)) return matrix
def parse_chr(file_name): """ Parsing file_name and extracting chromosome input file must be EXPERIMENT_AREA_CELL-TYPE.bam so bamtools create EXPERIMENT_AREA_CELL-TYPE.REF_chrN.PEAK :param file_name: :return: chromosome """ file_name = file_name.rsplit('.',1)[0] file_name = file_na...
def get_weak_csv_filename(data_type): """Prepare weakly labelled csv path. Args: data_type: 'training' | 'testing' | 'evaluation' Returns: str, weakly labelled csv path """ if data_type in ['training', 'testing']: return '{}_set.csv'.format(data_type) elif data_ty...
def lowerbool(value): """ Returns 'true' if the expression is true, and 'false' if not. """ return "true" if value else "false"
def _build_utilization_context(last_week, last_month, this_fy): """Build shared context components of utilization reports""" return { 'last_week_start_date': last_week['start_date'], 'last_week_end_date': last_week['end_date'], 'last_week_totals': last_week['totals'], ...
def lcs(s1, s2, i, j): """ The length of longest common subsequence among the two given strings s1 and s2 """ if i == 0 or j == 0: return 0 elif s1[i - 1] == s2[j - 1]: return 1 + lcs(s1, s2, i - 1, j - 1) else: return max(lcs(s1, s2, i - 1, j), lcs(s1, s2, i, j - 1))
def _boolean(sstr): """Coerce a string to a boolean following the same convention as :meth:`configparser.ConfigParser.getboolean`: - '1', 'yes', 'true' and 'on' cause this function to return ``True`` - '0', 'no', 'false' and 'off' cause this function to return ``False`` :param sstr: String repres...
def tools_section_line(line: str): """ pretty print the line of a tools section """ if not line: return line if line.startswith(('[[', 'name')): return line + '\n' return '\t{}\n'.format(line)
def indent_line(line): """Indent non-empty lines.""" if line: return 4 * ' ' + line else: return line
def _get_min_cd(cwd, cd): """ Given two absolute paths, return the shortest "cd" string that gets from the first (cwd) to the second (cd) """ if cwd is None: return cd # Find common part of path have = cwd.split("/")[1:] want = cd.split("/")[1:] nhave = len(have) ...
def nested_dict_to_list(path, dic, exclusion=None): """ Transform nested dict to list """ result = [] exclusion = ['__self'] if exclusion is None else exclusion for key, value in dic.items(): if not any([exclude in key for exclude in exclusion]): if isinstance(value, dict):...
def get_sequence_frequencies(sequences): """ Computes the frequencies of different sequences in a collection, returning a dictionary of their string representations and counts. Example -------- >>> s1 = [1,1,2,2,3] >>> s2 = [1,2,2,3,3] >>> s3 = [1,1,2,2,2] >>> sequences = [s1,s2,s2,s3,s3,s3] >>> ps.get_seque...
def get_local_batch_size(opts): """Returns local batch size. This is an `effective` batch size for one node. :param dict opts: A dictionary containing benchmark parameters. Must contain `batch_size`, `device` and optionally `num_gpus`. :return: Local batch size. :rtype: int ""...
def deanonymize(sequence, ent_dict, key): """Deanonymizes a sequence. Inputs: sequence (list of str): List of tokens to deanonymize. ent_dict (dict str->(dict str->str)): Maps from tokens to the entity dictionary. key (str): The key to use, in this case either natural language or SQL. ...
def convert_velocity(val, old_scale="km/h", new_scale="m/s"): """ Convert from a velocity scale to another one among km/h, and m/s. Parameters ---------- val: float or int Value of the velocity to be converted expressed in the original scale. old_scale: str Original scale from ...
def get_el_config(charge): """ Returns the electronic shell structure associated with a nuclear charge """ # Electronic shells: 1s, 2s, 2p, 3s, 3p, 4s, 3d, 4p, 5s, 4d, 5p, 6s, 4f, 5d, 6p, 7s, 5f, 6d, 7p el_shell = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Maximum number of elec...
def rgb2html(rgb, alpha=None): """ method will convert given rgb tuple to html representation rgb(R, G, B) if alpha is set, it will be included rgb(R, G, B, ) """ if alpha is not None: return 'rgba({0:d}, {1:d}, {2:d}, {3:s})'.format( *rgb, alpha if isinstance...
def dfs_topological_sort(arr, n): """ Topological sort with DFS. Return an empty list if there is a cycle. """ graph = [[] for _ in range(n)] for u, v in arr: graph[u].append(v) visited, stack = [0] * n, [] def dfs(u): if visited[u] == -1: return False i...
def is_vector(cls): """Returns whether class 'cls' is a std::vector class.""" return cls.__name__.startswith('vector_')
def group_keys_by_attribute(adict, name, tol='3f'): """Make group keys by shared attribute values. Parameters ---------- adict : dic Attribute dictionary. name : str Attribute of interest. tol : float Float tolerance. Returns ------- dic Group dictio...
def alias(requestContext, seriesList, newName): """ Takes one metric or a wildcard seriesList and a string in quotes. Prints the string instead of the metric name in the legend. .. code-block:: none &target=alias(Sales.widgets.largeBlue,"Large Blue Widgets") """ try: seriesList.name = newName e...
def mediana(v): """Encontra o valor mais ao meio de v""" n = len(v) sorted_v = sorted(v) midpoint = n//2 if n % 2 ==1: #Se for impar, retorna o valor do meio return sorted_v[midpoint] else: #Se for par, retorna a media dos valores do meio ...
def sum_words(words): """ Returns the ascii sum of the the letters in each word in words. Expects only capital letters. """ return list(map(lambda s: sum(map(lambda c: ord(c) - ord('A') + 1, s)), words))
def parse_hibp_page(page_str): """ >>> parse_hibp_page('A8C4A624898B4221FC963986F9DC19CF42E:1\r\nAA18199A6DB91A7A4BB1C4B2A89068DAAFC:1\r\n') {'A8C4A624898B4221FC963986F9DC19CF42E': 1, 'AA18199A6DB91A7A4BB1C4B2A89068DAAFC': 1} """ return dict( (hash_suffix, int(frequency)) for (hash_...
def get_deep(x, path, default=None): """ access value of a multi-level dict in one go. :param x: a multi-level dict :param path: a path to desired key in dict :param default: a default value to return if no value at path Examples: x = {'a': {'b': 5}} get_deep(x, 'a.b') returns 5 get_dee...
def anyendswith(value, ends): """ Check if `value` ends with one of the possible `ends` """ for end in ends: if value.endswith(end): return True return False
def run_program(memory): """Execute the successive instructions of the program""" instr_ptr = 0 while True: opcode = memory[instr_ptr] if opcode == 99: # opcode 99 means the program is completed break elif opcode in [1, 2]: # opcode 1 is addition, ...
def genomic_del3_abs_37(genomic_del3_37_loc): """Create test fixture absolute copy number variation""" return { "type": "AbsoluteCopyNumber", "_id": "ga4gh:VAC.Pv9I4Dqk69w-tX0axaikVqid-pozxU74", "subject": genomic_del3_37_loc, "copies": {"type": "Number", "value": 2} }
def exp_two(arg1, arg2): """ (float, float) -> float Exponentiates two numbers (arg1 ** arg2) Returns the exponent """ try: return arg1 ** arg2 except TypeError: return 'Unsupported operation: {0} ** {1} '.format(type(arg1), type(arg2))
def list_find(f, seq): """Return first item in sequence where f(item) == True.""" for item in seq: if f(item): return item
def parse_number(string, numwords=None): """ Parse the given string to an integer. This supports pure numerals with or without ',' as a separator between digets. Other supported formats include literal numbers like 'four' and mixed numerals and literals like '24 thousand'. :return: (skip, value...
def boolfromstring(string, name): """ Takes a string from the configuration file and makes it into a bool """ #try as a string, not case sensitive if string.lower() == "true": return True if string.lower() == "false": return False #try as a number try: return str(bool(int(str...
def _get_prediction(outputs): """Checks if multiple outputs were provided, and selects""" if isinstance(outputs, (list, tuple)): return outputs[0] return outputs
def getBeta(line): """ reads the resName from the pdbline """ if line == None: return 0.0 elif len(line) > 65: if line[60:66] != " ": return float( line[60:66].strip() )
def get_team_repo(remote_url): """ Takes remote URL (e.g., `git@github.com:mozilla/fireplace.git`) and returns team/repo pair (e.g., `mozilla/fireplace`). """ if ':' not in remote_url: return remote_url return remote_url.split(':')[1].replace('.git', '')
def cvt_str_to_sym(str): """Helper for interpret_w_eps --- Given a string, interpret it in all possible ways and return a set of pairs of (first, rest). E.g. "ab" interpreted as ("", "ab") as well as ("a", "b"). However, "" interpreted only as ("", ""). """ if str == "": ...
def get_totrup(data): """ :param data: a record with a field `totrup`, possibily missing """ try: totrup = data['totrup'] except ValueError: # engine older than 2.9 totrup = 0 return totrup
def application_error(e): """500 Internal Server Error""" return 'Sorry, unexpected error: {}'.format(e), 500
def find_rects(image: list) -> list: """ Find multiple rectangles: Potentially the image may have many distinct rectangles of 0's on a background of 1's. The function that takes in the image and returns the coordinates of all the 0 rectangles in either one of the following formats: [[top,le...
def filtername(f): """Return the name of a filter given its number. Parameters ---------- f : :class:`int` The filter number. Returns ------- :class:`str` The corresponding filter name. Examples -------- >>> filtername(0) 'u' """ if isinstance(f, (s...
def sortedby(item_list, key_list, reverse=False): """ sorts ``item_list`` using key_list Args: list_ (list): list to sort key_list (list): list to sort by reverse (bool): sort order is descending (largest first) if reverse is True else acscending (smallest first)...
def human_to_bytes(size): """Given a human-readable byte string (e.g. 2G, 30M), return the number of bytes. Will return 0 if the argument has unexpected form. """ bytes = size[:-1] unit = size[-1] if bytes.isdigit(): bytes = int(bytes) if unit == 'P': bytes...
def read(filename, binary=True): """ Open and read a file :param filename: filename to open and read :param binary: True if the file should be read as binary :return: bytes if binary is True, str otherwise """ with open(filename, 'rb' if binary else 'r') as f: return f.read()
def chip_converter(chip): """Converts a chip name to usable string.""" chip_map = { "3xc": "TC", "wildcard": "WC", "bboost": "BB", "freehit": "FH" } return chip_map[chip]
def get_function_name(s): """ Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str """ s = s.strip() if s.startswith("__attribute__"): # Remove "__attribute__ ((...
def validate_encoding(encoding_name): """Validate encoding name.""" try: import codecs codecs.lookup(encoding_name) except LookupError as e: raise ValueError(e) return encoding_name
def mk_matrix(coord, dist): """Compute a distance matrix for a set of points. Uses function 'dist' to calculate distance between any two points. Parameters: -coord -- list of tuples with coordinates of all points, [(x1,y1),...,(xn,yn)] -dist -- distance function """ n = len(coord) D = ...
def addOperator(args, combinationArg): """ SPARQL numeric + operator implemented via Python """ return ' + '.join([ "sparqlOperators.getValue(%s)%s" % ( i, combinationArg and "(%s)" % combinationArg or '') for i in args])
def for_name(name): """Dynamically load a class by its name. Equivalent to Java's Class.forName """ lastdot = name.rfind('.') if (lastdot == -1): return getattr(__import__('__main__'), name) mod = __import__(name[:lastdot]) for comp in name.split('.')[1:]: mod = getattr(mod...
def splitdrive(path): """ Split a pathname into drive and path. """ result = path.split(":", 1) if len(result) < 2: return ("DK", path) else: return (result[0].upper(), result[1])
def percent_list(part_list, whole_list): """return percent of the part""" w = len(whole_list) if not w: return (w,0) p = 100 * float(len(part_list))/float(w) return (w,round(100-p, 2))
def extend_result(val): """ separated with ',' if it is a list """ if isinstance(val, list): return ','.join(val) return val
def build_kwargs_read(spec: dict, ext: str) -> dict: """Builds up kwargs for the Pandas read_* functions.""" col_arg_names = {'.parquet': 'columns', '.xls': 'usecols', '.xlsx': 'usecols', '.csv': 'usecols'} kwargs = {} if 'columns' in list(s...
def mbxor(msg: bytearray, key: bytearray) -> bytearray: """Encrypt a message using the repeating key xor. Arguments: msg {bytearray} -- Message to be encrypted key {bytearray} -- Key to be used Returns: bytearray -- Ciphertext of msg ^ key, length of longer msg """ cipher =...
def logistic(x, c, x0, L, k): """Not Implemented. Placeholder for calculating asymptotic buildup curve Args: x (array): x values c (float): offset x0 (float): x-value of sigmoid's midpoint L (float): maximum value k (float): logistic growth steepness Returns: ...
def get_loc_per_repository(repo): """ Get LOC in the repository. Keyword arguments: repo -- object containing properties of the repo """ loc_count = 0 for file in repo['files']: if file is None or not 'LoC' in file: return -1 loc = file['LoC'] if loc <=...
def eval(x): """Convert x to a built-in Python data type, by default to string""" try: return __builtins__.eval(x) except: return str(x)
def _calc_auto_plot_height(group_count): """Dynamic calculation of plot height.""" ht_per_row = 40 if group_count > 15: ht_per_row = 25 return max(ht_per_row * group_count, 300)
def isiterable(obj): """ Check whether a given object is iterable Parameters ---------- obj: Iterable Returns ------- bool """ try: _ = iter(obj) except TypeError: return False return True
def unique_by(func, objects): """ Sorts by applying func to each item :param func: Applied to each object to get the sortable result :param objects: iterable :return: The sorted objects """ seen = set() def hash(obj): value = func(obj) return value not in seen and no...
def decode_far_reg(word: int): """ :param word: FAR register value :return: tuple for each field """ # 00 0000 0000 0000 0000 0000 0000 # 11 1 => 0x0380_0000 # 00 01 => 0x0040_0000 # 00 0011 1110 => 0x003E_0000...
def count_leaves(d:dict) -> int: """Count the number of leaves in a nested dictionary. """ n = 0 for k,v in d.items(): if type(v) is dict: n += count_leaves(v) else: n += 1 return n
def AvgEnsemble(dets, iou_threshold=0.5): """ Args: dets: list of [ymin, xmin, ymax, xmax, class, score] iou_threshold: float Returns: new detections like a list of [ymin, xmin, ymax, xmax, class, score] """ def computeIOU(box1, box2): """ Args: box1: [...
def transcribe(seq: str) -> str: """ transcribes DNA to RNA by generating the complement sequence with T -> U replacement """ # transcription dictionary containing mapping of compliment bases. nuc_dict = { 'A' : 'U', 'T' : 'A', 'G' : 'C', 'C' : 'G' } # ini...
def signExtImmed(immed): """Python int are not bounded unlike C int32, This function convert the given immed (16 bits long) into a valid python signed number """ if (immed & 0x8000): return immed - 0x10000 else: return immed
def clean_email_address_str(input_string): """Remove unwanted characters from an email address. This only handles characters, not encoding. Args: input_string (str): The email address to clean Returns: str: The cleaned version of `input_string` Examples: >>> clean_email_a...
def read_in(filename): """ return a bytes object(like "rb") read_in(path) like: read_in(r"c:\1.txt") """ result = b"" try: with open(filename,'rb') as f: result = f.read() except:pass return result