content
stringlengths
42
6.51k
def disparate_impact(fav_rate_unpriv, fav_rate_priv): """ Gets disparate impact between the unprivileged and privileged groups. :param fav_rate_unpriv: rate of favorable outcome for unprivileged group :type fav_rate_priv: `float` :param fav_rate_priv: rate of favorable outcome for privileged group ...
def doi(record): """ Adds a doi URI to the record if there's a ``doi`` entry in the record Parameters ---------- record : dict the record to update Returns ------- dict the given `record` with any updates applied """ doi = record.get('doi') if doi is not Non...
def find_diff_in_sentence(original_sentence_tokens: tuple, suspicious_sentence_tokens: tuple, lcs: tuple) -> tuple: """ Finds words not present in lcs. :param original_sentence_tokens: a tuple of tokens :param suspicious_sentence_tokens: a tuple of tokens :param lcs: a longest common subsequence ...
def fuzzy_not(v): """ Not in fuzzy logic Return None if `v` is None else `not v`. Examples ======== >>> from sympy.core.logic import fuzzy_not >>> fuzzy_not(True) False >>> fuzzy_not(None) >>> fuzzy_not(False) True """ if v is None: return v else: ...
def create_word_vocab(input_data): """create word vocab from input data""" sentence_separator = "|" word_vocab = {} for paragraph in input_data: sentences = paragraph.strip().split(sentence_separator) for sentence in sentences: words = sentence.strip().split(' ') ...
def modify_column(func, rows): """Apply 'func' to the first column in all of the supplied rows.""" delta = [] for columns in rows: delta.append([func(columns[0])] + columns[1:]) return delta
def parse_key_value_list(values: list) -> dict: """ Option callback to validate a list of key/value arguments. Converts 'NAME=VALUE' CLI parameters to a dictionary. :raises: ValueError """ if not values: return {} params = {} for value in values: parts = value.split(...
def gen_rho(K): """The Ideal Soliton Distribution, we precompute an array for speed """ return [1/K] + [1/(d*(d-1)) for d in range(2, K+1)]
def parse_artists(artists): """Takes a list of artists and return a nice, comma separated, string, of their, names""" result = '' comma = False for artist in artists: if comma: result += ', ' else: comma = True result += artist['name'] return result
def get_band_power(spectrum: list, bands: dict) -> dict: """ Get the summed power of each frequency range provided by bands. Args: - spectrum: the spectrum to be summed against. - bands: the bands to sum powers of. """ return {band: sum(spectrum[values[0]:values[1]]) ...
def mk_quote_string_for_target(value): """ mk_quote_string_for_target(target_name) -> str Return a quoted form of the given target_name suitable for including in a Makefile as a target name. """ # The only quoting we currently perform is for ':', to support msys users. return value.replace...
def _check_target_size(size): """ Common check to enforce type and sanity check on size tuples Args: size: Should be a tuple of size 2 (width, height) Returns: Raises a ValueError if ``size`` doesn't satisfy the required conditions. """ if not isinstance(size, (list, tuple)): ...
def check_require(move_coord, req_list): """ Check move eligibility: if move candidate on diagonal (required) :param move_coord: list :param diag_list: list :return: bool - True: eligible, False: ineligible """ return bool(set(move_coord) & req_list)
def bilinear_interpolation_01(x, y, values): """Interpolate values given at the corners of [0,1]x[0,1] square. Parameters: x : float y : float points : ((v00, v01), (v10, v11)) input grid with 4 values from which to interpolate. Inner dimension = x, ...
def dcs_monitorid_to_str(i): """ Helper that convert a monitor state int to a str. """ if i == 1: return "Undefined" elif i == 2: return "Healthy" elif i == 4: return "Attention" elif i == 8: return "Warning" elif i == 16: return "Critical" els...
def _get_repository_roots(ctx, files): """Returns abnormal root directories under which files reside. When running a ctx.action, source files within the main repository are all relative to the current directory; however, files that are generated or exist in remote repositories will have their root directory be ...
def string_to_dict(term_list): """Adds term_list as strings to a dictionnary. Saves term string as lower case since config file keys are automatically converted to lower case. Args: term_list (list) : Variant record terms list Return: dict: Empty or keys as strings """ te...
def filter_iwp_labels( iwp_labels, time_range=[], z_range=[], identifiers=[] ): """ Filters a list of IWP labels by time range, XY slice range, or by identifier name. IWP labels that match the specified criteria are returned. Time and slice ranges are inclusive. Takes 4 arguments: iwp_labe...
def get_same_padding(kernel_size): """Calculate padding size for same padding, assuming stride of 1 and square kernel""" if type(kernel_size) is tuple: kernel_size = kernel_size[0] pad_size = (kernel_size-1)//2 if kernel_size%2 == 0: padding = (pad_size, pad_size+1) els...
def make_reg_07h_byte(key: int) -> int: """ Make high bits of key. This key is used to encrypting to avoid wireless data intercepted by similar modules; This key is work as calculation factor when module is encrypting wireless data. :param key: The encryption key. (0-2^16-1) :return: The high ...
def dict_transform_lower_case_key(d): """Converts a dictionary to an identical one with all lower case keys""" return {k.lower(): v for k, v in d.items()}
def powerlaw(x, scale, power, return_components=False): """ Defines a power law Returns ------- scale * x**power """ return scale*x**power
def mat_multiply(A,B,C): """This functions performs the multiplication of matrixes taking A = Matrix 1, B = Matrix 2 and C = Resulting Matrix of 0's""" if len(A[0]) == len(B): for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): ...
def standardize(data, mean, std): """Standardize datasets using the given statistics. Args: data (np.ndarray or list of np.ndarray): Dataset or list of datasets to standardize. mean (number): Mean statistic. std (number): Standard deviation statistic. Returns: n...
def get_cli_fname(lon, lat, scenario=0): """Get the climate file name for the given lon, lat, and scenario""" # The trouble here is relying on rounding is problematic, so we just # truncate lon = round(lon, 2) lat = round(lat, 2) return "/i/%s/cli/%03ix%03i/%06.2fx%06.2f.cli" % ( scenari...
def extract_boto_args_from_env(env_vars): """Return boto3 client args dict with environment creds.""" boto_args = {} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if env_vars.get(i.upper()): boto_args[i] = env_vars[i.upper()] return boto_...
def tune(scale, acc_rate): """ tune: bool Flag for tuning. Defaults to True. tune_interval: int The frequency of tuning. Defaults to 100 iterations. Module from pymc3 Tunes the scaling parameter for the proposal distribution according to the acceptance rate over the last tune_i...
def ticks2sec(ticks, BPM, resolution): """ seconds """ #return ticks2ms(ticks, BPM, resolution) / 1000. ## === #return (60. / BPM)/resolution ## === return ticks * 60. / (BPM * resolution)
def merge(source, destination, overwrite=True): """Deep merge 2 dicts Warning: the source dict is merged INTO the destination one. Make a copy before using it if you do not want to destroy the destination dict. """ for key, value in list(source.items()): if isinstance(value, dict): ...
def interpolate(edge, x): """Given a sorted edge ((x1, y1), (x2, y2)) and an x value x, return a vertex (x, y') where y' is on the given edge. """ t = (x - edge[0][0]) / (edge[1][0] - edge[0][0]) y_prime = edge[0][1] + t * (edge[1][1] - edge[0][1]) return x, y_prime
def tan_combine_like_terms(terms): """ This method will take a set of 3-tuples, (a,b,c), where like terms are matching b,c It will then combine like terms by summing up all the coefficients a """ output = {} for term in terms: a = term[0] b = term[1] c = term[2] i...
def triangle_num(n): """ Return nth triangle number. """ return n * (n + 1) / 2
def replace_sublist(li, target, replacement): """ Replace a sublist with another sublist. Not very effcient. If 'eq' is given, this will be used to compare items. """ result = [] i = 0 while i < len(li): if li[i : i + len(target)] == target: i += len(target) result.extend(replacement) ...
def convert_file_extension_to_txt(image_file): """Convert and a file extension to .txt Args: image_file (str): String containing the image file Returns: Initial string where extension is changed to '.txt' Examples: >>> convert_file_extension_to_txt('verse007.mha') 'verse007.txt' """ return image_fi...
def flatten_nested_iterable(nested_iterable, list_type=(list, tuple)): """ Flatten an arbitrarily-deep nested_list. :param nested_iterable: a list to flatten_nested_iterables :param list_type: valid variable types to flatten_nested_iterables :return: list; a flattened list """ nested_iterab...
def mjd2hour(mjd, tz=0) : """ Extract hour part from mjd""" h = (mjd * 24.0 + tz) % 24.0 return h
def hsv_to_rgb(h, s, v): """ Convert hsv color code to rgb color code. Naive implementation of Wikipedia method. See https://ja.wikipedia.org/wiki/HSV%E8%89%B2%E7%A9%BA%E9%96%93 Args: h (int): Hue 0 ~ 360 s (int): Saturation 0 ~ 1 v (int): Value 0 ~ 1 """ if s < 0 or 1 ...
def unique(lst): """ Returns a list made up of the unique values found in lst. i.e., it removes the redundant values in lst. """ lst = lst[:] unique_lst = [] # Cycle through the list and add each value to the unique list only once. for item in lst: if unique_lst.count(item) <= ...
def split_at(s: str, i: int): """Returns a tuple containing the part of the string before the specified index (non-inclusive) and the part after the index """ return (s[:i], s[i:])
def rename_cols(column): """ Reformats tuple column names to str format :param col: column name :return: column name in str format :rtype: str """ if isinstance(column, tuple): column = '_'.join(str(x) for x in column) return column
def make_invalid_varname_comment(varname: str): """Make a comment about a Stata varname being invalid.""" return f'* Invalid STATA varname: {varname}'
def cleanup_ocr_text(txt: str) -> str: """Do some basic cleanup to make OCR text better. Err on the side of safety. Don't make fixes that could cause other issues. :param txt: The txt output from the OCR engine. :return: Txt output, cleaned up. """ simple_replacements = ( ("Fi|ed", "Fi...
def e2k(E, E0): """ Convert from energy in eV to k-space Parameters ---------- E : float Current energy in eV E0 : float Edge energy in eV Returns ------- out : float k-space value See Also -------- :func:`isstools.conversions.xray.k2e` """ ...
def str_to_bool(value): """ Convert a string too a bool object Parameters ---------- value : str The string object to convert to a bool. The following case insensitive strings evaluate to True ['true', 1', 'up', 'on'] Returns ------- bool Boolean based on the s...
def extract_target(targets, map_target_position): """Extract the real target.""" if isinstance(targets, (list, tuple)): return targets[map_target_position["target"]] else: return targets[:, map_target_position["target"]]
def is_valid_account_id(account_id): """Checks whether a provided account id is a valid AWS account id. Args: account_id (str): An account id string. Returns: True if the provided value is a valid AWS account id, false otherwise. """ if not isinstance(account_id, str): ret...
def calc_image_merge_clip(p1, p2, dst, q1, q2): """ p1 (x1, y1, z1) and p2 (x2, y2, z2) define the extent of the (non-scaled) data shown. The image, defined by region q1, q2 is to be placed at dst in the image (destination may be outside of the actual data array). Refines the modified points (q1',...
def find_start_end(grid): """ Finds the source and destination block indexes from the list. Args grid: <list> the world grid blocks represented as a list of blocks (see Tutorial.pdf) Returns start: <int> source block index in the list end: <int> destination bl...
def formatList(line): """Format mangled text into a list. Take any line and remove any incorrect characters, convert it to lowercase and transform the string into a list based on the commas. """ # Regex Version # cleaned = re.sub("'|\[|\]|\s|\n", "", line) # cleaned = cleaned.split(',')...
def contentfilter(content): """ Split into lines and format paragraphs """ output_lines = [] p_on = True for line in content.strip().splitlines(): if len(line.strip()) > 0: if line[0] == "<" and line[-1] == ">": if "<pre>" in line: p_on = False ...
def get_trigger_status(code): """Get trigger status from code.""" trigger_status = {0: "Enable", 1: "Disable"} if code in trigger_status: return trigger_status[code] + " (" + str(code) + ")" return "Unknown ({})".format(str(code))
def convert_little_endian_9bits(nbits): """Converts nine-bit long "bytes" to eight-bit bytes on a little-endian like format. Source: https://en.wikipedia.org/wiki/GIF#Image_coding""" left = '' result = [] for n in nbits: b = bin(n)[2:].zfill(9) if len(left) == 8: # Le...
def bin2gray(val): """ convert an unsigned binary number to reflected binary Gray code. :param val: value to convert (binary) :return: gray code """ return (val >> 1) ^ val
def printif(string: str, pre_sep: str = " ", post_sep: str = " ") -> str: """Print `string` if `string` is not null.""" if string not in [None, ""]: return f"{pre_sep}{string}{post_sep}" return ""
def _get_missing_parts(fmt): """ Return a list containing missing parts (day, month, year) from a date format checking its directives """ directive_mapping = { 'day': ['%d', '%-d', '%j', '%-j'], 'month': ['%b', '%B', '%m', '%-m'], 'year': ['%y', '%-y', '%Y'] } missin...
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ start_index = 0 middle_index = 0 end_index = len(input_list) - 1...
def merge_combiner(d1, d2): """Merges to dictionary used in call to .aggregateByKey Args: d1 (dict): python dictionary representing aggregate d2 (dict): python dictionary representing aggregate Returns: dict: Returns dictionary of merged combiners """ d1.update(d2) return d1
def product(iterable): """Return product of sequence of numbers. Equivalent of functools.reduce(operator.mul, iterable, 1). Multiplying numpy integers might overflow. >>> product([2**8, 2**30]) 274877906944 >>> product([]) 1 """ prod = 1 for i in iterable: prod *= i ...
def set_sample_dimensions(depth=2.5e-3,width=2e-3,length=30e-3): """ set the four point bending sample dimensions inputs: depth: default 2.5e-3 m width: default 2e-3 m length: default 30e-3 m """ dims = {'depth':dept...
def decode(value): """ django-peeringdb imports unicode literals from __future__, while peeringdb_server does not at this point. so we may get already decoded values for some enums while others still need to be decoded. """ try: return value.decode("utf-8") except UnicodeEncodeE...
def image_opts(options): """ Returns the image options as a string. Parameter options: the image options Precondition: options is a dictionary """ result = '(no options)' if len(options) > 0: flag = list(options.items())[0] result = '(--'+str(flag[0])+'='+str(flag[1])+'...
def example1(S): """Return the sum of the elements in sequence S.""" n = len(S) total = 0 for j in range(n): # loop from 0 to n-1 total += S[j] return total
def ID(obj): """Get an unique ID from object for dot node names""" return hex(id(obj)).replace('-','_')
def errToX_pos(x, y=None, dx=None, dy=None): """ calculate error of x**2 :param x: float value :param dx: float value """ if dx is None: dx = 0 return dx
def _same_contents(a, b): """Perform a comparison of the two files""" with open(a, 'r') as f: a_data = f.read() with open(b, 'r') as f: b_data = f.read() return a_data == b_data
def pil_coord_to_tesseract(pil_x, pil_y, tif_h): """ Convert PIL coordinates into Tesseract boxfile coordinates: in PIL, (0,0) is at the top left corner and in tesseract boxfile format, (0,0) is at the bottom left corner. """ #return pil_x, pil_y return pil_x, tif_h - pil_y
def deleteValueFromAllList(list, element): """ Usage: a=[1,4,2,5,1,1,1,2,6] deleteValueFromAllList(a,1) Output: [4,2,5,2,6] :param list: A list :param element: An element which is you want to delete from all list :return: Filtered List """ list = [x for x in list if x != element...
def rivers_with_station(stations): """Takes a list of stations and returns all unique rivers associated with the stations. """ rivers = set() for station in stations: rivers.add(station.river) return rivers
def gen_missing_deps_msg(missing_list): """Return string of missing deps for the PR message.""" missing_deps = None if len(missing_list) > 0: missing_deps = "Missing Dependencies:\n" missing_deps += "=====================\n" for pkg in sorted(missing_list): missing_deps +...
def dict_compare(d1, d2): """From http://stackoverflow.com/a/18860653/1469195""" d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1...
def user_model(username): """Return a user model""" return { 'metadata': { 'name': username, } }
def scalar_floordiv(x, y): """Implementation of `scalar_floordiv`.""" return x.__floordiv__(y)
def tcp_port_is_free_using_socket(port, bind_address = '', *socket_args, **socket_kwargs): """ Check if a given TCP port is not already in use \param port The TCP port to test \param bind_address The address to bind to (1st element of tuple provided as arg for bind() call) \param socket_args Positi...
def two_gaussian_potential_bc(vnew, f2, coords): """ Apply Boundary Condition to the potential, force, and coordinates. Parameters: ----------- vnew : float (or array of floats) Potential Energy f2 : float (or array of floats) Force coords ...
def first_dimension_length(array): """Returns the length of the first dimension of the provided array or list. Args: array (list or numpy.ndarray): An array. Returns: int: The length of the first dimension of the array. """ if type(array) is list: return len(array) else...
def leaders(arr: list) -> list: """ Time Complexity: O(n) """ leader_list: list = [arr[-1]] for i in range(len(arr) - 2, -1, -1): if arr[i] > leader_list[-1]: leader_list.append(arr[i]) return list(reversed(leader_list))
def palindrome(value: str) -> bool: """ This function determines if a word or phrase is a palindrome :param value: A string :return: A boolean """ lowered = value.lower() base = lowered.replace(" ", "") if base[::-1] == base: return True else: return False # pass...
def set_public_or_private(objectname): """ If an object (file/folder) starts with a specified character(s), then make it private (False/0), otherwise make public (True/1) """ private_identifier = "_" if objectname.startswith(private_identifier): return 0 else: return 1
def crop_box_left_bottom(current_size, target_size): """ Returns box coordinates (x1, y1, x2, y2) to crop image to target size from left-bottom. """ cur_w, cur_h = current_size trg_w, trg_h = target_size assert trg_w <= cur_w assert trg_h <= cur_h x1 = 0 x2 = trg_w y1 = cur_h...
def insertion_sort_log(num_list): """ Start the for loop on the second element (the number 1) as it's assumed that the first element is sorted. 'j' keeps a reference of the previous element's index. The while loop moves all items of the sorted segment forward if they are larger than the item to inse...
def get_radio_button_label(field_value, label_list): """Return human-readable label for problem choices form value.""" if len(label_list[0]) == 3: label_list = [(value, text) for value, icon, text in label_list] for value, text in label_list: if value == field_value: return text ...
def get_words_from_string(line): """ Return a list of the words in the given input string, converting each word to lower-case. Input: line (a string) Output: a list of strings (each string is a sequence of alphanumeric characters) """ word_list = [] # accumulates wo...
def unpack_uuid(entity): """Unpack the UUID string from a job spec, or no-op for UUID strings""" return entity['uuid'] if isinstance(entity, dict) else entity
def replace(s, replace): """Replace multiple values in a string""" for r in replace: s = s.replace(*r) return s
def reduce_boxes(boxes, n_o_b): """ Reduces the number of boxes by combining them. Combine the closesd boxes :param boxes: List[List[int]] = List of bboxes of the chars :param n_o_b: int = wanted number of boxes :return: List[List[int]] = modified boxes """ while len(boxes) > n_o_b: ...
def to_similarity(distance: int, length: int) -> float: """Calculates a similarity measure from an edit distance. Args: distance: The edit distance between two strings. length: The length of the longer of the two strings the edit distance is from. Returns: A similarity ...
def truthy_string(s): """Determines if a string has a truthy value""" return str(s).lower() in ['true', '1', 'y', 'yes']
def convert_metadata_bytes_to_str(metadata_bytes: bytes) -> str: """Convert bytes to a string. Assumes that exactly 32 bytes are given. """ metadata_str = metadata_bytes.decode("utf-8") stop_idx = len(metadata_str) for char in reversed(metadata_str): if char != "\x00": break...
def create_payload_for_firmware_update(job_type_id: int, baseline_identifier: str, catalog_identifier: str, repository_id: str, target_data: list, stage_update: bool): """ Generate the payload to initiate a firmware update job Ar...
def hash(string, replace='_', titlecase=False): """Replaces characters with dashes. Args: replace (string): The character to replace titlecase (bool): Titlecase every word """ if titlecase: string = string.lower().replace(replace, ' ').title() replace = ' ' return st...
def replace_stop(sequence): """ For a string, replace all '_' characters with 'X's Args: sequence (string) Returns: string: '_' characters replaced with 'X's """ return sequence.replace('_', 'X')
def _get_file(intuple): """ Extract the filename from the inputnode. >>> _get_file([("fmap.nii.gz", {"Units": "rad/s"})]) 'fmap.nii.gz' >>> _get_file(("fmap.nii.gz", {"Units": "rad/s"})) 'fmap.nii.gz' """ if isinstance(intuple, list): intuple = intuple[0] return intuple[0]
def _parse_content_text(text): """ <content type="text"> symbol:FANCA id:0000116087 position_mRNA:c.1626+1_1627-1 position_genomic:chr16:? Variant/DNA:c.(1626+1_1627-1)_(2151+1_2152-1)del Variant/DBID:FANCA_000723 Times_reported:1 </conte...
def convert_metadata_pairs_to_array(data): """ Given a dictionary of metadata pairs, convert it to key-value pairs in the format the Nylas API expects: "events?metadata_pair=<key>:<value>" """ if not data: return data metadata_pair = [] for key, value in data.items(): metada...
def _label_node(ref_name): """Return label for node described by `ref_name`.""" if ref_name.startswith('$Qed'): label = 'QED' else: label = ref_name return label
def calculate_position(commands): """ Calculate submarine position after executing commands (aim excluded). :param commands: list of read commands :return: final location """ horizontal_position = commands.get('forward', 0) depth = commands.get('down', 0) - commands.get('up', 0) result ...
def getLineNumberOfStringInFile(target, file): """Searches raw file content (string) by line for the occurrence of a target SATD comment's text. Returns the line numbers of the lines for full-length target matches.""" matches = [] file_split = file.splitlines() target_split = target.splitlines() for f_lin...
def is_list_of_numeric(value): """ Check if all elements in a list are int or float :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, (int, float)) for elem in value)
def bool_conv(value): """Convert value to a boolean if possible. Args: value (str): value to convert Returns: (bool): True if value in True, On, Yes, 1, False if value in False, Off, No, 0 Raises: TypeError: if value not True or False ""...
def INT_ICART(a, b, c): """Given a, b, and c, return a cartesian offset. #define INT_ICART(a, b, c) (((((((a)+(b)+(c)+1)<<1)-(a))*((a)+1))>>1)-(b)-1) """ return ((((((a + b + c + 1) << 1) - a) * (a + 1)) >> 1) - b - 1)