content
stringlengths
42
6.51k
def swap_score(xs, ys): """Return the number of characters that needs to be substituted to change the characters in the first string into the second string. If the strings not of equal length, we will disregard all "extra" characters in the larger string. This function only considers the leftmost character of each string to correspond to each other. For example, if the two inputs are "word" and "weird", we'll only consider potential substitutions for "word" and "weir". """ return sum(x != y for x, y in zip(xs, ys))
def get_neighborhood_weights_edgesnumber(ns,edge_dict): """ :param ns: this is the candidate community set :param edge_dict: e.g. {node1: {node2: {weight: value1}, {node3: {weight: value2 }}}}, node1 and node2 is connected with edge-weight value1, node1 and node3 is connnected with edge-weight value2 :return: the neighbors dict (whose key is the node index and value is the number of neightbors in ns); Win (Wout) is the total edge-weight in (external) ns; number_in (number_out) is the total number of edges in (external) ns; """ neighborhood_dict = {} Win = 0 number_in = 0 Wout = 0 number_out = 0 for i in ns: neii = edge_dict[i] for j in neii: if j in ns: Win += float(neii[j]['weight']) number_in += 1 else: Wout += float(neii[j]['weight']) number_out += 1 if (j not in neighborhood_dict): neighborhood_dict[j] = 1 else: neighborhood_dict[j] = neighborhood_dict[j] + 1 Win /= 2 number_in /= 2 return neighborhood_dict,Win, number_in, Wout, number_out
def include_base_causx_tags(tags): """we want to include certain tags no matter what, so add them in here Args: tags (dict): any existing tags Returns: dict: any existing tags, and empty tags for the required tags that aren't present """ tags_dict={"FactorClass":"","Relevance":"","Normalizer":"","Units":"","DocID":""} tags_dict.update(tags) return tags_dict
def get_array_first(array): """ get array first :param array: :return: """ if array and isinstance(array, list) and len(array) >= 1: return array[0] return None
def vec_abs(a): """ Computes the element-wise absolute value of a vector Parameters ---------- a: list[] A vector of scalar values Returns ------- list[] The absolute vector of a """ # return [abs(a[n]) for n in range(len(a))] return [*map(lambda ai: abs(ai), a)]
def top_two_word(counts): """ Given a list of (word, count, percentage) tuples, return the top two word counts. """ limited_counts = counts[0:2] count_data = [count for (_, count, _) in limited_counts] return count_data
def _calculate_steps(num_examples, batch_size, num_epochs, warmup_proportion=0): """Calculates the number of steps. Args: num_examples: Number of examples in the dataset. batch_size: Batch size. num_epochs: How many times we should go through the dataset. warmup_proportion: Proportion of warmup steps. Returns: Tuple (number of steps, number of warmup steps). """ steps = int(num_examples / batch_size * num_epochs) warmup_steps = int(warmup_proportion * steps) return steps, warmup_steps
def enum_tri(n, t, start_high=None): """ Recursive enumeration of the values that are in the tri-range of 0. """ # resolve start-high for initial conditions: if start_high is None: if t % 2: # odd start_high = True else: start_high = False # trivial case (complexity pruning) if not t and not start_high: return [[0]*n] # sanity if t > 2*n - 1: return False if t < 0: return False # base case if n == 1: if t == 1: if start_high: return [[1]] # \ return False # cannot end high on last bit elif t == 0: if not start_high: return [[0]] # _ return False # cannot end high on last bit else: return False # this should never happen # recursive case if start_high: # case 1: stay straight c1 = enum_tri(n-1, t-2, True) # case 2: change (go down) c2 = enum_tri(n-1, t-1, False) else: # case 1: stay straight c1 = enum_tri(n-1, t, False) # case 2: change (go up) c2 = enum_tri(n-1, t-1, True) # assemble from our partials f1 = [] f2 = [] if c1: f1 = [[0] + x for x in c1 if x] if c2: f2 = [[1] + x for x in c2 if x] return f1 + f2
def merge_two_dicts(dict1, dict2): """ Merges two dictionaries into one :param dict1: First dictionary to merge :param dict2: Second dictionary to merge :return: Merged dictionary """ merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict
def int_to_hexstring(data, data_type='H', str_len=8): """ Takes an integer and creates a hex string of the appropriate length Args: data (int): value to hexlify data_type (int): one of the enumerated TAGTYPES str_len (int): number of characters in the resulting string Returns: hexstring of the data """ if data_type in ('B', 'b'): fmt1 = '{:0>2}' elif data_type in ('H', 'h'): fmt1 = '{:0>4}' elif data_type in ('I', 'i'): fmt1 = '{:0>8}' elif data_type in ('R'): fmt1 = '{:0>16}' else: fmt1 = "{:0>4}" fmt2 = '{:0<' + str(int(str_len)) + '}' hexstring = fmt2.format(fmt1.format(hex(data)[2:])) return hexstring
def n_max(ops, key_func): """ Return the maximum element of ops according to key_func. :param ops: operations to configure the WaveShaper :type ops: list :param key_func: comparison key :type key_func: str :return: maximum element :rtype: int """ maximum = 0 for i in range(len(ops)): if ops[i][key_func] > maximum: maximum = ops[i][key_func] return maximum
def break_words(stuff): """This function will break up words for us. """ words = stuff.split(' ') return words
def convert_to_dot_notation(class_name): """take a class name from ClassAnalysis and format it for comparison against typical dot package notation eg. Lcm/aptoide/pt/v8engine/OpenGLES20Activity; --> cm.aptoide.pt.v8engine.OpenGLES20Activity Note: I think this is necesssary because the get_activities/services/providers/receivers function return the 'dot notation' format of a component, whereas the decompile class names are like Lcm/atpoide/..etself.c. """ converted = class_name if converted[0] == 'L': converted = converted[1:] converted = converted.replace('/','.') if converted[-1] == ';': converted = converted[:-1] return converted
def custom_format(source, language, class_name, options, md, classes=None, value_id='', **kwargs): """Custom format.""" return '<div lang="%s" class_name="class-%s", option="%s">%s</div>' % (language, class_name, options['opt'], source)
def encode_int(s: int) -> bytes: """Encodes int to little endian bytes Args: s (int): int to encode Returns: bytes: encoded int in little endian by """ return s.to_bytes(4, 'little')
def xgcd(x, y): """Extended GCD Args: x (integer) y (integer) Returns: (gcd, x, y) where gcd is the greatest common divisor of a and b. The numbers x, y are such that gcd = ax + by. """ prev_a = 1 a = 0 prev_b = 0 b = 1 while y != 0: q = x // y temp = x % y x = y y = temp temp = a a = prev_a - q * a prev_a = temp temp = b b = prev_b - q * b prev_b = temp return [x, prev_a, prev_b]
def increment_name(_shortname): """ Increment the short name by 1. If you get, say, 'woman_detective_unqualified', it returns 'woman_detective_unqualified_1', and then 'woman_detective_unqualified_2', etc. """ last_char = _shortname[-1] if last_char.isdigit(): num = int(last_char) return _shortname[:-1] + str(num + 1) return _shortname + "_1"
def seqToGenbankLines(seq): """ chunk sequence string into lines each with six parts of 10bp, return as a list >>> seqToGenbankLines("aacacacatggtacacactgactagctagctacgatccagtacgatcgacgtagctatcgatcgatcgatcgactagcta") ['aacacacatg gtacacactg actagctagc tacgatccag tacgatcgac gtagctatcg', 'atcgatcgat cgactagcta'] """ # first chunk into 10bp parts parts = [seq[i:i+10] for i in range(0, len(seq), 10)] # put into lines of 6*10 bp lines = [] for i in range(0, len(parts), 6): lines.append(" ".join(parts[i:i+6])) return lines
def find_parents(childs): """ finds the parent of each BeautifulSoup-Element given in a list (childs). in case of multiple childs having the same parent, the index of the parent will be returned for each element after the first""" parents = [] for child in childs: b_found = False for parent in parents: foundParent = child.findParent() if foundParent == parent: parents.append(parents.index(parent)) b_found = True break if not b_found: parents.append(child.findParent()) return parents
def parse_port(arg): """Parse port argument and raise ValueError if invalid""" if not arg: return None arg = int(arg) if arg < 1 or arg > 65535: raise ValueError("invalid port value!") return arg
def edges(tt): """Edges of the fundamental polygon""" n = len(tt) e=[] for i in range(n-1): e += [(i,i+1)] e += [(n-1,0)] return e
def _encode_hmc_values(values): """Encrypts any necessary sensitive values for the HMC entry""" if values is not None: values = values.copy() #Make sure to Encrypt the Password before inserting the database ## del two lines by lixx #if values.get('password') is not None: # values['password'] = EncryptHandler().encode(values['password']) return values
def milliseconds_to_tc(milliseconds): """converts the given milliseconds to FFMpeg compatible timecode :param milliseconds: :return: """ hours = int(milliseconds / 3600000) residual_minutes = milliseconds - hours * 3600000 minutes = int(residual_minutes / 60000) residual_seconds = residual_minutes - minutes * 60000 seconds = int(residual_seconds / 1000) residual_milliseoncds = residual_seconds - seconds * 1000 milliseconds = int(residual_milliseoncds) return "%02i:%02i:%02i.%03i" % (hours,minutes,seconds,milliseconds)
def bytesToSigned24(bytearr): """ converts the last 3 bytes of a 5 byte array to a signed integer """ unsigned=(bytearr[2]<<16)+(bytearr[3]<<8)+bytearr[4] return unsigned-16777216 if bytearr[2]&128 else unsigned
def classname(instance): """ Returns instance class name. Parameters ---------- instance : object Returns ------- str """ return instance.__class__.__name__
def get_search_query_context(name, type, fields=None): """ Create search multi-field query object Params ------ name: str type: str fields: list Returns ------- list Notes ----- Some fields contain same text but are analyzed differently. Making other fields available for search will help boost search relevance """ if fields and name: temp = [name] for key, val in fields.items(): if key not in ['autocomplete', 'raw']: temp.append(name + "." + key) return temp return []
def _scan_pattern_for_literal(text, character=None, target=None): """returns the number of repeating <characters>, subtracting the # of '?' characters until <target> is hit""" count = 0 qcount = 0 for c in text: if c == "?": qcount = qcount + 1 if c == target: return count if c not in ("?", "*", character): return count - qcount count = count + 1 return count
def get_alt_sxy(x_sum: float, y_sum: float, xy_sum: float, n: int) -> float: """calculate sxy by given sum values""" return xy_sum - x_sum / n * y_sum - y_sum / n * x_sum + x_sum * y_sum / n
def fragmentate_dictionary(old_dictionary): """This splits dictionary entries like "FW": 0 into "F":0 and "W": 0. Args: old_dictionary (dict): a dictionary containing either hydrophobicity or size scores for amino acids Returns: dict: a less-readable but more computationally efficient dictionary, compared to the original one """ new_dictionary = {} for key, value in old_dictionary.items(): for character in key: new_dictionary[character] = value return new_dictionary
def median(list_in): """ Calculates the median of the data :param list_in: A list :return: float """ list_in.sort() half = int(len(list_in) / 2) if len(list_in) % 2 != 0: return float(list_in[half]) elif len(list_in) % 2 ==0: value = (list_in[half - 1] + list_in[half]) / 2 return float(value)
def solr_escape(text): """ Escape reserved characters for pysolr queries. https://lucene.apache.org/solr/guide/6_6/the-standard-query-parser.html#TheStandardQueryParser-EscapingSpecialCharacters https://docs.mychem.info/en/latest/doc/chem_query_service.html#escaping-reserved-characters """ import re reserved_chars = r'+ - = && || > < ! ( ) { } [ ] ^ " ~ * ? : \ /'.split() pattern = re.compile('|'.join(map(re.escape, reserved_chars))) return pattern.sub(repl= lambda m: f"\\{m.group()}", string=text)
def octetsToHex(octets): """ convert a string of octets to a string of hex digits """ result = '' while octets: byte = octets[0] octets = octets[1:] result += "%.2x" % ord(byte) return result
def eratosthenes_sieve(n): """Return primes <= n.""" def add_prime(k): """Add founded prime.""" primes.append(k) pos = k + k while pos <= n: numbers[pos] = 1 pos += k numbers = [0] * (n + 1) primes = [2] for i in range(3, n + 1, 2): if not numbers[i]: add_prime(i) return primes
def end_with(string, ending): """ Boolean return value if string has the same ending as another string. :param string: the string to be checked. :param ending: the ending string. :return: True if the last characters of string are the same as ending otherwise, False. """ return string.endswith(ending)
def is_irs2(readpatt): """Return True IFF `readpatt` is one of the IRS2 READPATTs. >>> is_irs2("NRSIRS2") True >>> is_irs2("NRSIRS2RAPID") True >>> is_irs2("NRSN32R8") False >>> is_irs2("ALLIRS2") True """ return 'IRS2' in readpatt
def map_age(age): """Map ages to standard buckets.""" try: age = int(age) if age >= 90: return '90+' lower = (age // 10) * 10 upper = age+9 if age % 10 == 0 else ((age + 9) // 10) * 10 - 1 return f'{lower}-{upper}' except: if 'month' in age.lower(): return '0-9' return age
def find_when_start(char=None,list=[]): """ find first element in list that start with a char >>> find_when_start('a',['abc','bcd','cde']) 'abc' >>> find_when_start(char='a',list=['abc','bcd','cde']) 'abc' >>> find_when_start() """ element = None try: for object in list: if char == object[0]: element = object break except Exception as e: element = None print(str(e)) return element
def prefix1bits(b): """ Count number of bits encountered before first 0 """ return 0 if b&1==0 else 1+prefix1bits(b>>1)
def decimal_to_roman(dec): """Convert decimal number to roman numerals. Args: dec (int): Decimal. Returns: str: Return roman numerals. """ to_roman = [('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)] roman_numerals = [] for numeral, value in to_roman: count = dec // value dec -= count * value roman_numerals.append(numeral * count) return ''.join(roman_numerals)
def get_pipe_dict(d, i): """ given a dictionary d for a given instrument, return the dictionary for the ith pipeline version """ pipe_versions = list(d.keys()) k = pipe_versions[i] mode = list(d[k].keys())[0] return d[k][mode]
def validate_license_model(license_model): """ Validate LicenseModel for DBInstance Property: DBInstance.LicenseModel """ VALID_LICENSE_MODELS = ( "license-included", "bring-your-own-license", "general-public-license", "postgresql-license", ) if license_model not in VALID_LICENSE_MODELS: raise ValueError( "DBInstance LicenseModel must be one of: %s" % ", ".join(VALID_LICENSE_MODELS) ) return license_model
def getitem_helper(obj, elem_getter, length, idx): """Helper function to implement a pythonic getitem function. Parameters ---------- obj: object The original object elem_getter : function A simple function that takes index and return a single element. length : int The size of the array idx : int or slice The argument passed to getitem Returns ------- result : object The result of getitem """ if isinstance(idx, slice): start = idx.start if idx.start is not None else 0 stop = idx.stop if idx.stop is not None else length step = idx.step if idx.step is not None else 1 if start < 0: start += length if stop < 0: stop += length return [elem_getter(obj, i) for i in range(start, stop, step)] if idx < -length or idx >= length: raise IndexError("Index out of range. size: {}, got index {}".format(length, idx)) if idx < 0: idx += length return elem_getter(obj, idx)
def getFileDialogTitle(msg, title): """ Create nicely-formatted string based on arguments msg and title :param msg: the msg to be displayed :param title: the window title :return: None """ if msg and title: return "%s - %s" % (title, msg) if msg and not title: return str(msg) if title and not msg: return str(title) return None
def merged_value(values1, values2): """ combines values of different devices: (right now since primitive generator takes only one value we use max value) try: #val1={'res': '13.6962k', 'l': '8u', 'w': '500n', 'm': '1'} #val2 = {'res': '13.6962k', 'l': '8u', 'w': '500n', 'm': '1'} #merged_value(val1,val2) Parameters ---------- values1 : TYPE. dict DESCRIPTION. dict of parametric values values2 : TYPE. dict DESCRIPTION.dict of parametric values Returns ------- merged_vals : TYPE dict DESCRIPTION. max of each parameter value """ if not values1: return values2 merged_vals={} if values1: for param,value in values1.items(): merged_vals[param] = value for param,value in values2.items(): if param in merged_vals.keys(): merged_vals[param] = max(value, merged_vals[param]) else: merged_vals[param] = value return merged_vals
def calculate_total (price, percent): """ Parameters ---------- price : TYPE float percent : TYPE integer Returns ------- New number showing the price + the tip Should return number as a FLOAT """ total = price + price*percent/100 return total
def _create_text_labels(classes, scores, class_names): """ Args: classes (list[int] or None): scores (list[float] or None): class_names (list[str] or None): Returns: list[str] or None """ labels = None if classes is not None and class_names is not None and len(class_names) > 1: labels = [class_names[i] for i in classes] if scores is not None: if labels is None: labels = ["{:.0f}%".format(s * 100) for s in scores] else: labels = ["{} {:.0f}%".format(l, s * 100) for l, s in zip(labels, scores)] return labels
def find(f, seq): """Return first item in sequence where f(item) == True.""" for item in seq: if f(item): return item
def binsearch(array, val): """ Binary search. The input `array` must be sorted. Binary search of `val` in `array`. Returns `idx` such as `val == array[idx]`, returns `None` otherwise. """ left, right = 0, len(array) while left <= right: mid = (left + right) // 2 if array[mid] < val: left = mid + 1 elif array[mid] > val: right = mid - 1 else: return mid return None
def parse_array(raw_array): """Parse a WMIC array.""" array_strip_brackets = raw_array.replace('{', '').replace('}', '') array_strip_spaces = array_strip_brackets.replace('"', '').replace(' ', '') return array_strip_spaces.split(',')
def calc_zeta_induced_quasisteady(E, x): """ Induced zeta potential (quasi-steady limit) """ zeta_induced_quasisteady = E*x return zeta_induced_quasisteady
def _get_upload_headers(first_byte, file_size, chunk_size): """Prepare the string for the POST request's headers.""" content_range = 'bytes ' + \ str(first_byte) + \ '-' + \ str(first_byte + chunk_size - 1) + \ '/' + \ str(file_size) return {'Content-Range': content_range}
def indexOf(list, predicate): """ Return the index of the first element that satisfies predicate. If no element is found, return -1 """ for i, x in enumerate(list): if predicate(x): return i return -1
def define_op_expr(left_expr, opr, right_expr): """Returns op expression""" obj = { "left": left_expr, "op": {"name": opr}, "right": right_expr, } return obj
def _get_verticalalignment(angle, location, side, is_vertical, is_flipped_x, is_flipped_y): """Return vertical alignment along the y axis. Parameters ---------- angle : {0, 90, -90} location : {'first', 'last', 'inner', 'outer'} side : {'first', 'last'} is_vertical : bool is_flipped_x : bool is_flipped_y : bool Returns {'baseline', 'top'} """ if is_vertical: if angle == 0: if is_flipped_y: return "top" else: return "baseline" elif angle == 90: if is_flipped_x: if (location == "last" or (side == "first" and location == "inner") or (side == "last" and location == "outer")): return "baseline" else: return "top" else: if (location == "first" or (side == "first" and location == "outer") or (side == "last" and location == "inner")): return "baseline" else: return "top" elif angle == -90: if is_flipped_x: if (location == "first" or (side == "first" and location == "outer") or (side == "last" and location == "inner")): return "baseline" else: return "top" else: if (location == "last" or (side == "first" and location == "inner") or (side == "last" and location == "outer")): return "baseline" else: return "top" else: if angle == 0: if is_flipped_y: if (location == "first" or (side == "first" and location == "outer") or (side == "last" and location == "inner")): return "baseline" else: return "top" else: if (location == "last" or (side == "first" and location == "inner") or (side == "last" and location == "outer")): return "baseline" else: return "top" elif angle == 90: if is_flipped_x: return "baseline" else: return "top" elif angle == -90: if is_flipped_x: return "top" else: return "baseline"
def parse_arxiv_url(url): """ examples is http://arxiv.org/abs/1512.08756v2 we want to extract the raw id and the version """ ix = url.rfind('/') idversion = url[ix+1:] # extract just the id (and the version) parts = idversion.split('v') assert len(parts) == 2, 'error parsing url ' + url return parts[0], int(parts[1])
def Dup(x, **unused_kwargs): """Duplicate (copy) the first element on the stack.""" if isinstance(x, list): return [x[0]] + x if isinstance(x, tuple): return tuple([x[0]] + list(x)) return [x, x]
def pascal(n): """ pascal: Method for computing the row in pascal's triangle that corresponds to the number of bits. This gives us the number of layers of the landscape and the number of mutants per row. Parameters ---------- n : int row of pascal's triangle to compute Returns ------- line : list of ints row n of pascal's triangle """ line = [1] for k in range(n): line.append(line[k]* (n-k) / (k+1)) return line
def get_media_edge_comment_string(media): """AB test (Issue 3712) alters the string for media edge, this resoves it""" options = ['edge_media_to_comment', 'edge_media_preview_comment'] for option in options: try: media[option] except KeyError: continue return option
def check_spg_settings(fs, window, nperseg, noverlap): """Check settings used for calculating spectrogram. Parameters ---------- fs : float Sampling rate, in Hz. window : str or tuple or array_like Desired window to use. See scipy.signal.get_window for a list of available windows. If array_like, the array will be used as the window and its length must be nperseg. nperseg : int or None Length of each segment, in number of samples. noverlap : int or None Number of points to overlap between segments. Returns ------- nperseg : int Length of each segment, in number of samples. noverlap : int Number of points to overlap between segments. """ # Set the nperseg, if not provided if nperseg is None: # If the window is a string or tuple, defaults to 1 second of data if isinstance(window, (str, tuple)): nperseg = int(fs) # If the window is an array, defaults to window length else: nperseg = len(window) else: nperseg = int(nperseg) if noverlap is not None: noverlap = int(noverlap) return nperseg, noverlap
def is_valid_ip_addr(ip_addr): """Validates given string as IPv4 address for given string. Args: ip_addr (str): string to validate as IPv4 address. Returns: bool: True if string is valid IPv4 address, else False. """ ip_addr_split = ip_addr.split('.') if len(ip_addr_split) != 4: return False for ip_addr_octet in ip_addr_split: if not ip_addr_octet.isdigit(): return False ip_addr_octet_int = int(ip_addr_octet) if ip_addr_octet_int < 0 or ip_addr_octet_int > 255: return False return True
def reformat_conversation_context(context): """ Reformat context for conversation related commands (from having used string_to_context_key) to desired output format. parameter: (dict) context The context to reformat returns: The reformatted context """ to_emails = context.get('ToEmails') body = context.get('Body') attachments = context.get('Attachments') if to_emails: context['ToEmail'] = to_emails del context['ToEmails'] if body: context['BodyHTML'] = body del context['Body'] if attachments: del context['Attachments'] return context
def max_common_prefix(a): """ Given a list of strings (or other sliceable sequences), returns the longest common prefix :param a: list-like of strings :return: the smallest common prefix of all strings in a """ if not a: return '' # Note: Try to optimize by using a min_max function to give me both in one pass. The current version is still faster s1 = min(a) s2 = max(a) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
def add_res(acc, elem): """ Adds results to the accumulator :param acc: :param elem: :return: """ if not isinstance(elem, list): elem = [elem] if acc is None: acc = [] for x in elem: acc.append(x) return acc
def fibonacci_recursive(n): """Recursive implementation of the fibonacci function time: (2^n) more precisely O((1+sqrt(5))/2)^n) space: O(n) note that one recursive is fully resolved before the other begins """ if n < 2: return n return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
def key_description(character): """generate a readable description for a key""" ascii_code = ord(character) if ascii_code < 32: return 'Ctrl+{:c}'.format(ord('@') + ascii_code) else: return repr(character)
def isPal(x): """ >>> isPal(['a', 'b']) ['a', 'b'] ['a', 'b'] ['b', 'a'] ['a', 'b'] False >>> isPal(['a', 'b', 'a']) ['a', 'b', 'a'] ['a', 'b', 'a'] ['a', 'b', 'a'] ['a', 'b', 'a'] True """ assert type(x) == list, 'not a list' # assert to make sure x is a list tmp = x[:] # make a copy instead of referencing to the whole object print(tmp, x) # print before reversing tmp.reverse() print(tmp, x) # print after reversing if tmp == x: return True else: return False
def save_eval(val): """Evaluate variables, assuming they are str representations of e.g. int-types. Args: val (any): Value that shall be evaluated. Returns: res (any): Evaluated version of value if built-in `eval` was successful, otherwise `val`. """ try: res = eval(val) except TypeError: # val is not str-type, so return res = val except NameError: # val is str-type, but not the name of a variable, so return res = val except SyntaxError: # val is str-type, but does not just contain a representation, so return res = val return res
def route_fitness(r, c, length_fun, **kwargs): """ fitness of a route """ black_list = kwargs.get("black_list") return 1 / length_fun(r, c, black_list)
def get_span_string(run0, run1, runs=None): """Returns string of run0-run1, (or run0 if run0 == run1) """ if runs is not None: string = '' for run in runs: string += f'{run},' return string elif run0 == run1: return f'{run0}' else: return f'{run0}-{run1}'
def space_name(prefix, index): """Construct name of space from the prefix and its index.""" return "{p}{i}".format(p=prefix, i=index)
def build_default_endpoint_prefixes(records_rest_endpoints): """Build the default_endpoint_prefixes map.""" pid_types = set() guessed = set() endpoint_prefixes = {} for key, endpoint in records_rest_endpoints.items(): pid_type = endpoint['pid_type'] pid_types.add(pid_type) is_guessed = key == pid_type is_default = endpoint.get('default_endpoint_prefix', False) if is_default: if pid_type in endpoint_prefixes and pid_type not in guessed: raise ValueError('More than one "{0}" defined.'.format( pid_type )) endpoint_prefixes[pid_type] = key guessed -= {pid_type} elif is_guessed and pid_type not in endpoint_prefixes: endpoint_prefixes[pid_type] = key guessed |= {pid_type} not_found = pid_types - set(endpoint_prefixes.keys()) if not_found: raise ValueError('No endpoint-prefix for {0}.'.format( ', '.join(not_found) )) return endpoint_prefixes
def major_formatter(x, pos): """Return formatted value with 2 decimal places.""" return "[%.2f]" % x
def querify(query): """Return `query` as list""" if ' ' in query: queries = query.split(' ') else: queries = [query] return queries
def dewPointToRH(t_dry, t_dew): """ Calculate relative humidity from dry bulb and dew point (in degrees Celsius) :param float t_dry: Dry bulb temperature (degrees Celsius). :param float t_dew: Dew point temperature (degrees Celsius). :returns: Relative humidity (%) :rtype: float """ vap_t_dry = 6.11 * (10 ** ((7.5 * t_dry) / (237.3 + t_dry))) vap_t_dew = 6.11 * (10 ** ((7.5 * t_dew) / (237.3 + t_dew))) rh = (vap_t_dew / vap_t_dry) * 100. # Any out of bounds value is converted to an undefined value if (rh > 100 or rh < 0): rh = None return rh
def clamp_angle(angle, min_val, max_val): """clamp angle to pi, -pi range""" if angle < -360: angle += 360 if angle > 360: angle -= 360 clamp = max(min(angle, max_val), min_val) return clamp
def _tabulate(rows, headers, spacing=5): """Prepare simple table with spacing based on content""" if len(rows) == 0: return "None\n" assert len(rows[0]) == len(headers) count = len(rows[0]) widths = [0 for _ in range(count)] rows = [headers] + rows for row in rows: for index, field in enumerate(row): if len(str(field)) > widths[index]: widths[index] = len(str(field)) output = "" for row in rows: for index, field in enumerate(row): field = str(field) output += field + (widths[index] - len(field) + spacing) * " " output += "\n" return output
def get_spatial_cell_id(dataset_uuid:str, tile_id:str, mask_index:int)->str: """Takes a dataset uuid, a tile_id within that dataset, and a mask_index number within that tile to prodduce a unique cell ID""" return "-".join([dataset_uuid, tile_id, str(mask_index)])
def check_value_above_filter(value, threshold): """ Returns a boolean to indicate value at or above threshold. :param value: integer from a column "*read count". :param threshold: threshold for the filtering of these read counts. :return: boolean whether integer is equal or greater than threshold. """ return int(value) >= threshold
def Rs(ca, cb, n1, n2): """ Refraction coefficient Neglects absorption. Parameters ---------- ca: cos alpha cb: cos beta n1: refective index of medium 1 n2: refrective index of medium 2 Returns ------- Reflection coefficient """ return ((n1*ca - n2*cb)/(n1*ca + n2*cb))**2
def has_wav(wav_names, wav_prefix): """True if WAV file with prefix already exists.""" for wav_name in wav_names: if wav_name.startswith(wav_prefix): return True return False
def get_key(data, keyfields): """Return a tuple of key with the data and keyfields indexes passed""" return tuple([data[i-1] for i in map(int, keyfields.split(','))])
def message_to_str(message): """ Convert message to string """ # body may be bytes if isinstance(message["request"]["body"], bytes): message["request"]["body"] = message["request"]["body"].decode() return message
def intersection(l1, l2): """Return intersection of two lists as a new list:: >>> intersection([1, 2, 3], [2, 3, 4]) [2, 3] >>> intersection([1, 2, 3], [1, 2, 3, 4]) [1, 2, 3] >>> intersection([1, 2, 3], [3, 4]) [3] >>> intersection([1, 2, 3], [4, 5, 6]) [] """ return [num for num in l1 if num in l2]
def get_dict_item(from_this, get_this): """ get dic object item """ if not from_this: return None item = from_this if isinstance(get_this, str): if get_this in from_this: item = from_this[get_this] else: item = None else: for key in get_this: if isinstance(item, dict) and key in item: item = item[key] else: return None return item
def topLeftToCenter(pointXY, screenXY, flipY=False): """ Takes a coordinate given in topLeft reference frame and transforms it to center-based coordiantes. Switches from (0,0) as top left to (0,0) as center Parameters ---------- pointXY : tuple The topLeft coordinate which is to be transformed screenXY : tuple, ints The (x,y) dimensions of the grid or screen flipY : Bool If True, flips the y coordinates Returns ------- newPos : tuple The (x,y) position in center-based coordinates Examples -------- >>> newPos = topLeftToCenter((100,100), (1920,1080), False) >>> newPos (-860.0, 440.0) """ newX = pointXY[0] - (screenXY[0] / 2.0) newY = (screenXY[1] / 2.0) - pointXY[1] if flipY: newY *= -1 return newX, newY
def _must_decode(value): """Copied from pkginfo 1.4.1, _compat module.""" if type(value) is bytes: try: return value.decode('utf-8') except UnicodeDecodeError: return value.decode('latin1') return value
def flatten_list(list_of_lists): """Flatten a nested list of values. Args: list_of_lists (list): A nested list, example: ['a', ['b', 'c']] Returns: flat_list (list): A flattened list, example: ['a', 'b', 'c'] """ flat_list = [] for i in list_of_lists: if isinstance(i, list): flat_list.extend(flatten_list(i)) else: flat_list.append(i) return flat_list
def cross_product(vec1, vec2): """Cross product of two 2d vectors is a vector perpendicular to both these vectors. Return value is a scalar representing the magnitude and direction(towards positive/negative z-axis) of the cross product. """ (px1, py1), (px2, py2) = vec1, vec2 return px1 * py2 - px2 * py1
def _delElement(an_iterable, idx): """ :param iterable an_iterable: :param int idx: :return list: list without element idx """ a_list = list(an_iterable) new_list = a_list[0:idx] back_list = a_list[(idx+1):] new_list.extend(back_list) return new_list
def IsPng(png_data): """Determines whether a sequence of bytes is a PNG.""" return png_data.startswith('\x89PNG\r\n\x1a\n')
def get_item(dictionary, key): """ Return a key value from a dictionary object. **Parameters** ``dictonary`` Python dictionary object to parse ``key`` Key name tor etrieve from the dictionary """ # Use `get` to return `None` if not found return dictionary.get(key)
def disjoint(L1, L2): """returns non-zero if L1 and L2 have no common elements""" used = dict([(k, None) for k in L1]) for k in L2: if k in used: return 0 return 1
def ids_filter(doc_ids): """Create a filter for documents with the given ids. Parameters ---------- doc_id : |list| of |ObjectIds| The document ids to match. Returns ------- dict A query for documents matching the given `doc_ids`. """ return {'_id': {'$in': doc_ids}}
def fix_characters(cadena): """ Replaces unicode characters and encodes the string in utf-8 """ d = { '\xc1':'A', '\xc9':'E', '\xcd':'I', '\xda':'U', '\xdc':'U', '\xd1':'N', '\xc7':'C', '\xed':'i', '\xf3':'o', '\xf1':'n', '\xe7':'c', '\xba':'', '\xb0':'', '\x3a':'', '\xe1':'a', '\xe2':'a', '\xe3':'a', '\xe4':'a', '\xe5':'a', '\xe8':'e', '\xe9':'e', '\xea':'e', '\xeb':'e', '\xec':'i', '\xed':'i', '\xee':'i', '\xef':'i', '\xf2':'o', '\xf3':'o', '\xf4':'o', '\xf5':'o', '\xf0':'o', '\xf9':'u', '\xfa':'u', '\xfb':'u', '\xfc':'u', '\xe5':'a' } nueva_cadena = cadena for c in d.keys(): nueva_cadena = nueva_cadena.replace(c,d[c]) auxiliar = nueva_cadena.encode('utf-8') return nueva_cadena
def card_average(hand): """ :param hand: list - cards in hand. :return: float - average value of the cards in the hand. """ return sum(hand) / len(hand)
def replace_keys(my_dict, transform_key): """ Filter through our datastructure """ # # The idea here is to transform key values and list items # for key in my_dict.keys(): new_key = transform_key(key) if new_key != key: my_dict[new_key] = my_dict.pop(key) key = new_key if isinstance(my_dict[key], dict): replace_keys(my_dict[key], transform_key) elif isinstance(my_dict[key], list): my_dict[key] = [transform_key(x) for x in my_dict[key]] return my_dict
def experiment_key(study_id=None, experiment_id=None, fly_id=None, obj=None): """Exhibit A why duck typing is just shit sometimes""" if obj: return f"{obj.study_id}-{obj.experiment_id}-{obj.fly_id}" else: return f"{study_id}-{experiment_id}-{fly_id}"
def polygonAppendCheck(currentVL, nextVL): """Given two polygon vertex lists, append them if needed. Polygons will always have the last coordinate be the same as the first coordinate. When appending, they may, or may not, have the last coordinate of the first vertex list be the same as the first coordinate of the second vertex list. When appending, we need to eliminate one of these coordinates if present. Args: currentVL (list): First of two lists of vertexes to check. nextVL (list): Second of two lists of vertexes to check. Returns: tuple: Tuple: 1. ``True`` if the vertexes were appended, otherwise ``False``. 2. New vertex list if appended (otherwise ignored). """ wasAppended = False appendedList = [] # In a polygon, the polygon always connects to the origin. However, there # may be two different altitude levels present. currentStart = currentVL[0] polyIsComplete = False for x in currentVL[1:]: if (x[0] == currentStart[0]) and (x[1] == currentStart[1]) \ and (x[2] == currentStart[2]): polyIsComplete = True elif polyIsComplete: # Polygon probably starting new altitude currentStart = x polyIsComplete = False if not polyIsComplete: wasAppended = True # In SOME cases, multi-record polygons act like # polylines and duplicate the last point. last = currentVL[-1] first = nextVL[0] if (last[0] == first[0]) and (last[1] == first[1]) and (last[2] == first[2]): # skip duplicate element appendedList = currentVL[:-1] + nextVL else: appendedList = currentVL + nextVL return (wasAppended, appendedList)
def jacobi_symbol(n, k): """Compute the Jacobi symbol of n modulo k See http://en.wikipedia.org/wiki/Jacobi_symbol For our application k is always prime, so this is the same as the Legendre symbol.""" assert k > 0 and k & 1, "jacobi symbol is only defined for positive odd k" n %= k t = 0 while n != 0: while n & 1 == 0: n >>= 1 r = k & 7 t ^= (r == 3 or r == 5) n, k = k, n t ^= (n & k & 3 == 3) n = n % k if k == 1: return -1 if t else 1 return 0
def leading_spaces_count(line): """ (Used by tab-to-spaces converter code, for example.) """ i, n = 0, len(line) while i < n and line[i] == " ": i += 1 return i