content
stringlengths
42
6.51k
def cut_parser(lines): """cut format parser Takes lines from a cut file as input. returns dict of {codon:count}. """ result = {} for line in lines: if line.startswith('#'): continue if not line.strip(): continue fields = line.split() resul...
def reformat_large_tick_values(tick_val): """ Turns large tick values (in the billions, millions and thousands) such as 4500 into 4.5K and also appropriately turns 4000 into 4K (no zero after the decimal). """ new_tick_format = tick_val sign = '-' if tick_val < 0 else '' tick_abs = abs(tick_val...
def update_claims(session, about, provider_info, old_claims=None): """ :param session: :param about: userinfo or id_token :param old_claims: :return: claims or None """ if old_claims is None: old_claims = {} req = None try: req = session["authn_req"] except Key...
def sdg_gate_counts_deterministic(shots, hex_counts=True): """Sdg-gate circuits reference counts.""" targets = [] if hex_counts: # Sdg targets.append({'0x0': shots}) # H.Sdg.Sdg.H = H.Z.H = X targets.append({'0x1': shots}) # H.Sdg.S.H = I targets.append({'0x0'...
def lerp(x, x0, x1, y0, y1): """Linearly interpolate a value y given range y0...y1 that is proportional to x in range x0...x1 . """ return y0 + (x - x0) * ((y1 - y0) / (x1 - x0))
def _to_rgba(color): """ Converts a color to RGBA. Parameters ---------- color : int, float or list If numeric, is interpreted as gray-value between 0 and 1. If list, has to have length 3 or 4 and is interpreted as RGB / RGBA depending on length (again, with values in [0, 1]). ...
def mod_inverse(a, m): """ Modular Multiplicative Inverse of two integers 'a' and 'm' is a positive integer 'x' less than m such that (ax) % m is 1. Finds modular inverse of 'a' modulo 'm' by checking for all integers from 1 to 'm' and returns -1 if it doesn't exist. >>> from pydsa import mod_...
def dict_has_nested_key(d, keys): """Check if *keys (nested) exists in d (dict).""" _d = d for key in keys: try: _d = _d[key] except KeyError: return False return True
def pathLeaf(path): """ Extracts file name or directory name from given path. :param str path: Full or relative path :return: File name from given path. :rtype: str >>> pathLeaf("c:/temp/test.html") 'test.html' >>> pathLeaf("c:/temp/") 'temp' """ import ntpath head, tail ...
def parse_flags(raw_flags, single_dash=False): """Return a list of flags. If *single_dash* is False, concatenated flags will be split into individual flags (eg. '-la' -> '-l', '-a'). """ flags = [] for flag in raw_flags: if flag.startswith("--") or single_dash: flags.append(...
def getIndex(readmap, checklist): """ inputs: readmap - list of symbols checklist - list of strings(delineated by semicolons) """ readmap = list(readmap) #type cast from set to list holder = [] counter=0 for i in readmap: # iterate over readmap switch=True ...
def get_random_fact_pos(othersys): """ Make sure we get the 'random_fact' workflow spec no matter what order it is in """ rf2pos = 0 for pos in range(len(othersys)): if othersys[pos]['workflow_spec_id'] == 'random_fact': rf2pos = pos return rf2pos
def validate_coin_selection(selection): """Validation function that checks if 'selection' arugment is an int 1-5""" switcher = { 1: (True, "Quarter"), 2: (True, "Dime"), 3: (True, "Nickel"), 4: (True, "Penny"), 5: (True, "Done") } return switcher.get(selection, (F...
def write_log(game_data, message, type=0): """ Write a message in the game logs. Parameters ---------- game_data: data of the game (dic). message: message to print to game logs (str). (optional) type: type of the message <0 = info|1 = warning|2 = error> Return ------ ga...
def sbst_id(dic, id_, upd=None): """Substitute test id and upd dict. Parameters ---------- dic : dict id_ : str Subdir name with specific test results. upd : dict Update for dic. """ if upd is None: upd = {} return {**{k: (v.replace('__id__', id_) if isinsta...
def ranked_vaccine_peptides(variant_to_vaccine_peptides_dict): """ This function returns a sorted list whose first element is a Variant and whose second element is a list of VaccinePeptide objects. Parameters ---------- variant_to_vaccine_peptides_dict : dict Dictionary from varcode.Var...
def euclidean_dist(p1, p2): """ Returns the euclidean distance between points (p1, p2) in n-dimensional space. Points must have the same number of dimensions. """ if len(p1) != len(p2): raise ValueError("Points must have the same number of dimensions.") return sum((d1 - d2) ** 2 for...
def is_macosx_sdk_path(path): """ Returns True if 'path' can be located in an OSX SDK """ return (path.startswith('/usr/') and not path.startswith('/usr/local')) or path.startswith('/System/')
def serialize_composite_output(analysis, type): """.""" return { 'id': None, 'type': type, 'attributes': { 'thumb_url': analysis.get('thumb_url', None), 'tile_url':analysis.get('tile_url', None), 'dem':analysis.get('dem', None), 'zonal_stat...
def intersect_exprs(La, Lb): """ Intersect two lists of Exprs. """ b_unique_strs = set([node.unique_str() for node in Lb]) return [node for node in La if node.unique_str() in b_unique_strs]
def unslash(s): """Remove optional slash from the end.""" if not s or s[-1] != '/': return s return s[:-1]
def comb(N, k): """Compute N choose k""" if k > N or N < 0 or k < 0: return 0 M = N + 1 nterms = min(k, N - k) numerator = 1 denominator = 1 for j in range(1, nterms + 1): numerator *= M - j denominator *= j return numerator // denominator
def activate_model(cfg): """Activate the dynamic parts.""" cfg["fake"] = cfg["fake"]() return cfg
def resource_input_index(tensor_name, input_names, node_defs, functions): """Returns the index of the input corresponding to `tensor_name`. This method is used to find the corresponding index of an arbitrary resource tensor in a function (the function could be a loop body). We assume that resource handles are ...
def filter_pagenums(line): """ If the given line starts with a number, :param line: :return: """ line = line.strip() if len(line) > 0 and line[0].isdigit(): return None return line
def column_from_parts(table, column): """Given string parts, construct the full column name. >>> column_from_parts('foo', 'bar') 'foo/@/bar' """ if table is None: return column return '{}/@/{}'.format(table, column)
def flatten(array, level=1): """ Flattens array to given level """ for i in range(level): array = [item for sublist in array for item in sublist] return array
def id_collection_to_dict(collection, id_getter): """ Convert a collection of items that possess an id attribute to a dictionary which the same id as their key. :param collection: Collection of IDs. :type collection: dict, list, set, tuple :param id_getter: Function to extract ID from collectio...
def multi_level_argsort(l): """Return indices to sort a multi value tuple. Sorting is done on the first value of the tuple. Parameters ---------- l : list Returns ------- indices Example ------- >>> multi_level_argsort(((0, 2), (4, 9), (0, 4), (7, 9))) [0, 2, 1, 3] ...
def set_formatter_string(config: dict): """Set the formatter string dependending on the config. Currently our logs allow you to pass different configuration parameters to format the logs that are returned to us. This is a helper function to handle these cases. Args: config: contains only t...
def pipe(value, *funcs): """Pipe a value through a sequence of functions.""" for func in funcs: value = func(value) return value
def tree_pop_fields(root, fields): """deletes given fields (as iterable of keys) from root and all its children (recursively) returnes updated root """ for f in fields: root.pop(f) if root['is_leaf']: return root for i in range(len(root['children'])): root['children'][i]['child'] = t...
def odd(n, add=1): """Return next odd integer to `n`. Can be used to construt odd smoothing kernels in :func:`smooth`. Parameters ---------- n : int add : int number to add if `n` is even, +1 or -1 """ assert add in [-1, 1], "add must be -1 or 1" return n if n % 2 == 1 else...
def parse_line(line): """Parse line and return event (str) and command (str). If line starts with the comment character, #, then None is return for both event and command. """ comment_character = '#' #delimiter = '\t' no_comment = line.split(comment_character)[0] ...
def does_not_decrease(s): """ >>> does_not_decrease('1234') True >>> does_not_decrease('111123') True >>> does_not_decrease('135679') True >>> does_not_decrease('223450') False >>> does_not_decrease('111111') True >>> does_not_decrease('123789') True """ l = [...
def power(x, n): """Complexity: O(log n)""" if n == 0: return 1 else: partial = power(x, n // 2) result = partial * partial if n % 2 == 1: result *= x return result
def vals_to_pct(n, d): """Remaps the values of the dict `d` to percentages of `n`.""" return {k: round(float(v) / n * 100, ndigits=1) for k, v in d.items()}
def get_day_offset(day, number): """ Returns an integer representing the day number shifted by the given amount """ day -= number if day < 0: day += 7 return day
def target_arch(target): """ Returns the architecture from a target triple :param target: Triple to deduce architecture from :return: Architecture associated with given triple """ return target.split("-")[0]
def runge_kutta_fourth_y(rhs, h, y): """ Solves one step using a fourth-order Runge-Kutta method. RHS expects only the y variable. Moin, P. 2010. Fundamentals of Engineering Numerical Analysis. 2nd ed. Cambridge University Press. New York, New York. :param rhs: "Right-hand Side" of the equation(s). ...
def _move_buckets_to_field(value): """ Move buckets from a dimension into the field """ # return value buckets = value.pop("buckets", None) buckets_default_label = value.pop("buckets_default_label", "Not found") if buckets: if "field" in value: value["field"]["buckets"] = buckets...
def convert_kwargs_to_str(kwargs, max_len=None): """ Convert kwargs to a string, allowing for some arguments to raise exceptions during conversion and ignoring them. """ length = 0 strs = ["" for i in range(len(kwargs))] for i, (argname, arg) in enumerate(kwargs.items()): try: ...
def get_data_metdata_from_revision_record(revision_record): """ Retrieves the data block from revision Revision Record Parameters: revision_record (string): The ion representation of Revision record from QLDB Streams """ revision_data = None revision_metadata = None if ("payload" in...
def isAttrMirrored(attr, mirrorAxis): """ """ if mirrorAxis == [-1, 1, 1]: if attr == 'translateX' or attr == 'rotateY' or attr == 'rotateZ': return True elif mirrorAxis == [1, -1, 1]: if attr == 'translateY' or attr == 'rotateX' or attr == 'rotateZ': return ...
def midi2freq(midi_number): """ Given a MIDI pitch number, returns its frequency in Hz. Source from lazy_midi. """ midi_a4 = 69 # MIDI Pitch number freq_a4 = 440. # Hz return freq_a4 * 2 ** ((midi_number - midi_a4) * (1. / 12.))
def get_attribute(item, attribute): """ Like getattr, but recursive (i.e. you can ask for 'foo.bar.yay'.) """ value = item for part in attribute.split("."): value = getattr(value, part) return value
def _dictify(tuples): """Transform tuples of tuples to a dict of atoms.""" res = dict() for atom, n in tuples: try: res[atom] += int(n or 1) except KeyError: res[atom] = int(n or 1) return res
def get(path): """ Read & return the contents of the provided `path` with the given `content`.""" with open(path, encoding="utf-8") as file: return file.read()
def prefix_with(constant, pieces): """ From a sequence create another sequence where every second element is from the original sequence and the odd elements are the prefix. eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """ return [elem for piece in pieces for elem in [constant, piece]]
def parse_flag(value): """ Convert string to boolean (True or false) :param value: string value :return: True if the value is equal to "true" (case insensitive), otherwise False """ return value.lower() == "true"
def dfs_inorder_traversal_iterative_with_visited(node): """ @ref https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/713539/Python-3-All-Iterative-Traversals-InOrder-PreOrder-PostOrder-Similar-Solutions """ results = [] visited = set() # Recursive stack is replaced by stack of no...
def is_gaussian_integer(z): """ Checks whether a given real or complex number is a Gaussian integer, i.e. a complex number g = a + bi such that a and b are integers. """ if type(z) == int: return True return z.real.is_integer() and z.imag.is_integer()
def inclusion_explicit_no_context_from_template(arg): """Expected inclusion_explicit_no_context_from_template __doc__""" return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg}
def _findfeat(feats, to_find): """Check if 'to_find' is a feature (key) in 'feats'.""" for feat in feats: if (f"{to_find}=") in feat: return True return False
def flatten_list(values): """Flatten a list""" return [v for value in values for v in value]
def parseDeviceNumber(deviceNum): """ Parse the device number, returning the format of card# Parameters: deviceNum -- DRM device number to parse """ return 'card' + str(deviceNum)
def wrap_to_pm(x, to): """Wrap x to [-to,to).""" return (x + to)%(2*to) - to
def db2lin(data): """ Convert from logarithm to linear units Parameters ---------- data: single value or an array Returns ------- returns the data converted to linear """ return 10**(data/10.)
def calcular_precio_producto(coste_producto): """ num -> num Calcula el costo de un producto mas el 50% sobre el costo de fabrica >>> calcular_precio_producto(1000) 1500.0 >>> calcular_precio_producto(2000) 3000.0 :param coste_producto: num que representa el costo de fabrica del prod...
def reverse_inclusive_range(low, high): """Get decreasing range from high to low, inclusive to inclusive""" # Note that python range is inclusive to exclusive return range(high, low - 1, -1)
def findall(seq, f): """Return all the element in seq where f(item) == True.""" result = [] for element in seq: if f(element): result.append(element) return result
def filekind_to_keyword(filekind): """Return the FITS keyword at which a reference should be recorded.""" return filekind.upper()
def remove_chars(s, chars): """Remove any character in chars from string s s: string chars: string of characters """ for c in chars: if c in s: s = s.replace(c,'') return s
def hash128(str): """ return 7-bit hash of string """ hash = 0 for char in str: hash = (31 * hash + ord(char)) & 0xFFFFFFFF hash = ((hash + 0x80000000) & 0xFFFFFFFF) - 0x80000000 # EQUELLA reduces hashes to values 0 - 127 hash = hash & 127 return hash
def t_dwyer(raw_value): """Returns Dwyer sensor temperature from a raw register value. Range is -30C to +70C. """ # Temperature linear calibration = 100 / (2^15 - 1) T0 = -30.0 Ts = 100.0 / (2 ** 15 - 1) return (T0 + Ts * float(raw_value), "degC")
def _create_bifpn_input_config(fpn_min_level, fpn_max_level, input_max_level, level_scales=None): """Creates a BiFPN input config for the input levels from a backbone network. Args: fpn_min_level: the minimum pyramid l...
def MatchingOracleCost(N, K, k): """ Returns ------ cost : float The expected number of call it take to find k documents out of K in a database containing N documents (without replacement) Notes ----- This function does not check if the inputs are valid i.e. N >= K >...
def slices(start, xs): """Returns slices of a given sequence separated by the specified indices. If we wanted to get the slices necessary to split range(20) in sub-sequences of 5 items each we'd do: >>> seq = range(20) >>> indices = [5, 10, 15] >>> for piece in slices(0, indices): ... ...
def get_measurement_lag(gt_id): """Returns the number of days of lag (e.g., the number of days over which a measurement is aggregated plus the number of days late that a measurement is released) for a given ground truth data measurement """ # Every measurement is associated with its start date, and ...
def invert(x): """Return 1/x >>> invert(2) Never printed if x is 0 0.5 """ result = 1/x # Raises a ZeroDivisionError if x is 0 print('Never printed if x is 0') return result
def trunc(x, n=2.0, truncif='greater'): """truncates a value to a given number (useful if behavior unchanged by increases) Parameters ---------- x : float/int number to truncate n : float/int (optional) number to truncate to if >= number truncif: 'greater'/'less' wh...
def BFS_dist(sink, distList): """ returns the distance to sink given distList. Assumes source is distList[0] returns 1 more than length of distlist if sink not found in distlist """ for i in range(len(distList)): if sink in distList[i]: return i ###else retur...
def filter_staged(position_name, position_annotations, timepoint_annotations): """Filter-function for filter_annotations() to return worms that have been stage-annotated fully and are noted as "dead".""" stages = [tp.get('stage') for tp in timepoint_annotations.values()] # NB: all(stages) below is True ...
def to_w2v_format(token): """Return a given entity token in the format as it would appear in the w2v model: I.e. lowercase and entities in the format "[<QID>]" Arguments: token - A string. >>> to_w2v_format("[Q123:test]") '[q123]' >>> to_w2v_format("[fictional character|Q123:test]") '[...
def service_settings(service_settings): """Have service configured with Service Mesh""" service_settings.update({"deployment_option": "service_mesh_istio"}) return service_settings
def evaluateIdentifier(gold, pred): """ Performs an intrinsic evaluation of a Complex Word Identification approach. @param gold: A vector containing gold-standard labels. @param pred: A vector containing predicted labels. @return: Precision, Recall and F-1. """ #Initialize variables: precisionc = 0 precision...
def _filter_problematic_reqs(reqs): """There are some reqs that have issues when used in certain contexts""" problem_reqs = { # This causes a strange self-ref for arrow-cpp "parquet-cpp", } reqs = [r for r in reqs if r.split(" ")[0] not in problem_reqs] return reqs
def index_parser(index, all_items): """ Parses indices from a index-string in all_items Parameters ---------- index: str A string which contains information about indices all_items All items Returns ------- """ run = list() rm = list() try: if i...
def case_title(text): """Text in Title Case >>> case_title('foO BAr') 'Foo Bar' """ return text.title()
def is_number(value): """ Returns True if the given string value is numeric """ try: float(value) return True except ValueError: return False
def gcd(a, b): """Compute the greatest common divisor of a and b""" r = a % b # Remainder if r == 0: # if remainder is 0, then b is the GCM return b else: # if remainder is not 0, divide b by the remainder a = b b = r return gcd(a, b)
def get_fab_name(icfab): """ Returns human-readable name of fabricator based on provided ICFabricator id @param icfab: string realization of 2 bytes ICFabricator (in hexadecimal, e.g., '4090') @returns human-readable fabricator string """ if icfab.find('0003') != -1: return 'Renesas' # https://w...
def calculate_delta(num_attributes, sensitivity, epsilon): """Computing delta, which is a factor when applying differential privacy. More info is in PrivBayes Section 4.2 "A First-Cut Solution". Parameters ---------- num_attributes : int Number of attributes in dataset. sensitivity : f...
def classify_inv(disrupt_dict): """ Classify genic effect of a inversion. Inversions are disruptive if one or both breakpoints falls within a genic element. """ elements = disrupt_dict.keys() if 'CDS' in elements: # breakpoint disrupts exon -> LoF if ('BOTH-INSIDE' in disrup...
def convert_time(time): """ dealing with time. """ # seconds if time <= 60.0: time = time # minutes elif 60.0 < time < 3600.0: time = time / 60.0 # hours elif 3600.0 < time < 86400: # (3600.0 * 24, i.e. day) time = time / 3600.0 # days elif 86400.0 <= time...
def produceLTLStringMeaning(name, props_list): """ Produces a natural language explanation of the LTL :param name: a string specifying the LTL template name :param props_list: a list of list of strings indicating the propositions :return: a string of natural language meaning of the LTL """ ...
def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5]...
def list2complex(x: list): """ covert list of float into complex in an any dimension list. it's very useful when you want to convert float into complex in eigenvalue algorithm. :param x: (list of float) :return: (list of only complex) """ _list = [] for _i in x: if type(_i).__nam...
def is_jpg(data): """True if data is the first 11 bytes of a JPEG file.""" return data[:4] == '\xff\xd8\xff\xe0' and data[6:11] == 'JFIF\0'
def get_site(coord, L): """Get the site index from the 3-vector of coordinates.""" # XXX: 3D hardcoded, can do N-D return coord[0] * L[1] * L[2] + coord[1] * L[2] + coord[2]
def is_comment(item): """Quick check whether an item is a comment (reply) to another post. The item can be a Post object or just a raw comment object from the blockchain. """ return item['permlink'][:3] == "re-" and item['parent_author']
def _get_desktop_compiler_flags(compiler, compiler_table): """Returns the command line flags for this compiler.""" if not compiler: # None is an acceptable default value return [] try: return compiler_table[compiler] except KeyError: valid_keys = ", ".join(compiler_table.keys()) raise ValueErro...
def normalize(position): """ Accepts `position` of arbitrary precision and returns the block containing that position. Parameters ---------- position : tuple of len 3 Returns ------- block_position : tuple of ints of len 3 """ try: x, y, z = position if type(position) ...
def get_event_id(event_list=[], details=None): """Get the id of an event.""" if not details: return None # print("-----") # print("EVENT_LIST", event_list) # print("DETAILS", details) existing_event = next( ( one_event for one_event in event_list ...
def open_maybe_compressed_file(path): """Return a file object that possibly decompresses 'path' on the fly. Decompression occurs when argument `path` is a string and ends with '.gz' or '.xz'. """ if not isinstance(path, str): return path if path.endswith('.gz'): import gzip ...
def add_entry(ynew: float, s: float, s2: float, n: int, calc_var: bool): """Adds an entry to the metrics, s, s2, and n. s: previous value of sum of y[] s2: previous value of sum of y[]*y[] n: previous number of entries in the metric """ n = n + 1 s = s + ynew s2 = s2 + ynew * ynew ...
def _platform_toolchain_cmd_join(cmds): """ >>> cmds = _platform_toolchain_cmd_split(test_build_template) >>> out_template = _platform_toolchain_cmd_join(cmds) >>> "\\n".join(difflib.context_diff("\\n".join(test_build_template), "\\n".join(out_template))) '' >>> pprint.pprint(out_template) ...
def E_zeeman(m_vals, B_z): """ Energy shift due to the interaction of the orbital angular momentum of the Rydberg electron with the magnetic field. -- atomic units -- """ return m_vals * B_z * (1/2)
def rgb16_to_rgb24(color): """ Convert 16-bit RGB color to a 24-bit RGB color components. :param color: An RGB 16-bit color. :type color: int :return: A tuple of the RGB 8-bit components, (red, grn, blu). :rtype: tuple """ #red = (color & 0b1111100000000000) >> 11 << 3 #grn = (color...
def alpha_only(target_string, safe_char): """ Returns True if string contains all alphabetic and no numeric characters. Does not consider special characters. Checks quality of parsed prescriber first and last names. Depreciated in module version 1.0.0. Use for DEBUG only. Args: target_s...