content
stringlengths
42
6.51k
def combine(overiding_dict, base_dict): """Combining two dictionaries without modifying them. This is a private method, and should not be exposed to users. """ if overiding_dict is None: return dict(base_dict) return {**base_dict, **overiding_dict}
def eta(filesize, a, b): """ Determines how long the transfer of filesize bytes from A to B should take. units for filesize are bytes, a and b is speed in kilobytes """ return filesize/(min(a, b)*1024)
def encrypt_letter(letter): """Encrypt a single letter Arguments: letter {char} -- The character to encrypt Returns: char -- The encrypted character """ inc_ord_char = ord(letter) + 3 if letter.isupper(): if inc_ord_char > 90: inc_ord_char = inc_ord_c...
def split_nonsyllabic_maxonset(string, onsets): """ Finds split between onset and coda in list with no found syllabic segments Parameters ---------- string : iterable the phones to search through onsets : iterable an iterable of possible onsets Returns ------- int ...
def _getDictWithKey(key, dict_list): """ Returns the first dictionary in dict_list which contains the given key""" for d in dict_list: if key in d: return d return None
def _get_forms(dataset): """ Return the list of Form `dict`'s for a `cldfbench.CLDFWriter` or a `pycldf.Dataset`. """ return dataset.objects['FormTable'] \ if (hasattr(dataset, 'objects') and isinstance(dataset.objects, dict)) \ else list(dataset['FormTable'])
def const_fill(value): """Constant fill helper to reduce verbosity.""" return ('ConstantFill', {'value': value})
def plural(num, single="", many="s"): """ plural """ return single if num == 1 else many
def sizeof_fmt(num, suffix='B'): """ Sridhar Ratnakumar, Reusable library to get human readable version of file size?, Jul 7 '09, http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size :param num: memory size :param suffix: Default B :return: M...
def clean_jaspar_names(uncleaned_jaspar_ids): """ Clean names of jaspar transcription factor names. MSX3 <- lost in humans. RHOX11 <- only present in 3 species. DUX <- mouse only gene. EWSR1 <- didn't end up in the Ensembl BioMart export. MIX-A <- jaspar says present in xenopus laevis, but n...
def _give_default_names(list_of_objects, name): """Helper function to give default names to objects for error messages.""" return [name + '_' + str(index) for index in range(len(list_of_objects))]
def D_rvmu(r: float, v: float, mu: float) -> float: """ D = r * v * v / mu :param r: radius vector :type r: float :param v: velocity :type v: float :param mu: G * (m1 + m2) :type mu: float :return: D :rtype: float """ return r * v * v / mu
def extract_variants(pattern): """Extract the pattern variants (ie. {foo,bar}baz = foobaz or barbaz).""" v1, v2 = pattern.find('{'), pattern.find('}') if v1 > -1 and v2 > v1: variations = pattern[v1 + 1:v2].split(',') variants = [pattern[:v1] + v + pattern[v2 + 1:] for v in variations] ...
def deserialize_dict_1d(dict_in): """Convert str of list to list. Args: dict_in (dict): input dict Returns: (dict): deserialized dict """ assert isinstance(dict_in, dict) dict_out = dict_in for key, value in dict_out.items(): if isinstance(value, str): ...
def use_math(lines): """Check if an Earth Engine uses Math library Args: lines (list): An Earth Engine JavaScript. Returns: [bool]: Returns True if the script contains 'Math.'. For example 'Math.PI', 'Math.pow' """ math_import = False for line in lines: if 'Math...
def valence(sym): """ bonding valence """ return {'H': 1, 'HE': 0, 'C': 4, 'N': 3, 'O': 2, 'S': 2, 'F': 1, 'CL': 1, 'NE': 0, 'AR': 0}[sym.upper()]
def log_probability(value, mean, variance): """ Given a normal distribution with a given mean and varience, compute the log probability of a value from that distribution. """ # Your code here return 0.0
def sortResultsByDevice(results): """Sort the lava test jobs by device. :return: sorted list """ sortedResults = sorted( results, key=lambda i: (i["requested_device_type_id"], i["description"]), ) return sortedResults
def extract_ingredient_counts(ingredients_dict, ingredient_labels): """ Extract ingredient counts from dict for plotting in chart. :param ingredients_dict: dict mapping ingredient names to counts :param ingredient_labels: list of strings containing ingredient names :return: list of counts of ingredi...
def convert_simple_path(path): """Converts path given as list of tuples of 2 elements into list of point dictionaries""" mapped_path = [] for p in path: mapped_path.append({"location": {"lat": p[0], "lng": p[1]}}) return mapped_path
def _has_method(arg, method): """Returns true if the given object has a method with the given name. :param arg: the object :param method: the method name :type method: string :rtype: bool """ return hasattr(arg, method) and callable(getattr(arg, method))
def summation(n, term): """Sum the first N terms of a sequence. """ total, k = 0, 1 while k <= n: total, k = total + term(k), k + 1 return total
def _IsIn(matcher, operand, value): """Applies matcher to determine if the expression operand is in value. Args: matcher: Boolean match function that takes value as an argument and returns True if the expression operand is in value. operand: Number or string operand. value: The value to match aga...
def split(text): """ sometext|split """ return text.split()
def getint(data, offset, intsize): """Retrieve an integer (big-endian) and new offset from the current offset""" value = 0 while intsize > 0: value = (value<<8) + ord(data[offset]) offset = offset + 1 intsize = intsize - 1 return value, offset
def __write_rnx3_header_markertype__(markertype="SMARTPHONE"): """ """ TAIL = "MARKER TYPE" res = "{0:60s}{1}\n".format(markertype, TAIL) return res
def human_readable(n): """ Print sizes in bytes in more human readable form. https://stackoverflow.com/a/1094933/199166 """ for unit in ['B','K','M','G','T','P','E','Z']: if abs(n) < 1024.0: return f"{n:6.1f}{unit}" n /= 1024.0 return f"{n:6.1f}Y"
def func_calc_st(T,Qref,Tref,Tc): """ Calculate Elevated Temperature Surface Tension Parameters: Qref : Reference Surface Tension at temperature T, (mN/m) Tref : Reference temperature (K) Tc : Critical temperature (K) Return: Surface Tension at temperature T "...
def lonlat_intersect(lonlat1, lonlat2): """ Check if two lonlat boxes intersect :lonlat1: list, [leftlon, rightlon, botlat, toplat] :lonlat2: list, [leftlon, rightlon, botlat, toplat] :return: true if lonlat boxes overlap, false otherwise """ # Before continuing, note that a co...
def get_auth_string(auth_or_path): """Retrieves authentication string from string or file. Args: auth_or_path (str): Authentication string or path to file containing it Returns: str: Authentication string. """ if ":" in auth_or_path: return auth_or_path try: wi...
def filter_detecting_boundaries(detecting_boundaries): """ [[t1,t2],[],[t1,t2]] -> [[t1,t2],[t1,t2]] [[],[]] -> [] """ _detecting_boundaries = [] for couple in detecting_boundaries.copy(): if len(couple)!=0: _detecting_boundaries.append(couple) detecting_boundaries = _det...
def calculate_percentage(total: int, value: float): """Calcula a porcentagem do valores.""" result = (value / total) * 100 return result
def raytrace(pos1: tuple, pos2: tuple) -> list: """ Draws line between pos1 and pos2 for a taxicab grid """ x0, y0 = pos1 x1, y1 = pos2 tiles = [] dx = abs(x1 - x0) dy = abs(y1 - y0) x, y = x0, y0 n = 1 + dx + dy x_inc = 1 if x1 > x0 else -1 y_inc = 1 if y1 > ...
def memoize(f): """ Memoization decorator for functions taking one or more arguments. """ class memodict(dict): def __init__(self, f): self.f = f def __call__(self, *args): return self[args] def __missing__(self, key): ret = self[key] = self.f(*key) ...
def get_key(url, key="request_token"): """ Get the required key from the query parameter """ from urllib.parse import parse_qs, urlparse req = urlparse(url) key = parse_qs(req.query).get(key) if key is None: return None else: return key[0]
def _user_profile(user_profile): """ Returns the user profile object. For now, this just comprises the profile_image details. """ return { 'profile': { 'image': user_profile['profile_image'] } }
def parse_ini_file(fn): """Parse INI file and return dictionary""" ret = {} section = '' with open(fn) as infile: for line in infile: line = line.strip() if line == '' or line.startswith('#'): continue if line[0] == '[' and line[-1] == ']': ...
def assert_equal(other, obj, msg=None): """ Fail if the two objects are unequal as determined by the '==' operator. from functools import * from amara.lib.util import * f = partial(assert_equal, u'', msg="POW!") print (f(''),) # -> '' """ if not obj == other: raise Assertion...
def line_contains_any_of(the_line, items): """ Determine if any of the members of items is present in the string, if so, return True :param the_line: The input line to check against :param items: The (list of) check items :return: True if at least one item found, False otherwise """ for the_...
def b14toInt(b): """Convert 14bit integers from bytes Arguments: b {bytearray} -- bytes Returns: int32 -- b14 decoded int[summary] """ if len(b) < 2: return 0 b1 = ord(b[0]) << 1 b2 = ord(b[1]) << 8 bc = b2 + b1 bc = bc >> 1 return bc
def to_str(text): """Convert to unicode.""" try: # Python 2 return text.decode('utf-8') except AttributeError: # pragma: no cover # Python 3.5+ return text
def create_dict_pl(questions_list, tokens_label): """When we create vocabulary with placeholders, no need to preprocess sentences since they have already been preprocessed""" tokens = [token for sentence in questions_list for token in sentence] tokens.extend(list(tokens_label)) words = sorted(list(...
def _row_to_labels(row): """Extracts labels from a labelled ingredient data row. Args: A row of full data about an ingredient, including input and labels. Returns: A dictionary of the label data extracted from the row. """ labels = {} label_keys = ["name", "qty", "range_end", "...
def fixPayloadToOutput( payload: str, maxLength: int = 30, isProgressStatus: bool = False, ) -> str: """Fix the payload's size @type payload: str @param payload: The payload used in the request @type maxLength: int @param maxLength: The maximum length of the payload on output @type ...
def to_list(list_str): """Convert a string to a list. """ return [ v.strip('"').strip("'") for v in list_str .replace("\n", "").replace(" ", "").replace("\t", "") .strip("]").strip("[") .rstrip(",").split(",") ]
def isint(value): """ Determines if value is an integer Parameters ---------- value : Value """ try: int_val = int(value) if int_val == value or str(int_val) == value: return True else: return False except ValueError: ret...
def count_bits(bits): """Count number of bits on each bit position.""" counted_bits = { position: {'1': 0, '0': 0} for position, _ in enumerate(bits[0]) } for line in bits: for position, bit in enumerate(line): counted_bits[position][bit] += 1 return counted_bits
def indexed_color(index): """ """ colors = {0: 'b', # blue 1: 'g', # green 2: 'r', # red 3: 'c', # cyan 4: 'm', # magenta 5: 'y', # yellow 6: 'k', # black 7: 'w' # white } return colors[index]
def _find_literal(s, start, level, parts, exprs): """Roughly Python/ast.c:fstring_find_literal""" i = start parse_expr = True while i < len(s): ch = s[i] if ch in ("{", "}"): if level == 0: if i + 1 < len(s) and s[i + 1] == ch: i += 2 ...
def multiply_vector_by_value(vector, value): """ >>> multiply_vector_by_value([1, 2, 3], 5) [5, 10, 15] """ return [vector[i] * value for i in range(len(vector))]
def opt_pol_3(state) -> int: """The optimal policy illustrated in the textbook. When capital is 50, stake 50; when capital is 25 or 75 stake 25 (to get to either 50 or 100); otherwise stake the amount required to get to the nearest multiple of 25. """ if state < 25: return min(state, 25...
def rm_par(s: str): """Remove parenthesis.""" if s[0] == "(" and s[-1] == ")": s = s[1:-1] return s
def get_sample_ids(samples_lst): """list of just sample prefix""" sample_ids = [] for sample in samples_lst: sample_ids.append((sample.split("_")[0])) sorted_sample_ids = sorted(set(sample_ids), key=lambda x: float("." + x[3:])) print(sorted_sample_ids) print(len(sorted_sample_ids) == le...
def suma(cu, cd): """(list, list) -> list Suma entre dos numeros complejos""" a = cu[0] + cd[0] b = cu[1] + cd[1] r= [a,b] return r
def S(i): """Convert an int to a binary string wide enough to hold it.""" s = '' while i != 0: digit = i & 0xff i >>= 8 s += chr(digit) return s
def clear_empty(entry): """ Clear empty fields in entry """ gen = (field for field in entry.keys() if not entry[field]) for field in gen: del entry[field] return entry
def in_bounds(lat, lon, corners): """ Return true if the lat lon is within the corners. """ return \ lat >= corners[0] and lat <= corners[2] and \ lon >= corners[1] and lon <= corners[3]
def filer_has_permission(context, item, action): """Does the current user (taken from the request in the context) have permission to do the given action on the given item. """ permission_method_name = 'has_{action}_permission'.format(action=action) permission_method = getattr(item, permission_metho...
def is_number(value): """ Checks whether the value is a number :param value: :return: bool """ try: complex(value) except ValueError: return False return True
def is_palindrome(strng): """Return bool if strng is palindrome.""" return str(strng) == str(strng)[::-1]
def string_replacer(line): """Take string literals like 'hello' and replace them with empty string literals, while respecting escaping.""" r = [] in_quote = None escapes = 0 for i, c in enumerate(line): if in_quote: if not escapes and c == in_quote: in_quote = No...
def get_request_header(request, header_name, default=''): """Helper method to get header values from a request's META dict, if present.""" if request is not None and hasattr(request, 'META') and header_name in request.META: return request.META[header_name] else: return default
def _parseMinusList(fdata): """Parse a list of lines starting with '- '.""" rlist = [] tmplist = [] for line in fdata: if line and line[:2] == '- ': if tmplist: rlist.append(' '.join(tmplist)) l = line[2:].strip() if l: tmplist[...
def id_number_checksum(gd): """ Calculates a Swedish ID number checksum, using the Luhn algorithm """ n = s = 0 for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']): # Letter? It's an interimspersonnummer and we substitute the letter # with 1. if c.isalpha(): ...
def code(text: str) -> str: """Wrap input string in HTML code tag.""" return f'<code>{text}</code>'
def generate_edge_key(s: str, edge_predicate: str, o: str) -> str: """ Generates an edge key based on a given subject, predicate, and object. Parameters ---------- s: str Subject edge_predicate: str Edge label o: str Object id: str Optional identifier tha...
def getMoneyFormatNumber(int_float_num): """ return the value as money format, 12345 -> 12,345 :param int/float int_float_num :return string """ if isinstance(int_float_num, int): return '{:,}'.format(int(int_float_num)) elif isinstance(int_float_num, float): ret...
def make_grid(x, y, fill: int = 0): """Make a 2x2 list of lists filled with "fill".""" return [[fill for y in range(y)] for _ in range(x)]
def lr_scheduler(optimizer, epoch, init_lr=0.1, lr_decay_epoch=100): """Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.""" if epoch % lr_decay_epoch == 0 and epoch>1: for param_group in optimizer.param_groups: param_group['lr'] = param_group['lr'] * 0.1 return optimi...
def partition_classes(X, y, split_attribute, split_val): """Partition the data and labels based on the split value given. For example, given the following X and y: X = [[3, 'aa', 10], y = [1, [1, 'bb', 22], 1, [2, 'cc', 28], 0,...
def ppm_range(value, difference): """ Calculate incertitude on MS1/MS2 masses equivalent to given ppms """ return difference * 1000000 / value
def calculate_cpu_sleep_interval(cpulimit, percentused, elapsedtime): """ <Purpose> Calculates proper CPU sleep interval to best achieve target cpulimit. <Arguments> cpulimit: The target cpu usage limit percentused: The percentage of cpu used in the interval between the last sample of t...
def _update_strategy(strategy, global_signal): """Update strategy if global signal is supplied as a parameter.""" strat = strategy.copy() if isinstance(global_signal, str): strat.append("global") return strat, global_signal
def term(cp, term, weight): """create a new search term query Terms are hard-capped at 254 characters to not exceed the column definition. Also there's no use in using such long terms since they will be searched verbatim.""" return [ (cp, term[0:254], weight) ]
def get_from_key(item, key, reduced_key=None, delimiter="."): """ nice little tool to aid in flexibility when dealing with multilayer dicts. """ if type(item) is not dict: return item try: return item[key] except KeyError: if reduced_key is None: reduced_key =...
def linkObjectLists(annotation, objectlist): """Recursively adds the objects of the specified list to an annotation dictionary. Wherever the keyword "$selected_objects:phobostype1:phobostype2" is found as a value in the annotation dictionary, the value is replaced by a list of tuples: (pho...
def tts_ip_address(ip_address): """Convert an IP address to something the TTS will pronounce correctly. Args: ip_address (str): The IP address, e.g. '102.168.0.102' Returns: str: A pronounceable IP address, e.g. '192 dot 168 dot 0 dot 102' """ return ip_address.replace('.', ' Punkt '...
def subtract(coords1, coords2): """ Subtract one 3-dimensional point from another Parameters coords1: coordinates of form [x,y,z] coords2: coordinates of form [x,y,z] Returns list: List of coordinates equal to coords1 - coords2 (list) """ x = coo...
def line(x0, y0, dydx): """ Find a and b for a line a*x+b that goes through (x0,y0) and has the derivative dydx at this point. Formula: y = y0 + dydx*(x - x0) """ return dydx, y0 - dydx*x0
def b_to_string(bytes, encoding='utf-8'): """ Return utf-8 sting, terminating a first null byte""" bytes = bytes.split(b'\0',1)[0] string = str(bytes, encoding) return string
def get_feature_importance_list(feature_names: list, importance_list: list) -> object: """ marries feature names to importances from sklearn classifier feature_importances_ array and sorts by importance :param feature_names: dataframe for feture names :param importance_list: sklearn feature impo...
def fuzzy_join(objs, sep='/'): """Join the fuzzy_rule of the objects into one string. Args: objs (sequence): The objects each of which have fuzzy_rule property. sep (str): Defaults to '/'. Seperator for joining. Returns: str: The joined fuzzy_rule string. """ return sep.joi...
def _get_extension_for_entry(intake_entry): """ Given an intake catalog entry, return a file extension for it, which can be used to construct names when re-uploading the files to s3. It would be nice to be able to rely on extensions in the URL, but that is not particularly reliable. Instead, we infe...
def parse_key_name(keyname): """keyname => resource, username""" # Relies on resource name not containing -, validated in # validate_resource_name toks = keyname.split('-') if len(toks) != 2: return None, None # some other keyname not launched by nexus else: return toks
def doi_to_directory(doi): """Converts a doi string to a more directory-friendly name Parameters ---------- doi : string doi Returns ------- doi : string doi with "/" and ":" replaced by "-" and "-" respectively """ return doi.replace("/", "-").replace(":", "-")
def collide(l1, l2): """ Detect whether l1 and l2 have common elements. :param list l1: List 1. :param list l2: List 2. :rtype: bool """ return len(set(l1).intersection(l2)) > 0
def min_max_comparison(value, value_to_compare, condition): """ Translate the values and condition to comparison operator and get result. :param value: (numeric) original value :param value_to_compare: (numeric) value to compare with, the value to beat. :param condition: (str) min/max condition. If ...
def extract_unique_entities_and_relations(triples): """ Identifies unique entities and relation types in collection of triples. Args: triples: List of string triples. Returns: unique_entities: List of strings unique_relations: List of strings """ s_entities = set([tripl...
def clean_website(url): """ In a few instances, the URL was not formatted correctly. We correct that here. """ url = url.replace('http:/www', 'http://www') url = url.replace('http;/', 'http://') return url
def count_collisions(right: int, down: int, aoc_map: list) -> int: """ Given the trajectory, count the number of collisions (or close shaves) with trees. :param right: The number of spaces to the right moved in one time tick. :param down: The number of spaces down moved in one time tick. :param aoc_...
def int_from_32bit_array(val): """Converts an integer from a 32 bit bytearray :param val: the value to convert to an int :type val: int :rtype: int """ rval = 0 for fragment in bytearray(val): rval <<= 8 rval |= fragment return rval
def _filter_tuples(services_states, state): """Return a simple list from a list of tuples according to the condition @param services_states: LIST of (string, boolean): service and running state. @param state: Boolean to match the tuple against. @returns [LIST of strings] that matched the tup...
def IsClosed(spline): """Global function responsible to check the close status of a spline""" if spline is None: return False # ?? In case we've got a LineObject from a cache, get the Spline that created it and check it's closed state. ?? if spline.GetCacheParent() is not None: return s...
def attr_proc_title( binary, attrs ): """ Make a process title that has attr:<k>=<v> for set of attributes. """ return "%s %s" % (binary, " ".join( ["attr:%s=%s" % (k, v) for (k, v) in attrs.items()] ))
def is_valid_0_1(param): """ Checks if param is zero or one """ return param == "0" or param == "1" or param == 0 or param == 1
def filter_none(attribute, default): """Handle attributes of model components that are optional in SBML.""" if attribute is None: return default else: return attribute
def is_prime(n, s=[], ps=[]): """ Check whether a reasonably small number is prime or not. The user has the responsability to provide a big enough list of primes. The function will return True if it can't find a prime that divides n. Parameters ---------- n: int Number to check ...
def SelectSpecies(Species): """ convert various alternatives to standard species name: electron or proton """ if Species.lower() in ('e','e-','electron','beta'): Species = 'electron' elif Species.lower() in ('p','p+','h+','proton','h','hydrogen'): Species = 'proton' else: ...
def find_node_id_in_template(program, idx, template): """Given a node idx in the given program, try to find the corresponding node in the template""" ind_prog = ind_template = 0 def is_same_fun(fn1, fn2): """The function names in programs and templates don't always match 1:1, so we redefine equalit...
def is_iterable(posibleList): """Validate if element is iterable Args: posibleList (Any): posible iterable element Returns: bool: if element is iterable """ try: if isinstance(posibleList, (tuple, list)) or hasattr(posibleList, "__iter__"): _ = posibleList[0] ...