content
stringlengths
42
6.51k
def recursive_convert_sequences(data): """ recursively applies ``convert_sequences`` """ if not hasattr(data,'keys'): return data if len(data.keys()) == 0: return data try: int(data.keys()[0]) except ValueError: tmp = {} for key, value in data.items():...
def get_one_differing_var(vars1, vars2): """Checks to see if two sets of variables have one differing one?? """ if len(vars1) != len(vars2): return None ans = None for var in vars1: if var in vars2: if vars1[var] != vars2[var]: if ans is None: ...
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if num == 0: raise ValueError if num == 1: return "1" seq = [0, 1, 1] for i in range(3, num + 1): next_num = seq...
def response_succeeded(response): """ Given a Boto response, return True if the response was successful """ return response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 200
def get_maintenance_period_type(code): """Get maintenance period type from code.""" maintenance_period_type = {0: "One time", 2: "Daily", 3: "Weekly", 4: "Monthly"} if code in maintenance_period_type: return maintenance_period_type[code] + " (" + str(code) + ")" return "Unknown ({})".format(st...
def d_poly_f(x, c): """Derivative function of poly_f""" df_x = 0 for i in range(1, len(c)): df_x += pow(x, i - 1) * c[i] * i return df_x
def is_number(s): """Returns true if the input is number, false otherwise""" try: float(s) return True except ValueError: return False
def get_suffix_base64(raw_base64): """ get suffix and base code :param raw_base64: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA :return: png, iVBORw0KGgoAAAANSUhEUgAA """ parts = raw_base64.split(',', 1) code = parts[1] splits = parts[0].split(';')[0].split('data:')[1].split('/') s...
def bench(n): """Just a benchmarking function for relative expected performance""" items = [x for x in range(n)] return sum([x ** 2 for x in items])
def line_or_step_plotly(interval_label): """ For a given interval_label, forecast_type determine any kwargs for the plot. """ if 'instant' in interval_label: plot_kwargs = dict() elif interval_label == 'beginning': plot_kwargs = dict(line_shape='hv') elif interval_label == 'e...
def s2b(s): """portable way to convert string to bytes. In 3.x socket.send and recv require bytes""" return s.encode()
def exp_mod(bas, exp, n): """ find $(bas ** exp) % n$ :param base: :param exp: :param n: modulous taken form https://www.geeksforgeeks.org/exponential-squaring-fast-modulo-multiplication/ """ t = 1 while (exp > 0): # for cases where exponent # is not an even value ...
def colorize(text, color_code): """ Applies the given color code to the *trunk* of the given text, that is the stripped version of the text. All leading and trailing whitespaces won't be colorized. """ if len(text) == 0: return "" # Allow the combinations of color codes. For that a...
def convert_int_to_bits(int_value, index, size): """ :param int_value: The integer value to convert to shifted bit representation. :param index: Start index of value in desired 4-byte output. Least significant bit of output is index zero. :param size: Size in bits that integer value should take up in re...
def _splitext(p, sep, altsep, extsep): """Split the extension from a pathname. Extension is everything from the last dot to the end, ignoring leading dots. Returns "(root, ext)"; ext may be empty.""" sepIndex = p.rfind(sep) if altsep: altsepIndex = p.rfind(altsep) sepIndex = ma...
def cc_stripped(x, extended=False): """ strip control characters from string """ if extended: # also strip extended characters return "".join([i for i in x if ord(i) in range(32, 126)]) return "".join([i for i in x if ord(i) in range(32, 127)])
def pod(n, p): """ Sum of pth powers of n's digits. >>> pod(123, 2) # 1**2 + 2**2 + 3**2 14 """ s = 0 while n: s += (n % 10)**p n //= 10 return s
def _stringify(item): """ Private funtion which wraps all items in quotes to protect from paths being broken up. It will also unpack lists into strings :param item: Item to stringify. :return: string """ if isinstance(item, (list, tuple)): return '"' + '" "'.join(item) + '"' i...
def merge_definitions(def_list): """Merge definitions if they are exactly equivalent or contained within each other Args: def_list (List[str]): potentially distinct definitions for same term Returns: List[str]: List of unique definitions for term """ for a_idx, a in enumerate(def_l...
def casson(x, ystress=1.0, eta_bg=0.1): """Casson Model Note: .. math:: \sigma^{0.5}= \sigma_y^{0.5} + \eta_{bg}^{0.5} Args: ystress: yield stress [Pa] eta_bg : Background viscosity [Pa s] Returns: stress : Shear Stress, [Pa] """ return (ystress ** 0.5 + (...
def less(a, b, *args): """Implements the '<' operator with JS-style type coertion.""" types = set([type(a), type(b)]) if float in types or int in types: try: a, b = float(a), float(b) except TypeError: # NaN return False return a < b and (not args or l...
def is_exception(e, string): """Check if the given exception is a known Libcloud exception with the given content.""" try: if string in e.args[0]: return True except Exception: pass return False
def types(arr): """ types(arr) will return an array of length equivalent to that of the input array This is analogous to the type() function typically carried out on a singular variable """ return [type(a) for a in arr]
def larger(x, y): """For demo purposes only; built-in max is preferable""" if x > y: return x return y
def plur_simple(cardinality: int, word: str, suffix="s"): """Pluralises words that just have a suffix if pluralised.""" if cardinality - 1: word += suffix return f"{cardinality} {word}"
def build_person(first_name, last_name): """Return a dictionary of information about a person.""" person = {'first': first_name, 'last': last_name} return person
def _partition_by_player(val, p_vec, num_players): """Partitions a value by the players vector.""" parts = [] for p in range(num_players): inds = p_vec == p if inds.size > 0: parts.append(val[inds]) else: parts.append(None) return parts
def link_cmd(path, link): """Returns link creation command.""" return " ".join(["ln", "-sfn", path, link])
def flatten_json(json_data, current_key=None, current_dict=None): """ Flatten a nested json into a Python dictionary using a recursive strategy Parameters ---------- json_data: json Data to process """ if current_dict is None: current_dict = {} if current_key is N...
def update_dictionary(dict1, dict2): """Recursively update dict1 values with those of dict2""" for key, value in dict2.items(): if key in dict1: if isinstance(value, dict): dict1[key] = update_dictionary(dict1[key], value) else: dict1[key] = value ...
def is_list_or_tuple(obj): """ Determine whether an object is an iterable list or tuple """ return isinstance(obj, (list, tuple))
def topo_bowl(x,y): """Sample topo""" z = 1000.*(x**2 + y**2 - 1.) return z
def remove_invalid_records_from_split_dictionary(split_dictionary: dict, records: dict) -> dict: """ Removes records that exist in split_dictionary but not in records. Can be useful if you previously had a video in your project and used that to make a train / val / test split, but later deleted it. """ ...
def gcd(a, b): """ Calculates the GCD of the two parameters a and b. This method loops through all the numbers between 1 and the smaller number to calculate the GCD. """ smallerNumber = a if a < b else b biggestFactor = 1 temp = 0 while temp < smallerNumber: temp += 1 ...
def binary_to_decimal(bin_string: str) -> int: """ >>> binary_to_decimal("101") 5 >>> binary_to_decimal(" 1010 ") 10 >>> binary_to_decimal("-11101") -29 >>> binary_to_decimal("0") 0 >>> binary_to_decimal("a") Traceback (most recent call last): ... ValueError: bukan ...
def get_short_imagename(imagename): """Return image-specific suffix of imagename. This excludes a possible experiment-specific prefix, such as 0001_... for trial #1. """ splits = imagename.split("_") if len(splits) > 1: name = splits[-2:] if name[0].startswith("n0"): ...
def escape_node_name(node_name: str) -> str: """Escapes any special characters in an ontology node name""" return node_name.replace(r"|", r"\|").replace(r".", r"\.")
def badadd(x : float, y : float) -> float: """Another addition test""" return x + y + 1
def expandValues(inputs, count, name): """Returns the input list with the length of `count`. If the list is [1] and the count is 3. [1,1,1] is returned. The list must be the count length or 1. Normally called from `expandParameters()` where `name` is the symbolic name of the input. """ if len(in...
def _quote_remover(key): """ Extracts the actual key of the item passed in. """ if key.startswith('"') and key.endswith('"'): return key[1:-1] if '=' in key: key = _quote_remover(''.join(key.split('=')[1:])) return key
def two_largest_attempt(A): """Failed attempt to implement two largest.""" m1 = max(A[:len(A)//2]) m2 = max(A[len(A)//2:]) if m1 < m2: return (m2, m1) return (m1, m2)
def clean(p): """Fix common small problems.""" p = p.replace('any thing', 'anything').replace('no thing', 'nothing') p = p.replace('a water', 'water') return p
def get_choice_by_value(choices, value): """ """ for choice in choices: if choice[0] == value: return choice
def oui_ou_non(flag): """Retourne 'oui' si le flag est True, 'non' sinon.""" mots = { True: "|vrc|oui|ff|", False: "|rgc|non|ff|", None: "|rgc|non|ff|", } return mots[flag]
def add_num_commas(num): """ Adds commas to a numeric string for readability. Parameters ---------- num : int or float A number to have commas added to. Retruns ------- str_with_commas : str The original number with commas to make it more readable. "...
def load_list_room_items(data, room_names): """ Loading each room respective list of items. Parameters: data(dict): Nested dictionaries containing all information of the game. room_names(list): List containg room names. Returns: items_list(list): Returns list of roo...
def is_float(value): """Check if given value is float Parameters ---------- value : variable Returns ------- bool """ if value is not None: try: float(value) return True except ValueError: return False else: return...
def argsort(seq, reverse=False): """Return indices to get sequence sorted """ # Based on construct from # http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python # Thanks! # cmp was not passed through since seems to be absent in python3 r...
def get_best(emotion_str, likely, emotion_try): """ Returns the best emotion or most likely found """ likely = likely.replace('Likelihood.', '') if likely == "VERY_LIKELY": return (emotion_str,likely) if (likely == "LIKELY" and emotion_try[1] != "VERY_LIKELY" ): return (emotion_s...
def check_collisions(x, y, collision_radius, objs): """ Checks if the position x,y collide with any obj in objs with a collision_raidus of collision_radius """ epsilon = 0.2 for obj in objs: if (obj.x - x)**2 + (obj.y - y)**2 <= \ (obj.collision_radius + collision...
def integer_color_to_rgb(color): """ Convert integer color to (r,g,b) """ return ((color >> 16) & 255, (color >> 8) & 255, color & 255)
def scaleValue(value,entry): """ :returns: a new float value that has been normalized according to the feature's domain """ if entry['domain'] is float or entry['domain'] is int: # Scale by range of possible values return float(value-entry['lo']) / float(entry['hi']-entry['lo']) elif...
def sueldo_(cargo): """Devuelve el sueldo acorde al cargo del trabajador. :param cargo: Cargo del trabajador. :cargo type: str :return: Sueldo del trabajador :rtype: int >>> sueldo_("ejecutivo") 90 """ cargo = cargo.capitalize() sueldos = { "Externo": 50, "Ejecu...
def reorder_lists(results, reorder_ix_map, table_names): """ Reorder lists in `results[table_id][bin_label]`. Required for difference tables calculated with Tax-Calculator version <0.13.0 returns: results table with reordered lists in selected tables """ def reorder(disordered): reorde...
def helper_string_array_to_list(string_): """ string_ = '{"PMID:19514844","PMID:19943898"}' ['PMID:19514844', 'PMID:19943898'] """ return [an[1:-1] for an in string_[1:-1].split(",")]
def get_item_absolute_limit(page, per_page): """Get the total possible number of items.""" return per_page * (page + 1)
def map_values(function, dictionary): """Map ``function`` across the values of ``dictionary``. :return: A dict with the same keys as ``dictionary``, where the value of each key ``k`` is ``function(dictionary[k])``. """ return {k: function(dictionary[k]) for k in dictionary}
def get_active_profile(content, key): """ Gets the active profile for the given key in the content's config object, or NONE_PROFILE """ try: if content.config.has_option(key, 'profile'): return content.config.get(key, 'profile') else: return 'None' except: ...
def get_device_mac(run_command_fn, dev_name, netns_name=None): """Find device MAC address""" if netns_name: command_prefix = "ip netns exec %s " % netns_name else: command_prefix = "" (output, _) = run_command_fn("%scat /sys/class/net/%s/address" % (comm...
def clean(header): """ (list of str) -> str Cleans each item in the header list of non-alphanumeric characters. """ clean_header = [] for item in header: item = item.replace(',', '') item = item.replace(')', '') item = item.replace('(', '') item = item.replace('|', '') item = item.replace(';', '') ...
def is_u4int(value): """ Checks if a given value is an unsigned 4-byte integer. Args: value(:mod:`int`): the value to be checked. Returns: :obj:`bool`: Whether or not the value matches the format. """ return isinstance(value, int) and 0 <= value <= pow(2, 32) - 1
def remove_doublon(this_list): """ Helper function """ return list(set(this_list))
def readQuery(query): """ reads the html returned by the query and determines if login was successful Args: query: String html result of a form submission -- from sqlzoo.net/hack username: String username of login attempt Returns: boolean true iff login was...
def hex_line8(chunk): """Create 8 bit hex string from bytes in chunk""" result = ' '.join([ '%02x' % part for part in chunk]) return result.ljust(16 * 3 - 1)
def get_id_data_abstract_role_mappings(id_data): """Get the logical and physical names of the access control roles defined by a resource group. :param id_data: - Data extracted from a custom resource's physical id by get_data_from_custom_physical_resource_id :returns A dictionary mappi...
def get_lfn_key(lfn_obj: dict) -> str: """get either lfn key or file key from a file description""" if not lfn_obj or not isinstance(lfn_obj, dict): return '' if "lfn" in lfn_obj: return lfn_obj["lfn"] if "file" in lfn_obj: return lfn_obj["file"] return ''
def prepare_profile_data(results): """ Helper function which generates acc and runtime dictionaries which contain the values for each minimizer. :param results: The sorted results grouped by row and category :type results: dict[str, dict[str, list[utils.fitbm_result.FittingResult]]] :return: d...
def get_child_parents(edges): """Puts each non-parent node together with its parents Parameters ---------- edges : list A list of tuples corresponding to the Bayesian network structure as described in the input file Returns ------- child_parents A dictionary with non-paren...
def get_road_key(waypoint): """Returns a key corresponding to the waypoint road. Equivalent to a 'Road' object and used to compare waypoint roads""" return '' if waypoint is None else str(waypoint.road_id)
def get_basic_node(name): """Utility function to generate basic node template""" curr = {"name": name, "node_attrs": {}, "branch_attrs": {}, "children": []} return curr
def get(iterable, index=None, default=None): """ Get value of an iterable by index, mainly lists, tuples and sets that don't have a `get` method, works for dict too. Returns first random value if set, returns default value if not found. """ if isinstance(iterable, set): try: return n...
def _guess_concat(data): """ Guess concat function from given data """ return { type(u''): u''.join, type(b''): bytes, }.get(type(data), list)
def popcount1(n): """No shifting and better for N0 situation""" count = 0 while n: n &= n - 1 count += 1 return count
def getDefaultParam(N: int): """Physical parameters of 2D N-Ball Balancer The N-Ball Balancer consists of N bodies: - N balls (subscript from 0 to N-1, with 0 being the ball on the bottom) - lever arm (inside ball with subscript N-1) Physical parameters that multiple bodies have are indexe...
def insertConcat(regex): """ It was easier for me to parse the regex if I had a operation for concatenation rather than just "smushing" the things together. Here I add a . everyhwere there should be a concatenation.""" noConcatAfter = ['(', '|', '.'] noConcatBefore = [')', '|', '.', '*'] newRege...
def convert_list_to_string(li): """ example: input: [0, 1, 3, 5] output: 0,1,3,5 """ return ",".join(map(str, li))
def get_lomb_signif(lomb_model): """ Get the significance (in sigmas) of the first frequency from a fitted Lomb-Scargle model. """ return lomb_model['freq_fits'][0]['signif']
def rgb_from_index(i): """Map SAM palette index to RGB tuple""" intensities = [0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff] red = intensities[(i & 0x02) | ((i & 0x20) >> 3) | ((i & 0x08) >> 3)] green = intensities[((i & 0x04) >> 1) | ((i & 0x40) >> 4) | ((i & 0x08) >> 3)] blue = intensities[((i &...
def translate_version_str2list(version_str, depth=2): """Translates a version string in format 'x[.y[.z[...]]]' into a list of numbers""" if version_str is None: ver = depth * [0, ] else: ver = [] for i in version_str.split(".")[:depth]: try: i = int(i...
def flatten(nested_list): """Convert a list with arbitrary levels of nesting to a single-level list""" return [nested_list] if not isinstance(nested_list, list) else [x for X in nested_list for x in flatten(X)]
def get_shape_columns(shape): """Return the number of columns for the shape.""" try: return shape[1] except (IndexError, TypeError): return 0
def padl(text, n, c): """ left pad of text with character c """ text = str(text) return str(c) * (n - len(text)) + text
def delta_tau_i(kappa_i, p_1, p_2, g): """ Contribution to optical depth from layer i, Malik et al. (2017) Equation 19 """ return (p_1 - p_2) / g * kappa_i
def get_percentile_plot(stat): """Get x and y for plot describing percentile of stat < x for each x. :param stat: array of int values """ stat = sorted(stat) x = [] y = [] for i in range(len(stat)): if (i == len(stat) - 1) or (stat[i] != stat[i + 1]): x.append(stat[i]) ...
def choose_package(file_type, file_name): """Choose analysis package due to file type and file extension. @param file_type: file type. @return: package or None. """ if not file_type: return None file_type = file_type.lower() file_name = file_name.lower() if "apk" in file_name: ...
def t0(M_r: float, t_r: float, n: float) -> float: """ t0 = t_r - M_r / n :param M_r: mean anomaly at t_r :type M_r: float :param t_r: reference time :type t_r: float :param n: mean movement :type n: float :return: t0 :rtype: float """ return t_r - M_r / n
def return_lowercased_string(input_string): """You have a variable called input_string that is of type string. Return it but the lowercase version of it.""" return_value = f"{input_string.lower()}" return return_value
def list2rofi(datas): """ Convert python list into a list formatted for rofi Parameters ---------- datas : list elements stored in a list Returns ------- str elements separated by line-breaks Examples -------- >>> my_list = [1,2,3,4,5,6] >>> list2rofi(...
def sort_lists(*lists): """Sort a list of lists based on the first list""" out = [[] for _ in range(len(lists))] for vals in sorted(zip(*lists)): for i, val in enumerate(vals): out[i].append(val) return tuple(out)
def apply_operators(obj, ops, op): """ Apply the list of operators `ops` to object `obj`, substituting `op` for the generator. """ res = obj for o in reversed(ops): res = o.apply(res, op) return res
def as_backup_name(name): """Transform the schema name to its backup position.""" return "$".join(("etl_backup", name))
def backward_box(box): """decrease box level (min 1) Parameters ---------- box: int question box level Returns ------- int: updated box """ if box > 1: box -= 1 return box
def default_cache_key_func(func, *args): """The default cache key function.""" return func.__module__ + '.' + func.__name__ + ':' + ':'.join([str(arg) for arg in args])
def add_table_suffix(table, suffix): """Helper to deal with backticks when adding table suffix""" table = str(table) # Hack to handle SQLAlchemy tables if table.endswith("`"): table = table.rstrip("`") + suffix + "`" else: table = table + suffix return table
def _explicit_module_name(tags): """Returns an explicit module name specified by a tag of the form `"swift_module=Foo"`. Since tags are unprocessed strings, nothing prevents the `swift_module` tag from being listed multiple times on the same target with different values. For this reason, the aspect uses th...
def merge_two_dicts(dict1, dict2): """ Helper function for merging two dictionaries into a new dictionary as a shallow copy. :param dict1: (dict) First of two dictonaries to merge :param dict2: (dict) Second dictionary :returns: Merged dictionary :rtype: dict """ merged_dict = dict1...
def _map_boolean_to_human_readable(boolean, resource, token): """ Map a boolean into a human readable representation (Yes/No). :param boolean: boolean with the value that we want to transform :param resource: resource containing all the values and keys :param token: user token """ if boolea...
def sentitel_strict_acc(y_true, y_pred): """ Calculate "strict Acc" of aspect detection task of sentitel. """ total_cases=int(len(y_true)/5) true_cases=0 for i in range(total_cases): if y_true[i*5]!=y_pred[i*5]:continue if y_true[i*5+1]!=y_pred[i*5+1]:continue if y_true[i...
def unordlist(cs): """unordlist(cs) -> str Takes a list of ascii values and returns the corresponding string. Example: >>> unordlist([104, 101, 108, 108, 111]) 'hello' """ return ''.join(chr(c) for c in cs)
def _max(iterable): """ Max is zero, even if iterable is empty >>> _max([]) 0 >>> _max([5]) 5 >>> _max([1, 2]) 2 """ try: return max(iterable) except ValueError: return 0