content
stringlengths
42
6.51k
def split(value, separator=','): """ Wrapper for Python's `split()` string method. Args: value: A string separator: String on which the value will be split """ return value.split(separator)
def _compress(data: dict) -> dict: """ a function that "throws away" unnecessary data. The price we pay is that we loose the ability to easily deserialize the result. But if we're only interested in a simple tree that's fine. """ if ( "children" in data and "type" in data ...
def collatz_len_fast(n, cache): """Slightly more clever way to find the collatz length. A dictionary is used as a cache of previous results, and since the dictionary passed in is mutable, our changes will reflect in the caller. """ if n == 1: return 1 if n in cache: return c...
def iid_to_ndx(iid): """ Convert location index (iid) to zero based index for LIST[ndx] """ sndx = iid[-3:] # Last 3 characters of "L999" = "999" return int(sndx) - 1
def _filter_out_spotify_artists_without_genres(spotify_artists): """ We need at least one genre to add an artist to the graph, so filter out artists that Spotify returned with an empty genre list. """ return [ spotify_artist for spotify_artist in spotify_artists if len(spotif...
def process_parens(taxon): """subgenera are parenthesized; if this occurs in the name of a species or lower ranked taxon, strip out the subgenus reference; if the taxon is the subgenus, assume the parenthesized portion is the subgenus name, so strip out the genus name that preceeds it and ...
def respond(text): """Creates a response in-channel.""" return { "response_type" : "in_channel", "text" : text }
def encrypt_ascii(k: int, plaintext: str) -> str: """Return the encrypted message using the Caesar cipher with key k. Preconditions: - all({ord(c) < 128 for c in plaintext}) - 1 <= k <= 127 >>> encrypt_ascii(4, 'Good morning!') 'Kssh$qsvrmrk%' """ ciphertext = '' for lette...
def minify_html(html): """Perform a template-specific, rudimentary HTML minification for displaCy. Disclaimer: NOT a general-purpose solution, only removes indentation and newlines. html (unicode): Markup to minify. RETURNS (unicode): "Minified" HTML. """ return html.strip().replace(" ",...
def NfcNormalize(iri): """ On Python 2.3 and higher, normalizes the given unicode string according to Unicode Normalization Form C (NFC), so that it can be used as an IRI or IRI reference. """ try: from unicodedata import normalize iri = normalize('NFC', iri) except ImportErr...
def product(numbers): """Calculate product of numbers.""" result = 1 for number in numbers: result *= number return result
def checkArguments (arguments): """ Checks for the minimum # of arguments. Returns 0 on success and -1 on failure. Parameters arguments (String): Command line parameters passed by user """ # Minimum Argument Count: 2 if (len (arguments) >= 2): return 0 else: return -...
def first(sequence): """Returns the first item in a non-empty sequence, otherwise None.""" return sequence[0] if len(sequence) > 0 else None
def F2C(F): """Convert Fahrenheit to Celsius""" return (F - 32) / 1.8
def calculate_abv(og, fg, method="simple"): """Calculate percent alcohol by volume based on starting and finishing gravity readings. Args: og (float): Measured initial specific gravity fg (float): Measured final specific gravity """ if method == "advanced": return (76.08 * (...
def endMatch(MVal, newCIGAR): """ Function to end an ongoing match during error correction, updating new CIGAR and MD tag strings as needed. MVal keeps track of how many matched bases we have at the moment so that when errors are fixed, adjoining matches can be combined. When an intron or...
def peters_f(e): """f(e) from Peters and Mathews (1963) Eq.17 This function gives the integrated enhancement factor of gravitational radiation from an eccentric source compared to an equivalent circular source. Parameters ---------- e : `float/array` Eccentricity Returns -----...
def prettyPrint(anything=None): """ Easy pretty print. Expensive, useful for debugging. Args: anything, a python object. Returns, multi-line string. Does not break on error. """ import pprint try: if anything is not None: return pprint.pprint(anything) else...
def qpm_to_bpm(quarter_note_tempo, numerator, denominator): """Converts from quarter notes per minute to beats per minute. Parameters ---------- quarter_note_tempo : float Quarter note tempo. numerator : int Numerator of time signature. denominator : int Denominator of t...
def validate_clockwise_points(points): """ Validates that the points that the 4 points that dlimite a polygon are in clockwise order. """ if len(points) != 8: raise Exception("Points list not valid." + str(len(points))) point = [ [int(points[0]) , int(points[1])], ...
def perfect_function( pretty_int, pretty_optional='butts' ): """a perfect sample of a stand-alone function Args: pretty_int (int): a number pretty_optional (str): optional string Returns: str: concatenated values together """ return 'Hello world: ' + str(pr...
def find_combinations(numbers, target, partial=[]): """ Find combinations of numbers that sum to a particular target value; return them as a list of lists. """ combos = [] s = sum(partial) if s == target: combos.append(partial) if s >= target: return combos for i ...
def lcs(x, y): """ Finds the longest common subsequence of two strings. :param x: a string input value. :param y: a string input value. :return: the longest common subsequence of the two strings. """ matrix = [[0 for x in range(len(y) + 1)] for x in range(len(x) + 1)] for i in range(len(...
def generate_ring(num_node): """ It will generate the ring relationship. :param number of nodes :return dictionary for relationship of each node """ device_client_dic = {} for n in range(num_node): next_node = (n + 1) % num_node last_node = n - 1 if last_nod...
def energy(a, C, f, eref=1): """ Minimum energy (or other metric given as e below) of events that occur with a frequency of f for a cumulative frequency distribution of the form f = C*e**-a. """ return (f/C)**(1/-a)*eref
def daisy_chain_from_acquisitions(acquisitions): """Given a list of acquisiton dates, form the names of the interferograms that would create a simple daisy chain of ifgs. Inputs: acquisitions | list | list of acquistiion dates in form YYYYMMDD Returns: daisy_chain | list | names of daisy cha...
def shift(list, num): """ this function shifts the position of an existing list or string and returns it as a new list """ list = [x for x in list] for i in range(num): first = list[0] list.pop(0) list.append(first) return list
def all_pairs_matching_sum(a, t): """a is the array, t is the sum. Runtime Complexity: O(n^2), where n = len(a) """ num_1 = 0 num_2 = 0 matching_pairs = list() # iterate through numbers in the list for i in range(len(a)): num_1 = a[i] # iterate through all other numbers i...
def num_in_col(board, col, num): """True if num is already in the column, False otherwise""" return num in [row[col] for row in board]
def _sort_topk_votes(x, k): """ Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes. """ y = sorted(x.items(), key=lambda x: x[1], reverse=True)[:k] return [{'class': i[0], 'votes': i[1]} for i in y]
def efficientnet_params(model_name): """Map EfficientNet model name to parameter coefficients. 'Coefficients: width,depth,res,dropout """ params_dict = { 'efficientnet-b0': (1.0, 1.0, 224, 0.2), 'efficientnet-b1': (1.0, 1.1, 240, 0.2), 'efficientnet-b2': (1.1, 1.2, 260, ...
def max_column_sizes(header, data): """ Determine the maximum length for each column and return the lengths as a list """ sizes = [len(h) for h in header] for row in data: for i in range(len(header)): if len(row[i]) > sizes[i]: sizes[i] = len(row[i]) return sizes
def merge_roidb(roidbs): """ roidb are list, concat them together """ roidb = roidbs[0] for r in roidbs[1:]: roidb.extend(r) return roidb
def gf_mul(multiplicand, multiplier): """ Galois Field multiplication function for AES using irreducible polynomial x^8 + x^4 + x^3 + x^1 + 1 """ product = 0 a = multiplicand b = multiplier while a * b > 0: if b % 2: product ^= a if a >= 128: a = (...
def parse_sim_ser(data): """Extract simulationSerial from data Args: data (dict): models or request Returns: int: simulationSerial """ try: return int(data['simulationSerial']) except KeyError: try: return int(data['models']['simulation']['simulation...
def serialize(r): """ Returns the dictionary represenation serialized back to plain text """ d = "" if ("PROPERTY" in r): keys = sorted(r['PROPERTY'].keys()) for key in keys: for index, val in enumerate(r['PROPERTY'][key]): d += ("\r\nPROPERTY[{0}][{1}]=...
def func(element): """from element to vector representation""" a, b = element return [len(a), len(b)]
def get_small_joker_value(deck): """(list of int) -> int Precondition: the input deck is a valid deck. Return the value of the small joker (value of the second highest card) for the given deck of cards. >>> deck = [ 18, 21, 24, 27, 2, 5, 8, 11, 14, 17, 20, 23, 26, 1, 4, 7, 10, \ 13, 16, 19, 2...
def is_id(s): """ Return True if `s` is some kind of id. """ return s and ' ' not in s.strip()
def thelittleone(arg): """Return the 4th line of a verse. arg - [verb, object]""" return "The little one stops to {} his {},\n".format(arg[0], arg[1])
def multiline_string_repr(string): """Return a representation of the string using multi-line string format if possible.""" if '"""' not in string: string = '"""{}\n"""\n'.format(string) elif "'''" not in string: string = "'''{}\n'''\n".format(string) else: string = repr(strin...
def obj_get_arginfo(obj, args): """get_arginfo(obj, args) return a tuple of the object argument info.""" return ("arg_info",) * len(args)
def calcserverusedmem(mems): """ Return int(100*(MemTotal-MemFree)/MemTotal) from /proc/meminfo. """ return 100 * (mems[0] - mems[1]) / mems[0]
def _split_header_params(s): """Split header parameters.""" result = [] while s[:1] == b';': s = s[1:] end = s.find(b';') while end > 0 and s.count(b'"', 0, end) % 2: end = s.find(b';', end + 1) if end < 0: end = len(s) f = s[:end] resu...
def inverse(pmt): """ get the inverse of a permutation """ nelem = len(pmt) assert sorted(pmt) == list(range(nelem)) pmt = tuple(pmt) inv = tuple(pmt.index(i) for i in range(nelem)) return inv
def findLen(string: str): """ find the length of a string and take into account that emojis are double width """ counter = 0 for i in string: if ord(i) > 10000: # emoji is double width counter += 1 counter += 1 return counter
def str2hexstr(md5sum): """Return the hex representation of a string.""" return "".join([ "%02x" % ord(c) for c in md5sum ])
def ari(clusters_x, clusters_y): """ :return: adjusted rand index SCAN Section 6.2.1 """ def nCr(num): return num * (num - 1) / 2.0 n_x = sum([len(clusters_x[cl]) for cl in clusters_x]) n_y = sum([len(clusters_y[cl]) for cl in clusters_y]) assert n_x == n_y n = n_x sum_i =...
def convert_to_celsius(fahrenheit): """ (number) -> float Return the number of Celsius degrees equivalent to fahrenheit degrees >>> convert_to_celsius(75) 23.88888888889 """ return (fahrenheit - 32.0) * 5.0 / 9.0
def get_link_data_from_soup(soup): """extracts url and link text from soup link snippet <a class="topictitle" href="https://...">_text_</a> """ link_data = [] if soup == None: return [None, None] link = soup.get('href') text = soup.text if link is not None: link = lin...
def elem_Q(w, Q, n): """ Simulation Function: -Q- Inputs ---------- w = Angular frequency [1/s] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return 1 / (Q * (w * 1j) ** n)
def fibonacci(n): """ Use this function to get CPU usage """ return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)
def auto_key(*args, **kwargs): """ >>> auto_key(1,2,c=3,d=4) '1,2,c=3,d=4' >>> auto_key(1,2) '1,2' >>> auto_key(c=3,d=4) 'c=3,d=4' >>> auto_key() '' """ args_str = ",".join(map(str, args)) kwargs_str = ",".join(map(lambda kv: f"{kv[0]}={kv[1]}", kwargs.items())) retur...
def get_header(request: dict, name: str): """Get a header from the request payload sent by API Gateway proxy integration to Lambda. Does not deal with multi-value headers, but that's fine for this app""" for key in request['headers']: if key.lower() == name.lower(): return request['heade...
def compute_multipliers(tokens): """ Determine the multiplier based on the tokens at the end of a number (e.g. million from "one thousand five hundred million") """ total = 1 for token in tokens: value, label = token total *= value return total
def rellenaLista(maxTrials,tipoDummy): """ Funcion que nos permite rellenar listas con un valor predefinido maxtrial -> int dumy-any """ lista=[] for i in range(maxTrials+1): lista.append(tipoDummy) return lista
def apply_poly(poly, x, y, z): """ Evaluates a 3-variables polynom of degree 3 on a triplet of numbers. Args: poly: list of the 20 coefficients of the 3-variate degree 3 polynom, ordered following the RPC convention. x, y, z: triplet of floats. They may be numpy arrays of same l...
def to_conll_iob(annotated_sentence): """ `annotated_sentence` = list of triplets [(w1, t1, iob1), ...] Transform a pseudo-IOB notation: O, PERSON, PERSON, O, O, LOCATION, O to proper IOB notation: O, B-PERSON, I-PERSON, O, O, B-LOCATION, O """ proper_iob_tokens = [] for idx, annotated_token...
def convert_to_number(value, *, prefix=None, suffix=None): """Turns numeric looking things into floats or ints Integery things should be integers >>> for inty in ['0', '1', '2', '99999']: ... assert isinstance(convert_to_number(inty), int) Floaty things should be floats >>> for floaty in ['0...
def normalize_path_elms(path): """Replace space & dash into underbar and return it.""" return path.replace(' ', '__').replace('-', '_')
def solution(A): """Check if an array is a permutation. A permutation is a sequence containing each element from 1 to N once, and only once. Args: A (list): A non-empty list of N integers. Returns: int: 1 if the array is a permutation, 0 if it is not. Complexity: Time...
def indent(txt, indent_level): """ Indent a piece of text >>> indent('foo', 2) ' foo' """ indent = " " * indent_level return "\n".join(indent + x for x in txt.splitlines())
def fixedHierSubset(x, y): """ Returns whether x==y, or the fixed property with name x is a subset of y Currently (Jan 2015) the fixed properties names are 'UD_codes', 'Prefix_codes', 'Suffix_codes', 'Infix_codes', 'Outfix_codes', 'Hypercodes' :param tuple x :param tuple y :rtype: bool """...
def wrap_slack_code(str): """Format code.""" return f"`{str}`"
def recursive_config_join(config1: dict, config2: dict) -> dict: """Recursively join 2 config objects, where config1 values override config2 values""" for key, value in config2.items(): if key not in config1: config1[key] = value elif isinstance(config1[key], dict) and isinstance(val...
def decode_remote_id(msg): """ practice decoding some remote ids: | 0x27 | 0x01 0xe2 0x40 | 0x03 0x42 0x2a | 0x28 0x0c 0x89 | 0x92 0x00 0x00 0x00 >>> decode_remote_id(_remote_ids[0]) '123456' >>> decode_remote_id(_remote_ids[1]) '213546' >>> decode_remote_id(_remote_ids[2]) '821650' "...
def begin0(*vals): # eager, bodys already evaluated when this is called """Racket-like begin0: return the first value. Eager; bodys already evaluated by Python when this is called. g = lambda x: begin0(23*x, print("hi")) print(g(1)) # 23 """ return vals[0...
def trim(value): """ Strips the whitespaces of the given value :param value: :return: """ return value.strip()
def crossref_mime_type(jats_mime_type): """ Dictionary of lower case JATS mime type to crossRef schema mime type """ mime_types = {} mime_types["application/eps"] = "application/eps" mime_types["application/gz"] = "application/gzip" mime_types["application/tar.gz"] = "application/gzip" ...
def parse_hour(hour, sep=':') -> tuple: """Returns a tuple of integer from an hour like '14:34'.""" if not isinstance(hour, str): return hour return tuple([int(x) for x in hour.split(sep)])
def filter_tokens(tokens, filters): """ eliminates tokens contained in filters args: tokens: list of tokens to be filtered. filters: list of tokens that will get removed from 'tokens'. returns: filtered_tokens: a list of tokens that don't contain any token from filters. "...
def get_antigen_name(qseqid): """ Get the antigen name from the BLASTN result query ID. The last item delimited by | characters is the antigen name for all antigens (H1, H2, serogroup) @type qseqid: str @param qseqid: BLASTN result query ID @return: antigen name """ if qseqid: ...
def laceStringsRecur(S1, S2): """ s1 and s2 are strings. Returns a new str with elements of s1 and s2 interlaced, beginning with s1. If strings are not of same length, then the extra elements should appear at the end. """ def helpLaceStrings(s1, s2, out): print('s1: ', s1, 's2: ', s...
def df_has_data(data) -> bool: """Return True if `data` DataFrame has data.""" return data is not None and not data.empty
def getSubmissionTextAsSingleString(content): """ Get all submission titles as a single string """ items = reversed(content) text = '' for item in items: #print (item.link_flair_text) if item.is_self is not True: #print (str(item.author) + ' ' + item.permali...
def switch_animation_message(name, **params): """ Used to switch an animation params is a dictionary of animation parameters """ return ["animation", { "name": name, "params": params }]
def county_index(county: str) -> str: """ Transform a string into a form used to index something by county. Args: county (str): Name of county Returns: (str): Transformed name to be used as a dict index. """ return str(county).strip().upper().replace(' COUNTY', '')
def get_attribute_values(elements,name): """ returns a list of attributes 'name' from a list of elements """ attribute_values = [] for element in elements: attributes = element.attributes for n in range(attributes.length): attribute = attributes.item(n) if attribute.n...
def choose_rows(rows): """Choose rows from the dataframe according to values in one of the columns.""" # Ensure that the object is not empty. assert(len(rows) > 0) # The following rows preferentially select data where the device_id=64 (i.e the GLONASS over the Trimble). # Also select by data quali...
def phoneme_set(transcriptions): """Reduce list of lists of phonemes to a set of phonemes.""" transcription_phonemes = set() for transcription in transcriptions: for phoneme in transcription: transcription_phonemes.add(phoneme) return transcription_phonemes
def solidEnthalpy(T, hCP, TRef=298.15): """ solidEnthalpy(T, hCP, TRef=298.15) solidEnthalpy (J/mol) = A*(T-TRef) + 1/2*B*(T^2-TRef^2) + 1/3*C*(T^3-TRef^3) Parameters T, temperature in Kelvin TRef, reference temperature hCP, A=hCP[0], B=hCP[1], C=hCP[...
def name_it(id, start, stop): """ Automatically name a sound file with respect to (start, stop) slice audio :param id: :param start: :param stop: :return string: """ return "{}_{}_{}_{}".format(id, int(start * pow(10, 6)), ...
def int_to_bin_converter(value): """Placeholder for my own binary converter""" return f"{value:08b}"
def remove_comment(words): """remove comment string which starts with '#'.""" ret = [] for i in words: if len(i) <= 0: continue if i.startswith("#"): break if i.find("#") != -1: s = i.split("#")[0] ret.append(s) break ...
def make_dict(s_list): """ Convert file list into a dictionary with the file path as its key, and meta data as a list stored as the keys value. This format change makes searching easier. """ return { l_itm['path'] : l_itm for l_itm in s_list}
def balance(N, P, p): """Compute p'th interval when N is distributed over P bins. """ from math import floor L = int(floor(float(N)/P)) K = N - P*L if p < K: Nlo = p*L + p Nhi = Nlo + L + 1 else: Nlo = p*L + K Nhi = Nlo + L return Nlo, Nhi
def say_hello(username: str) -> int: """Say hello to username. Args: username (str): Say hello to ``username``. Returns: int: Return the status of the function. """ retv = 0 if isinstance(username, str): print(f'Hello {username}') else: retv = 1 return r...
def c_git_commit_handler(value, **kwargs): """ Return a git VCS URL from a package commit. """ return {'vcs_url': 'git+http://git.alpinelinux.org/aports/commit/?id={}'.format(value)}
def abs_val(num): """ Find the absolute value of a number. >>abs_val(-5) 5 >>abs_val(0) 0 """ return -num if num < 0 else num
def disable_next_audio_content_enable_previous_audio_content(value_next, value_previous): """ Disbaling the content that is not required """ return {"display":"none"}
def letter_perm(lex, couple): """ Letters permutations of the plugboard """ plug = [] for cara in lex: if cara == couple[0]: plug.append(couple[1]) elif cara == couple[1]: plug.append(couple[0]) else: plug.append(cara) return plug
def split_seq(seq,size): """ Split up seq in pieces of size """ return [seq[i:i+size] for i in range(0, len(seq), size)]
def isinstance_all(iterable, class_or_tuple): """ Check if all items of an iterable are instance of a class ou tuple of classes >>> isinstance_all(['Hello', 'World'], str) True >>> isinstance_all([1, 'Hello'], (str, int)) True >>> isinstance_all([True, 'Hello', 5], int) False ""...
def string_to_pmid_list(input_string:str): """ Parameters ---------- input_string : str input_string = ''' 8330046 8149174 8912442 9705549 10647690 11746546 26509358 26872575 27819757 ''' output = utils.string_...
def create_node(name, **kwargs): """Create and return a new node""" n = {'name': name, 'children': []} n.update(kwargs) return n
def ExtendPhycheIndex(original_index, extend_index): """Extend {phyche:[value, ... ]}""" if 0 == len(extend_index): return original_index for key in list(original_index.keys()): original_index[key].extend(extend_index[key]) return original_index
def strip_sensitive_data_from_sentry_event(event, hint): """ Helper method to strip sensitive user data from default sentry event when "send_default_pii" is set to True. All user-related data except the internal user id will be removed. Variable "hint" contains information about the error itself which w...
def pretty_timer(seconds: float) -> str: """Formats an elapsed time in a human friendly way. Args: seconds (float): a duration of time in seconds Returns: str: human friendly string representing the duration """ if seconds < 1: return f'{round(seconds * 1.0e3, 0)} milliseco...
def binary_search(integer, integers): """Takes a target search integer to pull from an array of given integers. If target integer is not in array returns False.""" while 1: if len(integers) % 2: mid = (len(integers) - 1) // 2 else: mid = int(len(integers) / 2) ...
def sign_non_zero(x): """ returns the sign of the input variable as 1 or -1 arbitrarily sign_non_zero(0) = 1 """ return 2 * (x >= 0) - 1