content
stringlengths
42
6.51k
def time_in_range(start, end, day_start, day_end): """Return true if event time range overlaps day range""" if (start <= day_start and end >= day_end): return True elif (start >= day_start and start <= day_end): return True elif (end >= day_start and end <= day_end): return True return False
def _one_hot(index, size): """returns one-hot vector with given size and value 1 at given index """ vec = [0 for _ in range(size)] vec[int(index)] = 1 return vec
def disambiguate(names, mark='1'): """ Given a list of strings ``names``, return a new list of names where repeated names have been disambiguated by repeatedly appending the given mark. EXAMPLE:: >>> disambiguate(['sing', 'song', 'sing', 'sing']) ['sing', 'song', 'sing1', 'sing11'] """ names_seen = set() new_names = [] for name in names: new_name = name while new_name in names_seen: new_name += mark new_names.append(new_name) names_seen.add(new_name) return new_names
def binary_search(array, k, pos): # O(logN) """ Apply binary search to find either a "start" or "end" of a particular number >>> binary_search([2, 3, 3, 3, 4], 3, 'start') 1 >>> binary_search([2, 3, 3, 3, 4], 3, 'end') 3 >>> binary_search([2, 3, 3, 3, 4], 5, 'start') -1 >>> binary_search([2, 3, 3, 3, 4], 5, 'end') -1 >>> binary_search([2, 3, 3, 3, 5], 4, 'start') -1 """ length = len(array) # O(1) i = 0 # O(1) j = length - 1 # O(1) if array[i] > k or array[j] < k: # O(1) return -1 # O(1) while i <= j: # O(logN) mid = ((j - i) // 2) + i # O(1) if i == j and array[mid] != k: # O(1) return -1 # O(1) if array[mid] > k: # O(1) j = mid - 1 # O(1) elif array[mid] < k: # O(1) i = mid + 1 # O(1) elif array[mid] == k: # O(1) if pos == 'start': # O(1) if mid == i or array[mid - 1] != k: # O(1) return mid # O(1) j = mid - 1 # O(1) elif pos == 'end': # O(1) if mid == j or array[mid + 1] != k: # O(1) return mid # O(1) i = mid + 1 # O(1)
def stringify_dict(d): """create a pretty version of arguments for printing""" if 'self' in d: del d['self'] s = 'Arguments:\n' for k in d: if not isinstance(d[k], str): d[k] = str(d[k]) s = s + '%s: %s\n' % (k, d[k]) return(s)
def list_all(seq): """Create a list from the sequence then evaluate all the entries using all(). This differs from the built-in all() which will short circuit on the first False. """ return all(list(seq))
def number_of_divisors(n) -> int: """ Returns the number of all non-trivial divisors """ n = abs(n) i = 2 NumberOfDivisors = 0 while i < n: if n % i == 0: NumberOfDivisors += 1 i += 1 return NumberOfDivisors
def _quote_if_str(val): """ Helper to quote a string. """ if isinstance(val, str): return f"'{val}'" return val
def fromDD(s): """Takes a string of 2 digits and returns a number with up to 2 digits""" if len(s) <= 2: return int(s) else: return int(s[0:2])
def avg(stats: list) -> float: """ Find the average of a list. Given a list of numbers, calculate the average of all values in the list. If the list is empty, default to 0.0. Parameters ---------- input_list : list A ``list`` of ``floats`` to find an average of. Returns ------- float Returns a ``float`` of the average value of the list. """ if len(stats) > 0: return sum(stats) / len(stats) else: return 0.0
def tablenamify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata value = str(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8').strip().lower() value = re.sub(r'[^\w\s\-\.]', '', value) value = re.sub(r'[-\s]+', '_', value) return value
def get_metric_names(data: dict) -> dict: """Retrieves metric names from returned data.""" row = {} for index, col in enumerate(data['result']['definition']['metrics']): row[index] = col["name"] return row
def name_test(item): """ used for pytest verbose output """ return f"{item['params']['peer_link']}"
def is_probably_number(value: str) -> bool: """ Determine whether value is probably a numerical element. """ # value is simply a numerical value probably_number = value.isdigit() if not probably_number: s = value.split(' ') if len(s) is 2: # value is made up of 2 components; # consider it a number if either of the components is a numerical value probably_number = True if s[0].isdigit() else s[1].isdigit() return probably_number
def create_description(name, args=None): """Create description from name and args. Parameters ---------- name : str Name of the experiment. args : None or argparse.Namespace Information of the experiment. Returns ------- description : str Entire description of the experiment. """ description = f"experiment_name: {name} \n" if args is not None: for k, v in vars(args).items(): description += f"{k:<32}: {v} \n" return description
def listToString(my_list): """ A function to convert a list to a string """ # initialize an empty string str1 = "" # traverse in the string for element in my_list: str1 += element # return string return str1
def clear_url(url): """ Remove domain and protocol from url """ if url.startswith('http'): return '/' + url.split('/', 3)[-1] return url
def find_str(s,l): """ Find index of occurence of string s in list l """ idx = 0 while idx < l.__len__() and l[idx] != s: idx = idx + 1 return idx
def reverse_complement(x): """Construct reverse complement of string. """ rc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} x = x.upper() return ''.join(rc[b] for b in x[::-1])
def getitem_helper(obj, elem_getter, length, idx): """Helper function to implement a pythonic getitem function. Parameters ---------- obj: object The original object elem_getter : function A simple function that takes index and return a single element. length : int The size of the array idx : int or slice The argument passed to getitem Returns ------- result : object The result of getitem """ if isinstance(idx, slice): start = idx.start if idx.start is not None else 0 stop = idx.stop if idx.stop is not None else length step = idx.step if idx.step is not None else 1 if start < 0: start += length if stop < 0: stop += length return [elem_getter(obj, i) for i in range(start, stop, step)] if idx < -length or idx >= length: raise IndexError("Index out of range. size: {}, got index {}" .format(length, idx)) if idx < 0: idx += length return elem_getter(obj, idx)
def configurePostfix(post): """configurePostfix(post) Configure a string that will be appended onto the name of the spectrum and other result attributes.""" return {'Postfix' : post }
def is_vm(obj): """ Checks if object is a vim.VirtualMachine. :param obj: The object to check :return: If the object is a VM :rtype: bool """ return hasattr(obj, "summary")
def set_output(kwargs, job, map): """Set the __no_output__ flag""" if 'return_preds' in kwargs: if kwargs['return_preds']: __no_output__ = False else: __no_output__ = True else: __no_output__ = job == 'fit' kwargs['return_preds'] = job != 'fit' if not map: # Need to ensure outputs always generated for stacking __no_output__ = False return __no_output__
def str_width(unicode_text): """calc string width, support cjk characters.""" from unicodedata import east_asian_width return sum(1+(east_asian_width(c) in "WF") for c in unicode_text)
def fetch_value(data: dict, key: str, default: str=''): """ Function to get a value from a key in a dict. Supports getting values from an array index. Args: data (dict): A dictionary. key (str): Key for which to get the value. Can have an index attached as [index]. default (str, optional): Default return value if key is empty or doesn't exist. Defaults to ''. Returns: [type]: Value of key in dictionary if it exists, otherwise the provided default value. Raises: IndexError: If provided index is out of bounds. """ value = default if data and key: try: start = key.index('[') end = key.index(']') value = data.get(key[:start], default)[int(key[start+1:end])] except ValueError: value = data.get(key, default) except IndexError as e: raise IndexError(f'index error using key -> {key}') from e except AttributeError: pass return value if value else default
def get_text_content(node, xpath=""): """ return the text from a specific node Parameters ---------- node : lxml node xpath : xpath.search Returns ------- str None if that xpath is not found in the node """ if node is None: return None if xpath: nodes = node.xpath(xpath) else: nodes = [node] if nodes: result = nodes[0].text if result is None: return "" else: return result else: return ""
def nvdot(nv, nb0, nbs, e_effective, F, alpha, B, pv): """ Calculates the rate of change in minutes for the total phage population, nv. Note that this assumes CRISPR immunity is only present for exactly matching clones. Inputs: nv : total phage population size at time t nb0 : number of bacteria without spacers at time t nbs : number of bacteria with spacers at time t e_effective: average overlap between bac and phage populations F : chemostat flow rate alpha : phage adsorption rate B : phage burst size pv : probability of phage infection success without CRISPR """ pva = pv*(1-e_effective) return -(F + alpha*(nb0+nbs))*nv + alpha*B*pv*nb0*nv + alpha*B*nbs*nv*pva
def arch2abi(arch): """Map arch to abi""" # pylint: disable=too-many-return-statements if "rv32e" in arch: if "d" in arch: return "ilp32ed" if "f" in arch: return "ilp32ef" return "ilp32e" if "rv32i" in arch: if "d" in arch: return "ilp32d" if "f" in arch: return "ilp32f" return "ilp32" if "rv64i" in arch: if "d" in arch: return "lp64d" if "f" in arch: return "lp64f" return "lp64" raise Exception("Unknown arch %s" % arch)
def license_filter(lic): """Used from the template to produce the license logo""" lic_abbr,lic_name=lic # something like BY-SA, CC BY-SA 4.0 unported if lic_abbr == "GNU": logo_file = "gpl" elif lic_name.startswith("CC0"): logo_file = "cc-zero" elif lic_name.startswith("CC"): logo_file = lic_abbr.lower() elif lic == "LGPLLR": logo_file = "LGPLLR" else: logo_file = None if logo_file: return '<span class="hint--top hint--info" data-hint="%s"><img class="license" src="logos/%s.svg" /></span>'%(lic_name,logo_file) else: return '<span class="hint--top hint--info" data-hint="%s">?</span>'%(lic_name)
def header(text): """Format text as a wikitext markup header""" if '|' not in text: return f"! {text}\n" else: return f"!{text[1:]}"
def is_in_range(a, low, high): """ Return True if 'a' in 'low' <= a >= 'high' """ return (a >= low and a <= high)
def dynamic_param_logic(text): """ validates parameter values for dynamic completion """ is_param = False started_param = False prefix = "" param = "" txtspt = text.split() if txtspt: param = txtspt[-1] if param.startswith("-"): is_param = True elif len(txtspt) > 2 and txtspt[-2]\ and txtspt[-2].startswith('-'): is_param = True param = txtspt[-2] started_param = True prefix = txtspt[-1] return is_param, started_param, prefix, param
def escape_xpath(string: str) -> str: """ Xpath string literals don't have escape sequences for ' and " So to escape them, we have to use the xpath concat() function. See https://stackoverflow.com/a/6938681 This function returns the *enclosing quotes*, so it must be used without them. For example: dom.xpath(f"//title[text() = {se.easy_xml.escape_xpath(title)}]") """ if "'" not in string: return f"'{string}'" if '"' not in string: return f'"{string}"' # Can't use f-strings here because f-strings can't contain \ escapes return "concat('%s')" % string.replace("'", "',\"'\",'")
def percentage_to_int(value): """ Scale values from 0-100 to 0-255 """ return round((255.0 / 100.0) * float(value))
def doGroup(indata, group_key_func, group_data_func): """Group the indata based on the keys that satisfy group_key_func (applied to the value) Return a dict of groups summarized by group_data_func Each group returned by group_data_func must be a dictionary, possibly similar to the original value of the indata elements Args: indata: group_key_func: group_data_func: Returns: dict of groups summarized by group_data_func """ gdata = {} for k, inel in indata.items(): gkey = group_key_func(inel) if gkey in gdata: gdata[gkey].append(inel) else: gdata[gkey] = [inel] outdata = {} for k in gdata: # value is a summary of the values outdata[k] = group_data_func(gdata[k]) return outdata
def make_filename_by_table_var(table, variable, prefix=''): """Generate a filename (without extention) using table and variable names.""" if prefix != '': prefix += '_' return prefix + variable + '_' + table
def make_suffix_array(s): """ Given T return suffix array SA(T). We use Python's sorted function here for simplicity, but we can do better. """ satups = sorted([(s[i:], i) for i in range(len(s))]) # Extract and return just the offsets return list(map(lambda x: x[1], satups))
def quadraticPointAtT(pt1, pt2, pt3, t): """Finds the point at time `t` on a quadratic curve. Args: pt1, pt2, pt3: Coordinates of the curve as 2D tuples. t: The time along the curve. Returns: A 2D tuple with the coordinates of the point. """ x = (1 - t) * (1 - t) * pt1[0] + 2 * (1 - t) * t * pt2[0] + t * t * pt3[0] y = (1 - t) * (1 - t) * pt1[1] + 2 * (1 - t) * t * pt2[1] + t * t * pt3[1] return (x, y)
def pad_input_ids_msmarco(input_ids, max_length, pad_on_left=False, pad_token=0): """An original padding function that is used only for MS MARCO data.""" padding_length = max_length - len(input_ids) padding_id = [pad_token] * padding_length if padding_length <= 0: input_ids = input_ids[:max_length] else: if pad_on_left: input_ids = padding_id + input_ids else: input_ids = input_ids + padding_id return input_ids
def bonferroni_correction(significance, numtests): """ Calculates the standard Bonferroni correction. This is used for reducing the "local" significance for > 1 statistical hypothesis test to guarantee maintaining a "global" significance (i.e., a family-wise error rate) of `significance`. Parameters ---------- significance : float Significance of each individual test. numtests : int The number of hypothesis tests performed. Returns ------- The Boferroni-corrected local significance, given by `significance` / `numtests`. """ local_significance = significance / numtests return local_significance
def get_cvss_score(vuln, vulners_api): """Get CVSS score if available, otherwise get Vulners AI score""" cvss = vuln["cvss"]["score"] if cvss == 0.0: try: return vulners_api.aiScore(vuln["description"])[0] except: return 0.0 else: return cvss
def odd(num): """ Check if a number is odd :type num: number :param num: The number to check. >>> odd(3) True """ return num % 2 != 0
def tree_search(states, goal_reached, get_successors, combine_states): """ Given some initial states, explore a state space until reaching the goal. `states` should be a list of initial states (which can be anything). `goal_reached` should be a predicate, where `goal_reached(state)` returns `True` when `state` is the goal state. `get_successors` should take a state as input and return a list of that state's successor states. `combine_states` should take two lists of states as input--the current states and a list of new states--and return a combined list of states. When the goal is reached, the goal state is returned. """ # If there are no more states to explore, we have failed. if not states: return None if goal_reached(states[0]): return states[0] # Get the states that follow the first current state and combine them # with the other current states. successors = get_successors(states[0]) next = combine_states(successors, states[1:]) # Recursively search from the new list of current states. return tree_search(next, goal_reached, get_successors, combine_states)
def normalize(position): """ Accepts `position` of arbitrary precision and returns the block containing that position. Parameters ---------- position : tuple of len 3 Returns ------- block_position : tuple of ints of len 3 """ x, y, z = position x, y, z = (int(round(x)), int(round(y)), int(round(z))) return (x, y, z)
def as_dicts(results): """Convert execution results to a list of tuples of dicts for better comparison.""" return [result.to_dict(dict_class=dict) for result in results]
def _to_date_in_588(date_str): """ Convert date in the format ala 03.02.2017 to 3.2.2017. Viz #100 for details. """ try: date_tokens = (int(x) for x in date_str.split(".")) except ValueError: return date_str return ".".join(str(x) for x in date_tokens)
def content_priority(experiment, obj): """ Return a priority to assign to ``obj`` for an experiment. Higher priority objects are shown first. """ score = 0 if hasattr(obj, 'photo'): photo = obj.photo score += photo.publishable_score() if photo.synthetic and photo.intrinsic_synthetic is not None: score += 10000000 if photo.light_stack: score += 1000000 if not photo.num_intrinsic_points: score += photo.num_intrinsic_points return score
def falling(n, k): """Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4 >>> falling(4, 10) # 4 * 3 * 2 * 1 # Only n times!! 24 """ if (n > k): total, stop = 1, n-k while n > stop: total, n = total*n, n-1 else: total = 1 while (n >1): total, n=total*n, n-1 return total
def unpackHexStrings(hexRow): """Unpacks a row of binary strings to a list of floats""" return [float.fromhex(ss) for ss in hexRow.split() if ss != ""]
def degree_to_order(degree): """Compute the order given the degree of a B-spline.""" return int(degree) + 1
def merge(a, b, *, replace=None): """ Merges dicts and lists from the configuration structure """ if isinstance(a, dict) and isinstance(b, dict): if not replace: replace = set() res = {} for key in set(a).union(b): if key not in a: res[key] = b[key] elif key not in b: res[key] = a[key] elif key in replace: res[key] = b[key] else: res[key] = merge(a[key], b[key], replace=replace) return res if isinstance(a, list) and isinstance(b, list): return a + b if isinstance(a, set) and isinstance(b, set): return a.union(b) return b
def split_content_header_data( content ): """ Splits content into its header and data components. :param content: The content to split. :returns: Tuple of ( header, data ). :raises RuntimeError: If the data could not be split. """ split_pattern = '*** The recorded data ***' try: split = content.index( split_pattern ) except ValueError as err: # could not find split string raise RuntimeError( 'Could not split content.' ) return ( content[ :split ], content[ split + len( split_pattern ): ] )
def isint(x): """Determine if provided object is convertible to an int Args: x: object Returns: bool """ if x is None: return False try: int(float(x)) return True except: return False
def get_action_mapping(n, exclude_self=True): """In a matrix view, this a mapping from 1d-index to 2d-coordinate.""" mapping = [ (i, j) for i in range(n) for j in range(n) if (i != j or not exclude_self) ] return mapping
def test_list(l): """ Return true if object is a list """ return isinstance(l, list)
def convert_move_to_action(move_str: str): """ :param move_str: A1 -> 0, H8 -> 63 :return: """ if move_str[:2].lower() == "pa": return None pos = move_str.lower() x = ord(pos[0]) - ord("a") y = int(pos[1]) - 1 return y * 8 + x
def set_haplotypes(curr_coverage): """Creates a list to manage counting haplotypes for subplots """ hps = sorted(curr_coverage.keys(), reverse=True) #if there are multiple haplotypes, must have 0,1,2 if len(hps) > 1 or (len(hps) == 1 and hps[0] != 0): if 0 not in hps: hps.append(0) if 1 not in hps: hps.append(1) if 2 not in hps: hps.append(2) elif 0 not in hps: hps.append(0) hps.sort(reverse=True) return hps
def redshifts_to_frequencies(z): """The cosmological redshift (of signal) associated with each frequency""" return 1420e6 / (z + 1)
def utm_from_lon(lon): """ utm_from_lon - UTM zone for a longitude Not right for some polar regions (Norway, Svalbard, Antartica) :param float lon: longitude :return: UTM zone number :rtype: int """ from math import floor return floor((lon + 180) / 6) + 1
def hinted_tuple_hook(obj): """ Decoder for specific object of json files, for preserving the type of the object. It's used with the json.load function. """ if '__tuple__' in obj: return tuple(obj['items']) else: return obj
def linspace(start, stop, num, decimals=18): """ Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value :type stop: float :param num: number of samples to generate :type num: int :param decimals: number of significands :type decimals: int :return: a list of equally spaced numbers :rtype: list """ start = float(start) stop = float(stop) if abs(start - stop) <= 10e-8: return [start] num = int(num) if num > 1: div = num - 1 delta = stop - start return [float(("{:." + str(decimals) + "f}").format((start + (float(x) * float(delta) / float(div))))) for x in range(num)] return [float(("{:." + str(decimals) + "f}").format(start))]
def exclude(list, exclusions): """New list >>> exclude(['a', 'b', 'c'], ['b']) ['a', 'c'] """ included = [] for item in list: if not item in exclusions: included.append(item) return included
def flatten(d): """ This flattens a nested dictionary. Args: d (dict|list): The object to flatten. Returns: flat_d (dict): The flattened object. """ def recurse(value, parent_key=""): if isinstance(value, list): for i in range(len(value)): recurse(value[i], f'{parent_key}.{str(i)}' if parent_key else str(i)) elif isinstance(value, dict): for k, v in value.items(): recurse(v, f'{parent_key}.{k}' if parent_key else k) else: obj[parent_key] = value obj = {} recurse(d) return obj
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. From Django's "django/template/defaultfilters.py". """ for c in r'[]/\;,><&*:%=+@!#^\'()$| ?^': value = value.replace(c,'') return value
def is_valid_ecl(eye_color): """Checks for valid Eye Color.""" if eye_color in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']: return True else: return False
def mayan_long_count_date(baktun, katun, tun, uinal, kin): """Return a long count Mayan date data structure.""" return [baktun, katun, tun, uinal, kin]
def bittest(val, n): """ Return the n^th least significant bit of val. """ return (val >> n) & 1
def get_tile_index(rank: int, total_ranks: int) -> int: """ Returns the zero-indexed tile number, given a rank and total number of ranks. """ if total_ranks % 6 != 0: raise ValueError(f"total_ranks {total_ranks} is not evenly divisible by 6") ranks_per_tile = total_ranks // 6 return rank // ranks_per_tile
def factors_singles(num): """ (int) -> list Builds a list of factors for a positive integer <num>. Returns the list """ return [x for x in range(1, num + 1) if num % x == 0]
def str_to_bool(s: str): """Return a boolean for the given string, follows the same semantics systemd does.""" if s.lower() in ('1', 'yes', 'true', 'on'): return True elif s.lower() in ('0', 'no', 'false', 'off'): return False else: raise NotImplementedError(f"Unknown boolean value from string: {s}")
def zero_fill(value: bytearray) -> bytearray: """ Zeroing byte objects. Args: value: The byte object that you want to reset. Returns: Reset value. """ result = b'' if isinstance(value, (bytes, bytearray)): result = b'/x00' * len(value) result = bytearray(result) return result
def get_common_gn_args(is_zircon): """Retrieve common GN args shared by several commands in this script. Args: is_zircon: True iff dealing with the Zircon build output directory. Returns: A list of GN command-line arguments (to be used after "gn <command>"). """ if is_zircon: return [ "out/default.zircon", "--root=zircon", "--all-toolchains", "//:instrumented-ulib-redirect.asan(//public/gn/toolchain:user-arm64-clang)", "//:instrumented-ulib-redirect.asan(//public/gn/toolchain:user-x64-clang)", ] else: return ["out/default"]
def _resolve_role(current_user, profile): """What is the role of the given user for the given profile.""" if current_user: if profile.user == current_user: return "OWNER" elif current_user.is_authenticated: return "ADMIN" else: return "ANONYMOUS" else: return "SYSTEM"
def is_number(string): """ Return whether or not a string is a number """ if string.startswith("0x"): return all(s.lower() in "0123456789abcdef" for s in string[2:]) if string.startswith("0b"): return all(s in "01" for s in string[2:]) else: return string.lstrip("-").replace(".", "", 1).isdigit()
def words_frequency(item): """Convert the partitioned data for a word to a tuple containing the word and the number of occurances. """ word, occurances = item return (word, sum(occurances))
def is_misc(_item): """item is report, thesis or document :param _item: Zotero library item :type _item: dict :returns: Bool """ return _item["data"]["itemType"] in ["thesis", "report", "document"]
def text_escape(v: str) -> str: """ Escape str-like data for postgres' TEXT format. This does all basic TEXT escaping. For nested types as of hstore or in arrays, array_escape must be applied on top. """ return (v.replace('\\', '\\\\') .replace('\b', '\\b').replace('\f', '\\f').replace('\n', '\\n') .replace('\r', '\\r').replace('\t', '\\t').replace('\v', '\\v'))
def parse_value(val: bytes): """Parse value from IMAP response :param val: :return: """ if val in (b'NIL', b'nil') or not val: return None if val.isdigit(): return int(val) return val
def level_to_color(tags): """ map django.contrib.messages level to bootstraps color code """ level_map = { 'debug': 'dark', 'info': 'info', 'success': 'success', 'warning': 'warning', 'error': 'danger' } return level_map[tags]
def one(item): """ Return the first element from the iterable, but raise an exception if elements remain in the iterable after the first. >>> one(['val']) 'val' >>> one(['val', 'other']) Traceback (most recent call last): ... ValueError: ...values to unpack... >>> one([]) Traceback (most recent call last): ... ValueError: ...values to unpack... >>> numbers = itertools.count() >>> one(numbers) Traceback (most recent call last): ... ValueError: ...values to unpack... >>> next(numbers) 2 """ (result,) = item return result
def ensure_str(obj): """Ensure `obj` is a str object (or None).""" return obj if obj is None else str(obj)
def dist(p1, p2): """Return Manhattan distance between the given points.""" return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def getDistance(posn1, posn2): """Helper for getSeeds that calculates the cartesian distance between two tuple points.""" distX = (posn1[0] - posn2[0]) ** 2 distY = (posn1[1] - posn2[1]) ** 2 return (distX + distY) ** 0.5
def convert_uuid(*args, **kwargs): """ Handle converter type "uuid" :param args: :param kwargs: :return: return schema dict """ schema = { 'type': 'string', 'format': 'uuid', } return schema
def get_oil_price(hp): """Provide oil cost per km from horsepower Arg: hp (int): horsepower of tugs Return: (float): oil price ($/km) """ hp_price = { 1800: 134.1075498270909, 2400: 185.0696699493183, 3200: 257.887743955886, 3300: 267.3812284262817, 3400: 276.9616518343608, 3500: 286.6290141801232, 3600: 296.3833154635688, 4000: 336.2699099741844, 4200: 356.734840855592, 4400: 377.5475274877326, 4500: 388.0842792103279, 5200: 464.2758315236272, 6400: 604.8009600994644, } return hp_price[hp]
def parse_resolution(res: str): """ Parse a resolution string. If the y value is zero, the x value is the number to scale the image with. """ # Check what type of input we're parsing if res.count("x") == 1: # Try parsing the numbers in the resolution x, y = res.split("x") try: x = int(x) y = int(y) except ValueError as e: raise AssertionError("**Width or height are not integers.**") from e # Assign a maximum and minimum size assert 1 <= x <= 3000 and 1 <= y <= 3000, "**Width and height must be between 1 and 3000.**" return x, y if res.startswith("*"): try: scale = float(res[1:]) except ValueError as e: raise AssertionError(rf"**Characters following \* must be a number, not `{res[1:]}`**") from e # Make sure the scale isn't less than 0. Whatever uses this argument will have to manually check for max size assert scale > 0, "**Scale must be greater than 0.**" return scale, 0 return None
def extra_year_bits(year=0x86): """ practice getting some extra bits out of the year byte >>> extra_year_bits( ) [1] >>> extra_year_bits(0x06) [0] >>> extra_year_bits(0x86) [1] >>> extra_year_bits(0x46) [0] >>> extra_year_bits(0x26) [0] >>> extra_year_bits(0x16) [0] """ # year = year[0] masks = [ ( 0x80, 7) ] nibbles = [ ] for mask, shift in masks: nibbles.append( ( (year & mask) >> shift ) ) return nibbles
def check_edge(t, b, nodes): """ t: tuple representing an edge b: origin node nodes: set of nodes already visited if we can get to a new node from `b` following `t` then return that node, else return None """ if t[0] == b: if t[1] not in nodes: return t[1] elif t[1] == b: if t[0] not in nodes: return t[0] return None
def modular_multiply(A, B, C): """Finds `(A * B) mod C` This is equivalent to: `(A mod C * B mod C) mod C` https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/modular-multiplication https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-quotient-remainder-theorem """ a_mod_c = A % C b_mod_c = B % C result = (a_mod_c * b_mod_c) % C return result
def list_latex2str(x): """Dataframe's map function Replaces the latex of the custom dataset to ground truth format. Args: x (list) : latex string to convert Returns: latex of ground truth format(str) """ return ' '.join(x)
def check_contain_chinese(check_str): """Check if the path name and file name user input contain Chinese character. :param check_str: string to be checked. """ for ch in check_str: if u'\u4e00' <= ch <= u'\u9fff': return True return False
def pagify(text: str, delim="\n", *, shorten_by=0, page_length=2000): """ Chunk text into manageable chunks. This does not respect code blocks or special formatting. """ list_of_chunks = [] chunk_length = page_length - shorten_by deliminator_test = text.rfind(delim) if deliminator_test < 0: # delim isn't in the text as rfind returns -1 delim = "" while len(text) > chunk_length: line_length = text[:chunk_length].rfind(delim) list_of_chunks.append(text[:line_length]) text = text[line_length:].lstrip(delim) list_of_chunks.append(text) return list_of_chunks
def cosine_similarity(str_a, str_b): """ Calculate cosine similarity Returns: cosine score """ set1 = set(str_a.decode('utf8')) set2 = set(str_b.decode('utf8')) norm1 = len(set1) ** (1. / 2) norm2 = len(set2) ** (1. / 2) return len(set1 & set2) / (norm1 * norm2)
def cired_re(b4, b5, b8, a=0.7): """ Red and Red-edge Modified Chlorophyll Index (Xie et al. 2018). .. math:: CIREDRE = (b8 / (a * b4 + (1 - a) * b5)) - 1 :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-edge 1. :type b5: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :param a: parameter. :type a: float :returns CIREDRE: Index value .. Tip:: Xie, Q., Dash, J., Huang, W., Peng, D., Qin, Q., Mortimer, \ H., ... Dong, Y. 2018. Vegetation indices combining the red \ and red-edge spectral information for leaf area index retrieval. \ IEEE Journal of Selected Topics in Applied Earth Observations \ and Remote Sensing 11(5), 1482-1493. doi:10.1109/JSTARS.2018.2813281. """ CIREDRE = (b8 / (a * b4 + (1 - a) * b5)) - 1 return CIREDRE
def divisible_by(divisor, number): """Return True if the ``number`` is divisible by ``divisor``. >>> divisible_by(3, 6) True >>> divisible_by(5, 10) True >>> divisible_by(3, 4) False """ return number % divisor == 0
def dirplus(obj=None): """Behaves similar to the dir() function, but omits the "dunder" objects from the output. Examples: >>> blah = 'Here is some blah blah' >>> dirplus()\n ['dirplus', 'blah'] >>> type(blah)\n <class 'str'> >>> dirplus(blah)\n ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] References: # This was a valuable reference for information about namespaces, globals(), locals(), and such like: https://realpython.com/python-namespaces-scope/ Args: obj (object, optional): Reference the desired object. Defaults to None. Returns: list: Returns a list of the pertinent "dir()" output """ if obj: return [e for e in dir(obj) if not e.startswith("__")] else: return [e for e in globals().keys() if not e.startswith("__")]
def replaceAll(initialString, translationHash): """ for each (toReplace, replacement) in `translationHash` applying the query-replace operation to `initialString` """ result = '' if initialString is not None: result = initialString for key, value in translationHash: result = result.replace(key, value) return result
def _filter_case_action_diffs(diffs): """Ignore all case action diffs""" return [ diff for diff in diffs if diff.path[0] != 'actions' ]
def write_editor(editor_list: list) -> str: """ Given a list of editors, insert into XML snippet, and return XML snippet :param editor_list: A list of 1+ editors structured as [('First','Last'),('First','Last')] :return: XML snippet for editors >>> write_editor([('Bertha B.', 'Jorkins')]) #doctest: +NORMALIZE_WHITESPACE '<v1:editors> <v1:editor> <v3:firstname>Bertha B.</v3:firstname> <v3:lastname>Jorkins</v3:lastname> </v1:editor> </v1:editors>' >>> write_editor([('Angelina', 'Johnson'), ('Gabrielle G.', 'Delacour'), ('Anthony', 'Goldstein')]) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE '<v1:editors>\n <v1:editor>\n <v3:firstname>Angelina</v3:firstname>\n <v3:lastname>Johnson</v3:lastname>\n </v1:editor>\n <v1:editor>\n <v3:firstname>Gabrielle G.</v3:firstname>\n <v3:lastname>Delacour</v3:lastname>\n </v1:editor>\n <v1:editor>\n <v3:firstname>Anthony</v3:firstname>\n <v3:lastname>Goldstein</v3:lastname>\n </v1:editor>\n </v1:editors>' """ editors_xml_snippet = "<v1:editors>" n = 0 for editor in editor_list: editors_xml_snippet += """ <v1:editor> <v3:firstname>""" + editor[0] + """</v3:firstname> <v3:lastname>""" + editor[1] + """</v3:lastname> </v1:editor>""" editors_xml_snippet += """ </v1:editors>""" return editors_xml_snippet
def fib_recursive(n): """Find the n-th fibonacci number, recursively""" if n < 1: return 0 if n <= 2: return (n - 1) return fib_recursive(n - 1) + fib_recursive(n - 2)