content
stringlengths
42
6.51k
def prefixes(word): """A list of the initial sequences of a word, not including the complete word.""" return [word[:i] for i in range(len(word))]
def _SplitByLength(seq, length): """A helper function for spliting a string or blob into sized chunks.""" return [seq[i:i+length] for i in range(0, len(seq), length)]
def set_flags(backend, flags): """Set proba on backend""" resets = list() if 'layer' in backend.__class__.__name__.lower(): updates = [backend] + backend.learners elif 'group' in backend.__class__.__name__.lower(): updates = backend.learners elif not isinstance(backend, list): ...
def enc(val): """Returns the passed value utf-8 encoded if it is a string, or unchanged if it is already bytes. """ try: return val.encode("utf-8") except AttributeError: # Not a string return val
def gene(result): """ Convert the gene name into a standarized format. """ if result["database"] == "ENSEMBL": return result["optional_id"] if result["rna_type"] == "piRNA" and result["database"] == "ENA": return result["product"] name = result["gene"] or "" name = name.re...
def zipf(dict_ranks, item): """Return the Zipf Law value of an item. Zipf's law states that given some corpus of natural language utterances, the frequency of any word is inversely proportional to its rank in the frequency table. Thus the most frequent word will occur approximately twice as often a...
def collection_core_fields(item): """Extract only fields that are used to identify a record""" record = {} # Define umm umm = item.get('umm', {}) record['ShortName'] = umm.get('ShortName') record['Version'] = umm.get('Version') record['EntryTitle'] = umm.get('EntryTitle') # Define meta ...
def precursor_permutation_given_index(precursor_list, permutation_index): """ Return permutation of list given index. Inspired by https://stackoverflow.com/questions/5602488/random-picks-from-permutation-generator. :param precursor_list: List of molecules :param permutation_index: Permutation index ...
def central_slice(k): """Return central slice objects (last 2 dimensions).""" if k < 1: return ..., slice(None), slice(None) return ..., slice(k, -k), slice(k, -k)
def clean_cuisine_names(cuisine_names): """ String manipulation of cuisine names. Parameter: --------- cuisine_names : list List containg the cuisine names. Returns: ------- clean_names : list List with the with the new names. """ clean_names = [] for i, na...
def sum_squared(variable_list): """Takes in an array and returns the sum of an array with each element squared""" return sum([el * el for el in variable_list])
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 = list...
def snake_to_camel(value: str, *, uppercase_first: bool = False) -> str: """ Convert a string from snake_case to camelCase """ result = "".join(x.capitalize() or "_" for x in value.split("_")) if uppercase_first: return result return result[0].lower() + result[1:]
def create_cloud_build_spec(buildable_images, docker_registry): """Returns Cloud Build specificatiion.""" cloud_build_spec = {} cloud_build_spec['steps'] = [] cloud_build_spec['images'] = [] for name, image in buildable_images.items(): step = {} step['id'] = name step['name...
def u(s): """ bytes/str/int/float -> str(utf8) """ if isinstance(s, (str,int,float)): return str(s) elif isinstance(s, bytes): return s.decode("utf-8") else: raise TypeError(s)
def _get_plot_name(name): """Looks in the parameter and returns a plot name. Expects the plot name to be identified by having "By Plot" embedded in the name. The plot name is then surrounded by " - " characters. That value is then returned. Args: name(iterable or string): An array/list o...
def concat(str1, str2): """Concatenate two strings""" return "%s%s" % (str1, str2)
def calc_rsr(txt): """Calculates the ratio of characters in the right-side of the QWERTY keyboard, also known as RSR (Right-Side Ratio), given a lower-case text object. """ lside = ['q','w','e','r','t', 'a','s','d','f','g', 'z','x','c','v','b'] rside = ['y','u','i...
def hide_string(s, char_replace='*'): """Returns a string of same length but with '*'""" return char_replace * len(s)
def get_constructed_history_and_golden_response(usr_utterances, sys_utterances): """ This function construct the reversed order concat of dialogue history from dialogues from users and system. as well as the last response(gold response) from user. @param usr_utterances: @param sys_utterances: @r...
def is_config_field(attr: str): """Every string which doesn't start and end with '--' is considered to be a valid configuration field.""" return not (attr.startswith('__') and attr.endswith('__'))
def get_size(size_in_bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if size_in_bytes < factor: return f"{size_in_bytes:.2f}{unit}{suffix}" ...
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 """ "*** YOUR CODE HERE ***" if k == 0: return 1 else: return n * fa...
def get_data_pm_1sigma(x, e=()): """ Compute the 68.27% confidence interval given the 1-sigma measurement uncertainties `e` are given, else return a 2-tuple with data duplicated. Parameters ---------- x: array-like e: optional, array-like or 2-tuple of array-like If array like, assu...
def parse_device_disk(token): """Parse a single disk from the header line. Each disks has at least a device name and a unique number in its array, after that could follow a list of special flags: (W) write-mostly (S) spare disk (F) faulty disk (R) replacement disk So...
def round(key): """ Split the classes and allow a +-20% error on the sizes """ DELTA = 0.2 DELTA_HIGH = 0.25 key = int(key) SIZE = 100 if key in range(int(SIZE*(1 - DELTA)), int(SIZE*(1 + DELTA))+1): return str(SIZE) SIZE = 500 if key in range(int(SIZE*(1 - DELTA)), int...
def is_dict(value, by_instance=False): """ Check whether the value is dict object :param value: :param by_instance: :return: """ if by_instance is True: return isinstance(value, dict) return type(value) == dict
def is_point_inside_rect(point: tuple, rect:tuple): """Returns whether a point is inside a rectangular region Args: point (tuple): The point to be tested rect (tuple): A rectangular region coordinates (up_left_x,upleft_y,bottom_right_x,bottom_right_y) Returns: boolean: If true then ...
def _str_to_bool(string): """ Converts command line boolean string to python boolean :param string: The command line string :return: The boolean interpretation of the string """ return string.lower() in ("yes", "true", "t", "1")
def mapping_google_id_info_to_sso_user_info(cognito_id, cognito_email, google_id_info): """ Map the Google ID token info to the user info. """ sso_user_info = dict() sso_user_info["cognito_id"] = cognito_id sso_user_info["cognito_email"] = cognito_email sso_user_info["federated_id"] = "googl...
def is_number(s): """Is string a number.""" try: float(s) return True except ValueError: return False
def spatial_subentry_id(search_result): """Get the id of a returned SpatialEntry.""" if 'stac_version' in search_result: return search_result['id'] return search_result['spatial_id']
def findMinMaxPoint(data): """ data: [[[x0,x1,x2,...],[y0,y1,y2,...]] * storke_number] """ minX = min(list(map(lambda x:min(x[0]), data))) maxX = max(list(map(lambda x:max(x[0]), data))) minY = min(list(map(lambda x:min(x[1]), data))) maxY = max(list(map(lambda x:max(x[1]), data))) retur...
def deprecated_extension(version_number: int) -> str: """ Return the extension that encodes the deprecated `version_number` of the password of some account. This extension is usually preceded by the account and succeeded by `.gpg`. :param version_number: version number of the deprecated password :r...
def fib(n): """Calculates the n'th fibonacci number (memo-ized version). Args: n: Which Fibonacci number to return Returns: the n'th Fibonacci number. """ if n >= 2: return fib(n-2) + fib(n-1) else: return 1
def sorted_items(params): #93 (line num in coconut source) """Return an iterator of the dict's items sorted by its keys.""" #94 (line num in coconut source) return sorted(params.items())
def cutter(value,arg): """ This is a customer filter to cut all values of "arg" from the string! """ return value.replace(arg,'')
def commonName(names): """return common name from list of names""" name = names[0] for n in names[1:]: while not name in n: name = name[:-1] # strip common endings for s in [' ','(','.','/','\\','_']: name = name.strip(s) return name
def path(symbol): """ replaces '.' with '/' """ return str(symbol).replace('.', '/')
def hmsm_to_days(hour=0,min=0,sec=0,micro=0): """ Convert hours, minutes, seconds, and microseconds to fractional days. Parameters ---------- hour : int, optional Hour number. Defaults to 0. min : int, optional Minute number. Defaults to 0. sec : int, optional ...
def format_path_data(path_data): """ Args: path_data (list or str): Either a list of paths, or just one path. Returns: list: A list of paths """ assert isinstance(path_data, str) or isinstance(path_data, list) if isinstance(path_data, str): path_data = [path_data] re...
def is_precipitating(weather: dict, conditions: tuple = ( 200, 201, 202, 210, 211, 212, 221, 230, 231, 232, 300, 301, 302, 310, 311, 312, 313, 314, 321, 500, 501, 502, 503, 504, 511, 520, 521, 522, 531, 600, 601,...
def dict_combine(*dict_list) -> dict: """Return the union of several dictionaries. Uses the values from later dictionaries in the argument list when duplicate keys are encountered. In Python 3 this can simply be {**d1, **d2, ...} but Python 2 does not support this dict unpacking syntax. Returns...
def calunc(wvl, data, unc): """ recalculate uncertainties for pixels in the box --- INPUT --- wvl wavelength data box unc uncertainty box (3D) --- OUTPUT --- unc_wvl 1D unc """ unc_wvl = unc return unc_wvl
def radio_params(param_name): """ Returns text values for some radio buttons instead of numeric. Parameters: param_name: mane for radio buttons setting Returns: dict with text values if the selected setting has a specific radio\ button name. Returns None if setting not in rad...
def get_best_n_decoys_per_sequence(tag_to_score, tag_to_sequence, n): """ aaa """ combined = {} combined2 = {} for tag in tag_to_sequence.keys(): seq = tag_to_sequence[tag] if seq == '': continue if not tag in tag_to_score: continue score = tag_to_score[tag] ...
def to_camel_case(text): """Convert to camel case. :param str text: :rtype: str :return: """ split = text.split('_') return split[0] + "".join(x.title() for x in split[1:])
def filter_none(data): """Helper function which drop dict items with a None value.""" assert isinstance(data, dict), "Dict only" out = {key: value for key, value in data.items() if value is not None} return out
def cs_rad(altitude, et_rad): """ Estimate clear sky radiation from altitude and extraterrestrial radiation. Based on equation 37 in Allen et al (1998) which is recommended when calibrated Angstrom values are not available. :param altitude: Elevation above sea level [m] :param et_rad: Extraterre...
def _eval_at(poly, x, prime): """evaluates polynomial (coefficient tuple) at x, used to generate a shamir pool in _make_shares below. """ accum = 0 for coeff in reversed(poly): accum *= x accum += coeff accum %= prime return accum
def MostGraded(adjList): """Search for the most graded node of a graph""" grade = 0 node = 0 for current in range(len(adjList)): toCompare = len(adjList[current]) if toCompare > grade: node = current grade = toCompare return grade, node
def sum_of_digits(n: int) -> int: """ Find the sum of digits of a number. >>> sum_of_digits(12345) 15 >>> sum_of_digits(123) 6 """ res = 0 while n > 0: res += n % 10 n = n // 10 return res
def lagrangef(mu, r2, tau): """Compute 1st order approximation to Lagrange's f function. Args: mu (float): gravitational parameter attracting body r2 (float): radial distance tau (float): time interval Returns: float: Lagrange's f function value """ ...
def _convert_to_path(resource_id: str) -> str: """Convert something like dpressel__ag-news into dpressel/ag-news :param resource_id: :return: """ return resource_id.replace('__', '/')
def line2strlist(l,separators): """ This routine breaks a line stored in l up and produces a list of strings. """ #separators = ["=","(",")","{","}","[","]",",","*","%",":",";"] a = l.split() if len(a) == 0: # # We have found a blank line. Introduce a special token to cope wit...
def trange(*args, **kwargs): """ >>> trange(3) (0, 1, 2) >>> trange(1, 3) (1, 2) >>> trange(0, 3, 2) (0, 2) """ return tuple(range(*args, **kwargs))
def dbfarg(n): """ """ res="arg"+str(n) return res
def process_line(cur_str): """Get value from each line of TextGridline, as {xmax = 0.29} will get {0.29}, {text = "kk"} will get {kk} """ tmp_array = cur_str.strip().split('=') tmp_array = [item for item in filter(lambda x: x != '', tmp_array)] return tmp_array[-1].strip()
def __get_EW__(num): """Get east or west for longitudes num: Numeric value of longitude""" if((num > 0) & (num < 180)): return "E" elif((num < 0) & (num > -180)): return "W" else: return ""
def get_unique_ops_names(all_ops): """ Find unique op names. Params: all_ops: list, of dictionary of all operations. Return: list of unique op names. """ return set(op['name'] for op in all_ops)
def _filter_symbol(c): """Makes control characters more human readable. """ if c in {'\n', '\r', '\t'}: return ''.join(['\\', c]) elif not c.isprintable(): return '.' else: return c
def is_same_version(version1, version2): """Check whether two versions are equal. This is the case if minor and major version are the same (e.g. 2.4.1 and 2.4.3). """ split_v1 = version1.split('.') split_v2 = version2.split('.') if len(split_v1) < 2 or len(split_v2) < 2: # unexpected f...
def flat_test_name(_id): """Return short form test name from TestCase ID.""" return '-'.join(_id.split('.')[1:])
def approx_fhess_p(x0,p,fprime,epsilon,*args): """ Approximate the Hessian when the Jacobian is available. Parameters ---------- x0 : array-like Point at which to evaluate the Hessian p : array-like Point fprime : func The Jacobian function epsilon : float "...
def vehicle(x, u, T): """Discrete-time 1D kinematic vehicle model.""" x_new = x + T * u return x_new
def _overlapping_membership_to_list_of_communities(membership_vector, size): """Convert membership vector to list of lists of vertices/labels in each community Parameters ---------- membership_vector : list of lists of int community membership i.e. vertex/label `i` is in communities fro...
def remove_grid_cells( config_list, skip_cells ): """ Remove the given list of cells from a configuration list :Parameters: config_list: list of (index, xcen, ycen, orient, column, row) List of configuration parameters describing the IDs, locations and orientations of the ...
def lookup_with_backup(mapping: dict, key: object, backup_key: object) -> object: """Return the corresponding value of key in mapping. If key is not in mapping, then return the corresponding value of of backup_key in mapping instead. This assumes that at least one of key and backup_key are a key in ma...
def maybe(typ, val): """Call typ on value if val is defined.""" return typ(val) if val is not None else val
def excelcol(num): """ This function converts an index number to excel styled column letter""" ecol = "" while num > 0: rem = (num - 1) % 26 num = (num - 1) // 26 ecol = ecol + chr(65 + rem) return ecol
def parameters(config): """ Extract Parameters from parameters.yml stored in the configuration """ return config.get('parameters.yml')
def add_columns_with_default(event, field_and_default_dict): """ Adds a column with the default value to every event where it's not already present :param event: A dictionary :param field_and_default_dict: A dictionary with keys and default values {field_1: default_for_field_1, field_2: default_for_field_2...
def mean(values): """ Compute the mean of a sequence of numbers. """ return sum(values)/len(values)
def update_c_delete_meta_lines(main, file): """ This update script deletes several meta lines :param file: Conan file path """ updated_global = False # noinspection SpellCheckingInspection line_deleting = [ "#!/usr/bin/env python", "#!/usr/local/bin/python", "# -*- cod...
def edgesFromNode(n): """ Return the two edges coorsponding to node n""" if n == 0: return 0, 2 if n == 1: return 0, 3 if n == 2: return 1, 2 if n == 3: return 1, 3
def iter_points(x): """Iterates over a list representing a feature, and returns a list of points, whatever the shape of the array (Point, MultiPolyline, etc). """ if not isinstance(x, (list, tuple)): raise ValueError('List/tuple type expected. Got {!r}.'.format(x)) if len(x): ...
def get_azfs_url(storage_account, container, blob=''): """Returns the url in the form of https://account.blob.core.windows.net/container/blob-name""" return 'https://' + storage_account + '.blob.core.windows.net/' + container + '/' + blob
def _tobin(x): """ Serialize strings to UTF8 Parameters ---------- x : str or bytes value to convert to a UTF8 binary string. Returns ------- bytes """ if isinstance(x, str): return bytes(x, 'utf-8') else: return x
def matrix_inverse(matrix): """Invert a 6-item homogenous transform matrix. A transform matrix [a, b, c, d, e, f] is part of a 3x3 matrix: a b 0 c d 0 e f 1 Invert it using the formula for the inverse of a 3x3 matrix from http://mathworld.wolfram.com/MatrixInverse.html """...
def get_typestrings(struct): """ Return the valid schema types as a set. """ type_strings = struct.get('type', []) if isinstance(type_strings, str): type_strings = {type_strings} else: type_strings = set(type_strings) if not type_strings: type_strings = { ...
def fact(n): """ Factorial. fact(5) = 5! = 5 * 4! = 5 * 4 * 3 * 2 * 1 = 120 :param int n: Target number :returns: n! :rtype: int """ if n == 1: return 1 return n * fact(n - 1)
def default_summary_filter(name: str) -> bool: """Default summary filter: omits any names that start with _.""" return not (name.startswith("_") or "/_" in name)
def text_to_labels(text, alphabet): """ Translation of characters to unique integer values """ ret = [] for char in text: ret.append(alphabet.find(char)) return ret
def transposeAndMap(listoflists, fn=lambda x: x,nothing=""): """ takes a list of lists and returns its transpose after doing a point-wise mapping: listoflists = [[1,2],[3,4]] fn = str yields [["1","3"],["2","4"]] """ innerdim = max((map(len,listoflists))) outp...
def _has_case_statement(path): """ Check if the file possibly contains a `case` statement at all. There is a slight chance that the result might be wrong in that the function could return `True` for a file containing the word `case` in a position that looks like a statement, but is not. Our import...
def normalize_teh_marbuta_bw(s): """Normalize all occurences of Teh Marbuta characters to a Heh character in a Buckwalter encoded string. Args: s (:obj:`str`): The string to be normalized. Returns: :obj:`str`: The normalized string. """ return s.replace(u'p', u'h')
def comma_separator(list_: list) -> str: """Separates commas using simple ``.join()`` function and analysis based on length of the list taken as argument. Args: list_: Takes a list of elements as an argument. Returns: str: Comma separated list of elements. """ return ", and...
def descendents(class_: type): """ Return a list of the class hierarchy below (and including) the given class. The list is ordered from least- to most-specific. Can be useful for printing the contents of an entire class hierarchy. """ assert isinstance(class_, type) q = [class_] out = [] while len(q): x = ...
def make_foldername(name): """Returns a valid folder name by replacing problematic characters.""" result = u'' for c in name.strip(): if c.isdigit() or c.isalpha() or c in (',', ' ', '.', '-'): result += c elif c == ':': result += "." else: result ...
def containerize(a, ttyp, ctyp): """ Convert a string version of a list, tuple, or comma-/space-separated string into a Python list of ttyp objects. """ if not isinstance(a, str): return a #strip off the container indicator ('[', ']' for list, '(', ')' for tuple) if '[' in a: ...
def rand_index_pair_counts(a, b, c, d): """ Compute the Rand index from pair counts; helper function. Arguments: a: number of pairs of elements that are clustered in both partitions b: number of pairs of elements that are clustered in first but not second partition c: number of pairs of element...
def cluster_by_diff(data, max_gap): """ a function that clusters numbers based on their differences based off of a stacktrace answer: http://stackoverflow.com/a/14783998 :param data: any list of floats or ints :param max_gap: the largest gap between numbers until starting a new cluster :ret...
def get_mean(data): """ Calculated mean for given list. @param data: list of numbers @return: arithmetic mean """ if not data: raise Exception("Empty data.") sum_x = sum(data) mean = float(sum_x) / len(data) return mean
def _extract_content_type(content_type: str) -> str: """extract content type""" if ';' in content_type: content_type = content_type.split(';')[0] if '/' in content_type: content_type = content_type.split('/')[-1] return content_type
def is_prime(n): """Detect if a number is a prime or not (robust method). :param num: A positive number :type num: int :returns: boolean :rtype: bool """ if n <= 1: return False elif n == 2: return True elif n > 2 and n % 2 == 0: return False else: ...
def is_tuple(obj): """Helper method to see if the object is a Python tuple. >>> is_tuple((1,)) True """ return type(obj) is tuple
def create_stream(data_type, transaction_id): """ Construct a 'createStream' message to issue a new stream on which data can travel through. :param data_type: int the RTMP datatype. :param transaction_id: int the transaction id in which the message will be sent on. """ msg = {'msg': data_type, ...
def shift_chord(chord, shift): """Shift chord""" if chord < 12: new_chord = (chord + shift) % 12 elif chord < 24: new_chord = (chord - 12 + shift) % 12 + 12 else: new_chord = chord return new_chord
def p(x, f=lambda x: x): """Pass None values through, otherwise apply function.""" if x is None: return None return f(x)
def ini_value(key_value): """Strips key= from key=value from ini configuration data""" equals_idx = key_value.index('=') + 1 return key_value[equals_idx:]