content
stringlengths
42
6.51k
def dict_alert_msg(form_is_valid, alert_title, alert_msg, alert_type): """ Function to call internal alert message to the user with the required paramaters: form_is_valid[True/False all small letters for json format], alert_title='string', alert_msg='string', alert_type='success, error, warning...
def make_map(elems): """ Create dictionary of elements for faster searching @param elems: Elements, separated by comma @type elems: str """ obj = {} for elem in elems.split(','): obj[elem] = True return obj
def is_list_of_int(value): """ Check if an object is a list of integers :param value: :return: """ return isinstance(value, list) and all(isinstance(elem, int) for elem in value)
def inverse_mod(k, p): """Returns the inverse of k modulo p. This function returns the only integer x such that (x * k) % p == 1. k must be non-zero and p must be a prime. """ if k == 0: raise ZeroDivisionError('division by zero') if k < 0: # k ** -1 = p - (-k) ** -1 (mod p) ...
def get_ori_letterunit(start, end, seq, gapchar='-'): """try to determine orientation (1 or -1) based on whether start>end, and letterunit (1 or 3) depending on the ratio of end-start difference vs the actual non-gap letter count. Returns tuple (ori,letterunit)""" if end > start: ori = 1 el...
def _get_rank_from_singular_values(sv, t): """ Gets rank from singular values with cut-off at a given tolerance """ rank = 0 for k in range(len(sv)): if sv[k] > t: rank = rank + 1 else: # sv is ordered big->small so break on condition not met break return...
def insert_shift_array(input_array, input_item): """inserts given item at the middle of an even-length array, or to the right of the middle element in an odd-length array """ # creates space in the array for shifting input_array += [0] # creates a stopping point for the while loop mid = len(inp...
def _preprocess_transcript(phrase, use_phonemes, word_phoneme_dict): """ transform the input phrase. if use_phonemes is true, the words in phrase are transformed into phoneme labels specified in word_phoneme_dict Arguments: phrase (list): list of words use_phonemes (b...
def string_strip(value): """ strips string value from any whitespaces, makes sure it stays in byte format """ if not ('bytes' in str(type(value)) or 'str' in str(type(value))): value = str(value).strip().encode("utf-8") else: value = value.strip() return value
def FilterDuplicatesAndReverse(cr_releases): """Returns the chromium releases in reverse order filtered by v8 revision duplicates. cr_releases is a list of [cr_rev, v8_rev] reverse-sorted by cr_rev. """ last = "" result = [] for release in reversed(cr_releases): if last == release[1]: continue ...
def _sized_byte_like(value, size): """Make the value byte like and the correct size. If the value is not the correct size it will be either padded with spaces or trancated Args: value(str, bytes, bytearray): The value to make byte-like and correctly sized size(int): The correct size of th...
def state_to_id(state): """Convert a state to its ID as used by the IBGE databases. Raises KeyError if the state is invalid. """ state = state.upper() states = {'AC': 12, 'AL': 27, 'AP': 16, 'AM': 13, 'BA': 29, 'CE': 23, 'DF': 53, 'ES': 32, ...
def tempInRange( temp, threshold, percent ): """ Check if temperature is within threshold; check for above/below threshod depending on percent :param temp: float/decimal :param threshold: float/decimal :param percent: float/decimal :return: boolean """ if percent < .50: ...
def find_proton_info (res_type,atom,protonsInfo): """ Find the proton information for a given atom and residue """ for protonInfo in protonsInfo: atom_type = atom.atom_type if (protonInfo['atomName'] == atom_type and (res_type == protonInfo['aminoAcidName'] or protonInfo['aminoAcidNa...
def _data_header(cols, parent_dict): """Constructs a header row for the worksheet based on the columns in the table and contents of the parent row""" out = [] for col in cols: if col == 'gau_id': out.append(parent_dict['geography_id']) elif col == 'oth_1_id': out.appe...
def float_or_none(val): """ Arguments: - `x`: """ if val is None: return None elif val == "": return None else: return float(val)
def generic_filter(s, function): """ :doc: text_utility Transforms `s`, while leaving text tags and interpolation the same. `function` A function that is called with strings corresponding to runs of text, and should return a second string that replaces that run of text. ::...
def filter_altitude(altitude): """Returns the altitude given in parameter, rounded one decimal place""" if altitude is not None and altitude > 0.0: # 10cm accuracy is enough for altitudes return round(float(altitude), 1) return None
def get_longest_length(text, newline): """Return length of longest line.""" return max([len(line) for line in text.split(newline)])
def getext(fname): """\ Get the file extension. >>> getext('file.xyz') 'xyz' >>> getext('file') '' >>> getext('file.') '' """ wds = fname.split('.') if len(wds) > 1: return wds[-1] return ''
def longestPalindrome(text): """ Finds the longest instance of a palindrome in a string """ ngrams = {} longest_palin = None for i in list(reversed(range(1,len(text)+1))): ngrams[i] = list() ngram = text while len(ngram) >= i: ngrams[i].append(ngram[0:i]) ...
def _get_headings(obj, delimiter="."): """ Utility function for getting all nested keys of a dictionary whose values are themselves a dict Args: obj (dict): nested dictionary to be searched delimiter (str): string delimiter for nested sub_headings, e. g. top_middle_low f...
def count_ngram(hyps_resp, n): """ Count the number of unique n-grams :param hyps_resp: list, a list of responses :param n: int, n-gram :return: the number of unique n-grams in hyps_resp """ if len(hyps_resp) == 0: print("ERROR, eval_distinct get empty input") return if ...
def angle_difference(a, b): """ Compute angle difference (b-a) in the range of -180 deg to 180 deg. :param a: Angle in degrees. :paramtype: float :param b: Angle in degrees. :paramtype b: float: :returns: (b-a) in range of -180 deg to 180 deg. :rtype: float Usage: .. code-block:...
def true_stress(tech_stress, tech_strain): """ Calculate the true stress data from technical data Parameters ---------- tech_stress : array-like float stress data from tensile experiments tech_strain : list of float strain data from tensile experiments Returns ------- ...
def remove_empty_dict(dict_name): """Remove dict items with no values Args: dict_name (dict): dictionary to remove empty items from Returns: dict : dictionary with empty keys removed """ return_dict = {} for key in dict_name: if dict_name[key]: retu...
def list_insert(collection, position, value): """:yaql:insert Returns collection with inserted value at the given position. :signature: collection.insert(position, value) :receiverArg collection: input collection :argType collection: sequence :arg position: index for insertion. value is insert...
def rppl(tx): """some shortening of the html""" tx=tx.replace("\n"," ") tx=tx.replace("\xad","") return tx
def convert_to_kgm3(rho, units): """Convert the density to Kg/m^3 from specified units""" units = units.lower() if units == "kgm3": pass elif units == "gcc": rho = rho * 1.0E3 else: raise ValueError("Density unit not recognised") return rho
def get_releases(data, **kwargs): """ Gets all releases from pypi meta data. :param data: dict, meta data :return: list, str releases """ if "entries" in data: return [e["version"] for e in data["entries"]] return []
def replace_oov_words_by_unk(tokenized_sentences, vocabulary, unknown_token="<unk>"): """ Replace words not in the given vocabulary with '<unk>' token. Args: tokenized_sentences: List of lists of strings vocabulary: List of strings that we will use unknown_token: A string representi...
def handle_exception(e): """Return JSON instead of HTML for general errors.""" return {'error': {'message': str(e), 'code': 500}}, 500
def base60_to_decimal(xyz,delimiter=None): """Decimal value from numbers in sexagesimal system. The input value can be either a floating point number or a string such as "hh mm ss.ss" or "dd mm ss.ss". Delimiters other than " " can be specified using the keyword ``delimiter``. """ divisors = [1,60.0,3600.0...
def parse_gff_attributes(attributes_string): """ Parse attributes field from GFF files. """ attributes = attributes_string.split(";") return {k: v for k, v in (a.split("=") for a in attributes)}
def LoadSourceCode(sourceFiles): """Return a dictionary with file paths (key) and contents (value).""" assert isinstance(sourceFiles, list) sourceCodes = {} for sourceFilePath in sourceFiles: with open(sourceFilePath) as f: sourceCodes[sourceFilePath] = f.read() return sourceCode...
def cmp(a, b): """Python 3 version of cmp built-in.""" return (a > b) - (a < b)
def calcMetresDistance(lat1, long1, lat2, long2): """Calculate the distance between two sets of coordinates (badly)""" return (abs(lat1 - lat2) + abs(long1 - long2)) * 100 # no, like, really badly
def color_change(elev): """Change Color depending on Mountain Elevation""" if elev < 1000: return 'green' if 1000 <= elev < 3000: return 'orange' return 'red'
def checkIfRomanNumeral(numeral): """Controls that the userinput only contains valid roman numerals""" numeral = numeral.upper() validRomanNumerals = ["M", "D", "C", "L", "X", "V", "I", "(", ")"] for letters in numeral: if letters not in validRomanNumerals: return False return Tr...
def points_2d_sqr_distance(p1, p2): """ Calculate square of distance between two points in two-dimensional space Parameters ---------- p1 : (float, float) First point p2 : (float, float) Second point Returns ------- float Square of distance between two point...
def dot_product(v1, v2): """ Compute the dot product of the vectors v1 and v2. """ return sum([i * j for i, j in zip(v1, v2)])
def update_to_merge_list(to_merge, subexon_1, subexon_2): """ Add subexon_1 and subexon_2 to the to_merge list. >>> update_to_merge_list([], 1, 2) [{1, 2}] >>> update_to_merge_list([{1, 2}], 2, 3) [{1, 2, 3}] >>> update_to_merge_list([{1, 2}], 8, 9) [{1, 2}, {8, 9}] """ group = ...
def sizeof_varlen(value): """Return number of bytes an integer will need when converted to varlength.""" if value <= 127: return 1 elif value <= 16383: return 2 elif value <= 2097151: return 3 else: return 4
def expand_table(table,cat_table,join_key): """ Utility function to add columns to one table based on the shared `join_key` with another table for every row in `table` add all the columns from `cat_table` from the row with matching `join_key` inputs ------ table : a list of dictionaries, ...
def _comparison(a, b) -> int: """Returns an int in [0, 2] representing the comparison result.""" return 0 if a < b else 1 if a == b else 2
def CommentPattern(lang_id=0): """Returns a list of characters used to comment a block of code @param lang_id: used to select a specific subset of comment pattern(s) """ return [u'{', u'}']
def append_key_value(content, key, value): """ Safely append the key/value as a separate line to the content :param content: :param key: :param value: :return: new content """ if key and value: if content: return '%s\n%s: %s' % (content, key, value) return '%s...
def count_components(adj): """Computes the number of components of a graph from its adjacency list.""" vis = [False] * len(adj) stack = [] def fill(start): vis[start] = True stack.append(start) while stack: for neighbor in adj[stack.pop()]: if vis[ne...
def base60_to_decimal(xyz,delimiter=None): """Decimal value from numbers in sexagesimal system. The input value can be either a floating point number or a string such as "hh mm ss.ss" or "dd mm ss.ss". Delimiters other than " " can be specified using the keyword ``delimiter``. """ divisors = [1,60.0,3600.0] ...
def string_to_int(payload): """ Author: Jingyu Usage: return a integer from a string, if the string is not a int, return -1 as error code. """ try: ret = int(payload) except ValueError: ret = -1 return ret
def parse_time(string_value): """ Used to parse time at which match is played. """ hrs, mns = string_value.split(".") return int(hrs), int(mns)
def get_full_exception_name(exception: Exception) -> str: """Get the full exception name i.e. get sqlalchemy.exc.IntegrityError instead of just IntegrityError """ module = exception.__class__.__module__ if module is None or module == str.__class__.__module__: return exception.__class__.__nam...
def round_nearest(num: float, to: float) -> float: """ Credited to Paul H. https://stackoverflow.com/questions/28425705/python-round-a-float-to-nearest-0-05-or-to-multiple-of-another-float :param num: :param to: :return: float """ return round(num / to) * to
def test_line(line): """returns true lines. Not comments or blank line""" if not line.strip(): return False # if the last line is blank if not line.split(): return False # if the last line is blank if line.startswith("#"): return False # comment line return line.rstrip()
def _map_to_numbers(string_list): """ Returns a tuple of mapping from numbers to strings, then from strings to numbers """ return {i: item for i, item in enumerate(string_list)}, {item: i for i, item in enumerate(string_list)}
def encode(seqTokens, tokenToIdx, allowUnk=False): """ Given seqTokens (list of tokens), encode to seqIdx (list of token_ixs) """ seqIdx = [] for token in seqTokens: if token not in tokenToIdx: if allowUnk: token = '<UNK>' else: raise KeyError('Token "%s" not in vocab' % token)...
def partial_hausdorff(s1,s2): """ Hausdorff distance for partial rank lists; as in partial_kendall, could be sped up by more efficient set size calculation. I normalize the distance by dividing by k*(k-1)/2. """ cardD = 0 cardR1 = 0 cardR2 = 0 k = len(s1) for i in range(len(s1))...
def bugname( rowhead ): """make bug names look nicer""" if "s__" in rowhead: return rowhead.split( "." )[1].replace( "s__", "" ).replace( "_", " " ) elif "g__" in rowhead: return rowhead.replace( "g__", "" ).replace( "_", " " ) else: return rowhead
def hex_to_rgb(value): """Return (red, green, blue) for the color given as #rrggbb.""" value =('0x%0*x' % (6,value))[2:] #pad to 6 digits and strip 0x lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def broadening_lorenzian(x, x0, intensity, sigma): """Apply lorenzian broadening""" return intensity * 1.0/(1 + ((x - x0)*2/sigma)**2)
def sharded_filenames(filename_prefix, num_shards): """Sharded filenames given prefix and number of shards.""" shard_suffix = '%05d-of-%05d' return [ '%s-%s' % (filename_prefix, shard_suffix % (i, num_shards)) for i in range(num_shards) ]
def _validate_clue_args(args): """Returns 0 if OK for hint, 1 for nonconforming args, 2 for bad char, 3 for other bad args, 8 for only one arg Deliberately skips length check as that is performed elsewhere""" argslist=args.split() if len(argslist)==1: return 8 ...
def guess_name_from_uri(uri): """ Given a URI like host.tld/bla/fah/jah or host.tld/bla/fah/jah/, returns jah. """ split_uri = uri.split('/') if split_uri[-1]: return split_uri[-1] # no trailing slash else: return split_uri[-2] # has trailing slash
def collapse_lists(list1,list2,compf,pathf): """Function to collapse two lists into a single list based on comparison and path functions. :param list1: First list :param list2: Second list :param compf: Comparator function to compare values returned by path function. ...
def solution(X, Y, D): """ A function that, given three integers X, Y and D, returns the minimal number of jumps of length D from position X to a position equal to or greater than Y. For example, given: X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as...
def find_mixed_types_columns(columns_info: dict): """ Search for columns with several types in them """ columns_with_mixed_types = [] for column_id, information in columns_info.items(): column_types = information['types'] if len(column_types) > 1: columns_with_mixed_types.append(...
def isPandigital10(s): """Check if number is pandigital from 0-9, i.e. that it has all digits from 0 to 9.""" if len(s) != 10: return False for i in range(0, 10): if s.find(str(i)) == -1: return False return True
def update_dictionary(default_dict, overwrite_dict=None, allow_unknown_keys=True): """Adds default key-value pairs to items in ``overwrite_dict``. Merges the items in ``default_dict`` and ``overwrite_dict``, preferring ``overwrite_dict`` if there are conflicts. Parameters ---------- default_di...
def convert_keys_to_string(dictionary): """Recursively converts dictionary keys to strings.""" if not isinstance(dictionary, dict): return dictionary return dict((str(k), convert_keys_to_string(v)) for k, v in dictionary.items())
def gcd_iter(a, b): """ :param a: int :param b: int , at least one of the two integers is not 0 :return: largest positive integer gcd that divides the numbers a and b without remainder """ # handling of negative integers if a < 0 and b < 0: a = abs(a) b = abs(b) e...
def map_device_id(line): """ :param line: adb device line :type line: str :return: """ return line.split()[0]
def lininterpol(first,second,x): """Perform linear interpolation for x between first and second. Parameters: 1. first: [x1, y1], where x1 is the first x value and y1 is its y value 2. second: [x2, y2], where x2 is the second x value and y2 is its y value 3. x: the x value whose y value will be ...
def next_day(fishes): """Meh >>> fishes = read_input('example') >>> fishes = next_day(fishes) >>> fishes [1, 1, 2, 1, 0, 0, 0, 0, 0] >>> fishes = next_day(fishes) >>> fishes [1, 2, 1, 0, 0, 0, 1, 0, 1] >>> fishes = read_input('example') >>> for n in range(18): ... fishes = ...
def iterable(x): """ iterable(x) -> bool Returns whether an instance can be iterated. Strings are excluded. Args: x (any): the input variable. Example:: >>> iterable(x for x in range(4)) True >>> iterable({2, 3}) True >>> iterable("12") Fa...
def string_intersection(s1, s2): """ Create an empty string and check for new occurrence of character common to both string and appending it. Hence computing the new intersection string. :param s1: :param s2: :return: """ result = "" for i in s1: if i in s2 and i not in r...
def check_pos(grid, row, col, val): """ check whether a value can be inserted into given cell """ for i in range(9): if grid[i][col] == val: return False for i in range(9): if grid[row][i] == val: return False start_col = col // 3 start_row = row // 3 f...
def validate(seq, alphabet='dna'): """ Check that a sequence only contains values from DNA alphabet """ import re alphabets = {'dna': re.compile('^[acgtn]*$', re.I), 'protein': re.compile('^[acdefghiklmnpqrstvwy]*$', re.I)} if alphabets[alphabet].search(seq) is not None: ...
def normalize_timestamp(value, ndigits=1): """ Utility function to round timestamps to the given number of digits. This helps to make the test suite less sensitive to timing issues caused by multitasking, processor scheduling, etc. """ return '%.2f' % round(float(value), ndigits=ndigits)
def aggregate_initial_architecture(hparams): """Helper function to aggregate initial architecture into an array hparam.""" output = hparams.copy() initial_architecture_size = len( [hp for hp in hparams.keys() if hp.startswith("initial_architecture_")]) if initial_architecture_size: output["initial_arc...
def superkeyword_presence(document, superkeywords): """Return 1 if document contains any superkeywords, 0 if not.""" for word in superkeywords: if word in document.split(): return True return False
def check_win(board: list, player_marker) -> bool: """Checks win on a given tic-tac-toe board. - `board` must be a 3x3 nested `list` or `tuple`. - `player_marker` must be the marker of the player that has to be checked for the win. - Returns `True` if `player_marker` has got 3 in a row, either veritcall...
def format_surname(s, keep_full = False): """Recieves a string with surname(s) and returns a string with nicely concatenated surnames or initals (with dots). """ # clean spaces s = s.strip() # go home if empty if not len(s): return '' if not keep_full: # only keep initi...
def _luhnify(gen): """calculates luhn sum given a generator of integers in reverse order.""" sum_ = 0 for index, val in enumerate(gen, 1): if index % 2: val *= 2 sum_ += val // 10 + val % 10 else: sum_ += val return (10 - sum_ % 10) % 10
def _FlattenList(l): """Flattens lists of lists into plain lists, recursively. For example, [[4, 5, 6], [7, 8], []] will become [4, 5, 6, 7, 8]. Non-list elements will get wrapped in a list, so 'foo' becomes ['foo']. None becomes []. Args: l: a list, or not. Returns: A flattened list. """ re...
def _activity_pattern_indices(indices, sens_mat): """ helper function that calculates the id of the activity pattern from a concentration vector given by the indices of ligands that are present and the associated interaction matrix """ Nr = len(sens_mat) # calculate the activity pattern id for ...
def get_limit(s_cache): """ Canned response for limits for servers. Returns only the absolute limits """ return {"limits": {"absolute": {"maxServerMeta": 40, "maxPersonality": 5, "totalPrivateNetworksUsed": 0, "max...
def factor_images_averaged(info_dict): """ Computes the factor mutliplying the variance noise in order to obtain an unbiaised variance in the case of estimating the background noise from several images. Parameters ----------- info_dict: dictionary Returns ------- factor_averaged...
def dump_datetime(value): """Deserialize datetime object into string form for JSON processing.""" if value is None: return None return value.strftime("%Y-%m-%d")
def _report_sorter(enum): """ :param tuple(int, str) enum: Tuple from enumerate() :return int: Value to use for sorting messages in this report """ index, message = enum if message[0] == '<': return -enum[0] # '<' makes message sort towards front, but keeping order with o...
def dim_div(dims1, dims2): """Create a new dimensionality tuple for the division of dims1 by dims2. :param dims1: The numerator dimensions. :type dims1: ``tuple`` :param dims2: The divisor dimensions. :type dims2: ``tuple`` :rtype: ``tuple`` """ return ( dims1[0] - dims2[0], ...
def align(adr, width): """round down address to a width bits boundary""" return adr & ~((width >> 3) - 1)
def FilterOutExtraInformation(spec, line_break_nmbr, extra_nmbr, raw_data): #removes everything after the second line break from the .com file. """ spec: <string> can be either 'above' or 'below' line_break_nmbr: <int> will remove everything above or below that number of line breaks, depending of spec e...
def format_number(number): """ Return the number formatted, if the number contain .0 return only the integer part """ if number % 1 == 0: return int(number) else: return number
def is_odd(number: int) -> bool: """ Test if a number is a odd number. :param number: the number to be checked. :return: True if the number is odd, otherwise False. >>> is_odd(-1) True >>> is_odd(-2) False >>> is_odd(0) False >>> is_odd(3) True >>> is_odd(4) Fals...
def get_node_placement(node_id, model_structure): """ get location of node based on node_id """ prev = 0 for n,i in enumerate(model_structure): # if n == 0: shape = i[0][-1] shape = shape+prev if node_id < shape: return (n,abs(prev-(node_id % sh...
def remove_duplicates(pkgs): """create a seperate set with unique package names. input list must be the format of the collection RossumPackage. """ visited = set() set_pkgs = [] for pkg in pkgs: if pkg.manifest.name not in visited: visited.add(pkg.manifest.name) ...
def is_likely_in_str(line, index): """ Return `True` if the `index` is likely to be within a string, according to the handling of strings in typical programming languages. Index `0` is considered to be within a string. """ cur_str_char = None escaped = False def in_str(): ...
def editDistRecursive(x, y): """ this implementation is very slow """ if len(x) == 0: return len(y) elif len(y) == 0: return len(x) else: distHor = editDistRecursive(x[:-1], y) + 1 distVer = editDistRecursive(x, y[:-1]) + 1 if x[-1] == y[-1]: distDiag ...
def f(value): """Format a float value to have 4 digits after the decimal point""" return "{0:.4f}".format(value)
def calculate_P_virial_np(r_ij): """ The virial between two particles. Computes the pairwise Lennard Jones interaction energy based on the separation distance in reduced units. Parameters ---------- r_ij : np.array The distance between the particles in reduced units. Returns ...