content
stringlengths
42
6.51k
def fib(n): """Calculates the nth fibbonaci number. NOTE: Uses index counting""" if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2)
def _recursive_max(jagged): """ Examples -------- from landlab.components.profiler.base_profiler import _recursive_max >>> struct = [[1, 2, 3, 4], ... [[2, 3, 4, 5], ... [3, 4, 5, 6]], ... [4, 5, 6, 7]] >>> _recursive_max(struct) 7 >>> _recursiv...
def bitstring_to_bytes(s: str) -> bytes: """ Converts a bitstring to a byte object. This function is necessary as certain libraries (specifically the base64 library) accepts byte objects, not strings which are often expressed in UTF-8 or ASCII formats. Parameters ---------- s: str Bits...
def ensure_value(namespace, dest, default): """ Thanks to https://stackoverflow.com/a/29335524/6592473 """ stored = getattr(namespace, dest, None) if stored is None: return default return stored
def search_sequence2(full_sequence, short_sequence, position, max_position): """ Recurently search for sequence with step = 1""" new_position = None try: new_position = full_sequence[position:].index(short_sequence)+position except ValueError: return [] if new_position > max_position...
def to_api_order(signed_order_json): """Given a signed order json, make compatible with 0x API Order Schema""" return {"metaData": {}, "order": signed_order_json}
def filter_combinations(combinations, mode): """ Filter a list of combinations, extracting only those which satisfy the condition of filter mode. :param combinations: a list with all the combinations to filter :param mode: the filter mode :return: a list of the filtered combinations. """ fil...
def if_ipaddress_return_it(ip): """[summary] Arguments: ip {[type]} -- [description] Returns: [type] -- [description] """ try: parts = ip.split('.') return len(parts) == 4 and all(0 <= int(part) < 256 for part in parts) except ValueError: return False # one of t...
def _format_links(link_x): """ Format links part """ try: pairs = "" for _dict in link_x: pairs += _dict['rel'] + '-> ' + _dict['href'] + '\n' return pairs[:-1] except: return link_x
def validate_birth_year(passport: dict) -> bool: """ Return True if the birthyear in a password is between 1920 and 2002 DOCTEST >>> validate_birth_year(passport={"ecl": "gry", "byr": "1937"}) True >>> validate_birth_year(passport={"ecl": "gry", "byr": "1919"}) False >>> validate_birth_...
def rdict(x): """ recursive conversion to dictionary converts objects in list members to dictionary recursively attributes beginning with '_' is converted to fields excluding the '_' """ if isinstance(x, list): l = [rdict(y) for y in x] return l elif isinstance(x, dict): ...
def _create_index_content(words): """Create html string of index file. Parameters ---------- words : list of str List of cached words. Returns ------- str html string. """ content = ["<h1>Index</h1>", "<ul>"] for word in words: content.append( ...
def paginate_list(list_to_paginate: list, page: int, elems_page: int = 10): """Grabs a 'page' out of the given `list_to_paginate` and returns a section `elems_page` large. Args: list_to_paginate (list): The list of items you would like to get the page of. page (int): The num...
def extract_text_from_proto(proto_list): """Extracts text from proto""" values = [] for item in proto_list: if item.pinned_field: values.append("%s: %s" % (item.pinned_field, item.text)) else: values.append("%s" % item.text) return values
def daily_clear_sky_irradiance(altitude, et_rad): """ Estimate clear sky radiation from altitude and extraterrestrial radiation. Based on equation 37 in Allen et al (1998) which is recommended when calibrated Angstrom values are not available. :param altitude: Elevation above sea level [m] ...
def tail_field(field): """ RETURN THE FIRST STEP IN PATH, ALONG WITH THE REMAINING TAIL """ if field == "." or field==None: return ".", "." elif "." in field: if "\\." in field: return tuple(k.replace("\a", ".") for k in field.replace("\\.", "\a").split(".", 1)) e...
def render_label(env_spec_entry): """ Creates the html output for label.Takes as argument the current dictionary. """ label_str = f'<label for="env_spec_{env_spec_entry["name"].lower()}">{env_spec_entry["name"]}</label>\n' return label_str
def static_cond(pred, fn1, fn2): """Return either fn1() or fn2() based on the boolean value of `pred`. Same signature as `control_flow_ops.cond()` but requires pred to be a bool. Args: pred: A value determining whether to return the result of `fn1` or `fn2`. fn1: The callable to be performed if pred...
def is_even(val): """ Confirms if a value if even. :param val: Value to be tested. :type val: int, float :return: True if the number is even, otherwise false. :rtype: bool Examples: -------------------------- .. code-block:: python >>> even_numbers = list(filter(is_even, ran...
def greet(name: str) -> str: """ Greetings! """ return "Yo, " + name
def is_directory(entry): """Returns true if the given entry is a directory""" return entry['nlink'] > 1
def retrieve_named_argument(args, argument_name, default_value=None): """Retrieves a named argument (prefixed with -) """ argument_value = default_value argument_val_list = [] for i, arg in enumerate(args): if (arg[0] == '-') & (arg[1:] == argument_name): for following_args in ar...
def Precond(M, r): """This can implement preconditioning into minresQLP.""" # if callable(M): # h = cg(M, r) # else: # h = inv(M).dot(r) # return h return r
def token_seems_valid(token: str) -> bool: """check validity of an api token based on its characters and length Args: token (str): sure petcare api token Returns: bool: True if ``token`` seems valid """ return ( (token is not None) and token.isascii() and token.isprintable(...
def importModule(moduleName): """ Import the named module, and return the module object - Works properly for fully qualified names. """ module = __import__(moduleName) components = moduleName.split('.') for comp in components[1:]: module = getattr(module, comp) return module
def extract_urlparam(name, urlparam): """ Attempts to extract a url parameter embedded in another URL parameter. """ if urlparam is None: return None query = name+'=' if query in urlparam: split_args = urlparam[urlparam.index(query):].replace(query, '').split('&') ret...
def get_arch_desc_constructor(arch_desc): """Return default archdesc constructor.""" default_con = {'type': 'DefaultSlotArchDescConstructor', 'args': {}} default_con['args']['arch_desc'] = arch_desc return default_con
def nth_even(n): """Return nth even number.""" return 2 * n - 2
def reaction_species_dictionaries(rxn_dct): """ return the species dictionaries for a reaction """ return rxn_dct['Reactants'], rxn_dct['Products']
def collide(ax0, ay0, ax1, ay1, bx0, by0, bx1=None, by1=None): """Return True if the two rectangles intersect.""" if bx1 is None: bx1 = bx0 if by1 is None: by1 = by0 return not (ax1 < bx0 or ay1 < by0 or ax0 > bx1 or ay0 > by1)
def _is_positive_int(item): """Verify that the value is a positive integer.""" if not isinstance(item, int): return False return item > 0
def to_string(params): """ Combine a parameter dictionary into a single url string Parameters ---------- params : dictionary Returns ------- url string of input dictionary (not encoded) Examples -------- >>> CMRparams = {'short_name': 'ATL06', 'version': '002', 'temporal':...
def pack_to_tuple(obj): """ Converts a given object to a tuple object If the object is a tuple, the function returns the input, otherwise creates a single dimensional tuple Parameters ---------- obj : Object Object that is converted to a tuple Returns ------- t : tuple...
def mul_inv(a, b): """ I claim no copyright on this function. I copied it from the internet. """ b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a // b a, b = b, a % b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1
def porownajPunkty(p1,p2): """ Compare two points Faster than numpy.all for small arrays """ for a, b in zip(p1,p2): if a!=b: return False return True
def generate_image_uuid(vdu, vnfd): """ This method creates the image_uuid based on the vdu info in the vnfd """ new_string = vnfd['vendor'] + '_' + vnfd['name'] + '_' + vnfd['version'] new_string = new_string + '_' + vdu['id'] return new_string
def boolean(value): """ Helper function for taking some basic steps to properly converting a "value" into a properly mapped/cast boolean. This was originally designed to be used when handling ConfigParser inputs/values that may not be properly cast due to older versions (e.g. agent must support Python 2...
def cubic_bezier_point(points, t): """ Get the coordinate of a point along a cubic bezier curve Args: points (:obj:`list` of :obj:`list` of :obj:`float`): control points t (:obj:`float`): position along the curve [0, 1] Returns: :obj:`tuple` of :obj:`float`: position of the curve a...
def _packTerms(terms): """ Packages terms into lists of 4. If the length of terms is not divisible by 4, then the final list is short a bit (but this is okay). """ segmentedTerms = [] index = 0 while True: endIndex = index + 4 if endIndex >= len(terms): endIndex = len(terms) segmentedTerms.append(term...
def whitespace_count(value): """Count the number of white space characters in the string representation for a scalar value. Parameters ---------- value: scalar Scalar value in a data stream. Returns ------- int """ return sum(c.isspace() for c in str(value))
def makemap(lst): """ :param lst: (array) :return: (dictionary) """ keyset = list(set(lst)) keyset.sort() return {k: i for i, k in enumerate(keyset)}
def char_diversity(data): """ used to detect non-sense and random keyboard strokes :param data: :return char diversity score: """ edit_length = len(data) if len(data) <= 0: return 0.0 unique_chars = list(set(data)) return round(edit_length ** (1 / len(unique_chars)), 4) if le...
def lin_sum(x, lr, y): """Returns linear sum.""" return x + lr * (y - x)
def _clean_roles(roles): """ Clean roles. Strips whitespace from roles, and removes empty items. Args: roles (str[]): List of role names. Returns: str[] """ roles = [role.strip() for role in roles] roles = [role for role in roles if role] return roles
def vecsum(la, lb): """ (1,4,2) + (2,-1,1) == (3,3,3) """ return tuple(a + b for a, b in zip(la, lb))
def hours_for_study(*chores): """ >>> hours_for_study(('A', 5)) 12 >>> hours_for_study() 17 >>> hours_for_study(('A', 6), ('B', 4)) 7 >>> hours_for_study(('B', 20)) 0 """ chore_hours = 0 total_hours = 17 for arg in chores: chore_hours += arg[1] tot...
def get_feature_dimensions(parameters): """ Returns dimensions (`int`s) of all node features. """ n_atom_types = len(parameters["atom_types"]) n_formal_charge = len(parameters["formal_charge"]) n_numh = int( not parameters["use_explicit_H"] and not parameters["ignore_H"] ) * len(...
def index_to_month(index): """ The opposite companion to ``month_to_index``. Returns a (year, month) tuple. """ return (index // 12) + 1, index % 12 + 1
def _get_map_key(wire_position): """ wire position, tuple of tuple like: ((0, 0), (0, 1)) """ if wire_position[0][0] + wire_position[0][1] > \ wire_position[1][0] + wire_position[1][1]: return str((wire_position[1], wire_position[0])) return str(wire_position)
def get_model_argument(args, kwargs, arg_index = 0): """ Utility function to get the model object from the arguments of a function :param args: :param kwargs: :param arg_index: :return: """ try: model = kwargs['model'] except KeyError: model = args[arg_index] re...
def str_to_set(text): """ transforms comma separated string into a set 'name1, name2, name3' -> {'name1', 'name2', 'name3'} """ if isinstance(text, str): return frozenset([name.strip() for name in text.split(',')]) elif isinstance(text, set) or isinstance(text, frozenset): # if its alrea...
def retrieve_temperature_data(data): """Retrieve temperature data main stuff""" max_temp = -100 min_temp = 100 avg_temp = 0 for item in data: if item["day"]["maxtemp_c"] > max_temp: max_temp = item["day"]["maxtemp_c"] if item["day"]["mintemp_c"] < min_temp: ...
def infer_chain(chain_str): """ :param chain_str: An input string, used to refer to a specific TCR chain locus :return: TRA or TRB """ if chain_str.upper() in ['TRA', 'A', 'ALPHA']: return 'TRA' elif chain_str.upper() in ['TRB', 'B', 'BETA']: return 'TRB' else: raise...
def linear_warmup_lr(current_step, warmup_steps, base_lr, init_lr): """Linear learning rate""" lr_inc = (float(base_lr) - float(init_lr)) / float(warmup_steps) lr = float(init_lr) + lr_inc * current_step return lr
def classifier(density): """Classify rocks with secret algorithm.""" if density <= 0: raise ValueError('Density cannot be zero or negative.') elif density >= 2750: return 'granite' elif density >= 2400: return 'sandstone' else: return 'not a rock'
def RgbFromHex(color_hex): """Returns a RGB color from a color hex. Args: color_hex: A string encoding a single color. Example: '8f7358'. Returns: A RGB color i.e. a 3-int tuple. Example: (143, 115, 88). """ return tuple(int(color_hex[i:i + 2], 16) for i in (0, 2, 4))
def validate_files(input_files): """ The valid files will have name: <class_name>_<split>.txt. We want to remove all the other files from the input. """ output_files = [] for item in input_files: if len(item.split("/")[-1].split("_")) == 2: output_files.append(item) retur...
def _is_generic_key(key): """Determines whether the key starts with a generic config dictionary key.""" for prefix in [ "graph_rewriter_config", "model", "train_input_config", "train_config", "eval_config"]: if key.startswith(prefix + "."): return True return False
def LJ_potential_bc(vnew,f2,coords): """ Apply Boundary Condition to the potential, force, and coordinates. Parameters: ----------- vnew : float (or array of floats) Potential Energy f2 : float (or array of floats) Force coords : float ...
def _remove_tag(tags, prop): """ convert a note into tags """ try: tags.remove(prop) except ValueError: pass return tags
def d2r(dx, fc, i): """ second-order right-sided derivative at index i """ D = -fc[i] + 4.0*fc[i+1] - 3.0*fc[i+2] D = D/(2.0*dx) return D
def convert_params(params): """ Function removes labels from dictionary with operations :param params: labeled parameters :return new_params: dictionary without labels of node_id and operation_name """ new_params = {} for operation_parameter, value in params.items(): # Remove right...
def iterable(obj): """return true if *obj* is iterable""" try: iter(obj) except TypeError: return False return True
def applyCoder(text, coder): """ Applies the coder to the text. Returns the encoded text. text: string coder: dict with mappings of characters to shifted characters returns: text after mapping coder chars to original text """ s = "" for char in text: if char in coder: ...
def normcase(s): """Normalize case of pathname. Makes all characters lowercase and all slashes into backslashes.""" return s.replace('/', '\\').lower()
def prime_factors(n): """Return a list of prime factors for n.""" factors = [] p = 2 while n >= (p * p): if n % p: p += 1 else: n = n // p factors.append(p) factors.append(n) return factors
def binary_search(arr, target, begin=None, end=None): """ :param arr: :param target: :param begin: :param end: :return: """ if begin is None: begin = 0 if end is None: end = len(arr) - 1 if end < begin or end < 0: return False, None elif end == begin:...
def encode_literal_num(n: int, size: int) -> bytes: """Send numbers as literal string in decimal `size`: target length of the byte str example: 123 -> ["0","0",... , "1","2","3"] """ s = str(n) s = "0" * (size - len(s)) + s # prevent overflow assert s[0] == "0" return s.encode("utf-8...
def _parenthesis_balancedQ(eqn): """Takes an eqn string and return True if parenthesis are balanced and False otherwise >>> map(_parenthesis_balancedQ,['(fdjd)*d((2-1)+x*2)', 'fs*(1-(x*2*(a+b))', 'dfs * (x-2) + b)']) [True, False, False] """ # 'opened_parenthesis' is increased, with '(' and dec...
def str_after_last(src, sub): """Return a substring from the last occurrence of the substring sub to the end of the string""" idx = src.rfind(sub) return src[idx + len(sub):] if idx >= 0 else ""
def point2knob(p, dims): """convert point form (single integer) to knob form (vector)""" knob = [] for dim in dims: knob.append(p % dim) p //= dim return knob
def gen_cubemap_data(cub_npix = 128): """Generate the camera for the cubemap views """ #================= CAMERA CUBEMAP DATA ===================== #The wide sensor is about 3 degrees per pixel #If we put the cubemap at 64 px it will be 1.4 deg/px #theta phi in spherical, alpha beta in Y X extrinsic...
def chainUpdate(l, value, position): """Update a list and return it.""" l[position] = value return l
def energy_remaining(distance): """Energy remaining after dissipation from emetor to receptor""" energy=1/distance return(energy)
def euleriteration(xi, yi, h, f): """Performs one iteration of Euler's method. Args: xi (float): The previous x value yi (float): The previous y value h (float): The step size f (function): The derivative of y at That is, y' = f(x,y). f must be a defined before as function of x ...
def interval_data_from_time_series(data, use_left_endpoint=False): """ This function converts time series data to piecewise constant interval data. A series of N time points and values yields N-1 intervals. By default, each interval takes the value of its right endpoint. In: ([t0, ...],...
def getNumbers(st): """It extracts float values for the price from a string. Ex. it extracts 10.99 from '$10.99' or 'starting at $10.99' """ st = str(st) ans = "" for ch in st: if (ch >= "0" and ch <= "9") or ch == ".": ans += ch try: ans = float(ans) except: ...
def update_with_default(params: dict, default_params: dict) -> dict: """ Fills in a dictionary of paramters with values from a dictionary of default parameters """ for key in default_params: params[key] = params.pop(key, default_params[key]) return params
def _get_updated_display_names(attr_name, new_val, old_val): """Get difference between old and new display names data""" new_links = set() old_links = set() for val in new_val: new_links.add(val.get("display_name", "")) for val in old_val: old_links.add(val.get("display_name", "")) return ( at...
def lfu_for_evict(cache_dict, evict_number=1): """ Use LFU(Least Frequently Used) strategy for evicting, the item that number of hits is the least will be removed. Test: >>> from common_cache import CacheItem >>> dict = {} >>> dict['a'] = CacheItem(key='a', value=0, expire=5) >>> dict['b'] ...
def rating_calc(item, ocurrences, last_ocurrences, total_ocurrences): """ Calculates the rating of the target language. """ rating = ocurrences / total_ocurrences if item in last_ocurrences: rating *= 2 if last_ocurrences and item == last_ocurrences[-1]: rating *= 4 return rating
def p1sp1m1function1(param1): """ function in a subpackage""" print("##### start p1sp1m1function1 in package1/subpackage1/p1sp1module1") res = param1 *10 return res
def mangle_string(name): """Take a string and make it a valid python module name. This is used for block names and versions. """ return name.lower().replace('-','_').replace('.', '_').replace(' ', '')
def ec_url(main_object): """Return URL entity in Demisto format for use in entry context Parameters ---------- main_object : dict The main object from a report's contents. Returns ------- dict URL object populated by report contents. """ url = main_object.get('url'...
def check_add_param(params): """check add type param""" success = True required_params = ["repo", "branch", "scm_repo", "scm_branch", "version_control", "enabled"] miss_params = list() for param in required_params: if param not in params or not params[param]: miss_params.append(p...
def time2id(parts): """ Combine a broken-up message identifier into a numeric one parts is a MessageID instance (or any 3-sequence); the return value is an integer. """ ts, ms, seq = parts return ts * 1024000 + ms * 1024 + seq
def darken(color, ratio=0.5): """Creates a darker version of a color given by an RGB triplet. This is done by mixing the original color with black using the given ratio. A ratio of 1.0 will yield a completely black color, a ratio of 0.0 will yield the original color. The alpha values are left intact. ...
def insert_sort(data): """Sort data via insertion.""" try: idx = 0 count = 1 for x in data[1:]: if not isinstance(x, type(data[idx])): raise TypeError() while x < data[idx]: data[idx], data[idx + 1] = data[idx + 1], data[idx] ...
def lcs_matrix(s1, s2): """ Compute the lcs matrix for s1 vs s2 s1 : sequence (of len m) s2 : sequence (of len n) return lcs_matrix[1:n][1:m] (list of list) This is not the fastest, nor the more memory efficient way to compute a lcs in many cases. It is a quadratic algorithm both in time ...
def get_metrics_str__(metrics_list, batch_or_cum_metrics, validation_dataset=False): """ internal helper functions: formats metrics for printing to console """ metrics_str = '' for i, metric in enumerate(metrics_list): if i > 0: metrics_str += ' - %s: %.4f' % (metrics_list[i], batch_or_...
def data_relay(state): """Relay state data format""" return 'close' if state else 'open'
def shell_quote(s): """ Escape quotes in shell variable names """ s = s.replace("'", "'\\''") return s.replace('"', '"\\""')
def is_valid(ticket, rules): """ Check if a ticket is valid by checking if all numbers on the ticket match at least one rule - outer all: all numbers must match at least one rule - middle any: number must match at least one of the rules e.g. "seat" or "class" - inner any: number must match at least ...
def build_hgnc_transcript(transcript_info): """Build a hgnc_transcript object Args: transcript_info(dict): Transcript information Returns: transcript_obj(HgncTranscript) { ensembl_transcript_id: str, required refseq_id: str, ...
def ERR_INVITEONLYCHAN(sender, receipient, message): """ Error Code 473 """ return "ERROR from <" + sender + ">: " + message
def check_array(arrays, nums): """Array can be either row or column""" for array in arrays: # for row in rows or col in cols win = all(i in nums for i in array) if win: return True return False
def _find_all(target_or_targets, name_or_provider): """Returns a list with all of the given provider from one or more targets. This function supports legacy providers (referenced by name) and modern providers (referenced by their provider object). Args: target_or_targets: A target or list of targets whose...
def convert_to_minutes(num_hours): """ (int) -> int Return the number of minutes there are in num_hours hours. >>> convert_to_minutes(2) 120 """ result = num_hours * 60 return result
def bpe_postprocess(string): """ Post-processor for BPE output. Recombines BPE-split tokens. :param string: :return: """ return string.replace("@@ ", "")
def parse_range(arg,dtype=int): """Parse argument of type (0,10), [0,10]""" try: # Remove brackets and recombine x = ''.join(arg[1:-1]) # Get rid of the comma x = x.split(',') # Convert to given data type return dtype(x[0]), dtype(x[-1]) except ValueError: ...