content
stringlengths
42
6.51k
def ooi_instrument_reference_designator(reference_designator): """ Parses reference designator into a dictionary containing subsite, node, and sensor. Args: reference_designator (str): OOI Instrument Reference Designator Returns: Dictionary of the parsed reference designator ""...
def last(iterable, *default): """Return the last item of an iterable or 'default' if there's none.""" try: iterable = reversed(iterable) except TypeError: pass else: return next(iterable, *default) iterable = iter(iterable) x = next(iterable, *default) for x in iterable: pass return x
def precision(TP, FP): """Precision or positive predictive value""" return (TP) / (TP + FP)
def _is_global_dataset(dataset: dict) -> bool: """Returns wether the given dataset is spotlight specific (FALSE) or non-spotlight specific (TRUE)""" return not any( [ i in dataset["source"]["tiles"][0] for i in ["{spotlightId}", "greatlakes", "togo"] ] )
def manhattan_distance(x, y): """Manhattan distance.""" return abs(0-x) + abs(0-y)
def inner2D(v1, v2): """Calculates the inner product of two 2D vectors, v1 and v2""" return v1[0]*v2[0] + v1[1]*v2[1]
def slice_double_accept(xp,x,u,step,interval,lnpdf,pdf_params): """ NAME: slice_double_accept PURPOSE: accept a step when using the doubling procedure INPUT: xp - proposed point x - current point u - log of the height of the slice step ...
def contains_missing(row): """ Returns true if the row contains a missing value somewhere """ for e in row: if e == '?': return True return False
def osm_zoom_level_to_pixels_per_meter( zoom_level: float, equator_length: float ) -> float: """ Convert OSM zoom level to pixels per meter on Equator. See https://wiki.openstreetmap.org/wiki/Zoom_levels :param zoom_level: integer number usually not bigger than 20, but this function allows ...
def _split_section_and_key(key): """Return a tuple with config section and key.""" parts = key.split(".") if len(parts) > 1: return "{0}".format(parts[0]), ".".join(parts[1:]) return "renku", key
def get_new_in_current(l_new, l_old, pattern_dict): """ Get those labels, that are supposed to be added but were already there and known :param l_new: new labels :param l_old: old labels :param pattern_dict: directory of patterns that are used to match the filenames :type l_new: ...
def base64_add_padding(data): """ Add enough padding for base64 encoding such that length is a multiple of 4 Args: data: unpadded string or bytes Return: bytes: The padded bytes """ if isinstance(data, str): data = data.encode('utf-8') missing_padding = 4 - len(dat...
def strip_prefix(string, strip): """ Strips a prefix from a string, if the string starts with the prefix. :param string: String that should have its prefix removed :param strip: Prefix to be removed :return: string with the prefix removed if it has the prefix, or else it just returns the or...
def element_counts(formula_list): """ Docstring for function pyKrev.element_counts ==================== This function takes a list of formula strings and gives atomic counts for C,H,N,O,P & S. Use ---- element_counts(Y) Returns a list of len(Y) in which each element is a dictionary containing...
def restore_args_with_whitespace(x): """Restore args with whitespace, to support file paths with whitespace""" y = [] for xi in x: if len(y) == 0: y.append(xi) else: if y[-1].endswith('\\'): y[-1] = y[-1][0:-1] + ' ' + xi else: ...
def convert_hex_into_decimal(hex_number: str) -> int: """ Converts a hexadecimal number into a decimal :param hex_number: :return: """ return int(hex_number, 16)
def setDefault(infile, outfile, keyfile, mode): """ Sets default params for easier testing/input in command line :param infile: file to read :param outfile: file to output :param keyfile: file to read key from :param mode: mode, either encrypt or decrypt only :return: all 4 fields initialize...
def checkFloat(value, default, allowNone=False): """Check if a variable is an float or a none.""" if allowNone and (value is None or value == "None"): return None try: return float(value) except Exception: return default
def collect_alignment(adict, off): """Collect alignment histogram.""" algn = 1 for ii in range(0, 5): mask = 1 << ii if off & mask: break algn *= 2 if algn in adict: adict[algn] += 1 else: adict[algn] = 1 return algn
def update_label(old_label, exponent_text): """Copied from: https://ga7g08.github.io/2015/07/22/Setting-nice-axes-labels-in-matplotlib/""" if exponent_text == "": return old_label try: units = old_label[old_label.index("[") + 1:old_label.rindex("]")] except ValueError: units...
def median(data): """Calculate the median of a list.""" data.sort() num_values = len(data) half = num_values // 2 if num_values % 2: return data[half] return 0.5 * (data[half-1] + data[half])
def itraceToStr( trace ): """ Concerts an instruction trace into a string """ traceStr = "" for i in trace: traceStr += "%s," % i[0] return traceStr[:-1]
def encode_varint_1(num): """ Encode an integer to a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: num (int): Value to encode Returns: bytearray: Encoded presentation of i...
def achat_submit_row(context): """ Displays the row of buttons for delete and save. """ opts = context['opts'] change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] ctx = { 'opts': opts, 'show_delete_link': False, 'show_save_as_new...
def bibser2bibstr(bib=u'', ser=u''): """Return a valid bib.series string.""" ret = bib if ser != u'': ret += u'.' + ser return ret
def solution(number): # O(N) """ Write a function to compute the fibonacci sequence value to the requested iteration. >>> solution(3) 2 >>> solution(10) 55 >>> solution(20) 6765 """ m = { 0: 0, 1: 1 } ...
def brightness_from_percentage(percent): """Convert percentage to absolute value 0..255.""" return (percent*255.0)/100.0
def getAllRootPaths(goId, goData): """ find all paths to the root for a given GO ID """ if not goId: return list() if goId not in goData: return [[goId]] res = list() for i in goData[goId]: paths = getAllRootPaths(i, goData) for path in paths: res.append...
def sh_parse_tile(s): """ Parse tile strings """ string = s.split(" ") final = [] for i in range(len(string)): final.append(max(min(int(string[i]), 63), 0)) return final
def translate(text, conversion_dict, before=None): """ Translate words from a text using a conversion dictionary Arguments: text: the text to be translated conversion_dict: the conversion dictionary before: a function to transform the input (by default it will fall back to t...
def unique_list(inp_list): """ returns a list with unique values of inp_list. :usage: >>> inp_list = ['a', 'b', 'c'] >>> unique_inp_list = unique_list(inp_list*2) """ return list(set(inp_list))
def requires_reload(action, plugins): """ Returns True if ANY of the plugins require a page reload when action is taking place. """ return any(p.get_plugin_class_instance().requires_reload(action) for p in plugins)
def strip_suffix(target, suffix): """ Remove the given suffix from the target if it is present there Args: target: A string to be formatted suffix: A string to be removed from 'target' Returns: The formatted version of 'target' """ if suffix is None or target is None: ...
def is_user_context(context): """Indicates if the request context is a normal user.""" if not context: return False if context.is_admin: return False if not context.user_id or not context.project_id: return False return True
def fileExistenceCheck(filepath,filename): """ Checks if the file exists in the location passed :param filepath: location of the file :type arg1: string :param filename: :type arg2: string """ from pathlib import Path tempfile = Path(filepath+filename) if tempfile.is_...
def _parse_cgroup_ids(cgroup_info): """Returns a dictionary of subsystems to their cgroup. Arguments: cgroup_info: An iterable where each item is a line of a cgroup file. """ cgroup_ids = {} for line in cgroup_info: parts = line.split(':') if len(parts) != 3: co...
def get_log(name): """Return a console logger. Output may be sent to the logger using the `debug`, `info`, `warning`, `error` and `critical` methods. Parameters ---------- name : str Name of the log. References ---------- .. [1] Logging facility for Python, http...
def removesuffix(string_, suffix): """As i ran into https://www.python.org/dev/peps/pep-0616/ .""" if suffix and string_.endswith(suffix): return string_[:-len(suffix)] else: return string_
def normalize_case(text): """ Normalize case of some (all-{upper|lower}case) text. Uses a wordlist to determine which words need capitalization. """ # todo: figure out a smarter way :) SPECIAL_CASE_WORDS = [ 'Trento', 'Provincia', ] text = text.lower() for word in SPECIAL_CA...
def beta_from_normalized_beta(beta_normalized, N, M): """ input: beta_normalized N: total number of values in each input image (pixels times channels) M: number of latent dimensions computes beta = beta_normalized * N / M given the relationship: ...
def add_linebreaks(text, max_len=80): """ Add linebreaks on whitespace such that no line is longer than `max_len`, unless it contains a single word that's longer. There are probably way faster methods, but this is simple and works. """ br_text = '' len_cnt = 0 for word in text.split(' '): len_cnt += len(word...
def binary_search(items, item, comparator=(lambda x, y: 0 if x == y else 1 if x > y else -1), lo=0, hi=None, insertion_index=False): """ Does a binary search on a list using a custom comparator :param items: sorted list of items to search :param item: item to find :param comparator...
def get_state(edge, distances): """ create one row for the log ['v1-v2', dist, dist, ...] """ edge_s = ['(' + edge[0] + '-' + edge[1] + ')'] distances_l = [distances[i] for i in sorted(distances.keys())] state = edge_s + distances_l return state
def test_fake_group(group_no, groups): """ Does tag span many groups? If so we'll create pseudo group of groups. Return the number of groups and total number of posts if true. Otherwise, return 0, 0 :param: group_no: Group number within groups list :param: groups: List of :return: Tru...
def _flash_encryption_tweak_range_bits(flash_crypt_config=0xF): """ Return bits (in reverse order) that the "key tweak" applies to, as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value. """ tweak_range = 0 if (flash_crypt_config & 1) != 0: tweak_range |= 0xFFFFFFFFFFFFFFFFE0000000000000...
def transaction_location_validator(transaction_location_pid): """Validate that the given transaction location PID is valid.""" return transaction_location_pid == "loc_pid"
def bold_viewed(val, viewed_pages): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ weight = 'bold' if val in viewed_pages else 'normal' return 'font-weight: %s' % weight
def word_preprocessing(word, ignore_non_alnumspc=True, ignore_space=True, ignore_numeric=True, ignore_case=True): """ Function for word preprocessing | | Argument | | word: a string to be processed | | Parameter | | ignore_non_alnumspc: whether to remove all non alpha/numeric/space characters | | ignore_space...
def pad_with_object(sequence, new_length, obj=None): """ Returns :samp:`sequence` :obj:`list` end-padded with :samp:`{obj}` elements so that the length of the returned list equals :samp:`{new_length}`. :type sequence: iterable :param sequence: Return *listified* sequence which has been end-padded. ...
def is_required_version(version, specified_version): """Check to see if there's a hard requirement for version number provided in the Pipfile. """ # Certain packages may be defined with multiple values. if isinstance(specified_version, dict): specified_version = specified_version.get("versio...
def convert_vars_to_readable(variables_list): """Substitutes out variable names for human-readable ones :param variables_list: a list of variable names :returns: a copy of the list with human-readable names """ human_readable_list = list() for var in variables_list: if False: # var in V...
def isstrictlyascending(lam): """This determines whether the index string is a strictly ascending sequence Parameters ---------- lam : an indexable object of things that are comparable. Usually an array of integers Returns ------- bool : true if the sequence is strictly ascending, else fal...
def is_magic_packet(data): """ Checks if a packet is a magic packet, returns True or False. Args: data (bytes): the payload from a packet """ # convert data to lowercase hex string data = data.hex().lower() # magic packets begin with 'f'*12 (called a synchronization stream) ...
def getMissingIndex(x): """ For a list, remove value in [" ",""] :param x(list): list of strings :returns empty_index: Index of empty String elements :returns x: Input list with empty element replaced with ".." """ empty_index = [i for i,elem in enumerate(x) if elem in [" ",""]] for i in...
def get_dynamic_hasher_names(HMAC_KEYS): """ Return base dynamic hasher names for each entry in HMAC_KEYS (we need to create one hasher class for each key). Names are sorted to make sure the HMAC_KEYS are tested in the correct order and the first one is always the first hasher name returned. """...
def is_iterable(obj) -> bool: """Whether the given object is iterable or not. This is tested simply by invoking ``iter(obj)`` and returning ``False`` if this operation raises a TypeError. Args: obj: The object to test Returns: bool: True if iterable, False else """ try: ...
def pattern_to_similarity(pattern: str) -> int: """ Convert a pattern of string consisting of '0', '1' and '2' to a similarity rating. '2': right letter in right place '1': right letter in wrong place '0': wrong letter :param pattern: string of pattern :return: similarity """ return ...
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'input_pdb_path': ['pdb', 'pqr'], 'input_clusters_zip': ['zip'], 'resid_pdb_path': ['pdb'], 'input_pdbqt_path': ['pdbqt'], 'output_pdb_path': ['pdb'], 'output_pdbqt_path': ['pdbqt'] } return ext i...
def value_shape(shape): """ """ return [shape[0], shape[1], 1]
def remove_html_spans(batch): """Removes lines containing a '<' or '>' from the texts.""" bad_strings = ["<", ">"] return { **batch, "text": [ "\n".join([line for line in text.split("\n") if not any([bs in line for bs in bad_strings])]) for text in batch["text"] ...
def isTriangle(input): """Check if list of three sides is a triangle.""" if 2*max(input) < sum(input): return True return False
def parse_commit_info(git_log, git_commit_fields=('id', 'body', 'author', 'timestamp', 'subject')): """Seperates the various parts of git commit messages Args: git_log(str): git commits as --format='%H%x1f%b%xlf%ae%xlf%ci%xlf%s%x1e' git_commit_...
def bounding_box_text(svg, node, font_size): """Bounding box for text node.""" return node.get('text_bounding_box')
def nf_input_to_cl(inp): """Convert an input description into command line argument. """ sep = " " if inp.get("separate") else "" val = "'%s'" % inp.get("default") if inp.get("default") else "$%s" % inp["name"] return "%s%s%s" % (inp["prefix"], sep, val)
def differentiateTwice(f, x0, h): """ @param f: function to differentiate) @param method: FDF, BDF, centered @param x0: point to differentiate at @return: f'(x0) """ df = (f(x0+h)-2*f(x0)+f(x0-h))/(h*h) return df
def build_years_array(db_years, first_year=None, last_year=None): """The database queries are parameterized to accept a single year of data. This function takes a two element array [db_years] (which contains year first and last years in the target database) and two optional arguments that specify the e...
def convert_points_to_letter(point): """ Converts a given point to a letter grade. Parameters: A number in range of 0 to 100. Returns: Letter grade. """ if point >= 94: grade = 'A' elif point >= 87 and point < 94: grade = 'A-' elif point >= 83 and point < 86: ...
def log_evidence_from_file_summary(file_summary, prior_count): """Open the file "multinestsummary.txt" and extract the log evidence of the Multinest analysis. Early in the analysis this file may not yet have been created, in which case the log evidence estimate is unavailable and (would be unreliable a...
def top_similars_reduce(data): """ reduce for top similars """ sim, item = data return (sim, item)
def union_overlapping(intervals): """Union any overlapping intervals in the given set.""" disjoint_intervals = [] for interval in intervals: if disjoint_intervals and disjoint_intervals[-1].overlaps(interval): disjoint_intervals[-1] = disjoint_intervals[-1].union(interval) else: disjoint_inte...
def distribute_n(n, n_proc, pid): """ l: list of elements to be distributed among n_proc processors pid: (int) process id of the process calling this function n_proc: total number of processors Returns the min and max index to be assigned to the processor with id pid """ n_per_proc = int(n /...
def get_layerwise_manipulation_strength(num_layers, truncation_psi, truncation_layers): """Gets layer-wise strength for manipulation. Recall the truncation trick played on layer [0, truncation_layers): w = truncation_psi * w + (1 - ...
def is_valid_role(role): """Check if a string is a valid role for use with gspread.""" return role in ["writer", "reader"]
def pop_recursive(d, key, default=None): """dict.pop(key) where `key` is a `.`-delimited list of nested keys. >>> d = {'a': {'b': 1, 'c': 2}} >>> pop_recursive(d, 'a.c') 2 >>> d {'a': {'b': 1}} """ if not isinstance(d, dict): return default if key in d: return d.pop(...
def datetime_as_iso(value): """Helper function to format datetime object to ISO8601 string.""" import datetime if not isinstance(value, datetime.datetime): return "" retval = value.strftime("%Y-%m-%dT%H:%M:%S%z") if not value.utcoffset(): return "".join([retval, "Z"]) return retv...
def intersect(lst1, lst2): """intersection of two lists """ lst3 = [value for value in lst1 if value in lst2] return lst3
def dp_make_weight(egg_weights, target_weight, memo={}): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is always a egg of value 1. Parameters: egg_weights - tuple of integers, available egg weights sor...
def fifo_pre_sequencing(dataset, *args, **kwargs): """ Generates an initial job sequence based on the first-in-first-out dispatching strategy. The job sequence will be feed to the model. """ sequence = [job for job in dataset.values()] return sequence
def tolist(a): """Given a list or a scalar, return a list.""" if getattr(a, '__iter__', False): return a else: return [a]
def _linearly_scale(inputmatrix, inputmin, inputmax, outputmin, outputmax): """ used by linke turbidity lookup function """ inputrange = inputmax - inputmin outputrange = outputmax - outputmin OutputMatrix = (inputmatrix-inputmin) * outputrange/inputrange + outputmin return OutputMatrix
def extend(target, element): """ Extend the given list with the given element. If element is a scalar, it is appended to target; if element is a list, target is extended with it. >>> extend([1, 2], 4) [1, 2, 4] >>> extend([1, 2], (1, 2,)) [1, 2, 1, 2] >>> extend([1, 2], {1: 2, 3: 4}) ...
def bisection1D(f, a, b, delta=0.00001): """ Find solution to f(x) = 0 with bisection method :param f: function f :param a: left starting point for x :param b: right starting point for x :param delta: threshold for solution :return: x """ start, end = a, b if f(a) == 0: r...
def full_name(user): """ returns users full name. Args: user (User): user object. Returns: str: full name from profile. """ if not user or not user.profile: return None profile = user.profile first = profile.first_name or profile.user.username last = " {}"....
def count_elements(head): """Counts the total number of elements inside the list""" if head is None: return -1 count = 1 curr = head while curr.next != head: count += 1 curr = curr.next return count
def _mk_range_bucket(name, n1, n2, r1, r2): """ Create a named range specification for encoding. :param name: The name of the range as it should appear in the result :param n1: The name of the lower bound of the range specifier :param n2: The name of the upper bound of the range specified :para...
def o_summ(listy): """ Input: A list of numbers. Output: The sum of all the numbers in the list, using sum function. """ return (sum(listy))
def int2bin(n): """convert a non-negative integer to raw binary buffer""" buf = bytearray() while n > 0: buf.insert(0, n & 0xFF) n >>= 8 return bytes(buf)
def get_fusion_options(defaults=None): """Adding arguments for the fusion subcommand """ if defaults is None: defaults = {} options = { # If a list of BigML models is provided, the script will # create a Fusion from them '--fusion-models': { "action": 'stor...
def increment(valence, increment): """ increment in the same direction as the valence """ if valence == 0.0: return valence elif valence > 0: return valence + increment else: # valence < 0 return valence - increment
def getobjectindex(blocklst,object): """ getobjectindex(blocklst,'SOLUTION ALGORITHM') returns the index of the object corresponding slashcomments can be retrived using this index """ ls=[] for el in blocklst: ls.append(el[0].upper()) return ls.index(object.upper())
def fix_3(lst): """ For each element in `lst`, add it with its following element in the list. Returns all of the summed values in a list. >>> fix_3([1, '1', 2, None]) <class 'TypeError'> <class 'TypeError'> <class 'TypeError'> <class 'IndexError'> [] >>> fix_3([1, 2, 3, 4]) ...
def get_puzzle(complex:bool = False) -> str: """Returns puzzle with high or medium complexity. Args: complex (bool, optional):An option if harder puzzle is required. Defaults to False. Returns: str: Returns puzzle string. """ if complex: return '4.....8.5.3..........7.........
def get_z_2p(x_1, x_2, s1, s2, n1, n2): """ """ if (n1 <= 30 or n2 <= 30): print("The sample sizes must be greater than 30.") else: s_error = ((s1**2 / n1) + (s2**2 / n2))**0.5 z = (x_1 - x_2) / s_error return z
def getAllIndices(element, alist): """ Find the index of an element in a list. The element can appear multiple times. input: alist - a list element - objective element output: index of the element in the list """ result = [] offset = -1 while True: try: o...
def module_name(prog): """ get the module name for a program """ return '_{}'.format(prog)
def is_final_option(string): """Whether that string means there will be no further options >>> is_final_option('--') True """ return string == '--'
def timezone_choice(tzname, country=None): """ Given a timezone string, convert it to a two-tuple suitable for a choice in a FormField. >>> timezone_choice('UTC') ('UTC', 'UTC') >>> timezone_choice('Australia/Sydney') ('Australia/Sydney', 'Sydney') >>> timezone_choice('America/Indiana/I...
def format_dictionary(adict, sep=', ', sort_first=True): """\ Formats a dictionary into a string of key=value pairs. :param adict: dictionary to format :param sep: separator. Default ',' :param sort_first: whether to sort the key-value pairs first before formatting :return: a string with the fo...
def html_format(obj, indent=0, notify_complete=False): """Formats one or more patient objects to a nice html string Args: obj(list): a list of patient objects or a patient object notify_complete(bool): set to False to NOT notify variants and phenotype terms by email """ if isinstance(ob...
def induce_soft_constraints(data, result): """ Induces Soft-constraints by adding High cost value to hingh confident edges. """ if "high_confident" in data["edges"].keys(): high_confidention_cost = -1000 result['edge_costs'] = result['edge_costs'] + data["edges"]["high_confident"] * high...