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(v...
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)...
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))...
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: ...
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 ...
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 = l...
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...
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....
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(...
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(le...
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...
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 ...
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),...
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 = {} ...
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: ...
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...
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"...
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....
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 ...
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,No...
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 with...
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...
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: ...
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 ...
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:...
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), ...
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 ...
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...
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': ...
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...
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, Binary...
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 r...
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 ...
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: err...
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 l...
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...
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...
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...
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...
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 set...
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 ""...
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 int...
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 tha...
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 ...
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 stor...
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) = e...
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 no...
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...
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]: ...
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 ...
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 repre...
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. """ ...
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 = t...
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 ...
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( ...
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 = ...