content
stringlengths
42
6.51k
def format_duration(duration: float): """Formats the duration (milliseconds) to a human readable way. :param duration: Duration in milliseconds :return: Duration in HOURS:MINUTES:SECONDS format. Example: 01:05:10 """ m, s = divmod(duration / 1000, 60) h, m = divmod(m, 60) if h: retu...
def create_average_data(json_data): """ Args: json_data -- School data in tree structure. Returns: dict -- Average of financial data across schools that provided data. """ avg = {} counts = {} for school in json_data: for year in json_data[school]: if y...
def build_header(src, episode_url): """ Build header. """ return {'Referer': episode_url}
def string_ijk1_for_cell_ijk1(cell_ijk1): """Returns a string showing indices for a cell in simulator protocol, from data in simulator protocol.""" return '[{:}, {:}, {:}]'.format(cell_ijk1[0], cell_ijk1[1], cell_ijk1[2])
def joint_number(text_list): """joint fraction number Args: text_list (list): text list. Returns: (list): processed text list. """ new_list = [] i = 0 while i < len(text_list): if text_list[i] == '(' and i + 4 < len(text_list) and text_list[i + 4] == ')': ...
def get_barycenter(vector): """ this function calculates a barycenter from an array with connections. :param list vector: vector of connections from an interconnectivity matrix 1 = connection, 0 = no connection. :return float: barycenter from the connection vector. """ wei...
def _cmp(kd1, kd2): """ Compare 2 keys :param kd1: First key :param kd2: Second key :return: -1,0,1 depending on whether kd1 is le,eq or gt then kd2 """ if kd1 == kd2: return 0 if kd1 < kd2: return -1 return 1
def verify(str1: str, str2: str): """ Verify two numeric (0s and 1s) representations of images. """ if len(str1) == len(str2): matches = 0 misses = 0 for char in enumerate(str1): if str1[char[0]] == str2[char[0]]: matches += 1 els...
def display(head): """.""" res = [] if not head: return res curr = head while curr: res.append(curr.data) curr = curr.next return res
def get_file_name_from_url(url: str) -> str: """Returns the filename from a given url. """ return url.rsplit('/', 1)[1]
def _clean_name(net, name): """ Clear prefix and some suffixes for name """ # prefix = net._prefix # name = name.replace(prefix, "") if name.endswith("_fwd_output"): name = name[:-len("_fwd_output")] elif name.endswith("_fwd"): name = name[:-len("_fwd")] elif name.endswith("_outp...
def bsearch_ins_pos(arr, t, left): """ Index where we should insert t in sorted arr. If t exists, then we can return the left (left=True) or right (left=False) side of the dups range. """ low = 0 high = len(arr) # note search goes 1 higher b/c you might need to insert afterwards while lo...
def inherits_from(obj, a_class): """ Return True if the object is an instance that inherited from the specified """ return isinstance(obj, a_class) and type(obj) != a_class
def MILLISECOND(expression): """ Returns the millisecond portion of a date as an integer between 0 and 999. See https://docs.mongodb.com/manual/reference/operator/aggregation/millisecond/ for more details :param expression: expression or variable of a Date, a Timestamp, or an ObjectID :return: A...
def boltHeadFinder(head): """ """ _head = str(head).lower() _head = _head.replace('bolt','') _head = _head.replace('screw','') _head = _head.replace('head','') _head = _head.replace(' ','') _head = _head.replace('_','') _head = _head.replace('-','') _head = _head.strip() ...
def _ord(i): """Converts a 1-char byte string to int. This function is used for python2 and python3 compatibility that can also handle an integer input. Args: i: The 1-char byte string to convert to an int. Returns: The byte string value as int or i if the input was already an ...
def strtobool(val): """Convert a string representation of truth to true (1) or false (0). this function is copied from distutils.util to avoid deprecation waring https://www.python.org/dev/peps/pep-0632/ True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', ...
def get_next_race_info(next_race_time_events: list, race_id: str) -> list: """Enrich start list with next race info.""" startlist = [] # get videre til information - loop and simulate result for pos 1 to 8 for x in range(1, 9): for template in next_race_time_events: start_entry = {} ...
def deep_merge(dict1: dict, dict2: dict) -> dict: """Deeply merge dictionary2 and dictionary1 then return a new dictionary Arguments: dict1 {dict} -- Dictionary female dict2 {dict} -- Dictionary mail to be added to dict1 Returns: dict -- Merged dictionary """ if typ...
def remove(geo, idxs=()): """ Remove idxs from a geometry """ new_geo = tuple(row for i, row in enumerate(geo) if i not in idxs) return new_geo
def listbox_width(items, max_width=30): """Calculate the width for a listbox, based on a list of strings and a maximum width. listbox_width(["foo", "bar", "asdf"], 10) #=> 4 ("asdf") listbox_width(["foo", "asdf", "beep boop"], 5) #=> 5 (max_width) """ max_item_width = max(map(len, items)...
def is_power_of_2(n: int) -> bool: """For a positive integer `n`, returns `True` is `n` is a perfect power of 2, `False` otherwise.""" assert n >= 1 return n & (n - 1) == 0
def split_and_number(strips, missing_indices): """ Number contiguous elements in an array with the information of the missing indices. """ remapped_strips = [] j = 0 missing_indices.sort() for i in range(len(strips)): if j in missing_indices: while j in missing_indice...
def get_color_from_cmap(val, val_min, val_max, cmap): """Return color. Args: val (float): value to get color for from colormap (mV) val_min (int): minimum value of voltage for colormap (mV) val_max (int): minimum value of voltage for colormap (mV) cmap (matplotlib.colors.Colorma...
def get_links(page_text): """ :param page_text: Page text :return: The list of external link of the page """ import re ragex = re.compile(r'\[\[.*?\]\]') l = ragex.findall(page_text) return [s[2:-2].split("|")[0] for s in l]
def buildParams(jobParams, args): """Build the list of parameters that are passed through to the command""" paramString = "" if (jobParams is not None): for param in jobParams: dash_prefix = '--' if len(param.name) > 1 else '-' value = args.get(param.name.replace("-", "_"), ...
def get_transitions(sequence): """ Extracts a list of transitions from a sequence, returning a list of lists containing each transition. Example -------- >>> sequence = [1,2,2,1,2,3,2,3,1] >>> ps.get_transitions(sequence) [[1, 2], [2, 1], [1, 2], [2, 3], [3, 2], [2, 3], [3, 1]] """ transitions = [] for pos...
def insert_row(order:int) -> str: """ insert polynomial root data into an SQL database """ params = ', '.join(["root{}, iroot{}".format(root, root) for root in range(order)]) inserts = ', '.join(["?, ?" for root in range(order)]) query = "INSERT OR REPLACE INTO polynomials (id, {}) VALUES (?, {})".format(params...
def _get_with_item_indices(exs): """Returns a list of indices in case of re-running with-items. :param exs: List of executions. :return: a list of numbers. """ return sorted(set([ex.runtime_context['with_items_index'] for ex in exs]))
def timeout_soft_cmd(cmd, timeout): """Same as timeout_cmd buf using SIGTERM on timeout.""" return 'timeout %us stdbuf -o0 -e0 %s' % (timeout, cmd)
def find_best_match(path, prefixes): """Find the Ingredient that shares the longest prefix with path.""" path_parts = path.split('.') for p in prefixes: if len(p) <= len(path_parts) and p == path_parts[:len(p)]: return '.'.join(p), '.'.join(path_parts[len(p):]) return '', path
def get_big_mat_nrows(nrows: int): """ Parameters ---------- nrows : int the number of rows in the matrix Returns ------- nrows : int the number of rows in the matrix BIGMAT : Input-logical-default=FALSE. BIGMAT is applicable only when IUNIT < 0. BIGMAT=FALSE sel...
def flatten(l): """Flattens a list of lists to the first level. Given a list containing a mix of scalars and lists, flattens down to a list of the scalars within the original list. Examples -------- >>> print(flatten([[[0], 1], 2])) [0, 1, 2] """ if not isinstance(l, list): ...
def dev_turn_left(dev0): """ m07.turn left..... return none........ """ try: dev0.swipe(150, 1000, 850, 1000) # (150, 1000) -> (850, 1000) except Exception as e: print("error at dev_turn_left.") pass else: pass finally: return None
def encode(request): """Encode request (command, *args) to redis bulk bytes. Note that command is a string defined by redis. All elements in args should be a string. """ assert isinstance(request, tuple) data = '*%d\r\n' % len(request) + ''.join(['$%d\r\n%s\r\n' % (len(str(x)), x) for x in requ...
def main(textlines, messagefunc, config): """ KlipChop func to to convert text into unique lines """ result = list() count = 0 for line in textlines(): if line not in result: result.append(line) count += 1 if config['sort']: result = sorted(result...
def formatFreq(value, pos): """ Format function for Matplotlib formatter. """ inv = 999. if value: inv = 1 / value return "1/%0.2f" % inv
def count_list_nodes(taxonomy): """ Count list nodes and return sum. :param taxonomy: taxonomy :return: int """ count = 0 keys = [x for x in list(taxonomy.keys()) if x != "data"] for i in keys: if set(taxonomy[i]) == set(list({"data"})): if i == keys[-1]: ...
def find_replace_line_endings(fp_readlines): """ special find and replace function to clean up line endings in the file from end or starttag characters """ clean = [] for line in fp_readlines: if line.endswith("=<\n"): line = line.replace("<\n", "lt\n") clean.appe...
def fatorial(num, show =False): """ program com um funcao fatorial, que recebe um numero como parametro e retorna o fatorial Com um parametro opcional se ele receber True mostra a operacao """ print('-=' * 30) fat = 1 for c in range(num, 0, -1): if show: print(c, end='')...
def has_unique_chars(string): """ Implement an algorithm to determine if a string has all unique characters. :param string: string :return: True/False """ if string is None: return False if not isinstance(string, str): return False return len(set(string)) == len(string)
def _add_read_queue_size(input_cmd, queue_size=50000): """ only add when mapall option is used and "-q" and "--reads-queue-size" is not already used. there is no other long command starting with q either. :param input_cmd: :param queue_size: :return: """ if "mapall" not in input_cm...
def getFeatureGeometry(feature): """ Return the geometry of a feature params: feature -> a feature """ return feature["geometry"]
def clean_check(name_list, link_list): """ This goes and checks that there are not any offsets. Both the name list and the link lists should be the same length :param name_list: :param link_list: :return: """ # making sure there are not offsets, if so stop the run try: if len(nam...
def _prod(iterable): """ Product of a list of numbers. Faster than np.prod for short lists like array shapes. """ product = 1 for x in iterable: product *= x return product
def pad_number(number, padding=3): """Add zero padding to number""" number_string = str(number) padded_number = number_string.zfill(padding) return padded_number
def _parse_query(query): """extract key-value pairs from a url query string for example "collection=23&someoption&format=json" -> {"collection": "23", "someoption": None, "format": "json"} """ parts = [p.split("=") for p in query.split("&")] result = {} for p in parts: if len...
def find_missing(integers_list, start=None, limit=None): """ Given a list of integers and optionally a start and an end finds all integers from start to end that are not in the list """ start = start if start is not None else integers_list[0] limit = limit if limit is not None else integers_list...
def _format_pos_to_db(pos: list) -> str: """ Returns a database-ready string that contains the position in the form x/y """ return "{}/{}".format(pos[0], pos[1])
def rgb_to_hex(rgb): """RGB to HEX conversion""" return '#%02x%02x%02x' % (rgb[0], rgb[1], rgb[2])
def insert_string(original, insertion, index): """ Insert a string at the given index of the provided string :param original: string to be inserted into :param insertion: string to insert :param index: index of insertion :return: initial string with completed insertion """ return origina...
def indent(string: str, n=4) -> str: """Indent a multi-line string by given number of spaces.""" return "\n".join(" " * n + x for x in str(string).split("\n"))
def make_subj(common_name, encrypted=False): """ Make a subject string :param common_name: Common name used in certificate :param encrypted: Add the encrypted flag to the organisation :return: A subject string """ return "/C=FR/ST=Auvergne-Rhone-Alpes/L=Grenoble/O=iPOPO Tests ({0})" \ ...
def pixel_distance(p1, p2): """straight 3-d euclidean distance (assume RGB)""" return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2)**0.5
def isPointValid(point, validPoints, clearance): """ Definition --- Method to check if point is valid and clear of obstacles Parameters --- point : node of intrest validPoints : list of all valid points clearance : minimum distance required from obstacles Returns --- bo...
def is_public_method(class_to_check, name): """Determine if the specified name is a public method on a class""" if hasattr(class_to_check, name) and name[0] != '_': if callable(getattr(class_to_check, name)): return True return False
def get_number_nation(number) -> str: """ Gets the nation of a number. :param number: The number to get the nation from. :return: The number's nation. """ return "000s" if len(str(number)) <= 2 else f"{str(number)[-3]}00s"
def custom_rounder(input_number, p): """ Return round of the input number respected to the digit. :param input_number: number that should be round :type input_number: float :param p: 10 powered by number of digits that wanted to be rounded to :type p: int :return: rounded number in float ...
def julian_century(jd_local): """Returns the Julian Century with Julian Day, julian_local.""" days_century = 2451545 # this is Saturday, AD 2000 Jan 1 in the Julian Calendar day_per_century = 36525 for i in range(2451545, 0, -36525): if jd_local < i: days_century = i - day_per_centu...
def score(letter): """ Returns index of letter in alphabet e.g. A -> 1, B -> 2, ... """ string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' return(string.index(letter) + 1)
def reverse_dict(original): """ Returns a dictionary based on an original dictionary where previous keys are values and previous values pass to be the keys """ final = {} for k, value in original.items(): if type(value) == list: for v in value: final.setde...
def _id_remapper(orig, new): """Provide a dictionary remapping original read indexes to new indexes. When re-ordering the header, the individual read identifiers need to be updated as well. """ new_chrom_to_index = {} for i_n, (chr_n, _) in enumerate(new): new_chrom_to_index[chr_n] = i_...
def find_predecessor_row_from_batch(parsed_rows, batch_row_id, predecessor_name): """ finds a relevant predecessor row in a batch """ batch_rows = filter( lambda x: x['parent_id'] == batch_row_id, parsed_rows ) for row in batch_rows: if row['name'] == predecessor_name: ...
def _round_pow_2(value): """Round value to next power of 2 value - max 16""" if value > 8: return 16 elif value > 4: return 8 elif value > 2: return 4 return value
def get_data_element(item='case'): """Method to get data elements other than categories and inteventions.""" results = {} try: case, params = {}, {} case[1] = 'Total Children' case[2] = 'Total Cases' case[3] = 'Total Interventions' case[4] = 'Percentage Interv...
def fib(n): """ Calculates the n-th Fabonacci number iteratively >>> fib(0) 0 >>> fib(1) 1 >>> fib(10) 55 """ a, b = 0, 1 for i in range(n): a, b = b, a + b return a
def _LookupTargets(names, mapping): """Returns a list of the mapping[name] for each value in |names| that is in |mapping|.""" return [mapping[name] for name in names if name in mapping]
def distance(a, b): """Returns the case-insensitive Levenshtein edit distance between |a| and |b|. The Levenshtein distance is a metric for measuring the difference between two strings. If |a| == |b|, the distance is 0. It is roughly the number of insertions, deletions, and substitutions needed to convert |a| ...
def to_namespace(node, namespace): """Return node name as if it's inside the namespace. Args: node (str): Node name namespace (str): Namespace Returns: str: The node in the namespace. """ namespace_prefix = "|{}:".format(namespace) node = namespace_prefix.join(node.spl...
def empty_if_none(_string, _source=None): """If _source if None, return an empty string, otherwise return string. This is useful when you build strings and want it to be empty if you don't have any data. For example when building a comma-separated string with a dynamic number of parameters: .. code-bl...
def model_trapezoidal_pulses(pileup_time, energy1, energy2, cfg): """ Models the pileup energy based on a trapezoidal filter. We have 4 scenarios for the pileup. The final energy depends on when the pileup signal peaks: 1. fully inside the gap of the first signal, 2. between the gap and the ...
def _board_to_string(board): """Returns a string representation of the board.""" return "\n".join("".join(row) for row in board)
def find_close_elements(a, b, precision = 0.01): """Finds close elements in two arrays with diffrent sizes. Parameters ---------- a : array of floats with dimention of N Description of parameter `a`. b : array of floats with dimention of M Description of parameter `b`. precision...
def common_filters(limit=None, sort_key=None, sort_dir=None, marker=None): """Generate common filters for any list request. :param limit: maximum number of entities to return. :param sort_key: field to use for sorting. :param sort_dir: direction of sorting: 'asc' or 'desc'. :param marker: The last ...
def sol_rad_island(et_rad): """ Estimate incoming solar (or shortwave) radiation, *Rs* (radiation hitting a horizontal plane after scattering by the atmosphere) for an island location. An island is defined as a land mass with width perpendicular to the coastline <= 20 km. Use this method only if...
def strip_code_prompts(rst_string): """Removes >>> and ... prompts from code blocks in examples.""" return rst_string.replace('&gt;&gt;&gt; ', '').replace('&gt;&gt;&gt;\n', '\n').replace('\n...', '\n')
def colored(str, color="red"): """ Color a string for terminal output @params str - Required : the string to color color - Optional : the color to use. Default value: red. Available options: red, yellow, blue """ colors = { "red": "\033[91m", "yellow": "\33[33m", ...
def is_hla(chrom): """ check if a chromosome is an HLA """ return chrom.startswith("HLA")
def clean_dict(dictionary: dict) -> dict: """Recursively removes `None` values from `dictionary` Args: dictionary (dict): subject dictionary Returns: dict: dictionary without None values """ for key, value in list(dictionary.items()): if isinstance(value, dict): ...
def correct_name(name): """ Ensures that the name of object used to create paths in file system do not contain characters that would be handled erroneously (e.g. \ or / that normally separate file directories). Parameters ---------- name : str Name of object (course, file, folder, e...
def flavor_id(request): """Flavor id of the flavor to test.""" return request.param if hasattr(request, 'param') else None
def _string_contains(arg, substr): """ Determine if indicated string is exactly contained in the calling string. Parameters ---------- substr : str or ibis.expr.types.StringValue Returns ------- contains : ibis.expr.types.BooleanValue """ return arg.find(substr) >= 0
def is_model(obj): """ Returns True if the obj is a Django model """ if not hasattr(obj, '_meta'): return False if not hasattr(obj._meta, 'db_table'): return False return True
def flatten_seq(seq): """convert a sequence of embedded sequences into a plain list""" result = [] vals = seq.values() if type(seq) == dict else seq for i in vals: if type(i) in (dict, list): result.extend(flatten_seq(i)) else: result.append(i) return result
def product(iterable, init=None): """ product(iterable) is a product of all elements in iterable. If init is given, the multiplication starts with init instead of the first element in iterable. If the iterable is empty, then init or 1 will be returned. If iterable is an iterator, it will be ex...
def no_replace(f): """ Method decorator to indicate that a method definition shall silently be ignored if it already exists in the target class. """ f.__no_replace = True return f
def has_prefix(sub_s, current_dict): """ :param sub_s: string, part of the input word :param current_dict: list, save words in the dictionary beginning with the entered letters :return: boolean """ cnt = 0 for w in current_dict: if w.startswith(sub_s): cnt += 1 # cnt > 0 means sub_s is a prefix of some wor...
def is_account_in_invalid_state(ou_id, config): """ Check if Account is sitting in the root of the Organization or in Protected OU """ if ou_id.startswith('r-'): return "Is in the Root of the Organization, it will be skipped." protected = config.get('protected', []) if ou_id in prot...
def _link2dict(l): """ Converts the GitHub Link header to a dict: Example:: >>> link2dict('<https://api.github.com/repos/sympy/sympy/pulls?page=2&state=closed>; rel="next", <https://api.github.com/repos/sympy/sympy/pulls?page=21&state=closed>; rel="last"') {'last': 'https://api.github.com/repos/s...
def lr_mark(line, lmark, rmark): """ read a string segment from line, which is enclosed between l&rmark e.g. extract the contents in parenteses Args: line (str): text line lmark (str): left marker, e.g. '(' rmark (str): right marker, e.g. ')' Return: str: text in between left and right markers ...
def _round_channels(channels, multiplier=1.0, divisor=8, channel_min=None): """Round number of filters based on depth multiplier.""" if not multiplier: return channels channels *= multiplier channel_min = channel_min or divisor new_channels = max( int(channels + divisor / 2) // divi...
def get_current_stream_name(logger, zulip_stream_names, stream_id): """ Check all Zulip streams and get a name for the current stream. Raise ValueError if it is impossible to narrow down stream names. :param logger: Logger object :param zulip_stream_names: List of Zulip stream names :param stre...
def _sign(num): """Defines the sign for the multiplication""" if not num: return 0 return 1 if num > 0 else -1
def validate_limit_amount(amount): """Validate limit amount value.""" errors = [] if not isinstance(amount, float) and not isinstance(amount, int): errors.append("Amount must be float or integer type.") return errors if amount <= 0: errors.append("Amount must be positive value."...
def determine_issue_category(issue_type, issue_types): """Determine the category of an issue.""" category = None for issue in issue_types: issue_id = issue["@Id"] if issue_id == issue_type: category = issue["@Category"] break return category
def attsiz(att: str) -> int: """ Helper function to return attribute size in bytes. :param str: attribute type e.g. 'U002' :return: size of attribute in bytes :rtype: int """ return int(att[1:4])
def get_test_values(alignments): """ @type alignments: C{dict} @param alignments: @return: @rtype: C{list} """ test_values = [] for hard_regions_index in alignments.keys(): soft_regions_list = [] for soft_regions_index in alignments[...
def github_disable_dismiss_stale_pull_request_approvals(rec): """ author: @mimeframe description: Setting 'Dismiss stale pull request approvals when new commits are pushed' was disabled. As a result, commits occurring after approval will not require approval. r...
def _sanatize_user_answer(answer): """ replace chars that shouldn't be in the answer """ #The user may have forgotten to enter a 0 if answer[0] == ".": answer = "0" + answer #values such as / , and - will not work so replace them try: return answer.replace("/",".").replace(",",".")...
def _convert_from_bcd(bcd): """ Converts a bcd value to a decimal value :param value: The value to unpack from bcd :returns: The number in decimal form """ place, decimal = 1, 0 while bcd > 0: nibble = bcd & 0xf decimal += nibble * place bcd >>= 4 place *= 10 ...