content
stringlengths
42
6.51k
def _is_special(name): """Return True if method name is special, False otherwise.""" return name.startswith('__') and name.endswith('__')
def to_string(state, nbqbits): """ Converts a state into a string. Args: state: Int representing the quantum state written in decimal nbqbits: Number of qubits of the quantum state Returns: String of the quantum state in binary form """ state_str = bin(state)[2:] st...
def get_population_dict(organism_list, species_names): """ Constructs population dict from organism list data structure. """ population_dict = { species: { 'statistics': { 'total': 0, 'alive': 0, 'dead': 0 }, 'or...
def is_valid_zip(ext): """ Checks if file is ZIP """ formats = ['zip'] return ext in formats
def get_next_address(previous_address: int, both_addresses_xored: int) -> int: """ Returns the next address given the previous address and the xor of previous and next addresses :param previous_address: The address of the previous node :param both_addresses_xored: The XOR of the previous and the next node :retur...
def relabel_sets(setOfSets): """ Relabels sets of sets so that they consist of elements made from a continuous sequence of integers, starting from 0. >>> write_sets(relabel_sets(read_sets('{{1,4},{1,3}}'))) '{{0,2},{0,1}}' >>> write_sets(relabel_sets(read_sets('{{a,b},{a,c}}'))) '{{0,2},{0,1}}...
def filterCmpList(cmpListR, rankCut, maxDist, taxonomy, outputInverse = False): """ Filters out all placements that are mismatches and all placements to the higher ranks that are lower than certain rank (e.g. bacteria or the root) and all placements that are more distant from the reference p...
def binarysearch(minim,maxim,function, flips_to_true=True): """ function needs to return a boolean whether the solution is ok this implementation is for function that starts with false for minim and flip to true for TTTTFFFF, pass set flips_to_true flag to false. This flag is important to set correc...
def add_vectors(v1, v2): """ Adds 2 vector :param v1: vector 1 :param v2: vector 2 :return: v1 + v2 """ return tuple([v1[i] + v2[i] for i in range(0, len(v1))])
def guess_track_type(adapter_type): """ Returns the possible track type to use given an adapter type. :param str adapter_type: the type of the adapter :return: the type of the track to use for the given an adapter type :rtype: str """ known = { "BamAdapter": "AlignmentsTrack", ...
def factorial(n: int) -> int: """Iterative implementation of factorial algorithm. factorial(0) = 1 factorial(1) = 1 :param n: positive integer """ result = 1 for i in range(2, n + 1): result *= i return result
def strip_nondigits(string): """ Return a string containing only the digits of the input string. """ return ''.join([c for c in string if c.isdigit()])
def apply_heat_recovery( enduse, heat_recovered, service, service_techs, curr_yr ): """Reduce heating demand according to assumption on heat reuse Arguments ---------- enduse : str Enduse strategy_vars : dict Strategy variables service...
def get_path_atoms(atom_1, atom_2, paths_dict, pointer_dict, max_path_length, truncate=True, self_attn=False): """Given a pair of atom indices, returns the list of atoms on the path. Args: atom_1: The start atom on the path. atom_2: The end atom on the path. paths_dict...
def extract_pattern(obj): """Extract pattern from str or re.compile object Returns: str: Extracted pattern """ if obj is not None: return getattr(obj, 'pattern', obj) return obj
def mention_as_text(mention): """Represents the given mention structure as simple textual summary. Args: mention (dict): Response containing information about medical concept. Returns: str: Formatted name of the reported medical concept, e.g. +Dizziness, -Headache. """ ...
def jaccardDistance(a, b): """ Returns the percentage of elements in set `a` or `b` that are not in both `a` and `b`. Args --- `a : set` The first set `b : set` The second set Returns --- `jDistance : float` The percent of elements not in both `a` and `b` """ a = set(a) b =...
def distance_xy(point1, point2): """ This function takes 4 arguments representing 2 points in cartesian coordinates and returns the Euclidean distance between the points: d(point1, point2) = sqrt((point1_x - point2_x)^2 + (point1_y - point2_y)^2) : param point1 : pair of values representing hori...
def trim(s, chars=None): """ To remove other characters when used as a filter for form fields, you can use `functools.partial`. Example: from functools import partial StringField(filters=[partial(trim, chars='/')]) """ return s.strip(chars) if isinstance(s, str) else None
def build_spark_command(config): """Build a configuration based command line to run something in spark Puts together a command line for submitting spark jobs to the cluster. Injects spark_conf and spark_args from the profile for the specified command into the command line. Parameters ---------...
def xsplit(txt, seps): """ Split a string in `txt` by list of delimiters in `seps` @param txt: string to split @param seps: list of separators @return: list of split units """ default_sep = seps[0] for sep in seps[1:]: # we skip seps[0] because that's the default separator txt = ...
def sort_list_of_dicts(list_, dict_key): """Sort list of dicts by dict key :param list list_: List of dicts, :param string dict_key: Dict key for sorting. :rtype: list """ # NOTE: Python 3 introduced new rules for ordering comparisons: # See detailed here (chapter ordering-comparisons) ...
def calculate_word_translation_accuracy(translation, truth_dict, topk): """ get topk accuarcy params: translation: truth_dict: topk: use topk translation example: translation = {1:[3, 2, 4]} truth_dict = {1:[2, 5]} topk = 2 -> calculate_word_translatio...
def _full_qualified_name(obj): """ Gets the full qualified name of an object """ klass = obj.__class__ module = klass.__module__ if module == 'builtins': return klass.__qualname__ # avoid outputs like 'builtins.str' return f'{module}.{klass.__qualname__}'
def parse_int_list(string): """ Parses a string of numbers and ranges into a list of integers. Ranges are separated by dashes and inclusive of both the start and end number. Example: parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13] """ integers = [] for comma_part in string.split...
def tle_fmt_int(num, digits=5): """ Return an integer right-aligned string with DIGITS of precision, all blank if num=0 Ignores sign. """ if num: num = abs(num) else: return " "*digits string_int = "{:>{DIGITS}d}".format(num,DIGITS=digits) return string_int
def nng_timeout(value): """Convert a timeout in seconds to an NNG timeout.""" return -1 if value is None else int(float(value) * 1000.0)
def kmerize(seq, ksize): """Return the set of unique k-mers from the sequence""" return set(seq[i : i + ksize] for i in range(len(seq) - ksize + 1))
def hexescape(char): """Escape char as RFC 2396 specifies""" hex_repr = hex(ord(char))[2:].upper() if len(hex_repr) == 1: hex_repr = '0%s' % hex_repr return '%' + hex_repr
def parse_request(request): """Parse incoming request into its components for evaluation.""" request_split = request.split() method = request_split[0] uri = request_split[1] protocol = request_split[2] headers = request_split[3:] if method != "GET": raise TypeError("Specified method...
def axis(name=None, cols=None, values=None, units=None): """Convenience function for generating axis descriptions when defining MetaArrays Example:: MetaArray([...], info=[ axis('Time', values=[0.0, 0.1, 0.2, 0.3], units='s'), axis('Signal', cols=[('V0', 'V', 'Voltage0'), ('V1', 'V', 'Voltage1'), ...
def ccs_ultralight(optlevel, chunksize, slicesize): """Correct the slicesize and the chunksize based on optlevel.""" if optlevel in (0, 1, 2): slicesize //= 2 slicesize += optlevel * slicesize elif optlevel in (3, 4, 5): slicesize *= optlevel - 1 elif optlevel in (6, 7, 8): ...
def canon_pairwise_tag(tag: str) -> str: """ Canonicalize pairwise tag to specify unencrypted storage. :param tag: input tag :return: tag prefixed with '~' if not already """ return '{}{}'.format('' if str(tag).startswith('~') else '~', tag)
def trial_division(n, bound=None): """ Return the smallest prime divisor <= bound of the positive integer n, or n if there is no such prime. If the optional argument bound is omitted, then bound=n. Input: n -- a positive integer bound - (optional) a positive integer Output: ...
def OrderedSet(alist): """ Creates an ordered set of type list from a list of tuples or other hashable items """ oset = [] for item in alist: if item not in oset: oset.append(item) return oset
def gray(n): """ Calculate n-bit gray code """ g = [0, 1] for i in range(1, int(n)): mg = g + g[::-1] # mirror the current code # first bit 0/2**u for mirror first = [0] * 2 ** (i) + [2 ** (i)] * 2 ** (i) g = [mg[j] + first[j] for j in range(2 ** (i + 1))] retur...
def alphabet_index(text: str) -> str: """Replaces each letter with its appropriate position in the alphabet.""" return " ".join([str(ord(x.lower())-96) for x in text if ord(x.lower())-96 >= 1 and ord(x.lower())-96 < 27])
def plus_activation(x): """ Not useful - just a check. """ return abs(x + 1)
def rpad(string, length, char=' '): """ >>> rpad('foo', 6) 'foo ' >>> rpad('foo', 2) 'foo' >>> rpad('foo', 6, '#') 'foo###' """ if len(string) < length: string += char * (length - len(string)) return string
def multiply(a, b): """Multiply two numbers and return the product""" product = round(a*b, 4) print("The product of " + str(a) + " and " + str(b) + " is " + str(product) + ".") return str(a) + " * " + str(b) + " = " + str(product)
def obs_to_dict(obs): """ Convert an observation into a dict. """ if isinstance(obs, dict): return obs return {None: obs}
def get_node(data_path): """ Return Blender node on a given Blender data path. """ if data_path is None: return None index = data_path.find("[\"") if (index == -1): return None node_name = data_path[(index + 2):] index = node_name.find("\"") if (index == -1): ...
def fibonacci_to(n): """Fibonacci function. Args: n (int): The index of the number on the Fibonacci series to return. Returns: int: The n number in the Fibonacci series. """ a, b = 0, 1 for _ in range(n): a, b = b, a + b return a
def add_undef_techs(heat_pumps, specified_tech_enduse, enduses): """Add technology to dict Arguments ---------- heat_pumps : list List with heat pumps specified_tech_enduse_by : dict Technologey per enduse enduses : list Enduses Return ------- specified_tech...
def soma(a, b): """ :param a: :param b: :return: """ s = a + b return s
def mod_to_num(mods:str): """It works.""" mods = mods.upper() total = 0 if 'NF' in mods: total += 1<<0 if 'EZ' in mods: total += 1<<1 if 'HD' in mods: total += 1<<3 if 'HR' in mods: total += 1<<4 if 'SD' in mods: total += 1<<5 if 'DT' in mods: total += 1<...
def countBits(num): """ :type num: int :rtype: List[int] """ ret=[None] * (num + 1) n=1 for i in range(0, num + 1): if i == 0: ret[i] = 0 elif i == n: ret[i] = 1 n = n * 2 else: ret[i] = ret[n / 2] + ret[i ...
def remap_line_numbers(cell_lines): """Create a mapping from script line number to notebook cell/line.""" line_map = {} cell_start = 0 for cell, cell_length in enumerate(cell_lines, 1): for line in range(1, cell_length + 1): line_map[cell_start + line] = cell, line cell_start...
def get_pack_installation_request_data(pack_id: str, pack_version: str): """ Returns the installation request data of a given pack and its version. The request must have the ID and Version. :param pack_id: Id of the pack to add. :param pack_version: Version of the pack to add. :return: The request ...
def get_ID (ID): """ input: "name, family, age, birth place" output: ["setayesh", "pasandideh", 13, "tehran"] """ ID = ID.split() ID[2] = int(ID[2]) return ID
def get_name(parameters): """ Generate a model name from its parameters. """ l = [] for k, v in parameters.items(): if type(v) is str and "/" in v: l.append((k, v[::-1][:v[::-1].index('/')][::-1])) else: l.append((k, v)) name = ",".join(["%s=%s" % (k, str(...
def is_package_info_doc(document_name): """Checks if the name of a document represents a package-info.java file.""" return document_name == "package-info"
def get_train_test_ind(paths): """ Select from the list of all files the train and test files :param paths: all files :return: list of train and list of test data """ list_train = [] list_test = [] for i, str_path in enumerate(paths): str_sequence = str_path.split('/')[0] ...
def ping(): """[ping func provides a health check] Returns: [dict]: [success response for health check] """ return {"response": "ping to datahub successful"}
def remove(ele, lst): """ remove all occurences of an element from a list """ pops = [] for i in range(len(lst)): if lst[i] == ele: pops.append(i) return [lst[i] for i in range(len(lst)) if i not in pops]
def is_sub_dict(sub_dict, dictionary): """Legacy filter for determining if a given dict is present.""" for key in sub_dict.keys(): if key not in dictionary: return False if (type(sub_dict[key]) is not dict) and (sub_dict[key] != dictionary[key]): return False if (...
def is_number(number): """ Returns true if number is a valid number value False otherwise """ try: float(number) return True except (ValueError, TypeError): return False
def get_except(data, i, ndata, end_value): """helper method for expand that gets the values until the end of an EXCEPT chain""" removed = [] ivalue_old = 0 while i < len(data): value = data[i] #print(' exclude?', i, value) if isinstance(value, int): ivalue = valu...
def get_interface_gateway_address(context, networktype): """ Determine if the interface has a default gateway. """ return context['gateways'].get(networktype, None)
def trianglePoints2(x, z, h, w): """ Takes the geometric parameters of the triangle and returns the position of the 3 points of the triagles. Format : [[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]] Specific used for walk """ P1 = [0, x, z+h] P2 = [w/2, x, z] P3 = [-w/2, x, z] return [P1, P2,...
def func_x_a_args(x, a=2, *args): """func. Parameters ---------- x: float a: int args: tuple Returns ------- x: float a: int args: tuple """ return x, None, a, None, args, None, None, None
def convertRange(val: float, old: tuple, new: tuple): """ Converts the range of a value to a new range. Example ------- convertRange(50, (0, 100), (0, 1)) >> 0.5 """ return (((val - old[0]) * (new[1] - new[0])) / (old[1] - old[0])) + new[0]
def __checkPassed(a,b,c,verbose): #used in __convert_dims """ Notes: internal logic to determine if correct information was passed in __convert_dims when finding cellsize -> arrdim or arrdim -> cellsize conversion Inputs: ...
def safe_getattr(obj, attr_name): """Get the attribute of an object returning None if the attribute does not exist. :param obj: An object :type obj: mixed :param attr_name: The name of the attribute :type attr_name: str or unicode """ try: return getattr(obj, attr_name) exce...
def n2b(offset, length, endian) -> bytes: """Convert offset to bytes.""" s = b'' for _ in range(length): if endian == 'I': s += bytes([offset & 0xFF]) else: s = bytes([offset & 0xFF]) + s offset = offset >> 8 return s
def get_urlpath_part(urlpath): """ Return a path without url fragment (something like `#frag` at the end). This function allow to use path from references and NCX file to read item from Manifest with a correct href (without losing the fragment part). eg.: url = 'text/chapter1.xhtml#part2'...
def tree_children(tree): """Returns a list of the subtrees of tree.""" if isinstance(tree, list): return tree[1:] else: return []
def get_instance_name(inst): """Get the name of an instance, or None if it doesn't have one. The name is the value for the metadata tag "Name," if it exists. """ if inst.get('Tags'): for tag in inst['Tags']: if tag['Key'] == 'Name': return tag['Value'] return Non...
def get_a_init_from_zs(zs): """ from list of redshifts returns initial scale factor, i.e. value after 'init' """ for z in zs: if z != 'init': return 1/(1.+z)
def sort_duplicate_list(sorted_duplicates): """ Splits list of users w/ duplicate emails into a list of lists, where each sublist is attached to one email """ sorted_dup_group = [] for index, part in enumerate(sorted_duplicates): if not index: sorted_dup_group.append([part]) ...
def slice_dict(d, keys): """Return restriction of `d` to `keys`. @type d: `dict` @type keys: `set` """ return {k: v for k, v in d.items() if k in keys}
def minimum_annotated_percent(target_background_percent, min_annotated_percent): """ :param target_background_percent: background pixels in sample :param min_annotated_percent: (int) Minimum % of non background pixels in sample, in order to consider it part of the dataset :return: (Bool) """ ...
def string_to_list_only_digit(word): """ Take each character of the 'word' parameter and return a list populated with all the characters. The if clause allows only the digits to be added to the list. :param word: string :return: list of digit inside 'word' """ return [c for c in word if ...
def find_location(index, SIZE): """ Finds the x and y coordinates in a square grid of SIZE**2 given an index. It is assumed that we are counting from left to right on a set of rows top-down, and that area is square. Rows and columns start from 0 given Python indexing conventions. e.g. ...
def total_ordering(cls): """Class decorator that fills in missing ordering methods""" convert = { '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)), ('__le__', lambda self, other: self < other or self == other), ('__ne__', lambda self, o...
def find_passing_students(lst): """ Takes a list created in convert function. Students can pass if the mt1*0.3 + mt2*0.3 + final*0.4 > 60. Args: lst: list of tuples created in convert function Return: student_names: list of stringss that stores the passing students' names. """ #...
def find_start(dna): """ Finds the location of the start codon. dna: a dna sequence returns: the location of the first letter of the start codon >>> find_start("AAGATGA") 3 >>> find_start("AAGATGGATG") 3 >>> find_start("ATG") 0 """ for i in range(len(dna)): codon ...
def traverse(obj, callback=None): """ walks a nested dict/list recursively :param obj: :param callback: :return: """ if isinstance(obj, dict): value = {k: traverse(v, callback) for k, v in obj.items()} elif isinstance(obj, list): value = [traverse(elem, callback) for ele...
def get_coeff(simplex, faces): """ If simplex is not in the list of faces, return 0. If it is, return index parity. """ if simplex in faces: idx = faces.index(simplex) return 1 if idx%2==0 else -1 else: return 0
def fix_url(url): """ The BGG API started returning URLs like //cf.geekdo-images.com/images/pic55406.jpg for thumbnails and images. This function fixes them. :param url: the url to fix :return: the fixed url """ if url and url.startswith("//"): url = "http:{}".format(url) return...
def get_bits(num, gen): """ Get "num" bits from gen """ out = 0 for i in range(num): out <<= 1 val = gen.next() if val != []: out += val & 0x01 else: return [] return out
def cast_to_list(data): """Cast data to a list if it is not already a list. :param data: The variable to be cast to a list. :return: The data in a list """ if not isinstance(data, list): data = [data] return data
def bit_set(x, n): """Returns if nth bit of x is set""" return bool(x & (1 << n))
def textise(url): """ My ISP is blocks github? Textise to the rescue! """ uri = "https://www.textise.net/showText.aspx?strURL=https%253A//" return uri + url.split("://")[1]
def bond_idx_to_symb(idxs, idx_symb_dct): """ Convert a list of bond idxs ((a1, b1), (a2, b2), ..., (an, bn)) to pairs of atom symbols """ return tuple( (idx_symb_dct[idx1], idx_symb_dct[idx2]) for (idx1, idx2) in idxs )
def timed(func, *args, **kwArgs): """Times a function call""" import time t1 = time.time() res = func(*args, **kwArgs) t2 = time.time() print(' %s took %0.3f ms' % (func.__name__, (t2-t1)*1000.0)) return res
def ColorfulPyPrint_set_verbose_level(verbose_level=1): """ set output verbose level :type verbose_level: int """ global O_VERBOSE_LEVEL O_VERBOSE_LEVEL = verbose_level return O_VERBOSE_LEVEL
def human_readable(seconds): """Human readable string from seconds""" days, seconds = divmod(int(seconds), 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if days > 0: return f"{days:d}d{hours:d}h{minutes:d}m{seconds:d}s" if hours > 0: return ...
def _linspace(x0, x1, n): """return a list from x0 to x1 with n+1 element (n gaps)""" dx = (x1 - x0) / n lst = [x0 + dx * i for i in range(n)] lst.append(x1) lst = list(map(lambda x: round(x, 2), lst)) return lst
def check_duplicate(cur_cen, all_cens, window=2): """Check if a candidate center frequency is too close to an existing one. Parameters ---------- cur_cen : float Candidate center frequency to check. all_cens : list of float List of all existing center frequencies. window : int, ...
def overrides_method(method_name, obj, base): """ Return True if the named base class method is overridden by obj. Parameters ---------- method_name : str Name of the method to search for. obj : object An object that is assumed to inherit from base. base : class Th...
def listT(l): """Return the 'transpose' of a list.""" return list(map(list, zip(*l)))
def get_labels_of_types(asset, label_types): """ Extracts the latest labels from an asset Parameters ---------- - asset: the asset to extract the labels from - label_types: type of label, either DEFAULT or REVIEW """ labels = [label for label in asset['labels'] if label['l...
def _validate_time_params(time_params): """Ensure time parameters specified are sufficient.""" allowed_params = ("Ntimes", "start_time", "integration_time", "time_array") if time_params.get("time_array", None) is not None: return True elif all(time_params.get(param, None) is not None for param i...
def read_file(file_name='data.txt'): """ Example of file name 'data.txt' """ with open(file_name, "r") as fichier: file = fichier.read() return file
def _stringify_schemes_dict(schemes_dict): """ Since this file has from __future__ import unicode_literals, we manually cast all values of mocked install_schemes to str() as the original schemes are not unicode on Python 2. """ return {str(n): {str(k): str(v) for k, v in s.items()} for n, s in schem...
def CommentPattern(lang_id=0): """Returns a list of characters used to comment a block of code @param lang_id: used to select a specific subset of comment pattern(s) """ return [u'<!--', u'-->']
def is_illegal_at_ends(c: str): """ IllegalCharacters::IllegalCharacters() https://source.chromium.org/chromium/chromium/src/+/master:base/i18n/file_util_icu.cc;l=66;drc=e45616a746204e7405d3e2414675978597817414 """ return c.isspace() or c == '.'
def iterative_topological_sort(graph, start=None): """ Get Depth-first topology. :param graph: dependency dict (like a dask) {'a':['b','c'], 'c':['b'], 'b':[]} :param start: str the node you want to search from. This is equivalent to the node you want to compute....
def _restore_padding(token): """Restore padding based on token size. :param token: token to restore padding on :returns: token with correct padding """ # Re-inflate the padding mod_returned = len(token) % 4 if mod_returned: missing_padding = 4 - mod_returned token += b'=' *...