content
stringlengths
42
6.51k
def toVTKString(text): """This method is deprecated. It converted unicode string into VTK string, but since now VTK assumes that all strings are in UTF-8 and all strings in Slicer are UTF-8, too, conversion is no longer necessary. The method is only kept for backward compatibility and will be removed in the fut...
def get_reducer(article: str, num_reducers: int) -> int: """We map an article title to a reducer. This is done via hashing.""" return (sum([ord(s) for s in article]) + len(article)) % num_reducers
def name_to_filename(name: str) -> str: """Name to Filename.""" alnum_name = "".join([c for c in name.strip() if c.isalnum() or c == " "]) return alnum_name.replace(" ", "_")
def CreateMatrix (rows: list): """ Create a matrix. """ assert len (rows) > 0, "matrix must not be empty" rl = len (rows[0]) assert rl > 0, "matrix must not be empty" for i in range (1, len (rows)): assert rl == len (rows[i]), "all rows must have the same size" rowSet = [] fo...
def __get_version(versions, build_version, is_version): """Evaluates entered build_version and returns if supported Args: version: A dictionary containing a list of supported build version. build_version: The user entered build_version. is_version: Boolean: Whether the provided build...
def getVerticesFaces(faceVertices): """given a list with all the vertices indices for each face returns a list for each vertex and wich faces are conneted to it Args: faceVertices (list): [description] Returns: list: list of faces connected to the vertices """ result = list() ...
def isPalindrome(x): """ :type x: int :rtype: bool """ if x >= 0: y = str(x) l = len(y) for i in range(l // 2): if y[i] == y[l - i - 1]: continue else: return False else: return True else: return False
def map_dict(fn, d): """takes a dictionary and applies the function to every element""" return type(d)(map(lambda kv: (kv[0], fn(kv[1])), d.items()))
def is_image(path): """OpenCV supported image formats""" extensions = [ 'bmp', 'dib', 'jpeg', 'jpg', 'jpe', 'jp2', 'png', 'webp' 'pbm', 'pgm', 'ppm', 'pxm', 'pnm', 'pfm', 'sr', 'ras', 'tiff', 'tif', 'exr', 'hdr', 'pic', ...
def _flatten(list_of_lists): """ Flattens the provided list of lists. """ return [val for sublist in list_of_lists for val in sublist]
def convert(f, x: float) -> float: """Returns the value of an expression given x.""" if type(f) is str: return eval(f) return f(x)
def next_cma(new_value, list_len, old_cma): """ Calculate next cumulative moving average 'list_len' is the length of the currently being averaged list before adding the new value """ return (new_value + list_len * old_cma) / (list_len + 1)
def freq_by_location(d): """ Takes in a dictionary of novel objects mapped to relative frequencies. Returns a dictionary with frequencies binned by publication location into lists list names key: - *location_UK* - published in the United Kingdom - *location_US* - published in the US - *loc...
def _get_name_info(name_index, name_list): """Helper to get optional details about named references Returns the dereferenced name as both value and repr if the name list is defined. Otherwise returns the name index and its repr(). """ argval = name_index if name_list is not None: ...
def article_xml_from_filename_map(filenames): """ Given a list of file names, return the article xml file name """ for file_name in filenames: if file_name.endswith(".xml"): return file_name return None
def compare_lists(llist1, llist2): """ Compares two singly linked list to determine if they are equal.""" # If list 1 is empty and list 2 is not empty. if not llist1 and llist2: # Return zero because the lists are not equal. return 0 # If list 2 is empty and list 1 is not empty. i...
def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return username == 'menrva' and password == 'menrva'
def parse_date(d): """Parse date string to (yyyy, MM, dd) :param d: the date string to parse :returns: parsed date as tuple or None on error """ date_fields = d.split('-') if date_fields and len(date_fields) == 3: return (int(date_fields[0]), int(date_fields[1]), int(date_fields...
def d_theta_inv(y, alpha): """ (theta')^(-1) (y) = alpha * y / (1 - |y|) Alternatives: In Baus et al 2013 b(beta) = (theta')^(-1) (beta*eta) [eq 12] In Nikolova et al 2013 b(y) = (theta')^(-1) (y) [eq 12] In Nikolova et al 2014 xi(t) = (theta')^(-1) (t) [eq ...
def dict_list_to_bins(dict_list: list, bin_key: str, comparison_key=None) -> dict: """ A dictionary binning function which reduces a set of data to a set of bins. :param dict_list: a list of dictionaries :param bin_key: a key for binning :param comparison_key: a key for counting :return: a ...
def _is_string_like(obj): """ Check whether obj behaves like a string. """ try: obj + '' except (TypeError, ValueError): return False return True
def gen_data_source_filter(data_sources): """ generates a SPARQL Filter clause aimed at limiting the possible values of a ?source variable """ filter_clause = '' if len(data_sources) > 0 : filter_clause = 'FILTER ( \n' for ds in data_sources : filter_clause += ' (s...
def prep_for_jinja(images): """ Prepares svg `images` for jinja rendering Parameters ---------- images : list-of-str Returns ------- outputs : list-of-tuple """ outputs = [] for im in images: with open(im, 'r') as src: content = src.read() outpu...
def chain(_input, funcs): """Execute recursive function chain on input and return it. Side Effects: Mutates input, funcs. Args: _input: Input of any data type to be passed into functions. funcs: Ordered list of funcs to be applied to input. Returns: Recusive call if any functi...
def make_query(specific_table, offset): """ Generate a query to retrieve data from database. :param specific_table: Name of table to retrieve data from. :param offset: Optional offset to start from. """ query = 'select DISTINCT * from `{}`'.format(specific_table) if isinstance(offset, int):...
def make_present_participles(verbs): """Make the list of verbs into present participles E.g.: empower -> empowering drive -> driving """ res = [] for verb in verbs: parts = verb.split() if parts[0].endswith("e"): parts[0] = parts[0][:-1] + "ing" ...
def switchAndTranslate(gm1, gm2, v1, v2, wrapModulo): """ Transforms [v1,v2] and returns it such that it is in the same order and has the same middle interval as [gm1, gm2] """ assert(v1 < v2) # keep the same middle of the interval if (wrapModulo): gmMiddle = float(gm1 + gm2) / 2...
def flatten_lists(*lists): """Flatten several lists into one list. Examples -------- >>> flatten_lists([0, 1, 2], [3, 4, 5]) [0, 1, 2, 3, 4, 5] Parameters ---------- lists : an arbitrary number of iterable collections The type of the collections is not limited to lists, ...
def mean(my_list): """ return the mean of a list Parameters ---------- my_list : list of numbers to take average of Returns ------- average : flt The mean of the list Examples -------- >>>md.mean([1.0, 2.0, 3.0]) 2.0 """ if not isinstance(my_list, list...
def data_str(v): """ Get a string representation of a data value: v itself if not list or dict or tuple len(v) otherwise Args: v (Any): value to print Returns: str: string for v """ return v if not isinstance(v, (list, dict, tuple)) else "{} items".format(len(v))
def _reconstruct_path(came_from, start, goal): """ This method is used to construct the path from start edge to goal edge """ current = goal path = [] while current != start: path.append(current) current = came_from.get(current) path.append(start) path.reverse() retur...
def map_range_constrained_int(x, in_min, in_max, out_min, out_max): """Map value from one range to another - constrain input range.""" if x < in_min: x = in_min elif x > in_max: x = in_max return int( (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_m...
def CombineIntervallsLarge(intervalls): """combine intervalls. Overlapping intervalls are concatenated into larger intervalls. """ if not intervalls: return [] new_intervalls = [] intervalls.sort() first_from, last_to = intervalls[0] for this_from, this_to in intervalls[1:]: ...
def mergeDictsItems(final, aux): """ Adds elements from aux dictionary which are not in final dictionary to it. @param {Object.<*>} final Final dictionary. @param {Object.<*>} aux Auxiliary dictionary. @return {Object.<*>} Merged dictionary. """ for key in aux.keys(...
def has_no_e(word, x): """ Check for the presence of the given letter in given word. Return True if none, else return False. word = word to check x = letter to check for """ for char in word[:]: if char == x: return False return True
def split_scopes(scopes): """ Splits "foo, bar, baz" into ["foo", "bar", "baz"] """ return list(map(lambda s: s.strip(), scopes.split(', ')))
def recursive_update(original_dict: dict, new_dict: dict) -> dict: """Recursively update original_dict with new_dict""" for new_key, new_value in new_dict.items(): if isinstance(new_value, dict): original_dict[new_key] = recursive_update( original_dict.get(new_key, {}), new_v...
def dmka(D, Ds): """Multi-key value assign Multi-key value assign Parameters ---------- D : dict main dict. Ds : dict sub dict """ for k, v in Ds.items(): D[k] = v return D
def red_cube_path(blue_path): """Return the corresponding red cube path matched to a blue cube path.""" start = blue_path.rfind('blue') red_path = blue_path[:start] + 'red' + blue_path[start+4:] return red_path
def DetermineType(value): """Determines the type of val, returning a "full path" string. For example: DetermineType(5) -> __builtin__.int DetermineType(Foo()) -> com.google.bar.Foo Args: value: Any value, the value is irrelevant as only the type metadata is checked Returns: Type path stri...
def ex_obj_to_inq(objType): """ Return the ex_inquiry string corresponding to the specified objType. This can be passed to the ex_inquiry_map() function to get the number of objects of the specified objType """ entity_dictionary = { 'EX_ASSEMBLY': 'EX_INQ_ASSEMBLY', 'EX_BLOB': 'E...
def _comma_separator(i, length): """A separator for an entirely comma-separated list given current item index `i` and total list length `length`. `None` if there should be no separator (last item). """ if length == 1: return None elif i != length - 1: return ", " else: ...
def pixel_scale_from_instrument(instrument): """ Returns the pixel scale from an instrument type based on real observations. These options are representative of VRO, Euclid, HST, over-sampled HST and Adaptive Optics image. Parameters ---------- instrument : str A string giving...
def stop_if_mostly_diverging(errdata): """This is an example stop condition that asks Relay to quit if the error difference between consecutive samples is increasing more than half of the time. It's quite sensitive and designed for the demo, so you probably shouldn't use this is a production settin...
def sort_by_index_with_for_loop(index, array): """ Sort the array with the given index and return a list of (<element>, <original index>, <new index>) tuples. Parameters: index: List of length n that contains interger 0 to n-1. array: List of length n. Returns: A list of len...
def is_void(data): """Detect nulls in other types""" if data in ('', 0, []): return 'is empty' else: return 'have data'
def lande_g(L,S,J): """Calculates the lande g factor given L, S and J .. math:: g = 1 + \\frac{J(J+1) + S(S+1) - L(L+1)}{2J(J+1)} Reference: Sobel'man, I.I. Introduction to the Theory of Atomic Spectra. 1972. pp. 277 Args: L (float): L number S (float): S numb...
def bbox2center(bbox): """docstring for bbox2center""" return [int((bbox[0]+bbox[2])/2), int((bbox[1]+bbox[3])/2)]
def asbool(s): """ Convert a string to its boolean value """ if s.lower() == 'true': return True elif s.lower() == 'false': return False elif s.isdigit(): return bool(int(s)) else: raise ValueError('must be integer or boolean: %r' % s)
def is_int(text: str) -> bool: """ Does the given type represent an int? """ return text == "i64"
def parse_chunks(chunks): """Parse chunks and extract information on individual streams.""" streams = [] for chunk in chunks: if chunk["tag"] == 2: # stream header chunk streams.append(dict(stream_id=chunk["stream_id"], name=chunk.get("name"), # optional...
def intWithUnit(s): """Convert string to int, allowing unit suffixes. This is used as 'type' for argparse.ArgumentParser. """ if len(s) == 0: return int(s) index = "BkMGTPE".find(s[-1]) if index >= 0: return int(float(s[:-1]) * (1 << (index * 10))) else: return int(s...
def parse_version(version): """ Convert a version string into a tuple of integers suitable for doing comparisons on. """ return tuple(int(x) for x in version.split('.'))
def encode_ignore(text): """ encode a bytes into a str with utf-8, 'ignore see also tostring. """ if not isinstance(text, str): text = str(text.encode('utf-8', 'ignore')) else: pass return text
def cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ return (x > y) - (x < y)
def representable(val: int, bits: int, signed: bool = True, shift: int = 0) -> bool: """ Checks if the value is representable with the given number of bits Will return True if it is possible to encode the value in 'val' with the number of bits given in 'bits'. Additionally, it can be specified if a sig...
def compute_input_and_target_lengths(inputs_length, noise_density, mean_noise_span_length): """This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2466>`__ . Training paramete...
def create_headers(bearer_token): """Returns authorization header Args: bearer_token: Bearer token """ headers = {"Authorization": "Bearer {}".format(bearer_token)} return headers
def _is_hex_str(value, chars=40): # type: (str, int) -> bool """Check if a string is a hex-only string of exactly :param:`chars` characters length. This is useful to verify that a string contains a valid SHA, MD5 or UUID-like value. >>> _is_hex_str('0f1128046248f83dc9b9ab187e16fad0ff596128f1524d05a9a77c...
def laglongToCoord(theta: float, phi: float): """Convert lagtitude and longitude to xyz coordinate.""" from math import cos, sin, pi theta, phi = theta/180*pi, phi/180*pi return sin(theta)*cos(phi), sin(phi), cos(theta)*cos(phi)
def subcloud_status_db_model_to_dict(subcloud_status): """Convert subcloud status db model to dictionary.""" if subcloud_status: result = {"subcloud_id": subcloud_status.subcloud_id, "sync_status": subcloud_status.sync_status} else: result = {"subcloud_id": 0, ...
def count_frequency(word_list): """ Counts frequency of each word and returns a dictionary which maps the word to their frequency """ D = {} for new_word in word_list: if new_word in D: D[new_word] = D[new_word] + 1 else: D[new_word] = 1 return D
def getBorders(faces): """ Arguments: faces ([[vIdx, ...], ...]): A face representation Returns: set : A set of vertex indexes along the border of the mesh """ edgePairs = set() for face in faces: for f in range(len(face)): edgePairs.add((face[f], face[f-1])) borders = set() for ep in edg...
def _tags_from_list(tags): """ Returns list of tags from tag list. Each tag in the list may be a list of comma separated tags, with empty strings ignored. """ if tags is not None: for tag in tags: return [t for t in tag.split(",") if t != ""] return []
def reorganize_data(texts): """ Reorganize data to contain tuples of a all signs combined and all trans combined :param texts: sentences in format of tuples of (sign, tran) :return: data reorganized """ data = [] for sentence in texts: signs = [] trans = [] for sign,...
def get_scanner(time, height): """Returns the position of the scanner in a layer with a given depth after a specified number of picoseconds has passed""" # Use triangle wave to determine the position offset = time % ((height - 1) * 2) if offset > height - 1: position = 2 * (height - 1) - of...
def raise_skip_event(events, event_name, *event_args): """Execute all functions defined for an event of a parser. If a function returns ``False``, this function will return ``True`` meaning that an event is trying to skip the associated function. Args: events (dict): Dictionary with all events...
def get_thresholds(threshs_d: dict) -> tuple: """ Parameters ---------- threshs_d : dict Thresholds configs Returns ------- names : list Name for the threshold thresh_sam : int Samples threshold thresh_feat : int Features threshold """ names ...
def is_complex(setting_value): """ returns True if the setting is 'complex' """ return '!!' in setting_value
def countBits(value): """ Count number of bits needed to store a (positive) integer number. >>> countBits(0) 1 >>> countBits(1000) 10 >>> countBits(44100) 16 >>> countBits(18446744073709551615) 64 """ assert 0 <= value count = 1 bits = 1 while (1 << bits) <= ...
def strides_from_shape(ndim, shape, itemsize, layout): """Calculate strides of a contiguous array. Layout is 'C' or 'F' (Fortran).""" if ndim == 0: return () if layout == 'C': strides = list(shape[1:]) + [itemsize] for i in range(ndim - 2, -1, -1): strides[i] *= st...
def only_given_keys(dictionary, keys): """ Outputs a dictionary with the key:values of an original dictionary, but only with items whose keys are specified as a parameter. """ res = dict(dictionary) for key in dictionary: if key not in keys: del res[key] return res
def stripExtra(name): """This function removes paranthesis from a string *Can later be implemented for other uses like removing other characters from string Args: name (string): character's name Returns: string: character's name without paranthesis """ startIndexPer=name.find('(') start...
def int_nthstr(n): """ Formats an ordinal. Doesn't handle negative numbers. >>> nthstr(1) '1st' >>> nthstr(0) '0th' >>> [nthstr(x) for x in [2, 3, 4, 5, 10, 11, 12, 13, 14, 15]] ['2nd', '3rd', '4th', '5th', '10th', '11th', '12th', '13th', '14th', '1...
def armstrong_number(number): """ Check if number is Armstrong number """ calc = number sum_ = 0 while calc > 0: dig = calc % 10 sum_ += dig ** 3 calc //= 10 if number == sum_: return True else: return False
def bisect(sequence, value, key=None, side='left'): """ Uses binary search to find index where if given value inserted, the order of items is preserved. The collection of items is assumed to be sorted in ascending order. Args: sequence: list or tuple Collection of items orde...
def isDict(val): """Returns true if the passed value is a python dictionary type, otherwise false. **Parameters:** * val - value to test **Returns:** True if the passed value is a dictionary, otherwise false.""" return isinstance(val, dict)
def unpack(cursor): """Returns data in a database cursor object as list""" return [data for data in cursor]
def format_regex_stack(regex_stack): """Format a list or tuple of regex url patterns into a single path.""" import re formatted = ''.join(regex_stack) formatted = re.sub('\([^<]*(<[^>]*>).*?\)', '\\1', formatted) formatted = formatted.replace('^$','/') formatted = formatted.replace('^','/') ...
def to_param(m): """ Converts testkit parameter format to driver (python) parameter """ value = m["data"]["value"] name = m["name"] if name == "CypherNull": return None if name == "CypherString": return str(value) if name == "CypherBool": return bool(value) if nam...
def pack_params(params): """ returns a tuple to be hashed, convert function into their name """ lp = [] for x in params: if callable(x): lp.append(x.__name__) else: lp.append(x) return tuple(lp)
def _strip_unbalanced_punctuation(text, is_open_char, is_close_char): """Remove unbalanced punctuation (e.g parentheses or quotes) from text. Removes each opening punctuation character for which it can't find corresponding closing character, and vice versa. It can only handle one type of punctuation ...
def funcname(func): """Get the name of a function.""" while hasattr(func, "func"): func = func.func try: return func.__name__ except Exception: return str(func)
def calc_sum(num): """returns sum of a list """ sum_num = 0 for t in num: sum_num = sum_num + t return sum_num
def findClosestMultipleAboveThreshold(num: int, threshold: int) -> int: """ Returns the number's closest multiple above the threshold """ while True: if threshold % num == 0: return threshold else: threshold += 1
def getInitial(name): """Get initial from name e.g. "Jane" >> "J. " Parameters ---------- name :str Name to retrieve initial from Returns ------- str Initialised name """ return name[0] + '. '
def get_threshold_multiplier(total_nobs, nob_limits, multiplier_values): """ Find the highest value of i such that total_nobs is greater than nob_limits[i] and return multiplier_values[i] :param total_nobs: total number of neighbour observations :param nob_limits: list containing the lim...
def get_polygons_neighborhood(polygons): """Returns for each polygon a set of intersecting polygons.""" nb_polygons = len(polygons) neighborhoods = [set() for c in range(nb_polygons)] for ix1, p1 in enumerate(polygons): for ix2 in range(ix1 + 1, nb_polygons): p2 = polygons[ix2] ...
def create_array(data_list): """ Returns all texts from a given soup. :param data_list: Soup array with all headlines/conversations embedded as text. :return: Array of headlines/conversations, retrieved from the soup. """ result_array = [] for li in data_list: if li.text != "": ...
def _warning_on_one_line(message, category, filename, lineno, file=None, line=None): """Formats warning messages to appear on one line.""" return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)
def write_ready_analogy(list_analogies, description, file): """ Print a ready analogy to a file :param list_analogies: list of list of 4 strings :param description: string describing the analogy category :param file: file to print to :return: number of printed analogies """ # Helper variables for printi...
def set_recursive(config, recursive): """ set global recursive setting in config """ config['recursive'] = recursive return True
def year_to_rating(movie_map): """Given a dictionary, returns new dictionary that maps release year to a list of IMBD ratings for each of those years. Parameter: movie_map: a dictionary that maps movieIDs to genre(s), release year, IMBD rating, female character count and male character coun...
def error_max_retry(num_retries, err_string): """error_max_retry message""" return "Unable to retrieve artifact after {} retries: {}".format(num_retries, err_string)
def get_vcs_uri_for_branch(data, branch=None): """ @param data: rosdoc manifest data @param branch: source branch type ('devel' or 'release') """ ri_entry = None if branch: branch_data = data.get('rosinstalls', None) if branch_data: ri_entry = branch_data.get(branch, ...
def retrieve_uuid(uuid_appended_id): """Retrieves the uuid of a uuid appended id Parameters ---------- uuid_appended_id : str A uuid appended id of the form uuid|base_id. Returns ------- str The uuid portion of the appended id. """ if uuid_appended_id.find('|') < 0...
def lorentzian(x, x0, gamma): """complex lorentzian peak lorentzianAmp(x, x0, gamma) = lorentzian(x, x0, gamma) * conj(lorentzian(x, x0, gamma)) """ return 1 / (1 + 1j * (x - x0) / gamma)
def flatten(l): """ flatten a nested list. https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists Parameters ---------- l: array-like """ return [item for sublist in l for item in sublist]
def is_image_file(filename): """ Return true if the file is an image Parameters ---------- filename : str the name of the image file Return ------ bool : bool True if **file** is an image. """ return any(filename.lower().endswith(extension) for extension in ['...
def union(probs): """ Calculates the union of a list of probabilities [p_1, p_2, ... p_n] p = p_1 U p_2 U ... U p_n """ while len(probs)>1: if len(probs) % 2: p, probs = probs[0], probs[1:] probs[0]=probs[0]+p -probs[0]*p probs = [probs[i-1]+probs[i]-probs[i-1]*probs[i] ...