content
stringlengths
42
6.51k
def _add_payload_files(zip_file, payload_info_list): """Add the payload files to the zip.""" payload_byte_count = 0 payload_file_count = 0 for payload_info_dict in payload_info_list: zip_file.write_iter(payload_info_dict["path"], payload_info_dict["iter"]) payload_byte_count += payload_i...
def expand_alsa_port_name(port_names, name): """Expand ALSA port name. RtMidi/ALSA includes client name and client:port number in the port name, for example: TiMidity:TiMidity port 0 128:0 This allows you to specify only port name or client:port name when opening a port. It will compare t...
def parse_bool(raw): """Takes a string representation of a truthy string value and converts it to bool. Valid boolean representations include: - y/yes/Yes/YES - true/True/TRUE - 1 Args: raw (str): Truthy value to convert. Returns: bool: Boolean representation o...
def calc_conformance(results): """Returns a tuple with the number of total and failed testcase variations and the conformance as percentage.""" total = len(results) failed = sum(1 for status, _ in results.values() if status != 'PASS') conformance = (total-failed)*100/total if total > 0 else 100 retu...
def func_a_args_kwargs(a=2, *args, **kwargs): """func. Parameters ---------- a: int args: tuple kwargs: dict Returns ------- a: int args: tuple kwargs: dict """ return None, None, a, None, args, None, None, kwargs
def bucket_sort(elements, bucket_size=10): """ Use the simple bucket sort algorithm to sort the :param elements. :param bucket_size: the distribution buckets' size :param elements: a integer sequence in which the function __get_item__ and __len__ were implemented() :return: the sorted elements in in...
def _create_url(searchword, area): """ Creates the url for the web page to scrape. """ return 'https://www.blocket.se/{}?q={}&cg=0&w=1&st=s&c=&ca=15&is=1&l=0&md=th'.format(area, searchword)
def validate_image(layer_list): """ Takes list of image layer strings. Validates image layer data by finding the layer with the fewest 0 digits, and then determines and returns the number of 1 digits multiplied by the number of 2 digits in that layer. """ min_count = 150 ...
def get_all_ngrams(sequence, n): """ Creates a list of all ngrams found in a given sequence. Example --------- >>> sequence = [2,1,1,4,2,2,3,4,2,1,1] >>> ps.get_unique_ngrams(sequence, 3) #doctest: +NORMALIZE_WHITESPACE [[2, 1, 1], [1, 1, 4], [1, 4, 2], [4, 2, 2], [2, 2, 3], [2, 3, 4], [3, 4, 2], ...
def eval_callbacks(callbacks, result): """Evaluate list of callbacks on result. The return values of the `callbacks` are ORed together to give the overall decision on whether or not the optimization procedure should continue. Parameters ---------- callbacks : list of callables Call...
def is_valid_data_node(data_dict): """Checks whether the json data node is valid.""" # Check if json element is a dict if type(data_dict) != dict: return False # Check if only data element is present in the dict if len(data_dict) != 1: return False # Try to parse the string ke...
def R_from_r(r): """ Calculate reflected power R from the reflection amplitude r of the Fresnel equations. Parameters ---------- r : array like Fresnel reflection coefficients Returns ------- R : array like Reflectivity """ return abs(r)**2
def binary_search(l, target): """ given a sorted list 'l' and a target value, return the position of target in the list or None if not found. """ i = 0 j = len(l) while j>i: m = (j-i)//2 + i if l[m] == target: return m elif l[m] < target: i = ...
def schedd_states(schedd_classad): """ Returns information about the number of jobs in each job state for a schedd :param schedd_classad: classad for schedd to query :return: a dictionary with job states as keys and number of jobs in given state as a value """ return {'Running': sc...
def rgb_to_hex(rgb): """Converts a RGB tuple or list to an hexadecimal string""" return '#' + ''.join([(hex(c).split('x')[-1].zfill(2)) for c in rgb])
def max_key(dic): """ Based on https://stackoverflow.com/questions/42044090/return-the-maximum-value-from-a-dictionary Returns the key of the max value in a dictionairy """ return [k for k, v in dic.items() if v == max(dic.values())][0]
def is_unique(string): """Determines if a string is unique. Args: string: any string of characters. Returns: a Boolean value dependant on the uniqueness Raises: ValueError: Empty string value given as an argument """ temp = list() if string: for charact...
def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ if len(dna1) > len(dna2): return True else: return False
def greet(name: str) -> dict: """ Greet the current user. :param name: Name of the user :return: Object: message to the user """ return {"message": f"Hello, {name}!"}
def _rec_validate(f, g, i, K): """Recursive helper for :func:`dmp_validate`.""" if type(g) is not list: if K is not None and not K.of_type(g): raise TypeError("%s in %s in not of type %s" % (g, f, K.dtype)) return {i - 1} elif not g: return {i} else: levels =...
def merge_headers(header_map_list): """ Helper function for combining multiple header maps into one. :param header_map_list: list of maps """ headers = {} for header_map in header_map_list: headers.update(header_map) return headers
def fmt_class(text: str, cls: str) -> str: """Format a string in a certain class (`<span>`). Args: text: The text to format. cls: The name of the class. Returns: A `<span>` with a class added. """ return f'<span class="{cls}">{text}</span>'
def rgb_norm(val): """Pixel normalization Function equivalent to keras.application.inception_v3.preprocess_input Arguments: val {int} -- Pixel value (0:255 range) Returns: int -- Pixel normalized value (-1:1 range) """ return 2/255*(val-255)+1
def readable_timedelta(days): """ Display days in a human readable way original function by Syed Marwan Jamal Arguments: - days : (int) amount of day to translate Returns: - : (str) human readable string with date """ number_of_weeks = days // 7 number_of_days = days % ...
def remove_keys(obj, rubbish): """Recursively remove keys whose are in `rubbish` and return cleaned object""" if isinstance(obj, dict): obj = { key: remove_keys(value, rubbish) for key, value in obj.items() if key not in rubbish} elif isinstance(obj, list): ...
def alternator(iterable, frontFirst=True): """ Alternates an iterable from front to back and returns the alternation as a list. Example: [0, 1, 2, 3, 4, 5] turns into [0, 5, 1, 4, 2, 3] if frontFirst is True and [5, 0, 4, 1, 3, 2] if frontFirst is False. Args: iterable (iterable...
def _MergeDeps(dest, update): """Merge the dependencies specified in two dictionaries. Arguments: dest: The dictionary that will be merged into. update: The dictionary whose elements will be merged into dest. """ assert(not set(dest.keys()).intersection(set(update.keys()))) dest.update(update) retu...
def selection_sort_counting(A): """Instrumented Selection Sort to return #swaps, #compares.""" N = len(A) num_swap = num_compare = 0 for i in range(N-1): min_index = i for j in range(i+1, N): num_compare += 1 if A[j] < A[min_index]: min_index = j ...
def clamp(n, lower, upper): """ :param n: Number to clamp :param lower: Lower bound :param upper: Upper bound :return: Clamped number """ return max(lower, min(n, upper))
def _is_chrome_only_build(revision_to_bot_name): """Figures out if a revision-to-bot-name mapping represents a Chrome build. We assume here that Chrome revisions are always > 100000, whereas WebRTC revisions will not reach that number in the foreseeable future.""" revision = int(revision_to_bot_name.spli...
def area(span: float, aspect: float) -> float: """Calculates the surface area using ``span`` and ``aspect``.""" return span ** 2 / aspect
def _scalarize(value): """Scalarize a value. If VALUE is a list that consists of a single element, return that element. Otherwise return VALUE.""" if type(value) == list and len(value) == 1: return value[0] return value
def div(value, arg): """Division >>> div(4, 2) 2 """ if arg is None: return 0 elif arg is 0: return 0 else: return value / arg
def unsigned_int(value): """ Converts the given byte value to an unsigned integer. """ return int.from_bytes(bytearray(value), 'little')
def daylight_hours(ws): """ :param ws: sunset hour angle [rad] :return: daylight hours [hour] """ # 24.0 / pi = 7.639437268410976 return 7.639437268410976 * ws
def dev_notifications_showing(dev0): """ m05.show the notifications..... return none......... """ try: dev0.open_notification() except Exception as e: print("error at dev_notifications_showing.") pass else: pass finally: return None
def get_least_edge_in_bunch(edge_bunch, weight='weight'): """ Edge bunch must be of the format (u, v, d) where u and v are the tail and head nodes (respectively) and d is a list of dicts holding the edge_data for each edge in the bunch todo: add this to some sort of utils file/ module in wardbradt/netw...
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: O(n) Space Complexity: O(1) """ if nums == None: return 0 if len(nums) == 0: return 0 if sum(nums) < 0: ...
def get_class_path(cls, use_tfds_prefix=True): """Returns path of given class or object. Eg: `tfds.image.cifar.Cifar10`.""" if not isinstance(cls, type): cls = cls.__class__ module_path = cls.__module__ if use_tfds_prefix and module_path.startswith('tensorflow_datasets'): module_path = '...
def one_to_three(one_letter): """ Convert a one letter code amino acid to a three letter code. """ assert one_letter.upper() in "FLSYCWPHERIMTNKVADQG*U", "Error, %s is not a valid amino acid" % one_letter AA = { "I": "Ile", "V": "Val", "L": "Leu", "F": "Phe", ...
def get_integer_form(elem_list): """For an element list like ['e1', 'a1_2', 'a1_1', 'a1_3'], return the integer 213, i.e., the 'subscripts' of the elements that follow the identity element.""" return int(''.join(map(lambda x: x.split("_")[1], elem_list[1:])))
def reverse_bits(v, bits): """ Do bit reversal operation. Example input (8 bits case): 11100001 10000111 """ y = 0 pos = bits - 1 while pos > 0: y += ((v & 1) << pos) v >>= 1 pos -= 1 return y
def get_cached_small_value(*args, **kwargs): """ Non-decorated base implementation of a method that fetches a property from a method of a class. Method receives """ prop, method, *args = args if isinstance(method, str): fn = getattr(prop, method) else: fn = method.__get_...
def rows_to_pages(rows): """ round up to the nearest 20, then divide by 20 eg 105 rounds to 120 then divides by 20 to returns 6""" return (rows - rows % -20) / 20
def join_url(*parts): """join parts of URL into complete url""" return '/'.join(str(s).strip('/') for s in parts)
def is_list_having_non_empty_items(list1): """ If the list has items, and if any of them is not empty/None, returns True. Otherwise, False. If the list has no elements, it returns False. If the list has elements but they are empty/None, return False. """ result = False if not list1: ...
def width(text, width): """ Insert a new line character for each block of `width` characters into the input text. :param str text: the input text for newlining. :param int width: a positive integer for dividing input with new lines. :returns: the newlined text. """ if not isinstance(wi...
def poorly_spaced_path(lam): """lam in [0,1] -> (offset in [0, 4], force_constant in [1, 16])""" lam_eff = lam ** 4 offset = 4 * lam_eff force_constant = 2 ** (4 * lam_eff) return offset, force_constant
def surround_quotes(obj): """ Surround input (string) with double quotes. """ # add double quotes around string obj = '"' + obj + '"' # return quoted string return obj
def populate_set(line, val_set): """ Collects values and put it in a set """ pos = line.find("\"") pos1 = line.rfind("\"") sub = line[pos + 1:pos1] val_list = sub.split(',') for val in val_list: val_set.add(float(val.strip())) return val_set
def DoSlash(sDirName): """Add a tailing slash if missing. """ return sDirName if sDirName[-1]=="/" else sDirName+"/"
def nullcnt(xs): """Counts null values in Graphite query result""" return len([x for x in xs if x is None])
def _get_subword_units(token, gram): """Return subword-units presentation, given a word/token. """ if token == '</s>': # special token for padding purpose. return [token] t = '#' + token + '#' return [t[i:i + gram] for i in range(0, len(t) - gram + 1)]
def cdr_to_stage(score): """ Convert the Clinical Dementia Rating scale (CDR) to descriptive terms (O'Bryant et al., 2010). This can be helpful for qualitative purposes. """ if score == 0.0: return ('Normal') elif score == 0.5: return ('Questionable') elif score == 1.0: ...
def _split_regex(regex): """ Return an array of the URL split at each regex match like (?P<id>[\d]+) Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/'] """ if regex[0] == '^': regex = regex[1:] if regex[-1] == '$': regex = regex[0:-1] res...
def umm_fields(item): """Return only the UMM part of the data""" if 'umm' in item: return item['umm'] return item
def calc_active_stake(staking_balance, deposit_cap, frozen_deposits_percentage=10): """ >>> full_balance = 1000 >>> calc_active_stake(9000, full_balance) 9000.0 >>> calc_active_stake(12000, full_balance) 10000.0 >>> calc_active_stake(9000, 400) 4000.0 >>> calc_active_stake(12000, 400...
def longest_common_subsequence_memoization(X, Y, m, n, dp): """ :param X: String 1st :param Y: String 2nc :param m: length of String 1 :param n: length of String 2 :param dp: Array for Storage of The Pre Calculate Value :return: length of Common Subsequence """ """ >>> longest_co...
def _create_weights_tuple(weights): """ Returns a tuple with the weights provided. If a number is provided, this is converted to a tuple with one single element. If None is provided, this is converted to the tuple (1.,) """ import numbers if weights is None: weights_tuple = (1.,) ...
def gen_names_for_range(N, prefix="", start=1): """generates a range of IDS with leading zeros so sorting will be ok""" n_leading_zeros = len(str(N)) format_int = prefix + "{:0" + str(n_leading_zeros) + "d}" return [format_int.format(i) for i in range(start, N + start)]
def strip_account_url(account_url): """ Remove http/https for an URL """ if account_url: if 'https://' in account_url: account_url = account_url.split('https://')[1] elif 'http://' in account_url: account_url = account_url.split('http://')[1] return accoun...
def deref_or_none(dictionary, key): """ @brief Look up a key in a dict; return None if not found """ if not dictionary: return None if key in dictionary.keys(): return dictionary[key] else: return None
def bool_(input_): """ Convert boolean or string to boolean, also 'False' and 'F' to False """ return bool(input_) if input_.upper() not in ["FALSE", "F"] else False
def get_default_params_bps_par(): """Return a tuple containing the default velocity perturbation parameters given in :cite:`BPS2006` for the parallel component.""" return (10.88, 0.23, -7.68)
def get_list_type(param_type): """ return type of given list """ if str(param_type).find('[str]') != -1: return str if str(param_type).find('[int]') != -1: return int if str(param_type).find('[float]') != -1: return float if str(param_type).find('[bool]') != -1: ...
def unicode_to_str(value): """If python2, returns unicode as a utf8 str""" if type(value) is not str and isinstance(value, type(u"")): value = value.encode("utf8") return value
def argparse_bool(s): """ parse the string s to boolean for argparse :param s: :return: bool or None by default example usage: parser.add_argument("--train", help="train (finetune) the model or not", type=mzutils.argparse_bool, default=True) """ if not isinstance(s, str): return s ...
def input_to_int(usr_input): """ Testuje zda-li uzivatelem zadany vstup je cislo. Pokud ano vraci ho. :param usr_input: uzivatelsky vstup :return: uzyivatelsky vstu prevedeny na int, v pripade neuspechu -1 """ try: value = int(usr_input) except ValueError: return -1 if v...
def parse_default_value(default_value, value_type, recognized_types=('Bool', 'DecDouble')): """ Parses default_value string to actual usable C++ expression. @param default_value_str: default_value field specified in document_policy_features.json5 @param value_...
def conv_str_to_bool(text, mapping_dict=None): """ Map a text to a boolean value. The default text to bool mapping is provided in the default_map dict below, however text and mapping_dict as inputs to map as per needs. default_map = {'yes': True, 'y': True, 'no': False, 'n': False } """ ...
def sec_to_time(seconds): """Transform seconds into a formatted time string. Parameters ----------- seconds : int Seconds to be transformed. Returns ----------- time : string A well formatted time string. """ m, s = divmod(seconds, 60) h, m = divmod(m, 60) r...
def check_prime(number) -> bool: """ :param number: Number :return: bool (True/False) """ if number <= 1: return False if number <= 3: return True if number % 2 == 0 and number % 3 == 0: return False i = 5 while i * i <= number: if number % i == 0 ...
def power(x,p): """ Elevates the number x to the power p. Arguments: ---------- * x [int/float]: a number. * p [int]: the power that will elevate x. Return: ------- * res [int/float]: result of x**p Why?: ----- According to the project pdf, the only authhorize...
def get_chapter_number(verse_id: int) -> int: """ Given a verse id return the int chapter number. :param verse_id: :return: int chapter number """ return int(verse_id % 1000000 / 1000)
def perm_recursive(S): """ Return a list with all permutations of the iterable passed as argument. Uses the simple recursive solution. This Algorithm does not handle repeated elements well. """ def expand_inserting(c, L): return [L[0:i] + [c] + L[i:] for i in range(len(L) + 1)] if not...
def save_split(s, sep, maxsplit): """Split string, always returning n-tuple (filled with None if necessary).""" tok = s.split(sep, maxsplit) while len(tok) <= maxsplit: tok.append(None) return tok
def majorToLNames(thisMajor,listOfStudents): """ return a list of the last names of students with the major, thisMajor >>> majorToLNames("MATH",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")]) ['KAY'] >>> """ answerList = [] for stud...
def group(merge_func, tokens): """ Group together those of the tokens for which the merge function returns true. The merge function should accept two arguments/tokens and should return a boolean indicating whether the strings should be merged or not. Helper for tokenise(string, ..). """ out...
def filePathToSafeString(filePath): """ Returns string representation of a given filepath safe for a single filename usage >>> filePathToSafeString('C:/Windows/system32') 'C__Windows_system32' """ retVal = filePath.replace("/", "_").replace("\\", "_") retVal = retVal.replace(" ", "_").repl...
def is_power_of_two(input_integer): """ Test if an integer is a power of two. """ if input_integer == 1: return False return input_integer != 0 and ((input_integer & (input_integer - 1)) == 0)
def describe_list_indices(full_list): """ Describe the indices of the given list. Parameters ---------- full_list : list The list of items to order. Returns ------- unique_elements : list A list of the unique elements of the list, in the order in which they firs...
def get_survived_value(x): """ returns the int value for the nominal value survived :param x: a value that is either 'yes' or 'no' :return: returns 1 if x is yes, or 0 if x is no """ if x == 'yes': return 1 else: return 0
def quarter_for_month(month): """return quarter for month""" if month not in range(1, 13): raise ValueError('invalid month') return {1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2, 7: 3, 8: 3, 9: 3, 10: 4, 11: 4, 12: 4}[month] # return (month + 2) // 3
def fib(n: int) -> int: """ :param n: input integer :return: Nth number of fibonacci sequence Time complexity : O(2^n) Space complexity : O(n) """ if n <= 2: return 1 return fib(n - 1) + fib(n - 2)
def group_by(iterable, key_selector): """ Returns an iterator which groups the iterable with a key provided by the supplied function. The source iterable does not need to be sorted. :param iterable: The items over which to iterate. :param key_selector: A function which selects the key to group on. ...
def restructure_gene_info(allele_annotations): """Restructure information related to gene """ gene_data = [] assembly_annotation = allele_annotations[0].get('assembly_annotation') if assembly_annotation and assembly_annotation[0]: for _doc in assembly_annotation[0].get('genes'): ...
def insertNewlines(text, lineLength): """ Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character ("\n") after each word that reaches or exceeds the desired line length. text: a string containing the text to wrap. line_length: the number of characte...
def partition(alist, indices): """A function to split a list based on item indices Parameters: ----------------------------- : alist (list): a list to be split : indices (list): list of indices on which to divide the input list Returns: ----------------------------- ...
def r(out, target, std_deviation, daily_return): """ Calculates a term that is used more often :param out: output from model :param target: target returns (annual) :param std_deviation: volatility estimate :param daily_return: daily returns for each time step :return: """ return out ...
def calc_recall(TP, FN): """ Calculate recall from TP and FN """ if TP + FN != 0: recall = TP / (TP + FN) else: recall = 0 return recall
def HumanizeBytes(totalBytes, precision=1, suffix=None): """ Convert a number of bytes into the appropriate pretty kiB, MiB, etc. Args: totalBytes: the number to convert precision: how many decimal numbers of precision to preserve suffix: use this suffix (kiB, MiB, etc.) instea...
def translate(x1, x2): """Translates x2 by x1. Parameters ---------- x1 : float x2 : float Returns ------- x2 : float """ x2 += x1 return x2
def _ExtractBertThroughput(output): """Extract throughput from Horovod output. Args: output: Horovod output Returns: A tuple of: Average throughput in sentences per second (float) Unit of the throughput metric (str) """ # Start from last line and iterate backwards. avg_throughput = 0 ...
def get_offset(num, rows, spacing): """Return offset from prototype position. Positional arguments: num -- the number of the object, starting from 0 rows -- how many rows before wrapping spacing -- a tuple of (x,y) spaing between objects """ x_offset = (num % rows) * spacing[0] # x-sp...
def generate_time_str(time): """convert time (in seconds) to a text string""" hours = int(time // 60**2) minutes = int((time - hours*60**2) // 60) seconds = int((time - hours*60**2 - minutes*60) // 1) ret = '' if hours: unit = 'hr' if hours == 1 else 'hrs' ret += f'{hours} {unit...
def cnf_sat(clauses): """ returns true if clauses is satisfied """ return len(clauses) == 0
def unquote(s): """Strip single quotes from the string. :param s: string to remove quotes from :return: string with quotes removed """ return s.strip("'")
def turn(orientation, direction): """Given an orientation on the compass and a direction ("L" or "R"), return a a new orientation after turning 90 deg in the specified direction.""" compass = ['N', 'E', 'S', 'W'] if orientation not in compass: raise ValueError('orientation must be N, E, ...
def _map_features(features, support): """Map old features indices to new ones using boolean mask.""" feature_mapping = {} new_idx = 0 for (old_idx, supported) in enumerate(support): if supported: val = new_idx new_idx += 1 else: val = None feat...
def constraintsHAngles(bonds): """Given a set of bonds from a Topology, return the set of angle constraints that you expect to appear in the system. An angle is constrained if the bond sequence is H-O-X or H-X-H where X is any element. """ expected_constraint_set = set() for bond in bonds: ...