content
stringlengths
42
6.51k
def fb_lookup(dic, keys, default): """Do dict-lookup for multiple key, returning the first hit. """ for key in keys: if key in dic: return dic[key] else: return default
def intable(s): """Check if a string can be converted to an int""" try: int(s) return True except ValueError: return False
def isFloat(value): """Returns True if convertible to float""" try: float(value) return True except (ValueError, TypeError): return False
def bytes_to_num(data): """ *data* must be at least 4 bytes long, big-endian order. """ assert len(data) >= 4 num = data[3] num += ((data[2] << 8) & 0xff00) num += ((data[1] << 16) & 0xff0000) num += ((data[0] << 24) & 0xff000000) return num
def maybe_append_new_line(code): """ Append new line if code snippet is a Python code snippet """ lines = code.split("\n") if lines[0] in ["py", "python"]: # add new line before last line being ``` last_line = lines[-1] lines.pop() lines.append("\n" + last_line) return "\n".join(lines)
def update_corpus_statistics(cs, ds): """ Updates corpus-level statistics (cs) using document-level statistics (ds). """ cs['tna'] += ds['rna'] cs['tnc'] += ds['rnc'] cs['tnb'] += ds['rnb'] if ds['mnc'] > cs['mnc']: cs['la'] = ds['la'] cs['mnc'] = max(cs['mnc'], ds['mnc']) cs['mnb'] = max(cs['mnb'], ds['mnb']) return cs
def format_mobileconfig_fix(mobileconfig): """Takes a list of domains and setting from a mobileconfig, and reformats it for the output of the fix section of the guide. """ rulefix = "" for domain, settings in mobileconfig.items(): if domain == "com.apple.ManagedClient.preferences": rulefix = rulefix + (f"NOTE: The following settings are in the ({domain}) payload. This payload requires the additional settings to be sub-payloads within, containing their their defined payload types.\n\n") rulefix = rulefix + format_mobileconfig_fix(settings) else: rulefix = rulefix + ( f"Create a configuration profile containing the following keys in the ({domain}) payload type:\n\n") rulefix = rulefix + "[source,xml]\n----\n" for item in settings.items(): rulefix = rulefix + (f"<key>{item[0]}</key>\n") if type(item[1]) == bool: rulefix = rulefix + \ (f"<{str(item[1]).lower()}/>\n") elif type(item[1]) == list: rulefix = rulefix + "<array>\n" for setting in item[1]: rulefix = rulefix + \ (f" <string>{setting}</string>\n") rulefix = rulefix + "</array>\n" elif type(item[1]) == int: rulefix = rulefix + \ (f"<integer>{item[1]}</integer>\n") elif type(item[1]) == str: rulefix = rulefix + \ (f"<string>{item[1]}</string>\n") rulefix = rulefix + "----\n\n" return rulefix
def split_privacy_between_eigenvalues_and_vectors_uniformly(n, d, epsilon): """Split privacy budget between eigenvalues and eigenvectors equally.""" print("Ignoring parameters in budget splitting n:%d d:%d" % (n, d)) return (epsilon / 2.0, epsilon / 2.0)
def _find(node, data): """Return the node containing data, or else None.""" if not node or node.data == data: return node else: return (_find(node.left, data) if (data < node.data) else _find(node.right, data))
def dict_deep_update(target, update): """Recursively update a dict. Subdict's won't be overwritten but also updated. Args: target: Target dictionary to update. update: Parameters to update. Returns: dict: Updated dictionary. """ for key, value in update.items(): if key not in target: target[key] = value elif isinstance(value, dict): target[key] = dict_deep_update(value, target[key]) return target
def goto_definition( obj, command_template='open -na "PyCharm.app" --args --line {lineno} "{filepath}"' ): """Opens the definition of the object in the file it was defined at the line it was defined. The default is set to use pycharm to open the file on a mac. To customize for your system/file_viewer, just use `functools.partial` to fix the `command_template` for your case. For pycharm on other systems, see: https://www.jetbrains.com/help/pycharm/opening-files-from-command-line.html For vi, see: https://www.cyberciti.biz/faq/linux-unix-command-open-file-linenumber-function/ Etc. """ import inspect, os try: filepath = inspect.getfile(obj) _, lineno = inspect.findsource(obj) command = command_template.format(filepath=filepath, lineno=lineno) os.system(command) # would prefer to use subprocess, but something I'm missing ## Not working with subprocess.run # import subprocess # print(command) # return subprocess.run(command.split(' ')) except TypeError: if hasattr(obj, 'func'): return goto_definition(obj.func, command_template) else: raise
def can_check_isinstance(specified_type): """Checks that specified_type can be the second arg to isinstance without raising an exception.""" try: isinstance(5, specified_type) except TypeError: return False return True
def area(pts,absolute=False): """ Computes the clockwise area of the polygon defined by the points. Args: pts: list of (x,y) tuples. Assumes last and first vertex are different. Cannot handle if input points contain None coordinates. absolute: if true, returns the absolute value Returns: float representing the area """ if pts[len(pts)-1] != pts[0]: pts.append(pts[0]) a=[(pts[i+1][0]-pts[i][0])*(pts[i][1]+pts[i+1][1]) for i in range(len(pts)-1)] A=sum(a)/2 if absolute: return abs(A) else: return A
def visiblename(name): """ Checks whether a given name should be documented/displayed by ignoring builtin ones. """ return not (name.startswith('__') and name.endswith('__'))
def random(maximum: int=0, score: str='silvathor_RANDOM'): """ Return a random integer in range [0, maximum[. :param maximum: The maximum value of the random number (excluded). :param score: The name of the Minecraft score for the random number. :return: A random number. """ score.lower().replace(' ', '_') return '\n'.join([ f'scoreboard objectives add {score} dummy', f'scoreboard players set maximum {score} {maximum}', f'summon area_effect_cloud ~ ~ ~ {{Tags:["{score}_aec"],Age:1}}', f'execute store result score @s {score} run data get entity @e[type=area_effect_cloud,tag={score}_aec,limit=1] UUID[0]', f'scoreboard players operation @s {score} %= maximum {score}', ])
def ask_user(a, b): # preliminary """get answer from user: a*b = ?""" print('{:d}*{:d} = '.format(a, b)) return a*b
def interval(fermentername, seconds): """ gives back intervall as tuppel @return: (weeks, days, hours, minutes, seconds) formats string for line 2 returns the formatted string for line 2 of fermenter multiview """ WEEK = 60 * 60 * 24 * 7 DAY = 60 * 60 * 24 HOUR = 60 * 60 MINUTE = 60 weeks = seconds // WEEK seconds = seconds % WEEK days = seconds // DAY seconds = seconds % DAY hours = seconds // HOUR seconds = seconds % HOUR minutes = seconds // MINUTE seconds = seconds % MINUTE if weeks >= 1: remaining_time = (u"W%d D%d %02d:%02d" % (int(weeks), int(days), int(hours), int(minutes))) return (u"%s %s" % (fermentername.ljust(8)[:7], remaining_time))[:20] elif weeks == 0 and days >= 1: remaining_time = (u"D%d %02d:%02d:%02d" % (int(days), int(hours), int(minutes), int(seconds))) return (u"%s %s" % (fermentername.ljust(8)[:7], remaining_time))[:20] elif weeks == 0 and days == 0: remaining_time = (u"%02d:%02d:%02d" % (int(hours), int(minutes), int(seconds))) return (u"%s %s" % (fermentername.ljust(11)[:10], remaining_time))[:20] else: pass pass
def nvl(value, defval="Unknown"): """ Provide a default value for empty/NULL/None. Parameters ---------- value: obj The value to verify. defval: obj The value to return if the provide value is None or empty. Returns ------- defval if value is None or empty, otherwise return value """ if value is None: return defval if not value: return defval return value
def url_from_user_input(url): """Return a normalized URL from user input. Take a URL from user input (eg. a URL input field or path parameter) and convert it to a normalized form. """ url = url.strip() if not url: return url if not (url.startswith("http://") or url.startswith("https://")): url = "https://" + url return url
def decodeString(s): """ "((A2B)2)2G2" -> 'AABAABAABAABGG' """ stack = [] digit = 0 for c in s: if c.isdigit(): digit = 10*digit + int(c) continue if digit != 0: stack[-1] = stack[-1]*digit digit = 0 if c == ')': curString = "" while stack[-1] != '(': curString = stack.pop() + curString stack[-1] = curString elif c == '(': stack.append(c) else: stack.append(c) if digit != 0: stack[-1] = stack[-1]*digit return "".join(stack)
def volume_pyramid(area_dasar: float, tinggi: float) -> float: """ kalkulasi dari volume pyramid referensi https://en.wikipedia.org/wiki/Pyramid_(geometry) >>> volume_pyramid(10, 3) 10.0 >>> volume_pyramid(1.5, 3) 1.5 """ return area_dasar * tinggi / 3.0
def _rev_bits(bits, l=32): """ Reverse bits """ rev = 0 for i in range(l): if bits & (1 << i) != 0: rev |= 1 << (l-i - 1) return rev
def GetFlagFromDest(dest): """Returns a conventional flag name given a dest name.""" return '--' + dest.replace('_', '-')
def validate_entangler_map(entangler_map, num_qubits, allow_double_entanglement=False): """Validates a user supplied entangler map and converts entries to ints Args: entangler_map (dict) : An entangler map, keys are source qubit index (int), value is array of target qubit index(es) (int) num_qubits (int) : Number of qubits allow_double_entanglement: If we allow in list x entangled to y and vice-versa or not Returns: Validated/converted map """ if not isinstance(entangler_map, dict): raise TypeError('Entangler map type dictionary expected') for k, v in entangler_map.items(): if not isinstance(v, list): raise TypeError('Entangle index list expected but got {}'.format(type(v))) ret_map = {} for k, v in entangler_map.items(): ret_map[int(k)] = [int(x) for x in v] for k, v in ret_map.items(): if k < 0 or k >= num_qubits: raise ValueError('Qubit value {} invalid for {} qubits'.format(k, num_qubits)) for i in v: if i < 0 or i >= num_qubits: raise ValueError('Qubit entangle target value {} invalid for {} qubits'.format(i, num_qubits)) if allow_double_entanglement is False and i in ret_map and k in ret_map[i]: raise ValueError('Qubit {} and {} cross-listed'.format(i, k)) return ret_map
def asShortCode(epsg): """ convert EPSG code to short CRS ``EPSG:<code>`` notation """ return "EPSG:%d" % int(epsg)
def batch_size_per_device(batch_size: int, num_devices: int): """Return the batch size per device.""" per_device_batch_size, ragged = divmod(batch_size, num_devices) if ragged: msg = 'batch size must be divisible by num devices, got {} and {}.' raise ValueError(msg.format(per_device_batch_size, num_devices)) return per_device_batch_size
def _check_dict_format(_dict): """[Checks if the _dict are in the expected format for conversion] Returns: [bool]: [is ok] """ for key in _dict.keys(): if not set(_dict[key].keys()) == {"type", "dict"}: print("Dict should only have type and dict as dict elements.") return False if not isinstance(_dict[key]["type"], str): print("type should be a string. e.g. geometry_msgs/PoseStamped") return False if not isinstance(_dict[key]["dict"], dict): print("dict should be a dict with message data") return False return True
def _merge(iterable1, iterable2): """ Merge two slices into a single ordered one. Complexity: O(n), Where n = len(iterable1) + len(iterable2) :param iterable1: :param iterable2: :return: """ if not iterable1: return iterable2 if not iterable2: return iterable1 # Now, we iterate both. Since each iterable is already ordered # We only need to compare each position and append in the correct order n1 = len(iterable1) n2 = len(iterable2) # Pre-allocate the list to be less expensive than appending result = [0] * (n1 + n2) i1 = i2 = 0 for i in range(n1 + n2): if i1 >= n1: result[i] = iterable2[i2] i2 += 1 continue elif i2 >= n2: result[i] = iterable1[i1] i1 += 1 continue if i2 >= n2 or iterable1[i1] <= iterable2[i2]: result[i] = iterable1[i1] i1 += 1 else: result[i] = iterable2[i2] i2 += 1 return result
def writeb(path, data): """Write data to a binary file. Args: path (str): Full path to file data (str): File bytes Returns: int: Number of bytes written """ with open(path, 'wb') as handle: return handle.write(data)
def identify(_line): """backend detection (simplified)""" _ident = "unknown" if "Joomla" in _line: _ident = "Joomla CMS" if "wp-content" in _line: _ident = "WordPress CMS" if 'content="Drupal"' in _line: _ident = "Drupal CMS" return _ident
def fib(n): """ Functional definition of Fibonacci numbers """ if n == 0 or n == 1: return n else: return fib(n - 1) + fib(n - 2)
def reflexive_closure_function(rel, universe): """ Function to return the reflexive closure of a relation on a set :param rel: A list that is a relation on set universe :param universe: A list that represents a set :return: A list that is the relexive closure of the relation rel on the set universe """ return rel + [(x, x) for x in universe if (x, x) not in rel]
def product(pmt1, pmt2): """ the product of two permutations """ nelem = len(pmt1) assert sorted(pmt1) == sorted(pmt2) == list(range(nelem)) prod = tuple(pmt2[i] for i in pmt1) return prod
def allCharacters(word): """[Function look over the word looking for all character contained in it ] Args: word ([String]): [Word from which we want to exclude the characters ] Returns: [String]: [All characters contained in the word, in form of String] """ charactersInWord = [] for char in word: if char in charactersInWord: pass else: charactersInWord.append(char) return ''.join(charactersInWord)
def ParseGitInfoOutput(output): """Given a git log, determine the latest corresponding svn revision.""" for line in output.split('\n'): tokens = line.split() if len(tokens) > 0 and tokens[0] == 'git-svn-id:': return tokens[1].split('@')[1] return None
def nExpPrioritize(nexp, base=20, award=2e6, penalty=-100): """adjust field priorities based on planned exps 1 exp: negative, 8 exp: super high """ assert nexp < 9 and nexp > 0, "invalid nexp" if nexp == 1: return penalty elif nexp == 8: return award elif nexp == 2: return 0 else: return nexp * base
def merge_dictionaries(row_data, default): """Merge d2 into d1, where d1 has priority for all values of d2 merge them into d1. If a value exists in d1 and in d2 keep the value from d1 :param d1: dictionary of values :param d2: dictionary of values :return: dictionary of unified values """ if default is None: return row_data if row_data is None: return default return {**default, **row_data}
def flatten_dict(deep_dict): """Turn `deep_dict` into a one-level dict keyed on `.`-joined path strings""" new_dict = {} for key, value in deep_dict.items(): if isinstance(value, dict): _dict = { ".".join([key, _key]): _value for _key, _value in flatten_dict(value).items() } new_dict.update(_dict) else: new_dict[key] = value return new_dict
def bubble_sort(arr_raw): """ args: arr_raw: list to be sorted return: arr_sort: list sorted """ for i in range(1, len(arr_raw)): for ii in range(0, len(arr_raw) - i): if arr_raw[ii] > arr_raw[ii + 1]: arr_raw[ii], arr_raw[ii + 1] = arr_raw[ii + 1], arr_raw[ii] else: pass return arr_raw
def px_U(box_hwidth): """ Args: box_hwidth (float): Half-width of the analysis box, in arcsec Returns: float: p(x|U) """ box_sqarcsec = (2*box_hwidth)**2 #box_steradians = box_sqarcsec * sqarcsec_steradians # return 1./box_sqarcsec
def ceildiv(a, b): """ To get the ceiling of a division :param a: :param b: :return: """ return -(-a // b)
def integer(i): """ Parses an integer string into an int :param i: integer string :return: int """ try: return int(i) except (TypeError, ValueError): return i
def _var(i=0): """ Return a distinct variable name for each given value of i """ alphabet = "XYZABCDEFGHIJKLMNOPQRSTUVW" return alphabet[i] if i < len(alphabet) else "X{}".format(i)
def is_string_ignored(string, ignored_substrings=""): """Check if string contains substrings""" lstr = str.lower(string) return not all(str.lower(x) not in lstr for x in ignored_substrings.split(",") if len(x) > 0)
def gravityLossUpToAltitude(altitude): """gives the gravity loss up to a given altitude""" if 0 <= altitude and altitude <= 20000: return 1500 - 0.075*altitude # m/s else: raise Exception("Invalid at given altitude: {0}".format(altitude))
def SieveOfEratosthenes(*args): """ Returns prime numbers within a range (including lower and upper bounds) or prime numbers less than or equal to given input Parameters ---------- *args : tuple Expects one or two arguments as described below Other Parameters ---------------- 1 argument : int denotes upper bound for prime numbers 2 arguments : (int,int) denotes lower and upper bounds for range of prime numbers Returns ------- array returns an array of prime numbers """ if(len(args)==1): n = args[0] prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 prime_arr = [] for p in range(2, n+1): if prime[p]: prime_arr.append(p) return prime_arr elif(len(args)==2): low = args[0] high = args[1] n = args[1] prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 prime_arr = [] for p in range(2, n+1): if (prime[p] and p>=low): prime_arr.append(p) return prime_arr elif(len(args)>2): raise NotImplementedError( "Invalid Number Of Arguments" )
def isfloat(value): """ Return True if all characters are part of a floating point value """ try: x = float(value) return True except ValueError: return False
def grades2map(gstring): """Convert a grade string from the database to a mapping: {sid -> grade} """ try: grades = {} for item in gstring.split(';'): k, v = item.split('=') grades[k.strip()] = v.strip() return grades except: if gstring: raise ValueError # There is an entry, but no data return None
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids): """ Ensures that the alternative id's in `nest_spec` are all in the universal choice set for this dataset. Raises a helpful ValueError if they are not. Parameters ---------- nest_spec : OrderedDict, or None, optional. Keys are strings that define the name of the nests. Values are lists of alternative ids, denoting which alternatives belong to which nests. Each alternative id must only be associated with a single nest! Default == None. list_elements : list of ints. Each element should correspond to one of the alternatives identified as belonging to a nest. all_ids : list of ints. Each element should correspond to one of the alternatives that is present in the universal choice set for this model. Returns ------- None. """ invalid_alt_ids = [] for x in list_elements: if x not in all_ids: invalid_alt_ids.append(x) if invalid_alt_ids != []: msg = "The following elements are not in df[alt_id_col]: {}" raise ValueError(msg.format(invalid_alt_ids)) return None
def count_instance_of_str(string1, string2): """Counts characters in string1 that are also in string2.""" count = 0 #for each char in string1, check if it's in string2 for char in string1: if char in string2: count += 1 return count
def fahrenheit_to_celsius(f): """Convert a Celsius temperature to Fahrenheit.""" return (f - 32.0) * 5.0 / 9.0
def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims): """Helper for calculating broadcast shapes with core dimensions.""" return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims) for core_dims in list_of_core_dims]
def RemoveQuots(string): """ Remove quotes at both ends of a string :param str string: string :return: string(str) - string """ if string[:1] == '"' or string[:1] == "'": string=string[1:] if string[-1] == '"' or string[-1] == "'": string=string[:-1] return string
def group_objects_by_model(objects): """ Group objects by their models Args: objects (:obj:`list` of :obj:`Model`): list of model objects Returns: :obj:`dict`: dictionary with object grouped by their class """ grouped_objects = {} for obj in objects: if obj.__class__ not in grouped_objects: grouped_objects[obj.__class__] = [] if obj not in grouped_objects[obj.__class__]: grouped_objects[obj.__class__].append(obj) return grouped_objects
def u_to_all_ratio(data): """ :param data: wikipedia content to be pre-processed :return: upper to lower case ratio vandals use either too many upper case or lower case words tobe applied before upper to lower transformation """ chars = list(data) upper_count = sum([char.isupper() for char in chars]) lower_count = sum([char.islower() for char in chars]) return round((1 + (upper_count)) / (1 + (lower_count) + (upper_count)), 4)
def _matches_package_name(name, pkg_info): """ :param name: the name of the package :type name: str :param pkg_info: the package description :type pkg_info: dict :returns: True if the name is not defined or the package matches that name; False otherwise :rtype: bool """ return name is None or pkg_info['name'] == name
def get_lvl_index(levels, lvl): """index of a given level in levels""" for k, v in levels.items(): if v['level'] == lvl: return k, v
def valid_arguments(valip, valch, valii, valid): """ Valid the arguments """ bvalid = True # Type converssion valch = int(valch) valii = int(valii) # Valid the parameters # Valid - IP if valip == "": print("IP is invalid.") bvalid = False # Valid - Channel if (valch < 1) | (valch > 4): print("Channel number is invalid.") bvalid = False # Valid - Index # Control device index if (valii < 0) | (valii > 63): print("Control device index is invalid.") bvalid = False # Valid - id if valid == "": print("id is invalid.") bvalid = False return bvalid
def remove_embed(text): """Removes the weird string from the end of genius results""" lyric = text.split('EmbedShare URLCopyEmbedCopy')[0] while lyric[-1].isnumeric(): lyric = lyric[:-1] return lyric
def concat(lists): """ Given a series of lists, combine all items in all lists into one flattened list """ result = [] for lst in lists: for item in lst: result += [item] return result
def get_backlinks(dictionary): """ Returns a reversed self-mapped dictionary @param dictionary: the forwardlinks """ o = dict() for key, values in dictionary.items(): try: for v in values: try: o[v].add(key) except KeyError: o[v] = {key} except TypeError as te: try: o[values].add(key) except KeyError: o[values] = {key} return o
def getcookies(cookiejar, host, path): """Get a dictionary of the cookies from 'cookiejar' that apply to the given request host and request path.""" cookies = {} for cdomain in cookiejar: if ('.' + host).endswith(cdomain): for cpath in cookiejar[cdomain]: if path.startswith(cpath): for key, value in cookiejar[cdomain][cpath].items(): cookies[key] = value return cookies
def guess_rgb(shape): """If last dim is 3 or 4 assume image is rgb. """ ndim = len(shape) last_dim = shape[-1] if ndim > 2 and last_dim < 5: return True else: return False
def user_event_search(msg): """ search product """ iscmd = msg['MsgType'] == 'text' and msg['Content'].startswith("search:") return iscmd
def DivideIfPossibleOrZero(numerator, denominator): """Returns the quotient, or zero if the denominator is zero.""" if not denominator: return 0.0 else: return numerator / denominator
def decode(string): """Decode a Base X encoded string into the number Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for decoding """ BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" base = len(BASE62) strlen = len(string) num = 0 idx = 0 for char in string: power = (strlen - (idx + 1)) num += BASE62.index(char) * (base ** power) idx += 1 return num
def error_porcentual(aceptado: float, experimental: float) -> str: """ Calcular error porcentual de un resultado experimental obtenido con respecto al aceptado """ porcentaje = abs(((aceptado - experimental) / aceptado) * 100) return "{:.8f}%".format(porcentaje)
def sci_notation(value, sig_figs=8): """ Print value in scientific notation with number of signficant digits specified by `sig_figs`. This filter is required as there are known issues when supplying some quantities (e.g. loop length) at arbitrarily high precision """ format_str = f'1.{sig_figs}e' return f'{value:{format_str}}'
def getLanguage(langID, sublangID): """ Get Language Standard. Args: langID (str): Landguage ID sublangID (str): Sublanguage ID Returns: str: Language encoding. """ langdict = { 9: { 0: "en", 1: "en", 3: "en-au", 40: "en-bz", 4: "en-ca", 6: "en-ie", 8: "en-jm", 5: "en-nz", 13: "en-ph", 7: "en-za", 11: "en-tt", 2: "en-gb", 1: "en-us", 12: "en-zw", }, # English 16: {0: "it", 1: "it", 2: "it-ch"}, # Italian, Italian (Switzerland) 22: {0: "pt", 2: "pt", 1: "pt-br"}, # Portuguese, Portuguese (Brazil) 10: { 0: "es", 4: "es", 44: "es-ar", 64: "es-bo", 52: "es-cl", 36: "es-co", 20: "es-cr", 28: "es-do", 48: "es-ec", 68: "es-sv", 16: "es-gt", 72: "es-hn", 8: "es-mx", 76: "es-ni", 24: "es-pa", 60: "es-py", 40: "es-pe", 80: "es-pr", 56: "es-uy", 32: "es-ve", }, # Spanish } sublangID = 0 if not sublangID else sublangID try: lang = langdict[langID][sublangID] except KeyError: lang = "en" return lang
def base36encode(number): """Converts an integer into a base36 string.""" ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz" base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <= number < len(ALPHABET): return sign + ALPHABET[number] while number != 0: number, i = divmod(number, len(ALPHABET)) base36 = ALPHABET[i] + base36 return sign + base36
def CleanTitle(title): """remove [graphic] from titles""" title = title.replace(' [graphic].', '') title = title.replace('[', '').replace(']','') return title
def flatten(lis): """indices = list(range(0, len(lis)))""" sortLis = list(sorted(lis)) m = {} for index, value in enumerate(sortLis): m[value] = index returnList = [] for value in lis: returnList.append(m[value]) """zippedSorted = list(zip(sortLis, indices)) newList = [] for x in lis: for y in zippedSorted: if x == y[0]: newList.append(y[1])""" return returnList
def avg(S,C): """This Function returns the average of the numbers given""" avg = 0 avg = S/C # Returns the rounded to 2 decimal places... return round(avg,2)
def _set_small_values_to_zero(tol, *values): """helper function to set infinitesimally small values to zero Parameters ---------- tol : float threshold. All numerical values below abs(tol) is set to zero *values : unflattened sequence of values Returns ------- Example ------- >>> tol = 1e-12 >>> a, b, c, d = _set_small_values_to_zero(tol, 1.0, 0.0, tol, 1e-13) >>> a 1.0 >>> b 0.0 >>> c 1e-12 >>> d 0.0 """ return [0 if abs(value) < tol else value for value in values]
def calc_num_overlap_samples(samples_per_frame, percent_overlap): """Calculate the number of samples that constitute the overlap of frames Parameters ---------- samples_per_frame : int the number of samples in each window / frame percent_overlap : int, float either an integer between 0 and 100 or a decimal between 0.0 and 1.0 indicating the amount of overlap of windows / frames Returns ------- num_overlap_samples : int the number of samples in the overlap Examples -------- >>> calc_num_overlap_samples(samples_per_frame=100,percent_overlap=0.10) 10 >>> calc_num_overlap_samples(samples_per_frame=100,percent_overlap=10) 10 >>> calc_num_overlap_samples(samples_per_frame=960,percent_overlap=0.5) 480 >>> calc_num_overlap_samples(samples_per_frame=960,percent_overlap=75) 720 """ if percent_overlap > 1: percent_overlap *= 0.01 num_overlap_samples = int(samples_per_frame * percent_overlap) return num_overlap_samples
def html(title, body): """Wrap the body HTML in a mobile-friendly HTML5 page with given title and CSS file 'style.css' from the static content directory.""" return """<!DOCTYPE html> <HTML> <HEAD> <TITLE>{}</TITLE> <META name="viewport" content="width=device-width, initial-scale=1.0"> <LINK rel="stylesheet" href="/style.css" type="text/css"> </HEAD> <BODY> {} </BODY> </HTML> """.format(title, body)
def adjust_boundingbox(face, width, height, size): """ :param face: dlib face class :param width: frame width :param height: frame height :param size: set bounding box size :return: x, y, bounding_box_size in opencv form """ x1 = face[0] y1 = face[1] x2 = face[2] y2 = face[3] center_x, center_y = (x1 + x2) // 2, (y1 + y2) // 2 # Check for out of bounds, x-y top left corner x1 = min(max(int(center_x - size // 2), 0), width - size) y1 = min(max(int(center_y - size // 2), 0), height - size) return [x1, y1, size]
def multipart_geoms_query(schema, table): """Returns sql query to check multipart geometries of a table. Args: schema: Name of the schema. table: Name of the table. Returns: String sql query. """ return ( 'SELECT id, ST_NumGeometries(geom) ' 'FROM {}.{} ' 'WHERE ST_NumGeometries(geom) > 1 ' 'ORDER BY id' ).format(schema, table)
def clean_tag(tag): """ Function to clean up human tagging mistakes. Non generalizable function. Need to edit in future to make more generalizeable """ tag = tag.upper().strip() if not tag.isalnum(): tag = '<Unknown>' elif 'MO' in tag or 'OL' in tag: tag = 'MOL' elif 'P' in tag and 'R' in tag: tag = 'PRO' elif tag == 'EE': tag = 'E' elif tag == 'BB': tag = 'B' return tag
def parse_requirements(r): """Determine which characters are required and the number of them that are required.""" req = {'d': 0, 'l': 0, 'u': 0, 's': 0} for c in r: if c == 'd': req['d'] += 1 elif c == 'l': req['l'] += 1 elif c == 'u': req['u'] += 1 elif c == 's': req['s'] += 1 else: continue return req
def safe_div(numerator: int, denominator: int) -> float: """Divide without Zero Division Error. Args: numerator (integer): the number above the line in a vulgar fraction. denominator (integer): the number below the line in a vulgar fraction. Returns: float: Return value Usage: >>> from py_admetric import utils >>> val = utils.safe_div(1,1) """ if denominator == 0: return 0.0 return numerator / denominator
def _trapz_2pt_error2(dy1, dy2, dx): """Squared error on the trapezoidal rule for two points. For errors dy1 and dy2 and spacing dx.""" return (0.5*dx)**2 * (dy1**2 + dy2**2)
def normalize(scope): """ Normalizes and returns tuple consisting of namespace, and action(s) """ parts = scope.split(":") return (parts[0], parts[1:])
def waterModis(ndvi, band7): """ # water.modis: Terra-MODIS water mapping tool # Xiao X., Boles S., Liu J., Zhuang D., Frokling S., Li C., Salas W., Moore III B. (2005). # Mapping paddy rice agriculture in southern China using multi-temporal MODIS images. # Remote Sensing of Environment 95:480-492. # # Roy D.P., Jin Y., Lewis P.E., Justice C.O. (2005). # Prototyping a global algorithm for systematic fire-affected # area mapping using MODIS time series data. # Remote Sensing of Environment 97:137-162. """ if((ndvi < 0.1) and (band7 < 0.04)): return(1) else: return(0)
def relate_objs(obj1_coords, obj2_coords, relation): """ Relates obj2 in relation to obj1, e.g. whether obj2 is behind obj1 or whether obj2 is right of obj1. :param obj1_coords: :param obj2_coords: :param relation: :return: """ relation_holds = False if relation == "behind" and obj1_coords[1] > obj2_coords[1]: relation_holds = True elif relation == "front" and obj1_coords[1] < obj2_coords[1]: relation_holds = True elif relation == "right" and obj1_coords[0] < obj2_coords[0]: relation_holds = True elif relation == "left" and obj1_coords[0] > obj2_coords[0]: relation_holds = True return relation_holds
def str_to_bool(string, truelist=None): """Returns a boolean according to a string. True if the string belongs to 'truelist', false otherwise. By default, truelist has "True" only. """ if truelist is None: truelist = ["True"] return string in truelist
def train(params, step, iters=1): """Executes several model parameter steps.""" for i in range(iters): params = step(params) return params
def flatten_list(_list): """Flatten a nested list""" return [x for el in _list for x in el]
def relpath(path): """Convert the given path to a relative path. This is the inverse of abspath(), stripping a leading '/' from the path if it is present. :param path: Path to adjust >>> relpath('/a/b') 'a/b' """ return path.lstrip('/')
def common_prefix(a, b): """:return: the longest common prefix between a and b.""" for i in range(min(len(a), len(b))): if a[i] != b[i]: return a[:i] return ''
def get_meta_data(file_name): """Helper function to retrieve a given file name's year, month, and zone. Takes a string file_name formatted as ``'AIS_yyyy_mm_Zone##.csv'`` and returns the numerical values of ``yyyy, mm, ##`` corresponding to year, month, and zone number as a tuple. Args: file_name (str): The file name to be parsed in format ``'AIS_yyyy_mm_Zone##.csv'``. Returns: tuple: The year, month, and zone corresponding to the filename passed in. """ meta_file_data = file_name.split( "_" ) # splits csv file on '_' character, which separates relevant file info year = int(meta_file_data[-3]) # third to last element of file is the year month = int( meta_file_data[-2] ) # second to last element of file is the month # get zone number for csv file being read ending_raw = meta_file_data[ -1 ] # gets last part of the file, with format "ZoneXX.csv" ending_data = ending_raw.split( "." ) # splits last part of file on '.' character zone_raw = ending_data[0] # gets "ZoneXX" string zone_data = zone_raw[ -2: ] # gets last 2 characters of "ZoneXX" string - will be the zone number zone = int(zone_data) return year, month, zone
def _merge_line_string(rel, startindex): """ takes a relation that might possibly be a bunch of ways that HAPPEN to be a single line, and transforms the MultiLineString object into a single LineString object """ #WARNING: THIS CURRENTLY "WORKS" BUT VIOLATES WINDINR ORDER FOR POLYGONS coordinate_list = rel["geometry"]["coordinates"] for clindex, cl in enumerate(coordinate_list): if clindex <= startindex: pass elif clindex < len(rel["geometry"]["coordinates"]): clreversed = list(reversed(cl)) if cl[0] == coordinate_list[startindex][-1]: rel["geometry"]["coordinates"][startindex] = rel["geometry"]["coordinates"][startindex] + cl[1:] del rel["geometry"]["coordinates"][clindex] return _merge_line_string(rel, startindex) elif clreversed[0] == coordinate_list[startindex][-1]: rel["geometry"]["coordinates"][startindex] = rel["geometry"]["coordinates"][startindex] + clreversed[1:] del rel["geometry"]["coordinates"][clindex] return _merge_line_string(rel, startindex) elif cl[-1] == coordinate_list[startindex][0]: # end of current list matches head of startindex list. rel["geometry"]["coordinates"][startindex] = cl + rel["geometry"]["coordinates"][startindex][1:] del rel["geometry"]["coordinates"][clindex] return _merge_line_string(rel, startindex) elif clreversed[-1] == coordinate_list[startindex][0]: rel["geometry"]["coordinates"][startindex] = clreversed + rel["geometry"]["coordinates"][startindex][1:] del rel["geometry"]["coordinates"][clindex] return _merge_line_string(rel, startindex) # see if we've swuashed everything down into one if len(rel["geometry"]["coordinates"]) == 1: # see if we got a line string, or a polygon if rel["geometry"]["coordinates"][startindex][0] == rel["geometry"]["coordinates"][startindex][-1]: # got ourselves a polygon rel["geometry"]["type"] = "Polygon" else: # linestring rel["geometry"]["type"] = "LineString" rel["geometry"]["coordinates"] = rel["geometry"]["coordinates"][0] elif startindex < len(rel["geometry"]["coordinates"])-1: return _merge_line_string(rel, startindex+1) return rel
def right_node(nodes, x, y): """ find the first right node and returns its position """ try: return str(nodes.index('0', x+1)) + " " + str(y) + " " except(KeyError, ValueError): return '-1 -1 '
def factorial(num): """ The factorial of a number. On average barely quicker than product(range(1, num)) """ # Factorial of 0 equals 1 if num == 0: return 1 # if not, it is the product from 1...num product = 1 for integer in range(1, num + 1): product *= integer return product
def debug(stmt, data): # pragma: no cover """Helpful debug function """ print(stmt) print(data) return data
def power(x,y): """returns x^y""" if(y==0): return 1 return x *power(x, y - 1)
def remove_whitespace_lines(text: str) -> str: """ Remove lines that only contains whitespace from a string. """ return "\n".join([line for line in text.splitlines() if line.strip()])
def adjacency_matrix(parent1, parent2): """Return the union of parent chromosomes adjacency matrices.""" neighbors = {} end = len(parent1) - 1 for parent in [parent1, parent2]: for k, v in enumerate(parent): if v not in neighbors: neighbors[v] = set() if k > 0: left = k - 1 else: left = end if k < end: right = k else: right = 0 neighbors[v].add(parent[left]) neighbors[v].add(parent[right]) return neighbors
def extract_group_ids(caps_directory): """Extract list of group IDs (e.g. ['group-AD', 'group-HC']) based on `caps_directory`/groups folder.""" import os try: group_ids = os.listdir(os.path.join(caps_directory, "groups")) except FileNotFoundError: group_ids = [""] return group_ids
def generate_deployment_ids(deployment_id, resources): """ Create a new deployment ID for a child deployment. :param deployment_id: An existing deployment ID. :type deployment_id: str :return: A new child deployment ID. :rtype: str """ return '{}-{}'.format(deployment_id, resources)