content
stringlengths
42
6.51k
def _color_from_bin(bin, n_bins): """ Return color for bin.""" if n_bins <= 0: return 'white' ratio = bin/float(n_bins) if ratio <= 0.2: return '#6fdba5' elif ratio <= 0.3: return 'orange' elif ratio <= 0.5: # return DEFAULT_COLORSCALE[bin] return 'red' ...
def y_pos(y0,v,t): """ Calculates the analytic vertical position in time @ In, y0, float, initial vertical position @ In, v, float, velocity of the projectile @ In, t, float, time of flight @ Out, y_pos, float, vertical position """ return y0 + v*t - 4.9*t*t
def pow_n(narray, n): """ Return array of numbers raised to arbitrary power n each """ return [pow(x, n) for x in narray]
def _merge_args_with_kwargs(args_dict, kwargs_dict): """Merge args with kwargs.""" ret = args_dict.copy() ret.update(kwargs_dict) return ret
def product(numbers): """Multiply together numbers.""" result = 1 for number in numbers: result *= number return result
def _mergedicts(main_dict, changes_dict, applied_changes, initial_path=''): """ Merge the 2 dictionaries. We cannot use update as it changes all the children of an entry """ for key, value in changes_dict.items(): current_path = '{}.{}'.format(initial_path, key) if key in main_dict.keys(...
def split_paragraphs(string): """ Split `string` into a list of paragraphs. A paragraph is delimited by empty lines, or lines containing only whitespace characters. """ para_list = [] curr_para = [] for line in string.splitlines(keepends=True): if line.strip(): curr_...
def key_in_kwargs(key, **kwargs): """ Tests if a key is found in function kwargs | str, kwargs --> bool """ kwarg_dict = {**kwargs} if key in kwarg_dict: return True return False
def remove_dot_segments(s): """Remove dot segments from the string. See also Section 5.2.4 of :rfc:`3986`. """ # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code segments = s.split('/') # Turn the path into a list of segments output = [] # Initialize the variable to use to...
def ab_string(S): """ >>> ab_string("aaaaaaabbbbbbbbbb") True >>> ab_string("b") True >>> ab_string("aba") False >>> ab_string("aaba") False """ found_b = False for aa in S: if ( aa == "b"): found_b = True else: # must be a ...
def ABCD_eq(b,c,d): """ Basic estimator formula for count in 'A' (signal domain) DEFINITION: A = B x C / D ^ |C | A |----- |D | B 0------> """ return b * c / d
def record_repeated_copies(per_file_stats): """Return a dictionary of length-2 lists. The length-2 list whose key is i corresponds to the files that were copied i times. The first element in each length-2 list is how many bytes those files need, the second element is the list of those file names. >>> x = {'2013092...
def string_list(argument): """Parse a list of strings. If no argument is given, return an empty list.""" return argument.split() if argument is not None else []
def GetAllowedAndroidApplications(args, messages): """Create list of allowed android applications.""" allowed_applications = [] for application in getattr(args, 'allowed_application', []) or []: android_application = messages.V2AndroidApplication( sha1Fingerprint=application['sha1_fingerprint'], ...
def get_ce_endpoint(ce): """ Extracts the endpoint from a computing element *ce* and returns it. Example: .. code-block:: python get_ce_endpoint("grid-ce.physik.rwth-aachen.de:8443/cream-pbs-cms") # -> "grid-ce.physik.rwth-aachen.de:8443" """ return ce.split("/", 1)[0]
def fy(vy0, n): """ Computed by hand """ return n*(2*vy0 + 1 -n) / 2
def format(value, arg): """ Alters default filter "stringformat" to not add the % at the front, so the variable can be placed anywhere in the string. """ try: if value is not None: # return (str(arg)) % value return (str(value)) % arg else: return ...
def getStateLabelsFromLineNo(line_no, n): """ Gets the indeces for labelling rho [i, j] from the line number of an array. Parameters: line_no (int): line number of an array e.g. position of a row in a matrix or column in rho_t n: the number of states in the system Returns: ...
def _remove_quotes(values): """Remove any quotes from quoted values.""" removed = [] for value in values: if value.startswith('"') and value.endswith('"'): value = value[1:-1] removed.append(value) return removed
def remove_whitespace_make_lowercase(data, exclude): """Removes whitespaces from input data and change input data to lowercase """ for field in data.keys(): if isinstance(data.get(field), str) and field != exclude: data[field] = data.get(field).strip().lower() return data
def convert_headers_str(_str): """ convert headers str to dict """ _list = [i.strip() for i in _str.split('\n')] headers_dict = dict() for i in _list: k, v = i.split(':', 1) headers_dict[k.strip()] = v.strip() return headers_dict
def obtener_nombre_pieza(simbolo): """ (str) -> str >>> obtener_nombre_pieza('p') 'Peon blanco' >>> obtener_nombre_pieza('R') 'Rey Negro' Retorna el nombre de la pieza del ajedrez dado su simbolo :param simbolo: la representacion de la pieza segun el enunciado :return: El nombre y...
def constraint_reach_back_row(_, stats): """Return true if two cells in the back row are round trip reachable.""" return stats['rtr_back_row'] >= 2
def is_empty(value): """Check whether the given value should be considered "empty".""" return value is None or value == '' or ( isinstance(value, (list, tuple, dict)) and not value)
def repeat(n: int, keyword: str) -> str: """ Build the filter to find articles containing `keyword` at least `n` times. eg. repeat(2, "environment") finds articles containing the word "environment" at least twice. Only single word repetitions are allowed. """ if " " in keyword: rai...
def GenerateTransitionMatrix(counts): """ Convert a countr matrix into a probability transition matrix. @param counts: for each key, how many times is the future node seen """ transitions = {} for key in counts: destination_actions = counts[key] # initialize the empty list ...
def get_edge_attrs(source_id, targe_id, node_label, edge_label, attrs_var): """Query for retreiving edge's attributes.""" query = ( "MATCH (n:{} {{ id: '{}' }})-[rel:{}]->(m:{} {{ id: '{}' }}) \n".format( node_label, source_id, edge_label, node_label, targe_id) + "RETURN properties(r...
def division_complejos(num1:list,num2:list) -> list: """ Funcion que realiza la division de dos numeros complejos. :param num1: lista que representa primer numero complejo :param num2: lista que representa segundo numero complejo :return: lista que representa la division de los numeros complejo...
def get_status_new(code: int) -> str: """Get the torrent status using new status codes""" mapping = { 0: "stopped", 1: "check pending", 2: "checking", 3: "download pending", 4: "downloading", 5: "seed pending", 6: "seeding", } return mapping[code]
def interpolate(x1: float, x2: float, y1: float, y2: float, x: float): """Perform linear interpolation for x between (x1,y1) and (x2,y2) """ return ((y2 - y1) * x + x2 * y1 - x1 * y2) / (x2 - x1) if (x2-x1)>0 else y1 #print(val) #print("---") #return val
def run_length_encoding(seq): """define the run length encoding function""" compressed = [] count = 1 char = seq[0] for i in range(1, len(seq)): if seq[i] == char: count = count + 1 else: compressed.append([char, count]) char = seq[i] c...
def list_keys_to_expand(config, root=True, pre_keys=()): """List the keys corresponding to List or callable.""" if isinstance(config, dict): keys = () for k, v in sorted(config.items()): keys += list_keys_to_expand(v, root=False, pre_keys=pre_keys + (k,)) return keys elif (not root and isinstanc...
def get_axis_vector(axis_name): """ Convenience. Good for multiplying against a matrix. Args: axis_name (str): 'X' or 'Y' or 'Z' Returns: tuple: vector eg. (1,0,0) for 'X', (0,1,0) for 'Y' and (0,0,1) for 'Z' """ if axis_name == 'X': return (1,0,0...
def genus_PARnamePAR_species(tokens): """ Input: Brassica (cabbage) oleracea Output: <taxon genus="Brassica" species="oleracea" sub-prefix="" sub-species=""><sp>Brassica</sp> (cabbage) <sp>oleracea</sp> </taxon> """ (genus, name, species) = tokens[0:3] return f'''<taxon ...
def query_equalize(query: str) -> str: """removes whitespace/newline deltas from sql""" return ' '.join(query.replace('\n', ' ').split())
def as_list(item): """Make item a list from types which can index, have items, or can pop""" try: item.index return list(item) except AttributeError: try: return list(item.items()) except AttributeError: try: item.pop re...
def mystery_3c(c1: float, c2: float, c3: float) -> int: """Function for question 3c.""" if c1 > 0: if c2 % 3 == 0: if c3 % c2 == 0: return 1 else: return 2 else: if c3 % c2 == 0: return 3 else: ...
def intersection(st, ave): """Represent an intersection using the Cantor pairing function.""" return (st + ave) * (st + ave + 1) // 2 + ave
def expand_str_list(l, prefix="", suffix=""): """add strings to the beginning or to the end of the string """ return [prefix + x + suffix for x in l]
def region_from_az(az: str = "") -> str: """ :param az: us-east-1b :type az: us-east1 :return: :rtype: """ if not az: return "" parts = az.split("-") ret_val = parts[0] + "-" + parts[1] + "-" + parts[2][:-1] return ret_val
def fibonacci(n): """ Generate a list of fibonacci numbers up to and including n. """ result = [1, 1] if n <= 2: return result[0:n] counter = 2 while True: next_fib = result[counter-2] + result[counter-1] if next_fib > n: break result.append(next_f...
def generate_primes(num1, num2): """Returns a list Prime numbers generated between the given range(num1, num2) """ if num1 > num2: raise Exception( "num1 can't be greater than num2. Specify the correct range.") if num1 == 0 or num2 == 0: raise Exception("Specify the corre...
def parse_int(string, default): """ Parses the string as a int by using a default value if is not possible. """ # If the string is not numeric if not string.isnumeric(): return default # Otherwise, return the string as int else: return int(string)
def jenkins_one_at_a_time_hash(s, size): """http://en.wikipedia.org/wiki/Jenkins_hash_function.""" h = 0 for c in s: h += ord(c) h += (h << 10) h ^= (h >> 6) h += (h << 3); h ^= (h >> 11); h += (h << 15); return h % size;
def isValidOptionSet(distractor,ans): """ Remove erroneously generated option sets Arguments: distractor: the wrong options ans: the correct answer Returns: True/False depending on whether the generated option sets are valid or not """ ...
def extract_source_files(imports, local_upload_path): """ Returns tuples of the imported sources files. """ imported_files = [] for imported_file in imports: if imported_file.startswith(local_upload_path): file_name = imported_file[len(local_upload_path):] file_content = imp...
def escape(s, quote=None): """ Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. """ s = s.replace("&", "&amp;") # Must be done first! s = s.replace("<", "&lt;") s = s.replace(">", ...
def _write_a_tikz_coordinate(name, xy, num_fmt): """Write a TikZ coordinate definition. Parameters ---------- name : str TikZ coordinate identified / name. xy : list or tuple of floats (x, y)-coordinates. num_fmt : str Specification of the numbers format, e.g. '.4f'. ...
def from_lane_to_hex_string(lane, w): """Convert a lane value to a string of bytes written in hexadecimal""" lane_hex_b_e = ((b"%%0%dX" % (w // 4)) % lane) # Perform the conversion temp = b'' length = len(lane_hex_b_e) // 2 for i in range(length): offset = (length - i - 1) * 2 t...
def diff_dict(a, b): """Returns a yaml-like textural diff of two dict. It is currently optimized for the .isolated format. """ out = '' for key in set(a) | set(b): va = a.get(key) vb = b.get(key) if va.__class__ != vb.__class__: out += '- %s: %r != %r\n' % (key, va, vb) elif isinstance...
def transform_triples(triples, relation_types, entities): """ Groups a list of relations triples by their relations and returns a suitable data structure. Args: triples (list): List of relation triples as tuples. relation_types (dict): Dictionary with relations as key and the amount of triples with this relatio...
def numberIsAWholeNumber(rawNumber): """ Checks if the input is a whole number or not by parsing. Params: rawNumber - A string holding the user's raw input (which may be a number) Returns: Flag representing whether the input is a whole number or not. """ try: int(rawNumber) ...
def consistent_det(A, E): """Checks if the attributes(A) is consistent with the examples(E)""" H = {} for e in E: attr_values = tuple(e[attr] for attr in A) if attr_values in H and H[attr_values] != e['GOAL']: return False H[attr_values] = e['GOAL'] return True
def gcd(m, n): """greatest common denominator, with euclid""" if n > m: m, n = n, m r = m % n # get the remainder if r == 0: return n return gcd(n, r)
def factorial(n: int) -> int: """Return the factorial of n. >>> factorial(5) 120 >>> factorial(1) 1 >>> factorial(0) 1 >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> factorial(1.1) Traceback (most recent call l...
def convert_ipaddress(ipint): """Function for converting a 32 bit integer to a human readable ip address https://geekdeck.wordpress.com/2010/01/19/converting-a-decimal-number-to-ip-address-in-python/ :param ipint: 32 bit int ip address :type ipint: integer :return: human readable ip address """ ipint = i...
def fix_actress_name(name): """Returns the updated name for any actress based on our replacement scheme""" """ if you want to ad any additional ways to fix names, simply add another elif line below elif name == 'name returned from javlibrary' return 'different name' """ if name == ...
def get_trader_fcas_availability_agc_status_condition(params) -> bool: """Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS.""" # Check AGC status if presented with a regulating FCAS offer if params['trade_type'] in ['L5RE', 'R5RE']: # AGC is active='1', AGC is ina...
def invert_dict(dictionary): """Constructs a new dictionary with inverted mappings so that keys become values and vice versa. If the values of the original dictionary are not unique then only one of the original keys will be included in the new dictionary. """ return dict((value, key) for key, v...
def to_list(stringlist, unquote=True): """Convert a string representing a list to real list.""" stringlist = stringlist[1:-1] return [ string.strip('"') if unquote else string for string in stringlist.split(",") ]
def _get_pairedvote(vote_id): """ Map vote its to a 0/1 flag for paired voting. """ return 1 if vote_id in [2, 5] else 0
def hello(args) -> int: """Say "hello"! """ print('hello!') return 0
def _make_options(o_dict): """Join options dict back into a valid options string. :param str options_dict: :return: options string for use in connection string :rtype: str """ return ' '.join( ["-c {}={}".format(k, o_dict[k]) for k in sorted(o_dict)])
def getPooledVariance( data ): """return pooled variance from a list of tuples (sample_size, variance).""" t, var = 0, 0 for n, s in data: t += n var += (n-1) * s assert t > len(data), "sample size smaller than samples combined" return var / float(t - len(data))
def index_acl(acl): """Return a ACL as a dictionary indexed by the 'entity' values of the ACL. We represent ACLs as lists of dictionaries, that makes it easy to convert them to JSON objects. When changing them though, we need to make sure there is a single element in the list for each `entity` value, s...
def maptostr(target_list): """Casts a list of python types to a list of strings Args: target_list (list): list containing python types Returns: List containing strings Note: May no longer be needed in Python3 """ return [str(each) for each in target_list]
def options2args(options): """Convert a list of command line options to a args and kwargs """ args = list() kwargs = dict() for a in options: if "=" in a: a = a.split("=", maxsplit=1) kwargs[a[0].lstrip("-")] = a[1] else: args.append(a) return args...
def taxname( rowhead ): """make g.s taxa names look nicer""" if "s__" in rowhead: return rowhead.split( "." )[1].replace( "s__", "" ).replace( "_", " " ) elif "g__" in rowhead: return rowhead.replace( "g__", "" ).replace( "_", " " ) else: return rowhead
def add(*args): """ Return sum of any number of arrays. """ return [sum(vals) for vals in zip(*args)]
def _add_hf_to_spc_dct(hf0k, spc_dct, spc_name, spc_locs_idx, spc_mod): """ Put a new hf0k in the species dictioanry """ if 'Hfs' not in spc_dct[spc_name]: spc_dct[spc_name]['Hfs'] = {} if spc_locs_idx not in spc_dct[spc_name]['Hfs']: spc_dct[spc_name]['Hfs'][spc_locs_idx] = {} spc_d...
def nicefy_props(data): """split keydef into key and modifiers """ from_, to = 'Keypad+', 'KeypadPlus' data = data.replace(from_, to) test = data.split('+') mods = '' if 'Ctrl' in data: mods += 'C' if 'Alt' in data: mods += 'A' if 'Shift' in data: mods += 'S' ...
def get_clip(ct): """ Ientify the number of bases that are soft or hard-clipped prior to a supplementary alignment of a query sequence (i.e., ONT read) using the pysam `cigar_tuple`. We use the number of bases clipped prior to an alignment as a proxy for that alignment's relative order in the or...
def get_ordinal(n): """Convert number to its ordinal (e.g., 1 to 1st) Parameters ---------- n : int Number to be converted to ordinal Returns ---------- str the ordinal of n """ return "%d%s" % ( n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n %...
def compute_grid(index, n_files, min_H, min_W, patch_size): """ Compute the coordinate on a grid of indices corresponding to 'index'. The indices are in the form of [i, tl_x, tl_y], where 'i' is the file index. tl_x and tl_y are the top left coordinates of the patched image. To get a patch from any imag...
def collect_codelist_values(path, data, pointer=''): """ Collects ``codelist`` values from JSON Schema. From https://github.com/open-contracting/jscc/blob/main/jscc/testing/checks.py#L674 """ codelists = set() if isinstance(data, list): for index, item in enumerate(data): co...
def gardner_anhydrite(Vp, A=2.19, B=0.16): """ Vp in km/sec """ Rho = A*Vp**B return Rho
def _ensure_extension(filename: str, extension: str): """Add the extension if needed.""" if filename.endswith(extension): return filename return filename + extension
def trembling_velocity(im_list): """ The displacement of each frame compared to the previous, this is done by detecting particles, and averaging their velocity at each time point. :param im_list: A consecutive list of frames :return: The average velocity of all the particles at a certain time point...
def unique(items): """Convert a sorted list of items into a unique list, taking the first occurrence of each duplicate item. Parameters ---------- items : list-like Returns ------- list """ s = set() result = [] for item in items: if not item in s: ...
def money_style(amount: float) -> str: """Return a corresponding bootstrap style to an amount of money :param amount: The amount of money :returns: The bootstrap style """ return 'success' if amount >= 0 else 'danger'
def _byte_to_int(data: bytes) -> int: """ Returns integer value of big endian byte data :param data: :return: Integer value :rtype: int """ return ord(data[0:1]) + (ord(data[1:2]) * 0x100) + (ord(data[2:3]) * 0x10000) + (ord(data[3:4]) * 0x1000000)
def step_edge_distance(num_of_steps, extent, step): """ You have a line segment with a given extent (length). In distance coordinates such as points, 0 is at the beginning of the segment increasing to the extent at the other end. A number line is defined with step increment 0 at the center of the line s...
def make_validation_func(func, args=None, expand_args=True): """Create a validation function based on our input""" validation_func = func if args is not None: if expand_args: validation_func = validation_func(*args) else: validation_func = validation_func(args) re...
def build_profile(first, last, **user_info): """Create a dictionary including all information of the users as we know""" profile = {'first_name': first, 'last_name': last} for key, value in user_info.items(): profile[key] = value return profile
def convert_path_list_to_path_map(path_list): """ The same path can have multiple methods. For example: /vcenter/vm can have 'get', 'patch', 'put' Rearrange list into a map/object which is the format expected by swagger-ui key is the path ie. /vcenter/vm/ value is a an object which contains key ...
def get_parsed_context(context_arg): """Return context arg stub.""" return {'parsed_context': context_arg}
def get_dim(sheet): """ Get the dimensions of data """ try: col_count = sheet.get_all_records() except: col_count = [[]] row = len(col_count) col = len(col_count[0]) return row, col
def filter_features(features, geom_type='Polygon'): """Filter input GeoJSON-like features to a given geometry type.""" return [f for f in features if f['geometry']['type'] == geom_type]
def create_grid( x: int, y: int, d: int, ) -> list: """Create a grid of digits Parameters ---------- x : int The number of elements in the x-direction y : int The number of elements in the y-direction d : int The digit to create the grid of Returns ...
def avg(new, avg, times): """ :param new: int, the new score :param avg: float, the average of score of the class :param times: int, numbers of the scores of the class :return: float, the new average """ new_avg = (avg * (times - 1) + new) / times return new_avg
def linear_approximation_real(x, x1, y1, x2, y2): """Linear approximation for float arguments""" return (y1 - y2) / (x1 - x2) * x + (y2 * x1 - x2 * y1) / (x1 - x2)
def lemma_from_lexemes(lexemes, separator=' '): """ given a list of dictionaries, each dictionary representing a lexeme, reconstruct the lemma :param list lexemes: list of dictionaries :param string separator: how to join the lexemes if 'breakBefore' = 'false' :r...
def NoTests(path, dent, is_dir): """Filter function that can be passed to FindCFiles in order to remove test sources.""" if is_dir: return dent != 'test' return 'test.' not in dent
def calculate_weighted_average(rated_stars): """ Function that calculates the recipe weighted average rating """ numerator = 0 denominator = 0 for key, value in rated_stars.items(): numerator += int(key) * value denominator += value return numerator/denominator
def print_num(n): """ there must be a package that does this better. oh well""" if n >= 1000000000: return "{}{}".format(round(float(n) / 1000000000, 2), "B") elif n >= 1000000: return "{}{}".format(round(float(n) / 1000000, 2), "M") elif n >= 1000: return "{}{}".format(round...
def gcd(a, b): """ Find GCD(a, b).""" # GCD(a, b) = GCD(b, a mod b). while (b != 0): # Calculate the remainder. remainder = a % b # Calculate GCD(b, remainder). a = b b = remainder # GCD(a, 0) is a. return a
def get_components(items): """Return a list of pairs of IDs and numbers in items. get_components(list(str)) -> list((str, int)) """ components = [] for item in items: item = item.strip() itemid, _, itemnumstr = item.partition(':') itemid = itemid.strip() itemnumstr =...
def fake_call(command, **kwargs): """ Instead of shell.call, call a command whose output equals the command. :param command: Command that will be echoed. :return: Returns a tuple of (process output code, output) """ return (0, str(command))
def cluster_set_name(stem, identity): """Get a setname that specifies the %identity value..""" if identity == 1.0: digits = "10000" else: digits = f"{identity:.4f}"[2:] return f"{stem}-nr-{digits}"
def pypi_prepare_rst(rst): """Add a notice that the rst was auto-generated""" head = """\ .. This file is automatically generated by setup.py from README.md and CHANGELOG.md. """ rst = head.encode('utf-8') + rst return rst