content
stringlengths
42
6.51k
def count_values(input_dict): """ :param input_dict: :return: Takes a dict and counts the unique values in that dict. """ value_list = [] for value in input_dict.values(): value_list.append(value) return len(set(value_list))
def to_str(value): """ A wrapper over str(), but converts bool values to lower case strings. If None is given, just returns None, instead of converting it to string "None". """ if isinstance(value, bool): return str(value).lower() if value is None: return value return str(value)
def wrap_count(method): """ Returns number of wraps around given method. """ number = 0 while hasattr(method, '__aspects_orig'): number += 1 method = method.__aspects_orig return number
def parse_port_range_list(range_list_str): """Parse a port range list of the form (start[:end])(,(start[:end]))*""" all_ranges = [] for range_str in range_list_str.split(','): if ':' in range_str: a, b = [int(x) for x in range_str.split(':')] all_ranges.extend(range(a, b + 1)) else: all_ranges.append(int(range_str)) return all_ranges
def horizon_str_to_k_and_tau(h:str): """ k=1&tau=0 -> (1,0) """ k = int(h.split('&')[0].split('=')[1]) tau = int(h.split('&')[1].split('=')[1]) return k, tau
def factorial(n): """ Returns the factorial of the given number n """ if n <= 1: return 1 return n * factorial(n - 1)
def get_header(results): """Extracts the headers, using the first value in the dict as the template.""" ret = ['name', ] values = next(iter(results.values())) for k, v in values.items(): if isinstance(v, dict): for metric in v.keys(): ret.append('%s:%s' % (k, metric)) else: ret.append(k) return ret
def deep_merge_dicts(original, incoming): """ Deep merge two dictionaries. Modifies original. For key conflicts if both values are: a. dict: Recursively call deep_merge_dicts on both values. b. anything else: Value is overridden. """ for key in incoming: if key in original: if isinstance(original[key], dict) and isinstance(incoming[key], dict): deep_merge_dicts(original[key], incoming[key]) else: original[key] = incoming[key] else: original[key] = incoming[key] return original
def split_name(name): """This method splits the header name into a source name and a flow name""" space_split = name.split(" ") upper_case = "" lower_case = "" for s in space_split: first_letter = s[0] if first_letter.isupper(): upper_case = upper_case.strip() + " " + s else: lower_case = lower_case.strip() + " " + s return (upper_case, lower_case)
def convert_to_24_hours(time, ap): """ Given a hour and an a/p specifier, then convert the hour into 24 hour clock if need be """ if ap.lower() == 'p' and time <= 12: time += 12 return time
def prune_shell(shell, use_copy=True): """ Removes exact duplicates of primitives, and condenses duplicate exponents into general contractions Also removes primitives if all coefficients are zero """ new_exponents = [] new_coefficients = [] exponents = shell['exponents'] nprim = len(exponents) # transpose of the coefficient matrix coeff_t = list(map(list, zip(*shell['coefficients']))) # Group by exponents ex_groups = [] for i in range(nprim): for ex in ex_groups: if float(exponents[i]) == float(ex[0]): ex[1].append(coeff_t[i]) break else: ex_groups.append((exponents[i], [coeff_t[i]])) # Now collapse within groups for ex in ex_groups: if len(ex[1]) == 1: # only add if there is a nonzero contraction coefficient if not all([float(x) == 0.0 for x in ex[1][0]]): new_exponents.append(ex[0]) new_coefficients.append(ex[1][0]) continue # ex[1] contains rows of coefficients. The length of ex[1] # is the number of times the exponent is duplicated. Columns represent general contractions. # We want to find the non-zero coefficient in each column, if it exists # The result is a single row with a length representing the number # of general contractions new_coeff_row = [] # so take yet another transpose. ex_coeff = list(map(list, zip(*ex[1]))) for g in ex_coeff: nonzero = [x for x in g if float(x) != 0.0] if len(nonzero) > 1: raise RuntimeError("Exponent {} is duplicated within a contraction".format(ex[0])) if not nonzero: new_coeff_row.append(g[0]) else: new_coeff_row.append(nonzero[0]) # only add if there is a nonzero contraction coefficient anywhere for this exponent if not all([float(x) == 0.0 for x in new_coeff_row]): new_exponents.append(ex[0]) new_coefficients.append(new_coeff_row) # take the transpose again, putting the general contraction # as the slowest index new_coefficients = list(map(list, zip(*new_coefficients))) shell['exponents'] = new_exponents shell['coefficients'] = new_coefficients return shell
def clean_lines(lines=[]): """Scrub filenames for checking logging output (in test_logging).""" return [l if 'Reading ' not in l else 'Reading test file' for l in lines]
def get_converter_type_default(*args, **kwargs): """ Handle converter type "default" :param args: :param kwargs: :return: return schema dict """ schema = {'type': 'string'} return schema
def dict_add(*dicts: dict): """ Merge multiple dictionaries. Args: *dicts: Returns: """ new_dict = {} for each in dicts: new_dict.update(each) return new_dict
def symbols(x: int) -> int: """ Returns length of int in symbols :param x: :return: int """ if x == 0: return 1 s = 0 if x < 0: s = 1 while x != 0: x = x // 10 s += 1 return s
def get_overlap(a, b): """ Finds out whether two intervals intersect. :param a: Two-element array representing an interval :param b: Two-element array representing an interval :return: True if the intervals intersect, false otherwise """ return max(0, min(a[1], b[1]) - max(a[0], b[0]))
def namespaced(name, namespace): """ Args: name: namespace: Returns: """ return namespace + '_' + name
def combinationSum(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ result = [] candidates = sorted(candidates) def dfs(remain, stack): if remain == 0: result.append(stack) return for item in candidates: if item > remain: break if stack and item < stack[-1]: continue else: dfs(remain - item, stack + [item]) dfs(target, []) return result
def standardise_satellite(satellite_code): """ :type satellite_code: str :rtype: str >>> standardise_satellite('LANDSAT-5') 'LANDSAT_5' """ if not satellite_code: return None return satellite_code.upper().replace('-', '_')
def varint_to_int(byte_str): """Returns the number(int/long) that was encoded in the Protobuf varint""" value = 0 size = 0 for current in byte_str: value |= (ord(current) & 0x7F) << (size * 7) size += 1 return value
def absolute_points(points): """Convert xdwapi-style point sequence in absolute coordinates.""" if len(points) < 2: return points p0 = points[0] return tuple([p0] + [p0 + p for p in points[1:]])
def each_unit_sum(number): """ :param number : :return: """ sum_value = 0 for item in str(number): sum_value += int(item) return sum_value
def green(s): """ Decorates the specified string with character codes for green text. :param s: Text to decorate with color codes. :return: String containing original text wrapped with color character codes. """ return '\033[92m{}\033[0m'.format(s)
def get_url_rels_from_releases(releases): """Returns all url-rels for a list of releases in a single list (of url-rel dictionaries) Typical usage with browse_releases() """ all_url_rels = [] for release_gid in releases.keys(): if 'url-rels' in releases[release_gid]: all_url_rels.extend([url_rel for url_rel in releases[release_gid]['url-rels']]) return all_url_rels
def _ListTypeFormatString(value): """Returns the appropriate format string for formatting a list object.""" if isinstance(value, tuple): return '({0})' if isinstance(value, set): return '{{{0}}}' return '[{0}]'
def filter_helper_and(l1, l2, l3): """ Provides and condition """ ans = set() for l in l1: if l in l2: ans.add(l) for l in l1: if l in l3: ans.add(l) for l in l2: if l in l3: ans.add(l) return list(ans)
def _jaccard(intersection, union): """Size of the intersection divided by the size of the union. Args: {intersection, union}: The intersection and union of two sets, respectively Returns: score (float): The Jaccard similarity index for these sets. """ return len(intersection) / len(union)
def calculate_length_weighted_avg(val1, length1, val2, length2): """ Calculates the length weighted average """ if val1 != None and length1 != None and val2 != None and length2 != None: a = ((float(val1)*float(length1)) + (float(val2)*float(length2))) b = (float(length1) + float(length2)) return round(a/b, 1) elif val1 != None and val2 != None: return round((val1 + val2)/2, 1)
def parse_multiple_values(val: str): """ Split a multiline string based on newlines and commas and strip leading/trailing spaces. Useful for multiple paths, names and such. Parameters ---------- val Multiline string that has individual values separated by newlines and/or commas Returns ------- list Return list of strings parsed from the input value """ lines = val.split("\n") full_list = [] for line in lines: names = [name.strip() for name in line.split(",") if name.strip()] full_list.extend(names) return full_list
def strip_prefix(name, common_prefixes): """snake_case + remove common prefix at start""" for prefix in common_prefixes: if name.startswith(prefix): return name.replace(prefix, "", 1) return name
def escape_star(v): """ """ if "*" in v: v = v.replace("*", "\\*") return v
def str_to_list(text): """ input: "['clouds', 'sky']" (str) output: ['clouds', 'sky'] (list) """ # res = [] res = [i.strip('[]\'\"\n ') for i in text.split(',')] return res
def _generate_and_write_to_file(payload, fname): """ Generates a fake but valid GIF within scriting """ f = open(fname, "wb") header = (b'\x47\x49\x46\x38\x39\x61' #Signature + Version GIF89a b'\x2F\x2A' #Encoding /* it's a valid Logical Screen Width b'\x0A\x00' #Smal Logical Screen Height b'\x00' #GCTF b'\xFF' #BackgroundColor b'\x00' #Pixel Ratio b'\x2C\x00\x00\x00\x00\x2F\x2A\x0A\x00\x00\x02\x00\x3B' #GlobalColorTable + Blocks b'\x2A\x2F' #Commenting out */ b'\x3D\x31\x3B' # enable the script side by introducing =1; ) trailer = b'\x3B' # I made this explicit, step by step . f.write(header) f.write(payload) f.write(trailer) f.close() return True
def _has_dimensions(quant, dim): """Checks the argument has the right dimensionality. Parameters ---------- quant : :py:class:`unyt.array.unyt_quantity` Quantity whose dimensionality we want to check. dim : :py:class:`sympy.core.symbol.Symbol` SI base unit (or combination of units), eg. length/time Returns ------- bool True if check successful. Examples -------- >>> import unyt as u >>> from unyt.dimensions import length, time >>> _has_dimensions(3 * u.m/u.s, length/time) True >>> _has_dimensions(3, length) False """ try: arg_dim = quant.units.dimensions except AttributeError: arg_dim = None return arg_dim == dim
def target_state(target_dict): """Converting properties to target states Args: target_dict: dictionary containing target names as keys and target objects as values Returns: dictionary mapping target name to its state """ if {} == target_dict: return None result = {} for key, value in target_dict.iteritems(): if not value.repaired: result[key] = "cut" elif value.targetable: result[key] = "targetable" else: result[key] = "untargetable" return result
def recursive_detach(in_dict: dict, to_cpu: bool = False) -> dict: """Detach all tensors in `in_dict`. May operate recursively if some of the values in `in_dict` are dictionaries which contain instances of `torch.Tensor`. Other types in `in_dict` are not affected by this utility function. Args: in_dict: Dictionary with tensors to detach to_cpu: Whether to move tensor to cpu Return: out_dict: Dictionary with detached tensors """ out_dict = {} for k, v in in_dict.items(): if isinstance(v, dict): v = recursive_detach(v, to_cpu=to_cpu) elif callable(getattr(v, 'detach', None)): v = v.detach() if to_cpu: v = v.cpu() out_dict[k] = v return out_dict
def substringp(thing1, thing2): """ SUBSTRINGP thing1 thing2 SUBSTRING? thing1 thing2 if ``thing1`` or ``thing2`` is a list or an array, outputs FALSE. If ``thing2`` is a word, outputs TRUE if ``thing1`` is EQUALP to a substring of ``thing2``, FALSE otherwise. """ return type(thing2) is str and type(thing1) is str \ and thing2.find(thing1) != -1
def parallelizable_function(agent): """ This is an upside-down parabola in 2D with max value at (z = (x, y) = 5 = (0, 0)). """ x = agent[0] y = agent[1] return (-1.2 * x**2) - (0.75 * y**2) + 5.0
def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats. Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ... Otherwise None """ if str(value).lower() in ("yes", "y", "true", "t", "1"): return True elif str(value).lower() in ("no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False else: return None
def _NamedNodeMap___isEqualMap(self, other): """ Test whether two maps have equal contents, though possibly in a different order. """ if other is None: return False if len(self._list)!=len(other._list): return False for selfItem in self._list: for otherItem in other._list: if selfItem.isEqualNode(otherItem): break else: return False return True
def has_field(obj, field): """Check if an object has a certain attribute, or if a dictionary has a certain key. :param obj: the data object :type obj: object or dict :param field: the field name :type field: str :returns: True if the object has the field, False otherwise :rtype: bool """ if isinstance(obj, dict): # Object is a dictionary. return field in obj else: # Object is an instance. return hasattr(obj, field)
def clean_name(name): """" Clean up the name of the location. """ name = name.strip() name = name.replace('NWR', 'National Wildlife Refuge') return name
def path_parse(s): """Parses paths given to the function, returns tuple (mode, user, host, path)""" if type(s) == tuple: fullpath = s[0].split("@") #ou partition elif type(s) == list: fullpath = s else: fullpath = s.split("@") if len(fullpath) == 1: return 1,None, None, fullpath[0] # integer 1 signals to local path elif len(fullpath) == 2: # we split distant@localhost:path user = fullpath[0] # contains distant host_path = fullpath[1] # contains localhost:path if host_path.count("::") >= 1: # if double colon is present we enter daemon mode temp = host_path.split("::") host = temp[0] # contains localhost path = temp[1] # contains path return 3, user, host, path # integer 3 signals daemon mode else: temp = host_path.split(":") host = temp[0] # contains localhost path = temp[1] # contains path return 2, user, host, path
def split_timestamp(string): """ Split timestamp in German form """ year = int(string.split(".")[2]) month = int(string.split(".")[1]) day =int(string.split(".")[0]) return year, month, day
def is_in_range(val, range_min, range_max): """ Checks if the specified value is within the given range. :param (int, float) val: Value to be evaluated. :param (int, float) range_min: Range lower value. :param (int, float) range_max: Range higher value. :return: Returns true if the value is within the range and false otherwise. :rtype: bool """ return True if range_min <= val <= range_max else False
def scrub_category_val(category_val): """Make sure that category val is a string with positive length.""" if not isinstance(category_val, str): category_val = str(category_val) if category_val.lower() == 'nan': category_val = 'NaN' if not category_val: category_val = 'NaN' return category_val
def format_currency(amount): """Convert float to string currency with 2 decimal places.""" str_format = str(amount) cents = str_format.split('.')[1] if len(cents) == 1: str_format += '0' return '{0} USD'.format(str_format)
def calc_pident(a, b): """ calculate percent identity """ m = 0 # matches mm = 0 # mismatches for A, B in zip(list(a), list(b)): if A == '.' or B == '.': continue if A == '-' and B == '-': continue if A == B: m += 1 else: mm += 1 try: return float(float(m)/float((m + mm))) * 100 except: return 0
def is_oppo_clearance_from_self_pass(event_list, team): """Returns whether an opponent cleared the ball after self was passing""" clearance = False self_pass = False for e in event_list[:2]: if e.type_id == 12 and e.team != team: clearance = True if e.type_id == 1 and e.team == team: self_pass = True return clearance and self_pass
def build_resource(properties): """Builds YouTube resource. Builds YouTube resource for usage with YouTube Data API. Source: `YouTube Data API Reference <https://developers.google.com/youtube/v3/docs/>`_. Args: properties (dict): Compact resource representation. Returns: dict: Expanded resource ready for use. """ resource = {} for p in properties: # Given a key like "snippet.title", split into "snippet" and "title", where # "snippet" will be an object and "title" will be a property in that object. prop_array = p.split('.') ref = resource for pa in range(0, len(prop_array)): is_array = False key = prop_array[pa] # For properties that have array values, convert a name like # "snippet.tags[]" to snippet.tags, and set a flag to handle # the value as an array. if key[-2:] == '[]': key = key[0:len(key)-2:] is_array = True if pa == (len(prop_array) - 1): # Leave properties without values out of inserted resource. if properties[p]: if is_array: ref[key] = properties[p].split(',') else: ref[key] = properties[p] elif key not in ref: # For example, the property is "snippet.title", but the resource does # not yet have a "snippet" object. Create the snippet object here. # Setting "ref = ref[key]" means that in the next time through the # "for pa in range ..." loop, we will be setting a property in the # resource's "snippet" object. ref[key] = {} ref = ref[key] else: # For example, the property is "snippet.description", and the resource # already has a "snippet" object. ref = ref[key] return resource
def apply_values(function, mapping): """\ Applies ``function`` to a sequence containing all of the values in the provided mapping, returing a new mapping with the values replaced with the results of the provided function. >>> apply_values( ... lambda values: map(u'{} fish'.format, values), ... {1: 'red', 2: 'blue'}, ... ) {1: u'red fish', 2: u'blue fish'} """ if not mapping: return {} keys, values = zip(*mapping.items()) return dict(zip(keys, function(values)))
def gen_key(uid, section='s'): """ Generate store key for own user """ return f'cs:{section}:{uid}'.encode()
def _make_old_git_changelog_format(line): """Convert post-1.8.1 git log format to pre-1.8.1 git log format""" if not line.strip(): return line sha, msg, refname = line.split('\x00') refname = refname.replace('tag: ', '') return '\x00'.join((sha, msg, refname))
def xor(*args): """Implements logical xor function for arbitrary number of inputs. Parameters ---------- args : bool-likes All the boolean (or boolean-like) objects to be checked for xor satisfaction. Returns --------- output : bool True if and only if one and only one element of args is True and the rest are False. False otherwise. """ output = sum(bool(x) for x in args) == 1 return output
def convert_to_list(xml_value): """ An expected list of references is None for zero values, a dict for one value, and a list for two or more values. Use this function to standardize to a list. If individual items contain an "@ref" field, use that in the returned list, otherwise return the whole item Args: xml_value (dict or list): value to transform to a list Returns: list: processed list of values from original xml_value """ if not xml_value: return [] elif isinstance(xml_value, dict): return [xml_value.get('@ref', xml_value)] else: return [val.get('@ref', val) for val in xml_value]
def arg_changer(hash_type): """Returns the hash type indicator for the tools""" if hash_type == "md5": return "raw-md5-opencl", 0 elif hash_type == 'md4': return "raw-md4-opencl", 900 elif hash_type == 'sha1': return "raw-sha1-opencl", 100 elif hash_type == 'sha-256': return "raw-sha256-opencl", 1400 elif hash_type == 'sha-512': return "raw-sha512-opencl", 1700 elif hash_type == 'md5crypt': return 'md5crypt-opencl', 500
def ind2(e,L): """returns the index of an element in a list""" def indHelp(e,L,c): if(c==len(L)): return c if(e==True): return c if(e == L[c]): return c return indHelp(e,L,c+1) return indHelp(e,L,0)
def degree_to_direction(degree): """ Translates degree to direction :param degree: 0, 90, 180 or 270# :return: 'N', 'E', 'S', or 'W' """ if degree == 0: return 'N' elif degree == 90: return 'E' elif degree == 180: return 'S' else: return 'W'
def game_hash(board): """ Returns a hash value representing the board such that: game_hash(B1) == game_hash(B2) <=> B1 is a rotation/reflection of B2 """ INDICES = ((0,1,2,3,4,5,6,7,8,9,10,11), (11,10,9,8,7,6,5,4,3,2,1,0), (8,9,10,11,4,5,6,7,0,1,2,3), (3,2,1,0,7,6,5,4,11,10,9,8)) return min(sum(board[i]<<(e*2) for e,i in enumerate(I)) for I in INDICES)
def list_longest_path(node): """ List the value in a longest path of node. @param BinaryTree|None node: tree to list longest path of @rtype: list[object] >>> list_longest_path(None) [] >>> list_longest_path(BinaryTree(5)) [5] >>> b1 = BinaryTree(7) >>> b2 = BinaryTree(3, BinaryTree(2), None) >>> b3 = BinaryTree(5, b2, b1) >>> list_longest_path(b3) [5, 3, 2] """ # node is None if node is None: return [] # base case, no left and right children elif node.left is None and node.right is None: return [node.value] # have children else: longest = [] path = list_longest_path(node.left) if len(path) > len(longest): longest = path path2 = list_longest_path(node.right) if len(path2) > len(longest): longest = path2 return [node.value] + longest
def qualified_name(cls): """Does both classes and class instances :param cls: The item, class or class instance :return: fully qualified class name """ try: return cls.__module__ + "." + cls.name except AttributeError: return cls.__module__ + "." + cls.__name__
def membercheck(entry): """ This function checks if there is an entry like "4 Mitglieder", which appears sometimes in the data. """ if entry['funct'] == "Mitglieder" and (entry["firstName"].isdigit() or entry["lastName"].isdigit()): return 1 return 0
def is_should_create(exists, expected, create_anyway): """If we should create a resource even if it was supposed to exist. :param exists: Whether we found the resource in target API. :param expected: Whether we expected to find the resource in target API. :param create_anyway: If we should create the resource, even though it was supposed to exist and did not. :return: """ return (not exists and not expected) or \ (not exists and expected and create_anyway)
def create_primes_3(max_n): """ using sieve of sundaram: http://en.wikipedia.org/wiki/Sieve_of_Sundaram The description was really understandable """ limit = max_n + 1 sieve = [True] * (limit) sieve[1] = False for i in range(1, limit//2): f = 2 * i + 1 for j in range(i, limit//2): k = i + j * f if k <= max_n: sieve[k] = False else: break return [2,3]+[2*k+1 for k in range(1, int(max_n/2)) if sieve[k]]
def _reorder_bounds(bounds): """Reorder bounds from shapely/fiona/rasterio order to the one expected by Overpass, e.g: `(x_min, y_min, x_max, y_max)` to `(lat_min, lon_min, lat_max, lon_max)`. """ lon_min, lat_min, lon_max, lat_max = bounds return lat_min, lon_min, lat_max, lon_max
def case2name(case): """ Convert case into name """ s = case.split(" ") s = [q for q in s if q] # remove empty strings return "_".join(s)
def append_lines(file, lines, encoding=None, errors=None): """Append the lines to a file. :param file: path to file or file descriptor :type file: :term:`path-like object` or int :param list(str) lines: list of strings w/o newline :param str encoding: name of the encoding :param str errors: error handler :return: number of characters written :rtype: int :raises OSError: on I/O failure .. versionchanged:: 0.6.0 Add parameter ``errors`` """ with open(file, 'a', encoding=encoding, errors=errors) as fh: cnt = fh.write('\n'.join(lines)) cnt += fh.write('\n') return cnt
def project_scope_to_namespace(scope, namespace): """Proyecta un scope al namespace de una expresion""" if scope is None: return None return set([x for x in scope if str(x.var.token) in namespace])
def create_api_string(x, y): """Create the portainer api string. Creates the string for connection to the portainer api host. Args: x: Command line arguments (sys.args). y: Number of required command line arguments Returns: The portainer connection string. """ if len(x) - 1 == y: return 'http://portainer:9000/api' else: return 'http://' + x[len(x) -1] + ':9000/api'
def parse_identifier(expr: str, pos: int): """ Parses an identifier. Which should match /[a-z_$0-9]/i """ ret = expr[pos] pos = pos + 1 while pos < len(expr): char_ord = ord(expr[pos]) if not ((char_ord >= 48 and char_ord <= 57) or (char_ord >= 65 and char_ord <= 90) or (char_ord >= 97 and char_ord <= 122) or char_ord == 36 or char_ord == 95): break ret += expr[pos] pos = pos + 1 return ret, pos
def split_trailing_whitespace(word): """ This function takes a word, such as 'test\n\n' and returns ('test','\n\n') """ stripped_length = len(word.rstrip()) return word[0:stripped_length], word[stripped_length:]
def oauth_config_loader(config: dict): """ Loads the key configuration from the default location :return: """ assert config is not None return config.get('user_authentication', {}).get('oauth'), config.get('keys')
def _listify_ips(ip_str): """Breaks a string encoding a list of destinations into a list of destinations Args: ip_str (str): A list of destination hosts encoded as a string Returns: list: A list of destination host strings """ if ip_str.startswith('['): return [x.strip() for x in ip_str.lstrip('[').rstrip(']').split(',')] return [ip_str]
def round_floats(value): """ Round all floating point values found anywhere within the supplied data structure, recursing our way through any nested lists, tuples or dicts """ if isinstance(value, float): return round(value, 9) elif isinstance(value, list): return [round_floats(i) for i in value] elif isinstance(value, tuple): return tuple(round_floats(i) for i in value) elif isinstance(value, dict): return {k: round_floats(v) for (k, v) in value.items()} else: return value
def find_stem(arr): """Find longest common substring in array of strings. From https://www.geeksforgeeks.org/longest-common-substring-array-strings/ """ # Determine size of the array n_items_in_array = len(arr) # Take first word from array as reference reference_string = arr[0] n_chars_in_first_item = len(reference_string) res = "" for i_char in range(n_chars_in_first_item): # Generate all starting substrings of our reference string stem = reference_string[:i_char] j_item = 1 # Retained in case of an array with only one item for j_item in range(1, n_items_in_array): # Check if the generated stem is common to to all words if not arr[j_item].startswith(stem): break # If current substring is present in all strings and its length is # greater than current result if (j_item + 1 == n_items_in_array) and (len(res) < len(stem)): res = stem return res
def distributed_opts_id(params: dict): """ Formatter to display distributed opts in test name. Params ------ A dictionary containing `batch_size`, `n_cpus` and `actor_cpu_fraction` as keys. """ fmt = 'batch_size={} n_cpus={} actor_cpu_fraction={}' return fmt.format(*list(params.values()))
def is_setting_key(key: str) -> bool: """Check whether given key is valid setting key or not. Only public uppercase constants are valid settings keys, all other keys are invalid and shouldn't present in Settings dict. **Valid settings keys** :: DEBUG SECRET_KEY **Invalid settings keys** :: _PRIVATE_SECRET_KEY camelCasedSetting rel secret_key :param key: Key to check. """ return key.isupper() and key[0] != "_"
def lr_schedule(epoch): """Learning Rate Schedule Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every epoch as part of callbacks during training. # Arguments epoch (int): The number of epochs # Returns lr (float32): learning rate """ lr = 0.0003 if epoch > 800: lr *= 0.5e-3 elif epoch > 600: lr *= 1e-3 elif epoch > 400: lr *= 1e-2 elif epoch > 200: lr *= 1e-1 print('Learning rate: ', lr) return lr
def human_duration(duration_seconds: float) -> str: """Convert a duration in seconds into a human friendly string.""" if duration_seconds < 0.001: return '0 ms' if duration_seconds < 1: return '{} ms'.format(int(duration_seconds * 1000)) return '{} s'.format(int(duration_seconds))
def get_pyramid_single(xyz): """Determine to which out of six pyramids in the cube a (x, y, z) coordinate belongs. Parameters ---------- xyz : numpy.ndarray 1D array (x, y, z) of 64-bit floats. Returns ------- pyramid : int Which pyramid `xyz` belongs to as a 64-bit integer. Notes ----- This function is optimized with Numba, so care must be taken with array shapes and data types. """ x, y, z = xyz x_abs, y_abs, z_abs = abs(x), abs(y), abs(z) if (x_abs <= z) and (y_abs <= z): # Top return 1 elif (x_abs <= -z) and (y_abs <= -z): # Bottom return 2 elif (z_abs <= x) and (y_abs <= x): # Front return 3 elif (z_abs <= -x) and (y_abs <= -x): # Back return 4 elif (x_abs <= y) and (z_abs <= y): # Right return 5 else: # (x_abs <= -y) and (z_abs <= -y) # Left return 6
def is_member(user, groups): """ Test if a user belongs to any of the groups provided. This function is meant to be used by the user_passes_test decorator to control access to views. Parameters ---------- user : django.contrib.auth.models.User The user which we are trying to identify that belongs to a certain group. groups : list of str A list of the groups we are checking if the user belongs to. Returns --------- bool True if the user belongs to any of the groups. False otherwise """ return any(map(lambda g: user.groups.filter(name=g).exists(), groups))
def split_identifier(identifier, ignore_error=False): """ Split Identifier. Does not throw exception anymore. Check return, if None returned, there was an error :param identifier: :param ignore_error: :return: """ prefix = None identifier_processed = None separator = None if ':' in identifier: prefix, identifier_processed = identifier.split(':', 1) # Split on the first occurrence separator = ':' elif '-' in identifier: prefix, identifier_processed = identifier.split('-', 1) # Split on the first occurrence separator = '-' else: if not ignore_error: # not sure how to logger from imported function without breaking logger in main function # logger.critical('Identifier does not contain \':\' or \'-\' characters.') # logger.critical('Splitting identifier is not possible.') # logger.critical('Identifier: %s', identifier) print('Identifier does not contain \':\' or \'-\' characters.') print('Splitting identifier is not possible.') print('Identifier: %s' % (identifier)) prefix = identifier_processed = separator = None return prefix, identifier_processed, separator
def get_mongolike(d, key): """ Retrieve a dict value using dot-notation like "a.b.c" from dict {"a":{"b":{"c": 3}}} Args: d (dict): the dictionary to search key (str): the key we want to retrieve with dot notation, e.g., "a.b.c" Returns: value from desired dict (whatever is stored at the desired key) """ lead_key = key.split(".", 1)[0] try: lead_key = int(lead_key) # for searching array data except: pass if "." in key: remainder = key.split(".", 1)[1] return get_mongolike(d[lead_key], remainder) return d[lead_key]
def config_default_option(config, key, getbool=False): """ Get default-level config option """ if config is None: return None section = 'defaults' if not section in config: return None return config[section].get(key, None) if not getbool else config[section].getboolean(key)
def extended_euclidean_algorithm(a, b): """extended_euclidean_algorithm: int, int -> int, int, int Input (a,b) and output three numbers x,y,d such that ax + by = d = gcd(a,b). Works for any number type with a divmod and a valuation abs() whose minimum value is zero """ if abs(b) > abs(a): (x, y, d) = extended_euclidean_algorithm(b, a) return (y, x, d) if abs(b) == 0: return (1, 0, a) x1, x2, y1, y2 = 0, 1, 1, 0 while abs(b) > 0: q, r = divmod(a, b) x = x2 - q * x1 y = y2 - q * y1 a, b, x2, x1, y2, y1 = b, r, x1, x, y1, y return (x2, y2, a)
def query2dict(query): """Convert a query from string into Python dict. """ query = query.split("&") _dict = {} for pair in query: key, value = pair.split("=", 1) _dict[key] = value return _dict
def get_max_sum(l): """ Create a list of lists - every sublist has on each 'i' position the maximum sum that can be made [with, without] the 'i' element Observations: 1) if the list contains only negative numbers => sum = 0 2) could be completed using only 3 variables """ if not len(l): return None if len(l) == 1: return l[0] if len(l) == 2: return max(l) f = [[l[0], 0], [l[1], max([l[0], 0])]] for e in l[2:]: f.append([e + max(f[-2]), max(f[-1])]) return max(f[-1])
def filterRequestReturnValue(requestResult: int, *args: int) -> bool: """ Filter function for filtering the results array to successes, warnings, errors """ for mod in args: if not requestResult % mod: return True return False
def dotprod(u,v): """ Simple dot (scalar) product of two lists of numbers (assumed to be the same length) """ result = 0.0 for i in range (0,len(u)): result = result + (u[i]*v[i]) return result
def four_seasons(T): """ >>> four_seasons([-3, -14, -5, 7, 8, 42, 8, 3]) 'SUMMER' >>> four_seasons([2, -3, 3, 1, 10, 8, 2, 5, 13, -5, 3, -18]) 'AUTUMN' """ count = len(T) // 4 winter_ampli = max(T[:count:]) - min(T[:count:]) spring_ampli = max(T[count:count*2:]) - min(T[count:count*2:]) summer_ampli = max(T[count*2:count*3:]) - min(T[count*2:count*3:]) autumn_ampli = max(T[count*3::]) - min(T[count*3::]) max_ampli = winter_ampli season = "WINTER" if (spring_ampli > max_ampli): max_ampli = spring_ampli season = "SPRING" if (summer_ampli > max_ampli): max_ampli = summer_ampli season = "SUMMER" if (autumn_ampli > max_ampli): max_ampli = autumn_ampli season = "AUTUMN" return season
def deduplicate(sequence): """ Return a list with all items of the input sequence but duplicates removed. Leaves the input sequence unaltered. """ return [element for index, element in enumerate(sequence) if element not in sequence[:index]]
def is_collection(collection): """Return ``True`` if passed object is Collection and ``False`` otherwise.""" return type(collection).__name__ == "Collection"
def complement_strand(dna): """ Finds the reverse complement of a dna. Args: dna (str): DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T'). Returns: str: the reverse complement string of a dna. """ reverse_complement = "" for character in dna[::-1]: if character == "A": reverse_complement += "T" elif character == "T": reverse_complement += "A" elif character == "C": reverse_complement += "G" elif character == "G": reverse_complement += "C" return reverse_complement
def calc_confidence(freq_set, H, support_data, rules, min_confidence=0.5, verbose=False): """Evaluates the generated rules. One measurement for quantifying the goodness of association rules is confidence. The confidence for a rule 'P implies H' (P -> H) is defined as the support for P and H divided by the support for P (support (P|H) / support(P)), where the | symbol denotes the set union (thus P|H means all the items in set P or in set H). To calculate the confidence, we iterate through the frequent itemsets and associated support data. For each frequent itemset, we divide the support of the itemset by the support of the antecedent (left-hand-side of the rule). Parameters ---------- freq_set : frozenset The complete list of frequent itemsets. H : list A list of frequent itemsets (of a particular length). min_support : float The minimum support threshold. rules : list A potentially incomplete set of candidate rules above the minimum confidence threshold. min_confidence : float The minimum confidence threshold. Defaults to 0.5. Returns ------- pruned_H : list The list of candidate rules above the minimum confidence threshold. """ pruned_H = [] # list of candidate rules above the minimum confidence threshold for conseq in H: # iterate over the frequent itemsets conf = support_data[freq_set] / support_data[freq_set - conseq] if conf >= min_confidence: rules.append((freq_set - conseq, conseq, conf)) pruned_H.append(conseq) if verbose: print(("" \ + "{" \ + "".join([str(i) + ", " for i in iter(freq_set-conseq)]).rstrip(', ') \ + "}" \ + " ---> " \ + "{" \ + "".join([str(i) + ", " for i in iter(conseq)]).rstrip(', ') \ + "}" \ + ": conf = " + str(round(conf, 3)) \ + ", sup = " + str(round(support_data[freq_set], 3)))) return pruned_H
def show_test_results(test_name, curr_test_val, new_test_val): """ This function prints the test execution results which can be passed or failed. A message will be printed on screen to warn user of the test result. :param test_name: string representing test name :param curr_test_val: integer representing number of tests failed so far before the test specified in test_name is executed :param new_test_val: integer representing number of tests failed after the test specified in test_name is executed :return: integer: 0 if test passed and 1 if test faild. """ failed_string = "Ooops, " + test_name + " failed. I am sorry..." pass_string = "Yeah, " + test_name + " passed!" if (curr_test_val < new_test_val): # this test has failed print(failed_string) return 1 else: print(pass_string) return 0
def ProtoFileCanonicalFromLabel(label): """Compute path from API root to a proto file from a Bazel proto label. Args: label: Bazel source proto label string. Returns: A string with the path, e.g. for @envoy_api//envoy/type/matcher:metadata.proto this would be envoy/type/matcher/matcher.proto. """ assert (label.startswith('@envoy_api_canonical//')) return label[len('@envoy_api_canonical//'):].replace(':', '/')
def to_tuple(collection): """ Return a tuple of basic Python values by recursively converting a mapping and all its sub-mappings. For example:: >>> to_tuple({7: [1,2,3], 9: {1: [2,6,8]}}) ((7, (1, 2, 3)), (9, ((1, (2, 6, 8)),))) """ if isinstance(collection, dict): collection = tuple(collection.items()) assert isinstance(collection, (tuple, list)) results = [] for item in collection: if isinstance(item, (list, tuple, dict)): results.append(to_tuple(item)) else: results.append(item) return tuple(results)
def find_end(a, x): """ Determines pointer to end index. :type nums: list[int] :type a: int :rtype: int """ l = 0 r = len(a) - 1 # Executes binary search while (l + 1) < r: m = l + (r - l) // 2 # Determines first appearance of target if (a[m] == x and a[m+1] != x): return m # Determines if target in left-half elif a[m] > x: r = m # Determines if target in right-half else: l = m + 1 # Determines target start at right index if a[r] == x: return r # Determines target start at left index else: return l
def render_html(result): """ builds html message :return: """ html_table = """ <table border="1" cellpadding="0" cellspacing="0" bordercolor=#BLACK> """ html_header = """<tr> <td> Jobs Status </td> </tr>""" # Make <tr>-pairs, then join them. # html += "\n".join( # map( # lambda x: """ # <td style="width: 175px;"> # """ + str(result) + "</td>", 1) # ) html_result = f"<tr> <td> {result} </td> </tr></table> <br><br>" html = html_table + html_header + html_result return html
def getBasePV(PVArguments): """ Returns the first base PV found in the list of PVArguments. It looks for the first colon starting from the right and then returns the string up until the colon. Takes as input a string or a list of strings. """ if type(PVArguments) != list: PVArguments = [PVArguments] for arg in PVArguments: try: i = arg.rindex(":") return arg[:i+1] except: pass return None