content
stringlengths
42
6.51k
def substring_edit_distance(s: str, t: str) -> int: """The minimum number of edits required to make t a substring of s. An edit is the addition, deletion, or replacement of a character. """ if not s: return len(t) if not t: return 0 M = [[0 for _ in range(len(t) + 1)] for _ in range(len(s) + 1)] ...
def strict_map(func, iterable): """ Python 2/3-agnostic strict map. """ return [func(i) for i in iterable]
def print_perf(start, end): """Print diff as ms between start and end times (floats in secs).""" diff = (end - start) * 1000 print('{:.2f} milliseconds elapsed'.format(diff)) return diff
def remove_ribozyme_if_possible(rna_type, _): """ This will remove the ribozyme rna_type from the set of rna_types if there is a more specific ribozyme annotation avaiable. """ ribozymes = set( ["hammerhead", "hammerhead_ribozyme", "autocatalytically_spliced_intron"] ) if "ribozyme"...
def create_exceptions_mapping(*sources): """Create a single mapping of exception names to their classes given any number of dictionaries mapping variable names to variables e.g. `locals()`, `globals()` or a module. Non-exception variables are filtered out. This function can be used to combine several module...
def get_not_gaps(start, end, gaplist): """Get inverse coords of gaps Parameters ---------- start : int end : int Coords for original sequence, 0-based pythonic gaplist : list list of (int, int) tuples specifying gaps. Must not be overlapping otherwise GIGO Returns ...
def toList(given): """ This will take what is given and wrap it in a list if it is not already a list, otherwise it will simply return what it has been given. :return: list() """ if not isinstance(given, (tuple, list)): given = [given] return given
def flatten(l): """ Flattens a nested list into a single list Arguments: l: list to flatten Returns: Flattened list """ out = [] for item in l: if type(item) == list: out = out + flatten(item) else: out.append(item) return out
def mk_const_expr(val): """ returns a constant expression of value VAL VAL should be of type boolean """ return {"type" : "const", "value": val }
def to_pascal_case(snake_case_word): """Convert the given snake case word into a PascalCase one.""" parts = iter(snake_case_word.split("_")) return "".join(word.title() for word in parts)
def Frr_unit_sphere(r): """Antiderivative of RR_sphere. The RR from r1 to r2 for a unit spherical area is rr_unit_sphere(r2) - rr_unit_sphere(r1) """ return 3 * r**3/3 - 9 / 4 * r**4/4 + 3 / 16 * r**6/6
def hex2rgb(hexcolor): """Convert a hex color to a (r, g, b) tuple equivilent.""" hexcolor = hexcolor.strip('\n\r #') if len(hexcolor) != 6: raise ValueError('Input #%s not in #rrggbb format' % hexcolor) r, g, b = hexcolor[:2], hexcolor[2:4], hexcolor[4:] return [int(n, 16) for n in (r, g, b)]
def is_prime(n): """Return True if n is prime. Copied from https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking- if-a-number-is-prime """ if n == 1: return False if n == 2: return True if n == 3: return True if n % 2 == 0: r...
def wordpiece(token, vocab, unk_token, sentencepiece_style_vocab=False, max_input_chars_per_word=100): """call with single word""" chars = list(token) if len(chars) > max_input_chars_per_word: return [unk_token], [(0, len(chars))] is_bad = False start = 0 sub_tokens = [] sub_pos = [...
def int2bin(i,nbits=8,output=str): """ Convert integer to binary string or list Parameters ---------- **`i`**: Integer value to convert to binary representation. **`nbits`**: Number of bits to return. Valid values are 8 [DEFAULT], 16, 32, and 64. **`output`**: Return data as `str` [...
def _sorted(dictionary): """Returns a sorted list of the dict keys, with error if keys not sortable.""" try: return sorted(dictionary) except TypeError: raise TypeError("tree only supports dicts with sortable keys.")
def _preprocess_dims(dim): """Preprocesses dimensions to prep for stacking. Parameters ---------- dim : str, list The dimension(s) to apply the function along. """ if isinstance(dim, str): dim = [dim] axis = tuple(range(-1, -len(dim) - 1, -1)) return dim, axis
def true_param(p): """Check if ``p`` is a parameter name, not a limit/error/fix attributes.""" return ( not p.startswith("limit_") and not p.startswith("error_") and not p.startswith("fix_") )
def distance_2D(p1, p2): """ Get distance between two points Args: p1: first point index 0 and 1 should be x and y axis value p2: second point index 0 and 1 should be x and y axis value Returns: distance between two points """ return (p1[0] - p2[0]) * (p1[0] - p2[0]) + ...
def _str_between(text, start, stop): """Returns the string found between substrings `start` and `stop`.""" return text[text.find(start) + 1 : text.rfind(stop)]
def make_dict(duration, voltages, beats, mean_hr, beat_times): """Makes a dictionary following the format described on github :param duration: Time length of data sequence :param voltages: Voltage extremes in tuple form :param beats: Number of beats :param mean_hr: Calculated heart rate in BPM ...
def remove_old_resources(resource_list): """ Remove resources in a list which have the same id as another resource but an older timestamp """ uniques = [] ids = set() for r in resource_list: if r["id"] not in ids: uniques.append(r) ids.add(r["id"]) return uniq...
def _encode(data, name='data'): """Call data.encode("latin-1") but show a better error message.""" try: return data.encode("latin-1") except UnicodeEncodeError as err: raise UnicodeEncodeError( err.encoding, err.object, err.start, err.end, ...
def _Offsets(*args): """Valid indentation offsets for a continued line.""" return dict((a, None) for a in args)
def expand_span(span, expand_length=2): """ Args: span (list): [st, ed] expand_length (int): length to add on the two sides Returns: expanded_span (list): [max(0, st-expand_length), ed + expand_length] Only use the span for indexing, no need to worry the case where ...
def de_dup_and_sort(input): """ Given an input list of strings, return a list in which the duplicates are removed and the items are sorted. """ input.sort() input=set(input) input = list(input) input.sort() ###################################### added line ###################### ...
def matches(rec, labels): """returns True if rec has these labels. rec: dictionary like: "2019-10-17_08-37-38-right_repeater.mp4": { "file": "2019-10-17_08-37-38-right_repeater.mp4", "car": { "label": "car", "count": 34, "frames": [ 0, ...
def avg_midrange(values): """Return the arithmetic mean of the highest and lowest value of values.""" vmin = min(values) vmax = max(values) return (vmin + vmax) / 2
def unindent(source): """ Removes the indentation of the source code that is common to all lines. Does not work for all cases. Use for testing only. """ def normalize(line): normalized = [] for i, c in enumerate(line): if c == " ": normalized.app...
def distance(x_1, x_2): """Calculate distance between sets. Args: x_1, x_2: sets. Returns: distance. """ return len(x_1) + len(x_2) - len(x_1.intersection(x_2)) * 2
def best_time(time1, time2): """Return the best of two given times.""" time = min(time1, time2) if time == 0: return max(time1, time2) # if no time yet --> set the highest return time
def is_prime(number): """ Finds the provided number Prime or Not Example No: 3.1 in Book Complexity: O(n) :param number: Number to be checked as Prime or Not :return: True / False """ if number <= 1: return False else: for i in range(2, number-1): if numbe...
def isHole(ring): """# problem due to inverted Tkinker canvas, so i do opposite of below: Checks to see if points are in counterclockwise order which denotes a inner ring of a polygon that has a donut-like shape or a hole such as a lake etc. Argument: ring - a list of tuples denoting x,y c...
def blend3(d = 0.0, u = 1.0, s = 0.05): """ blending function polynomial d = delta x = xabs - xdr u = uncertainty radius of xabs estimate error s = tuning scale factor returns blend """ d = float(d) u = float(u) s = min(1.0,float(abs(s))) # make sure positive <= 1...
def get_digit_b(number, digit): """ Given a number, returns the digit in the specified position, for an out of range digit returns 0 """ return number % 10**digit // 10**(digit-1)
def _str(int_inn): """Change the int to string but make sure it has two digits. The int represents a month og day.""" if len(str(int_inn)) < 2: int_as_string = '0' + str(int_inn) else: int_as_string = str(int_inn) return int_as_string
def header(text, color='black'): """Create an HTML header""" raw_html = f'<h1 style="margin-top:12px;color: {color};font-size:54px"><center>' + str( text) + '</center></h1>' return raw_html
def quantiles2percentiles(quantiles): """ converts quantiles into percentiles """ return [100*x for x in quantiles]
def post_match(view, name, style, first, second, center, bfr, threshold): """Ensure that backticks that do not contribute inside the inline or block regions are not highlighted.""" if first is not None and second is not None: diff = first.size() - second.size() if diff > 0: first = ...
def _convert_label(key): """Ctreate char label from key string.""" try: return ''.join(chr(int(_key, 16)) for _key in key.split(',')) except ValueError: return ''
def dop2str(dop: float) -> str: """ Convert Dilution of Precision float to descriptive string. :param float dop: dilution of precision as float :return: dilution of precision as string :rtype: str """ if dop == 1: dops = "Ideal" elif dop <= 2: dops = "Excellent" el...
def durationToText(seconds): """ Converts seconds to a short user friendly string Example: 143 -> 2m 23s """ days = int(seconds / 86400000) if days: return '{0} day{1}'.format(days, days > 1 and 's' or '') left = seconds % 86400000 hours = int(left / 3600000) if hours: ...
def keywithmaxval(dic): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(dic.values()) k=list(dic.keys()) if len(v) > 0: return k[v.index(max(v))] else: return None
def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 """ digits = 0 while n > 0: n = n // 10 digits += 1 return digits
def capitalize_first_character(some_string): """ Description: Capitalizes the first character of a string :param some_string: :return: """ return " ".join("".join([w[0].upper(), w[1:].lower()]) for w in some_string.split())
def root(number, index): """Calculates the number to the specified root""" return float(number) ** (1 / float(index))
def get_nth_subkey_letters(nth: int, key_length: int, message: str) -> str: """Return every nth letter in the message for each set of key_length letters in the message. Args: nth (int): Index to return for every key_length set of letters. key_length (int): Length of the key. message (st...
def find_epoch(s): """ Given a package version string, return the epoch """ r = s.partition(':') if r[1] == '': return '' else: return r[0]
def hexagonal(n: int) -> int: """Returns the nth hexagonal number, starting with 1.""" return n * (2 * n - 1)
def decode_list(list_): """ Decodes a list of encoded strings, being sure not to decode None types Args: list_: A list of encoded strings. Returns: A list of decoded strings """ return [ item.decode() if item is not None else None for item in list_ ]
def cleanup_model(model, form): """Remove values for fields that are not visible.""" new_model = {} fields = form["fields"] for key, value in model.items(): if key not in fields: continue if key.startswith("html-"): continue field = fields[key] if ...
def get_username( strategy, details, user= None, *args, **kwargs ): """ Use the 'steamid' as the account username. """ if not user: username = details[ 'player' ][ 'steamid' ] else: username = strategy.storage.user.get_username( user ) return { 'username': usernam...
def pad(f_bytes, mod_len): """ Pads the file bytes to the nearest multiple of mod_len """ return f_bytes + (b'0' * (mod_len - len(f_bytes) % mod_len))
def mm_as_cm(mm_value): """Turn a given mm value into a cm value.""" if mm_value == 'None': return None return float(mm_value) / 10
def filter_files(file_list, token=".csv"): """ Filter folders and files of a file_list that are not in csv format :param file_list: List of file names :param token: String to find and accept as file, ex: ".csv" :return: Filtered list """ final_file_list = list(filter(lamb...
def sanitize_properties(properties): """ Ensures we don't pass any invalid values (e.g. nulls) to hubspot_timestamp Args: properties (dict): the dict of properties to be sanitized Returns: dict: the sanitized dict """ return { key: value if valu...
def copy_keys_to_each_other(dict_1, dict_2, val=None): """ Make sure that all keys in one dict is in the other dict as well. Only the keys are copied over - the values are set as None eg: dict_1 = { "a": 1, "b": 2 } dict_2 = { "a": 13, "c": 4 } dict...
def split(path): """ splits path into parent, child """ if path == '/': return ('/', None) parent, child = path.rsplit('/', 1) if parent == '': parent = '/' return (parent, child)
def get_kmer_counts(kmer_idx): """ """ kmer_counts = {} for kmer, offsets in kmer_idx.items(): kmer_counts[kmer] = len(offsets) return kmer_counts
def get_line_padding(line_num: int) -> str: """ Gets line_num blank lines. :param line_num: The number of blank lines to get """ line: str = "" for i in range(line_num): line += "\n" return line
def rotate(l, n): """Rotate list for n steps.""" return l[n:] + l[:n]
def _sets_are_unique(sets): """ Returns True if each set has no intersecting elements with every other set in the list :param sets: a list of sets """ nsets = len(sets) for a in range(nsets): for b in range(a + 1, nsets): if len(sets[a].intersection(sets[b])) > 0: return False return Tru...
def get_last_base_call_in_seq(sequence): """ Given a sequence, returns the position of the last base in the sequence that is not a deletion ('-'). """ last_base_pos = None for pos_from_end, base in enumerate(sequence[::-1]): if base != '-': last_base_pos = len(sequence) - pos...
def _escape_user_name(name): """Replace `_` in name with `&lowbar;`.""" return name.replace("_", "&lowbar;")
def usage_type(d, i, r): """Get usage type from item :param d: Report definition :type d: Dict :param i: Item definition :type i: Dict :param r: Meter reading :type r: usage.reading.Reading :return: usage_type :rtype: String """ return i.get('usage_type', '')
def tile_coords_and_zoom_to_quadKey(TileX, TileY, zoom): """ The function to create a quadkey for use with certain tileservers that use them, e.g. Bing Parameters ---------- TileX : int x coordinate of tile TileY : int y coordinate of tile zoom : int tile map servi...
def wrapTex(tex): """ Wrap string in the Tex delimeter `$` """ return r"$ %s $" % tex
def relay_branch_tuple(relay_branches): """ Create list of (relay, branch) tuples """ relay_branch_tuple = list() for r, branches in relay_branches.items(): for b in branches: relay_branch_tuple.append((r,b)) return relay_branch_tuple
def most_favourite_genre(list_of_genres: list) -> str: """ Return one element, that is the most frequent in 2 lists of list_of_genres, return the first element in first list if there is no intersection or if 2 lists in list_of_genres are empty. If one of lists is empty, return the first element of t...
def sum_of_intervals(intervals): """ Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals are represented by a pair of integers in the form of an array. The f...
def extract_hydrogens_from_instructions(instruction): """ If the core or the fragment atom contains a "-" means that the user is selecting an specific H to be bonded with the heavy atom. For this reason, this detects if this option has been selected by the user and extract the PDB-atom-name of each elem...
def _build_tool_path(d): """Build the list of tool_path for the CROSSTOOL file.""" lines = [] for k in d: lines.append(" tool_path {name: \"%s\" path: \"%s\" }" % (k, d[k])) return "\n".join(lines)
def generate_positive_example(anchor, next_anchor): """Generates a close enough pair of states.""" first = anchor second = next_anchor return first, second
def _excel_col(col): """Covert 1-relative column number to excel-style column label.""" quot, rem = divmod(col - 1, 26) return _excel_col(quot) + chr(rem + ord('A')) if col != 0 else ''
def factorial(n: int) -> int: """ Return n! for postive values of n. >>> factorial(1) 1 >>> factorial(2) 2 >>> factorial(3) 6 >>> factorial(4) 24 """ fact = 1 for i in range(2, n+1): fact=fact*n return fact
def remove_multiple_spaces(string): """ Strips and removes multiple spaces in a string. :param str string: the string to remove the spaces from :return: a new string without multiple spaces and stripped """ from re import sub return sub(" +", " ", string.strip())
def average_above_zero(tab): """ brief : computs the average args : tab : a list of numeric value Return : the computed average Raises : Value error if no positive value Value error if input tab is ot a list """ if not (isinstance(tab, list)):#on veri...
def power(x, n): """Compute the value x**n for integer n.""" if n == 0: return 1 else: partial = power(x, n // 2) # rely on truncated division result = partial * partial if n % 2 == 1: # if n odd, include extra factor of x ...
def who_wins(character_score_1, character_score_2): """ Determines who wins """ if character_score_1 > character_score_2: return "player 1" else: return "player 2"
def formatExc (exc): """ format the exception for printing """ try: return f"<{exc.__class__.__name__}>: {exc}" except: return '<Non-recognized Exception>'
def check_new_measurement(timestamp, last_measurement): """ checks if latency measurements have been made for the last state @param timestamp: @param last_measurement: @return: """ for dpid_rec in last_measurement: for dpid_sent in last_measurement[dpid_rec]: if last_meas...
def links_differ(link1, link2): """Return whether two links are different""" differ = True if link1 == link2: differ = False # Handle when url had training slash if link1[0:-1] == link2: differ = False if link2[0:-1] == link1: differ = False return differ
def link(url, title, icon=None, badge=None, **context): """ A single link (usually used in a bundle with 'links' method. :param url: An action this link leads to. 'account', 'event' etc If the url starts with a slash, an looks like this: /aaa/bbb, then this link will lead to ...
def merge_metadata(cls): """ Merge all the __metadata__ dicts in a class's hierarchy keys that do not begin with '_' will be inherited. keys that begin with '_' will only apply to the object that defines them. """ cls_meta = cls.__dict__.get('__metadata__', {}) meta = {} for base in c...
def determine_winner(player_move, comp_move): """Takes in a player move and computer move each as 'r', 'p', or 's', and returns the winner as 'player', 'computer', or 'tie'""" if player_move == comp_move: return "tie" elif (player_move == "r" and comp_move == "s") or \ (player_mov...
def transform_txt_to_json(f): """ Transorm JS Object to JSON with the necessary information """ try: f = open('source.txt', 'rt') lines = f.readlines() f.close() with open('source.json', 'w') as json_file: line_with_data = lines[2][:-2] json_file.write(lin...
def single_line(string: str) -> str: """Turns a multi-line string into a single. Some platforms use CR and LF, others use only LF, so we first replace CR and LF together and then LF to avoid adding multiple spaces. :param string: The string to convert. :return: The converted string. """ re...
def validateYear(year): """ Validate the year value """ if year < 0: return False if len(str(year)) < 4: return False return True
def delete_x_with_catv(names_with_catv): """ Delete variables which end with CATV. Parameters ---------- names_with_catv : List of str. Returns ------- x_names : List of str. """ x_names = [] for x_name in names_with_catv: if x_name[-4:] != 'CATV': x_na...
def power(term, exponent): """Raise term to exponent. This function raises ``term`` to ``exponent``. Parameters ---------- term : Number Term to be raised. exponent : int Exponent. Returns ------- result : Number Result of the operation. Raises --...
def condition_flush_on_every_write(cache): """Boolean function used as flush_cache_condition to anytime the cache is non-empty""" return len(cache) > 0
def expected_overlapping(total, good, draws): """Calculates the expected overlapping draws from total of good.""" drawn = int(round(draws * (good / total))) return min(max(drawn, 0), int(round(good)))
def get_user_profile_url(user): """Return project user's github profile url.""" return 'https://github.com/{}'.format(user)
def has_permission(expected, actual): """ Check if singular set of expected/actual permissions are appropriate. """ x = set(expected).intersection(actual) return len(x) == len(expected)
def recommended_spacecharge_mesh(n_particles): """ ! -------------------------------------------------------- ! Suggested Nrad, Nlong_in settings from: ! A. Bartnik and C. Gulliford (Cornell University) ! ! Nrad = 35, Nlong_in = 75 !28K ! Nrad = 29, Nlong_in = 63 !20K ! Nrad =...
def check_clonotype( probe_v_gene: str, probe_j_gene: str, probe_cdr3_len: int, probe_cdr3_aa_seq: str, target_v_gene: str, target_j_gene: str, target_cdr3_len: int, target_cdr3_aa_seq: str, ) -> float: """ Compares two VH sequences to check if clonotypes match. Returns sequ...
def find_by_key(key, array): """Return a list of array elements whose first element matches the key. Args: key (string): Slash-separated string of keys to search for. array (list): Nested list of lists where first member of each list is a key. Returns: list: Elements from the list ...
def goodMatchGeneralized(matchlist,thresh=10): """This function looks through all the edit distances presented in the list 'matchlist', and returns the smallest one, or -1 if they are all -1 or all above thresh""" bestmatch = -1 minimatch = thresh+10 for match_index in range(len(matchlist)): ...
def remove_multiedges(E): """Returns ``(s, d, w)`` with unique ``(s, d)`` values and `w` minimized. :param E: a set of edges :type E: [(int, int, float)] :return: a subset of edges `E` :rtype: [(int, int, float), ...] """ result = [] exclusion = set() for...
def merge_extras(extras1, extras2): """Merge two iterables of extra into a single sorted tuple. Case-sensitive""" if not extras1: return extras2 if not extras2: return extras1 return tuple(sorted(set(extras1) | set(extras2)))