content
stringlengths
42
6.51k
def parse_id_array_param(list): """Converts a list of strings ids to int""" return [int(y) for y in list]
def color_interpolate(start_color, end_color, progress): """Auxiliary color interpolation function What this really does is just calculate start_color + progress * (end_color - start_color) Parameters: start_color - tuple RGB color 0 - 255; the color at 0.0 progress end_color - tuple RGB c...
def summarize_segments(segments): """Take a list of segments and create a simple summary""" if len(segments) > 0: on_floor = sum([x["duration"] for x in segments if x["location"] == 'on floor']) off_floor = sum([x["duration"] for x in segments if x["location"] == 'off floor']) working =...
def camelcase(text): """Convert text to camel case Notes: The algorithm sets the first letter of each word to uppercase. Existing uppercase letters are left unchanged. Words are split on whitespace. Args: text: string, text to convert Returns: string, converted...
def get_sig_label(primary_p, secondary_p, n_nominal, primary_q, primary_p_cutoff, secondary_p_cutoff=0.05, n_nominal_cutoff=2, secondary_or_nominal=True, fdr_q_cutoff=0.05, secondary_for_fdr=False): """ Checks if a gene should be considered exome-wide or F...
def distBetwClusters(clusterA, clusterB, Z): """ Computes the distance between 2 clusters min linkage """ dist = 1500 for i in clusterA: for j in clusterB: if Z[i][j] != 0: #print("Z[i][j]:" + str(Z[i][j])) dist = min(dist, Z[i][j])...
def multiply(a, b, c): """returns the product of three numbers""" return a * b * c
def handle_html(e, key): """ Handle an HTML field. """ value = "" if key in e: value = e[key]["hippostd:content"] \ .replace('\n','') \ .replace('\t','') return value
def test_climate_aware(distinct_keywords: float, total_keywords: float, article_cai: float) -> bool: """Returns whether an article with given parameters is climate aware or not.""" return distinct_keywords >= 8 and total_keywords >= 15 and article_cai >= 0.02
def constrain_cfgdict_list(cfgdict_list_, constraint_func): """constrains configurations and removes duplicates""" cfgdict_list = [] for cfg_ in cfgdict_list_: cfg = cfg_.copy() if constraint_func(cfg) is not False and len(cfg) > 0: if cfg not in cfgdict_list: cfg...
def clean_unit(unit_str): """remove brackets and all white spaces in and around unit string""" return unit_str.strip().strip('[]').strip()
def remove_list_items_and_duplicates(input_list, items_to_remove): """ If duplicates exist in input_list they will be removed. If maintaining list duplicates is required, use remove_list_items_and_retain_duplicates instead. """ if input_list is None: return [] elif items_to_remove is Non...
def flatten(nested): """ flattens a nested list >>> flatten([['wer', 234, 'brdt5'], ['dfg'], [[21, 34,5], ['fhg', 4]]]) ['wer', 234, 'brdt5', 'dfg', 21, 34, 5, 'fhg', 4] """ result = [] try: # dont iterate over string-like objects: try: nested + '' except(TypeError): pass else:...
def check_user_mask(input,verbose=False): """ Checks user-defined soft constraints by ensuring that input is a list of strings """ output = [] if not input: ouput = [] return output if (not isinstance(input,(list,tuple))): raise ValueError("\n User mask must be in the form of a list of tuples, each of len...
def is_reg_writable(reg): """Returns whether a Pozyx register is writeable.""" if (0x10 <= reg < 0x12) or (0x14 <= reg < 0x22) or (0x22 <= reg <= 0x24) or (0x26 <= reg < 0x2B) or ( 0x30 <= reg < 0x3C) or (0x85 <= reg < 0x89): return True return False
def memory_in_gb(bytes: int) -> float: """ Converts a memory amount in bytes to gigabytes. :param bytes: :return: """ gb = 2 ** 30 return bytes / gb
def is_list(v): """ Check if variable is list """ return isinstance(v, list)
def weakchecksum(data): """ Generates a weak checksum from an iterable set of bytes. """ a = b = 0 l = len(data) for i in range(l): a += data[i] b += (l - i) * data[i] return (b << 16) | a, a, b
def get_missing_words(grammar, tokens): """ Find list of missing tokens not covered by grammar """ missing = [tok for tok in tokens if not grammar._lexical_index.get(tok)] return missing
def to_list(x): """ Return x if it is already a list, or return a list if x is a scalar. """ if isinstance(x, (list, tuple)): return x # Already a list, so just return it. return [x]
def get_suggestion_string(sugg): """Return the suggestion list as a string.""" sugg = list(sugg) return ". Did you mean " + ", ".join(sugg) + "?" if sugg else ""
def change_depth(answer: object) -> int: """change the depth variable to visualize friends until that depth This is a helper function for plot function in Graph class in recommendation_graph.py """ choices = ['See only your friends', 'See your friends and their friends', "See your friend...
def parse_xy(string): """Extracts x and y values from strings in a geometry file. Parse the x, y values from strings in that have the format: '1x + 2.0y'. Args: string (str): the string to be parsed. Returns: x, y (float, float): the values of x and y. """ x = y = 0 if...
def output_name(pre_filename: str): """ Args: pre_filename: test_pre_*****.png Returns: test_localization_*****_prediction.png, test_damage_*****_prediction.png """ test_local = pre_filename.replace('pre', 'localization').replace('.png', '_prediction.png') test_damage =...
def solar_coord_type_from_ctype(ctype): """ Determine whether a particular WCS ctype corresponds to an angle or scalar coordinate. """ if ctype[2:4] == 'LN': if ctype[:4] in ['HPLN', 'HGLN']: return 'longitude', 180. return 'longitude', None elif ctype[2:4] == 'LT'...
def gal2l(gallon): """ Converts US gallons to liters using the conversion: 1 US gallon = 3.78541 l :param gallon: US gallons to convert :return liter: the US gallons converted to liters """ liter = 3.78541 * gallon return liter
def child_support_acts(responses, derived): """ Strip off unnecessary characters from child_support_act value """ act = responses.get('child_support_act', '').replace('"', '').replace('[', '').replace(']', '').replace(' ,', ' and ') return act
def convert(number: int) -> str: """convert number to rain string. Args: number (int): Returns: str: """ result = '' if number % 3 == 0: result += 'Pling' if number % 5 == 0: result += 'Plang' if number % 7 == 0: result += 'Plong' if resul...
def average_by_index(scores): """ :param scores: (list) Containing all the scores input by user :return : (float) The average of the elements in scores ---------------------------------------------- This function uses indices in for loop to calculate the average of scores """ ...
def kwarg_popper(kwargs, mpl_kwargs): """ This will not modify kwargs for you. Examples -------- kwargs, plot_kwargs = kwarg_popper(kwargs, plot_kwargs_list) """ kwargs = dict(kwargs) passthrough = {} for k in mpl_kwargs: if k in kwargs: passthrough[k] = kwargs.p...
def tag(dicts, key, value): """Adds the key value to each dict in the sequence""" for d in dicts: d[key] = value return dicts
def quote_title(title): """Quote an article name of a MediaWiki page.""" return title.replace(" ", "_")
def leap_year(year, calendar="standard"): """Determine if year is a leap year. Args: year (int): Year to assess. calendar (optional str): Calendar type. Returns: bool: True if year is a leap year. """ leap = False if (calendar in ["standard", "gregorian", "proleptic_gre...
def autocorrect(user_input, words_list, score_function): """Autocorrect the user_input if it is no a correct word. user_input represents a single word. words_list is a list of all valid words. score_function calculates the difference between two words. If the user_input string is contained insid...
def build_coreference(reference_id: int) -> dict: """Build a frame for a coreference JSON object.""" return { 'id': reference_id, 'representative': { 'tokens': [] }, 'referents': [] }
def get_match(partial): """ Return str value for partial bool. """ if partial is True: return 'partial' else: return 'full'
def quote(txt: str) -> str: """Add quotes to text if needed.""" if ' ' in txt: return '"' + txt + '"' return txt
def jacd(pola, polb): """Computes the jaccard distance Params: ------- * pola: dictionary from states to actions deterministic policy computed by experiment a * polb: dictionary from states to actions deterministic policy computed by experiment b Returns: -------- * jac...
def space_with_nbsp(text): """ Replace spaces with ;nbsp; """ return text.replace(' ', '&nbsp;')
def gcd(a, b): """ Greatest common divisor (greatest common factor) Notes --------- Euclidean algorithm: a > b > r_1 > r_2 > ... > r_n a = b*q + r b = r_1*q_1 + r_2 ... r_n-1 = r_n*q_n gcd(a,b) = gcd(b,r) gcd(a,0) = a """ while b != 0: a, b = b, a % ...
def get_r12_squared(r1, r2): """Get the distance between two centers in Cartesian space.""" return (r1[0] - r2[0])**2.0 + (r1[1] - r2[1])**2.0 + (r1[2] - r2[2])**2.0
def str_to_bool(string): """ str_to_bool('False') -> False str_to_bool('True') -> False str_to_bool('true') -> True """ if isinstance(string, bool): return string if string.lower() == 'false': return False elif string.lower() == 'true': return True else: ...
def get_L_BB_b2_d(L_HP_d, L_dashdash_d, L_dashdash_b2_d): """ Args: L_HP_d: param L_dashdash_d: L_dashdash_b2_d: L_dashdash_d: Returns: """ return L_dashdash_b2_d - L_HP_d * (L_dashdash_b2_d / L_dashdash_d)
def fitness(guess, message): """ Determine the fitness score of an individual. This takes in two strings to compare and returns the score (or fitness) for the closeness of the first string to the second one. """ if guess == message: # if the message is found return 'Done!' i = 0 ...
def score_to_quality(qval, offset: int=32, maxval: int=126): """Convert a score to quality value.""" cval = int(qval) + offset if cval > maxval: cval = maxval return chr(cval)
def create_arn_from_cert(account_number, region, certificate_name): """ Create an ARN from a certificate. :param account_number: :param region: :param certificate_name: :return: """ return "arn:aws:iam::{account_number}:server-certificate/{certificate_name}".format( account_numbe...
def _w_long(x): """Convert a 32-bit integer to little-endian. XXX Temporary until marshal's long functions are exposed. """ x = int(x) int_bytes = [] int_bytes.append(x & 0xFF) int_bytes.append((x >> 8) & 0xFF) int_bytes.append((x >> 16) & 0xFF) int_bytes.append((x >> 24) & 0xFF) ...
def replace_str(text, old, new, count=-1): """ Creates a copy of ``text`` with all occurrences of substring ``old`` replaced by ``new``. If the optional argument ``count`` is given, only the first count occurrences are replaced. :param text: The string to copy :type text: ``str`` ...
def _IsLongMacro(command): """Checks whether a command is a long macro.""" if len(command) == 3 and command[0] == "LONG" and command[1] == "MACRO": return True return False
def data_type(bit_width, prefix="uint", postfix="_t"): """Return a datatype based on a target bit width.""" size = 64 if bit_width <= 8: size = 8 elif bit_width <= 16: size = 16 elif bit_width <= 32: size = 32 return "{}{}{}".format(prefix, size, postfix)
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ frequency = [0 for i in range(10)] for i in input_list: freque...
def get_kmers(start,end,input_alignment): """ Accepts as start and end position within a MSA and returns a dict of all of the kmers :param start: int :param end: int :param input_alignment: dict of sequences :return: dict of sequence kmers corresponding to the positions """ kmers = {} ...
def fib_recursive(position): """ Fibonacci sequence function using recursive algorithm""" if position < 0: return -1 elif position == 0 or position == 1: return position else: return fib_recursive(position - 2) + fib_recursive(position - 1)
def isList(e): """ Variant that excludes None, as well as (byte) strings""" return ( e is not None and not isinstance(e,(str,bytes)) and isinstance(e, list))
def _improve_latex(s): """Improve an OSIRIS-generated latex string using common rules.""" # Descriptive subindexes in roman s2 = s.replace(r"\omega_p", r"\omega_{\mathrm{p}}") s2 = s2.replace("m_e", r"m_{\mathrm{e}}") # "Arbitrary units" in roman s2 = s2.replace("a.u.", r"\mathrm{a.u.}") ret...
def part_1_soliution_1(lines): """Simple iteration and counter solution. That's the way I like it. It can be done with smarter list comprehension, but the price paid is the readability. Counts the number of times a depth measurement increases.""" increase_counter = 0 for i in range(1, len(lines)...
def _GetDecimalModeFromListFormatMode_Tripplet(mode_tripplet_str): """rwx returns 7, r-x returns 5.""" decimal_mode = 0 sticky_bit = False #print mode_tripplet_str if mode_tripplet_str[0] == 'r': decimal_mode += 4 if mode_tripplet_str[1] == 'w': decimal_mode += 2 if mode_tripplet_str[2] =...
def error_general_details(traceback_str: str) -> str: """ Error message DM'ed to the user after a general error with the traceback associated with it. :param traceback_str: The formatted traceback. :returns: the formatted message. """ return f"Here is some more info on the error I encounte...
def select_from_list(tabstop, values): """Completes a partially-completed `tabstop` to one of predefined `values`.""" if tabstop: values = [value[len(tabstop):] for value in values if value.startswith(tabstop)] if len(values) == 1: return values[0] return "[" + " | ".join(values) + "]"
def pad_incr(ids): """Add 1 to ids to account for pad.""" return [i + 1 for i in ids]
def get_range_data(data, bytes_): """ Assists with testing HTTP calls which use the Range header. Should emulate the behavior of the Range header (RFC 2616): http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 @type data: string @param data: The data that you are making the range r...
def partition(lst, start, end): """ move elements below pivot value to left half of list and bigger to right half return the new position of the pivot element """ # use pivot as the last element in list # get it value x = lst[end] # initial store_index store_index = start # loop ...
def negate(a, a_neg): """Generates a negation constraint for variable a. Parameters ---------- a : str Variable to be negated. a_neg : str Identifier of the negated variable. Returns ------- str Text of the constraint. """ return "%s + %s = 1" % (a,...
def drop_redundant_fields(original_data, keys_to_drop): """ strip out any of the original VHS fields which are either empty, sparse, redundantly filled, or just generally unwanted in our ES index """ clean_data = { key: value for key, value in original_data.items() if key not in keys_to_drop...
def x_count(board): """ count how many 'x'-es are on the board """ return len([ch for ch in board if ch == 'x'])
def dtype_is_supported(dtype): """Check if data type is supported by BNNS backend""" return dtype in ("", "float32")
def _gr(gr, mi, mf, ttt, t1): """ Function used to calculate the growth rate necessary to have the ideal growth curve end at the final MTBF and to calculate the optimum growth rate for a test phase. """ return (ttt / t1)**gr + (mf / mi) * (gr - 1.0)
def findfirst(pred, seq): """Return the first element of given sequence that matches predicate. """ for item in seq: if pred(item): return item
def get_wellknown_url(domain, token): """Return the URL for the token file on the server.""" return "http://{0}/.well-known/acme-challenge/{1}".format(domain, token)
def get_player_stack(game_state, uuid): """ Given a Poker game state and a player's uuid, return the value of their stack (how many chips they have). """ if 'table' in list(game_state.keys()): return [player for player in game_state['table'].seats.players if player.uuid == uuid][0].stack ...
def methods_of(obj): """Utility function to get all methods of a object Get all callable methods of an object that don't start with underscore returns a list of tuples of the form (method_name, method). """ result = [] for i in dir(obj): if callable(getattr(obj, i)) and not i.startswith...
def convolution_of_two_uniforms(x, loc1, s1, loc2, s2): """ >>> convolution_of_two_uniforms(-2, 0, 1, 0, 2) 0.0 >>> convolution_of_two_uniforms(-1.5, 0, 1, 0, 2) 0.0 >>> convolution_of_two_uniforms(-1.49, 0, 1, 0, 2) 0.0050000000000000044 >>> convolution_of_two_uniforms(-0.51, 0, 1, 0, 2...
def dmu20_dt_zrl(mu10, mu11, mu20, a_ij, a_ji, b, hL_i, hL_j, ko, vo, kappa, q20=0, B0_j=0, B1_j=0, B2_i=0, B3_i=0): """!Calculate the time-derivative of the second moment(s1^2) of zero rest length crosslinkers bound to rods. @param mu10: First motor moment of s1 @param mu11: Second mo...
def _findstart(line_segment): """Find start of text to autocomplete. >>> _findstart("where x.pers") 8 >>> _findstart("from d.person, d.na") 17 >>> _findstart(" and x.") 10 >>> _findstart("where i") 6 >>> _findstart(" ") 3 """ if '.' in line_segment: retu...
def get_from_dicts(dict1, key, default_value, dict2, extra=''): """ Input: dict1 - first check in this dict (and remove if there) key - key in dict1 default_value - default value if not found dict2 - then check from here Output: value """ ...
def twos_comp(val, bits): """returns the 2's complement of int value val with n bits - https://stackoverflow.com/questions/1604464/twos-complement-in-python""" if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value r...
def connect_string(config): """return connect string""" return config['username'] + "/" + config['password'] + "@" + \ config['db_url']
def _copy_dict(dct, description): """Return a copy of `dct` after overwriting the `description`""" _dct = dct.copy() _dct['description'] = description return _dct
def get_schools_json_list(all_schools): """ Make json objects of the user schools and add them to a list. :param all_schools: School :return: """ schools = [] for school in all_schools: schools.append(school.json()) return schools
def parse_kwargs(s): """Parse command line arguments into Python arguments for parsers. Converts an arguments string of the form: key1=value1,key2=value2 into a dict of arguments that can be passed to Python initializers. This function also understands type prefixes and will cast values prefixed w...
def I_box(m,w,l): """Moment of a box with mass m, width w and length l.""" return m * (w**2 + l**2) / 12
def end_decoding(readings:list, byte_array:bytes, pointer:int): """ Function called if the coding info is 00, which means that there is no more data to decode. Input: readings: list where readings are being stored byte_array: bytes containing sensor's readings pointer: position in the ...
def is_valid_shape(shape): """Return whether the shape is valid for these set of functions""" return shape in ((6,),(9,),(3,3),(6,6))
def get_first_year(data_id): """Returns first year in which ground truth data or forecast data is available Args: data_id: forecast identifier beginning with "nmme" or ground truth identifier accepted by get_ground_truth """ if data_id.startswith("subx_cfsv2") or data_id.startswith("iri...
def l1_norm(vals): """Calculate the L1 norm of a vector.""" if len(vals)==0: return [] try: # If inputs are awesomediff.variable objects: return sum([abs(v.val) for v in vals]) except: return sum([abs(v) for v in vals])
def invert_scores(input_ranking): """ Function that given a ranking list, it corrects its relevance in preparation for dcg. For example, [1,1,2,3] --> [3,3,2,1] [1,2] --> [2,1] [1] --> [1] :param input_ranking ordered list with the ranking """ max_value = max(input_ranking) relevance...
def validate_hex(hex_string): """ Make sure a string can be hex decoded Args: hex_string (str): A string of hex characters to check Returns: boolean: True or False depending on if the string can be hex decoded >>> validate_hex('af') True >>> validate_hex('zh') False ...
def crunch_window_path(path): """ Returns the input window name void of all periods and exclamation points. """ return path.replace("!", "").replace(".", "")
def containment_distance(a, b): """ A case-insensitive distance measure on strings. Returns: - 0 if strings are identical - positive infinity if neither string contains the other - 1 / (minimum string length) if one string contains the other. Good for Organizations. I.e. "cis...
def main_image(images): """Get main or first image from all offer images. :param images: list Offer images """ main_img = [str(i) for i in images if i.is_main] if main_img: return str(main_img[0]) if not main_img and images: return images[0] return ''
def count_increases(lst): """Return a count of the number of times a number in the list is greater than the preceding number.""" return len([ y for (x,y) in zip(lst, lst[1:]) if y > x])
def merge_dicts(dict_to_merge, merged_dict): """Recursively merge the contents of dict_to_merge into merged_dict. Values that are already present in merged_dict will be overwritten if they are also present in dict_to_merge""" for key, value in dict_to_merge.items(): if isinstance(merged_dict.get(key...
def wrap_h(msg): """wraps text in a header tag for good desploy""" return "<h1>{}</h1>".format(msg)
def format_bytes(bytes, si = True): """ Formats bytes into a string """ if si: kilo = 1000. else: # Officially, a kibibyte kilo = 1024. if bytes >= (kilo * kilo * kilo): return "%.1f GB" % (bytes / (kilo * kilo * kilo)) elif bytes >= 1000000: return "...
def quantize_float(f, q): """Converts a float to closest non-zero int divisible by q.""" return int(round(f / q) * q)
def toggle_graphs(n_clicks, value): """ show graphs after first submission """ if n_clicks: return {'display': 'block'} else: return {'display': 'none'}
def bieos2ot(tag_sequence): """ transform BIEOS tag sequence to OT tag sequence :param tag_sequence: input tag sequence :return: """ new_sequence = [] for t in tag_sequence: assert t == 'B' or t == 'I' or t == 'E' or t == 'O' or t == 'S' if t == 'O': new_sequence....
def parse_header_format(description): """Get the format from a vcf header line description If format begins with white space it will be stripped Args: description(str): Description from a vcf header line Return: format(str): The format information from description """ ...
def extension(path): """Get the file extension of the last part of a path. A file extension is any part after the last dot inclusively. @param path: The path to split. @type path: string @return: The extension part of the path. @rtype: string """ end = path.rfind("\\") end = max(path.rfind("/"...
def test_a_rich(seq, a_region_size, a_ratio): """ Testing the number of As found in just downstream of the PAS. seq target sequence found downstream of the PAS a_region_size number of bases to look at from the PAS a_ratio A content >= to this ratio will be consider...