content
stringlengths
42
6.51k
def convert_ft_to_cm(ft_len): """Function to convert length in ft to cm""" cm_len = ft_len * 30.48 return cm_len
def bytes_format_converter(in_bytes: bytes)->list: """Assumes in_bytes to be in bytes format. Returns in hexadecimal format.""" count = 0 in_hex = [] values = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] bytes_list = list(in_bytes.hex()) for i in bytes_list: if count in values: ...
def _find_value(dictionary, key, default=None): """ Helper to find a value in a dictionary """ if key not in dictionary: return default return dictionary[key]
def find_bin(value, bins): """ Finds which value belongs to which bin. """ for i in range(0, len(bins)): if bins[i][0] <= value < bins[i][1]: return i return -1
def to_lower(text: str) -> str: """ Convert text to lower case. """ return text.lower()
def hydraulic_losses_suct_reflux(dzeta_enter_reflux, dzeta_turn90_reflux, n_turn90_reflux, dzeta_ventil_reflux, n_ventil_reflux, g, w_liq_real_enter_reflux): """ Calculates the hydraulic losses of suction line. Parameters ---------- dzeta_enter_reflux : float The local resistance of tube ent...
def write_addin(addin_file_path, addin_template, rvt_version): """ Writes the required *.addin to run RPS inside rvt to the journal folder :param addin_file_path: addin output path. :param addin_template: addin template to be used as base. :param rvt_version: rvt version to open the model with. ...
def program_code_store_cwd_json(path: str) -> str: """ Creates program code that stores its working directory as JSON into the specified `path`. """ return f""" import os with open("{path}", "w") as f: f.write(os.getcwd()) """
def is_dict(obj): """ Check if the object is a dict. """ return type(obj) == type({})
def decrypt_letter(letter, key_stream_value): """(str, int) -> str Precondition: the first parameter(letter) input should be a single uppercase letter and the second parameter input should be a number. the function just need to work for the 26 character English alphabet. Return the result decrypt...
def check_not_null(val): """A helper to implement the Soy Function checkNotNull. Args: val: The value to test. Returns: val if it was not None. Raises: RuntimeError: If val is None. """ if val is None: raise RuntimeError('Unexpected null value') return val
def SizeAsString(size): """Converts megabyte float to a string.""" if size < 1000.0: return "%0.2fMB" % size else: return "%0.2fGB" % (size / 1024.0)
def printexp_v2(btree): """Retrieve the hold math formula string from bTree (better version)""" s = '' if btree: leftC = btree.getLeftChild() righC = btree.getRightChild() if leftC and righC: s += '(' + printexp_v2(leftC) s += str(btree.getRoot()) ...
def get_public_attributes(cls, as_list=True): """ Return class attributes that are neither private nor magic. :param cls: class :param as_list: [True] set to False to return generator :return: only public attributes of class """ attrs = (a for a in dir(cls) if not a.startswith('_')) if ...
def dBm2W(dBm): """ Function to convert from dBm to W """ return 10**((dBm)/10.) / 1000
def size_of_spectrum_vector(number_of_freq_estimations): """size of dirty vector""" return 2*number_of_freq_estimations + 1
def gc_frac(guide_seq): """Compute fraction of guide that is GC. Args: guide_seq: string of guide sequence; must be all uppercase Returns: fraction of guide sequence that is G or C """ gc = guide_seq.count('G') + guide_seq.count('C') return float(gc) / len(guide_seq)
def recursive_sort(obj): """ Recursively sort lists/dictionaries for consistent comparison. """ if isinstance(obj, dict): return sorted((k, recursive_sort(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(recursive_sort(x) for x in obj) else: return ob...
def rest_recursive_dict(d): """ recursively serializes a jira-rest dictionary in to a pure python dictionary. """ out = {} for k, v in d.items(): if v.__class__.__name__ == 'PropertyHolder': out[k] = v.__dict__ else: out[k] = v return out
def loop_nums(min=5): """ Range filter for numerical loops. """ return range(1, min + 1)
def conf(state, with_defaults=False, **kwargs): """ This overrides the default `conf` inspect command to effectively disable it. This is to stop sensitive configuration information appearing in e.g. Flower. (Celery makes an attempt to remove sensitive information, but it is not foolproof.) """ ...
def sail_area(foot, height, roach_adj=1/.9): """ Generalized sail area with optional roach_adj factor. For main and mizzen sails, roach_adj is generally 1/.9. For jib sails, roach_adj is 1.0. >>> sail_area(15, 45) 375.0 >>> main_sail_area(15, 45) 375.0 >>> sail_area(12, 40, roach_ad...
def next(some_list, current_index): """ Returns the next element of the list using the current index if it exists. Otherwise returns an empty string. """ try: return some_list[int(current_index) + 1] # access the next element except: return ''
def parse_event_time(event_time): """Parse event time, or return default time""" strtime = str(event_time) strtime = strtime if strtime[11:] else strtime[:10] + '17:00:00-08:00' return strtime[:10] + 'T' + strtime[11:]
def _ul_subvoxel_overlap(xs, x1, x2): """For an interval [x1, x2], return the index of the upper limit of the overlapping subvoxels whose borders are defined by the elements of xs.""" xmax = max(x1, x2) if xmax >= xs[-1]: return len(xs) - 1 elif xmax <= xs[0]: ul = 0 return u...
def is_machine_readable_copyright(text): """ Return True if a text is for a machine-readable copyright format. """ return text and text[:100].lower().startswith(( 'format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0', 'format: http://www.debian.org/doc/packaging-man...
def uint64_to_hex(integer): """Returns the hex representation of an int treated as a 64-bit unsigned int. The result is padded by zeros if necessary to fill a 16 character string. Useful for converting keyspace ids integers. Example: uint64_to_hex(1) == "0000000000000001" uint64_to_hex(0xDEADBEAF) == "000...
def isiterable(obj): """Return True if ``obj`` is not str, and is iterable """ return hasattr(obj, '__iter__') and not isinstance(obj, str)
def normalize(text): """ Returns lowercased text with no spaces. """ return text.lower().replace(" ", "")
def remove_qs(url): """Remove URL query string the lazy way""" return url.split('?')[0]
def slices(series, length): """ return the 'set' of length n 'substrings' The tests cases require a list of lists of integers. """ result = [] if len(series) < length or length < 1: raise ValueError while len(series) >= length: result.append([int(x) for x in list(series[:l...
def parse_delimited_list(name, value, default): """ Parses a comma separated string into a list Argumments: value (str or list[str]): the value as a string or list of strings Returns: list[str]: the parsed value """ parsed_value = value if isinstance...
def to_molar_ratio(massfrac_numerator, massfrac_denominator, numerator_mass, denominator_mass): """ Converts per-mass concentrations to molar elemental ratios. Be careful with units. Parameters ---------- numerator_mass, denominator_mass : float or array-like The atomic mass of...
def get_field_id(node): """Returns field id of node as string""" return str(node["field_id"])
def get_options(num): """Convert bitmasked int options into a dict.""" return { 'require_id': bool(num & 1), 'register_id': bool(num & (1 << 1)), }
def accum(astr): """Return a each letter of case with n number of same letters. input = string, letters either a - z or A - Z output = string, one uppercase letter followed by lower case ones, and a dash ex: 'abcd' should return 'A-Bb-Ccc-Dddd' ex: 'RqaEzty' should return 'R-Qq-Aaa-Eeee-Zzz...
def _merge_duplicate_rows(rows, metrics, key): """ Given a list of query rows, merge all duplicate rows as determined by the key function into a single row with the sum of the stats of all duplicates. This is motivated by database integrations such as postgres that can report many instances of a query t...
def encode(data): """ Encodes a byte-array for use in midi sysex (msb of each byte must be 0, 8th byte encodes msbs of 7 preceding bytes) """ if isinstance(data, str): data = data.encode('utf8') ret = [] cnt = 0 msbs = 0 for d in data: # Most significant bit msb =...
def get_matches(lf, candidate_set, match_values=[1, -1]): """Return a list of candidates that are matched by a particular LF. A simple helper function to see how many matches (non-zero by default) an LF gets. Returns the matched candidates, which can then be directly put into the Viewer. :param lf: Th...
def make_ArrayOfData(param, factory): """Generates ArrayOfData if input is a dictionary for list of dictionaries""" if isinstance(param, dict): return factory.ArrayOfData([{'field': field, 'value': value} for field, value in param.items()]) elif isinstance(param, list): data = [[{'field': fi...
def swap(a, b, *s): # ( a b -- b a ) """ SWAPs the top of the stack with the second most top element :param a: :param b: :param s: :return: >>> swap(1, 2, 3) (2, 1, 3) """ return (b, a) + s
def normalized_image_to_normalized_device_coordinates(image): """Map image value from [0, 1] -> [-1, 1]. """ return (image * 2.0) - 1.0
def numViolations(playerEventList): """How many violations has a player committed since they have been tracked? """ return sum(1 for ce in playerEventList if ce.violation)
def h0_age( tau, distance, Izz ): """calculates the spin-down based upper limit, h0_age, from the supernova remnant's age, distance and estimated moment of inertia""" return 1.2e-24 * ( 3.4 / distance ) * pow( ( 300.0 / tau ) * ( Izz / 1.0e38) , 0.5)
def overlap(str1, str2): """ Finds the maximum overlap between strings STR1 and STR2. """ len1 = len(str1) len2 = len(str2) maxPossible = min(len(str1), len(str2)) for maxOver in range(maxPossible, 0, -1): if str1[:maxOver] == str2[len2 - maxOver:]: return maxOver, str2, str1 elif str2[:maxOver] == str1[l...
def _remove_trailing_nan(linelist): """Private function to clean project_value_list. Removes trailing nan's which are empty sub-project cells. As an example, input ["nan", 1, 2, "nan", "nan"] will return ["nan", 1, 2]. """ clean = linelist # Looping through reversed list to get trailing values ...
def ConstructAnnotatorURL(build_id): """Return the build annotator URL for this run. Args: build_id: CIDB id for the master build. Returns: The fully formed URL. """ _link = ('https://chromiumos-build-annotator.googleplex.com/' 'build_annotations/edit_annotations/master-paladin/%(build_id...
def cycle_check_undirected(graph, node=0, source_node=None, visited_nodes=None): """Returns true iff an undirected graph represented by an adjacency list has a cycle """ if visited_nodes is None: visited_nodes = set() if node in visited_nodes: return True # Found a cycle # Visit...
def remove_dollar(form_str): """Remove the dollar sign from a string and return a float""" return float(form_str.replace('$', ''))
def IsNamedTuple(component): """Return true if the component is a namedtuple. Unfortunately, Python offers no native way to check for a namedtuple type. Instead, we need to use a simple hack which should suffice for our case. namedtuples are internally implemented as tuples, therefore we need to: ...
def clean_name(name): """Ensures that names are composed of [a-zA-Z0-9] FIXME: only a few characters are currently replaced. This function has been updated only on case-by-case basis """ replace_map = { "=": "", ",": "_", ")": "", "(": "", ":": "_", ...
def _make_dlist(dall, rep=1): """make a list of strings representing the scans to average Parameters ---------- dall : list of all good scans rep : int, repetition Returns ------- dlist : list of lists of int """ dlist = [[] for d in range(rep)] for idx in range(rep): ...
def equate_prefix(name1, name2): """ Evaluates whether names match, or one name prefixes another """ if len(name1) == 0 or len(name2) == 0: return False return name1.startswith(name2) or name2.startswith(name1)
def rotate(cur_dir, val): # 0 -> turn left(counterclockwise), 1 -> turn right(clockwise) """returns rotated direction (left or right) based on val being 0 or 1""" if val == 0: return -cur_dir[1], cur_dir[0] elif val == 1: return cur_dir[1], -cur_dir[0]
def most_common_list_value(values): """Select the most common value from a list. Parameters ---------- values : List[T] Input list. Returns ------- T Most common value. """ occurrences = dict() for value in values: occurrences.setdefault(value, 0) ...
def lerp(channel1, channel2, current_step, total_steps): """ :lerp: linear interpolation function for traversing a gradient :param channel1: int | the rgb channel for the starting color in the gradient. :param channel2: int | the rgb channel for the ending color in the gradient. :param curr...
def equal_coords(a, b) -> bool: """ Checks if coords are equal""" return a[0] == b[0] and a[1]==b[1]
def _get_equality(analysis_1: dict, analysis_2: dict) -> dict: """Compares the two input dictionaries and generates a new dictionary, representing the equality between the two. Args: analysis_1(dict): Eg: {'rs10144418': ['T', 'C'], 'rs1037256': ['G', 'A'],... } analysis_2(dict): Eg: {'rs101...
def make_url_given_id(expid): """ Get url of JSON file for an experiment, give it's ID number :param expid: int with experiment ID number """ return "https://neuroinformatics.nl/HBP/allen-connectivity-viewer/json/streamlines_{}.json.gz".format(expid)
def isbit(integer, nth_bit): """Tests if nth bit (0,1,2..) is on for the input number. Args: integer (int): A number. nth_bit (int): Investigated bit. Returns: bool: True if set, otherwise False. Raises: ValueError: negative bit as input. Examples: >>> isb...
def dumpPacket(buffer): """ Name: dumpPacket(buffer) Args: byte array Desc: Returns hex value of all bytes in the buffer """ return repr([ hex(x) for x in buffer ])
def bool_type_next_after(x, direction, itemsize): """Return the next representable neighbor of x in the appropriate direction.""" assert direction in [-1, +1] # x is guaranteed to be either a boolean if direction < 0: return False else: return True
def geometric_series_recur(n, r): """Geometric series by recursion. Time complexity: O(n). Space complexity: O(n) """ # Base case. if n == 0: return 1 return pow(r, n) + geometric_series_recur(n - 1, r)
def create_nodes_dict (part): """ assign a dictionary to store the features of inidividual nodes """ data_dict = {} for node, block in enumerate(part): data_dict[node] = block return data_dict
def rrx(a, b, carry): """Rotate right with extend (Use carry as a 33rd bit) Returns (result, carry) """ b &= 31 a = (a & 0xffffffff) | ((carry & 1) << 32) a = (a >> b) | (a << (33 - b)) return (a & 0xffffffff, 1 & (a >> 32))
def get_overlap(gt_box: list, pr_box: list) -> float: """Intersection score between GT and prediction boxes. Arguments: gt_box {list} -- [x, y, w, h] of ground-truth lesion pr_box {list} -- [x, y, w, h] of prediction bounding box Returns: intersection {float} """ gt_x, gt_y...
def _guarded_name(method_name): # type: (str) -> str """Return name for guarded CRUD method. >>> _guarded_name('read') 'guarded_read' """ return 'guarded_' + method_name
def precision_recall_f(total_positives, attempted, correct, beta=1): """Returns the precision, recall, and f1-score given with this number of total positives, attempted, and correct items.""" precision = correct / attempted recall = correct / total_positives f_measure = (1 + beta * beta) * precision...
def parse_keywords(query): """ Parses the string for keywords. Returns a set of keywords, which contains no duplicates. """ return set(query.lower().split())
def get_lon_lat_from_tile_name(tile_name): """Returns _lon_lat""" parts = tile_name.split('_') lon_lat = f'_{parts[-2]}_{parts[-1].split(".tif")[0]}' return lon_lat
def asset_path(s): """Remove leading '//'""" return s[2:] if s[:2] == '//' else s
def get_number_of_proteins(feature_list): """Input a list of features and outputs the number of proteins present in the feature vector """ protein_names = [ "prot1", "prot2", "prot3", "prot4", "prot5", "prot6", "prot7", "prot6",...
def compareduce(f, *lst): """ A reduce modified to work for `f :: a -> b -> Bool` functions If `f` ever evaluates to False, return False, else return True This is mandatory because functools.reduce doesn't store previous values for each pair in the computation chain """ if len(lst) <= 1: ...
def first_non_space(s,i): """ :param s: string :param i: index :return: A pair of (the first character start from s[i] that is not a space, its index) """ l = len(s) while i < l and (s[i] == ' ' or s[i] == '\n'): i += 1 if i < l: return (s[i],i) else: return ...
def toAsn1IntBytes(b): """Return a bytearray containing ASN.1 integer based on input bytearray. An ASN.1 integer is a big-endian sequence of bytes, with excess zero bytes at the beginning removed. However, if the high bit of the first byte would be set, a zero byte is prepended. Note that the AS...
def tribonacci(n: int) -> int: """Calculate the Nth Tribonacci number.""" f0: int = 0 f1: int = 0 f2: int = 1 for _ in range(n): f0, f1, f2 = f1, f2, f0 + f1 + f2 return f0
def get_domain_from_fqdn(fqdn): """ Returns domain name from a fully-qualified domain name (removes left-most period-delimited value) """ if "." in fqdn: split = fqdn.split(".") del split[0] return ".".join(split) else: return None
def filter_set(s, where): """Returns a set.""" return set(filter(where, s))
def make_less_simple_string(m, n): """ What comes in: -- a positive integer m -- a positive integer n that is >= m What goes out: The same as the previous problem, but WITHOUT the hyphen after the LAST number. That is, this function returns the STRING whose characters are m,...
def normalize_language_explanation(chunk): """ i) X [aaa] ii) L [aaa] = "X" iii) X = L [aaa] :return: X [aaa] """ if '[' in chunk and not chunk.endswith(']'): chunk += ']' chunk = chunk.strip() if '=' not in chunk: return chunk chunks = chunk.split('=') left ...
def sec_to_exposure_decimation(sec): """ Convert seconds to exposure and decimation. The algorithm is limited since it multiplies decimation by 10 until the resulting exposure is less than 65_535. This is not perfect because it limits decimation to 10_000 (the next step would be 100_000 which is ...
def nopat(operating_income, tax_rate): """ nopat = Net Operating Profit After Tax """ return operating_income * (1-(tax_rate/100))
def str_complex(c, kindstr=''): """Converts the complex number `c` to a string in Fortran-format, i.e. (Re c, Im c). If c is iterable, it returns a string of the form [(Re c_1, Im c_1), ...]. :param c: Number/Iterable to print :param kindstr: Additional kind qualifier to append (default None) :...
def ERROR(obj): """Format an object into string of error color (red) in console. Args: obj: the object to be formatted. Returns: None """ return '\x1b[1;31m' + str(obj) + '\x1b[0m'
def validate_float_value(float_value_input, greater_than=None, less_than=None): """ The purpose of this function is to validate that a float value is valid. The value, its range (either greater than or less than a number) may also be tested. This function will bark if the valu...
def parse_msg(msg, block=False): """Create an array of fields for slack from the msg type :param msg: A string, list, or dict to massage for sending to slack """ if type(msg) is str: if block: return [{"value": f"```{msg}```"}] return [{"value": msg}] elif type(msg) is l...
def thread(data, *forms): """ Similar to pipe, but accept extra arguments to each function in the pipeline. Arguments are passed as tuples and the value is passed as the first argument. Examples: >>> sk.thread(20, (op.div, 2), (op.mul, 4), (op.add, 2)) 42.0 See Also: ...
def transition_processes_to_rates(process_list): """ Define the transition processes between compartments, including birth and deaths processes. Parameters ========== process_list : :obj:`list` of :obj:`tuple` A list of tuples that contains transitions rates in the following format: ...
def binary_search(data, target, low, high): """Return position if target is found in indicated portion of a python list and -1 if target is not found. """ if low > high: return -1 mid = (low + high) // 2 if target == data[mid]: return mid elif target < data[mid]: # recur...
def offset_type(length): # type: (int) -> str """ Compute an appropriate Rust integer type to use for offsets into a table of the given length. """ if length <= 0x10000: return 'u16' else: assert length <= 0x100000000, "Table too big" return 'u32'
def gather_pages(pdfs: list) -> list: """ Creates a list of pages from a list of PDFs. Args: pdfs (list): List of PDFs to collate. Returns: list: List of pages from all passed PDFs. """ output = [] for pdf in pdfs: for page in pdf.pages: output.append(pa...
def find_Gstart(seq, min_g_len=3): """ For Brendan's UMI design 5' NEB --- (NNNNHHHH) --- GGG(G) --- transcript --- (A)n --- 3' NEB the sequence should already have NEB primers removed. detect the beginning and end of G's and return it """ len_seq = len(seq) i = seq.find('G'*min_g_len) ...
def validate_project(project): """Ensures the given project is valid for Cloud Pub/Sub.""" # Technically, there are more restrictions for project names than we check # here, but the API will reject anything that doesn't match. We only check / # in case the user is trying to manipulate the topic into posting som...
def unquote(value): """Remove wrapping quotes from a string. :param value: A string that might be wrapped in double quotes, such as a HTTP cookie value. :returns: Beginning and ending quotes removed and escaped quotes (``\"``) unescaped """ if len(value) > 1 and valu...
def convert_pretrained(name, args): """ Special operations need to be made due to name inconsistance, etc Parameters: --------- args : dict loaded arguments Returns: --------- processed arguments as dict """ if name == 'vgg16_reduced': args['conv6_bias'] = args....
def fibonacci_by_index(index: int): """ Get the value at the index of the Fibonacci series. Austin W. Milne @awbmilne <austin.milne@uwaterloo.ca> Parameters ---------- index: number The index of the Fibonacci series to return. Returns ------- The value from the Fibonacci ...
def _zero_function(x): """Constant function 0. This is used in the expression system to indicate the zero function, such that we know, e.g., that derivatives vanish too. """ # pylint: disable=unused-argument return 0
def level_dataset(lv): """Get dataset key part for level. Parameters ---------- lv : `int` Level. Returns ------- `str` Dataset key part. """ return '_lv%d' % lv
def is_valid_input(letter_guessed): """ this function checks if the string is valid (one character in English) :param letter_guessed: string of characters :type letter_guessed: str :return: is the letter guessed valid or not :rtype: bool """ is_valid = False if len(letter_g...
def valid_passwords_2(passwords): """ Takes a list of password strings, and returns the number of passwords in the list meeting the following criteria: - Passwords are six digit numbers - In each password two adjacent digits must be the same - The two adjacent digits...