content
stringlengths
42
6.51k
def str_or_none(arg): """Returns None or str from a `str_or_none` input argument. """ if arg is None or str(arg).lower() == 'none': return None return str(arg)
def find_digits_in_str(string: str) -> str: """Find digits in a given string. Args: string: str, input string with the desired digits Returns: digits: str, found in the given string """ return "".join(x for x in string if x.isdigit())
def _set_deferred_timeout(reactor, deferred, timeout): """ NOTE: Make sure to call this only from the reactor thread as it is accessing twisted API. Sets a maximum timeout on the deferred object. The deferred will be cancelled after 'timeout' seconds. This timeout represents the maximum allowed time for Fido to wait for the server response after the connection has been established by the Twisted Agent. """ if timeout is None: return # set a timer to cancel the deferred request when/if the timeout is hit cancel_deferred_timer = reactor.callLater(timeout, deferred.cancel) # if request is completed on time, cancel the timer def request_completed_on_time(response): if cancel_deferred_timer.active(): cancel_deferred_timer.cancel() return response deferred.addBoth(request_completed_on_time)
def get_index_comma(string): """ Return index of commas in string """ index_list = list() # Count open parentheses par_count = 0 for i in range(len(string)): if string[i] == ',' and par_count == 0: index_list.append(i) elif string[i] == '(': par_count += 1 elif string[i] == ')': par_count -= 1 return index_list
def fhex(x, nDigits=2, prefix="0x", upper=True): """ Returns a hex string of the number `x`, with a fixed number `nDigits` of digits, prefixed by `prefix`. If `upper` is `True`, hex digits are upper-case, otherwise lower-case. >>> fhex(15) '0x0F' >>> fhex(255, 4, "", False) '00ff' .. seealso:: http://stackoverflow.com/a/12638477/1913780 """ return "{prefix}{x:0{nDigits}{case}}".format( prefix=prefix, x=x, nDigits=nDigits, case="X" if upper else "x", )
def jaro_similarity(s1, s2): """ Computes the Jaro similarity between 2 sequences from: Matthew A. Jaro (1989). Advances in record linkage methodology as applied to the 1985 census of Tampa Florida. Journal of the American Statistical Association. 84 (406): 414-20. The Jaro distance between is the min no. of single-character transpositions required to change one word into another. The Jaro similarity formula from https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance : jaro_sim = 0 if m = 0 else 1/3 * (m/|s_1| + m/s_2 + (m-t)/m) where: - |s_i| is the length of string s_i - m is the no. of matching characters - t is the half no. of possible transpositions. """ # First, store the length of the strings # because they will be re-used several times. len_s1, len_s2 = len(s1), len(s2) # The upper bound of the distance for being a matched character. match_bound = max(len_s1, len_s2) // 2 - 1 # Initialize the counts for matches and transpositions. matches = 0 # no.of matched characters in s1 and s2 transpositions = 0 # no. of transpositions between s1 and s2 flagged_1 = [] # positions in s1 which are matches to some character in s2 flagged_2 = [] # positions in s2 which are matches to some character in s1 # Iterate through sequences, check for matches and compute transpositions. for i in range(len_s1): # Iterate through each character. upperbound = min(i + match_bound, len_s2 - 1) lowerbound = max(0, i - match_bound) for j in range(lowerbound, upperbound + 1): if s1[i] == s2[j] and j not in flagged_2: matches += 1 flagged_1.append(i) flagged_2.append(j) break flagged_2.sort() for i, j in zip(flagged_1, flagged_2): if s1[i] != s2[j]: transpositions += 1 if matches == 0: return 0 else: return ( 1 / 3 * ( matches / len_s1 + matches / len_s2 + (matches - transpositions // 2) / matches ) )
def add_position_to_list_token(list_tokens): """add postion of each token in list of token Arguments: list_tokens {list} -- list of token Returns: list -- list of token with postion of each token """ list_tokens_pos = [] postion = 0 for token in list_tokens: list_tokens_pos.append((token, postion)) postion += 1 return list_tokens_pos
def split_by_value( total, nodes, headdivisor=2.0 ): """Produce, (sum,head),(sum,tail) for nodes to attempt binary partition""" head_sum,tail_sum = 0,0 divider = 0 for node in nodes[::-1]: if head_sum < total/headdivisor: head_sum += node[0] divider -= 1 else: break return (head_sum,nodes[divider:]),(total-head_sum,nodes[:divider])
def string_to_bool(raw_input): """Convert ("True","true","TRUE") to (True)..""" mapping = { "True": True, "False": False, "true": True, "false": False, "TRUE": True, "FALSE": False, } if raw_input in mapping.keys(): return mapping[raw_input] else: return None
def hash_init(size): """ initialises new hash table INPUTS: size of 1D hash table, int size should be greater than length of data * 2 in order to reduce conflicts OUTPUTS: hash table EXAMPLES: >>> hash_init(); """ #initialise KV = {"key": "", "value": None}; hash = []; #create 1D matrix for i in range(size): hash.append([KV]); return hash;
def mse(x, x_hats): """Mean squared error (MSE) cost function Args: x: One true value of $x$ x_hat: Estimate of $x$ Returns: ndarray of the MSE costs associated with predicting x_hat instead of x$ """ return (x - x_hats)**2
def get_max_value_key(dic): """ Fast method to get key for maximum value in dict. From https://github.com/nicodv/kmodes """ v = list(dic.values()) k = list(dic.keys()) return k[v.index(max(v))]
def iterative_lcm(x: int, y: int): """determine which is the smaller number among the 2 integer and do a iterative call of lcm % large_number""" if x < y: small = x large = y else: small = y large = x lcm = small while lcm%large !=0: lcm = lcm + small return lcm
def make_pair(img_paths, label_paths): """Take a list of image paths and the list of corresponding label paths and return a list of tuples, each containing one image path and the corresponding label path. Arguments: img_paths (list of `Path`): list of paths to images. labels_paths (list of `Path`): list of paths to labels. Returns: pairs (list of tuple): a list of tuples. Each tuple contain an image and the corresponding label. """ if len(img_paths) != len(label_paths): raise ValueError("The lengths of the two lists mismatch.") pairs = [] for img_path, label_path in zip(sorted(img_paths), sorted(label_paths)): img_stem = img_path.stem.replace("_leftImg8bit", "") label_stem = label_path.stem.replace("_gtFine_labelIds", "") if img_stem == label_stem: pair = (img_path, label_path) pairs.append(pair) return pairs
def hex_to_rgb(hex): """ Converts hex to rgb colours Parameters ---------- hex : string 6 characters representing a hex color Returns ------- rgb : tuple (length 3) RGB values References ---------- https://towardsdatascience.com/beautiful-custom-colormaps-with-matplotlib-5bab3d1f0e72 """ hex = hex.strip('#') # removes hash symbol if present lv = len(hex) return tuple(int(hex[i : i + lv // 3], 16) for i in range(0, lv, lv // 3))
def adder(x, y): """Add two numbers together.""" print("INSIDE ADDER!") return x + y
def render_location(data, query): """ location (l) """ return (data['override_location'] or data['location'])
def int_to_rgb(int_): """Integer to RGB conversion""" red = (int_ >> 24) & 255 green = (int_ >> 16) & 255 blue = (int_ >> 8) & 255 return red, green, blue
def getDAPI(filename): """ Simple string manipulation helper method to replace "FITC" with "DAPI" and "Blue" with "UV" of input FILENAME, Returns the modified string """ DAPI = filename.replace("FITC", "DAPI") DAPI = DAPI.replace("Blue", "UV") return DAPI
def _has_endpoint_name_flag(flags): """ Detect if the given flags contain any that use ``{endpoint_name}``. """ return '{endpoint_name}' in ''.join(flags)
def parse_price(params): """ Normalize price. """ params['price'] = int(params['price']) return params
def new_mean_temperature(area, height_external, temperature_external, heat): """ Calculates a new mean temperature for the volume. :param area: in m^2 :param height_external: in m :param temperature_external: in K :param heat: in J :return: temperature in K """ volume_air = area * height_external specific_heat_capacity = 1005 # J/kgK density_air = 1.29 * 273 / temperature_external # kg/m^3 energy_air = volume_air * specific_heat_capacity * density_air * temperature_external # J return (energy_air + heat)/(volume_air * density_air * specific_heat_capacity)
def chunk_sequence(sequence, chunk_length, allow_incomplete=True): """Given a sequence, divide it into sequences of length `chunk_length`. :param allow_incomplete: If True, allow final chunk to be shorter if the given sequence is not an exact multiple of `chunk_length`. If False, the incomplete chunk will be discarded. """ (complete, leftover) = divmod(len(sequence), chunk_length) if not allow_incomplete: leftover = 0 chunk_count = complete + min(leftover, 1) chunks = [] for x in range(chunk_count): left = chunk_length * x right = left + chunk_length chunks.append(sequence[left:right]) return chunks
def sanitize_input(data): """Sanitizes input for reddit markdown tables""" data = data.replace('|', '&#124;') data = data.replace('\n', '') data = data.replace('*', '\\*') return data
def transform(subject: int, loop_size: int) -> int: """Transform the ``subject`` in ``loop_size`` steps of a hard-coded algorithm.""" value = 1 for _ in range(loop_size): value *= subject value %= 20201227 return value
def remove_prefix(s, pre): """ Remove prefix from the beginning of the string Parameters: ---------- s : str pre : str Returns: ------- s : str string with "pre" removed from the beginning (if present) """ if pre and s.startswith(pre): return s[len(pre):] return s
def accuracy(a, b): """Function to return accuracy based on 10% difference""" scale = a * 0.1 if b <= a + scale and b >= a - scale: return 1 else: return 0
def flatten_bookmarks(bookmarks, level=0): """Given a list, possibly nested to any level, return it flattened.""" output = [] for destination in bookmarks: if type(destination) == type([]): output.extend(flatten_bookmarks(destination, level+1)) else: output.append((destination, level)) return output
def set_id(project_id, entity, args): """ :param project_id: :param entity: :param args: :return: """ entity["_id"] = str(project_id) + "-" + str(entity[args.get('id')]) return entity
def quantile(x,quantiles): """ Calculates quantiles - taken from DFM's triangle.py """ xsorted = sorted(x) qvalues = [xsorted[int(q * len(xsorted))] for q in quantiles] return list(zip(quantiles,qvalues))
def solution(nums: list) -> list: """ This function sorts the passed in array of numbers. """ if nums is None: return [] return sorted(nums)
def recursive_walker(tree, level=0, handlers=[], verbose=True): """recursive walker Recursively walk any tree-like structure such as dictionaries and lists. Common use cases are json or xml data. Arguments: - tree(dict): the tree to walk as dict - level(int): recursion depth information - handlers(list): list of callback functions to be evaluated for each step - verbose(bool): debug verbosity Returns: - None """ # assert iscomposite(tree), 'recursive_walker: arg tree has wrong type = %s' % (type(tree)) spacer = ' ' * 4 * level # if verbose: print('recursive_walker%s[%02d]' % (spacer, level)) # a tree leaf # if not iscomposite(tree): # apply callbacks for h in handlers: h(tree, level=level, handlers=handlers, verbose=verbose) return None
def find(element, JSON, path=None, all_paths=None, mutable=False): """Get paths to a value in JSON data. Usage: find(value, data) """ all_paths = [] if all_paths is None else all_paths path = tuple() if path is None else path if isinstance(JSON, dict): for key, value in JSON.items(): find(element, value, path + (key,), all_paths, mutable) elif isinstance(JSON, list): for index, value in enumerate(JSON): find(element, value, path + (index,), all_paths, mutable) else: if JSON == element: if mutable: path = list(path) all_paths.append(path) if not mutable: all_paths = tuple(all_paths) return all_paths
def _shell_quote(s): """Copy of bazel-skylib's shell.quote. Quotes the given string for use in a shell command. This function quotes the given string (in case it contains spaces or other shell metacharacters.) Args: s: The string to quote. Returns: A quoted version of the string that can be passed to a shell command. """ return "'" + s.replace("'", "'\\''") + "'"
def sensorOptimizer(horizontal, vertical, imageSize): """ Checks and adjusts a source image sensor size for compatiabilty with given image dimensions. Args: horizontal (float): sensor width in mm vertical (float): sensor height in mm imageSize (x,y): dimensions of given images in px Returns: (sensorWidth, sensorHeight) """ sensor = (horizontal, vertical) if imageSize[0] / imageSize[1] != sensor[0] / sensor[1]: newSensor = (sensor[0], (imageSize[1] * sensor[0]) / imageSize[0]) if newSensor[1] > sensor[1]: newSensor = ((sensor[1] * imageSize[0]) / imageSize[1], sensor[1]) return newSensor return sensor
def exp(x, epsilon=1e-16, maxiter=100): """ Computes an approximation of exp(x) using its series.""" epsilon = epsilon * x # relative precision nbiter = 1 exp_x = 1.0 x_power_n = x factorial_n = 1.0 delta_exp_x = x_power_n / factorial_n while delta_exp_x > epsilon and nbiter < maxiter: exp_x += delta_exp_x nbiter += 1 x_power_n *= x factorial_n *= nbiter delta_exp_x = x_power_n / factorial_n return exp_x
def calculate_mturk_cost(payment_opt): """MTurk Pricing: https://requester.mturk.com/pricing 20% fee on the reward and bonus amount (if any) you pay Workers. HITs with 10 or more assignments will be charged an additional 20% fee on the reward you pay Workers. Example payment_opt format for paying reward: { 'type': 'reward', 'num_total_assignments': 1, 'reward': 0.05 # in dollars 'unique': False # Unique workers requires multiple assignments to 1 HIT } Example payment_opt format for paying bonus: { 'type': 'bonus', 'amount': 1000 # in dollars } """ total_cost = 0 if payment_opt['type'] == 'reward': mult = 1.2 if payment_opt['unique'] and payment_opt['num_total_assignments'] > 10: mult = 1.4 total_cost = \ payment_opt['num_total_assignments'] * payment_opt['reward'] * mult elif payment_opt['type'] == 'bonus': total_cost = payment_opt['amount'] * 1.2 return total_cost
def merge_two_sorted_lists(list_1, list_2): """ Purpose: Merge two sorted lists into one sorted list Args: list_1 (List): Sorted List to Merge list_2 (List): Sorted List to Merge Returns: sorted_list (List): Merged Sorted List """ sorted_list = [] list_1_idx, list_2_idx, sorted_list_idx = 0, 0, 0 while list_1_idx < len(list_1) and list_2_idx < len(list_2): if list_1[list_1_idx] < list_2[list_2_idx]: sorted_list.append(list_1[list_1_idx]) list_1_idx += 1 else: sorted_list.append(list_2[list_2_idx]) list_2_idx += 1 if list_1_idx < len(list_1): while list_1_idx < len(list_1): sorted_list.append(list_1[list_1_idx]) list_1_idx += 1 if list_2_idx < len(list_2): while list_2_idx < len(list_2): sorted_list.append(list_2[list_2_idx]) list_2_idx += 1 return sorted_list
def getid(obj): """ Abstracts the common pattern of allowing both an object or an object's ID as a parameter when dealing with relationships. """ try: return obj.id except AttributeError: return obj
def virtualTemperature(T,r): """ """ return T*(0.622+r)/(0.622*(1+r))
def tuple_in_group_with_wildcards(needle, haystack): """Checks if needle is in haystack, allowing for wildcard components. Returns True if either needle or haystack is None, or needle is in haystack. Components in haystack are tuples. These tuples can have entries equal to None which serve as wildcard components. For example, if haystack = [(None, ...), ...], The first tuple in haystack has a wildcard for its first component. Args: needle (tuple): tuple to check if in group haystack (list): list of tuples of the same dimensions as tup. Returns: True if the tuple is in the group, False otherwise Raises: ValueError: Length of tup must match length of each tuple in group." """ if needle is None or haystack is None: return True if any(len(needle) != len(it_needle) for it_needle in haystack): raise ValueError("Length of tup must match length of each tuple in group.") for it_needle in haystack: if all(needle_comp == it_needle_comp or it_needle_comp is None for needle_comp, it_needle_comp in zip(needle, it_needle)): return True return False
def _dedupe_preserve_order(seq): """De-dupe a list, but preserve order of elements. https://www.peterbe.com/plog/uniqifiers-benchmark """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def canonical_gpu_indices(indices): """ If ``indices`` is not None, cast it to list of int. """ if isinstance(indices, str): return [int(idx) for idx in indices.split(',')] if isinstance(indices, int): return [indices] return indices
def augmentTermList(terms): """ Adds additional spellings and plurals to a list of cancer terms Args: terms (list of strings): List of strings of terms Returns: list of augmente strings """ # Lower case everything (if not already done anyway) terms = [ t.lower() for t in terms ] # A list of short cancer terms that are acceptable (others like ALL are too general and excluded) acceptedShortTerms = ["gbm","aml","crc","hcc","cll"] # Filter out smaller terms except the allowed ones terms = [ t for t in terms if len(t) > 3 or t in acceptedShortTerms ] # Filter out terms with a comma terms = [ t for t in terms if not ',' in t ] # Filter out terms with a semicolon terms = [ t for t in terms if not ';' in t ] # Filter out terms that start with "of " terms = [ t for t in terms if not t.startswith('of ') ] # Try the British spelling of tumor tumourTerms = [ t.replace('tumor','tumour') for t in terms ] # Terms that we can add an 'S' to pluralise (if not already included) pluralEndings = ["tumor", "tumour", "neoplasm", "cancer", "oma"] # Check if any term ends with one of the plural endings, and then pluralise it plurals = [] for t in terms: pluralize = False for e in pluralEndings: if t.endswith(e): pluralize = True break if pluralize: plurals.append(t + "s") # Sorted and unique the terms back together merged = sorted(list(set(terms + tumourTerms + plurals))) return merged
def _manhattan_distance(x0: float, y0: float, x1: float, y1: float) -> float: """Get manhattan distance between points (x0, y0) and (x1, y1).""" return abs(x0 - x1) + abs(y0 - y1)
def _bounded(original, default, maximum): """Makes sure a value is within bounds""" # If "original" comes from command line, it may be a string try: value = int(original) except ValueError: value = 0 # Check bounds if value < default: value = default if value > maximum: value = maximum return value
def solver_problem2(position): """input position and return min fuel cost of alignment with linear costs""" min_fuel = float("Inf") for i in range(min(position), max(position)): dist = [0] * len(position) dist = [ abs(position[j] - i) * (abs(position[j] - i) + 1) // 2 for j in range(len(position)) ] min_fuel = min(min_fuel, sum(dist)) return min_fuel
def extract_epoch(filename): """ Get the epoch from a model save string formatted as name_Epoch:{seed}.pt :param str: Model save name :return: epoch (int) """ if "epoch" not in filename.lower(): return 0 epoch = int(filename.lower().split("epoch_")[-1].replace(".pt", "")) return epoch
def linear_search(array, n): """ - Definition - In computer science, linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. Comlexity: Time Complexity: O(n) - since in worst case we're checking each element exactly once. """ is_found = False for i in array: if i == n: is_found = True else: continue return is_found
def checkdms(dms): """Verify a sexagesimal string; returns True if valid, False if not """ assert isinstance(dms, str) try: d=dms.split(':') for i in range(3): float(d[i]) return True except: return False
def _is_list(s): """Check a value is a CSV list.""" if s[0] == '[' and s[-1] == ']': return True else: return False
def pad(T, count): """Returns a 64-bit block padded to 8 bytes with PKCS#5 padding. pad assumes that its input is a byte array of length 8 and an integer between 1 and 8. The last count bytes of the array are assumed empty and will be overwritten with a byte representation of count. Some basic sanity checks are performed to avoid indexing out of bounds if this assumption is violated, but the results in that case are not defined. Keyword arguments: T -- A plain text string of 0 to 7 bytes in an 8-byte array. count -- The number of bytes at the tail of the input block to overwrite. """ if count > 0 and count <= len(T): for i in range(count): T[len(T) - (i + 1)] = count return T
def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ # Your code here dicHelp = {} for item in L: if item in dicHelp.keys(): dicHelp[item] += 1 else: dicHelp[item] = 1 dicHelpCopy = dicHelp.copy() for eachKey in dicHelp.keys(): if dicHelp[eachKey] % 2 == 0: dicHelpCopy.pop(eachKey) if not dicHelpCopy: return else: return max(dicHelpCopy.keys())
def problem_19_2(table): """ Design an algorithm to figure out if someone has won in a game of tic-tac-toe. Complexity: O(n^2) Args: table: list of list, dimentions NxN, filled with 1s and 0s Returns: boolean, True if 1 wins or False if 0 wins. """ n = len(table) sum_cols = [0] * n sum_rows = [0] * n sum_diag = [0] * 2 for row in range(n): for col in range(n): sum_rows[row] += table[row][col] sum_cols[col] += table[row][col] if row == col: sum_diag[0] += table[row][col] if row == n - col: sum_diag[1] += table[row][col] for sum_col in sum_cols: if sum_col == n: return True elif sum_col == 0: return False for sum_row in sum_rows: if sum_row == n: return True elif sum_row == 0: return False for i in range(2): if sum_diag[i] == n: return True elif sum_diag[i] == 0: return False return None
def buble_sort_naive(l): """ We start with this naive approach that just check if element close by and update the boolean variable and swap accondingly The complexity of this algorithm is O(n^2) """ swap = True while swap: swap = False for i in range(len(l)-1): if l[i]>l[i+1]: l[i], l[i+1] = l[i+1], l[i] swap = True return l
def sanitize_fb_return_data(results): """ sometimes integers are returned as string try to sanitize this a bit """ return_results = {} for instance in results: # turn None => 0 if results[instance] is None: return_results.update({instance: 0}) else: # try to parse as int try: return_results.update({instance: int(results[instance])}) # keep it a string if this fails except ValueError: return_results.update({instance: results[instance]}) return return_results
def test_progress(arg1, arg2, kwd1, kwd2, progress): """Simple test target for submit_progress.""" return arg1, arg2, kwd1, kwd2
def in_festival(fest_coord, approx_loc, radius): """ # Calculates the distance between two coordinates # using the distance formula. Returns true if distance # is less than or equal to the given radius # (festival is in GPS radius). >>> in_festival([1,2], [2,4], 2) False >>> in_festival([1,2], [3,2], 1) False >>> in_festival([1,2], [2,2], 1) True # Add at least 3 doctests below here # >>> in_festival([0, 0], [0, 0], 10000) True >>> in_festival([-1, 1], [1, 1], 4) True >>> in_festival([-1, 1], [1, 1], 1.5) False """ return ((fest_coord[1] - approx_loc[1]) ** 2 + (fest_coord[0] - approx_loc[0]) ** 2) ** 1/2 <= radius
def deslugify(slug): """Turn a slug into human speak""" return slug.replace('-', ' ').title()
def addElementwiseListArray(list1, list2): """ Add together the arrays of two lists (takes the length of the list1) """ l3 = [] for i in range(len(list1)): l3.append(list1[i] + list2[i]) return l3
def _cal_output_shape(height, width, kernel_shape, strides, pad): """ Args: kernel_shape: [height, width] strides: [height, width] pad: 'SAME' or 'VALID' Returns: output_shape: [output_h, output_w] """ # check the options of padding if (pad != 'SAME' and pad != 'VALID'): raise Exception("the option of padding must be either 'SAME' or 'VALID'") kernel_h, kernel_w = kernel_shape stride_h, stride_w = strides # calculate output_h if strides[0] == 1: if pad == 'SAME': output_h = height else: # VALID output_h = height + kernel_h - 1 elif strides[0] > 1: if pad == 'SAME': # output_h = (height - 1) * stride_h + kernel_h - 2 * pad_h # assuming padding is 1 output_h = (height - 1) * stride_h + kernel_h - 2 else: # VALID output_h = (height - 1) * stride_h + kernel_h else: raise ValueError # calculate output_w if strides[1] == 1: if pad == 'SAME': output_w = width else: # VALID output_w = width + kernel_w - 1 elif strides[1] > 1: if pad == 'SAME': output_w = (width - 1) * stride_w + kernel_w - 2 else: # VALID output_w = (width - 1) * stride_w + kernel_w else: raise ValueError return output_h, output_w
def mymap(x, r1, r2, s1, s2): """ Map x from range (r1, r2) to (s1, s2) """ rs = r2 - r1 ss = s2 - s1 return (x - r1)/rs * ss + s1
def _build_extended_bounds(from_ms=None, to_ms=None): """ Build extended_bounds """ bounds = {} if from_ms is not None: bounds['min'] = from_ms if to_ms is not None: bounds['max'] = to_ms return bounds
def kaiser_beta(a): """Compute the Kaiser parameter `beta`, given the attenuation `a`. Parameters ---------- a : float The desired attenuation in the stopband and maximum ripple in the passband, in dB. This should be a *positive* number. Returns ------- beta : float The `beta` parameter to be used in the formula for a Kaiser window. References ---------- Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476. """ if a > 50: beta = 0.1102 * (a - 8.7) elif a > 21: beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21) else: beta = 0.0 return beta
def convert_indices_to_mesh_faces(indices, mesh): """ Given a list of indices convert them to the names of faces. """ faces = [] for index in indices: faces.append('%s.f[%s]' % (mesh, index)) return faces
def tint_green(text: str) -> str: """Tints a given text green. :param text: The text to be tinted :type text: str :returns: The same text but tinted green :rtype: str """ return ("\x1b[32m%s\x1b[0m" % text)
def cycle_prev(id,cycle_length): """ computes the previous id in a cycle Parameters ---------- id : integer The index of an item in the cycle. cycle_length : integer The length of the cycle. Returns ------- integer The index of the previous item in the cycle """ if id==0: return cycle_length-1 else: return id-1
def check_meta_result(result, expected_value=None): """Check the result of a 'get' metadata operation """ if not isinstance(result, dict): return "pwrcmd output is not a dict" # Some errors return only the error itself if result['PWR_ReturnCode'] != 0 and "value" not in result: return None # value must exist as if PWR_ReturnCode is 0 (successful 'get') if "value" not in result: return "'value' not found" if expected_value is not None: if str(result['value']) != str(expected_value): return "Result value ({}) did not match expected ({})".format(result['value'], expected_value) return None
def which(program): """ Test to make sure that the program is executable """ import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def value(tab, i): """Return 3 digit value starting at position i[index starts from 1].""" return tab[i - 1] * 100 + tab[i] * 10 + tab[i + 1]
def _strip_tex_contents(lines, end_str): """Removes everything after end_str.""" for i in range(len(lines)): if end_str in lines[i]: if '%' not in lines[i]: return lines[:i + 1] elif lines[i].index('%') > lines[i].index(end_str): return lines[:i + 1] return lines
def unicode_str(string): """Converts a bytestring to a unicode string""" try: value = string.decode('utf-8') except AttributeError: value = string return value
def plural(items_or_count, singular: str, count_format='') -> str: """Returns the singular or plural form of a word based on a count.""" try: count = len(items_or_count) except TypeError: count = items_or_count num = f'{count:{count_format}}' if singular.endswith('y'): return f'{num} {singular[:-1]}{"y" if count == 1 else "ies"}' if singular.endswith('s'): return f'{num} {singular}{"" if count == 1 else "es"}' return f'{num} {singular}{"" if count == 1 else "s"}'
def _parser_choose_help(alt_words, index): """Take all the remain Word's as help (and respect Space's inside the Word's)""" help_tail = " ".join(alt_words[index:]) if not alt_words[index:]: help_tail = " ".join(_.lstrip("-") for _ in alt_words[:index]) help_tail = help_tail.replace("[", "").replace("]", "") help_tail = help_tail.title() help_else_none = help_tail if help_tail else None return help_else_none
def list_contains(list1, list2): """Return True if any item in `list1` is also in `list2`.""" for m in list1: for n in list2: if n == m: return True return False
def _update_schema_1_to_2(table_metadata, table_path): """ Given a `table_metadata` of version 1, update it to version 2. :param table_metadata: Table Metadata :param table_path: [String, ...] :return: Table Metadata """ table_metadata['path'] = tuple(table_path) table_metadata['schema_version'] = 2 table_metadata.pop('table_mappings', None) return table_metadata
def validate_budget(data): """Validate budget input.""" errors = [] savings = data.get("savings") if savings and not 0 <= savings <= 100: errors.append("Savings is out of range.") income = data.get("income") if income and income < 0: errors.append("Income must be positive.") return errors
def TYPE(expression): """ Returns a string that specifies the BSON type of the argument. See https://docs.mongodb.com/manual/reference/operator/aggregation/type/ for more details :param expression: The expression or variable :return: Aggregation operator """ return {'$type': expression}
def _BackendsToCell(backend_service): """Comma-joins the names of the backend services.""" return ','.join(backend.get('group') for backend in backend_service.get('backends', []))
def url_builder(cid, university): """Build URL for employee scraping.""" url_search_base = 'https://www.linkedin.com/search/results/people/?' url_search_people_company = '%sfacetCurrentCompany=["''%s''"]&page=' % (url_search_base, cid) url_search_people_university = '%s&facetSchool=["''%s''"]&origin=FACETED_SEARCH&page=' % (url_search_base, cid) if not university: url_employee_scraper = url_search_people_company else: url_employee_scraper = url_search_people_university return url_employee_scraper
def xor_hashes(*elements: object) -> int: """Combine all element's hashes with xor """ _hash = 0 for element in elements: _hash ^= hash(element) return _hash
def drain_semaphore_filename(component: str) -> str: """Obtain the canonical drain semaphore filename for the specified component name.""" return f".lta-{component}-drain"
def is_pysource(fname): """A file name is a python source file iff it ends with '.py' and doesn't start with a dot. """ return not fname.startswith('.') and fname.endswith('.py')
def add_session_message_padding(data: bytes, length): """Adds the custom padding that Session delivered the message with (and over which the signature is written). Returns the padded value.""" if length > len(data): data += b'\x80' + b'\x00' * (length - len(data)) return data
def get_github_headers(api_token): """ Load GH personal access token from file. """ gh_headers = {"AUTHORIZATION": f"token {api_token}"} return gh_headers
def decoupParagraphEnPhrases(paragraph): """returns the paragraph splited in phrases ignoring specifics titles. To be completed""" import re finsDePhrase = re.compile(r""" # Split sentences on whitespace between them. (?: # Group for two positive lookbehinds. (?<=[.!?]) # Either an end of sentence punct, | (?<=[.!?]['"]) # or end of sentence punct and quote. ) # End group of two positive lookbehinds. (?<! Mr\. ) # Don't end sentence on "Mr." (?<! M\. ) # Don't end sentence on "M." (?<! Mme\. ) # Don't end sentence on "Mme." (?<! Mrs\. ) # Don't end sentence on "Mrs." (?<! Jr\. ) # Don't end sentence on "Jr." (?<! Dr\. ) # Don't end sentence on "Dr." (?<! Prof\. ) # Don't end sentence on "Prof." (?<! Sr\. ) # Don't end sentence on "Sr." \s+ # Split on whitespace between sentences. """, re.IGNORECASE | re.VERBOSE) listeDePhrases = finsDePhrase.split(paragraph) return [ph for ph in listeDePhrases if ph]
def my_trim_whitespace(s): """ Returns a string that has at most one whitespace character between non-whitespace characters. >>> trim_whitespace(' hi there') 'hi there' """ buffer = '' for i, letter in enumerate(s): if letter.isspace(): try: if s[i + 1].isspace(): continue except IndexError: pass buffer = buffer + letter return buffer.strip()
def compute_unique_count_drift(df_prob, ref_df_prob): """Find the difference in unique counts of two distributions and return as percentage""" df_diff = set(df_prob.keys()) - set(ref_df_prob.keys()) ref_df_diff = set(ref_df_prob.keys()) - set(df_prob.keys()) return sum([df_prob[k] for k in df_diff] + [ref_df_prob[k] for k in ref_df_diff])
def fibonacci_original(n): """calculates the fibonacci sequence Args: n (int): number to checvk Returns: int: value of fib """ if n == 1: return 1 elif n == 2: return 1 elif n > 2: return fibonacci_original(n - 1) + fibonacci_original(n - 2)
def relativize_paths(root, paths): """ Take a list of fully-qualified paths and remove the root, thus making them relative to something. """ clean_paths = [] for path in paths: clean_paths.append(path.replace("%s/" % root, '')) return clean_paths
def col_index_list(info, key, value): """Given a list of dicts 'info', return a list of indices corresponding to columns in which info[key] == value. Use to build lists of default columns, non-exportable columns, etc.""" index_list = list() if info != None: for i in range(0, len(info)): if info[i].get(key) == value: index_list.append(i) return index_list
def cal_width(value, max): """Get width >>> cal_width(70, 100) 140.0 """ if not value or not max: return "None" width = (value / float(max)) * 200 return width
def first_is_not(l, v): """ Return first item in list which is not the specified value. If all items are the specified value, return it. Parameters ---------- l : sequence The list of elements to be inspected. v : object The value not to be matched. Example: -------- >>> first_is_not(['a', 'b', 'c'], 'a') 'b' """ return next((_ for _ in l if _ is not v), v)
def get_scale_for_nth_feature_map(k, m=4, scale_min=0.1484375, scale_max=0.75): """Calculating scale value for nth feature map using the given method in the paper. inputs: k = nth feature map for scale calculation m = length of all using feature maps for detections, 6 for ssd300, 4 for blazeface outputs: scale = calculated scale value for given index """ return scale_min + ((scale_max - scale_min) / (m - 1)) * (k - 1)
def _has_balanced_parens(rhs): """Returns True if all '(' precede and are followed by a correspoding ')'.""" open_parens = 0 for token in rhs: for char in token: if char == "(": open_parens += 1 elif char == ")": open_parens -= 1 if open_parens < 0: return False return open_parens == 0
def hexStringToRGB(hex): """ Converts hex color string to RGB values :param hex: color string in format: #rrggbb or rrggbb with 8-bit values in hexadecimal system :return: tuple containing RGB color values (from 0.0 to 1.0 each) """ temp = hex length = len(hex) if temp[0] == "#": temp = hex[1:length] if not len(temp) == 6: return None colorArr = bytearray.fromhex(temp) return colorArr[0], colorArr[1], colorArr[2]
def sum_of_years_digits(year): """Calculate the sum of years' digits. Arguments: year (``int``): The year to calculate up to. Returns: int: The sum of years' digits. """ if year <= 0: return 0 return year + sum_of_years_digits(year-1)
def estimate_reading_time(text): """Estimates the time needed for a user to read a piece of text This is assuming 0.9 seconds to react to start reading plus 15 chars per second to actually read the text. Parameters ---------- text : str The text the reading time should be estimated for. """ read_time = 0.9 + len(text) / 15 read_time = round(read_time, 1) return read_time if read_time > 2.4 else 2.4
def filter(key: str, value: str, index: dict): """Filter index by key value pair""" return [i for i in index if i.get(key) == value]
def byte_ord(b): """ Return the integer representation of the byte string. This supports Python 3 byte arrays as well as standard strings. """ try: return ord(b) except TypeError: return b