content
stringlengths
42
6.51k
def cap_absolute_value(value, max_absolute_value=1): """ Returns `value` with absolute value capped at `max_absolute_value`. Particularly useful in passing values to trignometric functions where numerical errors may result in an argument > 1 being passed in. This code is modified from the pyma...
def used_cached_results(metadata): """ Modified from: https://github.com/broadinstitute/dsde-pipelines/blob/develop/scripts/calculate_cost.py """ return ( "callCaching" in metadata and "hit" in metadata["callCaching"] and metadata["callCaching"]["hit"] )
def are_same_length(list1, list2) -> bool: """Return True if length of two lists are the same. Args: list1 (list or tuple): a list to be checked. list2 (list or tuple): a list to be checked. Returns: bool: True if length of two lists are the same. """ return len(list1) == l...
def remove_duplicates(results:list) -> list: """ Ensures that the hit_id in each result is unique """ hits = set() l = [] for d in results: hit_id = d.get('hit_id') if hit_id not in hits: hits.add(hit_id) l.append(d) return l
def _prioritize_pes(choices): """Prioritize and deprioritize paired environments based on names. We're looking for multiprocessing friendly environments, so prioritize ones with SMP in the name and deprioritize those with MPI. """ # lower scores = better ranks = {"smp": -1, "mpi": 1} sort_c...
def spt_pre_sequencing(dataset, *args, **kwargs): """ Generates an initial job sequence based on the shortest-processing-time dispatching strategy. The job sequence will be feed to the model. """ sequence = [] for job in dataset.values(): if sequence == []: sequence.appen...
def argsort_list(seq): """Returns indices such that the list is sorted. Example: argsort_list([2, 1, 3]) = [1, 0, 2]. """ return sorted(range(len(seq)), key=seq.__getitem__)
def plaintext(target): """ Returns `target` string stripped of non-ASCII characters. """ return "".join([c for c in target if ord(c) < 128])
def get_face_names_from_indices(mesh, indices): """ Returns a list of face names from a given list of face indices :param mesh: str :param indices: list(int) :return: list(str) """ found_face_names = list() for index in indices: face_name = '{}.f[{}]'.format(mesh, index) ...
def bubbleSort_decr(array): """ It repeatedly swaps adjacent elements that are out of order it has O(n2) time complexity smaller numbers are sorted first """ for i in range(len(array)): for j in range(len(array)-i-1): if array[j] < array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array
def key_type_validator(x): """ Property: KeySchema.KeyType """ valid_types = ["HASH", "RANGE"] if x not in valid_types: raise ValueError("KeyType must be one of: %s" % ", ".join(valid_types)) return x
def split_clusters(clusters): """Increase number of clusters 2x by splitting """ result = [] for cluster in clusters: even = cluster[0::2] odd = cluster[1::2] assert len(even) + len(odd) == len(cluster) if even: result.append(even) if odd: ...
def power(x, y): """ Initialize the result because x pow 0 = 1 , so this is the base condition.""" result = 1 while y > 0: """ Check weather y is an odd number. """ """ If y is odd number then multiply only once starting from the base condition. """ # x with result if (y & 1...
def bytes_fmt(value, precision=2): """Represent bytes value in a human-readable format.""" for units in ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'): if value < 1024 or units == 'YB': if units != 'B' or isinstance(value, float): # float = rate (B/s) value = round(value, precision) return '{} {}'...
def get_slope(r, sy, sx): """ Get the slope for a regression line having given parameters. Parameters ---------- > `r`: regrwssion coefficient of the line > `sy` sample standard deviation of y distribution > `sx`: sample standard deviation of x distribution Returns ------- The slope of the given...
def format_fuzzy_result(hits): """ format search result @param hits: searched parts @type hists: list @return part informaions @rtype: list """ part_list = list() for item in hits: info = item['_source'] part_info = { 'part_name' : info['part_name'], ...
def bump_version(version: str, mode: str) -> str: """given a version string will bump accordying to mode Eg. bump_version("1.0.3", "micro") -> "1.0.4" bump_version("1.0.3", "minor") -> "1.1.0" """ newver = [int(n) for n in version.split(".")] if mode == "major": ...
def PrettyOS(os, os_v1=None, os_v2=None, os_v3=None, os_v4=None): """Pretty os string.""" if os_v4: return '%s %s.%s.%s.%s' % (os, os_v1, os_v2, os_v3, os_v4) if os_v3: if os_v3[0].isdigit(): return '%s %s.%s.%s' % (os, os_v1, os_v2, os_v3) else: return '%s %s...
def path_to_edges(p: list): """ :param p: a path in a graph :return: all edges in the path p """ if len(p) == 1: return [(p[0], p[0])] e = [(p[i-1], p[i]) for i in range(len(p)) if i > 0] return e
def lmap(v, x, y) -> float: """Linear map of value v with range x to desired range y.""" return y[0] + (v - x[0]) * (y[1] - y[0]) / (x[1] - x[0])
def rotate_clockwise(array_2d): """ Code copied by: https://stackoverflow.com/a/48444999/3753724 """ list_of_tuples = zip(*array_2d[::-1]) return [list(elem) for elem in list_of_tuples]
def CreateResourceName(parent, collection, resource_id): """Creates the full resource name. Args: parent: The project or organization id as a resource name, e.g. 'projects/my-project' or 'organizations/123'. collection: The resource collection. e.g. 'logs' resource_id: The id within the collectio...
def round_percent(num): """Return a customercare-format percentage from a number.""" return round(num, 1) if num < 10 else int(round(num, 0))
def midpoint_point_point(a, b): """Compute the midpoint of two points lying in the XY-plane. Parameters ---------- a : sequence of float XYZ coordinates of the first point. b : sequence of float XYZ coordinates of the second point. Returns ------- list XYZ coord...
def simplified_env_name(env_name: str) -> str: """Get the simplified version of a gym environment name. In more details, if the given environment name contains the name of the exporting module, that module information is removed. For example: 'mymodule:MyEnv-v0' becomes 'MyEnv-v0'. Args: ...
def default_filter(files): """Function to filter folders based on content Parameters ---------- files : list A list containing strings of filenames in directory Returns ------- bool : a flag indicating whether the list contains '1.mkv', '2.mkv' and 'Labels.json' ...
def round_margin(margin: float, threshold: float) -> int: """Round margin according to threshold :param margin: calculated margin :param threshold: threshold for rounding :return: rounded margin """ root = int(margin) if threshold < margin - root: return root + 1 else: r...
def rivers_with_station(stations): """Create's a list of rivers from a list of Monitoring Stations""" RiversSet = set() for station in stations: RiversSet.add(station.river) return RiversSet
def _skewtent_onestep(value, threshold): """ Computes a single step of iteration through the skew-tent map given an input (previous) value and a threshold. Returns the next value as output. This function is called by _iterate_skewtent for iterating repeatedly. Parameters ---------- value : ...
def empty_bytearray(preallocate: int) -> bytearray: """ Returns bytearray that won't allocate for at least `preallocate` bytes. Useful in case you want to avoid allocating too often. """ b = bytearray(preallocate) b[:] = bytes() return b
def is_floating_number(number): """ is_floating_number :param number: :return: :rtype: boolean """ is_float = False try: float(number) is_float = True # except TypeError: # return False except ValueError: is_float = False return is_float
def adjust_ranges(bands, freq): """ The bands and frequencies are adjusted so that the first and last frequencies in the range are non-zero. :param bands: The bands dictionary. :param freq: The frequency dictionary. :return: Adjusted bands and frequencies. """ # Get the indices of the f...
def UInt64(value): """Encode a 64-bit integer value""" return value.to_bytes(8, 'big')
def moving_avg(v, N): """ simple moving average. Parameters ---------- v : list data ta to average N : integer number of samples per average. Returns ------- m_avg : list averaged data. """ s, m_avg = [0], [] for i, x in enumerat...
def _not_in(input, values): """Checks if the given input is not in the list of values :param input: The input to check :type input: int/float/string :param values: The values to check :type values: :func:`list` :returns: True if the condition check passes, False otherwise :rtype: bool "...
def cropRect(rect, cropTop, cropBottom, cropLeft, cropRight): """ Crops a rectangle by the specified number of pixels on each side. The input rectangle and return value are both a tuple of (x,y,w,h). """ # Unpack the rectangle x, y, w, h = rect # Crop by the specified value x += cropLeft y += cropTop w ...
def lpph2lpmm(lpph, n, pixelPitch): """Convert resolution specified in Line-Pair per Picture Height (LPPH) to Line-Pair per Milli Meters (LPMM) Parameters ---------- lpph : float resolution in terms of Line-Pair per Picture Height (LPPH) n : integer Number of pixels in the pictu...
def format_repr(obj, max_len=50, ellipsis="..."): """Wrapper around `repr()` to print shortened and formatted string version. obj: The object to represent. max_len (int): Maximum string length. Longer strings will be cut in the middle so only the beginning and end is displayed, separated by ellipsi...
def strength(x): """ :param x [x, y, z, k, g] history record scala 0 - 100 Neuron sense, strength can have positive or negative weight for optimization of whole algorithm It will be based on x[0] percentage of the biggest population and on level of x[1](not matter if is a -INT or +INT, what's ...
def addition(s, t): """Returns the mod-2 sum of two n-bit strings s and t.""" return tuple([(s[i] + t[i]) % 2 for i in range(len(s))])
def calc_target_joint_dimension_from_link_list(link_list): """Calculate Total Degrees of Freedom from link list Parameters ---------- link_list : list[skrobot.model.Link] Returns ------- n : int total Degrees of Freedom """ n = 0 for link in link_list: if hasatt...
def add_prefix(name, prefix=None, split='.'): """Add prefix to name if given.""" if prefix is not None: return '{}{}{}'.format(prefix, split, name) else: return name
def skewtent_onestep(value, threshold): """ Computes a single step of iteration through the skew-tent map given an input (previous) value and a threshold. Returns the next value as output. This function is called by _iterate_skewtent for iterating repeatedly. Parameters ---------- v...
def compare_pointlists(a, b, epsilon=0.001): """Check if two stroke lists (a and b) are equal.""" if len(a) != len(b): return False for stroke_a, stroke_b in zip(a, b): if len(stroke_a) != len(stroke_b): return False for point_a, point_b in zip(stroke_a, stroke_b): ...
def _set_default_temperature_rise( subcategory_id: int, family_id: int, ) -> float: """Set the default temperature rise. :param subcategory_id: the subcategory ID of the inductive device with missing defaults. :param family_id: the family ID of the inductive device with missing defaults. ...
def wiggle_sort(nums: list) -> list: """ Python implementation of wiggle. Example: >>> wiggle_sort([0, 5, 3, 2, 2]) [0, 5, 2, 3, 2] >>> wiggle_sort([]) [] >>> wiggle_sort([-2, -5, -45]) [-45, -2, -5] >>> wiggle_sort([-2.1, -5.68, -45.11]) [-45.11, -2.1, -5.68] ...
def _compress_cmd(log_path): """Return bash command which compresses the given path to a tarball.""" compres_cmd = 'cd "$(dirname %s)" && ' % log_path compres_cmd += 'f="$(basename %s)" && ' % log_path compres_cmd += 'tar czf "$f.tgz" "$f" && ' compres_cmd += 'rm -rf %s' % log_path return compr...
def GaussianPenalty(var,params): """ Adds a Gaussian log penalty factor to a log-likelihood variable """ penalty=-0.5*((var-params[0])/params[1])**2 return penalty
def convert_bytes(num): """ Convert num to idiomatic byte unit. :param num: the input number. :type num: int :return: str """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def cron_trigger_dict(ts_epoch): """A cron trigger as a dictionary.""" return { 'year': '2020', 'month': '*/1', 'day': '*/1', 'week': '*/1', 'day_of_week': '*/1', 'hour': '*/1', 'minute': '*/1', 'second': '*/1', 'start_date': ts_epoch, ...
def _parse_shell_command(shell_command, list_needed=False): """Utility function.""" if type(shell_command) == list: if list_needed: return shell_command cmd = '' for i in shell_command: cmd += i + ' ' else: if list_needed: cmd = [] s = shell_command.split(' ') for w in s: cmd.append(w) e...
def expand_id_map(id_map, all_ids): """ Ensures all ids within all_ids are included as keys in the mapping """ unmapped_ids = list(set(all_ids).difference(id_map.keys())) for i in unmapped_ids: id_map[i] = i return id_map
def parse_name(git_line: str) -> str: """ Return the author/committer name from git show output >>> parse_name('Author: John Doe <JohnDoe@email.com>') 'John Doe' """ data = git_line.split(":")[1] name = data.split("<")[0].strip() return name
def read_out_tweets(processed_tweets, speech_convertor=None): """ Input - list of processed 'Tweets' output - list of spoken responses """ return ["tweet number {num} by {user}. {text}.".format(num=index+1, user=user, text=text) for index, (user, text) in enumerate(processed_tweets)]
def print_from_template (s): """ Show the value of a string that is being processed in a Jinja template, for debugging. """ print(s) return s
def package_name(url): """ get the package name from a github url """ project = url.split('/')[-1].split('.')[0] user = url.split('/')[-2] return { "project": project, "user": user }
def rangeheads(s): """Return first element of each range in a sorted sequence of numbers. >>> rangeheads( (0, 1, 3, 4, 6) ) [0, 3, 6]""" sset = set(s) return [a for a in s if a - 1 not in sset]
def max_actions(points, action_cost, recover_cost, limit): """ Returns the max number of actions. It will weight the action cost against the available points, adding the recovery cost each time it runs out of points. """ if limit <= 0: actions = 0 elif action_cost <= 0: actions =...
def unpack_arch(architecture): """ :param architecture: dict. containing num. of units in every layer (2-layer FC network) :return: input_size, hidden_size, output_size of NN """ input_size = architecture["state_dim"] hidden_size = architecture["hidden_units"] output_size = architec...
def _get_literal_string_prefix_len(token_string: str) -> int: """ Getting the length of the literal string prefix. Parameters ---------- token_string : str String to check. Returns ------- int Length of the literal string prefix. Examples -------- >>> examp...
def abbreviation_pattern(prefix, suffix, capturing=False): """Create a pattern for matching the abbreviated word. The word may contain a single hash which separates the minimum permitted abbreviation on the left from optional letters on the right. If no word is present, the only the first letter is man...
def radialdesaturate(percentage=1.0, minimum=1.0): """ percentage = amount of blurring to apply - can go above 1 to increase the effect even more so. minimum = minimum amount of area to blur; lower numbers equals less of the screen blurred. """ return (""" // Name: 16-Sample Radial Blur // ...
def find_last_word(s): """Find the last word in a string.""" # Note: will break on \n, \r, etc. alpha_only_sentence = "".join([c for c in s if (c.isalpha() or (c == " "))]).strip() return alpha_only_sentence.split()[-1]
def _initialize_segments(lines): """Returns list([0, ...n]) for n = max length in lines.""" if lines: return [0] * max([len(line) for line in lines]) return []
def to_classname(filename: str) -> str: """ maps divided mock class file name to class names inverse function of headersplit.to_filename e.g. map "test/mocks/server/admin_stream.h" to "MockAdminStream" Args: filename: string, mock class header file name (might be the whole path instead of t...
def safe_boolcomp(value, expected): """Safely do a boolean comparison. This works even if the value you wantto compare is a string. Args: value: what you want to safely compare expected (bool): What you want to compare `value` with Returns: bool: True if str(value).lower() is ...
def _todict(obj, classkey=None): """Convert an object graph to dictionary. Adapted from: http://stackoverflow.com/questions/1036409/recursively-convert-python-object-graph-to-dictionary . """ if isinstance(obj, dict): for k in obj.keys(): obj[k] = _todict(obj[k], classkey) ...
def get_test_by_id( test_id ): # noqa: E501 """Get tests Get the status of a given test run. # noqa: E501 :param test_id: test ID :type test_id: str :rtype: ServiceTest """ return 'Not Implemented', 501
def filename_from_filepath(filepath): """ Strip the path off a filepath to get a filename""" try: return filepath[filepath.rindex('/')+1:] except ValueError: return filepath
def add_genotype(cell_genotypes, cell_barcode, umi, genotype): """ Append genotype information for cell and UMI to dictionary return modified cell_genotypes dictionary """ try: cell_genotypes[cell_barcode] except KeyError: # haven't seen the cell, must be new UMI cell_gen...
def get_nbr_genes(person, one_gene, two_genes): """ Return number of genes for person """ return (2 if person in two_genes else 1 if person in one_gene else 0)
def check_param(var, datatype): """Checks if a variable is the correct data type. If it's not correct, return the error message to raise. Parameters ----------- var the variable to check. datatype the data type to compare against. Returns ---------- ...
def problem_26(lim=1000): """ longest recurring cycle in decimal fractions""" def div_cycle(n, print_cyc=False): """ helper function to determine the length of the cycle in 1/n. Essentially, step through long division and once we reach a remainder that has already been seen, we have fou...
def naive_fibonacci(n): """ Return the n-th number in the fibonacci sequence. Uses recursion. The basic math expression is Xn = (Xn-1) + (Xn-2) The complexity is O(2^n). There are too many overlapping subproblems. """ n = int(n) if n == 0 or n == 1: # base case return n return na...
def reduce_files(step, paths, times=None, timestamps=None): """Filter out every STEP frame.""" # Reduce the paths add_last = False paths_new = paths[::step] if paths_new[-1] != paths[-1]: add_last = True # If new last frame is not the absolute last frame paths_new.append(path...
def wrap_index(idx, vector_size): """ wrap the index so they always stay inside vector size. """ if idx < 0: return vector_size + idx if idx >= vector_size : return idx - vector_size else: return idx
def mapFromTo(from_indices, to_indices): """Get a map from old index to new index.""" # if no old index exists map from new to new from_to = {} # magic mapping function: for t in to_indices: match = [f[1] for f in from_indices if f[0] is t[0]] if len(match) == 1: from_to[...
def is_pandas_df(obj): """Check if an object is a Pandas DataFrame Returns ------- bool Returns True if object is a Pandas DataFrame and False otherwise """ return obj.__class__.__module__ == "pandas.core.frame" and obj.to_records and obj.to_dict
def dbsession(request): """Create dict that represents database and database session.""" database = {'value': 'Framework value'} return database
def ramp_1(t,old,new,l): """ A function to simulate tardiness in compliance to social measures. Interpolates a parameter between the values 'old' and 'new' using a one parameter ramp function. Parameters ---------- t : float or int time since last checkpoint old : np.array ...
def get_pred_class(lls): """ Get MAP - class with max likelihood assigned Gets max key of dict passed in :param lls: Map from class name to log likelihood """ return max(lls, key=lls.get)
def strip_mult(*args): """ converts a variable amount of args to be striped of whitespace """ temp = [] for element in args: temp.append(element.strip()) return temp
def isSubDict(dict_super, dict_sub): """ Tests if the second dictonary is a subset of the first. :param dict dict_super: :param dict dict_sub: :return bool: """ for key in dict_sub.keys(): if not key in dict_super: return False if not dict_sub[key] == dict_super[key]: return False re...
def convert_to_time(time): """Print the training time in days: hours: minutes: seconds format.""" days = time // (24 * 60 * 60) time %= (24 * 60 * 60) hrs = time // (60 * 60) time %= (60 * 60) mins = time // 60 time %= 60 secs = time msg = f"Training completed in {days:.0f} ...
def s2_dn2toa(I): """convert the digital numbers of Sentinel-2 to top of atmosphere (TOA) Notes ----- sentinel.esa.int/web/sentinel/technical-guides/sentinel-2-msi/ level-1c/algorithm """ I_toa = I*10000 return I_toa
def _build_custom_vocab(tokens, vocab_length): """ Helper function for building custom vocab """ custom_vocab = {} cur_key = vocab_length for token in tokens: custom_vocab[token] = cur_key cur_key += 1 return custom_vocab
def show_supported(supported): """ Returns OK (in green) if supported evaluates to True, otherwise NOT OK (in red). """ try: from colorama import Fore, Style, init init() startcolor = Fore.GREEN if supported else Fore.RED stopcolor = Style.RESET_ALL except: s...
def rbsearch(list_,value,lower=None,upper=None): """Binary search, recursive.""" # handle empty list if len(list_) == 0: return None # set defaults for lower, upper if lower is None or upper is None: lower = 0 upper = len(list_) - 1 if list_[lower] == value: re...
def evaluateSystem(axiom, rules, n): """Evaluates a regular bog-standard L-System. axiom is a sequence of symbols. rules is either: a dictionary type S->Symbols, like {1: [1, 2, 3]} a list of tuples as the ones produced by the function production() a single tuple as the ones pro...
def lyrics_to_dictionary(songlyrics): """ argument: List, songlyrics returns: dictionary with -> word in songlyrics(key):numberofoccurences in song(value) """ lyrics_dictionary = {} for word in songlyrics: if word in lyrics_dictionary: lyrics_dictionary[word] = lyrics_dictio...
def _KeyValueToDict( pair ): """Converts an iterable object of key=value pairs to dictionary.""" d = dict() for kv in pair: (k, v) = kv.split('=', 1) d[k] = v return d
def simple_decompression(compressed_string): """Decompression for `simple_compression(string)`""" string=""; i=0; len_string = len(compressed_string) while True: if compressed_string[i].isdigit(): s = i while i<len_string and compressed_string[i].isdigit(): ...
def _blank_out_conflicting_opts(opt_list, opt_names, conflicting_opts=None): """Utility for :py:meth:`MRJobRunner._combine_opts()`: if multiple configs specify conflicting opts, blank them out in all but the last config (so, for example, the command line beats the config file). This returns a copy of *...
def solution(number: int) -> int: """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in. :param number: :return: """ result...
def _scrape_available_devices(text): """Scrapes the output of the adb devices command into a list :param text: Full output of adb devices command to scrape """ lines = text.split('\n') available_devices = [] for line in lines: words = line.split('\t') if len(words[0]) > 5 and ...
def get_first(data, *keys): """Retrieve a normalized data item, looking first in 'msg' """ if "msg" in data: first, *rest = keys cand = data["msg"].get(first) if cand is not None: return cand keys = rest for key in keys: cand = data.get(key) if...
def extract_objects(f_t): """Get objects coordinates as a list.""" objs_k = ['key', 'chest', 'food'] objs = {} for obj in objs_k: if obj not in objs: objs[obj] = [] keys = f_t.keys() keys = filter(lambda x: x.startswith(obj + '_'), keys) keys = map(...
def pattern(n): """ Perform checks on the number, if 0, return an empty string, if 1, return a string literal of 1, else,find the range of the numbers and convert each to a string and repeat the string x times will adding to another list join this list with \n """ return "\n".join(["1"]...
def substrings(a, b, n): """Return substrings of length n in both a and b""" subs = set() if (n > len(a)): return subs if (a == b and len(a) == n): return [a] for i in range(0, len(a) - n + 1): substring = a[i:i+n] if (substring in b): subs.add(substring)...
def repeat_count_with_max_length(x, max_length, assert_at_least_one_rep=False): """ The maximum number of times `x` can be repeated such that its length is <= `max_length`. Parameters ---------- x : tuple or Circuit the operation sequence to repeat max_length : int the maximum ...