content
stringlengths
42
6.51k
def modified_score_per_led(led_map): """ Get the modified score per LED. Ignore (remove) LEDs that hit no surface. The reflection value is used in the following way: new_heuristic_score = Shading Score * Tris Hit NO LONGER IN USE --> new_heuristic_score = 'Mean angle of the LED...
def replace_semicolons(s, replace_with=":"): """Replace semicolons with colons.""" return s.replace(";", replace_with)
def _num_items_2_ridge_ylimit(n): """ uses linear regression model to infer adequate figsize from the number of boxes in a boxplot Data used for training: X = [1, 3, 4, 6, 8, 11, 14, 16, 19, 22, 24] y = [.15, 0.5, 0.6, 0.9, 1.18, 1.7, 2.1, 2.4, 2.85, 3.3, 3.7] Parameters --------...
def sumDicts(*dicts): """Sums up dicts. sumDicts({'Hanswurs':777777}, {'Peter': 0.3}, {}, {'Hanswurs':-777775, 'Peter':0.9}) ==> {'Hanswurs': 2, 'Peter': 1.2} """ tmpDict = dict() keyList = list() keys = [e.keys() for e in dicts] for sublist in...
def _construct_rel_error_list(correct_results, actual_results, printer=None, verbose=False): """ Construct a list providing the relative utility error for each term in actual_results. Each term in actual_results must be present in correct_results. :param correct_results: The correct utility for each ter...
def keys_by_value(dct, func): """ return dictionary keys for specific values """ return frozenset(key for key, val in dct.items() if func(val))
def _app_id(app_id): """ Make sure the app_id is in the correct format. """ if app_id[0] != "/": app_id = "/{}".format(app_id) return app_id
def replace_none(params): """replace_none""" if params == "None": return None if isinstance(params, dict): for key, value in params.items(): params[key] = replace_none(value) if key == "split_char" and isinstance(value, str): try: ...
def get_node(i, j, ncol): """Assign a unique, consecutive number for each i, j location""" return i * ncol + j
def _bool(value): """Return env var cast as boolean.""" if isinstance(value, bool): return value return value is not None and value.lower() not in ( "false", "0", "no", "n", "f", "none", )
def _split_left(val, sep): """Split a string by a delimiter which can be escaped by \\""" result = [] temp = u"" escaped = False index = 0 left = True for c in val: left = False temp += c if c == sep[index] and not escaped: index += 1 else: ...
def readable_timedelta(days): # insert your docstring here """Returns a string of the number of week(s) and day(s) in the given days. Args: days (int): number of days to convert """ weeks = days // 7 remainder = days % 7 return "{} week(s) and {} day(s)".format(weeks, remainder)
def merge_params(list1, list2): """ Function to merge two list of params """ res = {} output = [] for item in list1: res[item['ParameterKey']] = item['ParameterValue'] for item in list2: res[item['ParameterKey']] = item['ParameterValue'] for item in res: ...
def encode_mode(mode): """ JJ2 uses numbers instead of strings, but strings are easier for humans to work with CANNOT use spaces here, as list server scripts may not expect spaces in modes in port 10057 response :param mode: Mode number as sent by the client :return: Mode string """ if...
def split_lines(text): """" Splits each line in the specified text into different cols. """ datatxt = [] # For each line in the file for line in text.split('\n'): # Split on tab col = line.split('\t') # Remove invalid records if len(col) != 2: contin...
def db_to_float(db, using_amplitude=True): """ Converts the input db to a float, which represents the equivalent ratio in power. """ db = float(db) if using_amplitude: return 10 ** (db / 20) else: # using power return 10 ** (db / 10)
def read_first_number(line): """Get the first number from a line.""" try: return int(line.split()[0]) except ValueError: return None
def parse_charoffset(charoffset): """ Parse charoffset to a tuple containing start and end indices. Example: charoffset = '3-7;8-9' [[3, 7], [8, 9]] """ # try split by ';' charoffsets = charoffset.split(';') return [[int(x.strip()) for x in offset.split('-')] for off...
def ObscureEmails(emails, domains): """Obscures the given emails that are in the given domains.""" obscured_emails = [] for email in emails: if not email: obscured_emails.append(email) continue parts = email.split('@', 2) if len(parts) < 2 or parts[1] in domains: # For any allowed Ap...
def get_sigma2(mu): """ returns variance of activity mu """ return mu * (1. - mu)
def return_this(anything: dict): """ returns the value in the "This" key. :param anything: :return: """ return anything["This"]
def inchi_formula(ich): """ gets the formula from an inchi string """ formula = ich.split('/')[1] return formula
def str_tspec(tspec, arg_names): """ Turn a single tspec into human readable form""" # an all "False" will convert to an empty string unless we do the following # where we create an all False tuple of the appropriate length if tspec==tuple([False]*len(arg_names)): return "(nothing)" return "...
def calc_answer(doc, perm, keys): """All permutations are ANDED """ ans = True for idx, key in enumerate(keys): if doc[key] != perm[idx]: ans = False break return ans
def choose(n, k): """ return the binomial coefficient of n over k """ def rangeprod(k, n): """ returns the product of all the integers in {k,k+1,...,n} """ res = 1 for t in range(k, n+1): res *= t return res if (n < k): ...
def get_type(formula_type: str) -> str: """ Get the kind of homebrew resource the formula refers to :param formula_type: Type of formula :return: Kind of Resource: either of Bottle, Application or unknown """ kind = "Unknown" if formula_type == "brew": kind = "Bottle" if formula_...
def str_to_bool (s): """ Given a string, parses out whether it is meant to be True or not """ s = str(s).lower() # Make sure if s in ['true', 't', 'yes', 'y', 'on', 'enable', 'enabled', 'ok', 'okay', '1', 'allow', 'allowed']: return True try: r = 10 if s.startswith("0x"): s = s[...
def camelize(s): """Camelize a str that uses _ as a camelize token. :param s: The str to camelize that contains a _ at each index where a new camelized word starts. :returns: The camelized str. """ return ''.join(s.replace('_', ' ').title().split())
def delta_set(x_prime, m): """ Returns the set of all the ordered pairs having an input x-or equal to x_prime. It is the set of the ordered pairs (x, x_prime + x) modulo 2. m is the number of elements of the substitution box. """ delta = set() for x in range(m): delta.add((x, x ^ x_p...
def get_fname(fileish): """ Return filename from `fileish` """ if isinstance(fileish, str): return fileish return getattr(fileish, 'name', "<file object>")
def convert_km_to_m(km_distance): """Function that converts distance in km to m!""" _ = km_distance * 10**3 return _
def unique(seq): """This utility method comes straight out of the Python Cookbook 2nd edition recipe 18.1 It returns the sequence removing any duplicate items, this depends of course on the sequence items actually implementing some form of comparison. It tries three methods, fastest to slow. See recipe for...
def _constant_schedule(epoch: int, start_epoch: int, swa_lr: float, init_lr: float) -> float: """ Calculate the updated learning rate which change by constant factor each step. :return: updated learning rate :rtype: float :param epoch: current epoch :param start_epoch: start epoch for SWAG ...
def pg_array_escape(tok): """ Escape a string that's meant to be in a Postgres array. We double-quote the string and escape backslashes and double-quotes. """ return '"%s"' % str(tok).replace('\\', '\\\\').replace('"', '\\\\"')
def string_to_int(msg): """Convert the string 'msg' to an integer. This function is the inverse of int_to_string(). """ # bytearray will give us the ASCII values for each character if not isinstance(msg, bytearray): msg = bytearray(msg) binmsg = [] # convert each character to binary...
def _handle_array(x): """Handle array or integer input argument for window functions Args: x (array_like, int): array or integer Returns: int: length of array or integer input """ if type(x) == int: N = x else: N = len(x) return N
def v_sub(v, w): """Subtracts two vectors :v: List 1 :w: List 2 :returns: List of subtracted vectors """ return [vi - wi for vi, wi in zip(v, w)]
def _filter_packages(package_versions, scoreboard_config): """Filter framework core packages from pip list. :param package_versions: List of packages installed by pip. :type package_versions: list :param scoreboard_config: Scoreboard configuration (documented in README.md). :type scoreboard_config:...
def all_attrs_missing(record): """Checks if all attributes have missing values, excluding ID and Class""" return all(value == '?' for value in record[1:-1])
def _format_date(dt): """ Returns formated date """ if dt is None: return dt return dt.strftime("%Y-%m-%d")
def ProximityOperator(kappa, a): """ The soft thresholding operator, used to enforce L1 regularization. It produces the solution to: \argmin_x 2 \kappa | x | + (x - a)^2 """ if a > kappa: return a - kappa elif a < -kappa: return a + kappa else: return 0.
def is_int(n): """Determines if a value is a valid integer""" try: int(n) return True except ValueError: return False
def as_list(value): """Returns value as a list If the value is not a list, it will be converted as a list containing one single item """ if isinstance(value, list): return value return [value]
def compare_project_names(p1: str, p2: str) -> bool: """Compares project names replacing `-` with `_`. Args: p1: project name p2: project name to compare to Returns: True if project names are the same, otherwise False Raises: None """ def replace(name): ...
def strip_lower_preparer(value): """Colander preparer that trims whitespace and converts to lowercase.""" if isinstance(value, str): return value.strip().lower() else: return value
def maximum(a, b): """ Finds the maximum of two numbers. >>> maximum(3, 2) 3 >>> maximum(2, 3) 3 >>> maximum(3, 3) 3 :param a: first number :param b: second number :return: maximum """ return a if a >= b else b
def table_log_format(timestamp, data): """ Return a formatted string for use in the log""" return str(timestamp) + '->[' + str(data) + ']'
def calc_tare_torque(rpm): """Returns tare torque array given RPM array.""" return 0.00104768276035*rpm - 0.848866229797
def _computenonoverlap(repo, c1, c2, addedinm1, addedinm2, baselabel=''): """Computes, based on addedinm1 and addedinm2, the files exclusive to c1 and c2. This is its own function so extensions can easily wrap this call to see what files mergecopies is about to process. Even though c1 and c2 are not us...
def es_parentesis(caracter): """ (str of len == 1) -> str >>> es_parentesis('(') 'Es parentesis' >>> es_parentesis('x') 'No es parentesis' >>> es_parentesis('xa') Traceback (most recent call last): .. TypeError: xa no es un parentesis :param caracter: str el caracter a eva...
def is_leap_year(year: int) -> bool: """Convenience function for determining if a year is a leap year. Args: year: The year to evaluate against leap year criteria Returns: whether or not the specified year is a leap year """ return (year % 400 == 0) or ((year % 4 == 0) and (year % ...
def create_importable_name(charm_name): """Convert a charm name to something that is importable in python.""" return charm_name.replace("-", "_")
def inv(bits): """invert a bit sequence. >>> assert inv([0, 0]) == [1, 1] >>> assert inv([1, 0]) == [0, 1] >>> assert inv([0, 1]) == [1, 0] >>> assert inv([1, 1]) == [0, 0] """ return [int(not b) for b in bits]
def _parse_table_name(table_name, schema=None): """Convenience to split a table name into schema and table or use the given schema. If a schema is passed it, it'll use that. Otherwise it'll try to parse it from the given name. For example 'schema.table_name' would be parsed into (table_name, schema) ...
def json_set_auths(recipe, auth): """Recusrsively finds auth in script JSON and sets them. Args: recipe: (dict) A dictionary representation fo the JSON script. auth: (string) Either 'service' or 'user'. Returns: (recipe) same structure but with all auth fields replaced. """ if isinst...
def hamming_distance(pattern, motiv): """ Calculates the Hamming-Distance of pattern and motiv """ if len(pattern) != len(motiv): return -1 hamming_distance = 0 for i in range(0, len(motiv)): if pattern[i] != motiv[i]: hamming_distance += 1 return hamming_distance
def cubicout(x): """Return the value at x of the 'cubic out' easing function between 0 and 1.""" return (x-1)**3 + 1
def truncateToUTR3(cds_end, exons): """ Truncates the gene to only target 3' UTR """ start_exon = 0 for exon in range(len(exons)): if (cds_end > exons[exon][1]) and (cds_end < exons[exon][2]): exons[exon][1] = cds_end start_exon = exon return exons[start_exon:]
def start_of_chunk(prev_tag, tag, prev_type, type_): """Checks if a chunk started between the previous and current word. Args: prev_tag: previous chunk tag. tag: current chunk tag. prev_type: previous type. type_: current type. Returns: chunk_start: boolean. """...
def split_path(str): """Splits a data path into rna + id. This is the core of creating controls for properties. """ # First split the last part of the dot-chain rna, path = str.rsplit('.',1) # If the last part contains a '][', it's a custom property for a collection item if '][' in path: ...
def tsv_cost_carb_yrmap(tsv_data, aeo_years): """Map 8760 TSV cost/carbon data years to AEO years. Args: tsv_data: TSV cost or carbon input datasets. aeo_years: AEO year range. Returns: Mapping between TSV cost/carbon data years and AEO years. """ # Set up a matrix mapping...
def same_party(party_1: dict, party_2: dict) -> bool: """Check that party name and address are identical (registering party is also secured party).""" if party_1['address'] != party_2['address']: return False if 'businessName' in party_1 and 'businessName' in party_2 and party_1['businessName'] == p...
def slugify(thing, these=('\n',), those=(' ',)) -> str: """Replace these (default: new lines) by those (default: space) and return string of thing.""" if not these or not those: return str(thing) if len(these) < len(those): raise ValueError('slugify called with more replacement targets than ...
def transform_cmds(argv): """ Allows usage with anaconda-project by remapping the argv list provided into arguments accepted by Bokeh 0.12.7 or later. """ replacements = {'--anaconda-project-host':'--allow-websocket-origin', '--anaconda-project-port': '--port', ...
def _totalValue(comb): """ Total a particular combination of items Args: comb tuple of items in the form (item, weight, value) Returns: tuple (total value, total weight) """ totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, totwt)
def format_key(key, title=True): """Return formatted key.""" key = ' '.join(key.split('_')) return key.title() if title and key.islower() else key
def hash_graph(graph): """Convert graph nodes to hashes (networkx is_isomorphic needs integer nodes).""" return {hash(key): [hash(value) for value in graph[key]] for key in graph}
def select_subscription(subs_code, subscriptions): """ Return the uwnetid.subscription object with the subs_code. """ if subs_code and subscriptions: for subs in subscriptions: if (subs.subscription_code == subs_code): return subs return None
def is_utriangular(A): """Tells whether a matrix is an upper triangular matrix or not. Args ---- A (compulsory) A matrix. Returns ------- bool True if the matrix is an upper triangular matrix, False otherwise. """ for i in range(len(A)): for j ...
def dot(vector1, vector2): """Dot product of vectors vector1 and vector2.""" return sum((a*b) for a, b in zip(vector1, vector2))
def solve_theta(theta, gamma, gainratio=1): """ solve theta_k1 from the equation (1-theta_k1)/theta_k1^gamma = gainratio * 1/theta_k^gamma using Newton's method, starting from theta """ ckg = theta**gamma / gainratio cta = theta eps = 1e-6 * theta phi = cta**gamma - ck...
def indicator_function_ei(X_i, M, X_nk_n): """Returns 1 if M is smaller or equal than X_nk_n and if X_nk_n is smaller than X_i, and 0 otherwise.""" return 1*(M <= X_nk_n < X_i)
def cdname_2_cdcategory(name, mapping): """ Applies a mapping to a triphone representation string in LC-P+RC form, returning a mapped string in the same form... """ splitr = name.split("+") substr = splitr[0] if len(splitr) == 2: rc = splitr[-1] else: rc = '' spl...
def statusFromList(alist, indent, func = None): """ generate a status message from the list of objects, using the specified function for formatting """ if func == None: func = lambda item : '(' + str(item['id']) + ') ' + item['nzbName'] status = '' if len(alist): i = 0 ...
def address_to_raw(address): """Converts a string representation of a MAC address to bytes""" return bytes([int(n, 16) for n in address.split(":")][::-1])
def _create_gcp_network_tag_id(vpc_partial_uri, tag): """ Generate an ID for a GCP network tag :param vpc_partial_uri: The VPC that this tag applies to :return: An ID for the GCP network tag """ return f"{vpc_partial_uri}/tags/{tag}"
def _darknet_parse_tshape(tshape): """Parse tshape in string.""" return [int(x.strip()) for x in tshape.strip('()').split(',')]
def set_port(port=None): """ This helper function gives the user the ability to set or not set the port""" if port: port = ":" + str(port) else: port="" return port
def param_to_str(param_name, keys): """Check the parameter is within the provided list and return the string name. """ if param_name.isdigit(): param_name = int(param_name) if param_name <= len(keys): param_name = keys[param_name - 1] else: raise ValueErro...
def delete(context, key): """Delete a key from the current task context.""" return context.pop(key, None)
def fmt_option_key(key, value): """Format a single keyword option.""" if value is None: return "" return f"{key}={value}"
def _recode_to_binary(char, keep_zero=False): """ Recodes a dictionary to binary data. :param char: A dictionary of taxa to state values :type char: dict :param keep_zero: A boolean flag denoting whether to treat '0' as a missing state or not. The default (False) is to ignore '0' a...
def drop_tables(name): """Returns string used to produce DROP statement. Parameters ---------- name : string indicates the name of the table to delete. Returns ------- query : string """ drop_string="DROP TABLE IF EXISTS " query=drop_string+name return query
def _scoped_name(name_scope, node_name): """Returns scoped name for a node as a string in the form '<scope>/<node name>'. Args: name_scope: a string representing a scope name, similar to that of tf.name_scope. node_name: a string representing the current node name. Returns A string representing a sc...
def _instance_tag(instance, tagname): """get name tag from instance.""" for kv in instance['Tags']: if kv['Key'] == tagname: return kv['Value'] return None
def all(p, xs): """Returns true if all elements of the list match the predicate, false if there are any that don't. Dispatches to the all method of the second argument, if present. Acts as a transducer if a transformer is given in list position""" for x in xs: if not p(x): return...
def deep_len(lst): """Return the depth of a list.""" return sum(deep_len(el) if isinstance(el, (list, tuple)) else 1 for el in lst)
def is_image_file(filename): """Check if a given file is an image file.""" return any([filename.endswith(img_type) for img_type in [".jpg", ".png", ".gif"]])
def other_side(end1): """ Changes scaffold end name from 'left' to 'right' and vice versa. """ name_parts = end1.split("_") if name_parts[0] == "left": end2 = "right_" + name_parts[1] elif name_parts[0] == "right": end2 = "left_" + name_parts[1] else: end2 = "other_si...
def sheet_cal(width, thickness, l_speed, s_density): """ Calculates the required throughput for sheets given the width, thickness, line speed, and solid polymer density Parameters ---------- width : int or float Sheet width [mm] thickness : int or float ...
def is_int(str_val): """ Check if str_val is int type :param str_val: str :return: bool """ if str_val.startswith('-') and str_val[1:].isdigit(): return True elif str_val.isdigit(): return True else: return False
def _extract_ansible_register(playbook_results, register_name): """ *NOTE: Subspace >= 0.5.0 required* Using 'PlaybookRunner.results', search for 'register_name' (as named in atmosphere-ansible task) Input: 'PlaybookRunner.results', 'name_of_register' Return: exit_code, stdout, stderr """ ...
def sparse_poly_to_integer(degrees, coeffs, order): """ Converts polynomial to decimal representation. Parameters ---------- degrees : array_like List of degrees of non-zero coefficients. coeffs : array_like List of non-zero coefficients. order : int The coefficient'...
def echo(mth, txt): """ This function echos back the first parameter (as a string) as a result transformed by the chosen method. """ if(mth == "echo"): return txt elif(mth == "reverse"): return txt[::-1] elif(mth == "uppercase"): return txt.upper() elif(mth == "lo...
def color_srgb_to_scene_linear(c): """ Convert from sRGB to scene linear color space. Source: Cycles addon implementation, node_color.h. """ if c < 0.04045: return 0.0 if c < 0.0 else c * (1.0 / 12.92) else: return pow((c + 0.055) * (1.0 / 1.055), 2.4)
def single_db2(server, args_array, **kwargs): """Method: single_db2 Description: Function stub holder for mongo_db_restore.single_db. Arguments: (input) server -> Server instance. (input) args_array -> Dictionary of arguments. """ status = True err_msg = "Dump Failure" ...
def royal_road1(individual, order): """Royal Road Function R1 as presented by Melanie Mitchell in : "An introduction to Genetic Algorithms". """ nelem = len(individual) // order max_value = int(2**order - 1) total = 0 for i in range(nelem): value = int("".join(map(str, individual[i*o...
def shunt(infix): """Return the infix regular expression in postfix.""" # Convert the input into a stack-ish reversed list infix = list(infix)[::-1] # Operator stack. opers = [] # Output list (postfix regular expression) postfix = [] # Operator precedence prec = {'*' : 100, '+' : ...
def is_basetype(value): """ Returns: (bool): True if value is a base type """ return isinstance(value, (int, float, str))
def func_linear(x, a, b): """ Simple linear function to use for scipy.curve_fit. """ return a + b * x