content
stringlengths
42
6.51k
def election_slug(state, start_date, race_type, special=False, **kwargs): """ Generate a standardized election identifier string. Args: state: Lowercase state postal abbreviation. For example, "md". start_date: Start date of election, in the form YYYY-MM-DD. Required. race_type: Ra...
def linear_interpolation(left, right, alpha): """ Linear interpolation between `left` and `right`. :param left: (float) left boundary :param right: (float) right boundary :param alpha: (float) coeff in [0, 1] :return: (float) """ return left + alpha * (right - left)
def _LoadPathmap(pathmap_path): """Load the pathmap of obfuscated resource paths. Returns: A dict mapping from obfuscated paths to original paths or an empty dict if passed a None |pathmap_path|. """ if pathmap_path is None: return {} pathmap = {} with open(pathmap_path, 'r') as f: for ...
def STRING_BOUNDARY(e): """ :return: expr that matches an entire line """ return r"^{e}$".format(e=e)
def is_sorted(array): """ Check if an array is sorted in ascending order (assumes an array of numbers, such as integers or float) :param array: the array to be checked :return: a message ("Array is sorted" or "Array is not sorted") """ return "Array is %ssorted" % ('not ' if sorted(array) != lis...
def factmod(n: int, p: int) -> int: """Return n % p in O(p + logp(n)).""" fact = [1]*p for i in range(1, p): fact[i] = fact[i-1] * i % p ans = 1 while n > 1: if n//p & 1: ans = p - ans ans = ans * fact[n % p] % p n //= p return ans
def transpose(motif, interval): """Raise every note in a motif by a designated interval. Only the notes' pitch parameters are altered. Arguments: motif (list of MyNotes) interval (int) Returns: A list of int """ new_motif = [(i + interval) for i in motif] return new_moti...
def calculateCylinderInertia(mass, r, h): """Returns upper diagonal of inertia tensor of a cylinder as tuple. Args: mass(float): The cylinders mass. r(float): The cylinders radius. h(float): The cylinders height. Returns: : tuple(6) """ i = mass / 12 * (3 * r ** 2 + h ** 2...
def replace_booleans(line): """replaces postgres boolean literals with 0|1 within the values in an INSERT statement as created by pg_dump. .. note:: - we rely on the INSERT statements not containing newlines. - we somewhat naively split the values at commas and assume that if a single ...
def decode_ascii(byte_msg) -> str: """Decodes a byte array to a string. :param Union[bytes, bytearray] byte_msg: The bytes to decode. :rtype str The decoded string. """ if len(byte_msg) == 0: return "" try: for i in range(0, len(byte_msg)): if byte_m...
def fibonacci(index): """ Recursive function that calculates Fibonacci sequence. :param index: the n-th element of Fibonacci sequence to calculate. :return: n-th element of Fibonacci sequence. """ if index <= 1: return index return fibonacci(index - 1) + fibonacci(index - 2)
def split_list(n): """will return the list index""" return [(x + 1) for x, y in zip(n, n[1:]) if y - x != 1]
def split_list(ls, sep): """ Split list similarly to split string, according to some separator """ ret = [] cur = [] for x in ls: if (x != sep): cur.append(x) elif cur: ret.append(cur) cur = [] if cur: ret.append(cur) return ret
def _get_band_locations(raster_bands: list, requested_bands: list): """ Get list indices for band locations. """ locations = [] for b in requested_bands: try: locations.append(raster_bands.index(b.lower())) except ValueError: raise ValueError(f'{b} not in rast...
def f_merge_opnum(num, op): """ f_merge([1,2,3,4],"+*/") ==> [1,+,2,*,3,/,4] """ merge_op_num = list(num[:]) for i in range(0, 3): merge_op_num.insert(i*2+1, op[i]) merge_op_num = list(map(str, merge_op_num)) return merge_op_num
def _get_window_size(offset, step_size, image_size): """ Calculate window width or height. Usually same as block size, except when at the end of image and only a fracture of block size remains :param offset: start columns/ row :param step_size: block width/ height :param image_size: image wi...
def wrap(x, vmin, vmax): """Wrap a value x within bounds (vmin,vmax)""" return (x-vmin) % (vmax-vmin)+vmin
def billions2(x, pos): """The two args are the value and tick position""" if x == 0: return '0' else: return '%1.0f\\,G' % (x * 1e-9)
def return_name(image_name): """Converts inverted image name to original name Inverted images are stored in the database under the image they're derived from. As such, to locate information corresponding to the inverted image, the database must be queried via the original image name. Args: ...
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ # MY IMPLEMENTATION # for every key in hand dictionary handlist = [] for letter in hand.keys(): # add letter to list as often...
def fetch_tmax(dbname, dt, bbox): """Downloads maximum temperature from NCEP Reanalysis.""" url = "http://iridl.ldeo.columbia.edu/SOURCES/.NOAA/.NCEP-NCAR/.CDAS-1/.DAILY/.Diagnostic/.above_ground/.maximum/dods" varname = "temp" return url, varname, bbox, dt
def keyval_change_reporting(keyword, original_val, replacement_val): """ Creates a reporting string to be saved in the HEADERERR or COMMENTS column of the exposure table. Give the keyword, the original value, and the value that it was replaced with. Args: keyword, str. Keyword in the exposure t...
def add_new_category(x): """ Aimed at 'trafficSource.keyword' to tidy things up a little """ x = str(x).lower() if x == 'nan': return 'nan' x = ''.join(x.split()) if r'provided' in x: return 'not_provided' if r'youtube' in x or r'you' in x or r'yo' in x or r'tub' in x or ...
def contains(item, cell_value): """ This func. returns True if item = cell-value or item is contained in cell value (when there is more than 1 token in a cell). """ return False if cell_value is None \ else False if cell_value.find(item) == -1 \ else True
def find_in_rectangle(point_list, query_rect): """Szukanie punktow z listy nalezacych do prostokata.""" result = [] for pt in point_list: if pt in query_rect: result.append(pt) return result
def same_elements(elems_a, elems_b): """Checks if two iterables (such as lists) contain the same elements. Elements do not have to be hashable (this allows us to compare sets of dicts for example). This comparison is not necessarily efficient. """ a = list(elems_a) b = list(elems_b) for x i...
def is_valid_cog(cog): """Validates course over ground Arguments --------- cog : float Course over ground Returns ------- True if course over ground is greater than zero and less than 360 degrees """ return cog >= 0 and cog < 360
def extrac_traj_num(traj): """ Extracts the number of the trajectory :param traj: name of the trajectory (str) :return: number of the trajectory (int) """ num = traj.split(".")[0].split("_")[-1] return int(num)
def _format_text(text): """Lowercases and normalizes spaces.""" text = text.lower() text = " ".join(text.split()) text = text.strip() return text
def as_float_default(s, default=0): """Cast a string to float or return a default value instead of throwing an error on invalid argument. """ try: return float(s) except ValueError: return default
def stop(data): """ Get the stop coordinate as an int of the data. """ value = data["genome_coordinate_end"] if value: return int(value) return None
def getMidpoint(x, y, w, h): """ Helper function for calculating the center point of bounding box using tlwh coordinates """ x_point = x + (w/2) y_point = y + (h/2) return x_point, y_point
def fvfm(fm, f0): """Calculate Fv/Fm Fv/Fm = (fm - f0) / fm :param fm: Fm :param f0: F0 :returns: Fv/Fm (float) """ return (fm - f0) / fm
def collect_distribution(function, samples: int): """Count the number of times the given function returns each output value.""" assert(callable(function)) outputs = {} for i in range(samples): o = function() outputs[o] = outputs.get(o, 0) + 1 return outputs
def conv_output_shape(h_w, kernel_size = 1, stride = 1, pad = 0, dilation = 1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is not tuple: kernel_size = (kernel...
def has_role(role, roles): """ Check if the a role is contained in a role list Looks if a role is contained to a list independently to the case sensitivity. """ if role is None or roles is None: return False return role.lower() in [r.lower() for r in roles]
def format_label(x): """Format label for librdf.""" return x.replace("_", " ")
def decode_textfield_quoted_printable(content): """ Decodes the contents for CIF textfield from quoted-printable encoding. :param content: a string with contents :return: decoded string """ import quopri return quopri.decodestring(content)
def is_string(value): """ Checks if `value` is a string. Args: value (mixed): Value to check. Returns: bool: Whether `value` is a string. Example: >>> is_string('') True >>> is_string(1) False .. versionadded:: 1.0.0 """ return isinsta...
def left_window_coords(win_size, original_left_bound): """ Returns a `tuple` `(new_start, new_end)` left of original bound describing a window of length `win_size` (see note). Note: Converts any new value less than `1` to `1`. :param win_size: size of window to the left. :param original_left_b...
def CollectObjectIDs(ids, obj): """Collect object ids seen in a structure""" if id(obj) in ids: return ids.add(id(obj)) if isinstance(obj, (list, tuple, set, frozenset)): for e in obj: CollectObjectIDs(ids, e) elif isinstance(obj, dict): for k, v in obj.items(): ...
def average(number1, number2, number3): """ Calculating the average of three given numbers Parameters: number1|2|3 (float): three given numbers Returns: number (float): Returning the statistical average of these three numbers """ return (number1 + number2 + number3) / 3.0
def calc_average(last, current, share_of_use): """ function to calculate the weighted average of schedules """ return last + current * share_of_use
def isNotTooFarFrom(p, q): """takes two complex numbers, returns boolean""" tol_isNotTooFarFrom = 10 return abs(p-q) < tol_isNotTooFarFrom
def extract(line): """ >>> extract('1-3 a: abcde') (1, 3, 'a', 'abcde') """ pw_range, pw_letter, pw_password = line.split() first, second = map(int, pw_range.split("-")) letter = pw_letter.split(":")[0] return first, second, letter, pw_password
def get_restype_from_titgroup(group): """Given a titratable group unique id e.g. (A:0112:CTERM or A:0111:ASP), return the residue type (ASP)""" ptype=group.split(':')[-1].upper() if ptype=='NTERM' or ptype=='CTERM': return None else: return ptype
def _base_type(data): """Create a base_type integer value from the string sent by agents. Args: data: base_type value as string Returns: base_type: Base type value as integer """ # Initialize key variables if bool(data) is False: value = None else: value = ...
def get_rm(x, N): """ """ cumsum, rm = [0], [] for i, j in enumerate(x, 1): cumsum.append(cumsum[i - 1] + j) if i >= N: mean = (cumsum[i] - cumsum[i - N]) / N rm.append(mean) return rm
def period(n, a): """Compute the period of a^kmod n)""" remainder_list = [] k = 1 while True: r = len(remainder_list) if r > 128: return None remainder = a ** k % n if remainder in remainder_list: return r else: remainder_list.a...
def i2a(interfaces): """ Extract the non-loopback IPv4 addresses from network-get-interfaces results. Example: reply = {'results': [ { 'name': 'ens18', 'hardware-address': '6e:25:bb:c7:4b:76', 'ip-addresses': [ { 'ip-addre...
def tablize_user(user: dict) -> dict: """Create a table entry for a user. Args: user: user to create a table entry for """ tab_map = { "Name": "user_name", "UUID": "uuid", "Full Name": "full_name", "Role Name": "role_name", "Email": "email", "Last...
def _safe_toint(val): """ Try and turn a string into a number, returning -1 if In this case, I know that valid values will never be -1, so returning that is forcing a failure :param val: :return: """ try: return int(val) except ValueError: return -1
def icon_name(resolution): """Create file name from image resolution. Args: resolution (str): resolution of the image. Returns: icon_name (str): File name of an icon for .iconset. """ return 'icon_' + resolution + '.png'
def muc(gold_mentions, response_mentions): """ M. Vilain, J. Burger, J. Aberdeen, D. Connolly, and L. Hirschman. 1995. A model theoretic coreference scoring scheme. In MUC-6. https://www.aclweb.org/anthology/M/M95/M95-1005.pdf The MUC measure focuses on the links (pairs of mentions) and compu...
def gtsrb_signname(classid): """ class id to sign name mapping """ labels = { 0 : "speed limit 20 (prohibitory)", 1 : "speed limit 30 (prohibitory)", 2 : "speed limit 50 (prohibitory)", 3 : "speed limit 60 (prohibitory)", 4 : "speed limit 70 (prohibitory)", ...
def pronounce(name): """ Generate the pronunciation code of the string """ name = name.upper() result = "" if len(name) == 0 : return '0000' else: result += name[0] dictionary = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6", "AEIOUHWY":"."} ...
def _Flatten(nmap_list): """Flattens every `.NestedMap` in nmap_list and concatenate them.""" ret = [] for x in nmap_list: ret += x.Flatten() return ret
def create_sublists(input_list, n=3): """Create a list of sub-lists with n elements.""" total_list = [input_list[x : x + n] for x in range(0, len(input_list), n)] # Fill in any blanks. last_list = total_list[-1] while len(last_list) < n: last_list.append("") return total_list
def binary_solver(intermediate_fn, model_fn, target_output : float, initial_lower_bound : float, initial_upper_bound : float, tolerance : float): """ Solver which finds the input which produces the supplied target output, using a simple binary search-like algorithm. :param intermediate_fn: Intermediate...
def mean(list): """Function that returns the mean of a list""" sum = 0 for num in list: sum += num return sum/len(list)
def invalid_pl_vsby(i, v): """Checks if visibility is inconsistent with PL""" if i == '+' and v >= 3.0: return True elif i == '' and v > 6.0: return True else: return False
def shift(text, key): """ Caesar-Cipher Encryption Shifts Characters by given key Args: text (string): The text message to encrypt/shift. key (int): The number to shift the characters by. Returns: string: Shifted/Encrypted text """ result = "" # transverse the plain...
def bool_to_int(labels: list) -> list: """ Turn a list of 0s and 1s into a list whose values are the indices of 1s. Used to create a valid Kaggle submission. E.g. [1, 0, 0, 1, 1] -> [0, 3, 4] """ return [i for i, x in enumerate(labels) if x == 1]
def _find_java_comment(text): """ We are NOT in a comment. Return a ref to any code found, a ref to the rest of the text, and the value of inComment. """ multi_line = False posn_old = text.find('/*') # multi-line comment posn_new = text.find('//') # one-line comment if posn...
def get_chapter(link): """ this should cover 2 cases eg, get `1`: http://www.mangapanda.com/wild-life/1 http://www.mangapanda.com/751-35090-1/wild-life/chapter-1.html problem: http://www.mangapanda.com/wild-life """ return link.split("/")[-1].split("-")[-1].split(".")[0]
def fa_attachment(extension): """ Add fontawesome icon if found. Else return normal extension as string. :param extension: file extension :return: matching fontawesome icon as string """ if extension == 'pdf': return "<i class='fa fa-file-pdf-o fa-lg'></i>" elif extension == 'jpg' o...
def find_shared_neurons(listA, listB): """ :param listA: list of unique neurons in A(dtype:list of int) :param listA: list of unique neurons in B(dtype:list of int) :return: shared neurons between list A and B(dtype:list of int) """ shared_neurons = set.intersection(set(listA), set(listB)) r...
def diff_max(value_a, value_b, position_a, position_b): """ Retorna o maior valor entre 2 valores """ # Cod 100 - Equal # Cod 101 - No image if not value_a or not value_b: return 101, 0 if value_a > value_b: return position_a, round((value_a - value_b), 2) elif value_a < value_b...
def _exit_code(results): """ results from run_tasks take the form of a dict with one or more entries hostname: Exception | None If every entry in the dict has a value of None, the exit code is 0. If any entry has a value that is not None, something failed, and we should exit with a non-zero exi...
def _check_mean_sub_values(value, channels): """ Checks if mean subtraction values are valid based on the number of channels "value" must be a tuple of dimensions = number of channels Returns boolean: True -> Expression is valid False -> Expression is invalid """ if value...
def removeSESSID(urlssid): """ Remove the phpsessid information... don't care about it now """ k = urlssid.find('PHPSESSID') if k > 0: return urlssid[0:k-1] k = urlssid.find('sid') if k > 0: return urlssid[0:k-1] return urlssid
def format_commit_outputs(commit: dict = {}) -> dict: """Take GitHub API commit data and format to expected context outputs Args: commit (dict): commit data returned from GitHub API Returns: (dict): commit object formatted to expected context outputs """ author = commit.get('author...
def false_positive(a, b): """ Return quantity FP - False Positives What is in A and not in B being A the set of Positive prediction and B the set of Actual Positive """ fp = 0 for item in a: if item not in b: fp += 1 return fp
def order_by_keys(dict): """ Sort a dictionary by keys, case insensitive ie [ Ada, eC, Fortran ] Default ordering, or using json.dump with sort_keys=True, produces [ Ada, Fortran, eC ] """ from collections import OrderedDict return OrderedDict(sorted(dict.items(), key=lambda s: s[0].lower())...
def path_absolute2relative(path_list, parent_path): """change absolute path to relative path Args: path_list (string list): paths need to be changed parent_path (string): parent path Returns: string list: changed path """ string_list_type = type(['','']) string_type = t...
def all_vocab(train, dev, test): """ Returns the vocabulary """ data = train + dev + test words = [] for item in data: words.extend(item) return set(words)
def tracks_entry(tracks): """ Insert tracks for table row. Args ---- tracks: list Tracks for row of 5 album art covers. """ tracks_entry = """<td><p>{}<br>{}<br>{}<br>{}<br>{}</p></td>\n""".format(*tracks) return tracks_entry
def _deep_update(main_dict, update_dict): """Update input dictionary with a second (update) dictionary https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth Parameters ---------- main_dict: dict Input dictionary update_dict: d...
def configure_redshift(redshift, *structs): """ Check and obtain a redshift from given default and structs. Parameters ---------- redshift : float The default redshift to use structs : list of :class:`~_utils.OutputStruct` A number of output datasets from which to find the redsh...
def find_best_type_for_prop(prop): """Find best type match for property.""" multiple_types = prop['type'] # delete it so that we throw an exception if none of types # are non-'null' del prop['type'] for one_type in multiple_types: # sometimes the types are base types and sometimes they ...
def _generate_overlaps(sequence, order): """ This function takes an input sequence & generates overlapping subsequences of length order + 1, returned as a tuple. Has no dependencies & is called by the wrapper compute() Parameters ---------- sequence : string String containing nucleo...
def maximum_subarray_linear(array): """Maximum subarray linear.""" if not array: return None, None, None i = low = high = 0 curr = max_sum = array[0] for j in range(1, len(array)): if curr < 0: i = j curr = array[j] else: curr += array[j] ...
def check_enclosing_brackets(params: str): """ Performs an initial check of format of a parameters - whether it is enclosed in brackets and whether it is not empty :param params: parameter to be checked :return: True if check was a success, False otherwise """ if not params or (str.strip(par...
def pad_sequence(seq, pad_tok, max_length): """ Args: sequences: a generator of list or tuple pad_tok: the char to pad with Returns: a list of list where each sublist has same length """ sequence_padded, sequence_length = [], [] seq = list(seq) seq_ = seq[:max_lengt...
def decodeBytes(bytesString, errors='replace'): """ Purpose: Decode a bytes string to a unicode string :param bytes_string: bytes, bytes string to be decoded :param errors: str, mode to handle unicode conversion errors :return: str/unicode, decoded string """ ...
def _decode(encoded): """Decode a string into utf-8 :param encoded: Encoded string :type encoded: string :return: Decoded string :rtype: string """ if not encoded: return "" decoded = encoded.decode('utf-8') if decoded.endswith('\n'): decoded = decoded[:-1] retur...
def array_abs(arg): """Return the abs value of an array""" try: return abs(arg) except: try: return [abs(item) for item in arg] except: return None
def poly_area(x, y): """ Method to compute the area of an irregular, closed, convex polygon. The x and y vectors are the vertices ; the last should equal the first. Author: Xavier Bonnin (LESIA) """ # Must be a closed area if (x[-1] != x[0]) or (y[-1] != y[0]): x.append(x[0]) ...
def get_attrs(foreground, background, style): """Get foreground and background attributes.""" return foreground + (background << 4) + style
def board(n): """ Creates the game's board with n x n cells. All cells must have a 'dead' status. Returns the game's board which is a dictionary with n x n elements. Each cell corresponds to a dictionary element with its key being a tuple (i,j), where i is the row number and j the column number. (Th...
def dasherize(word): """Replace underscores with dashes in the string. Example:: >>> dasherize("lower_case") "lower-case" """ return word.replace("_", "-")
def wrap_hebtext(string): """Wrap hebrew text with Latex polyglossia tag.""" return '\\texthebrew{%s}'%string
def gen_linear_ring(coords: list): """ Generate linear ring """ return '\n'.join([','.join(map(str, coord)) for coord in coords])
def match_anat(fname, json_data): """ Match anatomical images """ folder, suffix, attrs, md = "anat", None, {}, {} desc = json_data["SeriesDescription"].lower() if "t1" in desc: suffix = "T1w" elif "t2" in desc: suffix = "T2w" if suffix: if "NORM" in json_data["I...
def share_of_shelf_index(products_of_brand_x, total_products): """Return share of shelf index showing the percentage of total products made up by brand X. Args: products_of_brand_x (int): Number of products of brand X in portfolio, category, or on shelf. total_products (int): Total number of pr...
def test_metathesis(word, anagram): """ Tests if a word and an anagram are a metathesis pair This is only true if the words are I. Anagrams II. Differ in two places """ count = 0 for para in zip(word, anagram): if para[0] != para[1]: count += 1 return count == 2
def area_folder_name(cells_identifier): """ Create a name from cells_identifiers e.g to store results """ if isinstance(cells_identifier, str): area_str = cells_identifier else: if isinstance(cells_identifier, list): area_str = '_'.join(str(e) for e in cells_identifier) e...
def top_bbox_from_scores(bboxes, scores): """ Returns the top matching bounding box based on scores Args: bboxes (list): List of bounding boxes for each object scores (list): List of scores corresponding to bounding boxes given by bboxes Returns: matched...
def base_int(string: str) -> int: """ convert a str to int by detecting automaticaly the type of the int :param string: the string to convert :return: the int """ if len(string) > 1 and string[0:2] == ("0x" or "0X"): return int(string[2:], 16) if len(string) > 0 and string[0] =...
def append_to_lists( systolic_list, diastolic_list, date_list, systolic, diastolic, date ): """ Append systolic, diastolic, date to similar lists """ systolic_list.append(systolic) diastolic_list.append(diastolic) date_list.append(date) return systolic_list, diastolic_list, date_lis...