content
stringlengths
42
6.51k
def tj(a): """ Tab Join """ return "\t".join(map(lambda i: str(i), a))
def build_latex(hyp): """ Parameters ---------- hyp : dict {'segmentation': [[0, 3], [1, 2]], 'symbols': [{'symbol': ID, 'probability': 0.12}], 'geometry': {'symbol': index, 'bottom': None or dict, 'subscript': None or dict, ...
def getHashedBucketEndpoint(endpoint, file_name): """ Return a hashed bucket endpoint """ # Example: # endpoint = "atlas_logs", file_name = "log.tgz" # -> hash = "07" and hashed_endpoint = "atlas_logs_07" # return endpoint + "_" + getHash(file_name, 2) return endpoint
def pt2px(pt): """Crude point to pixel work""" return int(round(pt * 96.0 / 72))
def ApplyFuncs(data, funcs): """Takes input data and list of str funcs; evals; applies.""" for f in funcs: try: func = eval("lambda x: "+f) data = func(data) except Exception as e: print("Function "+f+" did not evaluate correctly:") print(e) ...
def gini(clusters_labels): """Compute the Gini coefficient for a clustering. Parameters: - clusters_labels: pd.Series of labels of clusters for each point. """ import pandas as pd # Get frequencies from clusters_labels clusters_labels = pd.Series(clusters_labels) frequencies = c...
def callMultiF(f,n,cache): """ Try to get n unique results by calling f() multiple times >>> import random >>> random.seed(0) >>> callMultiF(lambda : random.randint(0,10), 9, set()) [9, 8, 4, 2, 5, 3, 6, 10] >>> random.seed(0) >>> callMultiF(lambda : random.randint(0,10), 9, set([8,9,10]...
def _get_hamming_distance(a, b): """Calculates hamming distance between strings of equal length.""" distance = 0 for char_a, char_b in zip(a, b): if char_a != char_b: distance += 1 return distance
def apply_cushion(x0, x1, cushion): """ x0, x1: ints, x coordinates of corners. cushion: float, how much leniancy to give. """ if x0 < x1: x0 += cushion x1 -= cushion else: x0 -= cushion x1 += cushion return x0, x1
def choose_mrna(mrna1, mrna2, min_identity, max_ratio_diff, blast_dict): """ """ best_mrna = None best_mrna_length = 0 for mrna in [mrna1, mrna2]: if not mrna: continue if mrna not in blast_dict: continue transcript_name = mrna.split(".mrna")[0] # if the best match is a protein fro...
def beta(R0, gamma, prob_symptoms, rho): """ R0 from model parameters. """ Qs = prob_symptoms return R0 * gamma / (Qs + (1 - Qs) * rho)
def sort_by_key_asc(my_list=[], keys=[]): """ Reorder your list ASC based on multiple keys Parameters: :param (list) my_list: list of objects you want to order [{'code': 'beta', 'number': 3}, {'code': 'delta', 'number': 2}] :param (list) keys: list of keys and direction to orde...
def get_table_position(screen_layout): """ return first position of table encountered within screen layout """ for _, data in screen_layout.items(): if data.get('table'): return data['position'] return None
def font_size_picker(button_name, input): """ description: - Increase font for highlited button :param buttonname: the button to be determined wheter to be bigger or not :param game_state: the button to be highlighted :return: int font size """ if button_name == "move_left" and input...
def _reverse_ordering(ordering_tuple): """ Given an order_by tuple such as `('-created', 'uuid')` reverse the ordering and return a new tuple, eg. `('created', '-uuid')`. """ def invert(x): return x[1:] if (x.startswith('-')) else '-' + x return tuple([invert(item) for item in ordering_...
def prime_factors(n): """ GCD algorithm to produce prime factors of `n` Parameters ---------- n : int The number to factorize. Returns ------- list The prime factors of `n`. """ i = 2; factors = [] while i * i <= n: if n % i: i += 1 ...
def compare_queryset(first, second): """ Simple compare two querysets (used for many-to-many field compare) XXX: resort results? """ result = [] for item in set(first).union(set(second)): if item not in first: # item was inserted item.insert = True elif item not in se...
def xmlbool(bool): """Convert a boolean into the string expected by the elfweaver XML.""" # Is there a smarter way of doing this? if bool: return "true" else: return "false"
def in_array(array1, array2): """This function is the solution to the Codewars Which are in? Kata that can be found at: https://www.codewars.com/kata/550554fd08b86f84fe000a58/train/python""" words_in_array = set() for word_from_array2 in array2: for word_from_array1 in array1: ...
def mad_quote(value): """Add quotes to a string value.""" if '"' not in value: return '"' + value + '"' if "'" not in value: return "'" + value + "'" # MAD-X doesn't do any unescaping (otherwise I'd simply use `json.dumps`): raise ValueError("MAD-X unable to parse string with escaped...
def fileno(file_or_fd): """Return a file descriptor from a file descriptor or file object.""" fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)() if not isinstance(fd, int): raise ValueError("Expected a file (`.fileno()`) or a file descriptor") return fd
def _check_eftype(eftype): """Check validity of eftype""" if eftype.lower() in ['none', 'hedges', 'cohen', 'glass', 'r', 'eta-square', 'odds-ratio', 'auc']: return True else: return False
def v1_deep_add(lists): """Return sum of values in given list, iterating deeply.""" total = 0 lists = list(lists) while lists: item = lists.pop() if isinstance(item, list): lists.extend(item) else: total += item return total
def _change_controller_type(raid_config, type): """Typecast the controller values to requested type :param raid_config: The dictionary containing the requested RAID configuration. :param type: Requested type for the typecast :returns raid_config: The modified raid_config with typecasted ...
def sumatoria_gauss(n: int) -> int: """CHALLENGE OPCIONAL: Re-Escribir utilizando suma de Gauss. Referencia: https://es.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF """ return n * (n + 1) // 2
def split_forward_slash_value(value, default): """ Returns '<default>/<value>' if value does not contain '/', otherwise '<token1>/<token2>' """ if '/' in value: return tuple(value.split('/', 1)) return default, value
def safe_repr(obj, limit=1000): """ Find the repr of the object, but limit the number of characters. """ r = repr(obj) if len(r) > limit: hlimit = limit // 2 r = '%s ... %s' % (r[:hlimit], r[-hlimit:]) return r
def root_equals(col: str, val: str) -> str: """Return a string that has col = val.""" return f"{col} = {val}"
def _parse_conll_identifier( value: str, line: int, field: str, *, non_zero=False ) -> int: """Parse a CoNLL token identifier, raise the appropriate exception if it is invalid. Just propagate the exception if `value` does not parse to an integer. If `non_zero` is truthy, raise an exception if `va...
def generate_hosts_inventory(json_inventory): """Build a dictionary of hosts and associated groups from a Ansible JSON inventory file as keys. Args: json_inventory (dict): A dictionary object representing a Ansible JSON inventory file. Returns: dict(list): A dictionary of hosts with each ho...
def different_ways_tabulation(n): """Tabulation implementation of different ways, O(n) time and O(n) space pre-allocated""" # build array such that d[i] = # ways to write i as sum of 1s, 3s, and 4s d = [0] * (n + 1) # d allows us to define D0 = 1 as above, but we cannot represent Dn = 0 for negative n...
def _round_up_div(a: int, b: int) -> int: """Divide by b and round up to a multiple of b""" return (a + b - 1) // b
def left_rotate(n, b): """Left rotate a 32-bit integer n by b bits.""" return ((n << b) | (n >> (32 - b))) & 0xffffffff
def square_and_multiply(x, k, p=None): """ Square and Multiply Algorithm Parameters: positive integer x and integer exponent k, optional modulus p Returns: x**k or x**k mod p when p is given """ b = bin(k).lstrip('0b') r = 1 for i in b: r = r ** 2 if i == ...
def load_file(file_path): """Load the contents of a file into a string""" try: with open(file_path, 'r') as file: return file.read() except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available return None
def editdistance(seq1, seq2): """Calculate the Levenshtein edit-distance between two strings. The edit distance is the number of characters that need to be substituted, inserted, or deleted, to transform seq1 into seq2. For example, transforming 'rain' to 'shine' requires three steps, consisting of two substitut...
def score_style(polarity_value): """ Returns colour of score progress bar based on polarity score. :param polarity_value: the polarity :return color: the colour of the progress bar """ color = 'warning' if polarity_value < 33: color = 'danger' if polarity_value > 66: ...
def press_Davison_1968(t_k): """From Davison Parameters ---------- t_k, K Returns ------- Vapor pressure, Pa References ---------- Davison, H.W. "Complication of Thermophysical Properties of Liquid Lithium." NASA Technical Note TN D-4650. Cleveland, Ohio: Lewis Researc...
def strip_quotes(text) -> str: """ Strips starting and trailing quotes from input string :param text: Text string to strip the quotes from. :return: Text string without quotes. """ if text is None: return "" l = len(text) if l == 0: return text start = 0 if text[0...
def convert_service_banner_json(json): """Convert json file to string if supplied with custom banner json file.""" # open json file with open(json, "r") as j: json_string = j.read() return json_string
def get_site_ends_distance(s1, e1, s2, e2): """ Get nearest distance between two site ends / starts. >>> get_site_ends_distance(100, 120, 130, 150) 10 >>> get_site_ends_distance(130, 150, 100, 120) 10 >>> get_site_ends_distance(100, 120, 120, 140) 0 >>> get_site_ends_distance(120, 1...
def compose_dict_obj(raw_data, keys, search_words): """ Return a dictionary of selected keys from raw_data """ d = {} for key in keys: if key == "keyword": d[key] = search_words else: d[key] = raw_data.get(key) return d
def node_available(node): """ Return true if the node can append a child """ if node is None: return False return node.status == 'OK' and (not node.left or not node.right)
def fnSeconds_To_Hours(time_period): """ Convert from seconds to hours, minutes and seconds. Date: 16 October 2016 originally in AstroFunctions.py """ num_hrs = int(time_period/(60.*60.)); time_period =time_period - num_hrs*60.*60.; num_mins = int(time_period/60.); n...
def strip_num(word : str): """Returns the word, without numerical chars at the beginning""" i =0 while i<len(word) and word[i].isnumeric(): i+=1 return word[i:]
def upper_lower_none(arg): """Validate arg value as "upper", "lower", or None.""" if not arg: return arg arg = arg.strip().lower() if arg in ["upper", "lower"]: return arg raise ValueError('argument must be "upper", "lower" or None')
def importString(import_name): """Imports an object based on a string. The string can be either a module name and an object name, separated by a colon, or a (potentially dotted) module name. """ if ':' in import_name: modname, obj = import_name.split(':', 1) elif '.' in import_name: ...
def replace_variable_in_value(value, variable, replacement): """ Replace variable in value string with replacement string """ return value.replace(variable, replacement)
def check5(n, p): """ Return a bool. Check if a set of measurements can apply normal approximation. """ return n * p > 5 and n * (1 - p) > 5
def find_metadata_item(metadata_items, key_name): """ Finds a metadata entry by the key name. """ for item in metadata_items: if item['key'] == key_name: return item return None
def dict_as_tuples(dct): """Transforms a dict to a choices list of tuples.""" lst = [] for key in dct.keys(): lst.append((key, dct[key])) return lst
def add_fracs_for(n): """ Returns the sum of the fractions 1/1 + 1/2 + ... + 1/n Parameter n: The number of fractions to add Precondition: n is an int > 0 """ # Accumulator v = 0 # call this 1/0 for today for i in range(1,n+1): v = v + 1.0 / i return ...
def solve_substring_with_precedence(text): """ Same as 'solve_substring' but read the addition first :param str text: A flat equation to solve :return: The result of the given equation :rtype: int """ text = text.replace("(", "") text = text.replace(")", "") inputs = text.split(" ") ...
def tcl_delta_filename(curef, fvver, tvver, filename, original=True): """ Generate compatible filenames for deltas, if needed. :param curef: PRD of the phone variant to check. :type curef: str :param fvver: Initial software version. :type fvver: str :param tvver: Target software version. ...
def parse_soil_code(s): """ Function to parse the soil code. :param s: (str) String with the soil code. :return: Soil code. """ return s.replace("'", "")
def ordered_sample(population, sample_size): """ Samples the population, taking the first `n` items (a.k.a `sample_size') encountered. If more samples are requested than are available then only yield the first `sample_size` items :param population: An iterator of items to sample :param sample_size: ...
def find_check_run_by_name(check_runs, name): """ Search through a list of check runs to see if it contains a specific check run based on the name. If the check run is not found this returns 'None'. Parameters ---------- check_runs : list of dict An array of check runs. This can be an ...
def yesno(value, icaps=True): """ Return 'yes' or 'no' according to the (assumed-bool) value. """ if (value): str = 'Yes' if icaps else 'yes' else: str = 'No' if icaps else 'no' return str
def get_stats(data): """ Returns some statistics about the given data, i.e. the number of unique entities, relations and their sum. Args: data (list): List of relation triples as tuples. Returns: tuple: #entities, #relations, #entities + #relations. """ entities = set() relations = set() for triple in d...
def parse_arxiv_url(url): """ examples is http://arxiv.org/abs/1512.08756v2 we want to extract the raw id (1512.08756) and the version (2) """ ix = url.rfind('/') assert ix >= 0, 'bad url: ' + url idv = url[ix+1:] # extract just the id (and the version) parts = idv.split('v') assert ...
def _difftrap1(function, interval): """ Perform part of the trapezoidal rule to integrate a function. Assume that we had called difftrap with all lower powers-of-2 starting with 1. Calling difftrap only returns the summation of the new ordinates. It does _not_ multiply by the width of the trap...
def try_call(func, *args, **kwargs): """ Attempts to invoke a function with arguments. If `func` is not callable, then returns `func` The second return value of this function indicates whether the argument was a callable. """ if callable(func): ret = func(*args, **kwargs) return ret,...
def _cons6_77(m6, L66, L67, d_byp, k, Cp, h_byp, dw1, kw1, dw2, kw2, adiabatic_duct=False, conv_approx=False): """dz constrant for edge bypass sc touching 2 corner bypass sc""" term1_out = 0.0 if not adiabatic_duct: if conv_approx: R2 = 1 / h_byp + dw2 / 2 / kw2 ...
def split_list(func, *args): """ Split args into one list containing all args where func returned True, and rest in the second one. """ one, two = [], [] for arg in args: if func(arg): one.append(arg) else: two.append(arg) return one, two
def default(x, y, f=None): """If y is not None, returns y if f is None, otherwise returns f(y). If y is None, returns x. >>> default(1, None, None) 1 >>> default(1, 5, None) 5 >>> default(1, 5, lambda x: x + 1) 6 """ if y: if f: return f(y) else: ...
def class_name_to_dir_name(class_name): """ Replace all spaces with underscores. :param class_name: Class name string. :return: Modified class name. """ return class_name.replace(" ", "_")
def url_part_unescape(urlpart): """ reverse url_part_escape """ return ''.join( bytes.fromhex(s).decode('utf-8') if i % 2 else s for i, s in enumerate(urlpart.split('_')) )
def Int2AP(num): """Convert integer to A-P string representation.""" val = b''; AP = b'ABCDEFGHIJKLMNOP' num = int(abs(num)) while num: num, mod = divmod(num, 16) val = AP[mod:mod+1] + val return val
def decode_number(num): """ Decodes numbers found in app.xml. They are of the formats "U:" (undefined), "V:" (void/none?), or "I:<integer>". Returns None if the number is undefined ("U:") or an empty string. Raises an exception if the format is otherwise invalid. """ if num == "" or num...
def _merge_tokens(token_1: str, token_2: str) -> str: """Fast, whitespace safe merging of tokens.""" if len(token_2) == 0: text = token_1 elif len(token_1) == 0: text = token_2 else: text = token_1 + " " + token_2 return text
def convert_to_milli(val): """ Converts a string to milli value in int. Useful to convert milli values from k8s. Examples: convert_to_milli('10m') -> 10 convert_to_milli('10000m') -> 10000 convert_to_milli('1') -> 1000 convert_to_milli('100') -> 100000 """ if val[...
def _pprint(params): """Pretty print the dictionary 'params'.""" params_list = list() for i, (k, v) in enumerate(params): if type(v) is float: this_repr = '{}={:.4f}'.format(k, v) else: this_repr = '{}={}'.format(k, v) params_list.append(this_repr) ...
def flatten(items, seq_types=(list, tuple)): """convert nested list to flat list""" for c, item in enumerate(items): while c < len(items) and isinstance(items[c], seq_types): items[c : c + 1] = items[c] return items
def apply_typedef(item, typedef): """ This applies isinstance() to item based on typedef. """ if isinstance(typedef, (tuple, list)): typedef_strlist = list(typedef) elif isinstance(typedef, str): typedef_strlist = [typedef] else: return False typedef_ok = [] ...
def escape_lemma(lemma): """Format the lemma so it is valid XML id""" def elc(c): if (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z'): return c elif c == ' ': return '_' elif c == '(': return '-lb-' elif c == ')': return '-rb-' ...
def format_parameter_list(parameters): """Given an item list or dictionary of matching parameters, return a formatted string. Typically used to format matching parameters or bestrefs dicts for debug. """ items = sorted(dict(parameters).items()) return " ".join(["=".join([key, repr(str(value))]) for...
def remove_suffix(string, suffix): """ This function removes the given suffix from a string, if the string does indeed end with the suffix; otherwise, it returns the original string. """ # Special case: if suffix is empty, string[:0] returns ''. So, test for a non-empty suffix. if suffix and str...
def makeFlags(*args): """Resolve tuple-like arguments to a list of string. Parameters ---------- args List of tuples of the form: [(True, "foo"), (False, "bar")] Returns ------- dirname : str The generated directory name Examples -------- >>> makeFlags((True, "...
def unlist(nestedList): """Take a nested-list as input and return a 1d list of all elements in it""" import numpy as np outList = [] for i in nestedList: if type(i) in (list, np.ndarray): outList.extend(unlist(i)) else: outList.append(i) return outList
def neighbors (row, col, nrows, ncols): """Returns a list of `(r, c)` 4-neighbors (up, down, left, right) for `(row, col)`. Invalid neighbor coordinates outside the range row and column range `[0, nrows]` or `[0, ncols]`, respectively, will not be returned. """ deltas = (-1, 0), (0, -1), (1, 0)...
def varintdecode(data): """ Varint decoding """ shift = 0 result = 0 for c in data: b = ord(c) result |= ((b & 0x7f) << shift) if not (b & 0x80): break shift += 7 return result
def int_func(A): """ Defines the interaction term of the target and dark matter particle Parameters ---------- A : Float Atomic mass of the detector element. Returns ------- Interaction factor. """ return(A**2)
def separate_type(type_dict): """return the type for word and class separately""" wt_dict = dict() ct_dict = dict() for key, v in type_dict.items(): contain_word = key.find('w') != -1 contain_class = key.find('c') != -1 if contain_word and not contain_class: w...
def is_palindromic_phrase(s): """ (str) -> bool Return True iff s is a palindrome, ignoring case and non-alphabetic characters. >>> is_palindromic_phrase('Appl05-#$elppa') True >>> is_palindromic_phrase('Mada123r') False """ result = '' for i in range...
def set_show_fps_counter(show: bool) -> dict: """Requests that backend shows the FPS counter Parameters ---------- show: bool True for showing the FPS counter """ return {"method": "Overlay.setShowFPSCounter", "params": {"show": show}}
def make_contact_name(contact: dict, include_title: bool = True) -> str: """ Create a contact_name string from parts. Args: contact (dict): Document from contacts collection. include_title (bool): Whether to include the title field as a prefix. Returns: (str): Contact name strin...
def modular_pow(base, exponent, modulus): """Computes (base**exponent) % modulus by using the right-to-left binary method.""" if modulus == -1: return 0 result = 1 base %= modulus while exponent > 0: if exponent % 2: result = (result * base) % modulus exponent >...
def my_hourly_schedule(_context): """ A schedule definition. This example schedule runs a pipeline every hour. For more hints on scheduling pipeline runs in Dagster, see our documentation overview on Schedules: https://docs.dagster.io/overview/schedules-sensors/schedules """ run_config = {}...
def asInt(val): """Converts floats, integers and string representations of integers (in any base) to integers. Truncates floats. Raises ValueError or TypeError for all other values """ if hasattr(val, "lower"): # string-like object; force base to 0 return int(val, 0) else: ...
def CreateModelInfo(model_info_d): """ model_info_d: (dict) model_in_use: (str) """ mm = model_info_d['model_in_use'] HTML_l = ["<h2> Information on Model: </h2>"] HTML_l += ["<h3> Using the following given Model:</h3>"] HTML_l += ["<h4>" + mm.split('/')[-1] + "</h4>"] HTML_l +=...
def extract_filter_list(filter_list): """Helper for isolated script test wrappers. Parses the --isolated-script-test-filter command line argument. Currently, double-colon ('::') is used as the separator between test names, because a single colon may be used in the names of perf benchmarks, which contain URLs. ...
def visit(h): """Converts our bespoke linked list to a python list.""" o = h l = [] while o is not None: l.append(o.value) o = o.next return l
def convert_vface_to_efaces(vfaces): """Convert faces given by vertices to faces given by strings (edge faces). It works for up to 26 edges.""" #list of edges eds = [] nA = ord("A") na = ord("a") faces = [] for ff in vfaces: #print("ff",ff) f = ff+[ff[0]] n = len(f) e = ...
def timeout_command(command, timeout): """call shell-command and either return its output or kill it if it doesn't normally exit within timeout seconds and return None""" import subprocess, datetime, os, time, signal start = datetime.datetime.now() process = subprocess.Popen(command, stdout=subproce...
def _fix_host(host: str) -> str: """ Remove any leading "https://" from a host :param host: the host string :return: possibly modified result """ if host.startswith("https://"): host = host[len("https://") :] return host.replace("/", "")
def nested_get(futures, ndim, getter): """Recusively get results from nested futures. """ return (tuple(getter(fut) for fut in futures) if ndim == 1 else tuple(nested_get(fut, ndim - 1, getter) for fut in futures))
def rgb_2_plt_tuple(r, g, b): """converts a standard rgb set from a 0-255 range to 0-1""" plt_tuple = tuple([x/255 for x in (r, g, b)]) return plt_tuple
def kochanekBartelsInterpolator(v0, v1, v2, v3, alpha, tension, continuity, bias): """ Kochanek-Bartels interpolator. Allows even better control of the bends in the spline by providing three parameters to adjust them: * tension: 1 for high tension, 0 for normal tension and -1 for low tension. ...
def iops_to_kiops(number: float) -> float: """ Convert iops to k-iops. Parameters ---------- number : float A ``float`` in iops. Returns ------- float Returns a ``float`` of the number in k-iops. """ return round(number * 1e-3, 3)
def _strToBoundNumeral(v, interval, conversion): """Test (and convert) a generic numerical type, with a check against a lower and upper limit. @param v: the literal string to be converted @param interval: lower and upper bounds (non inclusive). If the value is None, no comparison should be done @param c...