content
stringlengths
42
6.51k
def lookup_key_path(job, obj, path): """ Get the item at the given path of keys by repeated [] lookups in obj. Work around https://github.com/BD2KGenomics/toil/issues/2214 """ for key in path: obj = obj[key] return obj
def normalize_option_name(name): """Use '-' as default instead of '_' for option as it is easier to type.""" if name.startswith("--"): name = name.replace("_", "-") return name
def transform_misses(record): """Format the missed datasets record we got from the database to adhere to the response schema.""" response = {} response["datasetId"] = dict(record).get("stableId") response["internalId"] = dict(record).get("datasetId") response["exists"] = False # response[...
def sort_imgs(image_list, subject_id, EVAL_TIMES): """ Function to extract and group the corresponding images in a list of all images with names like: Step_30_aligned_reference.jpg Input: image_list: Contains all filenames of the images as string subject_id: id of the respective subject...
def parse_related_content_Descriptor(data,i,length,end): """\ parse_related_content_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). Parses a descriptor that identifies that the elementary stream it is part of delivers a 'related content' subtable. The returned dict is: { ...
def splice(alists, recycle = True): """ Accepts a list of nonempty lists or indexable objects in argument alists (each element list may not be of the same length) and a keyword argument recycle which if true will reuse elements in lists of shorter length. Any error will result in an empty list...
def signed_leb128_decode(data) -> int: """Read variable length encoded 128 bits signed integer. .. doctest:: >>> from ppci.utils.leb128 import signed_leb128_decode >>> signed_leb128_decode(iter(bytes([0x9b, 0xf1, 0x59]))) -624485 """ result = 0 shift = 0 while True: ...
def get_span_labels(sentence_tags, inv_label_mapping=None): """Go from token-level labels to list of entities (start, end, class).""" if inv_label_mapping: sentence_tags = [inv_label_mapping[i] for i in sentence_tags] span_labels = [] last = 'O' start = -1 for i, tag in enumerate(sentence_tags): pos...
def getmembers(_object, _predicate): """This is an implementation of inspect.getmembers, as in some versions of python it may be buggy. See issue at http://bugs.python.org/issue1785""" # This should be: # return inspect.getmembers(_object, _predicate) # ... and it is re-implemented as: ob...
def safe_str(obj, newline='\\n'): """This function eliminates newlines and replaces them with the explicit character newline string passed. Defaults to the showing '\n' explicitly""" return str(obj).replace('\n', newline)
def seq(*sequence): """Runs a series of parsers in sequence optionally storing results in a returned dictionary. For example: seq(whitespace, ('phone', digits), whitespace, ('name', remaining)) """ results = {} for p in sequence: if callable(p): p() continue...
def inv_transform_vertex(x, phi): """ Given a vertex id x and a set of partial isomorphisms phi. Returns the inverse transformed vertex id """ for _phi in phi: if _phi[1] == x: return _phi[0] raise Exception('Could not find inverse transformation')
def _is_equal_position(first: tuple, second: tuple, position): """Whether both position are equal in the given tuples.""" if len(first) > position: if len(second) > position: return first[position] == second[position] return first[position] is None if len(second) > position: ...
def get_resources(name, config): """Retrieve resources for a program, pulling from multiple config sources. """ return config.get("resources", {}).get(name, {})
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ index_map = {} for i in range(len(nums)): num = nums[i] pair = target - num if pair in index_map: return [index_map[pair], i] index_map[num] = i return ...
def valid_number(num, default=None, name='integer value', lbound=None, ubound=None): """Given a user-provided number, return a valid int, or raise.""" if not num and num != 0: assert default is not None, "%s must be provided" % name num = default try: num = int(num) except (TypeError, ...
def multiply_1(factor: int): """ Example where input argument has specified variable annotation. This example is showing how to cast variable. And assert in order to check for any error at the early stage. :param factor: :return: results: int """ # This will print a data type of this variabl...
def gon2dec(gon): """ Converts Gradians to Decimal Degrees :param gon: Gradians :type gon: float :return: Decimal Degrees :rtype: float """ return 9/10 * gon
def set_document_cookie_disabled(disabled: bool) -> dict: """ Parameters ---------- disabled: bool Whether document.coookie API should be disabled. **Experimental** """ return { "method": "Emulation.setDocumentCookieDisabled", "params": {"disabled": disabled}, ...
def env_matches(env_name, factor): """Determine if an env name matches the given factor. The env name is split into its component factors, and matches if the given factor is present in the component factors. Partial matches are not valid. >>> env_matches('py37-django21', 'py37') True ...
def ms_len(data): """Implementation of `len`.""" return data.__len__()
def is_list_of_strings(lst) -> bool: """ Verifies that given parameter is a list of strings :param lst: list :return: True if parameter is list of strings """ if lst and isinstance(lst, list): return all(isinstance(elem, str) for elem in lst) else: return False
def keep_last_and_only(authors_str): """ This function is dedicated to parse authors, it removes all the "and" but the last and and replace them with ", " :param str: string with authors :return: string with authors with only one "and" """ last_author = authors_str.split(" and ")[-1] ...
def evaluate_query(r, query): """ >>> r = {"id": "123", "info": {"name": "bla"}} >>> evaluate_query(r, {"id": "123"}) True >>> evaluate_query(r, {"info.name": "bla"}) True >>> evaluate_query(r, {"info.name": "foo"}) False """ if len(query) > 1: return all([evaluate_query(...
def generate_repo_name(repo_name): """ This function for converting general string to github_repo_format_string. Args: :param repo_name: repository name. Returns: repo_name (str): Return a string as github repository correct format. """ return repo_name.replace(" ", "...
def dictmax(d): """ returns key with maximum value in dictionary """ return max(d.keys(), key = lambda x: d[x])
def value_to_dni(confidence_value): """ This method will transform an integer value into the DNI scale string representation. The scale for this confidence representation is the following: .. list-table:: STIX Confidence to DNI Scale :header-rows: 1 * - Range of Values -...
def _format_epilog(commands): """Create a epilog string for the specified commands. Args: commands: Sequence of (func, name, description) Returns: str: Formatted list of commands and their descriptions """ lines = [] lines.append("Commands:") for command in commands: ...
def hill_equation(val, diss_cf, hill_cf): """ Hill equation :param val: input value :param diss_cf: dissociation coefficient :param hill_cf: Hill coefficient :return: Hill equation for input *val* """ if val == 0: return 0 else: return 1 / (1 + (diss_cf / val) ** hill...
def combine_batch_pair(summary_a, summary_b): """Combines two batches into one. :param summary_a: list, of first batch :param summary_b: list, of second batch :return: list: PartialSummary, combined data of first and second batch in single list """ summary = summary_a # Set first list as base...
def _config_path_to_class_and_name(path): """ Local helper function that takes a pettingzoo config path and returns it in the service_class/service_name format expected in this module """ path = path.split(".")[0] parts = path.split("/") if len(parts) >= 2: service_class = parts[-2] service_name = parts[-1] ...
def decode_string(s): """ :type s: str :rtype: str """ stack = []; cur_num = 0; cur_string = '' for c in s: if c == '[': stack.append((cur_string, cur_num)) cur_string = '' cur_num = 0 elif c == ']': prev_string, num = stack.pop() ...
def jaccard_score(list1, list2): """ Jaccard similarity score The Jaccard coefficient measures similarity between finite sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets https://en.wikipedia.org/wiki/Jaccard_index :param input_...
def get_full_name(taxid, names_map, ranks_map): """ Generate full taxonomic lineage from a taxid Args: taxid (str): taxid names_map (dict[str:str]): the taxonomic names for each taxid node ranks_map (dict[str:str]): the parent node for each taxid Returns: taxonomy (str): ...
def adoc_with_preview_command(event=None, verbose=True): """Run the adoc command, then show the result in the browser.""" c = event and event.get('c') if not c: return None return c.markupCommands.adoc_command(event, preview=True, verbose=verbose)
def _get_jinja_error_slug(tb_data): """ Return the line number where the template error was found """ try: return [ x for x in tb_data if x[2] in ("top-level template code", "template", "<module>") ][-1] except IndexError: pass
def one_hot_encode(input_field, output_field, options, function_name, field_prefix=""): """ Generates lua lines that One-Hot encodes a field from its possible options :param input_field: original censys field :param output_field: flattened version of censys field :param options: array of the possib...
def no_embed_link(url: str) -> str: """Makes link in discord message display without embedded website preview""" return f"<{url}>"
def poly_func(X): """This polynomial was chosen because all of its zeroes (-2, 4, 8) lie in the x-range we're looking at, so it is quite wiggly""" return X**3 - 10*X**2 + 8*X + 64
def _strip_state_dict_prefix(state_dict, prefix='module.'): """Removes the name prefix in checkpoint. Basically, when the model is deployed in parallel, the prefix `module.` will be added to the saved checkpoint. This function is used to remove the prefix, which is friendly to checkpoint loading. ...
def escaped(val): """ escapes a string to allow injecting it into a json conf """ val = val.replace('\\', '/') val = val.replace('"', '\"') return val
def celsius_to_fahr(temp): """ Convert Celsius to Fahrenheit. Parameters ---------- temp : int or double The temperature in Celsius. Returns ------- double The temperature in Fahrenheit. Examples -------- >>> from convertempPy import convertempPy as tmp ...
def is_chinese_char(uchar): """ Whether is a chinese character. Args: uchar: A utf-8 char. Returns: True/False. """ if uchar >= u'\u3400' and uchar <= u'\u4db5': # CJK Unified Ideographs Extension A, release 3.0 return True elif uchar >= u'\u4e00' and uchar <= u'\u9f...
def list_element(title, subtitle=None, image_url=None, buttons=None, default_action=None): """ Creates a dict to use with send_list :param title: Element title :param subtitle: Element subtitle (optional) :param image_url: Element image URL (optional) :param buttons: List of button_postback to s...
def sample_lines(lines, n): """Draw a sample of n lines from filename, largely evenly.""" if len(lines) <= n: return "".join(lines) else: m = len(lines) return "".join([lines[x * m // n + m // (2 * n)] for x in range(n)])
def is_valid_json(ext): """ Checks if is a valid JSON file """ formats = ['json'] return ext in formats
def format_duration(seconds: float) -> str: """ Formats time in seconds as (Dd)HH:MM:SS (time.stfrtime() is not useful for formatting durations). :param seconds: Number of seconds to format :return: Given number of seconds as (Dd)HH:MM:SS """ x = '-' if seconds < 0 else '' m, s = divmod(abs...
def result_has_error(results): """ Check the results list for any possible error and return a tuple which contains the status and error message. If the record contains a Plural attribute, multiple API calls may be performed for a single record. Args: results: List of API responses Retu...
def bottom_up_cut_rod(price, length): """ bottom up implementation of cut rod memoized algorithm """ incomelst = [float("-Inf") for _ in range(length + 1)] # set zero income for zero length incomelst[0] = 0 for j in range(1, length + 1): income = float("-Inf") for i in range(j): ...
def get_vxlan_ip(n): """ Returns an IP address in the range 192.168.0.0 - 192.168.255.255 without using X.0 or X.255 """ quot, rem = divmod(n, 254) ip_addr = "192.168.%s.%s" % (quot + 1, rem + 1) return ip_addr
def startdate(acquired): """Returns the startdate from an acquired date string Args: acquired (str): / separated date range in iso8601 format Returns: str: Start date """ return acquired.split('/')[0]
def find_bucket_key(s3_path): """ This is a helper function that given an s3 path such that the path is of the form: bucket/key It will return the bucket and the key represented by the s3 path """ s3_components = s3_path.split('/') bucket = s3_components[0] s3_key = "" if len(s3_comp...
def check_type(var_type, value): """ Check that the type of value is the Python equivalent of var_type or a list of it @param var_type (string) Type of val (INTEGER, REAL, LOGICAL, STRING) @param val (int/boolean/float/string/list) Value to check @return The value in (int, float, boolean, stri...
def snapshot_state_counts_nondeterministic(shots): """Snapshot Statevector test circuits reference counts.""" targets = [] # Snapshot |000> + i|111> targets.append({'0x0': shots/2, '0x7': shots/2}) # Snapshot |+++> targets.append({'0x0': shots/8, '0x1': sh...
def pretty_describe(object, nestedness=0, indent=2): """Nice YAML-like text version of given dict/object Maintains dict ordering """ if not isinstance(object, dict): return str(object) sep = '\n{}'.format(" " * nestedness * indent) out = sep.join(('{}: {}'.format(k, pretty_describe(v, n...
def is_linux(conf): """ `is_linux` returns true if we are building for linux FIXME: we should probably test a waf-based variant or configuration variable rather than sys.platform... """ import sys return 'linux' in sys.platform.lower()
def bootstrap_level(level: str) -> str: """Maps logging levels to bootstrap levels. Defaults to light. Arguments: level: The logging level. """ return { "DEBUG": "secondary", "INFO": "info", "WARNING": "warning", "ERROR": "danger", }.get(level.upper(), "light...
def create_hover_text(node_attributes, only_use=set()): """ create string of node attributes :param dict node_attributes: a dict such as: {'attr': {'pos': None, 'lemma': 'demonstratie', 'mw': False, 'rbn_type': None, 'rbn_feature_set': None} ...
def count_in_str(pattern, str): """counts the number of times the pattern appears in the string for example: count_in_str("a", "abcaabc") returns 3 count_in_str("ab", "abcaabc") return 2""" c = 0 sp = len(pattern) while len(str) >= sp: slice = str[:sp] if pattern == s...
def reformat_dict_f(dic, mapping): """ switch keys with key values (unique identifier) """ return {k: dic[v] for k, v in mapping.items()}
def damerau_levenshtein_distance(word1: str, word2: str) -> int: """Calculates the distance between two words.""" inf = len(word1) + len(word2) table = [[inf for _ in range(len(word1) + 2)] for _ in range(len(word2) + 2)] for i in range(1, len(word1) + 2): table[1][i] = i - 1 for i in range...
def solution(A): """ DINAKAR Idea is xor of two same numbers produces 0 x = 3 (011) and y = 3 (011) is 000 at the end single numbers left in xor variable. :return: """ xor = 0 for item in A: xor ^= item return xor
def prune_none_and_empty(d): """ Remove keys that have either null values, empty strings or empty arrays See: https://stackoverflow.com/a/27974027/5472444 """ if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in [prune_none_and_empty(v) for v in d] if v] return ...
def __uglify(text: str) -> str: """ csv and json format output contain this non human readable header string: no CamelCase and no space. """ return text.lower().replace(' ', '_')
def parent_index(i): """Vrati index rodice prvku na pozici 'i'. Pokud neexistuje, vrati None. """ return (i - 1) // 2 if i > 0 else None
def create_lzh (archive, compression, cmd, verbosity, interactive, filenames): """Create a LZH archive.""" opts = 'a' if verbosity > 1: opts += 'v' cmdlist = [cmd, opts, archive] cmdlist.extend(filenames) return cmdlist
def transaction_type_5(): """Transaction of type "ipfs" """ data = { 'data': {}, 'serialised': '' } return data
def _client_type(app_id): """ Determine whether the given ID is a bundle ID or a a path to a command """ return "1" if app_id[0] == "/" else "0"
def newton(f,seed,itern=10,rounding=3,diff_tol=0.1,sol_tol=1E-10): """ The function newton has several parameters all of them has been talked about a bit below: 1. f: It is the function/equation to be solevd, the user of the package must define this function before calling the solve...
def normalize_text(text): """tidy up string""" return text.replace('\n', '')
def String_to_Tips(string): """ given a .newick subtree as a string, return a list of the tips args string: should be a .newick string eg "((A,B),((C,D),E))" returns overall_tiplist: a list that looks like ["A", "B", "C", "D", "E"] str_to_tips: a dict of all subclades to their tiplists. {"((A,B),((C,...
def restart_omiserver(run_command): """ Restart omiserver as needed (it crashes sometimes, and doesn't restart automatically yet) :param run_command: External command execution function (e.g., RunGetOutput) :rtype: int, str :return: 2-tuple of the process exit code and the resulting output string (r...
def regex_matches_to_indexed_words(matches): """Transforms tokensregex and semgrex matches to indexed words. :param matches: unprocessed regex matches :return: flat array of indexed words """ words = [dict(v, **dict([('sentence', i)])) for i, s in enumerate(matches['sentences']) ...
def get_url_without_trailing_slash(value): """ Function which strips a trailing slash from the provided url if one is present. :param value: URL to format. :type value: ``str`` :rtype: ``str`` """ result = value[:-1] if value.endswith("/") else value return result
def middleware(resolver, obj, info, **kwargs): """ example middleware """ return resolver(obj, info, **kwargs)
def find_char_groups(s): """ Find character groups """ pos = 0 groups = [] escaped = False found = False first = None for c in s: if c == "\\": escaped = not escaped elif escaped: escaped = False elif c == "[" and not found: ...
def properties(obj): """ Returns a dictionary with one entry per attribute of the given object. The key being the attribute name and the value being the attribute value. Attributes starting in two underscores will be ignored. This function is an alternative to vars() which only returns instance vari...
def decimal_to_base2(dec): """Convert decimal number to binary number by iteration. Time complexity: O(d/2). Space complexity: O(d/2). """ # Push remainders into stack. rem_stack = [] while dec > 0: dec, rem = divmod(dec, 2) rem_stack.append(rem) # Pop remainders and co...
def show_size(n) -> str: """ Returns the size ``n`` in human readable form, i.e. as bytes, KB, MB, GB, ... :return: human readable size """ _n = n if _n < 1024: return "{} bytes".format(_n) for dim in ['KB', 'MB', 'GB', 'TB', 'PB']: _n = _n / 1024.0 if _n < 1024: ...
def chunk(mylist, chunksize): """ Args: mylist: array chunksize: int Returns: list of chunks of an array len chunksize (last chunk is less) """ N = len(mylist) chunks = list(range(0, N, chunksize)) + [N] return [mylist[i:j] for i, j in zip(chunks[:-1], chunks[1:])]
def cleanup_favorite(favorite): """Given a dictionary of a favorite item, return a str.""" return str(favorite["post"])
def _pad_sequences(sequences, pad_tok, max_length): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with Returns: a list of list where each sublist has same length """ sequence_padded, sequence_length = [], [] for seq in sequences: seq...
def get_shifted_product(first_list: list, second_list: list) -> list: """ Returns a list of the product of each element in the first list with each element in the second list shifted by one index. """ shifted_second_list = second_list[1:] return [a * b for a, b in zip(first_list, shifted_second_...
def get_result_from_input_values(input, result): """Check test conditions in scenario results input. Check whether the input parameters of a behave scenario results record from testapi match the input parameters of the latest test. In other words, check that the test results from testapi come from a t...
def check_not_finished_board(board: list): """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\ '*?????*', '*?????*', '*2*1***']) False >>> ch...
def ilen(iterator): """ Counts the number of elements in an iterator, consuming it and making it unavailable for any other purpose. """ return sum(1 for _ in iterator)
def rewardListToString(s): """[Turns a List of Reward Objects into a comma seperated strings] Arguments: s {[list of rewards]} -- [list of rewards] Returns: [String] -- [string of comma seperated reward names] """ # initialize an empty string str1 = "" rew...
def argument(*name_or_flags, **kwargs): """Helper function to satisfy argparse.ArgumentParser.add_argument()'s input argument syntax""" return (list(name_or_flags), kwargs)
def get_gear_ratio(g: int, gear_ratios: dict): """get gear ratio Args: g (int): gear gear_ratios (dict): mapping of gear to gear ratio Returns: [float]: gear ratio """ return gear_ratios[g]['ratio']
def _kamb_radius(n, sigma): """Radius of kernel for Kamb-style smoothing.""" a = sigma**2 / (float(n) + sigma**2) return (1 - a)
def _embedded_checkpoint_frames(prefixed_frame_dict): """prefixed_frame_dict should be a dict of base64-encoded files, with prefix""" template = ' checkpoint_frames[{0}] = "{1}"\n' return "\n" + "".join(template.format(i, frame_data.replace('\n', '\\\n')) for i, frame_data in pr...
def newton(f, f_prime, x0, tol): """ Find the root of f(x) = 0 using the Newton-Raphson method recursively. Parameters ---------- f - function f_prime - derivative of f x0 - starting value tol - tolerance Returns ------- root of f(x) """ ...
def get_str2id(strings_array): """Returns map from string to index in array. """ str2id = {} for i in range(len(strings_array)): str2id[strings_array[i]] = i return str2id
def pluralize(input): """Readwise pluralize""" if input == 1: return '' else: return 's'
def has_prefix(sub_s, dic): """ :param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid :return: (bool) If there is any words with prefix stored in sub_s """ if sub_s == None: return True for word in dic: if word.startswith(sub_s): return True return False
def map_labels(labels, mapping): """Map labels to new labels defined by mapping.""" return [mapping.get(l, l) for l in labels]
def uuid_from_obj(obj): """Try to get uuid from an object. Args: obj (Object): The object possibly containing uuid. Returns: Object: obj.uuid if it exists; otherwise, obj """ if hasattr(obj, "uuid"): return obj.uuid return obj
def getMoshDamage(n): """ Amount of damage from a mosh with N players on stage """ if n > 6 or n < 1: raise Exception("Invalid n={}".format(n)) return [5,10,20,40,64,100][n-1]
def to_hectar(x, resx, resy): """convert a pixel number into a surface in hectar using the provided resolution (res in meters)""" return x * resx * resy / 10000
def _trim_dollar(value): """Trim dollar character if present.""" return value[1:] if value.startswith("$") else value