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 parameter dict Returns ------- dict """ from six import iteritems for k, v in iteritems(override): if k in target and isinstance(target[k], dict) and isinstance(override[k], dict): target[k] = merge(target=target[k], override=override[k]) else: target[k] = override[k] return target
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 doxygen config. Usage: result = replace_uppercase_letters(input) """ r = [] for c in filename: # l being: last character was not uppercase newc = c if c.isupper(): newc = '_' + c.lower() r.append(newc) return ''.join(r)
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_intervals = [] begin_add, end_add = interval_to_add merge_begin = None merge_end = None merging = False for interval in intervals: begin, end = interval # if prior to interval_to_add, then add to processed if end < begin_add: processed_intervals.append(interval) # if after interval_to_add, then add to processed elif begin > end_add: if merging: merging = False processed_intervals.append((merge_begin, merge_end)) processed_intervals.append(interval) # else end >= begin_add and begin <= end_add else: if merge_begin is None: merge_begin = begin_add if begin_add < begin else begin merge_end = end_add if end_add > end else end merging = True return processed_intervals
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"], "changes": descr["changes"] != {}, # whether there where any changes } return 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 abs((x-y)/y) < eps
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 return r, 1. - p
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] ] """ sorted_listing_scores = [[key, listing_scores[key]] for key in sorted(listing_scores, key=listing_scores.get, reverse=True)][:size_n] return sorted_listing_scores
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 = sorted_entities[i] next_ent = sorted_entities[i + 1] if (next_ent["start"] < curr_ent["end"] and next_ent["entity"] != curr_ent["entity"]): return True return False
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(ls[int(int(n) / 2 - 1):int(int(n) / 2 + 1)]) / 2.0
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: return texts_list diff = lengths - width for idx, text in reversed(list(enumerate(texts_list))): texts_list[idx] = texts_list[idx][:-diff] lengths = sum([len(x) for x in texts_list]) if lengths <= width: break diff = lengths - width return texts_list
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] if k1 in d[k2]: return False return True
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: return False return True
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-duping. """ return list(set(dishes).difference(set(appetizers)))
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 base. (Example: if base = 5, values will be rounded to the nearest multiple of 5 or 10.) Returns ------- rv : int rounded value. """ if direction.lower().startswith("u"): rv = value + (roundingBase - value % roundingBase) # round up to nearest base elif direction.lower().startswith("d"): rv = value - value % roundingBase # round down to nearest base else: rv = int(roundingBase * round(float(value) / roundingBase)) # round up or down to nearest base return rv
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: # # +-------+---------------------------+ # | ".. container ::" type | # +---+ | # | blocks | # +-------------------------------+ if blocks[i][b'type'] == b'paragraph' and blocks[i][b'lines'][ 0 ].startswith(b'.. container::'): indent = blocks[i][b'indent'] adjustment = blocks[i + 1][b'indent'] - indent containertype = blocks[i][b'lines'][0][15:] prune = True for c in keep: if c in containertype.split(b'.'): prune = False if prune: pruned.append(containertype) # Always delete "..container:: type" block del blocks[i] j = i i -= 1 while j < len(blocks) and blocks[j][b'indent'] > indent: if prune: del blocks[j] else: blocks[j][b'indent'] -= adjustment j += 1 i += 1 return blocks, pruned
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 element["keyphrases"]: if not generic_label: label = element["keyphrases"][candidate_span["keyphrase-id"]]["keyphrase-label"] else: label = "KEYPHRASE" return label
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"Supported orders are {x_scales}" ) return x_scale
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] parts = _path.split("/") if len(parts) == 1: return "/" rs = "/".join(parts[:len(parts) - _levels]) if rs == "": return "/" return rs
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: list of functions to apply to values """ if transformers is None or len(transformers) == 0: return sample result = list(sample) ntransformers = len(transformers) assert len(sample) >= ntransformers for i in range(len(sample)): f = transformers[i % ntransformers] if f is not None: result[i] = f(sample[i]) return result
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 return ret
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 ]*$", '', sentence.lower().replace("'", "")) whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ') return ''.join(filter(whitelist.__contains__, sentence)).lower()
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 bIsThisCertInThisList(oLeft, rightList) == False: #in right but not left #missingFromLeft.append(oLeft) for oRight in rightList: if oRight not in leftList: missingFromRight.append(oRight) continue #if bIsThisCertInThisList(oRight, leftList) == False: #in left but not in right #missingFromRight.append(oRight) result = {'MissingFromRight' : missingFromRight , 'MissingFromLeft' : missingFromLeft} return result
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 spaces. Any other input raises TypeError or ValueError. Return True if the argument is a valid ACN, otherwise False. >>> isacn('004 085 616') True >>> isacn('005 085 616') False """ if isinstance(obj, int): if not 0 <= obj < 10**9: raise ValueError('int out of range for an ACN') obj = '%09d' % obj assert len(obj) == 9 if not isinstance(obj, str): raise TypeError('expected a str or int but got %s' % type(obj)) obj = obj.replace(' ', '') if len(obj) != 9: raise ValueError('ACN must have exactly 9 digits') if not obj.isdigit(): raise ValueError('non-digit found in ACN') digits = [int(c) for c in obj] weights = [8, 7, 6, 5, 4, 3, 2, 1] assert len(digits) == 9 and len(weights) == 8 chksum = 10 - sum(d*w for d,w in zip(digits, weights)) % 10 if chksum == 10: chksum = 0 return chksum == digits[-1]
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_index = tweet_text.rfind(" ", start_index) return tweet_text[start_index:]
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 = divmod(time2, 3600) min, sec = divmod(min, 60) if day > 0: return "%d days %02dh:%02dm:%02ds" % (day, hour, min, sec) else: return "%02dh:%02dm:%02ds" % (hour, min, sec)
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 ' 'zero') raise ValueError(msg.format(value)) else: return value
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, 0xD7A3 + 1): # Range of Hangul characters as defined in UnicodeData.txt return True return False
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. >>> dic={'src_lang': 'de'} >>> setdefault_source_language(dic, None) 'de' >>> dic {'source_language': 'de'} >>> dic={'src_lang': 'de', 'source_language': 'en'} >>> setdefault_source_language(dic, None) Traceback (most recent call last): ... ValueError: Conflicting values for source_language ('en') and src_lang ('de')! """ res = [] has_other = False first = True for otherkey in ('source_language', 'src_lang'): if first: get = dic.get first = False else: get = dic.pop if otherkey in dic: res.append(get(otherkey)) if len(set(res)) == 1: dic['source_language'] = res[0] return res[0] elif not res: dic['source_language'] = default return default else: raise ValueError('Conflicting values for source_language (%r)' ' and src_lang (%r)!' % tuple(res))
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 order while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: ret.append(arr1[i]) i += 1 elif arr2[j] < arr1[i]: ret.append(arr2[j]) j += 1 else: # case where both elements are equal, order doesn't matter ret.append(arr1[i]) ret.append(arr2[j]) j += 1 i += 1 # append remainders while i < len(arr1): ret.append(arr1[i]) i += 1 while j < len(arr2): ret.append(arr2[j]) j += 1 return ret
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] \ = {}".format(test_mode, params["foo"])) # Print out the value of "miff", passed in below via the Python Operator print(" 'miff' was passed in via task params = {}".format(params["miff"])) return 1
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 token is separated by one or more delimeter characters in the origingal string, and quoted substrings are not split, This function returns a list of strings. Once the string is split Nmax times, any remaining text will be appended to the last entry of the list. Comments are stripped from the string before splitting begins. """ tokens = [] token = '' reading_token = True escaped_state = False quote_state = None for c in string: if (c in comment_char) and (not escaped_state) and (quote_state == None): if len(token) > 0: tokens.append(token) return tokens elif (c in delimiters) and (not escaped_state) and (quote_state == None): if reading_token: if (nmax == 0) or (len(tokens) < nmax-1): if len(token) > 0: tokens.append(token) token = '' reading_token = False else: token += c elif c in escape: if escaped_state: token += c reading_token = True escaped_state = False else: escaped_state = True # and leave c (the '\' character) out of token elif (c in quotes) and (not escaped_state): if (quote_state != None): if (c == quote_state): quote_state = None else: quote_state = c token += c reading_token = True else: if (c == 'n') and (escaped_state == True): c = '\n' elif (c == 't') and (escaped_state == True): c = '\t' elif (c == 'r') and (escaped_state == True): c = '\r' elif (c == 'f') and (escaped_state == True): c = '\f' token += c reading_token = True escaped_state = False if len(token) > 0: tokens.append(token) return tokens
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'] test2 = {"a" : "1", "b" : "2", "c" : 3} test3 = 'this is a test string' test4 = 12 test5 = 4.3 test6 = True my_return = '[COLOR dodgerblue]%s[/COLOR] : %s\n' % (test1, koding.Data_Type(test1)) my_return += '[COLOR dodgerblue]%s[/COLOR] : %s\n' % (test2, koding.Data_Type(test2)) my_return += '[COLOR dodgerblue]%s[/COLOR] : %s\n' % (test3, koding.Data_Type(test3)) my_return += '[COLOR dodgerblue]%s[/COLOR] : %s\n' % (test4, koding.Data_Type(test4)) my_return += '[COLOR dodgerblue]%s[/COLOR] : %s\n' % (test5, koding.Data_Type(test5)) my_return += '[COLOR dodgerblue]%s[/COLOR] : %s\n' % (test6, koding.Data_Type(test6)) koding.Text_Box('TEST RESULTS', my_return) ~""" data_type = type(data).__name__ return data_type
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 the power set takes exponential time. """ power_set = [set()] for x in S: for A in list(power_set): power_set.append(A.union({x})) partition = (S, set()) best = sum(S) for A in power_set: B = S.difference(A) val = max(sum(A), sum(B)) if val < best: partition = (A, B) best = val return partition
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 = amount_influence - 1 current_influence = current_influence + 1 return cost + (2*current_influence + amount_influence + 1)*amount_influence/2
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__.copy() # Need to be a copy to not get original class' attributes. # Remove all not necessaries values if attributes_to_delete: for x in attributes_to_delete: del dict_copy[x] return dict_copy
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 pairs
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 tuple([recursive_copy(it) for it in obj]) if isinstance(obj, dict): copy_obj = dict() for key in obj: copy_obj[key] = recursive_copy(obj[key]) return copy_obj return obj
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 (added, removed)
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) return rest
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.hex()) return code[:position]
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, 400), (700, 300), (600, 200)] """ leftx = centrex - halfwidth rightx = centrex + halfwidth pt0 = (leftx, centrey + radius) pt1 = (leftx - radius, centrey) pt2 = (leftx, centrey - radius) pt3 = (rightx, centrey + radius) pt4 = (rightx + radius, centrey) pt5 = (rightx, centrey - radius) return [pt0, pt1, pt2, pt3, pt4, pt5]
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 minutes/seconds. m, s = divmod(total, 60) # Calculate hours/minutes. h, m = divmod(m, 60) # Return an tuple. return (h, m, s)
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 = coordinates[0], coordinates[1], coordinates[2], coordinates[3] lat = ''.join(lat.split('.')) lat_ddm = lat[:2] + '.' + str(int(int(lat[2:]) / 60)) lat_dd = '{}'.format('-' + lat_ddm if lat_direction == 'S' else lat_ddm) lng_ddm = ''.join('{}'.format(lng[1:] if lng.startswith('0') else lng).split('.')) is_zero = lng_ddm[2:].startswith('0') lng_ddm = lng_ddm[:2] + '.' + (str(int(int(lng_ddm[2:]) / 60)) if not is_zero else ('0' + str(int(int(lng_ddm[2:]) / 60)))) lng_dd = '{}'.format('-' + lng_ddm if lng_direction == 'W' else lng_ddm) dd = {'Lat_dd': float(lat_dd), 'Lng_dd': float(lng_dd)} return dd
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])), Arg((0, typing.Any))), (typing.List[typing.Any], typing.Any), None, frozenset({0}), False))), (typing.List[typing.Any], typing.List[typing.Any]), None, frozenset({0}), False)), Arg((0, int)), Arg((1, typing.Any))), (typing.List[typing.Any], int, typing.Any), None, frozenset({0}), False)),), (typing.List[typing.Any],), typing.Any, frozenset({0}), False))), (typing.Any, typing.Any), bool, None, True)) #any_0 = lpop(linsert(lextend(any_list_0,lappend(any_list_1,any_0)),int_0,any_1)) >>> any_0 = Arg((0, typing.Any)) #lappend(any_list_1,any_0) >>> lappend = Fun(('lappend', 'list.append', (Arg((1, typing.List[typing.Any])), Arg((0, typing.Any))), (typing.List[typing.Any], typing.Any), None, frozenset({0}), False)) #lextend(any_list_0,lappend(any_list_1,any_0)) #case 3 >>> qfs1 = {} >>> v1 = 'x' >>> qfs2 = {} >>> v2 = 'x' >>> assert iimplies(v1, qfs1, v2, qfs2) #case 1 >>> qfs1 = {'x':0} >>> v1 = 'y' >>> qfs2 = {'x':0} >>> v2 = 'x' >>> assert iimplies(v1, qfs1, v2, qfs2) >>> assert qfs1 == {'x':0 , 'y':0} #case 0 >>> qfs1 = {'y':0} >>> v1 = 'y' >>> qfs2 = {'x':0} >>> v2 = 'x' >>> assert iimplies(v1, qfs1, v2, qfs2) >>> qfs1 = {'y':0} >>> v1 = 'y' >>> qfs2 = {'x':0} >>> v2 = 'x' >>> assert iimplies(v2, qfs2, v1, qfs1) """ if v2 in qfs2: if v1 in qfs1: #case 0 return qfs2[v2] == qfs1[v1] else: #case 1 qfs1[v1] = qfs2[v2] #set so that others will see it return True else: if v1 in qfs1: #case 2 #no need to set qfs because this is false, will stop the process return False else: #case 3 qfs1[v1] = qfs2[v2] = len(qfs1) + len(qfs2) #so that others will see it return True
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] otherwise """ if isinstance(item, (list, tuple)): return item else: return [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 [[word for word in sentence if len(word) > 0] for sentence in X]
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}f}}'.format(precision) if distance < 1000: return '{0:d}bp'.format(int(distance)) if distance < 1000000: fmt_string = formatting_string + 'kb' return fmt_string.format(float(distance) / 1000) fmt_string = formatting_string + 'Mb' return fmt_string.format(float(distance) / 1000000)
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, this is not so for Python's normal integer type: on a 32-bit machine, values of n >= 2^31 need to be expressed as python long integers or they will "look" negative and won't work. E.g. 0x80000000 needs to be passed in as 0x80000000, or it will be taken as -2147483648 instead of +2147483648. EXAMPLE: bitstring(10, 8) -> "01010000" """ if minlen < 1: raise ValueError("a bitstring must have at least 1 char") if n < 0: raise ValueError("bitstring representation undefined for neg numbers") result = "" while n > 0: if n & 1: result = result + "1" else: result = result + "0" n = n >> 1 if len(result) < minlen: result = result + "0" * (minlen - len(result)) return result
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: if path != paths[idx-1]: change[idx] = 1 return change
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 ----- The attribute of the module could be a class, function, variable, etc. Raises ------ ValueError: If there is no `:` separating the path and attr. """ # rindex gives last index. # The last is needed because the first colon index could be mapped drives in windows. lastColonIndex = pathAttr.rindex(":") # this raises a valueError # there should be at least 1 colon. 2 is possible due to mapped drives in windows. return (pathAttr[:lastColonIndex]), pathAttr[lastColonIndex + 1 :]
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 k += 1 return [i+1 for i, p in enumerate(prime) if p]
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: hl: (str) TSV Header line without new-line cd_fp: (str) Debugging cds_d: (dict) Codes dict counts: (d) rcbarcode to vector of counts indexes: list<str> vector of names of samples colSums: list<int> samples to total number of counts colSumsUsed: list<int> samples to total number of counts for used barcodes nSamples: (i) number of Samples so far (equivalent to number of codes files so far) nUsed: (i) number of Barcodes from .codes found in pool file nIgnore: (i) number of Barcodes from .codes not in pool file orig_cd_fp: (str) First codes fp in list [oneperfile]: (b) Only exists after first file parsed. If one index per file Returns: cds_d: (As above) thisIndex: (i)/None if oneperfile mode, which index name in (indexes) is this file? """ header_cols = hl.split('\t') first = header_cols[0] index_name = header_cols[1] if cds_d["nSamples"] == 0: # We are processing the first file cds_d["indexes"] = [index_name] cds_d["nSamples"] = 1 cds_d["colSums"] = [0] cds_d["colSumsUsed"] = [0] thisIndex = 0 else: # Indexes is a list of the 'indexes' from the first input codes file. # We make a dict of index value (str) -> location (0-based) within indexes list. oldcol = { cds_d["indexes"][i]:i for i in range(len(cds_d["indexes"]))} if index_name in oldcol: thisIndex = oldcol[index_name] else: cds_d["nSamples"] += 1 cds_d["indexes"].append(index_name) thisIndex = len(cds_d["indexes"]) - 1 cds_d["colSums"].append(0) cds_d["colSumsUsed"].append(0) ''' Deprecated multiplexing else: if not (len(cols) == len(cds_d["indexes"])): raise Exception("Expecting {} columns, but got {} columns in codes file {}".format( len(cds_d["indexes"]), len(cols), cd_fp)) for i in range(len(cols)): if not cols[i] == cds_d["indexes"][i]: raise Exception("Index mismatch in {} vs {} -- \n {} vs {}".format( cd_fp, cds_d["orig_cd_fp"], cols[i], cds_d["indexes"][i] )) ''' return [cds_d, thisIndex]
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 -- input matrix converted to a string """ strOutput = "" for i in range(len(matrixToDisplay)): for j in range(len(matrixToDisplay[0])): strOutput += (str(matrixToDisplay[i][j])).ljust(20) strOutput = strOutput + "\n" return strOutput
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: return '%.2f Kb' % (l / float(10**6)) return '%.2f' % l
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 not range1 or not range2: return False return range1[0] <= range2[1] and range1[1] >= range2[0]