content
stringlengths
42
6.51k
def float_range(start, end, step=1., exceed=False): """Like range() but for floats""" l = [] i = start if exceed: more = step else: more = 0. while i < end + more: l.append(i) i += step return l
def msg_encode(t:float, v:tuple): """encode t, v, into str. Args: t: time stamp in millisecond v: a list of float Returns: str: encoded string """ return ("{'t':%.6f,'v':[" % float(t) + ','.join(map(str, v)) + "]}").encode('UTF-8')
def get_boolean_options_from_json(conf_json, ncn, ncrt, tst, frc, quiet): """Parse config json for boolean options and return them sequentially. It takes prioritised values as params. Among these values, non-None/True values are preserved and their values in config json are ignored.""" opt = {'NoChain':...
def niceSub(val): """auxiliary function to have a nice inequation plot""" if val > 0: return "-" + str(val) elif val <0: return "+" + str(-val)
def t_ana(i, j, dz, dx, zsa, xsa, vzero): """Calculate analytical times in homogeneous model.""" return vzero * ((dz * (i - zsa)) ** 2.0 + (dx * (j - xsa)) ** 2.0) ** 0.5
def interpolate_X( data, x ) : """For internal use only.""" l = len( data ) if( l < 1 ) : return( 0. ) y = 0. if( data[0][0] <= x <= data[-1][0] ) : i = 0 while( i < l ) : if( x <= data[i][0] ) : break i += 1 if( x == data[i][0] ) : y = da...
def isfib(number): """ Check if a number is in the Fibonacci sequence. :type number: integer :param number: Number to check """ num1 = 1 num2 = 1 while True: if num2 < number: tempnum = num2 num2 += num1 num1 = tempnum elif num2 == nu...
def quartile(arr, val): """ Return the quartile (0-3) of val in arr. """ sorted_array = sorted(arr) interval_length = len(sorted_array) / 4.0 return int(sorted_array.index(val) / interval_length)
def get_assessment_detail(assessments): """ Iterate over assessments details from response and retrieve details from assessments. :param assessments: list of assessments from response :return: list of detailed elements of assessments :rtype: list """ return [{ 'ID': assessment.get('...
def _as_tuple(x): """Return a tuple from the input.""" if isinstance(x, tuple): return x return (x,)
def public_config(config): """Create a public version of the configuration data. This simply minimizes boilerplate for having to filter out private items. """ return {key: value for key, value in config.items() if not key.startswith("_")}
def format_address(*, ip_address, port, protocol): """Format address""" port = f':{port}' if port else '' return f'{protocol}://{ip_address}{port}'
def is_weakly_lesser_type(a: type, b: type) -> bool: """ Compares two types, a and b, returning True if a is weakly "less" than b. The comparison is determined by the following type ordering: bool, int, float, complex. """ ordered_types = ( bool, int, float, complex,...
def bytes2ipv4(ipv4: bytes): """Convert a bytes (a sequence of bits) to IPv4 address""" return ".".join(str(b) for b in ipv4)
def can_sub(kwargs): """Determines if the counter in kwargs allows for another sub.""" try: return not kwargs["counter"].done() except KeyError: return True
def ticker_price_for_dest_amount(side: str, start_amount: float, dest_amount: float): """ :return: price for order to convert start_amount to dest_amount considering order's side """ if dest_amount == 0 or start_amount == 0: raise ValueError("Zero start ot dest amount") if side is None: ...
def r_find_last_common(CL0_r, DoneSet0, CL1_r, DoneSet1): """CL0_r, CL1_r -- reversed versions of the command lists CL1 and CL0. i: 0 1 2 3 4 5 6 7 8 k: 0 1 2 3 4 5 6 .-.-.-.-.-.-.-.-.-. .-.-.-.-.-.-.-. |g|B|i|j|k|l|A|m|o| |a|b|c|B|A|e...
def lines(s): """ Split a string in lines using the following conventions: - a line ending \r\n or \n is a separator and yields a new list element - empty lines or lines with only white spaces are not returned. - returned lines are stripped. Because of these constraints "".split() cannot be use...
def vector_product(a, b): """Returns the dot product of two vectors""" return a["X"]*b["X"] + a["Y"]*b["Y"] + a["Z"]*b["Z"]
def find_nodes_by_attr(subtree, attr, value): """ Returns list of nodes in `subtree` that have attribute `attr` equal to `value`. """ results = [] if subtree[attr] == value: results.append(subtree) if 'children' in subtree: for child in subtree['children']: child_rest...
def chandrupatla( t: float, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float, ) -> float: """ Estimates the root using Chandrupatla's method. Apply inverse quadratic interpolation whenever the interpolation is monotonic over the ...
def _escape_split(sep, argstr): """ Allows for escaping of the separator: e.g. task:arg='foo\, bar' It should be noted that the way bash et. al. do command line parsing, those single quotes are required. """ escaped_sep = r'\%s' % sep if escaped_sep not in argstr: return argstr.spl...
def div(value, arg): """ Divides the value; argument is the divisor. Returns empty string on any error. """ try: value = int(value) arg = int(arg) if arg: return value / arg except: pass return ''
def func1(a,b): """This is use to minus number""" c = (a-b) return c
def coLuminosity(Ico, nu_rest, DL, z): """ Calculate the line luminosity of CO, based on Equation (3) of Solomon & Vanden Bout (2005). Parameters ---------- Ico : array like The integrated line flux, units: Jy km/s. nu_rest : float The rest-frame frequency. DL : float ...
def hex(n: int) -> str: """render the given number using upper case hex, like: 0x123ABC""" if n < 0: return "-0x%X" % (-n) else: return "0x%X" % n
def mergesort(input_list): """ Takes in a list and splits it into halves recursively, then compares parts of the list to each other and merges them sorted into another list """ output = [] if len(input_list) > 1: mid = len(input_list) // 2 first_half = input_list[:mid] second...
def sanitize_locations(locations): """ The location maybe vectors etc, need a serializable nice format. """ res = {} for frame, location in enumerate(locations): res[frame] = [location[0], location[1], location[2]] return res
def _remove_capsule_name(capsule_name, fullname): """Remove "capsule_name" from capsule_name.some_module.some_module2 Since the files in the zip file won't have "capsule_name" in the paths """ parts = fullname.split(".") return ".".join(parts[1:])
def latest(scores): """Return last score.""" return scores[-1]
def text_remove_empty_lines(text): """ Whitespace normalization: - Strip empty lines - Strip trailing whitespace """ lines = [ line.rstrip() for line in text.splitlines() if line.strip() ] return "\n".join(lines)
def ExtendPhycheIndex(original_index, extend_index): """Extend {phyche:[value, ... ]}""" if extend_index is None or len(extend_index) == 0: return original_index for key in list(original_index.keys()): original_index[key].extend(extend_index[key]) return original_index
def check_text(text: str, words: tuple) -> bool: """ Determines if one of the 'words' in the input tuple is found in the 'text' string. Returns True if so. @param text: The string to be checked @param words: A tuple holding words to be searched for @return: True if one of the 'words' is found i...
def _contains_fallback(iterable, item): """Fallback to determine whether the iterable contains the value specified. Uses a loop instead of built-in methods. :param iterable: Iterable sequence. :param item: The value to find. :returns: ``True`` if the iterable sequence contains the value; `...
def equal(a, b, eps=0.001): """ Check if a and b are approximately equal with a margin of eps """ return a == b or (abs(a - b) <= eps)
def _word_feats_string(strn): """ NLTK word feature generator for the NaiveBayesClassifier that takes a string """ return dict([(word, True) for word in strn.split(" ")])
def parse_pairs(pairs): """Parse lines like X=5,Y=56, and returns a dict.""" # ENST00000002501=0.1028238844578573,ENST00000006053=0.16846186988367085, # the last elem is always "" data = {x.split("=")[0]: x.split("=")[1] for x in pairs.split(",")[:-1]} return data
def lower_dict_keys(origin_dict): """ convert keys in dict to lower case Args: origin_dict (dict): mapping data structure Returns: dict: mapping with all keys lowered. Examples: >>> origin_dict = { "Name": "", "Request": "", "URL": "", ...
def realm_scope(realm_role): """ :return scope of policy for client role """ return {"realm_roles": [{"name": realm_role()}]}
def _simplify_doc(doc): """ Limit a document to just the three fields we should upload. """ # Mutate a copy of the document to fill in missing fields doc = dict(doc) if 'text' not in doc: raise ValueError("The document {!r} has no text field".format(doc)) return { 'text': doc...
def all_images_unique(all_images): """Check if all the images generated are unique Args: all_images (JSON object): List of all images with each element as JSON object Returns: bool: true or false """ seen = list() return not any(i in seen or seen.append(i) for i in all_images)
def list_getlast(items): """ :param items: :return: """ return items[len(items)-1]
def unique(seq): """preserves the order (unlike list(set(seq)))""" seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def get_new_lastmod(timestr): """Return a new lastmod string given a time as a string.""" return "lastmod: " + timestr + "\n"
def BuildFileName(url): """Construct the file name from a given URL. Args: url: the given URL Returns: filename: the constructed file name """ filename = url.strip('\r\n\t \\/') filename = filename.replace('http://', '') filename = filename.replace(':', '_') filename = filename.replace('/', '_...
def get_chunk_type(tok, idx_to_tag): # copy from guillaumegenthial / sequence_tagging """ Args: tok: id of token, ex 4 idx_to_tag: dictionary {4: "B-PER", ...} Returns: tuple: "B", "PER" """ tag_name = idx_to_tag[tok] tag_class = tag_name.split('-')[0] tag_type = ...
def list_equal(list1, list2): """Compares two given lists. If one item in the two lists is different, the function returns false. If all items ate equal, returns True. """ for i, item in enumerate(list1): if item != list2[i]: return False return True
def _noop(val, *args, **kwargs): """ Parser does nothing. """ # It means nothing but can suppress 'Unused argument' pylint warns. # (val, args, kwargs)[0] return val
def remove_letter(letter, string): """Removes all occurrences of a given letter from a string.""" string_without_letter = string.replace(letter, '') return string_without_letter
def is_autogenerated(example, scan_width=5): """Check if file is autogenerated by looking for keywords in the first few lines of the file.""" keywords = ["auto-generated", "autogenerated", "automatically generated"] lines = example["content"].splitlines() for _, line in zip(range(scan_width), lines): ...
def star_formation_rate(z, z_inhom=0.): """Returns the star formation rate, per comoving volume, evaluated at the specified redshift. Ref: A.M. Hopkins and J.F. Beacom, Astrophys. J. 651, 142 (2006) [astro-ph/060146] P. Baerwald, S. Huemmer, and W. Winter, Astropart. Phys. 35, 508 (2012) [1107....
def parse_size(s): """ Parses a size specification. Valid specifications are: 123: bytes 123k: kilobytes 123m: megabytes 123g: gigabytes """ if not s: return None mult = None if s[-1].lower() == "k": mult = 1024**1 elif s[-...
def reverseVowelsA(s): """ :type s: str :rtype: str """ vowels=[string for string in s if string.lower() in"aeiou"] lst=set(vowels) result="" index=len(vowels)-1 for i in s: if i not in lst: result+=i else: result+=vowels[index] index-=1 return result
def _create_database_sql_new(database_name): """Return a tuple of statements to create the database with the given name. :param database_name: Database name :type: str :rtype: tuple """ tmpl = "create database {} with owner = dcc_owner template = template0 " \ "encoding = 'UTF8' lc_co...
def dict_to_dict_strs(d): """ Parses a dict to a list of key:value strings. Used to go from Python->HTTP. """ return ["{0}:{1}".format(k,v) for k,v in d.items()]
def _proc_lines(in_str): """ Decode `in_string` to str, split lines, strip whitespace Remove any empty lines. Parameters ---------- in_str : bytes Input bytes for splitting, stripping Returns ------- out_lines : list List of line ``str`` where each line has been stripp...
def email2words(email): """Return a slightly obfuscated version of the email address. Replaces @ with ' at ', and . with ' dot '. """ return email.replace('@', ' at ').replace('.', ' dot ')
def strip_key(k): """Sanitize variant identifiers. This is necessary because variants with the same chrom, pos and alleles hash to the same value. """ if k.startswith("uk_"): return k[3:] return k
def check_ecl(s: str) -> bool: """ >>> check_ecl("blu") True >>> check_ecl("blk") False """ return s in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
def dict_to_prop(d): """convert dictionary to multi-line properties""" if len(d) == 0: return "" return "\n".join("{0}={1}".format(k, v) for k, v in d.items())
def Yes_No(value, collection): """ True -> "Yes", green background ; False->"No",red, None to "-",no color """ if value: return ("Yes", "black; background-color:green;") if value == None: return ("-", "black") return ("No", "black; background-color:red;")
def percentage(part, whole): """ Compute a percentage. :param part: The part. :type part: float :param whole: The whole. :type whole: float :return: The computed percentage. """ return 100 * float(part) / float(whole)
def parse_area_coords(full_string: str) -> tuple: """Given a line describing an area of a matrix, return all the coordinates within that area and the square id. Ex: #1 @ 258,327: 19x22 -> #1, [(258, 327), (259, 327), ..., (276, 327), ..., (276, 348)]""" square_id, _, left_top, area = full_strin...
def c_to_f(t_c): """Convert from Celsius to Fahrenheit.""" if t_c is None: return None return 1.8 * t_c + 32.0
def cmp(a, b): """ Equivalent of python 2 cmp function for python 3 """ return (a > b) - (a < b)
def homology(t1, t2): """ :param t1: The value to be compared with t2. :param t2: Another value to be compared with t1. :return result: The bigger value will be return. """ if t1 > t2: return t1 else: return t2
def s_suffix(num): """Simplify pluralization.""" if num > 1: return 's' return ''
def style_to_dict(style): """Parses an HTML tag style attribute. :param style: """ if isinstance(style, dict): return style d = {} styles = style.split(';') for s in styles: # noinspection PyBroadException try: key, value = s.split(':') d[key....
def _flatten_field(playField): """ Flattens the playfield array :param playField: 2d array :return: 1d array """ field_array = [] for row in playField: for item in row: field_array.append(item) return field_array
def len2bytes(v1, v2): """Return the packet body length when represented on 2 bytes""" return ((v1 - 192) << 8) + v2 + 192
def is_annotable_type(obj): """ check whether given object can be decorated """ return callable(obj) or isinstance(obj, (classmethod, staticmethod))
def cross(A, B): """Calculate cross product of two vectors. Parameters ---------- A, B : list of float Vectors to be multiplied. Returns ------- float Cross product of `A` and `B`. """ return [ A[1] * B[2] - A[2] * B[1], A[2] * B[0] - A[0] * B[2], ...
def _get_iterator(to_iter, progress): """ Create an iterator. Args: to_iter (:py:attr:`array_like`): The list or array to iterate. progress (:py:attr:`bool`): Show progress bar. Returns: :py:attr:`range` or :py:class:`tqdm.std.tqdm`: Iterator object. """ iterator = rang...
def to_boolean(value): """ Convert a value from a GET or POST request parameter to a bool """ if isinstance(value, bytes): value = value.decode('ascii', errors='replace') if isinstance(value, str): return value.lower() == 'true' else: return bool(value)
def cast_cap_words_to_lower(string: str) -> str: """ Cast cap word format to lower case with underscores >>> cast_cap_words_to_lower("ClassName") 'class_name' >>> cast_cap_words_to_lower("AnotherOne") 'another_one' :param string: any str :return: str in lower case w...
def summation_i_squared(n): """summation_i_squared: calculate the squared Args: n: stopping condition """ if not isinstance(n, int) or n <= 0: return None elif n == 1: return n return sum(map(lambda i: i ** 2, range(1, n + 1)))
def get_meterological_equation_case_cdd(t_min, t_max, t_base): """Calculatease number to calculate cdd with Meteorological Office equations as outlined in Day (2006): Degree-days: theory and application Arguments --------- t_min : float Minimum daily temperature t_max : float Ma...
def prob1(limit=1000): """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ a = 0 for i in range(1, limit): if i % 3 == 0 or i % 5 == 0: ...
def decodeNet(net): """ Decode a net's string. i.e. "abc~20~" => "abc[20]" Args: net (string): encoded net string Returns: string: decoded net string """ nsplit = net.split("~") if len(nsplit) > 1: ret = ''.join([nsplit[0], "[", nsplit[1], "]"]) else: ret =...
def gt_het(g): """ Return True if genotype call is heterozygous. Parameters ---------- g : str Genotype call. Returns ------- bool True if genotype call is heterozygous. Examples -------- >>> from fuc import pyvcf >>> pyvcf.gt_het('0/1') True >...
def generate_archiveit_urits(cid, seed_uris): """This function generates TimeMap URIs (URI-Ts) for a list of `seed_uris` from an Archive-It colleciton specified by `cid`. """ urit_list = [] for urir in seed_uris: urit = "http://wayback.archive-it.org/{}/timemap/link/{}".format( ...
def _check_minmax_arg(arg): """Checks that arg is an integer or a flat collection of integers.""" if not isinstance(arg, (tuple, list)): if not isinstance(arg, int): raise ValueError return [arg] else: for a in arg: if not isinstance(a, int): r...
def is_valid_line(line): """Filters lines that contains an empty returns tag.""" return '/// <returns></returns>' not in line
def _final_is_class_declaration(line): """Checks whether the line containing `final` modifier is a class declaration. Returns `False` for the lines containing no `final` modifier. Args: line: the line to check. Returns: bool: `True` if the line is class declaration, `False` otherwise....
def build_lemma_dict(entry_dict_list): """build dictionary mapping (lemma,pos) to (form,feats)""" lemma_dict={} for entry in entry_dict_list: key=(entry["lemma"],entry["pos"]) value=(entry["form"],entry["feats"]) if lemma_dict.get(key): lemma_dict[key].append(value) ...
def search_matrix(matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ # Locate row first. n = len(matrix) if n == 0: return False l = 0 while n > 0: step = n // 2 i = l + step if not matrix[i]: return ...
def get_dxy(nchr_pop1, nchr_pop2, allele1_pop1, allele1_pop2): """ Calculates dxy between two populations. """ p1 = allele1_pop1/nchr_pop1 p2 = allele1_pop2/nchr_pop2 dxy = round(p1*(1-p2) + p2*(1-p1), 4) return dxy
def get(identifier): """ Returns an activation function from a string. Returns its input if it is callable (already an activation for example). Args: identifier (str or Callable or None): the activation identifier. Returns: :class:`nn.Module` or None """ if identifier is None: ...
def coordDiff(xf, xi, tf, ti): """ Calculate changes in distance (dx) and time (dt) final(x, t) - initial(x, t) """ dx = xf - xi dt = tf - ti return dx, dt
def sort_and_filter(claims, number=0, reverse=False): """Sort the input list and remove duplicated items with same claim ID. Parameters ---------- claims: list of dict List of claims obtained from `claim_search`. number: int, optional It defaults to 0, in which case the returned lis...
def fix_entities(text): """Reconstruct important entities""" if "clinton" in text: return "hillary clinton" elif "donald" in text: return "donald trump" elif "hillary" in text: return "hillary clinton" elif "trump" in text: return "donald trump" else: retu...
def editFilePrefix(oldPrefix, newPrefix, fileList): """Changes the file names of a list of files. Could be used on any list fo strings.""" splitIndx = len(oldPrefix) newList = [] for fileName in fileList: nameBit = fileName[splitIndx:] newName = newPrefix + nameBit newList.append...
def to_dict(func_data): """ convert (ret_type, 'name', par_str, call_str, sig_str, call_list, sig_list) tuple to dict with corresponding keys """ return dict(zip(('ret_type', 'name', 'par_str', 'call_str', 'sig_str', 'call_list', 'sig_list'), func_data))
def write_nested_dict_to_file(data, outputfilename, orient='second'): """ Args: data = nested dictionary (2D) { "FACOAE120": { "C00001": -1.0, "C00010": 1.0, "C01832": -1.0, "C02679": 1.0 } } orient = 1. first: write th...
def findNT(line, varNum): """Takes a line from a GATK file, and the varient number, and returns the nucleotide that corresponds to that variant ID""" # nts is a list where 0 is the reference, and then each postion after that # is the postion of the variable nts = [] nts.append(line.split('\t'...
def extract_labels(js): """Extracts list of labels from a JSON object representing a paper. Args: js (dict): JSON object representing a paper in the PeTaL golden dataset. Returns: List(str): all of its labels concatenated into a single list """ if 'label' in js: return js[...
def standardize_mhc(mhc): """ Standardize the name of mhc """ mhc = mhc.replace('*', '') return mhc
def dictify(s): """ Very very dirty minimal YAML parser is OK for testing. """ return dict(zip(s.split()[0::2], s.split()[1::2]))
def double_eights(n): """Return true if n has two eights in a row. >>> double_eights(8) False >>> double_eights(88) True >>> double_eights(2882) True >>> double_eights(880088) True >>> double_eights(12345) False >>> double_eights(80808080) False """ "*** YOUR ...
def reveal_letter(real_word, current_word, letter): """" reveal_letter-game""" k = 0 for i in real_word: if i == letter: current_word[k] = letter k += 1 return current_word