content
stringlengths
42
6.51k
def prod(iterable): """ Product of a sequence of numbers. Faster than np.prod for short lists like array shapes, and does not overflow if using Python integers. """ product = 1 for x in iterable: product *= x return product
def _key_id_or_name_n(key, index): """Internal helper function for key id and name transforms. Args: key: A datastore key. index: The depth in the key to return; 0 is root, -1 is leaf. Returns: The id or name of the nth deep sub key in key. """ if not key: return None path = key.to_path() ...
def LR_calc(item1, item2): """ Calculate Likelihood ratio (LR). :param item1: item1 in expression :type item1:float :param item2: item2 in expression :type item2:float :return: LR+ and LR- as float """ try: result = item1 / item2 return result except (ZeroDivisio...
def lerp(position: float, target: float, magnitude: float) -> float: """Linearly interpolates this position value towards a target value, which changes by a maximum of the magnitude value, returning the resulting position. Is a helper function for Vector.lerp. Preconditions: - magnitude >= 0 ...
def countSetBits(n): """Counts the number of bits that are set to 1 in a given integer.""" count = 0 while (n): count += n & 1 n >>= 1 return count
def matrixMulti(A, B): """Multiplica dos matrices, C = A*B """ rowsA, colsA = len(A), len(A[0]) rowsB, colsB = len(B), len(B[0]) if colsA != rowsB: exit('Dimensiones incorrectas') C = [[0 for row in range(colsB)] for col in range(rowsA)] for i in range(rowsA): for j in range(colsB): for k in range(cols...
def abbr(a, b): """ >>> abbr("daBcd", "ABC") True >>> abbr("dBcd", "ABC") False """ n = len(a) m = len(b) dp = [[False for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0] = True for i in range(n): for j in range(m + 1): if dp[i][j]: if j...
def unique_elements_and_occurrences(elements): """ """ unique_elements = {} for element in elements: try: unique_elements[element] = unique_elements.get(element, 0) + 1 except Exception as e: print(e) unique_elements = list(unique_elements.items()) unique...
def gcd(p, q): """Returns the greatest common divisor of p and q >>> gcd(48, 180) 12 """ while q != 0: if p < q: (p,q) = (q,p) (p,q) = (q, p % q) return p
def bool_to_pass_fail(value:bool) -> str: """Converts a boolean True to "Pass" and False to "Fail" Parameters ---------- value : bool A boolean value representing True for Pass and False for Fail Returns ------- str "Pass" or "Fail" """ if value: return "Pa...
def map_opacity(freq: float, freq2opacity: dict) -> float: """Take an input iSNV frequency and return the corresponding opacity level for plotting""" x = int(freq*10) return freq2opacity[x]
def net_in_sol_rad(sol_rad, albedo=0.23): """ Calculate net incoming solar (or shortwave) radiation from gross incoming solar radiation, assuming a grass reference crop. Net incoming solar radiation is the net shortwave radiation resulting from the balance between incoming and reflected solar radia...
def remove_redundant_paths(paths): """ Returns a list of unique paths. """ results = [] for path in paths: redundant = False paths_copy = paths[:] paths_copy.pop(paths.index(path)) for p in paths_copy: if p.startswith(path) and len(p) > len(path): ...
def specialInterpretValue(value,index,*args,**kwargs): """Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and index is not None, look up index within the tuple/list/dict - Else, just return it """ if callable(valu...
def order(A): """Returns the order of the matrix. Args ---- A (compulsory) A matrix. Returns ------- tuple the order of the given matrix in the form (rows, columns). """ return (len(A), len(A[0]))
def delete_till_beginning_of_line(text): """delete till beginning of line""" if text.rfind("\n") == -1: return '' return text[0:text.rfind("\n") + 1]
def convert_to_unicode(input_string): """Convert input string to unicode.""" if isinstance(input_string, bytes): return input_string.decode('utf-8') return input_string
def _json_add_classification_filter(json, classification, equality="equals"): """ Add classification Filter element and return """ limits = 'Classification[{0}:{0}]'.format(classification) if equality == 'max': limits = 'Classification[:{0}]'.format(classification) json['pipeline'].insert(0, { ...
def degree_calc(steps, steptype): """ calculate and returns size of turn in degree , passed number of steps and steptype""" degree_value = { "full": 1.8, "half": 0.9, "1/4": 0.45, "1/8": 0.225, "1/16": 0.1125, "1/32": 0.05625, "1/64": 0.028125, ...
def fibonacciDP(ith): """compute nth Fibonacci using Dynamic Programming Bottom-up""" if ith == 1 or ith == 2: return 1 a, b = 1, 1 i = 2 while i < ith: i += 1 b, a = a+b, b return b
def levenshtein(s1: str, s2: str) -> int: """Calculate the Levenshtein distance between two strings Args: s1: first string s2: second string Returns: Distance between s1 and s2 """ if len(s1) < len(s2): return levenshtein(s2, s1) # len(s1) >= len(s2) if len...
def dinfflowdir(np, input, output1, output2): """ command: dinfflowdir -fel demfel.tif -ang demang.tif -slp demslp.tif, demfile: Pit filled elevation input data, angfile: Dinf flow directions output, slopefile: Dinf slopes output """ dinfflowdir = "mpirun -np {} dinfflowdir -fel {} -ang {} -slp {}".format( ...
def find_language_out_proxy(doc): """Return the language at the higher level 'EuropeanaAggregation'.""" lang = "" try: lang = doc["edm:EuropeanaAggregation"][0]["edm:language"][0] except KeyError: lang = "" except IndexError: lang = "" if lang == "mul": lang = "" ...
def bai_from_bam_file(bam_file): """ Simple helper function to change the file extension of a .bam file to .bai. """ if not bam_file.endswith('.bam'): raise ValueError('{0} must have a .bam extension.'.format(bam_file)) return bam_file[:-3] + 'bai'
def title(s): """Convert string to title case keeping any words already starting with capital letter as is. """ return " ".join([w.title() if w.islower() else w for w in s.split()])
def left_shift(s, times): """left shifting a list """ for i in range(times): s.append(s.pop(0)) return s
def clean_up_line(line): """Removes leading and trailing whitespace and comments from the line. :Parameters: - `line`: the line to be cleaned-up :type line: string :Return: - the cleaned-up string :rtype: string """ hash_position = line.find("#") if hash_position != -1: ...
def ceildiv(a: int, b: int) -> int: """Safe integer ceil function""" return -(-a // b)
def check_string_to_float(s: str) -> bool: """Check if string can be converted to float.""" try: float(s) return True except: return False
def _preprocess(j): """preprocess the file out into nodes ways and relations""" node_storage = {} nodes_reused = {} way_storage = {} ways_reused = {} relation_storage = {} for elem in j["elements"]: # on our first pass, we go through and put all the nodes into storage eid = e...
def get_topic_name(prefix, table, operation, host=None): """Create a topic name. The topic name needs to be synced between the agent and the plugin. The plugin will send a fanout message to all of the listening agents so that the agents in turn can perform their updates accordingly. :param pre...
def intersection_pt(L1, L2): """Returns intersection point coordinates given two lines. """ D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * L2[2] - L1[2] * L2[0] if D != 0: x = Dx / D y = Dy / D return x, y else: return False
def identify_phecode_from_ranged_list(sorted_ranged_list, icd10): """turns icd10 into a set of phecodes from sorted, ranged phecode list""" icd10 = icd10.replace('.', '') phecodes = set() for (low, high, phecode) in sorted_ranged_list: if icd10 < low: continue elif icd10 <= ...
def quoteString(s): """ Quote a string according to the rules for the I{quoted-string} production in RFC 2616 section 2.2. @type s: C{str} @rtype: C{str} """ return '"%s"' % s.replace('\\', '\\\\').replace('"', '\\"')
def check_all_values_equal(iterable) -> bool: """ Check if all elements of an iterable (e.g., list) are equal. :param iterable: iterable to check :return: bool saying if all elements are equal """ iterator = iter(iterable) try: first = next(iterator) except StopIteration: ...
def qstr(s, validate=True): """Return a quoted string after escaping '\' and '"' characters. When validate is set to True (default), the string must consist only of 7-bit ASCII characters excluding NULL, CR, and LF. """ if validate: s.encode('ascii') if '\0' in s or '\r' in s or '\n' in s: raise ValueError...
def normalize_formula(formula): """ Insert ones after elements where the subscript is omitted. Streamlines the process of parsing the formula. Returns a copy of :formula: with ones inserted in it. """ previous_was_number = None previous_index = 0 parts = [] for idx, item in enumerate(formula...
def doesFileFullfillConstraints(fullPath, constraints = []): """ @param constrains := list auf conditions, which a file shoul have in its name or path """ for const in constraints: if const in fullPath: return True
def expand(expanding, variables): """expand the given string using the given variables""" # find right-most start of variable pattern start = expanding.rfind("${") # keep searching while we find variable patterns while start >= 0: # find left-most end of variable pattern (starting at curren...
def wrap_text(text: str, max_length: int, prefix: str): """ Reformat text to a line limit, breaking on spaces :param text: Some text with spaces in it :param max_length: Max line length including the indent :param prefix: Prefix for each line :return: Wrapped text """ rest = text re...
def toggle_collapse(n, is_open): """ collapse the side bar """ if n: return not is_open return is_open
def format_user_service(config, service_type, **kwargs): """Formats a string displayed to the user based on the service type and a substitution context (``user_display`` in the OpenChallSpec). Args: config (dict): The normalized challenge config service_type (string): The service type of the se...
def backend_key_to_query(backend_key): """Convert backend key to queryable dictionary""" n, d, l = backend_key.split('-') return {'number': int(n), 'data_type': d, 'lineage_hash': l}
def real_basename(path): """Python's os.path.basename is not basename.""" if path.rsplit('/', 1)[1] is '': return None return path.rsplit('/', 1)[1]
def is_namedtuple(v) -> bool: """Figuring out if an object is a named tuple is not as trivial as one may expect""" try: return isinstance(v, tuple) and hasattr(v, "_fields") except TypeError: return False
def get_bbox_height(bbox): """ **SUMMARY** (Dev Zone) Get height of the bounding box **PARAMETERS** bbox - Bounding Box represented through 2 points (x1,y1,x2,y2) **RETURNS** height of the bounding box """ return bbox[3] - bbox[1] + 1
def addMatrix(A,B): """Add two matrices""" return [[A[i][j] + B[i][j] for j in range(len(A))] for i in range(len(B))]
def get_all_required_frames(curve_data): """ Returns all keys in a list of dictionaries as a sorted list. """ res = set() for dct in curve_data.values(): for key in tuple(dct.keys()): res.add(int(key)) return sorted(list(res))
def __add_abcd_counts(x, y): """ Adds two tuples. For example. :math:`x + y = (x_a + y_a, x_b + y_b, x_c + y_c, x_d + y_d)` :param x: Tuple (a, b, c, d). :param y: Tuple (a, b, c, d). :return: Tuple (a, b, c, d). """ return x[0] + y[0], x[1] + y[1], x[2] + y[2], x[3] + y[3]
def filter_oauth_params(params): """Removes all non oauth parameters from a dict or a list of params.""" is_oauth = lambda kv: kv[0].startswith("oauth_") if isinstance(params, dict): return list(filter(is_oauth, list(params.items()))) else: return list(filter(is_oauth, params))
def extensions_are_equivalent(ext1, ext2): """Return whether file extensions can be considered as equivalent.""" synonyms = [{"jpg", "jpeg"}] ext1, ext2 = ext1.lower(), ext2.lower() return ext1 == ext2 or any((ext1 in s and ext2 in s) for s in synonyms)
def divides(a, b): """ Return True if a goes into b. >>> divides(3, 6) # Tests! True >> divides(3, 7) False """ return b % a == 0
def replstring(string, i, j, repl): """ Replace everything in string between and including indices i and j with repl >>> replstring("abc", 0, 0, "c") 'cbc' >>> replstring("abc def LOL jkl", 8, 10, "ghi") 'abc def ghi jkl' """ # Convert to list since strings are immutable strlist = li...
def parser_data_broadcast_Descriptor(data,i,length,end): """\ parser_data_broadcast_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "data_broadcast", "contents" : unparsed_descriptor_contents } ...
def herz_me(val): """Return integer value for Hz, translated from (MHz|kHz|Hz).""" result = 0 if isinstance(val, bytes): val = str(val) if val.endswith("MHz"): stripped = val.replace("MHz", "") strip_fl = float(stripped) result = strip_fl * 1000000 elif val.endswith("...
def bit_at_given_position_set_or_unset(n, k): """ Check whether the bit at given position is set or unset :return: if it results to '1' then bit is set, else it results to '0' bit is unset :example: Input : n = 32, k = 5 Output : Set (100000) ...
def make_lock_uri(s3_tmp_uri, emr_job_flow_id, step_num): """Generate the URI to lock the job flow ``emr_job_flow_id``""" return s3_tmp_uri + 'locks/' + emr_job_flow_id + '/' + str(step_num)
def get_leaf_info(lines): """ If there is information about the leaves in the file, retrieve and return it Parameters ---------- lines : [str] file content without comments Returns ------- [str] list with leaf names """ leaves = list(filter(lambda x: x.startswi...
def check_settings_changed(updated, existing): """Since updating the settings requires closing the index, we don't want to do it unless it's really needed. This will check if all the updated settings are already in effect.""" if not isinstance(updated, dict) or not isinstance(existing, dict): re...
def LongestCommonSubsequence(A,B): """Find longest common subsequence of iterables A and B.""" A = list(A) B = list(B) # Fill dictionary lcsLen[i,j] with length of LCS of A[:i] and B[:j] lcsLen = {} for i in range(len(A)+1): for j in range(len(B) + 1): if i == 0 or j == 0: ...
def get_longest_consecutive_sequence(array: list): """given array return longest consecutive sequence length the following algorithm provides the length in O(N) time """ if len(array) < 1: return 0 hashmap = {number: True for number in array} longest_consecutive = 1 # array must have a val...
def _clean_html_a(name, value): """ Clean the 'a' tag for an HTML field. This allows 'title', 'target', and 'href's that point to http or https. """ if name in ('title', 'target'): return True elif name == 'href': return value.startswith('http://') or value.startswith('https://')...
def _custom_remove_char(text_orig, char): """Removes characters from a list of string Inputs: text: String or list that has strings as elements. Transformation will be applied to all strings. char: character(s) to be removed. This can be a string, or a list of strings (if multiple characters need ...
def unescape(string): """Replace some characters to nothing""" string = string.replace('/', '') string = string.replace('->', '') string = string.replace('(', '') string = string.replace(')', '') return string
def crc16(data): """ Generate the crc-16 value for a byte string. >>> from binascii import unhexlify >>> c = crc16(unhexlify(b'8792ebfe26cc130030c20011c89f')) >>> hex(~c & 0xffff) '0xc823' >>> v = crc16(unhexlify(b'8792ebfe26cc130030c20011c89f23c8')) >>> hex(v) '0xf0b8' """ ...
def build_speaker_index(hyp): """Build the index for the speakers. Args: hyp: a list of tuples, where each tuple is (speaker, start, end) of type (string, float, float) Returns: a dict from speaker to integer """ speaker_set = sorted({element[0] for element in hyp}) ...
def cast(value): """Returns int, bool or str""" try: value = int(value) except ValueError: if value.lower().strip() in ["true", "t", "1", "yes"]: value = True elif value.lower().strip() in ["false", "f", "no", "0"]: value = False return value
def get_printable_size(byte_size): """ A bit is the smallest unit, it's either 0 or 1 1 byte = 1 octet = 8 bits 1 kB = 1 kilobyte = 1000 bytes = 10^3 bytes 1 KiB = 1 kibibyte = 1024 bytes = 2^10 bytes 1 KB = 1 kibibyte OR kilobyte ~= 1024 bytes ~= 2^10 bytes (it usually means 1024 bytes but some...
def partition_G(nodelist, second_smallest_eigval_vec): """Returns a partition of the graph G basied on second smallest eigenvector of the normalized Laplacian matrix nL. Parameters ---------- nodelist : collection A collection of nodes in `G`. second_smallest_eigval_vec : array ...
def normalize_whitespace(s): """ Removes leading and ending whitespace from a string. """ try: return u' '.join(s.split()) except AttributeError: return s
def get_color_list(length, start, middle, end): """ Creates a color list based on the indicies given Expected Complexity: O(log(n)) (time) and O(1) (space) :param length: Integer for the size of the sublist :param start: Integer for the starting index in the list :param middle: Integer for the ...
def _int_version(version_string): """Get int version string""" major = int(version_string.split(".")[0]) return major
def is_subsequence(a, b): """ is subsequence :param a: :param b: :return: """ b = iter(b) print(b) gen = (i for i in a) print(gen) for i in gen: print(i) gen = ((i in b) for i in a) print(gen) for i in gen: print(i) return all(i in b for i...
def fsv(pcset): """Finds smallest values of pcset and returns their index numbers.""" l = [] for x in range(len(pcset)): if len(l) == 0 or pcset[x] < pcset[l[0]]: l = [x] elif pcset[x] == pcset[l[0]]: l.append(x) return l
def return_stack_elem(index=None): """Symbolic accessor for the return stack""" return 'R', index
def int2name(i): """ Convert integer to Excel column name. """ div = i + 1 name = "" while div > 0: mod = (div - 1) % 26 name = chr(65 + mod) + name div = (div - mod) // 26 return name
def create_udp_port(byte_array): """ Creates the UDP port out of the byte array :param byte_array: The byte array we want to get the port number :return: Integer of the port number """ first_two_bytes = [int(no) for no in byte_array] first_two_bytes = first_two_bytes[:2] return int.from_...
def make_random_access(iter): """ Return a list or tuple containing the elements of iter. If iter is already a list or tuple, it returns iter. """ if isinstance(iter, list) or isinstance(iter, tuple): return iter return list(iter)
def c_flag(opt, test_not=False): """ convert a test parameter into t if true for the Fortran build system """ if test_not: if opt: return "FALSE" else: return "TRUE" else: if opt: return "TRUE" else: return "FALSE"
def is_float(some_str): """ Return True, if the given string represents a float value. """ try: float(some_str) return True except ValueError: return False
def ResetStNum(N=0): """Reset the state numbering counter. """ global NXTSTATENUM NXTSTATENUM = N return NXTSTATENUM
def get_filetype(filename): """ Gets the filetype of an object based on the extension in its filename Args: filename (str): The name of the file Returns: str: The filetype of the file """ # If the filename isn't named according to good practice, # this will return nonsense -...
def remove_stopwords(input, stopwordfile): """french_stopwords = stopwords.words('french') cleaned_stopwords = [] cleaned_stopwords.append("les") for stopword in french_stopwords: cleaned_stopwords.append(remove_diacritic(stopword))""" filtered_text = "" """for word in input.split(): ...
def sequence_stringify (iterable, highlight = lambda t: False, stringify = str): """ Print and join all elements of <iterable>, highlighting those matched by <highlight : obj -> bool> """ def formatting (data): return ("[{}]" if highlight (data) else "{}").format (stringify (data)) return " ".join (...
def clean_triples(properties): """Convert triples to just relation + tail entity.""" cleaned = [] for triple in properties: if triple[1].startswith("i/P") and triple[0].startswith("i/Q"): if "?" not in triple[1] and "?" not in triple[0]: cleaned.append((triple[1], triple[0])) continue ...
def _take_nearest_pair(values, target): """Given a sorted, monotonic list of values and a target value, returns the closest two pairs of numbers in the list to the given target. The first being the closest number less than the target, the second being the closest number greater than the target. ...
def _split_input_slice(batch_size, work_load_list): """Get input slice from the input shape. Parameters ---------- batch_size : int The number of samples in a mini-batch. work_load_list : list of float or int, optional The list of work load for different devices, in the same...
def effic_cutoff(zone_type): """Returns the HSPF cutoff for determinig whether a heat pump is qualified as efficient or not. 'zone_type' is 'Single' for 'Multi', which affects the cutoff. """ return 12.5 if zone_type=='Single' else 11.0
def get_failure_array(pattern): """Calculates the new index we should go to if we fail a comparison Parameters ---------- pattern: str The pattern to be identified Returns ------- list List of indices for the failure table """ failure = [0] i = 0 j = 1 ...
def get_payment_mode(record): """Return payment mode.""" budget_code = record.get("budget_code") if not budget_code: return 'INDIVIDUAL_PAYMENT' elif budget_code and budget_code.lower() == "cash": return 'INDIVIDUAL_PAYMENT' else: return 'BUDGET_CODE'
def confopt_float(confstr, default=None): """Check and return a floating point number.""" ret = default try: ret = float(confstr) except: # catches the float(None) problem pass return ret
def min_max_norm(x, minimum, maximum) -> float: """Rescales a variable to a range between 0 and 1 using the rescaling method (also known as min-max normalization). Args: x (number): Variable that will be rescaled. minimum (number): Minimum value from the dataset. maximum (number): Maxim...
def parse_window(window): """ Utility function to use a path to index a :class:`paprika.restraints.DAT_restraint` instance. Parameters ---------- window : str A string representation of a particular simulation window Returns ------- window_number : int The window number...
def _create_ha_id(name, channel, param, count): """Generate a unique entity id.""" # HMDevice is a simple device if count == 1 and param is None: return name # Has multiple elements/channels if count > 1 and param is None: return "{} {}".format(name, channel) # With multiple pa...
def read_str_num(string, sep = None): """Returns a list of floats pulled from a string. Delimiter is optional; if not specified, uses whitespace. Parameters ---------- string : str String to be parsed. sep : str, optional Delimiter (default is None, which means consecut...
def zip_dicts(*dicts): """Given a list of dictionaries, zip their corresponding values and return the resulting dictionary""" return {key: [dictionary[key] for dictionary in dicts] for key in dicts[0].keys()}
def plasma_freq(n_e): """ Given an electron density parameter (n_e), compute the plasma frequency. """ eps0 = 8.8542E-12 #[A*s/(V*m)] Permittivity e = 1.602E-19 #[C] Elementary charge me = 9.109E-31 #[kg] Electron rest mass omega_p...
def _compare_trigrams(trig1: set, trig2: set) -> float: """ Checks how many trigrams from the first set are present in the second and returns that value divided by the length of the second set. """ count = 0 for i in trig1: if i in trig2: count += 1 return count / len(tri...
def distance(x: int, y: int, a: int, b: int) -> float: """Distance between two points""" return ((x - a) ** 2 + (y - b) ** 2) ** .5
def read_line(filename): """help function to read a single line from a file. returns none""" try: f = open(filename) line = f.readline().strip() f.close() return line except IOError: return None