content
stringlengths
42
6.51k
def _recursive_to_list(array): """ Takes some iterable that might contain iterables and converts it to a list of lists [of lists... etc] Mainly used for converting the strange fbx wrappers for c++ arrays into python lists :param array: array to be converted :return: array converted to lists ...
def get_hours(minutes: int) -> int: """ Converts minutes to hours :param minutes: Minutes before conversion :return: Hours """ return int(minutes / 60)
def process_input(input): """ Returns rules and messages, as lists Rules = ['0: 4 1 5', '1: 2 3 | 3 2', etc] Messages = ['ababbb', 'bababa', etc] """ # first split the rules block from the messages block rules_line, messages_line = input.split("\n\n") # then split each blow into a l...
def _translate_category(glyph_name, unicode_category): """Return a translation from Unicode category letters to Glyphs categories.""" DEFAULT_CATEGORIES = { None: ("Letter", None), "Cc": ("Separator", None), "Cf": ("Separator", "Format"), "Cn": ("Symbol", None), "Co":...
def simplify_repeats(list_pattern): """ Converts ['a','a','b','a','b', 'b','b'] to ['a!2', 'b','a','b!3'] """ n_repeats = 0 output_list = [] for i, x in enumerate(list_pattern): # if not the last element if i != len(list_pattern) - 1: # if the next element is a repeat...
def get_switchport_config_commands(name, existing, proposed, module): """Gets commands required to config a given switchport interface """ proposed_mode = proposed.get('mode') existing_mode = existing.get('mode') commands = [] command = None if proposed_mode != existing_mode: if pr...
def styleId_from_name(name): """ Return the style id corresponding to *name*, taking into account special-case names such as 'Heading 1'. """ return { 'caption': 'Caption', 'heading 1': 'Heading1', 'heading 2': 'Heading2', 'heading 3': 'Heading3', ...
def integer_value(value): """ Convert value to an integer. Takes base indicators into account, such as 0x for base-16, 0 for base-7. """ return int(value, 0)
def floatstrip(x): """ Given a float will return if it is actually an integer eg. 16.0 -> 16 """ if x == int(x): return str(int(x)) else: return str(x)
def _multi_line(in_string): """true if string has any linefeeds""" return "\n" in str(in_string)
def parse_condition(conditions): """ Args: conditions (list) """ d = {} for arg in conditions: if "=" not in arg: raise SyntaxError key = arg.partition("=")[0] if key == "gid": d["gid"] = int(arg.partition("=")[-1]) elif key == "host": ...
def doBoundingBoxesIntersect(a, b, c, d): """ Check if bounding boxes do intersect. If one bounding box touches the other, they do intersect. First segment is of points a and b, second of c and d. """ ll1_x = min(a[0], b[0]) ll2_x = min(c[0], d[0]) ll1_y = min(a[1], b[1]) ll2_y = min...
def triangleType(x, y, z): """ Determine if the triangle is valid given the length of each side x,y,z. :param x: First side of triangle :param y: Second side of triangle :param z: Third side of triangle :returns: Whether a triangle is an 'Equilateral Triangle', 'Isosceles Tria...
def dec2hexs(n): """ converts an integer to a hexadecimal string """ s = '' while n > 15: s = "0123456789ABCDEF"[n % 16] + s n //= 16 return "0123456789ABCDEF"[n] + s
def write_lines(file, lines, encoding=None, errors=None): """Write the lines to a file. :param file: path to file or file descriptor :type file: :term:`path-like object` or int :param list(str) lines: list of strings w/o newline :param str encoding: name of the encoding :param str errors: error...
def S_load_calc(va,vb,vc,Zload): """Power absorbed by load at PCC LV side.""" return (1/2)*(va*(-(va/Zload)).conjugate() + vb*(-(vb/Zload)).conjugate() + vc*(-(vc/Zload)).conjugate())
def com2lst(s): """separate CSVs to a list, returning [s] if no commas.""" if "," in s: s=s.split(",") else: s=[s] return s
def word_count(text): """ Count number word in text Args: text (str): string text Returns: (int): number of word in text """ if isinstance(text, str): tokens = text.split(" ") else: tokens = [] return len(tokens)
def make_expr(expr, loop_count, thread_count): """ Prepare an expression for threading """ e = \ """ import errno, os, sys, signal, multiprocessing """ + expr e += \ """ if @THREAD_COUNT@ == 0: test() else: for i in range(@THREAD_COUNT@): t = multiprocessing.Process(target=test) t.st...
def find_all_indexes(text, pattern, first=False): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. Best and worst case are O(n * m) because it goes to the end no matter what. Could consider improving by checking when theres less than m chars in ...
def module_level_function(arg1, arg2='default', *args, **kwargs): """This function is declared in the module.""" local_variable = arg1 * 2 return local_variable
def get_pivot_index(array, first, last): """ Function for getting pivot index. :param array: array with items <list> :param first: first index in array <int> :param last: last index in array <int> :return: median of first, mid, last values in array <int> """ mid = (first + last) // 2 ...
def find_optional_pay(term, opt_pay_recur, opt_pay_custom): """ This method is used to find the list of optional payments for each month""" opt = [opt_pay_recur] * term # Initialize optional payment for this_month in opt_pay_custom.keys(): if this_month <= term: # Check if the month is valid ...
def list_base_properties(bases): """ returns a dictionary of properties assigned to the class""" rtn_dict = {} for base in bases: if hasattr(base, 'properties'): rtn_dict.update(base.properties) return rtn_dict
def trip(u, v): """ Returns the scalar triple product of vectors u and v and z axis. The convention is z dot (u cross v). Dotting with the z axis simplifies it to the z component of the u cross v The product is: positive if v is to the left of u, that is, the shortest right hand ro...
def inlist(x) -> list: """Wrap argument in a list if it's not already a list itself""" if isinstance(x, list): return x return [x]
def invertDictLossless(D): """similar to invertDict, but values of new dict are lists of keys from old dict. No information is lost. >>> old = {'key1':1, 'key2':2, 'keyA':2} >>> invertDictLossless(old) {1: ['key1'], 2: ['key2', 'keyA']} """ n = {} for key, value in D.items(): n....
def get_video_results(preds, anomaly_frames, normal_frames): """Returns confusion matrix values for predictions of one video Args: preds (set): set of frame number predictions for a threshold anomaly_frames (set) set of frames numbers that are anomalies normal_frames (set) set of normal ...
def _add_tags(tags, additions): """ In all tags list, add tags in additions if not already present. """ for tag in additions: if tag not in tags: tags.append(tag) return tags
def _sr(s): """ reverse a string """ return s[::-1]
def simple_drop_keyspace(keyspace_name): """ Given a keyspace name, produce keyspace dropping CQL (version 3 CQL). No other cleanup is done. :param keyspace_name: what the name of the keyspace is to drop :type keyspace_name: ``str`` """ return "DROP KEYSPACE {name}".format(name=keyspace_na...
def tree_unflatten(flat, tree, copy_from_tree=None): """Unflatten a list into a tree given the tree shape as second argument. Args: flat: a flat list of elements to be assembled into a tree. tree: a tree with the structure we want to have in the new tree. copy_from_tree: optional list of elements that ...
def rowcol2idx(r,c,shape): """ Given a row, column, and matrix shape, return the corresponding index into the flattened (raveled) matrix. """ assert len(shape) == 2 rows,cols = shape return r * cols + c
def mul_inplace(X,varX, Y,varY): """In-place multiplication with error propagation""" # Z = X * Y # varZ = Y**2 * varX + X**2 * varY T = Y**2 # create T with Y**2 varX *= T # varX now has Y**2 * varX del T # may want to use T[:] = X for vectors T = X # reuse T for X**2 * varY T **...
def list_avg(l): """Calculate average of a list after removing outliers and return as float""" l.sort() return sum(l[1:-1])/float(len(l[1:-1]))
def _to_extended_delta_code(seconds): """Return the deltaCode encoding for the ExtendedZoneProcessor which is roughtly: deltaCode = (deltaSeconds + 1h) / 15m. With 4-bits, this will handle deltaOffsets from -1:00 to +2:45. """ return f"({seconds // 900} + 4)"
def text_restrict(text, width): """ Restrict string `text` to width `width`. """ if len(text) > width: return "..."+text[(-1*width)+2:-1] return text
def encode_bigint_bitvec(value, bitlen=None): """Encode a Bit-Endian integer into a vector of bits""" if bitlen is None: bitlen = value.bit_length() binval = '{{:0{:d}b}}'.format(bitlen).format(value) return [int(x) for x in binval]
def mFWQ(mFL, qL): """ mFWQ(mFL, qL): (mole or mass) Fraction Weighted Quantity Parameters: mFL, list of mole or mass fractions, sum(mFL) = 1 qL, list of quantities corresponding to items in mFL Returns: weighted averaged of items in qL """ aveQ = 0...
def _handle_negatives(numbers): """ Add the minimum negative number to all the numbers in the such that all the elements become >= 0 """ min_number = min(filter(lambda x : type(x)==int,numbers)) if min_number < 0: return [x+abs(min_number) if type(x)==int else x for x in numbers]...
def prepareRegexForMySQL(pattern): """Convert regex to MySQL syntax.""" pattern = pattern.replace(r'\s', '[:space:]') pattern = pattern.replace(r'\d', '[:digit:]') pattern = pattern.replace(r'\w', '[:alnum:]') pattern = pattern.replace("'", '\\' + "'") # pattern = pattern.replace('\\', '\\\\') ...
def to_conll_iob(annotated_sentence): """ `annotated_sentence` = list of triplets [(w1, t1, iob1), ...] Transform a pseudo-IOB notation: O, PERSON, PERSON, O, O, LOCATION, O to proper IOB notation: O, B-PERSON, I-PERSON, O, O, B-LOCATION, O """ proper_iob_tokens = [] for idx, annotated_token...
def first_item(list_or_dict): """ If passed a list, this returns the first item of the list. If passed a dict, this returns the value of the first key of the dict. :param < list | dict > list_or_dict: A list or a dict. :rtype obj: The first item of the list, or the first value of the dict """ ...
def extract_json_values(obj: dict, key: str) -> list: """ Pull all values of specified key from nested JSON. Args: obj (dict): nested dict key (str): name of key to pull out Returns: list: [description] """ arr = [] def extract(obj, arr, key): """ Recursive...
def length_of_elements(elementList, index=0, lengths=None): """ Returns the length of each row (sub-array) in a single array """ if lengths is None: lengths = [] # Will only calculate len if index is lower than the len of the array. # If it isn't less, will return the final array of leng...
def guess_format(filename): """ Try to guess a file's format based on its extension (or lack thereof). """ last_period = filename.rfind('.') if last_period == -1: # No extension: assume fixed-width return 'fixed' extension = filename[last_period + 1:] if extension == 'xls'...
def intersection(set_1, set_2): """realisation of two sets intersection(simple set generator inside)""" return {i for i in set_1 if i in set_2}
def isprime(n): """ check if integer n is a prime """ # make sure n is a positive integer n = abs(int(n)) # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: return True # all other even numbers are not primes if not n ...
def _unpack_tuple(x): """Unpacks one-element tuples for use as return values Args: x: """ if len(x) == 1: return x[0] else: return x
def lerp(start, stop, amount): """Linearly interpolate amount between start and stop. Source: https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support""" return (1 - amount) * start + amount * stop
def sum_fuel_enduse_sectors(data_enduses, enduses): """Aggregate fuel for all sectors according to enduse Arguments -------- data_enduses : dict Fuel per enduse enduses : list Enduses nr_fueltypes : int Number of fuetlypes Returns ------- aggregated_fuel_end...
def _check_launchctl_stderr(ret): """ helper class to check the launchctl stderr. launchctl does not always return bad exit code if there is a failure """ err = ret["stderr"].lower() if "service is disabled" in err: return True return False
def g_iter(n): """Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) 10 >>> g_iter(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion']) True """ if n <= ...
def get_tts_type(cfg): """Get TTS type from the configuration.""" return cfg['TTS']['type']
def _list_of_kv(kv): """Split string `kv` at first equals sign.""" ll = kv.split("=") ll[1:] = ["=".join(ll[1:])] return ll
def to_unicode_str(byte_string, errors="replace"): """Turn a byte string into a unicode string. Should be used everywhere where the input byte string might not be trusted and may contain invalid unicode values. Args: byte_string (bytes): The bytestring that will be converted to a native ...
def find_contraction(positions, input_sets, output_set): """ Finds the contraction for a given set of input and output sets. Parameters ---------- positions : iterable Integer positions of terms used in the contraction. input_sets : list List of sets that represent the lhs side ...
def convert_to_seconds(time): """Convert a time string to seconds""" seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800} if time.isnumeric(): return int(time) return int(time[:-1]) * seconds_per_unit[time[-1]]
def find(seq): """Return first item in sequence where f(item) == True.""" f = lambda number: number != None for item in seq: if f(item): return item
def spec_char_rating(pw): """ Takes in the password and returns a special-character (S-C) score. Parameters: pw (str): the password string Returns: spec_rating (float): score produced by increments of 0.5 for every unique S-C in the password. [Max val- 1.5] """ symbols = [ ...
def extract_string(data, offset=0): """ Extract string """ str_end = offset while data[str_end] != 0: str_end += 1 return data[offset:str_end].decode('ascii')
def words_and_phrases(text): """splits a list containing single words and/or multi-word phrases""" words = [] phrases = [] for t in text: if len(t.split()) > 1: phrases.append(t) else: words.append(t) return words, phrases
def c_d(val): """current divisor""" if val == 0: return 100 elif val >=1 and val <= 3: return 10 else: return None
def append_fp_postfix(type_str, input_val_list): """Generates and returns a new list from the input, with .0f or .0 appended to each value in the list if type_str is 'float', 'double' or 'cl::sycl::half'""" result_val_list = [] for val in input_val_list: if (type_str == 'float' or type_str == 'c...
def calculate_transaction_size(n_of_txin, n_of_txout): """Transaction size in bytes based on inputs and outputs for non segwit addresses """ return (n_of_txin * 180) + (n_of_txout * 34) + 10 + n_of_txin
def enthalpy_f1(T, hCP, TRef=298.15): """ enthalpy_f1(T, hCP, TRef=298.15) slop vapor & solid phases: T in K, enthalpy in J/mol; enthalpy change correlation enthalpy = A*(T-TRef) + 1/2*B*(T^2-TRef^2) - C*(1/T-1/TRef) Parameters T, temperature TRef, reference temperature ...
def mapping_freq_names(freq: str) -> str: """Converts a short frequency name into a long frequency name. Parameters ---------- freq : str Short frequency name. Returns ------- str Long frequency name. """ mapping = { "s": "seconds", "H": "hours", ...
def levenshtein(a: str, b: str) -> int: """Find the levenshtein distance between two strings""" if not len(a): return len(b) if not len(b): return len(a) if a[0] == b[0]: return levenshtein(a[1:], b[1:]) return 1 + min( levenshtein(a[1:], b), levenshtein(a, b...
def reverse_index(ls): """Reverse the order of indices in ls, which is a list of lists of the form ls[A][B]. Assumes the inner list has the same length for all A. Returns a list of lists where the corresponding element is ls[B][A]. """ rev = [] if len(ls) == 0: return rev len_second...
def get_recur_attr(obj, attr: str): """ Follow the dot `.` in attribute string `attr` to the final object :param obj: any object :param attr: string of attribute access :return: the final desire object or '!!! Not Exists' example: if we need to access `c` object as in `a.b.c`, then `obj=a,...
def ascending_digits(password): """Check to see if each digit in the number is equal to or larger than the one before Parameters ---------- password : int password number Returns ------- ascending_dig: bool True if all digits are equal to or larger than the one before, ...
def validate_split_durations(train_dur, val_dur, test_dur, dataset_dur): """helper function to validate durations specified for splits, so other functions can do the actual splitting. First the functions checks for invalid conditions: + If train_dur, val_dur, and test_dur are all None, a ValueError...
def _add_non_standard_params(params, raw_data): """non standard params are parameters that are spelled differently in GET and POST/PUT requests For example 'admin' in POST/PUT requests is called 'is_admin' in GET """ if 'admin' in params and params['admin'] is not None: raw_data['admin'] = pa...
def levenshtein(seq1, seq2): """Compute the edit distance between two words seq1 and seq2. Parameters ---------- seq1 : str The first word. seq2 : str The second word. Returns ------- int The edit distance. """ if len(seq1) < len(seq2): return le...
def get_subdict(full_dict, keys, strict=True): """ Returns a sub-dictionary of ``full_dict`` containing only keys of ``keys``. Args: full_dict: Dictionary to extract from. keys: keys to extract. strict: If false it ignores keys not in full_dict. Otherwise it crashes on those. ...
def get_function_types(subcommand_params): """ Reads all subcommands and returns a set with all the types of functions used """ list_functions = [ subcommand["function_type"] for subcommand in subcommand_params ] return set(list_functions)
def encode_uint128(val): """ Format a value as a unsigned 128 bit integer Specs: * **uint128 len**: 16 bytes * **Format string**: 'z' """ return val.to_bytes(16, 'little', signed=False)
def fft_message(fft): """ forms the message expected in OutputDevice in_queues fft should be an array of 7 numbers representing the bands """ return ["fft", fft]
def get_timeout(filesize): """ Get a proper time-out limit based on the file size. :param filesize: file size (int). :return: """ timeout_max = 3 * 3600 # 3 hours timeout_min = 300 # self.timeout timeout = timeout_min + int(filesize / 0.5e6) # approx < 0.5 Mb/sec return min(ti...
def make_character_to_num(characters): """ Convert character set into a dictionary. """ chars = list(characters) return dict(zip(chars, range(1, len(chars) + 1)))
def isValidName(name, allNames): """ Parameters ---------- name: str allNames: dict Returns ------- bool """ if not isinstance(name, str): return False for mainName in allNames.keys(): if name.lower() in allNames[mainName] + [mainName.lower()]: re...
def parse_visitor_guid_team(d): """ Used to parse GUID of team. """ return str(d.get("tUGUID", "BVBL0000XXX 1")).replace(" ", "+")
def lerp(x, y, p): """Interpolate between x and y by the fraction p. When p == 0 x will be returned, when p == 1 y will be returned. Note that p is not restricted to being between 0 and 1. :Return: The interpolated value. :Param x, y: The interpolation end-points. :Param p: ...
def _identify_seeds(cluster): """Update the SEED list on each node.""" # Select first node from each zone as a SEED node. seed_ips = [] seed_data = [] for z in cluster.keys(): seed_node = cluster[z][0] seed_ips.append(seed_node['ip']) seed_data.append(seed_node) return se...
def _normalize_var_name(text, start_del, end_del): """ Search&replace all pairs of (start_del, end_del) with pairs of ({, }). :param text: str to normalize :param start_del: delimiter that indicates start of variable name, typically {{ :param end_del: delimiter that indicates end of variable name, ...
def matTransposed(mat): """Return the transposed of a nxn matrix. >>> matTransposed(((1, 2), (3, 4))) ((1, 3), (2, 4))""" dim = len(mat) return tuple( tuple( mat[i][j] for i in range(dim) ) for j in range(dim) )
def parse_healthy(data: dict) -> bool: """ Health Parser for endpoints that report "healthy": True None or missing will be considered unhealthy """ return str(data.get('healthy', False)).lower() == "true"
def prettyprint_float(val, digits): """Print a floating-point value in a nice way.""" format_string = "%." + f"{digits:d}" + "f" return (format_string % val).rstrip("0").rstrip(".")
def map_phone2phone(phone_list, label_type, map_file_path): """Map from 61 phones to 39 or 48 phones. Args: phone_list (list): list of 61 phones (string) label_type (string): phone39 or phone48 or phone61 map_file_path (string): path to the phone2phone mapping file Returns: m...
def _safe_getattr(value, attr, default): """Returns whether this value has the given attribute, ignoring exceptions.""" try: return getattr(value, attr) except Exception: return default
def parse_vespa_json(data): """ Parse Vespa results to get necessary information. :param data: Vespa results in JSON format. :return: List with retrieved documents """ ranking = [] if "children" in data["root"]: ranking = [hit["fields"]["id"] for hit in data["root"]["children"] if "...
def is_iterable(x): """Test a variable for iterability. Determine whether an object ``x`` is iterable. In Python 2, this was as simple as checking for the ``__iter__`` attribute. However, in Python 3, strings became iterable. Therefore, this function checks for the ``__iter__`` attribute, returning...
def df_approx( f, x0, dx=1e-5, METHOD='FFD' ): """ INPUT : - Function - Point of Interest - OPTIONAL: Tolerance - OPTIONAL: FD Method RETURN: - Derivative at Point """ a = x0 # Create a copy # Estimate derivative using FFD if (METHOD ...
def is_apple_os(os_): """returns True if OS is Apple one (Macos, iOS, watchOS or tvOS""" return str(os_) in ['Macos', 'iOS', 'watchOS', 'tvOS']
def tensor_to_op_name(tensor_name): """Strips tailing ':N' part from a tensor name. For example, 'dense/kernel:0', which is a tensor name, is converted to 'dense/kernel' which is the operation that outputs this tensor. Args: tensor_name: tensor name. Returns: Corresponding op name. """...
def _format_station_json_to_dict(json_content): """ iterates json content, makes a dict adds it to a list :returns a list of dictionary """ stations = [] required_fields = ['name', 'location', 'frequency', 'stream_url'] for counter, station in enumerate(json_content, start=1): statio...
def sval(val): """ Returns a string value for the given object. When the object is an instanceof bytes, utf-8 decoding is used. Parameters ---------- val : object The object to convert Returns ------- string The input value converted (if needed) to a string...
def _parse_utm_projection_string(line): """Convert strings like 'WGS84 UTM 32N' to a proj4 definition.""" words = line.lower().split() assert len(words) == 3 zone = line.split()[2].upper() if zone[-1] == 'N': zone_number = int(zone[:-1]) zone_hemisphere = 'north' elif zone[-1] ==...
def splitdrive(p): """Split a path into a drive specification (a drive letter followed by a colon) and path specification. It is always true that drivespec + pathspec == p.""" if p[1:2] == ':': return p[0:2], p[2:] return '', p
def safediv(*args): """ .. function:: safediv(int, int, int) -> int Returns the first argument, when the division of the two subsequent numbers includes zero in denominator (i.e. in third argument) Examples: >>> sql("select safeDiv(1,5,0)") safeDiv(1,5,0) -------------- 1 ""...