content
stringlengths
42
6.51k
def is_test_file_name(file_name): """ Returns whether the given file name is the name of a test file. Parameters ---------- file_name : `str` A file's name. Returns ------- is_test_file_name : `bool` """ if file_name == 'test.py': return True if file_name.startswith('test_') and file_name.endswith('.py'): return True if file_name.endswith('_tests.py'): return True return False
def get_exchange_name(cls): """Returns the exchange name of the given class, or None""" return getattr(cls, '__exchange_name__', None)
def GassmannModel(Phi, Kdry, Gdry, Kmat, Kfl): """ GASSMANN MODEL Gassmann's equations. Written by Dario Grana (August 2020) Parameters ---------- Phi : float or array_like Porosity (unitless). Kdry : float Bulk modulus of dry rock (GPa). Gdry : float Shear modulus of dry rock (GPa). Kmat : float Bulk modulus of solid phase (GPa). Kfl : float Bulk modulus of the fluid phase (GPa). Returns ------- Ksat : float or array_like Bulk modulus of saturated rock (GPa). Gsat : float or array_like Shear modulus of saturated rock (GPa). References: Grana, Mukerji, Doyen, 2021, Seismic Reservoir Modeling: Wiley - Chapter 2.6 """ # Bulk modulus of saturated rock Ksat = Kdry + ((1 - Kdry / Kmat) ** 2) / (Phi / Kfl + (1 - Phi) / Kmat - Kdry / (Kmat ** 2)) # Shear modulus of saturated rock Gsat = Gdry return Ksat, Gsat
def tri_state_value(tri_state: str) -> bool: """Returns whether a tri-state code turns a switch on or off. :param tri_state: The tri-state code. :type tri_state: str :returns: True if the tri-state codes turns a switch on, False otherwise. :rtype: str """ return 'F' == tri_state[-1:]
def _IsPemSectionMarker(line): """Returns (begin:bool, end:bool, name:str).""" if line.startswith('-----BEGIN ') and line.endswith('-----'): return True, False, line[11:-5] elif line.startswith('-----END ') and line.endswith('-----'): return False, True, line[9:-5] else: return False, False, ''
def search_for_vowels_return_data(word): """Return data based on any vowels found.""" vowels = set('aeiou') return vowels.intersection(set(word))
def _find_by_prior_token(tokens, keys): """ If any key in keys appears in tokens, return the token following said key. If more than one key in keys matches, use the first matching key in keys. Otherwise, return None. """ # Determine which key matches match_key = None for key in keys: if key in tokens: match_key = key break else: return None # Determine the index of the following token index = tokens.index(match_key) + 1 if index >= len(tokens): return None return tokens[index]
def tail(sequence): """ Returns the slice of *sequence* containing all elements after the first. """ return sequence[1:]
def is_cast(field_spec): """ is this spec requires casting :param field_spec: to check :return: true or false """ if not isinstance(field_spec, dict): return False config = field_spec.get('config', {}) return 'cast' in config
def get_particles(words, _lines): """parser particles command""" if len(words) <= 0: raise Exception("Decay need particles") name = words[0] return ("Particle", {"name": name, "params": words[1:]})
def sanitize_list_values(value): """Parse a string of list items to a Python list. This is super hacky... :param str value: string-representation of a Python list :return: List of strings :rtype: list """ if not value: return [] if value.startswith("["): value = value[1:] if value.endswith("]"): value = value[:-1] if not value: return [] raw_values = [v.strip() for v in value.split(",")] return [v.strip('"') for v in raw_values]
def two_complement_2_decimal(value, n_bits): """Converts a two's component binary integer into a decimal integer.""" for current_bit in range(n_bits): bit = (value >> current_bit) & 1 if bit == 1: left_part = value >> (current_bit + 1) left_mask = 2**(n_bits - (current_bit + 1)) - 1 right_mask = 2**(current_bit + 1)-1 right_part = value & right_mask out = ((~left_part & left_mask) << (current_bit + 1)) + right_part if out >> (n_bits - 1): out = -value return out return 0
def getFieldShortName(field_name): """ Simplifies `field_name` in the exported dataframe by removing Watson Assistant prefixes """ return field_name.replace('request.','').replace('response.','').replace('context.system.','').replace('context.','')
def convert_power_to_energy(power_col, sample_rate_min="10T"): """ Compute energy [kWh] from power [kw] and return the data column Args: df(:obj:`pandas.DataFrame`): the existing data frame to append to col(:obj:`string`): Power column to use if not power_kw sample_rate_min(:obj:`float`): Sampling rate in minutes to use for conversion, if not ten minutes Returns: :obj:`pandas.Series`: Energy in kWh that matches the length of the input data frame 'df' """ time_conversion = {"1T": 1.0, "5T": 5.0, "10T": 10.0, "30T": 30.0, "1H": 60.0} energy_kwh = power_col * time_conversion[sample_rate_min] / 60.0 return energy_kwh
def toggleprefix(s): """Remove - prefix is existing, or add if missing.""" return ((s[:1] == '-') and [s[1:]] or ["-"+s])[0]
def reverse(lst): """ Helping function for convex_hull() that reverses the order of a list pre: lst is a python list post: returns a list which is a mirror image of lst (lst is reversed) """ new_lst = [] for i in range(len(lst) - 1, -1, -1): new_lst.append(lst[i]) return new_lst
def _list_complement(A, B): """Returns the relative complement of A in B (also denoted as A\\B)""" return list(set(B) - set(A))
def non_repeating_substring(str1: str) -> int: """ This problem follows the Sliding Window pattern, and we can use a similar dynamic sliding window strategy as discussed in Longest Substring with K Distinct Characters. We can use a HashMap to remember the last index of each character we have processed. Whenever we get a repeating character, we will shrink our sliding window to ensure that we always have distinct characters in the sliding window. Time Complexity: O(N) Space Complexity: O(1) Parameters ---------- str1 : str input string Returns ------- max_length : int the length of the longest substring without any repeating character """ max_length = 0 seen = {} window_start = 0 for window_end in range(len(str1)): right_char = str1[window_end] if right_char in seen: window_start = max(window_start, seen[right_char] + 1) seen[right_char] = window_end max_length = max(max_length, window_end - window_start + 1) return max_length
def _get_instance_id_from_arn(arn): """ Parses the arn to return only the instance id Args: arn (str) : EC2 arn Returns: EC2 Instance id """ return arn.split('/')[-1]
def _parse_boolean(value, default=False): """ Attempt to cast *value* into a bool, returning *default* if it fails. """ if value is None: return default try: return bool(value) except ValueError: return default
def get_hertz(reg, key): """Returns the hertz for the given key and register""" return int(reg * 2 ** (key / 12))
def removeParenthesis(s): """ Remove parentheses from a string. Params ------ s (str): String with parenthesis. """ for p in ('(', ')'): s = s.replace(p, '') return s
def signal_initialization(signature): """Generate the Signal initialization from the function signature.""" paren_pos = signature.find('(') name = signature[:paren_pos] parameters = signature[paren_pos:] return f' {name} = Signal{parameters}\n'
def run_program(program, opcode_pos): """ Runs a supplide Intcode program. >>> run_program([1,0,0,0,99]) [2,0,0,0,99] """ opcode = program[opcode_pos] if opcode == 99: return program operand1 = program[program[opcode_pos + 1]] operand2 = program[program[opcode_pos + 2]] target = program[opcode_pos + 3] new_program = list(program) if opcode == 1: new_program[target] = operand1 + operand2 elif opcode == 2: new_program[target] = operand1 * operand2 else: raise BaseException("Unknown opcode") return run_program(new_program, opcode_pos + 4)
def to_int(inp): """ returns items converted to int if possible also works for tuples\n also works recursively watch out because passing a string '12t' will be ripped into a list [1,2,t] """ if isinstance(inp[0],list): return tuple(to_int(l) for l in inp) if isinstance(inp[0],tuple): return tuple(to_int(l) for l in inp) out = [] for i in inp: try: out.append(int(i)) except ValueError: out.append(i) if isinstance(inp,tuple): return tuple(out) else: return tuple(out)
def normalize_pipeline_name(name=''): """Translate unsafe characters to underscores.""" normalized_name = name for bad in '\\/?%#': normalized_name = normalized_name.replace(bad, '_') return normalized_name
def rescale(value, orig_min, orig_max, new_min, new_max): """ Rescales a `value` in the old range defined by `orig_min` and `orig_max`, to the new range `new_min` and `new_max`. Assumes that `orig_min` <= value <= `orig_max`. Parameters ---------- value: float, default=None The value to be rescaled. orig_min: float, default=None The minimum of the original range. orig_max: float, default=None The minimum of the original range. new_min: float, default=None The minimum of the new range. new_max: float, default=None The minimum of the new range. Returns ---------- new_value: float The rescaled value. """ orig_span = orig_max - orig_min new_span = new_max - new_min try: scaled_value = float(value - orig_min) / float(orig_span) except ZeroDivisionError: orig_span += 1e-6 scaled_value = float(value - orig_min) / float(orig_span) return new_min + (scaled_value * new_span)
def merge_mappings(target, other, function=lambda x, y: x + y): """ Merge two mappings into a single mapping. The set of keys in both mappings must be equal. """ assert set(target) == set(other), 'keys must match' return {k: function(v, other[k]) for k, v in target.items()}
def encapsulate_name(name): """ Encapsulates a string in quotes and brackets """ return '[\"'+name+'\"]'
def handle_config_cases(some_config): # C """ Simply used to standardise the possible config entries. We always want a list """ if type(some_config) is list: return some_config if some_config is None: return [] else: return [some_config]
def get_dict_buildin(dict_obj, _types=(int, float, bool, str, list, tuple, set, dict)): """ get a dictionary from value, ignore non-buildin object """ ignore = {key for key in dict_obj if not isinstance(dict_obj[key], _types)} return {key: dict_obj[key] for key in dict_obj if key not in ignore}
def lfilter(*args, **kwargs): """Take filter generator and make a list for Python 3 work""" return list(filter(*args, **kwargs))
def get_struct_neighbors(grid, structure_num, proximity): """Given a grid of structures, returns the closest proximity neighbors to the given structure params: - Grid: 2D numpy array - structure_num: int - proximity: int :returns - A list of neighboring structures to the current structure_num """ # Get the number of columns for ease of access width = len(grid) height = len(grid[0]) # We'll make it a set initially to avoid duplicate neighbors neighbors = set() for i in range(-proximity, proximity + 1): for j in range(-proximity, proximity + 1): if not (i == 0 and j == 0): x = min(max((structure_num // height) - i, 0), width - 1) y = min(max((structure_num % height) - j, 0), height - 1) if grid[x][y] != structure_num: neighbors.add(grid[x][y]) return list(neighbors)
def res_spec2res_no(res_spec): """simple extraction function""" if not res_spec: return False if (len(res_spec) == 4): return res_spec[2] if (len(res_spec) == 3): return res_spec[1] return False
def __formulate_possible_contexts(doctype=None, docname=None, fieldname=None, parenttype=None, parent=None): """ Possible Contexts in Precedence Order: key:doctype:name:fieldname key:doctype:name key:parenttype:parent key:doctype:fieldname key:doctype key:parenttype """ contexts = [] if doctype and docname and fieldname: contexts.append(f'{doctype}:{docname}:{fieldname}') if doctype and docname: contexts.append(f'{doctype}:{docname}') if parenttype and parent: contexts.append(f'{parenttype}:{parent}') if doctype and fieldname: contexts.append(f'{doctype}:{fieldname}') if doctype: contexts.append(f'{doctype}') if parenttype: contexts.append(f'{parenttype}') return contexts
def construct_fip_id(subscription_id, group_name, lb_name, fip_name): """Build the future FrontEndId based on components name. """ return ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/frontendIPConfigurations/{}').format( subscription_id, group_name, lb_name, fip_name )
def vat_checksum(number): """ Calculate the check digit for romanian VAT numbers. """ weights = (7, 5, 3, 2, 1, 7, 5, 3, 2) number = (9 - len(number)) * '0' + number check = 10 * sum(w * int(n) for w, n in zip(weights, number)) return check % 11 % 10
def tasks_to_job_ids(task_list): """Returns the set of job IDs for the given tasks.""" return set([t.get_field('job-id') for t in task_list])
def reasoner_graph_to_cytoscape(graph): """Generate cytoscape spec for query graph.""" cs_graph = {} nodes = [] edges = [] for node in graph["nodes"]: cs_node = {} node_types = "" if isinstance(node["type"], str): node_types = node["type"] else: node_types = "\n".join(node["type"]) cs_node["data"] = { "id": node["id"], "label": node_types + "\n[" + node.get("curie", "") + "]", "curie": node.get("curie", ""), "type": node_types, } nodes.append(cs_node) for edge in graph["edges"]: cs_edge = { "data": { "id": edge["id"], "source": edge["source_id"], "target": edge["target_id"], "label": edge["type"], } } edges.append(cs_edge) cs_graph["elements"] = {"nodes": nodes, "edges": edges} cs_graph["style"] = [ { "selector": "node", "style": { "label": "data(label)", "color": "white", "background-color": "#60f", # #009 looks good too "shape": "rectangle", "text-valign": "center", "text-border-style": "solid", "text-border-width": 5, "text-border-color": "red", "width": "15em", "height": "5em", "text-wrap": "wrap", }, }, { "selector": "edge", "style": { "curve-style": "unbundled-bezier", # "control-point-distances": [20, -20], # "control-point-weights": [0.250, 0.75], "control-point-distances": [-20, 20], "control-point-weights": [0.5], "content": "data(label)", "line-color": "#808080", "target-arrow-color": "#808080", "target-arrow-shape": "triangle", "target-arrow-fill": "filled", }, }, ] return cs_graph
def find_zeroes(f, a, b, epsilon=1e-10): """ Find the zero-crossing of the function f in the interval [a, b]. The function assumes that there is a single zero-crossing in the interval. :param f: The function. :param a: The lower bound of the interval. :param b: The upper bound of the interval. :param epsilon: The stopping tolerance. When the interval is less that this, the function will return. Defaults to 1e-10. :return: The zero-crossing of f or None if there is no zero-crossing in the interval. """ # Guard against someone getting the ordering of a and b wrong. low = min(a, b) high = max(a, b) middle = (low + high) / 2 # Evaluate the functions, and store the results. We're doing this to reduce the number of function evaluations # that we need, in case the function is expensive to evaluate. f_low = f(low) f_high = f(high) f_middle = f(middle) # If there's no zero-crossing in the interval, then we're done. We can test this by looking at the sign of the # function evaluations at the bounds. If they're different, then there's a zero-crossing. An easy way to check # this is to multiply them together. If they signs are different, then their product is negative. If there's no # zero-crossing, return None. if f_low * f_high > 0: return None # If the interval is narrow enough, return the mid-point of it. This is the base case of the recursion. if abs(high - low) < epsilon: return middle # If we haven't hit the base case, then we have to recursively call the function. Pick the half of the interval # that contains the zero crossing, and call the function on that. We can do this by looking at the sign of the # function evaluated at the mid-point. If it's different from the function evaluated at the lower bound, then we # should keep the bottom half. if f_low * f_middle > 0: return find_zeroes(f, middle, high, epsilon) else: return find_zeroes(f, a, middle, epsilon)
def convert_dict_of_sets_to_dict_of_lists(dictionary): """ Returns the same dictionary, but the values being sets are now lists @param dictionary: {key: set(), ...} """ out = dict() for key, setvalue in dictionary: out[key] = list(setvalue) return out
def convert_celsius_to_fahrenheit(deg_celsius): """ Convert degress celsius to fahrenheit Returns float value - temp in fahrenheit Parameters: ----------- deg_celcius: float temp in degrees celsius Returns: ------- float """ return (9/5) * deg_celsius + 32
def has_only_valid_characters(hex: str) -> bool: """Return True if hex has only valid hexadecimal characters.""" _valid_hex_characters = set("#abcdef0123456789") return set(hex) <= _valid_hex_characters
def _is_png(filename): """Determine if a file contains a PNG format image. Args: filename: string, path of the image file. Returns: boolean indicating if the image is a PNG. """ return filename.endswith('.png')
def fix_v(value, other=False, dot=False): """ share.fix_v(T.trade_info()[1][1])) :param other: if True, the "()%:" will be removed :param dot: if True, the dot will be removed :param value: value is editing here :return: list of float number, first item is the value of the share, second of is the change with yesterday value and the last one is the percent of this change. """ value = value.replace(',', '') if other: value = value.replace('(', ' ') value = value.replace('-', ' ') value = value.replace(')', ' ') value = value.replace('%', '') value = value.replace(':', ' ') if dot: value = value.replace('.', '') # value = value.split(' ') # list(map(float, value.split())) return value
def shortcut_Euler_Tour(tour): """Find's the shortcut of the Euler Tour to obtain the Approximation. """ Tour = [] for vertex in tour: if vertex not in Tour: Tour.append(vertex) Tour.append(tour[0]) return Tour
def relative_refractive_index(n_core, n_clad): """ Calculate the relative refractive index (Delta) for an optical fiber. Args: n_core : the index of refraction of the fiber core [-] n_clad: the index of refraction of the fiber cladding [-] Returns: the relative refractive index (Delta) [-] """ return (n_core**2 - n_clad**2) / (2 * n_core**2)
def greet(friend, money): """Greet people. Say hi they are your friend. Give them $20 if they are your friend and you have enough money. Steal $10 from them if they are not your friend. """ if friend and (money > 20): print("Hi") money = money - 20 elif friend: print("Hello") else: print("Ha ha!") money = money + 10 return money
def valToBool(rawVal): """ Convert string or integer value from the config file or command line to a boolean. """ retVal = False if type(rawVal) == str: retVal = (rawVal.strip().strip('"').lower()[0] in ['y','t','1']) else: try: retVal = bool(rawVal) except: retVal = False return retVal
def lower_case(words): """ Set ALL words to LOWER case. """ return [w.lower() for w in words]
def get_epsilon_array(gamma_array): """Flip 0 and 1 for epsilon from gamma""" return list(map(lambda d: '1' if d == '0' else '0', gamma_array))
def refines_constraints(storage, constraints): """ Determines whether with the storage as basis for the substitution map there is a substitution that can be performed on the constraints, therefore refining them. :param storage: The storage basis for the substitution map :param constraints: The constraint list containing the expressions to be substituted. :return: True if the substitution would change the constraint list. """ storage_names = ["storage[" + str(key) + "]" for key, _ in storage.items()] for name in storage_names: for constraint in constraints: if name in constraint.slot_names: return True return False
def parse_authentication(authentication): """Split the given method:password field into its components. authentication (str): an authentication string as stored in the DB, for example "plaintext:password". return (str, str): the method and the payload raise (ValueError): when the authentication string is not valid. """ method, sep, payload = authentication.partition(":") if sep != ":": raise ValueError("Authentication string not parsable.") return method, payload
def createExpressionString(exprList): """Creates a string of expressions Keyword arguments: exprList -- List of expression strings Joins the expression strings to one String using as delimiter semicolon Returns string of expressions """ expressionString = ";".join(exprList) expressionString = ";" + expressionString + ";" return expressionString
def is_writable_file_like(obj): """return true if *obj* looks like a file object with a *write* method""" return callable(getattr(obj, 'write', None))
def extract_minor(chord): """Checks whether the given cord is specified as "minor". If so, it pops out the specifier and returns a boolean indicator along with the clean chord. E.g. ---- Am --> True, A B# --> False, B# F#m --> True, F# """ if chord[-1] == 'm': return True, chord[:-1] else: return False, chord
def split_in_words_and_lowercase(line): """Split a line of text into a list of lower-case words.""" parts = line.strip('\n').replace('-', ' ').replace("'", " ").replace('"', ' ').split() parts = [p.strip('",._;?!:()[]').lower() for p in parts] return [p for p in parts if p != '']
def set_dict_values(d, value): """ Return dict with same keys as `d` and all values equal to `value'. """ return dict.fromkeys(d, value)
def c(n, alpha, beta, x): """The third term of the recurrence relation from Wikipedia, * P_n-2^(a,b).""" term1 = 2 * (n + alpha - 1) term2 = (n + beta - 1) term3 = (2 * n + alpha + beta) return term1 * term2 * term3
def parse_line(data): """ Takes an IRC line and breaks it into the three main parts; the prefix, command, and parameters. It gets returned in the form of ``(prefix, command, params)``. This follows :rfc:`2812#section-2.3.1`, section 2.3.1 regarding message format. >>> message = ":nickname!myuser@myhost.net PRIVMSG #gerty :Hello!" >>> parse_line(message) ('nickname!myuser@myhost.net', 'PRIVMSG', ['#gerty', 'Hello!']) """ if data[0] == ":": prefix, data = data[1:].split(" ", 1) else: prefix = None if " :" in data: data, trailing = data.split(" :", 1) params = data.split() params.append(trailing) else: params = data.split() return prefix, params[0], params[1:]
def minkowski_distance(x, y, p=2): """ Calculates the minkowski distance between two points. PARAMETERS x - the first point y - the second point p - the order of the minkowski algorithm. Default = 2. This is equal to the euclidian distance. If the order is 1, it is equal to the manhatten distance. The higher the order, the closer it converges to the Chebyshev distance, which has p=infinity """ from math import pow assert(len(y)==len(x)) sum = 0 for i in range(len(x)): sum += abs(x[i]-y[i]) ** p return pow(sum, 1.0/float(p))
def parse_records(database_records): """ A helper method for converting a list of database record objects into a list of dictionaries, so they can be returned as JSON Param: database_records (a list of db.Model instances) Example: parse_records(User.query.all()) Returns: a list of dictionaries, each corresponding to a record, like... [ {"id": 1, "title": "Book 1"}, {"id": 2, "title": "Book 2"}, {"id": 3, "title": "Book 3"}, ] """ parsed_records = [] for record in database_records: print(record) parsed_record = record.__dict__ del parsed_record["_sa_instance_state"] parsed_records.append(parsed_record) return parsed_records
def create_distr_name(dep_vars=None, cond_vars=None) -> str: """ Creates a name based on the given variables of a distribution and the variables it is conditioned on :param dep_vars: The random variables of a distribution. x in p(x|z) :param cond_vars: The conditioned-on variables of a distribution. z in p(x|z) :return: A string of the name. """ name = '' if dep_vars: if not isinstance(dep_vars[0], list): name += ','.join([v.name for v in dep_vars]) else: dep_vars_x = dep_vars[0] dep_vars_y = dep_vars[1] name += ','.join([v.name for v in dep_vars_x + dep_vars_y]) if cond_vars: name += '|' + ','.join([v.name for v in cond_vars]) return name
def bisect_true_first(arr): """Binary search (first True) arr = [0, ..., 0, 1, ..., 1]. ^ """ lo, hi = 0, len(arr) while lo < hi: mid = lo + hi >> 1 if arr[mid]: hi = mid else: lo = mid + 1 return lo
def call_method(obj, methodName): """ Execute a method of an object using previously passed arguments with setarg filter """ method = getattr(obj, methodName) if hasattr(obj, '__call_arguments'): ret = method(*obj.__call_arguments) del obj.__call_arguments return ret return method()
def get_class_string(obj): """ Return the string identifying the class of the object (module + object name, joined by dots). It works both for classes and for class instances. """ import inspect if inspect.isclass(obj): return "{}.{}".format( obj.__module__, obj.__name__) else: return "{}.{}".format( obj.__module__, obj.__class__.__name__)
def get_total_categories(studios): """Gets total category counts. Args: studios (array-like): a list of studios, either as MongoDB representations or as dictionaries. Returns: A dictionary mapping each category to a total block count. """ categories = dict() for studio in studios: bc = studio["stats"]["total"]["block_categories"] for cat in bc: if cat not in categories: categories[cat] = 0 categories[cat] += bc[cat] return categories
def group_anagrams_ver1(strs: list) -> list: """Mine solution this is slower than the ver2 because the ver1 has one more for loop iteration.""" anagrams = [] for i, word in enumerate(strs): if i == 0: anagrams.append([word]) else: exist = False # Compare a word and the first element in anagram. for anagram in anagrams: chars = [char for char in word if char in anagram[0]] # Add a word to a anagram when have same letters and length if len(chars) == len(anagram[0]): anagram.append(word) exist = True else: continue # Add new anagram when a word can not belong to any anagram. if exist == False: anagrams.append([word]) return anagrams
def GetNextTokenIndex(tokens, pos): """Get the index of the next token after 'pos.'""" index = 0 while index < len(tokens): if (tokens[index].lineno, tokens[index].column) >= pos: break index += 1 return index
def _get_prefixes_for_action(action): """ :param action: iam:cat :return: [ "iam:", "iam:c", "iam:ca", "iam:cat" ] """ (technology, permission) = action.split(':') retval = ["{}:".format(technology)] phrase = "" for char in permission: newphrase = "{}{}".format(phrase, char) retval.append("{}:{}".format(technology,newphrase)) phrase = newphrase return retval
def door_from_loc(env, loc): """ Get the door index for a given location The door indices correspond to: right, down, left, up """ if loc == 'east' or loc == 'front': return (2, 1), 2 if loc == 'south' or loc == 'right': return (1, 2), 3 if loc == 'west' or loc == 'behind': return (0, 1), 0 if loc == 'north' or loc == 'left': return (1, 0), 1 assert False, 'door without location'
def make_node_bodies(objects, meta): """Return the node containing internationalized data.""" node = {} for body_id, body in objects.items(): node[body_id] = body return node
def bin_position(max_val): """ ` _ @ """ symbol_map = {0: " `", 1: " _", 2: " @"} if max_val <= 3: return [symbol_map[i] for i in range(max_val)] first = max_val // 3 second = 2 * first return [" `"] * first + [" _"] * (second - first) + [" @"] * (max_val - second)
def squareSum(upperLimit): """ Returns the square of the sum of [1,upperLimit] --param upperLimit : integer --return square of sums : integer """ totalSum = sum(list(range(1,upperLimit+1))) return (totalSum ** 2)
def calcular_costo_envio(kilometros): """ num -> num calcular el costo del envio cuando se trabaja fuera de la ciudad >>> calcular_costo_envio(500) 57500 >>> calcular_costo_envio(50) 5750 :param kilometros: num que representa los kilometros recorridos en el envio :return: num que representa el precio del costo de envio de por 115 """ recargo = (kilometros * 115) return recargo
def squareCoordsForSide(s): """ Square with side s origin = 0,0 """ coords = ( ( # path (0,0), (s,0), (s,s), (0,s), ), ) return coords
def transform_members_list_into_motif_dic(center_dic, members_dic_list, mdl_cost, mean_dist): """ This functions creates the dictionary related to the motif composed by the subsequences in members_dic_list :param center_dic: dictionary related to the center of motif :type center_dic: dic :param members_dic_list: list of dictionaries related to all the subsequences that belong to the motif :type members_dic_list: list of dic :param mdl_cost: MDL cost of the motif (as defined by Tanaka et all) :type mdl_cost: float :param mean_dist: mean distance between all the pair of motif's members :type mean_dist: float :return: motif_dic :rtype: dic """ members_ts_pointers = [dic['pointers'] for dic in members_dic_list] motif_dic = { 'pattern': center_dic['pattern'], 'mdl_cost': mdl_cost, 'mean_dist': mean_dist, 'members_ts_pointers': members_ts_pointers, 'center_ts_pointers': center_dic['pointers'] } return motif_dic
def wrap(x, m): """ Mathematical modulo; wraps x so that 0 <= wrap(x,m) < m. x can be negative. """ return (x % m + m) % m
def clean_label(labels): """ Remove undesired '' cases """ labels = list(filter(''.__ne__, labels)) return labels
def merge(seq1, seq2): """Merge two sorted arrays into a single array""" if not seq1 or not seq2: raise ValueError("Input sequences do not exist or empty") merged_size = len(seq1) + len(seq2) merged_seq = [None] * merged_size seq1_index = 0 seq2_index = 0 merged_index = 0 while merged_index < merged_size: is_first_seq_exhausted = seq1_index >= len(seq1) is_second_seq_exhausted = seq2_index >= len(seq2) if (not is_first_seq_exhausted) and ( is_second_seq_exhausted or seq1[seq1_index] <= seq2[seq2_index] ): merged_seq[merged_index] = seq1[seq1_index] seq1_index += 1 merged_index += 1 else: merged_seq[merged_index] = seq2[seq2_index] seq2_index += 1 merged_index += 1 return merged_seq
def lmap_call(func, args_seq): """map every func call and return list result >>> from operator import add >>> lmap_call(add, [(1, 2), (3, 4)]) [3, 7] """ result = [] for args in args_seq: result.append(func(*args)) return result
def get_data_version(str_hash, hash_dict): """ Obtain version string from hash :param str_hash: Hash string to check :param hash_dict: Dictionary with hashes for different blocks :return: List with version string and hash string """ str_version = 'Unknown' if 'versions' in hash_dict: hash_dict = hash_dict['versions'] for hash_elem in hash_dict: if str_hash == hash_dict[hash_elem]: str_version = hash_elem break return str_version
def split(list): """ Divide the unsorted list at midpoint into sublists Returns two sublists - left and right Take overall O(k log n) time """ mid = len(list)//2 left = list[:mid] right = list[mid:] return left, right
def apply_formatting(msg_obj, formatter): """ Receives a messages object from a thread and returns it with all the message bodies passed through FORMATTER. Not all formatting functions have to return a string. Refer to the documentation for each formatter. """ for x, obj in enumerate(msg_obj): if not msg_obj[x].get("send_raw"): msg_obj[x]["body"] = formatter(obj["body"]) return msg_obj
def subspan(arg1, arg2): """Return whether the (x,y) range indicated by arg1 is entirely contained in arg2 >>> subspan((1,2), (3,4)) False >>> subspan((1,3), (2,4)) False >>> subspan((3,4), (1,2)) False >>> subspan((2,4), (1,3)) False >>> subspan((1,4), (2,3)) False >>> subspan((2,3), (1,4)) True >>> subspan((1,4), (1,4)) True """ if arg1 == arg2: # ignores two identical matching strings return True beg1, end1 = arg1 beg2, end2 = arg2 return (beg1 >= beg2) and (end1 <= end2) and ((beg1 != beg2) or (end1 != end2))
def chunks(lst, *lens): """Split the supplied list into sub-lists of the given lengths, and return the list of sub-lists.""" retval = [] start = 0 for n in lens: retval.append(lst[start:start + n]) start += n return retval
def new_file_path(photo_date): """ Get the new file path for the photo. An example would be 2019/January/31st :param photo_date: The list for the date that is supplied from the exif data :return: Array of all the new file paths """ if len(photo_date) == 3: month = photo_date[0] day = int(photo_date[1]) year = int(photo_date[2]) if day in (1, 21, 31): new_day = str(day) + "st" elif day in (2, 22): new_day = str(day) + "nd" elif day == 23: new_day = str(day) + "rd" else: new_day = str(day) + "th" final_string = "./" + str(year) + "/" + str(month) + "/" + str(month) + "-" + str(new_day) return final_string
def _strip_unsafe_kubernetes_special_chars(string: str) -> str: """ Kubernetes only supports lowercase alphanumeric characters, "-" and "." in the pod name. However, there are special rules about how "-" and "." can be used so let's only keep alphanumeric chars see here for detail: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/ :param string: The requested Pod name :return: Pod name stripped of any unsafe characters """ return ''.join(ch.lower() for ch in list(string) if ch.isalnum())
def R6(FMmin, alpha_A): """ R6 Determining the maximum assembly preload FMmax (Sec 5.4.3) --- FMmin : alpha_A : """ # FMmax = alpha_A * FMmin # (R6/1) # return FMmax #
def convert_ft_to_in(len_ft): """Function to convert length in ft to inches""" ans = len_ft * 12 return round(ans,2)
def check_vulnerable_package(version, version_string): """Check if the request version available in vulnerable_versions.""" if(version in version_string.split(",")): return True return False
def is_anno_moderate(anno): """ Check if the difficulty of the KITTI annotation is "moderate" Args: anno: KITTI annotation Returns: bool if "moderate" """ height = anno['bbox'][3] - anno['bbox'][1] if (anno['occluded'] > 1) or (anno['truncated'] > 0.30) or height < 25: return False return True
def create_grid(taille): """ Function that generate a grid of size: taille*taille The grid is empty (only ' ') """ game_grid = [] for i in range(0,taille): game_grid.append([' ' for j in range(taille)]) return game_grid
def builtin_2swap(a, b, c, d): """Modify the stack: ( a b c d -- c d a b ).""" return (c, d, a, b)
def all_to_bytes(some_type): """Makes UTF-8 string from bytes, int, float""" if isinstance(some_type, bytes): return some_type elif isinstance(some_type, int): return str(some_type).encode() elif isinstance(some_type, float): return str(some_type).encode() else: return some_type.encode()
def set_r0_multiplier(params_dict, mul): """[summary] Args: params_dict (dict): model parameters mul (float): float to multiply lockdown_R0 by to get post_lockdown_R0 Returns: dict: model parameters with a post_lockdown_R0 """ new_params = params_dict.copy() new_params['post_lockdown_R0']= params_dict['lockdown_R0']*mul return new_params
def normalize( p ): """ Naive renormalization of probabilities """ S = sum( p ) return [ pr/S for pr in p ]
def get_api_url(remote): """ Default Artifactory API URL, based on remote name :param remote: Remote name (e.g. bincrafters) :return: Artifactory URL """ return f"https://{remote}.jfrog.io/artifactory/api"
def swap_position(string, pos1, pos2): """ swap position X with position Y means that the letters at indexes X and Y (counting from 0) should be swapped. """ new_string = list(string) new_string[pos1] = string[pos2] new_string[pos2] = string[pos1] return ''.join(new_string)
def flatten(x, par = '', sep ='.'): """ Recursively flatten dictionary with parent key separator Use to flatten augmentation labels in DataFrame output Args: x (dict): with nested dictionaries. par (str): parent key placeholder for subsequent levels from root sep (str: '.', '|', etc): separator Returns: Flattened dictionary Example: x = {'Cookies' : {'milk' : 'Yes', 'beer' : 'No'}} par, sep = <defaults> output = {'Cookies.milk' : 'Yes', 'Cookies.beer' : 'No'} """ store = {} for k,v in x.items(): if isinstance(v,dict): store = {**store, **flatten(v, par = par + sep + k if par else k)} else: store[par + sep + k] = v return store