content
stringlengths
42
6.51k
def _parent_key(d): """ Return the function path of the parent of function specified by 'id' in the given dict. """ parts = d['id'].rsplit('|', 1) if len(parts) == 1: return '' return parts[0]
def fib_memo(n, seen): """ Return the nth fibonacci number reasonably quickly. @param int n: index of fibonacci number @param dict[int, int] seen: already-seen results """ if n not in seen: seen[n] = (n if n < 2 else fib_memo(n - 2, seen) + fib_memo(n - 1, seen)) ...
def flip_string(string): """Perform byte-swap to reverse endianess, we use big endian, but atmel processor is little endian""" i = 0 reverse_string = '' string_length = len(string) while i < string_length: reverse_string += string[string_length-i-1] i += 1 return reverse_string
def pix2point(shape, ix, iy, ovs=1): """ find the nearest pixel to point `ix`, `iy` in the plane with shape `shape` ovs is the oversampling factor for spatial antialiasing """ cr = ((ix/ovs)*3.0/shape[0] - 2.0) # [0, width] > [-2, 1] ci = ((iy/ovs)*2.0/shape[1] - 1.0) # [0, heigh...
def unescape(s): """ unescape html tokens. <p>{{ unescape(content) }}</p> """ return ( s.replace("&amp;", "&") .replace("&lt;", "<") .replace("&gt;", ">") .replace("&quot;", '"') .replace("&#039;", "'") )
def getValues(currentValues, current, total): """ Return either the current values (for this horizon) or all computed results Parameters ---------- currentValues : Boolean True: return 'current', False: return 'total' current : Pointer Pointer to the current values total : ...
def determine_major_version(all_repos_tags): """ Determine official major version i.e 4.1 , 4.2..etc using oxauths repo @param all_repos_tags: @return: """ versions_list = [] for tag in all_repos_tags["oxauth"]: # Exclude any tag with the following if "dev" not in tag \ ...
def pre_process(strr): """ Write preprocessing to be performed on string to normalize string For now: string needs to be lower case Ideas: Group similar character by unsupervised learning, require CV and replace appropriate alphabet """ strr = strr.lower() return strr
def shortstr(s,max_len=144,replace={'\n':';'}): """ Obtain a shorter string """ s = str(s) for k,v in replace.items(): s = s.replace(k,v) if max_len>0 and len(s) > max_len: s = s[:max_len-4]+' ...' return s
def slice_arrays(arrays, start=None, stop=None): """Slices an array or list of arrays. """ if arrays is None: return [None] elif isinstance(arrays, list): return [None if x is None else x[start:stop] for x in arrays] else: return arrays[start:stop]
def removeStopWords(words,stop_words=None): """ remove stop words from word list """ if stop_words: return [word for word in words if word not in stop_words] else: return words
def count_variables(expr): """Count variables with the same value. >>> count_variables('xxy') { 'x': 2, 'y': 1 } """ result = {} variables = [] for x in list(expr): if x not in variables: variables.append(x) for x in variable...
def _normalise_drive_string(drive): """Normalise drive string to a single letter.""" if not drive: raise ValueError("invalid drive letter: %r" % (drive,)) if len(drive) > 3: raise ValueError("invalid drive letter: %r" % (drive,)) if not drive[0].isalpha(): raise ValueError("inval...
def sep_num(number, space=True): """ Creates a string representation of a number with separators each thousand. If space is True, then it uses spaces for the separator otherwise it will use commas Note ---- Source: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separ...
def label_map(x): """Mapping the original labels.""" if x == 2: return 1 else: return -1
def _coerce_bool(some_str): """Stupid little method to try to assist casting command line args to booleans """ if some_str.lower().strip() in ['n', 'no', 'off', 'f', 'false', '0']: return False return bool(some_str)
def evap_i(pet, si, simax): """evaporation from interception""" # set to 0 when FAO pet is negative (Wilcox & Sly (1976)) if pet < 0: pet = 0 if simax == 0: ei = 0 else: ei = min(si, pet * (si / simax) ** (2 / 3)) si = si - ei pet_r = pet - ei return ei, si, pet_r
def check_column(board): """ list -> bool This function checks if every column has different numbers and returns True is yes, and False if not. >>> check_column(["**** ****", "***1 ****", "** 3****", \ "* 4 1****", " 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"]) False >>> ...
def fixDelex(filename, data, data2, idx, idx_acts): """Given system dialogue acts fix automatic delexicalization.""" try: turn = data2[filename.strip('.json')][str(idx_acts)] except: return data if not isinstance(turn, str): #and not isinstance(turn, unicode): for k, act in turn...
def _model(source_names): """Build additive model string for Gaussian sources.""" return ' + '.join(['normgauss2d.' + name for name in source_names])
def test_for_blank_lines_separating_reference_lines(ref_sect): """Test to see if reference lines are separated by blank lines so that these can be used to rebuild reference lines. @param ref_sect: (list) of strings - the reference section. @return: (int) 0 if blank lines do not separate referen...
def check_is_fid_valid(fid, raise_exception=True): """ Check if FID is well formed :param fid: functional ID :param raise_exception: Indicate if an exception shall be raised (True, default) or not (False) :type fid: str :type raise_exception: bool :returns: the status of the check :rt...
def min_bounding_dimension(bounds): """Return a minimal dimension along axis in a bounds ([min_x, max_x, min_y, max_y, min_z, max_z]) array.""" return min(abs(x1 - x0) for x0, x1 in zip(bounds, bounds[1:]))
def convert_data(planet): """Convert string values of a dictionary to the appropriate type whenever possible. Remember to set the value to None when the string is "unknown". Type conversions: rotation_period (str->int) orbital_period (str->int) diameter (str->int) climate (s...
def get_date(file_name): """ Parameters ---------- file_name : file name string Returns ------- date string for file in the form yyyymmddhhmm """ # Examples: # Vid-000351067-00-06-2014-10-29-13-20.jpg # Vid-000330038-00-02-2016-01-14-19-22.jpg date = None if len(fil...
def select(q_sols, q_d, w=[1]*6): """Select the optimal solutions among a set of feasible joint value solutions. Args: q_sols: A set of feasible joint value solutions (unit: radian) q_d: A list of desired joint value solution (unit: radian) w: A list of weight corresponding to ro...
def to_str(x, fmt): """Convert variable to string.""" x = "" if x is None else x if not isinstance(x, str): # Special handling for floating point numbers if "f" in fmt: # Number of decimals is specified if "." in fmt: n = int(fmt[3:].split(".")[0]) ...
def parse_num(maybe_num) -> int: """parses number path suffixes, returns -1 on error""" try: return int(maybe_num) except ValueError: return -1
def char_ngrams(n, word, **kwargs): """This function extracts character ngrams for the given word Args: n (int): Max size of n-gram to extract word (str): The word to be extract n-grams from Returns: list: A list of character n-grams for the given word """ del kwargs ch...
def is_lower_snake(text): """ Check if a string is in a lower_snake_case format :param text: String to check :return: Whether string is in lower snake format """ if " " in text: return False return "_" in text and not text.isupper()
def parse_file_arg(arg): """Handles @file format for users, to load the list of users from said file, one per line.""" if not isinstance(arg, list): arg = [arg] ret = [] for val in arg: if val[0] == '@': with open(val[1:]) as arg_file: ret.extend(arg_file.read...
def linearsearch(A, elem): """ Linear Search Algorithm that searches for an element in an array with O(n) time complexity. inputs: Array A and element e, that has to be searched output: True/False """ for a in A: if a==elem: return True return False
def is_compressed_filetype(filepath): """ Use to check if we should compress files in a zip. """ # for now, only include files which Blender is likely to reference import os assert(isinstance(filepath, bytes)) return os.path.splitext(filepath)[1].lower() in { # images b'.exr'...
def check_type(obj, acceptable_types, optional=False): """Object is an instance of one of the acceptable types or None. Args: obj: The object to be inspected. acceptable_types: A type or tuple of acceptable types. optional(bool): Whether or not the object may be None. Returns: ...
def first_close_to_final(x, y, min_rel_proximity=0.05): """ returns the chronologically first value of x where y was close to min_rel_proximity (y[-1] - y[0]) of the final value of y, i.e., y[-1]. """ min_abs_proximity = (y[-1] - y[0]) * min_rel_proximity final_y = y[-1] for i in range(l...
def leap_year(year): """Determinates if a year is leap""" if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True
def elem_to_string(*args): """Converts list of elements to string""" return "t %d %d %d\n" % tuple(args)
def remove_space_characters(field): """Remove every 28th character if it is a space character.""" if field is None: return None return "".join(c for i, c in enumerate(field) if i % 28 != 27 or c != ' ')
def create_html_url_href(url: str) -> str: """ HTML version of a URL :param url: the URL :return: URL for use in an HTML document """ return f'<a href="{url}">{url}</a>' if url else ""
def get_ip(record, direction): """ Return required IPv4 or IPv6 address (source or destination) from given record. :param record: JSON record searched for IP :param direction: string from which IP will be searched (e.g. "source" => ipfix.sourceIPv4Address or "destination" => ipfix....
def _byteOrderingEndianess(num, length=4): """ Convert from little endian to big endian and vice versa Parameters ---------- num: int input number length: number of bytes of the input number Returns ------- An integer with the endianness changed with respect to input n...
def re_im_to_complex(realpart, imaginarypart): """Convert real and imaginary parts to complex value *realpart* real part linear units *imaginarypart* imaginary part linear units """ return realpart + 1j*imaginarypart
def aliquot_sum(input_num: int) -> int: """ Finds the aliquot sum of an input integer, where the aliquot sum of a number n is defined as the sum of all natural numbers less than n that divide n evenly. For example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is a simple O(n) implementation. ...
def dict_from_object(obj: object): """Convert a object into dictionary with all of its readable attributes.""" # If object is a dict instance, no need to convert. return (obj if isinstance(obj, dict) else {attr: getattr(obj, attr) for attr in dir(obj) if not attr.startswith('_...
def ArchToBits(arch): """Takes an arch string like x64 and ia32 and returns its bitwidth.""" if not arch: # Default to x64. return 64 elif arch == 'x64': return 64 elif arch == 'ia32': return 32 assert False, 'Unsupported architecture'
def _indent_run_instruction(string: str, indent=4) -> str: """Return indented string for Dockerfile `RUN` command.""" out = [] lines = string.splitlines() for ii, line in enumerate(lines): line = line.rstrip() is_last_line = ii == len(lines) - 1 already_cont = line.startswith(("&...
def round_width(width, multiplier, min_depth=8, divisor=8): """ Round width of filters based on width multiplier from: https://github.com/facebookresearch/SlowFast/blob/master/slowfast/models/video_model_builder.py Args: width (int): the channel dimensions of the input. multiplier (float): t...
def unique_items_in_order(x) -> list: """ Return de-duplicated list of items in order they are in supplied array. :param x: vector to inspect :return: list """ ret = [] if x is not None: seen = set() for item in x: if item not in seen: ret.append(...
def gtf_or_db(fname): """ Determine if a file is GTF or TALON DB. Parameters: fname (str): File name / location Returns: ftype (str): 'gtf' or 'db' depending on results """ ext = fname.split('.')[-1] if ext == 'gtf': return 'gtf' elif ext == 'db': return 'db' else: raise Exception('File type must be gt...
def percentage_format(value,decimal=2): """ Format number as percentage """ formatStr = "{:." + str(decimal) + "%}" return formatStr.format(value) #return "{:.2%}".format(value)
def straight_backoff(count): """ Wait 1, 2, 5 seconds. All retries after the 3rd retry will wait 5*N-5 seconds. """ return (1, 2, 5)[count] if count < 3 else 5 * count - 5
def binV2_to_A2(S2,R_acq,mv_per_bin): """ Used to convert SII(t)[bin_V**2] to SII(t)[A**2] """ return S2*(mv_per_bin*1.0e-3)**2/(R_acq**2)
def cleanstring(data): """Remove multiple whitespaces and linefeeds from string. Args: data: String to process Returns: result: Stipped data """ # Initialize key variables nolinefeeds = data.replace('\n', ' ').replace('\r', '').strip() words = nolinefeeds.split() resul...
def exact_exp_date(results, exp): """Returns a string of unique expiry date in yyyy-mm-dd form results: tuple of (Ticker[0] Strike[1] Type[2] Expiration[3] Last[4] Bid[5] Ask[6]) exp: expiration date that was entered or inferred. however, may not have day of the month, or may resolve to mul...
def get_name(filename): """ Return the name of the file. Given naming convention '<name>_<type>.<ext>' where none of the variables contains '_'. """ return filename.split('.')[0].split('_')[0]
def repeat(l, n): """ Repeat all items in list n times repeat([1,2,3], 2) => [1,1,2,2,3,3] http://stackoverflow.com/questions/24225072/repeating-elements-of-a-list-n-times """ return [x for x in l for i in range(n)]
def twos_complement(val, nbits): """Compute the 2's complement of int value val. Credit: https://stackoverflow.com/a/37075643/9235421""" if val < 0: if (val + 1).bit_length() >= nbits: raise ValueError(f"Value {val} is out of range of {nbits}-bit value.") val = (1 << nbits) + val ...
def parse_virustotal(dyn_data: dict) -> dict: """ parses out virustotal information from dyn_data dictionary Not used, just used for data analysis sake Args: dyn_data: dictionary read from dynamic data Returns: network_dict: dictionary parsing the network information extracted...
def poslin(n): """ Positive Linear """ if n < 0: return 0 else: return n
def is_power_of_two(n): """ Determine whether or not given number is a power of two :param n: given number :type n: int :return: whether or not given number is a power of two :rtype: bool """ if n != 0 and n & (n - 1) == 0: return True else: return False
def check_serie_is_number(serie, max_serie=5000): """Check if serie is valid and return boolean. Check if serie is a integer and if so if it is not a made up number for research. First check if it can be converted to a integer and if so check if it has a smaller value than max_serie. Sometime...
def _get_test_methods(test_case_name, test_class_map): """Takes ``test_class_map`` or ``skip_class_map`` and returns the list of methods for the test case or ``None`` if no methods were specified for it :param test_case_name: Name of the test case to check :param test_class_map: Dictionary mapping test...
def fib(num): """ the worst implementation of Fibonacci numbers calculation complexity: T(N) = O(a ^ N), a - constant Parameters ---------- num : int requested Fibonacci number Returns ------- out : int Fibonacci number """ if num < 2: return nu...
def standardize_formula(qstr,rstr,formula_list): """ Docstring for function pyKrev.standardize_formula ==================== This function takes a list of formula and replaces any instances of qstr with rstr. This is an important pre-processing step if isotope names are present in your molecular formul...
def generic_element(title, subtitle=None, image_url=None, buttons=None): """ Creates a dict to use with send_generic :param title: Content for receiver title :param subtitle: Content for receiver subtitle (optional) :param image_url: Content for receiver image to show by url (optional) :param bu...
def floatify(item, default=0.0): """Another environment-parser: the empty string should be treated as None, and return the default, rather than the empty string (which does not become an integer). Default can be either a float or string that float() works on. Note that numeric zero (or string '0') ret...
def find_last_slash(string): """ Search for / in a string. If one or more / was found, divide the string in a list of two string: the first containf all the character at left of the last / (included), and the second contains the remanent part of the text. If no / was found, the first element of the ...
def is_blank(line): """Returns true if the line is empty. A single hyphen in a line is considered as blank """ return line.isspace() or not line or line.strip() == '-'
def triangleCoordsForSide(s): """ Upwards pointing equilateral triangle with equal sides s origin = 0,0 """ factor = 3**0.5/2 coords = ( ( # path (0,0), (s,0), (s/2,factor*s), ), ) return coords
def floateq(a, b, eps=1.e-12): """Are two floats equal up to a difference eps?""" return abs(a - b) < eps
def create_choice(name, value) -> dict: """A function that will create a choice for a :class:`~SlashOption` Parameters ---------- name: :class:`str` The name of the choice value: :class:`Any` The value that will be received when the user selected this choice ...
def get_params_or_defaults(params, defaults): """Returns params.update(default) restricted to default keys.""" merged = { key: params.get(key, default) for key, default in defaults.items() } return merged
def sparse_euclidean2(v1, v2): """Calculates the squared Euclidean distance between two sparse vectors. Args: v1 (dict): First sparse vector v2 (dict): Second sparse vector Returns: float. Squared distance between ``v1`` and ``v2``. """ d = 0.0 for i,v in v...
def use_c_string(str_format: str, items: dict) -> bool: """ Tests if we should use the C type string formatting. Otherwise, defaults to False. Meaning we should use format_map() instead :param str_format: The string format :param items: A dictionary of items to pass to the string formatter :ret...
def HasPositivePatterns(test_filter): """Returns True if test_filter contains a positive pattern, else False Args: test_filter: test-filter style string """ return bool(len(test_filter) > 0 and test_filter[0] != '-')
def baseconvert(n, k, digits="ACDEFGHIKLMNPQRSTVWY"): """Generate a kmer sequence from input integer representation. Parameters ---------- n : int Integer representation of a kmer sequence. k : int Length of the kmer (i.e. protein sequence length). digits : str Digits to...
def decompress_amount(x): """\ Undo the value compression performed by x=compress_amount(n). The input x matches one of the following patterns: x = n = 0 x = 1+10*(9*n + d - 1) + e x = 1+10*(n - 1) + 9""" if not x: return 0; x = x - 1; # x = 10*(9*n + d - 1) + e x, e...
def convert1Dto3Dindex(index,NX,NY,NZ): """Converts 1D array index to 1D array index""" k = index / (NX*NY) j = (index - k*NX*NY) / NX i = index - k*NX*NY - j*NX return [i,j,k]
def dest_namespace(name): """ArgumentParser dest namespace (prefix of all destinations).""" return name.replace("-", "_") + "_"
def lat2txt(lat, fmt='%g'): """ Format the latitude number with degrees. :param lat: :param fmt: :return: :Examples: >>> lat2txt(60) '60\N{DEGREE SIGN}N' >>> lat2txt(-30) '30\N{DEGREE SIGN}S' """ if lat < 0: latlabstr = u'%s\N{DEGREE SIGN}S' % fmt latla...
def poly_derivative(poly): """ args: polynomial return: derivatoive """ if isinstance(poly, list) is False or len(poly) == 0: return None derivatives = [] for i in range(len(poly)): if type(poly[i]) != int and type(poly[i]) != float: return if i != 0: ...
def true_range(data): """True range Arguments: data {list} -- List of ohlc data [open, high, low, close] Returns: list -- True range of given data """ trng = [] for i, _ in enumerate(data): if i < 1: trng.append(0) else: val1 = data[i][1]...
def check_enumerated_value(x): """ Enumerated values (video modes, pixel formats, etc.) should be able to be given as either the lookup key (e.g. 'VM_640x480RGB') or the PyCapture2 code (e.g. 4). Argparse can only return one datatype though, so this func is used to convert to codes to ints while kee...
def _build_options_dict(user_input, default_options): """Create the full dictionary of trust region fast start options from user input. Args: user_input (dict or None): dictionary to update the default options with. May only contain keys present in the default options. default_optio...
def f(x,y): """dy/dx = f(x,y) = 3x^2y""" Y = 3.*x**2. * y return Y
def find_artifact(artifacts, name): """Finds the artifact 'name' among the 'artifacts' Args: artifacts: The list of artifacts available to the function name: The artifact we wish to use Returns: The artifact dictionary found Raises: Exception: If no matching artifact is ...
def _normalize_whitespace(s): """Replaces consecutive whitespace characters with a single space. Args: s: The string to normalize, or None to return an empty string. Returns: A normalized version of the given string. """ return ' '.join((s or '').split())
def get_str_cmd(cmd_lst): """Returns a string with the command to execute""" params = [] for param in cmd_lst: if len(param) > 12: params.append('"{p}"'.format(p=param)) else: params.append(param) return ' '.join(params)
def beats(one, two): """ Evaluates what moves beats what ------- Returns bool true if the move one beats the move two """ return ( (one == "rock" and two == "scissors") or (one == "scissors" and two == "paper") or (one == "paper" and two == "rock") )
def clean_text(text, stopwords): """ Converts free-text with punctuation, numbers, capital letters etc. into a list of words without any of the punctuation and other 'noise' and excludes the pre-determined 'stopwords' """ # remove digits text = ''.join(i for i in text if not i.is...
def state_in_addrlist(state, l): """ Determine whether the instruction addresses of a state are in a list provided by ... """ if not l: # empty list return False for addr in state.block().instruction_addrs: if addr in l: return True return False
def make_commands(trace_executable: str, tracin_filenames: list) -> list: """Create a list of shell command to run trace on the supplied set of tracin :param trace_executable: the name of trace executable :param tracin_filenames: the list of trace input file to be simulated :return: a list of trace she...
def ordered_lst_ele(ident_boud_lst): """ The task of this function is to identify if the elements boundaries list created are in a proper order i.e., to check if the connected elements are present next to each other in the list. If the current element is having connections with the element in successive ...
def remove_duplicates(fresh, existing): """ Checks the order ids from existing orders and returns only new ones from fresh after removing the duplicates """ return list([order for order in fresh if order.get("id") and not existing.get(order.get("id"), None)])
def get_digits(n, reverse=False): """Returns the digits of n as a list, from the lowest power of 10 to the highest. If `reverse` is `True`, returns them in from the highest to the lowest""" digits = [] while n != 0: digits.append(n % 10) n //= 10 if reverse: digits.reverse...
def convert_boolean_list_to_indices(list_of_booleans): """ take a list of boolean values and return the indices of the elements containing True :param list_of_booleans: list sequence of booleans :return: list with integer values list of the values that were True in the input list_of_boo...
def is_number(s): """ Returns True if string is a number.""" try: float(s) return True except ValueError: return False
def search_for_ISM(edge_IDs, transcript_dict): """ Given a list of edges in a query transcript, determine whether it is an incomplete splice match (ISM) of any transcript in the dict. Will also return FSM matches if they're there""" edges = frozenset(edge_IDs) ISM_matches = [transcript_dic...
def replace_space(string): """Replace a space to %20 for url. Parameters ---------- string: A string Returns ------- string: A reformatted string. """ return string.replace(' ', '%20')
def write_txt(w_path, val): """Write a text file from the string input. """ with open(w_path, "w") as output: output.write(val + '\n') return None