content
stringlengths
42
6.51k
def _sequence2num(sequence): """ Returns the input sequence as a number. """ if isinstance(sequence, str): sequence = int(sequence[2]) return sequence
def compare_solutions(dict_1, dict_2, keys): """ Compare solution obtained from NEMDE approximation with observed NEMDE solution. Keys and values in dict_1 are used as the basis. For each key specified in 'keys' the model and acutal NEMDE solution is compared. Keys in dict_1 but not in 'keys' have t...
def dot(v, u): """Compute dot product of vectors *v* and *u*.""" return sum(u[i] * v[i] for i in range(len(v)))
def unique_chars(word): """ Returns a sorted string containing the unique characters""" ordered = sorted(word) return "".join(ordered)
def update_config_resgrp(config): """load resource group related config info""" cnf_az_cluster = config["azure_cluster"] cnf_az_cluster["resource_group"] = cnf_az_cluster.get( "resource_group", config["cluster_name"] + "ResGrp") cnf_az_cluster["vnet_name"] = config["cluster_name"] + "-VNet" ...
def dic_lowest(dic): """ Gets the key with the lowest value in the dictionary. Parameters ---------- dic: The dictionary to get the lowest value out of Returns ------- The key with the lowest value in the dictionary. """ lowest = 100000000 s = "error" for sp in dic: if dic[sp] < lowest: lowest =...
def get_user_name(user_json): """Derive user name used in export from user profile JSON. User name is the bit of their login ID before the @. # e.g. "someuser@ourdomain.net" --> "someuser" It's possible that the user structure passed in will not have a login ID at all, in which case there is n...
def timestamp(): """Returns string with a current time timestamp""" import datetime return datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
def brightness_to_percentage(byt): """Convert brightness from absolute 0..255 to percentage.""" return int((byt * 100.0) / 255.0)
def check_shots_vs_bounds(shot_dict, mosaic_bounds, max_out_of_bounds = 3): """Checks whether all but *max_out_of_bounds* shots are within mosaic bounds Parameters ---------- shot_dict : dict A dictionary (see czd_utils.scancsv_to_dict()) with coordinates of all shots in a .scancsv file...
def f_to_c(f_temp): """ Converts from Farenheint to Celsius """ try: return (float(f_temp) - 32.0) * 5.0 / 9.0 except ValueError: return None
def mock_render_to_string(template_name, context): """ Return a string that encodes template_name and context """ return str((template_name, sorted(context.items())))
def union(a, b): """Returns a new list of the union between a and b""" return set(a) | set(b)
def name_value(obj): """ Convert (key, value) pairs to HAR format. """ return [{"name": k, "value": v} for k, v in obj.items()]
def group(s, n): """Repack iterator items into groups""" # See http://www.python.org/doc/2.6/library/functions.html#zip return list(zip(*[iter(s)] * n))
def float_range(start, stop=None, step=None): """Return a list containing an arithmetic progression of floats. Return a list of floats between 0.0 (or start) and stop with an increment of step. This is in functionality to python's range() built-in function but can accept float increments. A...
def string_to_functional(dict_string): """ Turn input string for function option into a (string, dictionary) representing the functional to be used in calculations. Args: dict_string: String that provides the string/float pairs, separated by a space. Returns: tuple: Tup...
def to_psql_array(lst): """ Convert lists to psql friendly format. """ return "{" + ",".join(map('{}'.format, lst)) + "}"
def check_game_over(boardPlaceTestList): """Check in the "boardPlaceTestList" if there is still a piece that can be placed on the board. If there is not, retrun gameOverTest as true else as false.""" gameOverTest = False for currentTest in boardPlaceTestList: if currentTest == True: ...
def merge(less, L, R): """ Merge two lists of tuples by their first element First argument is the comparison function returns true if arg1 is "less" than arg2 """ i = 0 k = 0 result = [] while i < len(L) or k < len(R): if i == len(L): result.append(R[k]) k += 1 elif k == len(R)...
def two_of_three(x, y, z): """Return a*a + b*b, where a and b are the two smallest members of the positive numbers x, y, and z. 1. Find minimum of all inputs 2. Find maximum of all minimums 3. Use ** as `to the power of` 4. Add them together >>> two_of_three(1, 2, 3) 5 >>> two_of_t...
def dict_diff(expected: dict, actual: dict) -> dict: """ :param expected: :param actual: :return: """ diff = {} for key in actual.keys(): if expected.get(key) is not actual.get(key): diff.update({key: actual.get(key)}) return diff
def is_requirement(line): """ Return True if the requirement line is a package requirement. Returns: bool: True if the line is not blank, a comment, a URL, or an included file """ return not ( line == '' or line.startswith('-r') or line.startswith('#') or lin...
def percentage(percent: float) -> str: """ Formats percentage into a string logged in stats :param percent: Percentage :return: formatted duration """ return "{:.2f}%".format(percent)
def _find_file(searched_file_name, rfiles): """Search for a filename in an array for {fname:fcontent} dicts""" for rfile in rfiles: if rfile.has_key(searched_file_name): return rfile return None
def hexagonal(n): """Returns the n-th hexagonal number""" return n*(2*n-1)
def datastore_start_cmd(port, assignment_options): """ Prepares command line arguments for starting a new datastore server. Args: port: An int - tcp port to start datastore server on. assignment_options: A dict containing assignment options from ZK. Returns: A list of command line arguments. """ ...
def _get_block_sizes_v1(resnet_size): """Retrieve the size of each block_layer in the ResNet model. The number of block layers used for the Resnet model varies according to the size of the model. This helper grabs the layer set we want, throwing an error if a non-standard size has been selected. Arg...
def variable_set_up_computer(num): """Return the computer's choice""" if num == 1: return 'The computer chose rock.' elif num == 2: return 'The computer chose paper.' elif num == 3: return 'The computer chose scissors.'
def skip_odd_numbers(value): """ Example filter function """ return value % 2 == 0
def kernel_sigmas(n_kernels, lamb, use_exact): """ get sigmas for each guassian kernel. :param n_kernels: number of kernels (including exactmath.) :param lamb: :param use_exact: :return: l_sigma, a list of simga """ bin_size = 2.0 / (n_kernels - 1) l_sigma = [0.00001] # for exact ma...
def fromStr(valstr): """try to parse as int, float or bool (and fallback to a string as last resort) Returns: an int, bool, float, str or byte array (for strings of hex digits) Args: valstr (string): A user provided string """ if(len(valstr) == 0): # Treat an emptystring as an empty b...
def fast_fib(n, memo = {}): """ Assume n is an int > 0, memo used only by recursive calls returns Fibonacci of n. """ if n == 0 or n == 1: return 1 try: return memo[n] except KeyError: result = fast_fib(n-1, memo) + fast_fib(n-2, memo) memo[n] = result ...
def is_project_in_server(server: dict, github_path: str) -> bool: """Check if project is in server""" # pylint: disable=use-a-generator return any( [project.get("githubPath") == github_path for project in server.get("projects", {})])
def stringify(val): """ Accepts either str or bytes and returns a str """ try: val = val.decode('utf-8') except (UnicodeDecodeError, AttributeError): pass return val
def markovToLatex(markov, labels, precision=2): """Prints the transition matrix in a latex format.""" lstring = '' # print the labels lstring += '\\text{' + str(labels[0]) + '}' for i in range(1, len(labels)): lstring += ' \\text{ ' + str(labels[i]) + '}' lstring += '\\\\\n' # h...
def input_to_list(input_data, capitalize_input=False): """ Helper function for handling input list or str from the user. Args: input_data (list or str): input from the user to handle. capitalize_input (boo): whether to capitalize the input list data or not. Returns: list: returns t...
def logout(session): """Logout If the user has a teamID in the session it is removed and success:1 is returned. If teamID is not in session success:0 is returned. """ if 'tid' in session: session.clear() return {"success": 1, "message": "Successfully logged out."} else: ...
def parse_unknown_args(**unk_args): """Parse kwargs like `dict(foo=False, bar=42)` into parameters like `--no-foo --bar 42`.""" parsed = [] for key, value in unk_args.items(): base_name = key.replace('_', '-') if isinstance(value, bool): # boolean values don't follow the norm...
def _flow_tuple_reversed(f_tuple): """Reversed tuple for flow (dst, src, dport, sport, proto)""" return (f_tuple[1], f_tuple[0], f_tuple[3], f_tuple[2], f_tuple[4])
def cmap(i, j, n): """Given a pair of feed indices, return the pair index. Parameters ---------- i, j : integer Feed index. n : integer Total number of feeds. Returns ------- pi : integer Pair index. """ if i <= j: return (n * (n + 1) // 2) - ((n...
def CFMtom3sec(VCFM): """ Convertie le debit volumique en CFM vers m3/sec Conversion: 2118.8799727597 CFM = 1 m3/sec :param VCFM: Debit volumique [CFM] :return Vm3sec: Debit volumique [m3/sec] """ Vm3sec = VCFM / 2118.8799727597 return Vm3sec
def getY(line, x): """ Get a y coordinate for a line """ m, c = line y = int((m * x) + c) return y
def job_name(job): """ find a friendly name for the job defined""" return '_'.join(j for j in job).replace('=', '-').replace('--','')
def _cubic_interpolation(x, xtab0, xtab1, ytab0, ytab1, yptab0, yptab1): """Cubic interpolation of tabular data. Translated from the cubeterp function in seekinterp.c, distributed with HEASOFT. Given a tabulated abcissa at two points xtab[] and a tabulated ordinate ytab[] (+derivative yptab[]) at ...
def format_data(account): """Format the account data into printable format.""" account_name = account["name"] account_descr = account["description"] account_country = account["country"] return f"{account_name}, a {account_descr} from {account_country}"
def dict_to_title(argmap): """ Converts a map of the relevant args to a title. """ # python 3, this will be sorted and deterministic. print(argmap) exclude_list = ["train-file", "classes-file", "val-file", "cmd", "role-file"] return "_".join([k + "=" + v for k, v in argmap.items() if k not in exclu...
def avg(num_1, num_2): """computes the average of two numbers""" return (num_1 + num_2) / 2.0
def select_proxy(scheme, host, port, proxies): """Select a proxy for the url, if applicable. :param scheme, host, port: The url being for the request :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs """ proxies = proxies or {} if host is None: return proxies.ge...
def get_segment_length(fs, resolution_shift=0): """ Calculates a segment length such that the frequency resolution of the resulting analysis is in the region of ~1Hz subject to a lower limit of the number of samples in the signal. For example, if we have a 10s signal with an fs is 500 then we convert fs...
def productExceptSelf(nums): """ :type nums: List[int] :rtype: List[int] """ arr = [1] for num in nums[:-1]: arr.append(num*arr[-1]) tmp = 1 for i in range(len(nums)-1, -1, -1): arr[i] = arr[i]*tmp tmp = tmp*nums[i] return arr
def manhattan_distance(x, y): """Manhattan distance from origin to a point(x, y)""" return abs(0 - x) + abs(0 + y)
def gen_image_name(reference: str) -> str: """ Generate the image name as a signing input, based on the docker reference. Args: reference: Docker reference for the signed content, e.g. registry.redhat.io/redhat/community-operator-index:v4.9 """ no_tag = reference.split(":")[0] ...
def find_unique_name(name, names, inc_format='{name}{count:03}', sanity_count=9999999): """ Finds a unique name in a given set of names :param name: str, name to search for in the scene :param names: list<str>, set of strings to check for a unique name :param inc_format: str, used to increment the n...
def GetExpandedList(l, s): """return a list where every elment in l is duplicated s times. """ nl = [] for x in l: nl += [x] * s return nl
def byte_from_str(size, unit): """ :param size: 3.6 :param unit: T / TB :return: """ unit = unit.upper() try: size = float(size) except: size = float(size[:-1]) if unit == 'T' or unit == 'TB': return size * 1024 * 1024 * 1024 * 1024 elif unit == 'G' or uni...
def valid_refined(candidate): """ Utility function that determines if a passed permutation is valid. Specifically, there exists one and only one "pair" of matching digits. """ permutation = str(candidate) for char in permutation[::-1]: if 2 == permutation.count(char): return ...
def egcd(n: int, m: int) -> dict: """Extended Euklidean algorithm. Finds greatest common divisor of n and m Args: n -- first number m -- second number Return: dictionary with specified keys: reminder -- greatest common divisor a, b -- answers to equation an + bm = rem...
def has_common_element(a, b): """ Return True if iterables a and b have at least one element in common. """ return not len(set(a) & set(b)) == 0
def clean_principals_output(sql_result, username, shell=False): """ Transform sql principals into readable one """ if not sql_result: if shell: return username return [username] if shell: return sql_result return sql_result.split(',')
def range_n_inv(n, end=0, step=-1): """ Return the sequence [start, start+1, ..., start+N-1]. """ return list(range(n, end, step))
def exec_command(command): """ Execute the command and return the exit status. """ import subprocess from subprocess import PIPE pobj = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True) stdo, stde = pobj.communicate() exit_code = pobj.returncode return exit_code, stdo...
def is_valid_to_add(prefix, new_char, available): """ We assume that prefix is already a valid block-chain, by induction. Returns whether or not prefix + new_char is a valid block-chain. We can do this fast, in one iteration over prefix, by keeping track of the smallest character we've seen so far,...
def _isASCII(mthd: str) -> bool: """ Check if the given method contains only ASCII characters. From https://stackoverflow.com/a/27084708/5768407. :param mthd: the method to verify contains only ASCII characters :returns: returns a boolean representing whether or not the given method contains only ASCII...
def _split_ports_per_fabric(slot_grouping, fabric_data): """Splits the slots per fabric which are to be placed on the same VIOS. :param slot_grouping: The slots which are to be placed in the same vios Ex: [3, 6] Here the slots 3 and ...
def copy(obj, deep_copy=True): """ A function that allows the use of deep coping or shallow coping a value. :param obj: value to copy. :param deep_copy: flag that indicated if a deep copy should be done. :return: return a copy of the object. """ if deep_copy: re...
def fibonacci_sequence(n): """implement problem 2""" a = 0 b = 1 total = 0 if a < 0: print("input smaller than zero") elif n == 0: return a elif n == 1: return b else: while total < n: c = a + b a = b b = c i...
def set_metadata_language(dir): """ Set the language code in the metadata <dc:language> tag by going recursively over every metadata.opf file in the Calibre library. Some Catalan ebooks have the language metadata incorrectly coded as: <dc:language>cat</dc:language> in the content.opf file...
def parse_message(data): """Return a tuple containing the command, the key, and (optionally) the value cast to the appropriate type.""" command, key, value, value_type = data.strip().split(';') if value_type: if value_type == 'LIST': value = value.split(',') elif value_type =...
def title(message, underline='='): """Return a string formated as a Markdown title. underline argument will be printed on the line below the message. """ return '{}\n{}\n\n'.format(message, underline * len(message))
def _get_combined_beta_probability(p_beta: float, opinion): """ S -> I :param p_beta: :param opinion: positive opinion reduce the probability of infection :return: combined infected probability """ opinion_rate = 1 if opinion == 1: opinion_rate /= 2 return p_beta ...
def is_range_common_era(start, end): """ does the range contains CE dates. BCE and CE are not compatible at the moment. :param start: :param end: :return: False if contains BCE dates. """ return all([start.get("is_common_era"), end.get("is_common_era")])
def titlecomment(line): """Condition for a line to be a title comment""" return line.startswith('//') and len(line.lstrip('//').strip()) > 0
def getStrongs(word, strongs_index): """ Retrieves the strongs found for a word :param word: :param strongs_index: :return: a list of strong numbers """ if word in strongs_index: return strongs_index[word] else: return []
def pad_seq(dataset, field, max_len, symbol): """ pad sequence to max_len with symbol """ n_records = len(dataset) for i in range(n_records): assert isinstance(dataset[i][field], list) while len(dataset[i][field]) < max_len: dataset[i][field].append(symbol) return dataset
def bitDescription(bits, *descriptions): """Return a description of a bit-wise value.""" ret = [] for desc in descriptions: if len(desc) == 2: yes, no = desc[1], None else: yes, no = desc[1:3] if bits & (1 << desc[0]): if yes: ret.a...
def concat_code_sequences(val): """ Post-process a code field into a string, allowing it to be initially written as a sequence of strings. (which provides room to write comments) """ if isinstance(val, list): return ' // '.join(x.strip() for x in val) return val
def as_icon(icon: str) -> str: """Convert icon string in format 'type/icon' to fa-icon HTML classes.""" icon_type, icon_name = icon.split("/") if icon_type.lower() == "branding": icon_type = "fab" else: icon_type = "fas" return f'{icon_type} fa-{icon_name}'
def mk_ref_id(refname: str) -> str: """Create gerrit CD/ABCD name, refname must not be empty. >>> mk_ref_id("1") '01/1' >>> mk_ref_id("41242") '42/41242' """ refid = refname[-2:] if len(refname) > 1 else ("0" + refname[-1]) return refid + "/" + refname
def camel_farm(identifier): """ Convert from underscored to camelCase. """ words = identifier.split('_') return ''.join([words[0]] + [word.capitalize() for word in words[1:]])
def transform_wire_string_to_tuple(wirestring): """ Transforms String representation to integer :param wirestring: String configuration which occurs in output.gate.txt and output.inputs.txt file :return: decomposition of the String into Tuple of three Integers """ wirelist = wirestring.split('...
def clean_codeblock(text): """Remove codeblocks and empty lines, return lines.""" text = text.strip(" `") lines = text.split("\n") clean_lines = [] if lines[0] in ["py", "python"]: lines = lines[1:] for line in lines: if line.strip() != "": clean_lines.append(line) ...
def count_common_letters(strings): """ :type strings: list[str] :rtype: int """ if len(strings) < 2: return 0 common_elements = set(strings[0]) for s in strings[1:]: common_elements = common_elements.intersection(set(s)) return len(common_elements)
def check_meta(file_content, options): """Check if given tag is in current file and adds FileContent object.""" if options['tags'] == [None]: return True for elm in file_content: if 'meta' in elm: for tag in elm['meta'].get('tags', []): if tag in options['tags']: ...
def second_kulczynski_sim(u, v): """ Computes the second Kulczynski similarity between sets u and v. sim = (1/2) * ((a / (a + b)) + (a / (a + c)) ) Where a = # of items in intersection(u, v) b = # of items only in u c = # of items only in v params: u, v: sets to compare ...
def get_out_nodes(in_node_dict): """Create output dictionary from input dictionary. Parameters ---------- in_node_dict : dict of int to list of int Dictionary maps node index to closest input ancestors. It can be created with get_in_nodes. Returns ------- out : dict of int ...
def minDistance(word1, word2): """The minimum edit distance between word 1 and 2.""" if not word1: return len(word2 or '') or 0 if not word2: return len(word1 or '') or 0 size1 = len(word1) size2 = len(word2) tmp = list(range(size2 + 1)) value = None for i in range(size1)...
def make_flattened_values(dic, key_order, fun): """ dic is a dictionary mapping keys in key_order to a list. each element of a list is another dictionary. i.e., dic looks like dic = { k0 : [ {l0 : v00}, {l1 : v01} ... ], k1 : [ {l0 : v10}, {l1 : v11} ... ], ... } key_order is a list ...
def get_file_ext(ext, fileName): """ Helper function for making sure the correct file ending is appended. Parameters ------------- ext = str, file extension. ex) ".json" or ".txt" fileName = str, path to file. Can include custom directory, uses processes/ by default. Retur...
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ if len(ints) == 0: print('Cannot get min and max from empty array') return None min_num, max_num = 0, 0 if len...
def deep_merge_dicts(lhs: dict, rhs: dict) -> dict: """ Deep merging two dicts """ for key, value in rhs.items(): if isinstance(value, dict): node = lhs.setdefault(key, {}) deep_merge_dicts(node, value) else: lhs[key] = value return lhs
def compare(a, b): """ Compare two base strings, disregarding whitespace """ import re return re.sub(r"\s*", "", a) == re.sub(r"\s*", "", b)
def fibonacci_iterative(nth_nmb: int) -> int: """An iterative approach to find Fibonacci sequence value. YOU MAY NOT MODIFY ANYTHING IN THIS FUNCTION!!""" old, new = 0, 1 if nth_nmb in (0, 1): return nth_nmb for __ in range(nth_nmb - 1): old, new = new, old + new return new
def is_allowed_char(ch): """ Test if passed symbol is allowed in abbreviation @param ch: Symbol to test @type ch: str @return: bool """ return ch.isalnum() or ch in "#.>+*:$-_!@"
def _get_fitting_type(fitting_angle, rounded): """Returns fitting type for expansions and reductions. Parameters: fitting_angle: Fitting angle. Usually is 180 for square fittings. rounded: Rounded fitting. Usually is False for square fittings. """ if fitting_angle != 180 and rounded: ...
def recursive_gcd(x: int, y: int): """keep call the recursive_gcd function until y = 0""" if y == 0: return x return recursive_gcd(y, x%y)
def get_src(src, pt, tform): """ Args: src (2D indexable): The generalized array (supporting "float indexing") pt: The point of the image we would like to fill tform: Callable """ # The dest[pt] = src[tform(pt)] tformed = tform(pt) ret = src(tformed[1], tformed[0]) re...
def generate_big_rules(L, support_data, min_conf): """ Generate big rules from frequent itemsets. Args: L: The list of Lk. support_data: A dictionary. The key is frequent itemset and the value is support. min_conf: Minimal confidence. Returns: big_rule_list: A lis...
def new_sleep_summary_detail( wakeupduration, lightsleepduration, deepsleepduration, remsleepduration, wakeupcount, durationtosleep, durationtowakeup, hr_average, hr_min, hr_max, rr_average, rr_min, rr_max, ): """Create simple dict to simulate api data.""" ret...
def xoai_abstract(source, *args, **kwargs): """ CZ: EN: """ value = [] for lang_vers in source: lang = lang_vers["@name"] field = lang_vers["element"]["field"] if isinstance(field, list): for abstract in field: value.append( ...