content
stringlengths
42
6.51k
def getCoverage(contigHeader): """ Gets the coverage given a contigHeader. """ return float(contigHeader.split(' ')[-1].split('_')[1])
def convert_to_dtype(data, dtype): """ A utility function converting xarray, pandas, or NumPy data to a given dtype. Parameters ---------- data: xarray.Dataset, xarray.DataArray, pandas.Series, pandas.DataFrame, or numpy.ndarray dtype: str or numpy.dtype A string deno...
def is_binary_file(filename): """Return true if a file contains binary (non-text) characters.""" text_chars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F}) try: with open(filename, "rb") as fp: return bool(fp.read(1024).translate(None, text_chars)) except (I...
def base_file_name(long_path): """Reduce file path to base file name without extension""" return long_path.split('/')[-1].split('.')[0]
def dict_max_value(d): """ Return the (key, value) with the maximum value. This is the fastest way of doing this: http://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary """ k = list(d.keys()) v = list(d.values()) max_v = max(v) return (k[v.index(max_v...
def strip(s): """ Remove leading and trailing characters from string """ return s.strip()
def denorm_sin2_cos2(norm_sin2_cos2): """ Undo normalization step of `encode_2theta_np()` This converts values from the range (0, 1) to (-1, 1) by subtracting 0.5 and multiplying by 2.0. This function does not take any steps to ensure the input obeys the law: sin ** 2 ...
def make_data_dict_for_donut_chart(data_labels_list): """Make a data_dictionary to pass through into chart.js donut chart""" data_dict = { "labels": data_labels_list[1][0:5], #getting top 5 place types, so slicing from 0 - 5 "datasets": [ { "data": da...
def get_playlist_video_url(playlist_id): """Compile the user videos url.""" return f'https://www.pornhub.com/playlist/{playlist_id}'
def KK_RC25(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (...
def find_keyword(URL, title, keywords): """ find keyword helper function of history_list """ for keyword in keywords: # case insensitive if len(keyword) > 0 and (URL is not None and keyword.lower() in URL.lower()) or (title is not None and keyword.lower() in title.lower()): return T...
def handle(req): """handle a request to the function Args: req (str): request body """ ret_str = 'Hello OpenFaas. I received the following text:\n' return ret_str + req
def gt_miss(g): """ Return True if sample genotype is missing. Parameters ---------- g : str Sample genotype. Returns ------- bool True if sample genotype is missing. Examples -------- >>> from fuc import pyvcf >>> pyvcf.gt_miss('0') False >>> ...
def list_and_add(a, b): """ Concatenate anything into a list. Args: a: the first thing b: the second thing Returns: list. All the things in a list. """ if not isinstance(b, list): b = [b] if not isinstance(a, list): a = [a] return a + b
def power(b: int, e: int) -> int: """Returns the base value to the power of the exponent as an integer. Example: (5, 3) returns 125 = 5^3. Args: b: The base value. e: The exponent value. """ result = 1 while e > 0: if e & 0x1: result *= b e >>= 1 b *= b return result
def get_item_or_none(request, value, itype=None, frame='object'): """ Return the view of an item with given frame. Can specify different types of `value` for item lookup Args: request: the current Request value (str): String item identifier or a dict containing @id/uuid itype (s...
def s2m(seconds: float) -> float: """Convert seconds to minutes.""" return round(seconds / 60, 1)
def multiply_2d(a, b): """ Multiply two matrices (a*b) using zip functions. Matrices must have dimensions that allow multiplication (ie. M x N and N x L). :param a: (list) 2D matrix :param b: (list) 2D matrix :return: (list) 2D matrix containing the result of a*b """ # check if giv...
def criba_eratostenes(n): """Criba Eratostenes""" l=[] multiplos = set() for i in range(2, n+1): if i not in multiplos: l.append(i) multiplos.update(range(i*i, n+1, i)) return l
def get_child_id(service_name): """Get id of the child from service name""" service = service_name.split("_") id = service[-1] return id
def prefix_metricsdict(metricsdict, prefix): """ Add a prefix to the names in the metrics dict. If the prefix and old name should be separated by an underscore or hyphen, that must be included in the prefix! :param dict: :return: """ ret = {} for k, v in metricsdict.items(): ret[...
def check_new_states(new_states): """ check if the recoded new states in consecutive order new_states is a list of new states in the map file. """ sort_list = [int(x) for x in sorted(new_states)] return max(sort_list) == len(set(sort_list))
def format_size(size): """ Format into byes, KB, MB & GB """ power = 2**10 i = 0 power_labels = {0: 'bytes', 1: 'KB', 2: 'MB', 3: 'GB'} while size > power: size /= power i += 1 return f"{round(size, 2)} {power_labels[i]}"
def is_even(number): """ tests whether the number is even """ return number % 2 == 0
def fizz_buzzable(num): """ We're only interested in valid fizz buzz numbers. """ return num % 3 == 0 or num % 5 == 0
def _get_readable_id(id_name): """simplified an id to be more friendly for us people""" pos = id_name.rfind('/') if pos != -1: return id_name[pos+1:] else: return id_name
def is_predicate(logic, start, end): """Returns T/F depending on if logic string is predicate and index of predicate operator (<=)""" equals_ind = logic.index("=") if equals_ind>end or equals_ind<start: return True, equals_ind return False, -1
def max_version(candidates): """Allows to ensure we don't downgrade""" highest_name = None highest = None for name, version in candidates: if highest is None or (version and version > highest): highest_name = name highest = version return highest_name, highest
def get_default_arrow(scale=1): """Get the default arrow """ return { 'cylinder_radius': scale*0.05, 'cylinder_height': scale*0.75, 'cone_radius': scale*0.125, 'cone_height': scale*0.25 }
def _left_rotate(n, b): """Left rotate a 32-bit integer n by b bits.""" return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF
def irm_penalty_scheduler(step, n_anneal_steps=100, base_penalty_weight=10000.): """ Schedule the IRM penalty weight using a step function as done by https://github.com/facebookresearch/InvariantRiskMinimization If the penalty weight is 0. (IRM disabled), just return 0. """ if base_penalty_weigh...
def signif(x, digits=6): """Round a numeric to the specified number of significant digits. Examples: signif(12345000, 3) == 12300000 signif(1.2345, 3) == 1.23 signif(0.0012345, 3) == 0.00123 """ from math import log10, floor ## Using the conventions of the round function, the first ...
def get_first(somelist, function): """ Returns the first item of somelist for which function(item) is True """ for item in somelist: if function(item): return item return None
def sequence(arcs): """sequence: make a list of cities to visit, from set of arcs""" succ = {} for (i, j) in arcs: succ[i] = j curr = 1 # first node being visited sol = [curr] for i in range(len(arcs) - 1): curr = succ[curr] sol.append(curr) return sol
def dict2args(data): """Convert a dictionary of options to command like arguments. Note: This implementation supports arguments with multiple values. """ result = [] for k, v in data.items(): if v is not False: prefix = "-" if len(k) == 1 else "--" flag = f"{prefix}{...
def tag(*tags): """Select a (list of) tag(s).""" vtag = [t for t in tags] return {"tag": vtag}
def row_formatter(row, qualifier='"'): """ Format a row in a consistent way """ output_row = [] for item in row: if item is None: item = '""' else: item = qualifier + str(item) + qualifier output_row.append(item) return output_row
def get_num_cols(sheet): """ Get the number of columns in an Excel sheet. """ # Internal representation? if (hasattr(sheet, "num_cols")): return sheet.num_cols() # xlrd sheet? if (hasattr(sheet, "ncols")): return sheet.ncols # Unhandled sheet object. return 0
def clean_output(text): """ This takes the text-generated output of the model and cleans it up for printing purposes @param text: The text-generated output of the model @return: The cleaned up text-generated output """ punctuations = ['!', '.', '?', ']'] text_split = text.split(':') for...
def optlist_to_dict(optlist, opt_sep=',', kv_sep='=', strip_quotes=False): """Parse an option list into a dictionary. Takes a list of options separated by ``opt_sep`` and places them into a dictionary with the default value of ``True``. If ``kv_sep`` option is specified then key/value options ``key=va...
def getIpv4(addr): """ Get IPv4 address via parameter addr """ return '.'.join(map(str, addr))
def byte_to_button(val): """ Convert button byte to list of values """ btn = [] for x in range(8): valid = (val >> x) & 0x01 if valid > 0: btn.append(True) else: btn.append(False) return btn
def boltFinder(bolt): """ """ # _bolt = str(bolt).lower() _bolt = _bolt.replace('bolt','') _bolt = _bolt.replace('type','') _bolt = _bolt.replace(' ','') _bolt = _bolt.strip() # #_M1_6 = ['m1.6', 'm1,6'] #_M2 = ['m2'] #_M2_5 = ['m2.5', 'm2,5'] _M3 = ['m3'] _M4 ...
def is_number(n): """Check if something is a number (int, float or complex)""" return any(isinstance(n, tp) for tp in [int, float, complex])
def explode_dep_versions2(s): """ Take an RDEPENDS style string of format: "DEPEND1 (optional version) DEPEND2 (optional version) ..." and return a dictionary of dependencies and versions. """ r = {} l = s.replace(",", "").split() lastdep = None lastcmp = "" lastver = "" incm...
def brent( t: float, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float, ) -> float: """ Estimates the root using Brent's method. If it can, inverse quadratic interpolation is used. Otherwise, secant interpolation is used. If ...
def choices_from_dict(source, prepend_blank=True): """ Convert a dict to a format that's compatible with WTForm's choices. It also optionally prepends a "Please select one..." value. Example: # Convert this data structure: STATUS = OrderedDict([ ('unread', 'Unread'), ('o...
def host_get_id(host): """ Retrieve the host id """ return host['id']
def imap_any(conditions): """ Generate an IMAP query expression that will match any of the expressions in `conditions`. In IMAP, both operands used by the OR operator appear after the OR, and chaining ORs can create very verbose, hard to parse queries e.g. "OR OR OR X-GM-THRID 111 X-GM-THRID 22...
def ends_overlap(left, right): """Returns whether the left ends with one of the non-empty prefixes of the right""" for i in range(1, min(len(left), len(right)) + 1): if left.endswith(right[:i]): return True return False
def getMostStrictType(typeA: str, typeB: str) -> str: """Return the most 'strict' type of license from the available types. Args: typeA (str): type of the first license typeB (str): type of the second license Returns: str: the most 'strict' type """ strict = ["Public Domain", "Permissive", "Weak Copyleft",...
def phone_format(n): """ Formats a phone number. See https://stackoverflow.com/a/7058216 """ return format(int(n[:-1]), ",").replace(",", "-") + n[-1]
def is_prime(n): """Returns True if n is prime.""" # ASCII are expected to be encoded in one byte. a Lookup table is faster and cheaper return n in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]
def performance_measure(confusion_matrix): """Return [accuracy, precision, recall, f1 score] based on given confusion matrix Args: confusion_matrix (2d array): given based on the following format: [[true positive, false negative], [false positive, true negative]] """ t...
def count_cond(condition, n): """ >>> def divisible(n, i): ... return n % i == 0 >>> count_cond(divisible, 2) # 1, 2 2 >>> count_cond(divisible, 4) # 1, 2, 4 3 >>> count_cond(divisible, 12) # 1, 2, 3, 4, 6, 12 6 >>> def is_prime(n, i): ... return count_cond(divisible...
def cstrencode(pystr): """ encode a string into bytes. If already bytes, do nothing. """ try: return pystr.encode("utf-8") except UnicodeDecodeError: return pystr.decode("utf-8").encode("utf-8") except AttributeError: return pystr
def mechanismHub_fee_percent(params, substep, state_history, prev_state, policy_input): """ This mechanism returns the updated fee percent. """ return 'fee_percent', policy_input['fee_percent']
def get_names(entities): """Get the names of the entities.""" return entities.keys()
def cmp(x, y): """ Replacement for built-in Python 2 function cmp that was removed in Python 3 From https://docs.python.org/2/library/functions.html?highlight=cmp#cmp : Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zer...
def ktoe_to_gwh(ktoe): """Conversion of ktoe to gwh. As ECUK input ktoe per year are provided, which are converted into GWh per year. Arguments ---------- ktoe : float Energy demand in ktoe Returns ------- gwh : float Energy demand in GWh Notes ----- ht...
def div(dividend, divisor): """ Takes two ints and returns a tuple (quotient, remainder) """ quotient = 0 while dividend - divisor >= 0: dividend -= divisor quotient += 1 return (quotient, dividend)
def _get_operator_name(spec): """ Gives operator name from YAML short hand naming format """ components = spec.split("_") name = "".join(x[:1].upper() + x[1:] for x in components) if spec.endswith("dataset"): return name return name + "Operator"
def unicode_to_bytes(s, encoding='utf-8', errors='replace'): """ Helper to convert unicode strings to bytes for data that needs to be written to on output stream (i.e. terminal) For Python 3 this should be called str_to_bytes :param str s: string to encode :param str encoding: utf-8 by default ...
def dict_of_lists_to_list_of_dicts(dic, num): """Function to convert a dict of lists to a list of dicts. Mainly used to prepare actions to be fed into the ``env.step(action)``. ``env.step`` assumes action to be in the form of a list the same length as the number of workers. It will assign the first acti...
def default_value(type): """ Returns the value to initialize a message member with. 0 for integer types, 0.0 for floating point, false for bool, empty string for everything else @param type: The type @type type: str """ if type in ['byte', 'int8', 'int16', 'int32', 'int64', ...
def var_name_clean(line_in): """ Removes #, $ and PVM_ from line_in, where line in is a string from a Bruker parameter list file. :param line_in: input string :return: output string cleaned from #, $ and PVM_ """ line_out = line_in.replace('#', '').replace('$', '').replace('PVM_', '').strip() ...
def _format_generic_task_id(prefix, padding, tasknum): # type: (str, bool, int) -> str """Format a generic task id from a task number :param str prefix: prefix :param int padding: zfill task number :param int tasknum: task number :rtype: str :return: generic task id """ return '{}{}'...
def pos253(i): """ return key positions in N253 (1..10) from Meier's Table 2: 0 = map center, the reference position of N253 1..10 = reference positions in the table """ pos = [ ['00h47m33.100s', '-25d17m17.50s' ], # map reference ['00h47m33.041s', '-25d17m26.61s' ], # p...
def join(first, *paths): """ Joins the given VSI path specifiers. Similar to :func:`os.path.join` but takes care of the VSI-specific handles such as `vsicurl`, `vsizip`, etc. """ parts = first.split('/') for path in paths: new = path.split('/') if path.startswith('/vsi'): ...
def question_input (user_decision=None): """Obtains input from user on whether they want to scan barcodes or not. Parameters ---------- user_decision: default is None, if passed in, will not ask user for input. string type. Returns ------- True if user input was 'yes' False is...
def parse(tokens, object): """ does the parse of the scanned/tokenized JSON string @param tokens list of JSON tokens @param object final dictionary or one 'node' in the tree while parsing """ name = None array = None while len(tokens) > 0: token = tokens.pop() if token ...
def test_input(line): """ :param line: (str) the input for finding words in dic :return: (bool) make sure the input corresponds to the format """ if 6 >= len(line) or len(line) > 9: return False for j in range(0, len(line), 2): if not line[j].isalpha() or len(line[j]) != 1: return False for k in range(1, ...
def fitPolynominal(percent): """Correct result basing on Immunoratio polynominal. """ a = 0.00006442 b = -0.001984 c = 0.611 d = 0.4321 return a * percent ** 3 + b * percent ** 2 + c * percent + d
def primes1(n): # WAYYYY FASTER """ Returns a list of primes < n """ sieve = [True] * (n//2) for i in range(3,int(n**0.5)+1,2): if sieve[i//2]: sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1) return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]]
def randbytes(length: int) -> bytes: """ Generate a random bytes object. :param length: Length of the random bytes object. :return: Random bytes object. """ import random return bytes(random.getrandbits(8) for _ in range(length))
def odd_elements(array): """ """ odd = set() for item in array: if item in odd: odd.remove(item) else: odd.add(item) return odd
def query_to_json(query, name): """This query is useful to fetch a complex join with some aggregations as a single blob, and later, just hydrate it without having to iterate over the resultset .. Example: SELECT u.id::varchar, to_jsonb(array_agg(scopes)) as scopes, ...
def _PrepareFinalizeExportDisks(_, snap_disks): """Encodes disks for finalizing export. """ flat_disks = [] for disk in snap_disks: if isinstance(disk, bool): flat_disks.append(disk) else: flat_disks.append(disk.ToDict()) return flat_disks
def has_triple_string_quotes(string_contents: str) -> bool: """Tells whether string token is written as inside triple quotes.""" if string_contents.startswith('"""') and string_contents.endswith('"""'): return True elif string_contents.startswith("'''") and string_contents.endswith("'''"): r...
def _conv2d3d_strides_or_dilations(name, value, data_format, default_value=1): """Compute strides or dilation values for 2D and 3D convolutions.""" if value is None: value = default_value if not isinstance(value, (int, list)): raise ValueError("{} must be an int or list".format(name)) #...
def star_wars(x, y, elem, neighbours): """Star Wars preset of the Generations family. (345/2/4)""" red_count = 0 for neighbour in neighbours: if neighbour == 3: red_count += 1 if elem == 3: # The cell is alive if red_count in [3,4,5]: return 3 else: ...
def check_int(x): """check_int checks if input 'x' is decimal integer. It returns value as an int type. """ if isinstance(x, int): return x if not x.isdecimal(): raise RuntimeError("{} is not a decimal number".format(x)) return int(x)
def hasannotation(string_list): """ Judge whether the string type parameter string_list contains annotation """ for c in string_list: if c == "#": return True return False
def list_ints(number): """ Makes a list from number down to 0. If number = 2, returned: [2,1,0]""" return list(range(number, -1, -1))
def isFalse (b) : """return True if b is equal to False, return False otherwise >>> isFalse(False) True >>> isFalse(True) False >>> isFalse("hello world") False """ # this is very similar to isTrue if b is False or b == False : # base case: b equals to False => return Fa...
def append_zero(number): """function to append zero to number""" if number < 10: new_str = "0" +str(number) return new_str else: return number
def factorization_shape_to_kernel_shape(factorization, factorization_shape): """Returns a convolutional kernel shape rom a factorized tensor shape """ if factorization.lower() == 'tt': kernel_shape = list(factorization_shape) out_channel = kernel_shape.pop(-1) kernel_shape = [out_cha...
def get_padded_composition(stoichiometry, elements): """ Return a list that contains how many of each species in elements exists in the given stoichiometry. e.g. for [['Li', 2], ['O', 1]] with elements ['O', 'Li', 'Ba'], this function will return [1, 2, 0]. Parameters: stoichiometry (list): mat...
def clean_line(line): """Remove comments and parentheses from the input line.""" # strip comments: comment_begin = line.find('#') line = line[:comment_begin] # remove parentheses: line = line.replace('[', '').replace(']', '') line = line.replace('(', '').replace(')', '') return line
def fix_unicode(unicrap): """This takes a UNICODE string and replaces Latin-1 characters with something equivalent in 7-bit ASCII. It returns a plain ASCII string. This function makes a best effort to convert Latin-1 characters into ASCII equivalents. It does not just strip out the Latin-1 c...
def relate_files_ts(files1_ts, files2_ts): """Relate two sets of timestep-sorted file names with each other.""" files2_file1 = {} for tss1, file1 in files1_ts.items(): files2_file1[file1] = [ file2 for tss2, file2 in files2_ts.items() if any(ts1 in tss2 for ts1 in...
def retrieve_train_test_instances(cases, train_indices, test_indices): """ Retrieves training and test cases from indices for hpo. Parameters ---------- cases : list of dicts, where single dict represents a case Cases of the training set of the event log. train_indices : list of...
def summary_table(params, proteins): """ Returns a string representing a simple summary table of protein classifcations. """ out = "" counts = {} for seqid in proteins: category = proteins[seqid]['category'] if category not in counts: counts[category] = 1 ...
def frames2beats(n_frames, framerate, tempo): """Converts a number of frames to duration in beats, given a framerate and tempo.""" return (n_frames / float(framerate)) * (tempo / 60.)
def getNumGamesWithRN(rn: int) -> str: """Return a query to get the count of games with a given Ryu Number. The resulting query takes the form: `(COUNT(*): int)` """ return (f"SELECT COUNT(*) FROM game " f"WHERE ryu_number={rn};" )
def convert_percentage_string_to_float(percentage_string): """Converts a string of the form 'xx.xx%' to its equivalent decimal value. :param percentage_string: A string in percentage form to be converted. :returns: A floating-point number rounded to 4 decimal places (2 decimals in percentage form). """...
def get_strand_color(is_rev): """ Get color for forward and reverse reads :param is_rev: True if read is reversed :return: """ if is_rev == 240.0: return 1 else: return 0
def tidy_filesize(size: int) -> str: """ Convert upload size to human readable form. Decision to use powers of 10 rather than powers of 2 to stay compatible with Jinja filesizeformat filter with binary=false setting that we are using in file_upload template. Parameter: size in bytes Return...
def crown_capture_probability(n, k): """ Calculate the probability that a sample of `k` taxa from a clade of `n` total taxa includes a root node, under a Yule process. This equation is taken from: Sanderson, M. J. 1996. How many taxa must be sampled to identify the root node of a large clade? ...
def pitch_size(pitch): """Compute the size of a pitch. Arguments: pitch {[triple]} -- a triple (pitchname,accidental,tie) """ size = 0 # add for the pitchname size += 1 # add for the accidental if not pitch[1] == "None": size += 1 # add for the tie if pitch[2]: ...