content
stringlengths
42
6.51k
def merge(target, override): """ Recursive dict merge Based on merge method found in dcase_util > https://github.com/DCASE-REPO/dcase_util/blob/master/dcase_util/containers/containers.py#L366 Parameters ---------- target : dict target parameter dict override : dict override par...
def replace_uppercase_letters(filename): """Replace uppercase letters in a string with _lowercase (following doxygen way) e.g. : TimeStepping --> _time_stepping This is useful to postprocess filenames from xml-doxygen outputs and feed them to doxy2swig, even when CASE_SENSE_NAMES = NO in doxyg...
def rate(hit, num): """Return the fraction of `hit`/`num`, as a string.""" if num == 0: return "1" else: return "%.4g" % (float(hit) / num)
def add_interval(intervals, interval_to_add): """ Question 14.6: Takes an array of disjoint intervals with integer endpoints, sorted by increasing order of left endpoint, and an interval to add, and returns the union of the intervals in the array and the added interval """ processed_interval...
def srev(S): """In : S (string) Out: reverse of S (string) Example: srev('ab') -> 'ba' """ return S[::-1]
def normalize_ret(ret): """ Normalize the return to the format that we'll use for result checking """ result = {} for item, descr in ret.items(): result[item] = { "__run_num__": descr["__run_num__"], "comment": descr["comment"], "result": descr["result"], ...
def assertCloseAbs(x, y, eps=1e-9): """Return true iff floats x and y "are close\"""" # put the one with larger magnitude second if abs(x) > abs(y): x, y = y, x if y == 0: return abs(x) < eps if x == 0: return abs(y) < eps # check that relative difference < eps assert...
def generate_filename(num_docs, op_type, input_type) -> str: """ Generates filename using num_docs, op_type, input_type """ return f'docs_{num_docs}_{op_type}_{input_type}.parquet'
def _TIME2STEPS(time): """Conversion from (float) time in seconds to milliseconds as int""" return int(time * 1000)
def normalize_column(tag): """Delete extra spaces from data""" if type(tag) == list: return list(set( [' '.join(item.split()) for item in tag] )) elif type(tag) == str: return [tag, ] else: return []
def convert_params(mu, alpha): """ Convert mean/dispersion parameterization of a negative binomial to the ones scipy supports See https://en.wikipedia.org/wiki/Negative_binomial_distribution#Alternative_formulations """ r = 1. / alpha var = mu + 1. / r * mu ** 2 p = (var - mu) / var ret...
def linear(x, a, b): """linear Parameters ---------- x : int a : float b : float Returns ------- float a*x + b """ return a*x + b
def get_top_n_score(listing_scores, size_n=30): """ Getting the top scores and limiting number of records If N = 2, Get the top 2 listings based on the score { listing_id#1: score#1, listing_id#2: score#2 } TO [ [listing_id#1, score#1], [listing_id#2, score#2...
def do_entities_overlap(entities): """Checks if entities overlap. I.e. cross each others start and end boundaries. :param entities: list of entities :return: boolean """ sorted_entities = sorted(entities, key=lambda e: e["start"]) for i in range(len(sorted_entities) - 1): curr_ent =...
def median(nums): """ calculates the median of a list of numbers """ ls = sorted(nums) n = len(ls) if n == 0: raise ValueError("Need a non-empty iterable") # for uneven list length: elif n % 2 == 1: # // is floordiv: return ls[n // 2] else: return sum(...
def swap_bytes(value): """Convert hex string to little-endian bytes.""" str = hex(value)[2:].zfill(8) return str[6:8] + str[4:6] + str[2:4] + str[0:2]
def mbar2inHg (mbar): """ Convert millibars to inches of mercury. :param mbar: (`float`) The pressure in millibars. :return: - **inHg** (`float`) -- The pressure in inches of mercury. """ inHg = 0.029530 * mbar return inHg
def soil_air_heat_transfer(Vw): """ :param Vw: Velocity of the wind, m/s :return: Soil-air heat transfer coefficient, W/(m2*K) """ return 6.2 + 4.2*Vw
def valid_service(value): """Test if a service is a valid format. Format: <domain>/<service> where both are slugs. """ return ('.' in value and value == value.replace(' ', '_'))
def name_orcid(entry): """Helper function for Name + ORCID""" return f"{entry['name']} (ORCID: [{entry['ORCID']}](https://orcid.org/{entry['ORCID']}))"
def resize_until_fit(texts_list, width): """ Removes from end of text_list such that the length of elements in text_lest fit width :param texts_list: :param width: :return: text_list modified to fit with width """ lengths = sum([len(x) for x in texts_list]) if lengths < width: ...
def doubleEscape(arg1, arg2): """Search through arg1 and replace all instances of arg2 with 2 copies of arg2.""" output = '' for c in arg1: if c == arg2: output += arg2 + arg2 else: output += c return output
def is_independent_set(d, a): """ test if vertices in `a` are independent in graph with dict `d` Parameters ========== d : dictionary of the graph a : tuple or list of vertices """ n = len(a) for i in range(n): for j in range(i): k1 = a[i] k2 = a[j] ...
def utoascii(text): """ Convert unicode text into ascii and escape quotes. """ if text is None: return "" out = text.encode("ascii", "replace") out = out.replace('"', '\\"') return out
def PssmValidator(pssm): """validate each PSSM matrix format, no head. pssm = [[], [], ... , []] """ #print pssm for pos in pssm: if len(pos)!=4: return False for base in pos: try: float(base) except ValueError: retu...
def ixor(a, b): """Same as a ^= b.""" a ^= b return a
def separate_appetizers(dishes, appetizers): """ :param dishes: list of dish names :param appetizers: list of appetizer names :return: list of dish names The function should return the list of dish names with appetizer names removed. Either list could contain duplicates and may require de-...
def hash_string(s) -> int: """ Used to compress UB (molecule barcodes) to group identical ones. Mapping is deterministic, unique and fast for UBs used. """ result = 0 for c in s: result *= 5 result += ord(c) return result
def round2ArbatraryBase(value, direction, roundingBase): """Round value up or down to arbitrary base Parameters ---------- value : float Value to be rounded. direction : str Round up, down to the nearest base (choices: "up","down","nearest") roundingBase : int rounding...
def prunecontainers(blocks, keep): """Prune unwanted containers. The blocks must have a 'type' field, i.e., they should have been run through findliteralblocks first. """ pruned = [] i = 0 while i + 1 < len(blocks): # Searching for a block that looks like this: # # +...
def keyphrase_label_from(candidate_span, element, generic_label=True): """Receive candidate_span and element from dataset and return keyphrase label""" label = "NON-KEYPHRASE" if "keyphrases" in element and\ "keyphrase-id" in candidate_span and \ candidate_span["keyphrase-id"] in ele...
def change_coords(h, coords): """ updates coords of home based on directions from elf """ if h == '^': coords[1] += 1 elif h == '>': coords[0] += 1 elif h == 'v': coords[1] -= 1 elif h == '<': coords[0] -= 1 return coords
def is_list(l): """returns True if `l` is a list, False if not""" return type(l) in [list, tuple]
def check_x_scale(x_scale): """ Checks the specified x_scale is valid and sets default if None """ if x_scale is None: x_scale = "physical" x_scales = ["physical", "treewise"] if x_scale not in x_scales: raise ValueError( f"Unknown display x_scale '{x_scale}'. " f"Sup...
def php_dirname(_path, _levels=1): """ >>> php_dirname("/etc/passwd") '/etc' >>> php_dirname("/etc/") '/' >>> php_dirname(".") '.' >>> php_dirname("/usr/local/lib", 2) '/usr' """ if _path == ".": return "." if _path.endswith("/"): _path = _path[:-1] ...
def transform_with(sample, transformers): """Given a list of values and functions, apply functions to values. This does nothing if the list of functions is None or empty. If there are fewer transformers than the length of the list, it wraps around. :param sample: list of values :param transformers...
def any_user(iterable): """ Performs essentially the same function as the builtin any() command If an items in the list is true, this will return true :param iterable: :return: true/false """ for element in iterable: if element: return True return False
def get_deps(project_config): """ Get the recipe engine deps of a project from its recipes.cfg file. """ # "[0]" Since parsing makes every field a list return [dep['project_id'][0] for dep in project_config.get('deps', [])]
def isPowerOfThree(n): """ :type n: int :rtype: bool """ if n <= 0: return False while(n>1): if n % 3 != 0: return False n=n//3 return True
def make_rgb(cred, cgreen, cblue): """ make rgb for components """ redval = int(round(cred)) greenval = int(round(cgreen)) blueval = int(round(cblue)) ret = int(redval * 0x10000 + greenval * 0x100 + blueval) if ret < 0: ret = 0 if ret > 0x00ffffff: ret = 0x00ffffff ...
def parse(sentence): """ Removes everything but alpha characters and spaces, transforms to lowercase :param sentence: the sentence to parse :return: the parsed sentence """ # re.sub(r'([^\s\w]|_)+', '', sentence) # return sentence.lower()#.encode('utf-8') # re.sub("^[a-zA-Z ]*$", '', sen...
def diffCertLists(leftList : list, rightList : list) -> dict: """ Return diff between to lists of certs """ missingFromLeft = list() missingFromRight = list() for oLeft in leftList: if oLeft not in rightList: missingFromLeft.append(oLeft) continue #if ...
def convert_sim_dist_oneminus(val: float) -> float: """ Convert from similarity to distance with 1 - x. """ assert 0 <= val <= 1 out = 1 - val assert 0 <= out <= 1 return out
def isacn(obj): """isacn(string or int) -> True|False Validate an ACN (Australian Company Number). http://www.asic.gov.au/asic/asic.nsf/byheadline/Australian+Company+Number+(ACN)+Check+Digit Accepts an int, or a string of digits including any leading zeroes. Digits may be optionally separated with...
def filter_tweet_url(tweet_text): """ Extract URL to original tweet from tweet text. Parameters: tweet_text (str): tweet text must include an URL Returns: url (str): url referening to original tweet """ start_index = tweet_text.rfind("https://t.co/") end...
def get_time_str(time_in): # time_in in seconds """Convert time_in to a human-readible string, e.g. '1 days 01h:45m:32s' Args: time_in: float Time in seconds Returns: A string """ day = round(time_in) // (24*3600) time2 = time_in % (24*3600) hour, min = div...
def page_not_found(e): """ When client connects to a route that doesn't exist. Returns: Error message that resource was not found. """ return "<h1>404</h1><p>The resource could not be found.</p>", 404
def split_extra_tests(filename): """Take a filename and, if it exists, return a 2-tuple of the parts before and after '# demo'.""" try: contents = open(filename).read() + '# demo' return contents.split("# demo", 1) except IOError: return ('', '')
def parse_float_ge0(value): """Returns value converted to a float. Raises a ValueError if value cannot be converted to a float that is greater than or equal to zero. """ value = float(value) if value < 0: msg = ('Invalid value [{0}]: require a number greater than or equal to ' ...
def _is_hangul_syllable(i): """ Function for determining if a Unicode scalar value i is within the range of Hangul syllables. :param i: Unicode scalar value to lookup :return: Boolean: True if the lookup value is within the range of Hangul syllables, otherwise False. """ if i in range(0xAC00, 0...
def page_max_100(resource): """Always returns 100 as the page max size.""" if resource is not None: return 100
def setdefault_source_language(dic, default=None): """ This function modifies the given dict in-place; like the {}.setdefault method, it returns the actual value. Besides the verbose 'source_language' key, the 'src_lang' alias is considered as well. If both are found, they must be equal. >>> d...
def merge_helper(arr1, arr2): """ Merges two arrays in increasing order :type arr1: list :type arr2: list :rtype: list """ i = 0 # index for arr1 j = 0 # index for arr2 ret = list() # iterate through both arrays, creating a new list that takes new elements # in increasing ord...
def my_py_command(test_mode, params): """ Print out the "foo" param passed in via `airflow tasks test example_passing_params_via_test_command run_this <date> -tp '{"foo":"bar"}'` """ if test_mode: print(" 'foo' was passed in via test={} command : kwargs[params][foo] \ = {}...
def NSplitQuotedString(string, nmax, quotes, delimiters=' \t\r\f\n', escape='\\', comment_char='#'): """ Split a quoted & commented string into at most "nmax" tokens (if nmax>0), where each tok...
def Data_Type(data): """ This will return whether the item received is a dictionary, list, string, integer etc. CODE: Data_Type(data) AVAILABLE PARAMS: (*) data - This is the variable you want to check. RETURN VALUES: list, dict, str, int, float, bool EXAMPLE CODE: test1 = ['this','is','a','list...
def split_text(text, n=100, character=" "): """Split the text every ``n``-th occurrence of ``character``""" text = text.split(character) return [character.join(text[i : i + n]).strip() for i in range(0, len(text), n)]
def brute_force_partition(S): """ Brute force partition algorithm This function finds the optimal partition of the subset of the real numbers, S, by computing every possible subset of S and comparing every possible partition for the optimal one. This algorithm takes exponential time, since computing t...
def get_cost_influence(did_we_trade, amount_influence, current_influence): """ returns how much it costs to buy amount_influence if did_we_trade and have current_influence """ if amount_influence == 0: return 0 cost = 0 if did_we_trade: cost = cost + 1 amount_influence = ...
def class_properties(object, attributes_to_delete=None): """ Return a string with actual object features without not necessaries :param attributes_to_delete: represent witch attributes set must be deleted. :return: A copy of class.__dic__ without deleted attributes """ dict_copy = object.__dict_...
def encode(content, charset): """Encode content using specified charset. """ try: return content.encode(charset) except: return False
def get_pairs(word): """ (Subword Encoding) Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings) """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return ...
def recursive_copy(obj): """ Copy a container object recursively Args: obj (list, tuple, dict or object): input container object. Return: copied object. """ if isinstance(obj, list): return [recursive_copy(it) for it in obj] if isinstance(obj, tuple): return...
def diff_access(access1, access2): """Diff two access lists to identify which users were added or removed. """ existing = {str(user['id']) for user in access1['users']} new = {str(user['id']) for user in access2['users']} added = list(new - existing) removed = list(existing - new) return...
def grad(x): """ The gradient (derivative) of the sigmoid function :param x: inputs :return: derivative of sigmoid, given x. """ deriv = x * (1 - x) return deriv
def remove_prefix(text, prefix): """ Remove the prefix from the text if it exists. >>> remove_prefix('underwhelming performance', 'underwhelming ') 'performance' >>> remove_prefix('something special', 'sample') 'something special' """ null, prefix, rest = text.rpartition(prefix) re...
def data_to_hex(data): """ @type data: C{bytearray} @rtype: C{str} """ txt = ''.join('%02x' % (i) for i in data) return txt
def remove_swarm_metadata(code: bytes) -> bytes: """ Remove swarm metadata from Solidity bytecode :param code: :return: Code without metadata """ swarm = b'\xa1\x65bzzr0' position = code.find(swarm) if position == -1: raise ValueError('Swarm metadata not found in code %s' % code....
def calc_route(centrex=400, centrey=300, halfwidth=200, radius=100): """This just calculates the 6 points in our basic figure of eight should be easy enough and we then draw lines between each point and get the last point >>> calc_route(400, 300, 200, 100) [(200, 400), (100, 300), (200, 200), (600,...
def total_time(lessons): """ Iterates through a list of lessons and totals the time in seconds. """ # Set total to zero. total = 0 # Loop through all the lessons. for lesson in lessons: total += lesson.lesson_duration # Put the total into (hours,mins,seconds) # Calculate minu...
def contains_reserved_character(word): """Checks if a word contains a reserved Windows path character.""" reserved = set(["<", ">", ":", "/", "\\", "|", "?", "*"]) word_set = set(list(word)) return not reserved.isdisjoint(word_set)
def ddm2dd(coordinates): """ Convert degree, decimal minutes to degree decimal; return 'Lat_dd': float(lat_dd), 'Lng_dd': float(lng_dd)} Input Ex.: ['3020.1186383580', 'N', '0894.5222887340', 'W'], return: {'Lat_dd': float(lat_dd), 'Lng_dd': float(lng_dd)} """ lat, lat_direction, lng, lng_direction...
def listToItem2index(L): """converts list to dict of list item->list index This is lossy if there are duplicate list items""" d = {} for i, item in enumerate(L): d[item] = i return d
def _color(param): """ Switch-case for determining the color of the message depending on its type """ return { 'Success': 'green', 'Warning': 'orange', 'Error': 'red', 'Information': 'blue', 'Debug': 'black' }.get(param, 'Debug')
def filterRows(function, rows): """ Filter rows with given filter function and return only rows that returns true. """ return [y for y in rows if function(y)]
def EPS(x): """ returns 10^(-15) if x is 0, otherwise returns x """ if x == 0: return 1.e-15 else: return x
def cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ return (x > y) - (x < y)
def iimplies(v1, qfs1, v2, qfs2): """ >>> from eqfun import EqFun #>>> f1 = EqFun(('eq', '==', (Arg((0, typing.Any)), Fun(('lpop', 'list.pop', (Fun(('linsert', 'list.insert', (Fun(('lextend', 'list.extend', (Arg((0, typing.List[typing.Any])), Fun(('lappend', 'list.append', (Arg((1, typing.List[typing.Any]...
def check_convert_single_to_tuple(item): """ Checks if the item is a list or tuple, and converts it to a list if it is not already a list or tuple :param item: an object which may or may not be a list or tuple :return: item_list: the input item unchanged if list or tuple and [item] ...
def _int(v): """ >>> _int('5') 5 >>> _int('Abacate') nan """ try: return int(v) except Exception: return float("nan")
def lget(_list, idx, default): """Safely get a list index.""" try: return _list[idx] except IndexError: return default
def _decode_mask(mask): """splits a mask into its bottom_any and empty parts""" empty = [] bottom_any = [] for i in range(32): if (mask >> i) & 1 == 1: empty.append(i) if (mask >> (i + 32)) & 1 == 1: bottom_any.append(i) return bottom_any, empty
def catalan(n): """Helper for binary_bracketings_count(n). """ if n <= 1: return 1 else: # http://mathworld.wolfram.com/CatalanNumber.html return catalan(n-1)*2*(2*n-1)/(n+1)
def drop_empty_strings(X): """ :param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> drop_empty_strings([['', '', 'quid', 'est', 'veritas'], ['vir', 'qui', 'adest']]) [['quid', 'est', 'veritas'], ['vir', 'qui', 'adest']] """ return [[wo...
def mfluxcorr(lambda_r, p0, p1, lamb_piv=1113.): """ Correction factor to power-law fit Parameters ---------- lambda_r p lamb_piv Returns ------- """ lamb_piv = 1113. # This is the pivot point in the restframe spectrum return p0 + p1*(lambda_r/lamb_piv - 1.)
def sql_unique(index): """ Is the index unique or not return : string """ res = "" if "unique" in index: if index["unique"]: res = "UNIQUE" return res
def format_genomic_distance(distance, precision=1): """ Turn an integer genomic distance into a pretty string. :param int distance: Genomic distance in basepairs. :param int precision: Number of significant figures to display \ after the decimal point. """ formatting_string = '{{0:.{0}...
def unzip(lst): """Unzip a zipped list""" return list(zip(*lst))
def bitstring(n, minlen=1): """Translate n from integer to bitstring, padding it with 0s as necessary to reach the minimum length 'minlen'. 'n' must be >= 0 since the bitstring format is undefined for negative integers. Note that, while the bitstring format can represent arbitrarily large numbers, ...
def as_path_change(paths): """ mark the idx at which AS path changes Args: paths (list of list of ASN): [[ASN,...],...] Returns: list of int, index of change is set to 1, otherwise 0 """ change = [0] * len(paths) for idx, path in enumerate(paths): if idx > 0: ...
def He1_function(phi): """First derivative of the expansive part of the potential H Args: phi: phase-field Returns: He1: First derivative of the expansive part of the potential H """ He1=phi return He1
def separateModuleAndAttribute(pathAttr): """ Return True of the specified python module, and attribute of the module exist. Parameters ---------- pathAttr : str Path to a python module followed by the desired attribute. e.g.: `/path/to/my/thing.py:MyClass` Notes ----- ...
def _eratosthenes(n): """Sieve of Eratosthenes An array of bits hi is used to mark primality, i.e. mark[i] is True if i+1 is prime Eratosthenes -- ancient Greek mathematician """ prime = [False] + [True] * (n-1) k = 2 while k * k <= n: if prime[k-1]: for i in range(k*k, n+1, k): prime[i-1] = False ...
def ProcessCodeFileHeaderLine(hl, cds_d, cd_fp): """Processes header line (str) from a .codes file output from MultiCodes Description: We make sure the variables for cds_d are ready to process another file. The colSums and colSumsUsed lists have another item added to them. Args: ...
def displayComplexMatrix(matrixToDisplay): """This method takes in a list of tuples representing a matrix and converts it into a string Arguments: matrixToDisplay {list} -- list containing all the elements of a matrix as object of class ComplexNumbers Returns: strOutput -- inpu...
def short_hex(x): """Return shorthand hexadecimal code, ex: cc3300 -> c30""" t = list(x) if t[0] == t[1] and t[2] == t[3] and t[4] == t[5]: return '%s%s%s' % (t[0], t[2], t[4]) else: return x
def any_none(*args): """Shorthand function for ``any(x is None for x in args)``. Returns True if any of `*args` are None, otherwise False.""" return any(x is None for x in args)
def clean_dalton_label(original_label: str) -> str: """Operator/integral labels in DALTON are in uppercase and may have spaces in them; replace spaces with underscores and make all letters lowercase. >>> clean_dalton_label("PSO 002") 'pso_002' """ return original_label.lower().replace(" ", ...
def prettyLength(l): """ takes in an average base pairs (float) and kicks out a string """ if not isinstance(l, float): raise RuntimeError('prettyLength is intended for floats, rewrite for %s' % l.__class__) if l > 10**6: return '%.2f Mb' % (l / float(10**6)) if l > 10**3: re...
def _RangesOverlap(range1, range2): """Checks whether two revision ranges overlap. Note, sharing an endpoint is considered overlap for this function. Args: range1: A pair of integers (start, end). range2: Another pair of integers. Returns: True if there is any overlap, False otherwise. """ if...