content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Dict from typing import Callable from typing import Any import json def build_dumber(encoders: Dict[str, Callable[[Any], Any]]): """ Build a json dumber function from a map of encoders for fields that needs to be encoded differently. Args: encoders (Dict[str, Callable[[Any], Any]]): The ...
739d73e3dc4a29a44c569a6f03803aa53bb6b3fe
628,965
def butterworth(X, cutoff, order, mu=0, cutin=None): """ Butterworth transfer function. Parameters ---------- X : numpy.ndarray, required Range of values to plot over. cutoff : float, required Cut-off value for function. Note that if array X includes values both above a...
e6337d16f5b0755d4168d66e87da98536135b064
628,968
def is_from_module(obj, module): """Check if an object "belongs" to a module. >>> import collections >>> is_from_module(collections.ChainMap, collections) True >>> is_from_module(is_from_module, collections) False """ return getattr(obj, '__module__', '').startswith(module.__name__)
91024d94e480d71cfb28724470e52fceb92222d0
628,970
def has_all_permissions(user, permissions): """ Return `True` only if the user has all the permissions """ for perm in permissions: if not user.has_perm(perm): return False return True
5b82b3cceb7ea4cdb3ce52f1ba5f73364a542f70
628,974
def ensure_list(list_or_scalar): """Convert the input to a list if it is not.""" if isinstance(list_or_scalar, list): return list_or_scalar return [list_or_scalar]
e137404798a5d0d115a3835ca4601bfa0e66bdad
628,980
def remove_templates(text): """Remove all text contained between matched pairs of '{{' and '}}'. Args: text (str): Full text of a Wikipedia article as a single string. Returns: str: A copy of the full text with all templates removed. """ good_char_list = [] prev_char = None ...
97cd95160703aef8e74bbb4134c83eee2b195fa8
628,981
def _find_scalar_and_max_depth(pylist): """Finds nesting depth of scalar values in pylist. Args: pylist: A nested python `list` or `tuple`. Returns: A tuple `(scalar_depth, max_depth)`. `scalar_depth` is the nesting depth of scalar values in `pylist`, or `None` if `pylist` contains no scalars. ...
2e5dda0532d640c0cbb2a2d3169fc92dcc27b8e3
628,982
def binary_search(lo, hi, condition): """Binary search.""" # time complexity: O(log N) # space complexity: O(1) # dep: condition() # keep looping as long as the substring exists while lo <= hi: mid = (lo + hi) // 2 # the int division result = condition(mid) if ...
18e7b9b3ad63f2c5cdc345b2277d06b17fae791d
628,986
def info_qry(tickers, flds) -> str: """ Logging info for given tickers and fields Args: tickers: tickers flds: fields Returns: str Examples: >>> print(info_qry( ... tickers=['NVDA US Equity'], flds=['Name', 'Security_Name'] ... )) ticker...
9f7e447a83dcef9496fa6272316a3b366a9a0d60
628,993
def waveform_time_to_spec_time(t, spectrogram_len, spectrogram_generator): """Converts time in waveform space to time in spectrogram space given parameters of STFT""" hop_length, window_length = spectrogram_generator.hop_length, spectrogram_generator.win_length for hop in range(spectrogram_len): if...
3c5cbb9c00184a1d097093bf3a6ce7fac2a8c2c9
628,996
def tokenize_rulekey_line(line): """ Tokenizes a line of the form: '<type>(<value>):<type>(<value>):...<type>(<value>):' Tokens are returned in reverse order, because the serialization was also reversed. """ # Since ':' can appear within a token value, we cheat and delimit tokens by '):'. delimi...
843d708d3400bc978a5f79396fa9586d34d5249a
628,998
def generate_nav_urls(host, query, results): """Generate links to previous and next pages for navigation.""" cur_page = results.current_page() if cur_page > 1: url_prev_page = 'http://' + host + '/search?q=' + query \ + '&page=' + str(cur_page - 1) else: url_prev_...
82d47cd6c3fb192d3900b11336f45bbc08fa29d3
629,007
from typing import Tuple def calculate_vwap( first_stock_values: dict, pv: float, sum_volume: float, actual_pv: float, actual_vol: float ) -> Tuple[float, float, float]: """ Function to calculate the VWAP. Volume-weighted average price(VWAP) """ if not ...
fafe5d8ee6ed85a8f726b737c9826bb34be05cf9
629,008
def GetMatchingDepsEntries(depsentry_dict, dir_path): """Gets all deps entries matching the provided path. This list may contain more than one DepsEntry object. Example: dir_path='src/testing' would give results containing both 'src/testing/gtest' and 'src/testing/gmock' deps entries for Chromium's DEPS. Exa...
7ebf54add4785cadb5561ee2ecd75bbdd020474f
629,011
def _ensure_is_list(obj): """ Return an object in a list if not already wrapped. Useful when you want to treat an object as a collection,even when the user passes a string """ if obj: if not isinstance(obj, list): return [obj] else: return obj else: ...
d2025a28e6143941a828452ef3134de49544ca76
629,012
from typing import Optional def convert_negative_none(value: int) -> Optional[int]: """Convert an negative int value from the ToonAPI to a NoneType.""" return None if value < 0 else value
3cfbb00e47a9edbb4a8826779abd1b143829ceef
629,020
import re def short_expression(original: str, level: int = 0) -> str: """Abbreviate the expression, keeping it human-readable. If `level` is 0, just remove parts that are implicit from context, such as a leading ``PSA_KEY_TYPE_``. For larger values of `level`, also abbreviate some names in an una...
d19610031945ad38151e8ce85e8a4ba1f93e5d5c
629,021
def frame_center(array, verbose=False): """ Return the coordinates y,x of the frame(s) center. Parameters ---------- array : 2d/3d/4d array_like Frame or cube. verbose : bool optional If True the center coordinates are printed out. Returns ------- cy, cx : float ...
27a3089afcb36f77627c19ab431e1866ef33e773
629,022
import re def _sanitize_to_identifer(name): """ Changes a string with various characters into an identifier that is valid for python. i.e. 'minimum RR-interval' -> 'minimum_RR_interval' """ n = name.strip() n = re.sub('/', ' ', n) n = re.sub('-', ' ', n) n = re.sub(' +', '_', n) ...
625237efbddddaf0cb5414ded626f4dc46dd04ae
629,030
def time_switch(x): """ Convenience codes to convert for time text to pandas time codes. """ return { 'min': 'Min', 'mins': 'Min', 'minute': 'Min', 'minutes': 'Min', 'hour': 'H', 'hours': 'H', 'day': 'D', 'days': 'D', 'week': 'W', ...
f9b83a7252958525a0fa081f4f8e9833fa92a0bc
629,040
async def get_sensor(client, sensor_name): """Get last sensor value (in encoded form), or None if no value.""" reply, informs = await client.request('sensor-value', sensor_name) assert reply == [b'1'] status = informs[0].arguments[3] value = informs[0].arguments[4] if status in {b'nominal', b'wa...
18e300422457b27d30be09fda703977ec1e98070
629,042
from itertools import islice, tee def sliding_window(iterable, length=2): """ Return a sliding window over iterable. """ its = ( islice(it, i, None) for i, it in enumerate(tee(iterable, length)) ) return zip(*its)
1d4ac431446477c2b4934cb1dfa9676679463140
629,045
from typing import List def get_package_nvrs(built_packages: List[dict]) -> List[str]: """ Construct package NVRs for built packages except the SRPM. Returns: list of nvrs """ packages = [] for package in built_packages: if package["arch"] == "src": continue ...
a560d3dbf89fbb934fb100fdb73491df972a06de
629,046
def get_auth_results(reportee, dkim_result, spf_result, **kw): """Return "auth_results" part. This can be no or more raw DKIM results and one or more SPF results. For now we always return either no or one DKIM and one SPF result, based on the passed `dkim_result` and `spf_result` and use only the `reportee` dom...
afe3e91a2edfaf2e29e5383bbf553c49b4e4810e
629,047
def _compare_dacls(dacl1, dacl2): """ This method compare the two given DACLs to check if they are identical. Identical means here that they contains the same set of ACEs in the same order. """ return ([dacl1.GetAce(index) for index in range(dacl1.GetAceCount())] == [dacl2.GetAce(index) ...
9396f2d48fbb7a809fdd02403eb57af6d98d2ad4
629,048
def cat_dist(x, y): """ A dummy implementation of a binary distance metric. """ return int(x['x'] != y['x']) + int(x['xx'] != y['xx'])
4c3a64bef59faf814bffc448d07812113cd7152d
629,049
def makelower(indict): """return a copy of a string->string dict such that all keys and values are lowercase.""" return {k.lower(): v for k, v in indict.items()}
1c2b7c9bf010e91143160d482860628be2261c8e
629,051
import random def make_humane_gibberish(length): """Generate a meaningless but human-friendly string. Characters are chosen so that no two characters are alike. Easily confused characters, such as '1' and 'l' are also excluded. """ result = '' for i in range(length): result += random.choice('ACEFHJKNPQRTVXY...
65410b354a676b00801fb137755529ee09bfc45c
629,054
def as_tuple(*values): """ Convert sequence of values in one big tuple. Parameters ---------- *values Values that needs to be combined in one big tuple. Returns ------- tuple All input values combined in one tuple Examples -------- >>> as_tuple(None, (1, 2,...
1c5e97236c1b5c9dd2da6666b794b85c385ac885
629,056
def _process_edge_df(subgraph): """ Returns an edge DataFrame with the names of the genes instead of their IDs. """ return subgraph.get_edge_dataframe().merge( subgraph.get_vertex_dataframe().reset_index(), left_on='source', right_on='vertex ID', ).merge( subgraph.get...
a8fee40fa5af2668c8419fe79371c3948dbc5d6c
629,058
def active(config): """ Verifies that the signature of a configuration has not timed out. :param config: :return: True/False """ return True
79ec58ef868858809b72773cac99953cafd10768
629,059
def get_data_year_location_age(year, location, age, data_structure): """ Retrieve the data for a given year, location, and age. :param year: a defined year for which corresponding data will be returned :param location: a defined location for which corresponding data will be returned :param age: a d...
5db474b7033d0e392df03159d1df6507699bf881
629,060
def getChange(current, previous): """Get the Percentage Change. Parameters: current (int): Current value previous (int): Previous value Returns: int: Percentage Change """ if current == previous: return 0 try: return ((current - previous) / previous) * 100.0 e...
a99e3e5820bfafe4ba7e2281b48f42349a079d9e
629,061
def logical_xor(a, b, unsafe=False): """logical xor without the bloat of numpy.logical_xor could be substituted with numpy.logical_xor !important: if unsafe is set to True, a and b are not checked. This improves speed but is risky. expects integers [0,1] or bools """ if not unsafe: ...
bc1981e81412f29fd91b1f5d57405a3d92ac4fa3
629,064
import torch def compute_output_gradient_times_vec_intermediate(relu_network, x, z0): """ Compute z and Wz defined in output_gradient_times_vector() function. Notice that when the relu network input is 0, we use only the right derivative. Return: z, Wz: Refer to output_gradient_times_vector...
4088ea9c3f9735258dfe3475e01a51873608a44c
629,067
from typing import List def sector_to_subreddit_list(sector: str) -> List: """Returns list of subreddit for respective sector Parameters ---------- sector : str sector of ticker Returns ------- List List of subreddits """ sector_subreddit_map = { "Basic Ma...
eb9da27db1b83f9291fff9812c3b7d716864e0e4
629,070
def v_relative(v, met): """ Estimates the relative air velocity which combines the average air velocity of the space plus the relative air velocity caused by the body movement. Parameters ---------- v : float air velocity measured by the sensor, [m/s] met : float metabolic rate,...
b226578ce844dc60d208670614b4c06d604c7d3a
629,072
def list_duplicates(cells): """Find duplicates in list for detailed reporting """ # reference https://stackoverflow.com/questions/9835762 seen = set() # save add function to avoid repeated lookups seen_add = seen.add # list comprehension below chosen for computational efficiency # adds a...
15ff3405d33d7e9b0a47021f164c5f53a316cbf6
629,073
def convert_range(p): """Convert a float from 0-1 range to integer 0-255 range.""" return max(0, min(255, round(255 * p)))
5afb82261d8f02fd3363ac30196e6cc544a94573
629,075
def GetRunKeyName(name): """Returns a str used to uniquely identify a run.""" return 'Run_%s' % name
113933373ae1a38408912453a1e84586ba78dca7
629,076
def binary_search(my_list: list, item: int) -> int: """ 二分法排序 :param my_list: 查找列表 :param item: 所需要查找的元素 :return: 索引位置, 没有找到返回 -1 """ low_index = 0 hight_index = len(my_list) - 1 while low_index <= hight_index: mid = (low_index + hight_index) // 2 guess = my_list[mid]...
e866cc752099d8e17810991e1b7e63b58cc9817b
629,077
import functools import warnings def deprecated(obj=None, suffix=""): """ Decorator to mark a function or a class as deprecated """ def decorator_deprecation_warning(obj): @functools.wraps(obj) def wrapped(*args, **kwargs): if isinstance(obj, type): msg = (...
019813143c185c4d322d0a057210631481d9843b
629,078
def parse_data(dataframe): """ Dataframe looks like: label1 label2 label3 ... trial1 0.4 0.4 ... trial2 0.6 0.1 ... . . . . . . returns: [ [0.4, 0.6, ...] , [0.4, 0.1, ...] ] """ labels = dataframe.co...
0bcca55d7d175236c19fd6ae7ea74dd2adff0c7f
629,081
def _is_all_zeros(data: bytes) -> bool: """Returns True if data is None, empty, or consists of all zeros.""" if data is None: return True for i in data: if i != 0: return False return True
f222a47f2b5747f7fa6a155073d686190427efc4
629,088
def get_left_child(iIndex): """ Given an index it returns it's left child's index. """ return 2 * iIndex + 1
998665b926e97e30934215228ea893bc6b119a58
629,093
def unbox_enum(typ, obj, c): """ Convert an enum member's value to its native value. """ valobj = c.pyapi.object_getattr_string(obj, "value") return c.unbox(typ.dtype, valobj)
db6644a9e67db3a629882b4e053068ef7fd552d5
629,094
def unsigned_int(value): """Convert from signed to unsigned int (Channel Access does not support unsigend int)""" if type(value) == int and value < 0: value = value+0x100000000 return value
ff93ffaa7b1bee45d3c89372aba116a86b3032e6
629,096
def find_all(str_:str, key:str): """ Returen all the starting indices of string `key` in string `str_`. Example: ---------- >>> find_all("abcaa", 'a') [0, 3, 4] """ p, indices = -1, [] while True: p = str_.find(key, p + 1) if p < 0: break indices.append(...
1f8ea4f3a7a71c83605441189c93ecdd104248f1
629,097
def _token_symbols(token_list): """Given a list of tokens, returns a list of their symbol names.""" return [token.symbol for token in token_list]
e45e2a694332461ddf89804d387829a2263a2c66
629,098
def formatannotation(annotation, base_module=None): """ This is taken from Python 3.7's inspect.py; the only change is to add documentation. INPUT: - ``annotation`` -- annotation for a function - ``base_module`` (optional, default ``None``) This is only relevant with Python 3, so the doct...
8d4887774f5c940796f822cedeeaf562a4d6c290
629,104
def bytes2human(size, *, unit="", precision=2, base=1024): """ Convert number in bytes to human format. Arguments: size (int): bytes to be converted Keyword arguments (opt): unit (str): If it will convert bytes to a specific unit 'KB', 'MB', 'GB', ...
e35db9550ab2ff5a9ddc24903e29e5f21f66b465
629,106
def boolean(obj): """ Convert obj to a boolean value. If obj is string, obj will converted by case-insensitive way: * convert `yes`, `y`, `on`, `true`, `t`, `1` to True * convert `no`, `n`, `off`, `false`, `f`, `0` to False * raising TypeError if other values passed If obj is non...
f2172b0d4c5794425a11a28705de81871a6fbe36
629,111
from operator import mod def is_islamic_leap_year(i_year): """Return True if i_year is an Islamic leap year.""" return mod(14 + 11 * i_year, 30) < 11
d7c20c674ee2e93423adf3c3307bfa73f0716efc
629,113
def _split_up_multiple_entries(entry): """Split up lists of entries that have been recorded as a single string.""" split_types = ['<br>', '<br/>', '<br />'] for split_type in split_types: if split_type in entry: return entry.split(split_type) return [entry]
b9309269c72adc245597b1359c90476efc5e75f6
629,117
def fibonacci(n): """Return nth term in fibonacci sequence Parameters ---------- n: int nth term in fibonacci sequence to calculate Returns ------- int: int nth term of fibonacci sequence, equal to sum of previous two terms Examples ...
9ef3df4ea1d2ca1eb77a645db438031d4bc4748e
629,121
import inspect def get_all_args(fn) -> list: """ Returns a list of all arguments for the function fn. >>> def foo(x, y, z=100): return x + y + z >>> get_all_args(foo) ['x', 'y', 'z'] """ sig = inspect.signature(fn) return list(sig.parameters)
bb5b90f978f62ab96124b290ad243602b4cced0c
629,122
import typing def _remove_arg( source: typing.List[str], flag: str, has_value: bool, ) -> typing.List[str]: """ Search for and remove the specified flag within the source arguments. This function removes it and its optional value if has_value is specified, returning a copy of the source l...
e85035c7d88b180f47c29cf3d5b2b051570f3a64
629,123
def canBalance(arr): """ Determine if a list of numbers is balance. Parameter: arr := list of numbers Return: True if a split position can be found in the arr such that both halves sum of numbers are equal. False otherwise. Assuming numbers can be integers or float...
17b6c2bd1163708c420b5e4f3d132f4abaae1f35
629,124
import itertools def std_from_mean_kde(data): """ Plot the KDE of the pandas series along with vertical reference lines for each standard deviation from the mean. Parameters: - data: pandas Series with numeric data Returns: Matplotlib Axes object. """ mean_mag, st...
d16d3945f4d7d1d0ee7a6ead20e78ced8d288e47
629,126
def makeopendir(fs, directory): """ Creates and opens the given directory in the given PyFilesystem. """ if not fs.isdir(directory): fs.makedir(directory) return fs.opendir(directory)
684e69f18123e9ebf257aa231f69e36bbe02e711
629,128
import functools def patch(cls, attr): """Patch the function named attr in the object cls with the decorated function.""" orig_func = getattr(cls, attr) @functools.wraps(orig_func) def decorator(func): def wrapped_func(*args, **kwargs): return func(orig_func, *args, **kwargs) ...
cafd5a15e2c3f1c50614073003134727c3d81a62
629,130
import re def findReadPosition(fullAssembly, read, label=''): """Finds the index of a given target (read) inside the context (fullAssembly) ========================================= context -------------- target ^ ^ startIndex ...
6d839ea2974f32e84d5b36c3e908255d7a6a631b
629,134
def quantize_float(f, q): """Converts a float to closest non-zero int divisible by q.""" return int(round(f / q) * q)
28a7170b3c1d2d8e7c0d9dc36ae8bc1b31c01165
629,136
def generate_avatar_path(obj, filename): """ Generates an unique path to user's avatar dir according to user's id. """ return 'images/avatars/' + str(obj.id) + '/' + filename
a68f1761d2f1aeb94a2565816cb7cac8a2d076e0
629,137
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict: """ Starts from base starting dict and then adds the remaining key values from updater replacing the values from the first starting dict with the second updater dict. Thus, the update_dict has precedence as it updates and replaces the...
b9df7f3bf7785c67198ec0f282e89d51f25d153a
629,140
import re from typing import Tuple from typing import Optional def get_year_data(match: re.Match, mixed: bool = False) -> Tuple[int, Optional[int]]: """Get year data from match.""" if mixed: year_string, *_ = match.groups() else: _, year_string, *_ = match.groups() if "-" in year_str...
dbe2f81f6d90b282c7eb5904d12e685ae68c4b11
629,153
def dot(p1, p2): """Dot product 4-momenta""" e = p1[0] * p2[0] px = p1[1] * p2[1] py = p1[2] * p2[2] pz = p1[3] * p2[3] return e - px - py - pz
54ed5f7aced40877bddb3257540741ab615186f6
629,154
import shlex def string_to_tokens(s): """ Converts string to list of tokens, with support for quotes. Defined here for convenience. See shlex documentation for more information on parsing rules: https://docs.python.org/2/library/shlex.html#parsing-rules :param s: string "a b 'c d' e" :re...
454c34be86b558f4afaadb26260b2160d71ecbe3
629,155
def in_list(collection_list): """Return true if test is in collection""" if "test" in str(collection_list): return True else: return False
28fbd8a1fbf5f877775a481b768d2aa121e55499
629,162
def library_dilution_calculator_fixed_volume(concentration, size, ul): """Calculate ng per sample (based on given ul_sample) needed for multiplexing.""" nM_DNA = (float(concentration)*(10.0**6.0))/(660*float(size)) ng_sample = (660*float(size)*nM_DNA*ul)/(10.0**6.0) return ng_sample
956533c26991cc8a19ad09bd400d46762e39342f
629,165
def _format_timedelta(timedelta): """Convert timedelta to string, lopping off microseconds.""" # This approach probably looks awful to all you time nerds, but it will work # in all the locales we use in-house. return str(timedelta).split('.')[0]
d0714efaa5a4138a40d9a25394e24852344a50f0
629,166
def genPPG(prices, weights): """ Generates low and high price per gram amounts for an item returns an array, with first element being low, and second element being high if there is only one variant of an item, a single element array will be returned """ try: assert(prices...
0502e1206da85009a7051584718d5bebf416ece2
629,167
def add_carry_bits(res, carry, MASK=0xFFFFFFFF): """Adds bits at each position 1 + 1 = 0 1 + 0 = 1 Examples: >>> res, carry = int("0101", 2), int("0011", 2) >>> bin(add_carry_bits(res, carry)) '0b110' """ return (res ^ carry) & MASK
e56c253b5eec5dd8f51164171c023cb041439222
629,171
import json def is_string_json_loadable(string: str): """ Determine if the serialized dictionary is a JSON object. Rather than constructing a complicated regex pattern, a simple try/except of the json.load should suffice. """ try: json.loads(string) return True except json.JSO...
818b41c3a1bfb582b29b906b179ff3087cb8f937
629,172
import struct def byte2py_int(data): """ Converts byte to Python int value. """ return struct.unpack('B', data)[0]
8934fe55225e2fb33fd5272b1060ee4079044051
629,173
def _get_interval_domain_min(dom): """ Get the lower bound of an interval domain Args: dom: Domain Returns: Domain min value """ return dom[0] if isinstance(dom, tuple) else dom
db17a8725eea1d4ffc62122309d33bcbb4c9a25f
629,174
def create_decompose_file_name(hw_details, decompose_param_obj): """ Creates file name for output of decompose process using hw_details_class obj and schedule_param obj """ fname = "" fname += str(hw_details.tree_depth) fname += str(hw_details.n_tree) fname += decompose_param_obj.str_fname() return...
1c8436c60790a1e2fcf0d5ea6ac7c8c318f8413b
629,175
import re def to_snake(string): """ Converts to snake case. :param string: A target string. :return: Converted string. """ return re.sub(r'(?<!^)(?=[A-Z])', '_', string).lower()
845bd2fec36c721cc792b283369a0dd6ab52a61b
629,177
def with_metaclass(mcls): """ For metaclass compatibility between Python 2 and 3. cf. http://stackoverflow.com/questions/22409430/portable-meta-class-between-python2-and-python3 """ def decorator(cls): body = vars(cls).copy() # clean out class body body.pop('__dict__', None)...
a7899592615a3bf5eb05e50ff81c880711efd4ba
629,178
import inspect def get_keyword_names(obj): """Returns a list of method names for the given object This excludes methods that begin with an underscore, and also excludes the special method `get_keyword_names`. """ names = [ member[0] for member in inspect.getmembers(obj, inspect.is...
2de0ad018fb2742cbe1d1fbebf6c0a621f1ab1f2
629,179
from typing import Optional def parse_key(headers) -> Optional[str]: """ Parses the header for an API key, and returns it if found. The authorization header must be in the following format: ``Token <api key>``. :param headers: A dictionary of request headers :return: If present, the key pa...
cda11fd0afa08fb3a85ed457b913f4e32d229c1f
629,181
def _receptor_standard_config(config): """Set standard config for network with receptor layer.""" config.data_dir = './datasets/proto/relabel_200_100' config.receptor_layer = True config.ORN_NOISE_STD = 0.1 config.kc_dropout_rate = 0. config.lr = 1e-4 # For receptor, this is the default LR ...
401111613a11255b3b3768c7c3e19ac57fb6a896
629,182
def validate_both(first_validator, second_validator): """Make sure both validators pass""" def validate(cursor_trail, tree): return (first_validator(cursor_trail, tree) and second_validator(cursor_trail, tree)) return validate
5f9fbe3663614661c02004b76ade546abbdba416
629,187
def repeat_flaky_test(test, n_repeats=2, n_allowed_failures=0, *args, **kwargs): """ Run the given test `n_repeats` times, raising the `n_allowed_failures+1`^th assertion error. Parameters ---------- test : Callable[Any, V] test to wrap n_repeats : int, optional number of times ...
d8998a87f30c01241ed51901edf89e2a845a59bf
629,194
def maximum_border_length(w): """Maximum string borders by Knuth-Morris-Pratt :param w: string :returns: table f such that f[i] is the longest border length of w[:i + 1] :complexity: linear """ n = len(w) f = [0] * n # init f[0] = 0 k = 0 # current lo...
564a29d77f8cc83e7093ae351ff3d308eebaa703
629,201
def hash_object(object_): """ Returns the hash value of the given object even if it not defines `__hash__`. Parameters ---------- object_ : `Any` The object to get it's hash value of. Returns ------- hash_value : `int` """ try: hash_value = hash(object_)...
49e6c303eb26e2085426e82443de36991a6e97f6
629,202
from typing import List def read_ta_list(fname: str)->List[str]: """ Read total list of TAs from a file with one TA roll number per line""" tfile = open(fname,"r") tas = [] for l in tfile: s=l.strip() if (len(s)==0): continue tas.append(s.lower()) return tas
7d683a32a9381a7efc80223cf2cea200238dc0a8
629,203
import math def sum_of_divisors_v2(n): """Find the sum of all divisors of a given integer. NOTE: If we look carefully, all the divisors are present in pairs. For example if n = 100, then the various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10). resource: https://www.geeksforgeek...
33bc5b22cca28dc3c1be8b65b81182b3f3ec858b
629,204
def replace_vol(img, vol, center, vol_as_mask=None): """Replace a volume within an image, centering on the given coordinates and cropping the input volume to fit. Args: img: Image as a Numpy array into which ``vol`` will be placed. ``img`` will be updated in-place. vol: Volume...
b3f9e1fc23c1c2855b0a98f79ca4410052f45010
629,207
import torch def max_loss(predict,target): """return max value of predict - target""" return torch.max(torch.abs(predict-target))
10fe62e7270497030e52ff0734656431bdb92561
629,210
import re import string from typing import Counter def get_words(text): """Retrieve the words present in a given string of text. The return value is a list of tuples where the first member is a lowercase word, and the second member the number of time it is present in the text. Example: IN: "Did th...
8885fc4a872458fd5551fb0d7fdd0652d9683853
629,212
def create_put_request(item): """Create a PutRequest object.""" return {'PutRequest': {'Item': item}}
c1ed85b84161ccee0aa84acc0d3004cae5e4adad
629,222
def filter_invalid_unicode(text): """Return an empty string and True if 'text' is in invalid unicode.""" return ("", True) if isinstance(text, bytes) else (text, False)
cdc488b4a7610a74e2b0e6a63ea365664f92e1bf
629,223
import json def get_city_from_string(ctx: str): """ Parses the city out of the JSON contained in the given string. :param ctx: a string containing JSON. :return: (city id, city name) tuple or (None, None) if not found. """ js = json.loads(ctx) for j in js["data"]: if "iglu:com.dbi...
51298c7e2b3c6c2441e5500fdfb0e7aaf42abbdb
629,225
def toBytes(b): """ Converts a string to a bytes object by encoding it as utf-8. """ if type(b) == str: return b.encode("utf-8") else: return b
29912d7cbc75c7d7a6b4e73bf3b7a4935699ef68
629,226
def read_file_to_string(path): """ Returns the contents of a file at ``path`` as a string. :param path: A path string :return: Contents of the file as a string :raises FileNotFoundError: If ``path`` does not exist :raises UnicodeDecodeError: If file does not contain UTF-8/ASCII text """ ...
2f55a15b690bed9e0a92f85883aafe1eda7413c2
629,227
def _pos_trace_func(state): """Trace function which records the state position (pos) component.""" return {'pos': state.pos}
28029a353adc375fbc3d1e0d6c74f3762f8ea48e
629,232
def strip_wikilink_to_article(wikilink): """Strip wikilink to article. Parameters ---------- wikilink : str Wikilink Returns ------- stripped_wikilink : str String with stripped wikilink. Examples -------- >>> strip_wikilink_to_article('[[dansk (sprog)|dansk]]'...
d81502263ec5b1685969ed1954ba9403fec9495f
629,235
def fao56_penman_monteith(net_rad, t, ws, svp, avp, delta_svp, psy, shf=0.0): """ Estimate reference evapotranspiration (ETo) from a hypothetical short grass reference surface using the FAO-56 Penman-Monteith equation. Based on equation 6 in Allen et al (1998). :param net_rad: Net radiation at crop ...
922e7ae8b4c80b622a0eb7e7bb17185a5c20a99b
629,238
def is_empty(module, container_name, facts): """ Check if container can be removed safely. To be removed, a container shall not have any container or device attached to it. Current function parses facts to see if a device or a container is attached. If not, we can remove container Parameters ...
e91eb5dfa36c14d701082d0831d6be5147d88179
629,239