content
stringlengths
42
6.51k
def bezier_quadratic(p0, p1, p2, t): """Returns a position on bezier curve defined by 3 points and t.""" return p1 + (1-t)**2*(p0-p1) + t**2*(p2-p1)
def trade(first, second): """Exchange the smallest prefixes of first and second that have equal sum. >>> a = [1, 1, 3, 2, 1, 1, 4] >>> b = [4, 3, 2, 7] >>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7 'Deal!' >>> a [4, 3, 1, 1, 4] >>> b [1, 1, 3, 2, 2, 7] >>> c = [3, 3, 2, 4, 1] ...
def clean_state_dict(state_dict): """save a cleaned version of model without dict and DataParallel Arguments: state_dict {collections.OrderedDict} -- [description] Returns: clean_model {collections.OrderedDict} -- [description] """ clean_model = state_dict # create new Ordered...
def make_file_string(year): """ Create a file name string from the year, e.g. 'laetoli_csho_1998.xls' :param year: four digit integer value :return: string representation of file name """ return 'laetoli_csho_'+str(year)+'.xls'
def is_backward_locking(locked_keys, key): # ### Naive dead lock detect: # # Locks must be acquired in alphabetic order(or other order, from left to right. # Trying to acquire a `lock>=right_most_locked`, is a forward locking Otherwise it # ...
def generate_doc_text_replace_options(use_case, model_name, precision, mode): """ Returns a dictionary of the default text replace options that are used for generating documentation. This is used as the default key/value pairs when """ # Define dictionary of keywords to replace and try to set prope...
def select_files(files, search): """Select files based on a search term of interest. Parameters ---------- files : list of str File list. search : str String to use to keep files. Returns ------- list of str File list with selected files kept. """ retur...
def convert_to_list(input, _type=int, _default_output=None): """ Converts the input to a list if not already. Also performs checks for type of list items and will set output to the default value if type criteria isn't met Args: input: input that you are analyzing to convert to list of type ...
def metaslice(alen, nmeta, trim=0, thickness=False): """ Return *[imin,imax,istp]* so that `range(imin,imax+1,istp)` are the boundary indices for *nmeta* (centered) metaslices. Note: *imax* is the end boundary index of last metaslice, therefore element *imax* is *not* included in last ...
def file_parts(filename): """ prefix is part before the first dot extension is all the parts after the first dot """ prefix = filename.split(".")[0] extension = ".".join(filename.split(".")[1:]).lstrip(".") return prefix, extension
def _join_prodigy_tokens(text): """Return all prodigy tokens in a single string """ return "\n".join([str(i) for i in text])
def TOTAL_DEGREE_FREEDOM(N_DOFSNODE, N_NODES): """ This function determines the quantity and ID values of the structure's global degrees of freedom. Input: N_DOFSNODE | Number of degress of freedom per node | Integer N_NODES | Number of nodes | Integer Outpu...
def middlePoint(A, B): """ Finds the point between two points @parameter A: point #1 @parameter B: point #2 @returns: typle(x,y) halfway from A toward B""" return (int((B[0] + A[0]) / 2), int((B[1] + A[1]) / 2))
def check_all_there(the_list): """Checks if all of the elements are not None or if there is an empty list. Keywords: (list) the_list: input list of everything Returns: (bool) True: if everything inside the list """ # For each row in the list for row in the_list: # For ...
def dict_of(cls): """Decorator that converts a class into a dict of its public members.""" return {k: v for k, v in cls.__dict__.items() if not k.startswith('_')}
def identify_ossim_kwl(ossim_kwl_file): """ parse geom file to identify if it is an ossim model :param ossim_kwl_file : ossim keyword list file :type ossim_kwl_file : str :return ossim kwl info : ossimmodel or None if not an ossim kwl file :rtype str """ try: with open(ossim_kwl_...
def bin2str(binary): """Convert biary 16 bit binary message into a string of chars.""" assert isinstance(binary, bytes), 'must give a byte obj' assert len(binary) % 16 == 0, 'must have 16 bit valuess' return ''.join([chr(int(binary[n: n+16], 2)) for n in range(0, len(binary), 16)]).e...
def getURL(key): """Takes in Spreadsheet key and appends url attributes. key -- Google Spreadsheet Key """ return "https://spreadsheets.google.com/feeds/list/"+str(key)+"/od6/public/basic?alt=json"
def _corner_to_coco_bbox(bbox): """ from corner format to (tlx, tly, w, h) :param bbox: :return: """ return [(bbox[0]), (bbox[1]), (bbox[2] - bbox[0]), (bbox[3] - bbox[1])]
def _process_project_id(issues, project_id): """Set the project id of given issues""" for task in issues: task["project id"] = project_id return issues
def get_args_string(cli_args): """Convert dict of cli argument into string Args: cli_args: dict of cli arguments Returns: str: string of joined key=values """ args = [] for key, value in cli_args.items(): if not value: continue if type(value) == list:...
def compare_lines(expected_path, to_test_path, num_lines, reverse=False): """Compares the first n lines of two files. Args: expected_path: Path to the file with the expected content, as a string. to_test_path: Path to the file to compare with the expected file, as a string. ...
def split_list(l, size): """Split a list into evenly sized chunks Parameters ---------- l : list The list to split size : n The size of each chunk Returns ------- A list of sub-lists Examples -------- >>> from fnss.util import split_list >>> split_list(...
def LineModel(line): """ Summary : This functions compares a string to model with typo handling Parameters : comparison string Return : Boolean """ try: line = line.lower() except: return False if 'default:' in line: return False if...
def merge(left, right): """When left side/right side is empty, It means that this is an individual item and is already sorted.""" #We make sure the right/left side is not empty #meaning that it's an individual item and it's already sorted. if not len(left): return left if not len(...
def collide(Aleft, Aright, Bleft, Bright): """ optimised for speed. """ # quickest rejections first; if Aright < Bleft: return(False) if Aleft > Bright: return(False) if Aleft == Bleft: return(1) # I have to cheat here otherwise it returns 0 which will evaluate as False; ...
def get_dice_coefficient(a_license, b_license): """Sorensen dice coefficient may be calculated for two strings, x and y for the purpose of string similarity measure. Dice coefficient is defined as 2nt/(na + nb), where nt is the number of character bigrams found in both strings, na is the number of bigra...
def find_sum(num_digits, nums): """ Find the total sum of the numbers entered """ sum = 0 for count in range (num_digits): sum = sum + nums[count] return sum
def printable(s): """make a string printable. Converts all non-printable ascii characters and all non-space whitespace to periods. This keeps a string to a fixed width when printing it. This is not meant for canonicalization. It is far more restrictive since it removes many things that migh...
def secant(func, min_guess, max_guess, err_tolerance, max_try=10000): """ Find the root of a function using secant method. (Newton method) arguments: func: f(x) min_guess: minimum x as guess max_guess: maximum x as guess err_tolerance: value where f(root) must be less than err_tolerance ...
def get_digit(number, position, base=10): """Return the digit we are looking at based on the position and the base. For example: number = 1234, position = 3, looking at the 1. position_digit = 10 ** 3 = 1000. divide 1234 by 1000 floored = 1. modulo the result by 10 as we are doin...
def product(cdc): """ Given a string, including a number, this function calculates the value of digit's number product. """ nb = 1 for elt in cdc: nb *= int(elt) return nb
def unique(iterable): """Return unique values from iterable.""" seen = set() return [i for i in iterable if not (i in seen or seen.add(i))]
def cursor(s): """'ab|c' -> (2, 'abc')""" cursor_offset = s.index("|") line = s[:cursor_offset] + s[cursor_offset + 1 :] return cursor_offset, line
def _list_subclasses(cls): """ Recursively lists all subclasses of `cls`. """ subclasses = cls.__subclasses__() for subclass in cls.__subclasses__(): subclasses += _list_subclasses(subclass) return subclasses
def get_pairs(X): """ Given a list NX returns a list of the len(X) choose 2 pairs """ pairs = [] for i in range(len(X)): for j in range(len(X)): if i < j: pairs.append((X[i], X[j])) return pairs
def _format_meter_reference(counter_name, counter_type, counter_unit): """Format reference to meter data. """ return "%s!%s!%s" % (counter_name, counter_type, counter_unit)
def evaluateUDGoogleSpecial(tokensArrayGT, tokensArrayProvider): """See evaluateUD, except we account for Google's service not being able to recognize the POS tags 'INTJ', 'SCONJ', and 'SYM'. The total count of ground-truth tokens is deducted by the occurence count of these three tags. Arguments: token...
def update_global_map(global_map, map_update): """ Maps an article copy to a source article in the global map. If the source article isn't found, adds the source article and copy to the global map. :param global_map: List of articles with associated copies :param map_update: Dictionary of data to up...
def consistency_zero_division(line): """ This function returns a new line for each Row of the rdd with the evaluation of the Consistency dimension Args: line(Row): row of the rdd """ try: return (line[0], float(line[1][1]) / line[1][0]) except Exception: return (line...
def ensure_uid(doc_or_uid): """ Accept a uid or a dict with a 'uid' key. Return the uid. """ try: return doc_or_uid['uid'] except TypeError: return doc_or_uid
def GetTryJobCommand(change_list, extra_change_lists, options, builder): """Constructs the 'tryjob' command. Args: change_list: The CL obtained from updating the packages. extra_change_lists: Extra change lists that would like to be run alongside the change list of updating the packages. options: O...
def countKey(theDict, name): """ Return the number of times the given par exists in this dict-tree, since the same key name may be used in different sections/sub-sections. """ retval = 0 for key in theDict: val = theDict[key] if isinstance(val, dict): retval += countKey(val,...
def format_height_imperial(height): """Formats a height in decimeters as F'I".""" return "%d'%.1f\"" % ( height * 0.32808399, (height * 0.32808399 % 1) * 12, )
def development_overhead_cost_discount(hybrid_plant_size_MW, technology_size_MW): """ Overhead is 2% of total cost (before management cost) at 100 MW. And 12 % of TIC at 5 MW. https://www.nrel.gov/docs/fy19osti/72399.pdf """ if technology_size_MW == 0: overhead_discount_multiplier = 0 ...
def upper_power_of_two(value) -> int: """Returns the value of 2 raised to some power which is the smallest such value that is just >= *value*.""" result = 1 while result < value: result <<= 1 return result
def getSQLT(timestamp): """Make timestamp for SQLite from Python timestamp, meaning a UNIX epoch INTEGER. :param timestamp: :return: SQLite compatible timestamp in the form of a UNIX epoch INTEGER""" # I know this is a very small function, but now it's clear what SQL needs return int(timestamp)
def Sphere(individual): """Sphere test objective function. F(x) = sum_{i=1}^d xi^2 d=1,2,3,... Range: [-100,100] Minima: 0 """ #print(individual) return sum(x**2 for x in individual)
def throttling_mod_func(d: list, e: int): """Perform the modular function from the throttling array functions. In the javascript, the modular operation is as follows: e = (e % d.length + d.length) % d.length We simply translate this to python here. """ return (e % len(d) + len(d)) % len(d)
def _flatten_dependency_maps(all_dependency_maps): """Flatten a list of dependency maps into one dictionary. Dependency maps have the following structure: ```python DEPENDENCIES_MAP = { # The first key in the map is a Bazel package # name of the workspace this file is defined in. ...
def diam_fractal(DIM_FRACTAL, DiamInitial, NumCol): """Return the diameter of a floc given NumCol doubling collisions.""" return DiamInitial * 2**(NumCol / DIM_FRACTAL)
def touchdown(situation, new_situation, **kwargs): """Assumes successful XP and no 2PC -- revisit this for 2015?""" new_situation['score_diff'] = situation['score_diff'] + 7 new_situation['yfog'] = 25 return new_situation
def newton_raphson(func, funcd, initial_guess=1, acc=0.000001, max_iter=100000): """ func -> Function to find root of funcd -> Derivative of function It does not work all the time!! """ guess = initial_guess # CAREFUL: Dont forget abs()!! while abs(func(guess)) > acc and max_iter >= 0: ...
def get_wait_time(retries, args): """ Calculates how long we should wait to execute a failed task, based on how many times it's failed in the past. Args: retries: An int that indicates how many times this task has failed. args: A dict that contains information about when the user wants to retry the...
def _MilestoneLabel(alerts): """Returns a milestone label string, or None.""" revisions = [a.start_revision for a in alerts if hasattr(a, 'start_revision')] if not revisions: return None start_revision = min(revisions) try: milestone = _GetMilestoneForRevision(start_revision) except KeyError: lo...
def is_valid_config(config): """ Checks if a data structure can be considered as a valid binoas configuration file. Returns true or false. """ return ( len(config.keys()) == 1 and ('binoas' in config) )
def number_to_cells(num, num_cells): """Convert an integer into 32-bit cells""" cells = [] for i in range(num_cells): cells.insert(0, (0xFFFFFFFF & (num >> (32 * i)))) return " ".join(["0x%x" % x for x in cells])
def reverse_complement(sequence): """ Return reverse complement of a sequence. """ complement_bases = { 'g':'c', 'c':'g', 'a':'t', 't':'a', 'n':'n', 'G':'C', 'C':'G', 'A':'T', 'T':'A', 'N':'N', "-":"-", "R":"Y", "Y":"R", "S":"W", "W":"S", "K":"M", "M":"K", "B":"V", "V":"B", "D": ...
def _uniquify(seq, sep='-'): """Uniquify a list of strings. Adding unique numbers to duplicate values. Parameters ---------- seq : `list` or `array-like` A list of values sep : `str` Separator Returns ------- seq: `list` or `array-like` A list of updated va...
def to_list(str_rep_list: str) -> list: """ Convenience function to change a string representation of a Python list into an actual list object. :param str str_rep_list: String that represents a Python list. e.g. "['0.5', '2.0']" :return: The parsed representative string. :rtype: list """ in...
def replace_tup(tupl, old, new, count=-1): """ Creates a copy of ``tupl`` with all occurrences of value ``old`` replaced by ``new``. Objects are replaced by value equality, not id equality (i.e. ``==`` not ``is``). If the optional argument ``count`` is given, only the first count occurrences are ...
def freeze(o): """ Makes a hash out of anything that contains only list,dict and hashable types including string and numeric types """ if isinstance(o, dict): return frozenset({ k:freeze(v) for k,v in o.items()}.items()) if isinstance(o,list): return tuple(freeze(v) for v in o) ...
def make_symmetric(dict): """Makes the given dictionary symmetric. Values are assumed to be unique.""" for key, value in list(dict.items()): dict[value] = key return dict
def shortest_row_F(F1): """ Get the minimum and maximum length of the elements of F1. Parameters ---------- F1 : list of numpy 1D arrays. Returns ------- shortest_row length of the shortest element in F1. longest_row length of the longest element in F1...
def _mat_vec_dot_fp(x, y): """Matrix (list of list) times vector (list).""" return [sum(a * b for a, b in zip(row_x, y)) for row_x in x]
def parse_address(json) -> list: """ Function that parses the Google maps API json output @param json: Google's reverse lookup json object @returns: a list with address, zipcode, neighborhood, and locality (Google defined) """ result=json['results'][0] address=result['formatted_address...
def _kappamstar(kappa, m, xi): """ Computes maximized cumulant of order m Parameters ----- kappa : list The first two cumulants of the data xi : int The :math:`\\xi` for which is computed the p value of :math:`H_0` m : float The order of the cumulant Returns ...
def remove_tokens_at_indices(tokens, indices): """ param 'indices' is assumed to be sorted in increasing order :type tokens: list[object] :type indices: list[int] """ for index in reversed(indices): tokens = tokens[0:index] + tokens[index+1:] return tokens
def format_sec(s): """ Format seconds in a more human readable way. It supports units down to nanoseconds. :param s: Float of seconds to format :return: String second representation, like 12.4 us """ prefixes = ["", "m", "u", "n"] unit = 0 while s < 1 and unit + 1 < len(prefixes):...
def BrickNameStrip(s, level=0): """Progressively strips (with increasing levels) a part description by making substitutions with abreviations, removing spaces, etc. This can be useful for labelling or BOM part lists where space is limited.""" sn = s if level == 0: sn = sn.replace(" ", " ") ...
def _get_type_and_value(entry): """Parse dmidecode entry and return key/value pair""" r = {} for l in entry.split('\n'): s = l.split(':') if len(s) != 2: continue r[s[0].strip()] = s[1].strip() return r
def filter_and_rename_dict(indict, filterdict): """ Renames the keys of the input dict using the filterdict. Keys not present in the filterdict will be removed. Example: >>> import pprint >>> outdict =filter_and_rename_dict({'a': 1, 'b':[2,2]}, {'a': 'c', 'b': 'd', 'e': 'f'}) ...
def make_message(msg_format, coll_id="testcoll", type_id="testtype", **kwargs): """ Combine supplied message format string with keyword parameters to build a message text. """ msg_vals = dict(kwargs, coll_id=coll_id, type_id=type_id) msg_text = msg_format%msg_vals ...
def httpDelete( url, contentType=None, connectTimeout=10000, readTimeout=60000, username=None, password=None, headerValues=None, bypassCertValidation=True, ): """Performs an HTTP DELETE to the given URL. Args: url (str): The URL to send the request to. contentTyp...
def unchunk(body: bytes): """ Unchunks a Transfer-encoding: chunked HTTP response :param body: The bytes of the chunked response :return: The unchunked response """ # new_body will have unchunked response new_body = b"" # iterate through chunks until we hit the last chunk crlf_loc ...
def mu_prime(eta, eta_0, Kappa=0.4): """ eta = k z, vertical coordinate [Adi.] Kappa, Von Karman constant (typically 0.4) """ return (1/Kappa)*(1/(eta + eta_0))
def g(n): """Return the value of G(n), computed recursively. >>> g(1) 1 >>> g(2) 2 >>> g(3) 3 >>> g(4) 10 >>> g(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g', ['While', 'For']) True """ "*** YOUR CODE HERE ***" if n < 4: ...
def suggestDType(x): """Return a suitable dtype for x""" if isinstance(x, list) or isinstance(x, tuple): if len(x) == 0: raise Exception('can not determine dtype for empty list') x = x[0] if hasattr(x, 'dtype'): return x.dtype elif isinstance(x, float): ...
def averageJCoup_on(models, my_data): """Returns a dictonary with the average J-Couplings for the given type: averageJCoup[residue] = value""" averageJCoup = {} for model_num, model in enumerate(my_data): if model_num not in models: continue for resnum in model: ...
def computeStrideLength(window_length, overlap_ratio): """ Convert window length (units of samples) and window overlap ratio to stride length (number of samples between windows). This assumes uniform sampling. """ return round(window_length * (1 - overlap_ratio))
def split_sentence(s): """ Given a string, [s], split it into sentences. # Arguments * `s` (str) - a string to split. # Returns A list strings representing the sentences of the text. It is guaranteed that each string is non-empty, has at least one whitespace character, and both start...
def ends_in_regular(string): """ According to the specification, the font fullname should not end in 'Regular' for plain fonts. However, some fonts don't obey this rule. We keep the style info, to minimize the diff. """ string = string.strip().split()[-1] return string is 'Regular'
def objective(data): """ Objective function Returns sum of array Parameters: data : np.array """ return -sum(data)
def check_allowed_references( get_allows_none, get_allowed_types, request, ref_dict ): """Check the reference according to rules specific to requests. In case the ``ref_dict`` is ``None``, it will check if this is allowed for the reference at hand. Otherwise, it will check if the reference dict's k...
def uniq_add(my_list=[]): """Add all unique integers in a list (once for each integer).""" result = 0 for x in set(my_list): result += x return (result)
def get_id(fastq_seq): """ Retrieve sequence ID for a READs. :param fastq_seq: (list) a list contains four lines of a fastq file :return: id: (string) a sequence id """ if "@" in fastq_seq[0]: id = fastq_seq[0].strip().split()[0].replace("@", "") return id else: raise...
def _merge_bounds(b1, b2): """Merge bounds coordenates.""" mins1, maxs1, sums1, n1 = b1 mins2, maxs2, sums2, n2 = b2 if n1 > 0: if n2 > 0: min_lat = min([mins1[0], mins2[0]]) min_lon = min([mins1[1], mins2[1]]) max_lat = max([maxs1[0], maxs2[0]]) ...
def rm_whitespace(data): """Function: rm_whitespace Description: Remove white space from a data string. Arguments: (input) data -> Data string. (output) Data string minus any white spaces. """ return data.replace(" ", "")
def lchloc(b5, b7): """ Leaf Chlorophyll Content (Wulf and Stuhler, 2015). .. math:: LChloC = b7/b5 :param b5: Red-edge 1. :type b5: numpy.ndarray or float :param b7: Red-edge 3. :type b7: numpy.ndarray or float :returns LChloC: Index value .. Tip:: Wulf, H.; Stuhler, S....
def text2ascii(text): """ Takes in a string text, returns the encoded text in ascii.""" ascii_string = " ".join(format(ord(x)) for x in text) return ascii_string
def create(event, context): """Noop.""" return "MNPJobDefinitionCleanupHandler", {}
def _autotuple(a): """Automatically convert the supplied iterable to a scalar or tuple as appropriate.""" if not hasattr(a, "__iter__"): return a if len(a) == 1: return a[0] return tuple(a)
def make_line_points(y1, y2, line): """ Convert a line represented in slope and intercept into pixel points """ if line is None: return None #look at https://github.com/paramaggarwal/CarND-LaneLines-P1/blob/master/P1.ipynb for average moving lines slope, intercept = line # make...
def length(requests_mean): """ Arbitry choices to associate number of requests with length """ if requests_mean<=5.: return 'short'; elif requests_mean<=10: return 'medium'; else: return 'long';
def fuse_slice_pair(slice0, slice1, length): """computes slice `s` such that array[s] = array[s0][s1] where array has length `length`""" start0, stop0, step0 = slice0.indices(length) start1, stop1, step1 = slice1.indices(len(range(start0, stop0, step0))) stop01 = start0 + stop1 * step0 return slice(...
def getval(obj, getter): """Gets a value from an object, using a getter which can be a callable, an attribute, or a dot-separated list of attributes""" if callable(getter): val = getter(obj) else: val = obj for attr in getter.split('.'): val = getattr(val, a...
def crop(w, h, bw, bh): """Crop Makes sure one side fits and crops the other Arguments: w (int): The current width h (int): The current height bw (int): The boundary width bh (int): The boundary height Returns: dict """ # Init the return dRet = {} # Easier to work with floats w = float(w) h = f...
def translate(x, lowerIn, upperIn, lowerOut, upperOut): """Map in value range to another range""" y = (x - lowerIn) / (upperIn - lowerIn) * (upperOut - lowerOut) + lowerOut return y
def get_5d_string( number ): """ takes an integer < 100000, returns a string of the number that's the 5 characters long. If the number is < 10000, it puts zeros at the front to make the string 5 chars long """ thing = "" for i in range(5): thing+= str( int(number/( 10**(4-i))) % 10 ) ...
def strip_characters(text: str, *args: str) -> str: """Remove specified characters from given text.""" for char in args: text = text.replace(char, "") return text