content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Union from pathlib import Path def add_extension(file_path: Union[str, Path], extension: str) -> Union[str, Path]: """Adds the extension to the file path if it is not present. Parameters ---------- file_path : Union[str, Path] The path to the file. extension : str ...
f0a6c638701cd5ce34c387a3e6d445bcad4a2d1f
633,121
import os def env(variable, default=None): """ Shortcut to return the expanded version of an environment variable """ return os.path.expandvars(os.environ.get(variable, default) if default else os.environ[variable])
535fb05accbf1f6790b4c6af82bde92b099d3c9a
633,122
def compute_average_cosine_similarity(square_norm_of_sum, num_vectors): """Calculate the average cosine similarity between unit length vectors. Args: square_norm_of_sum: The squared norm of the sum of the normalized vectors. num_vectors: The number of vectors the sum was taken over. Returns: A float...
231f75f153da38cfbcd43fd4198a8734ab565b48
633,123
import argparse def process_command_line(argv): """Process command line invocation arguments and switches. Args: argv: list of arguments, or `None` from ``sys.argv[1:]``. Returns: args: Namespace with named attributes of arguments and switches """ # script_name = argv[0] argv...
de809cbddfe4ac0ab8f9b5566d736bdb0a6a38e0
633,124
def ignoreStrReplace(line, cur, rep): """Wrapper for str.replace to ignore strings""" if '"' in line: #Split string at quotation marks lsplit = line.split('"') #Replace items contained within even partitions lsplit[::2] = [spl.replace(cur, rep) for spl in lsplit[::2]] #Re...
bbc2593354fdc9c748bd6fcadc81e48a30a5e55c
633,125
def encode(char, offset): """Shift any letters by a given offset. Ignore non-letter characters.""" if char < 97 or char > 122: return chr(char) char += offset if char > 122: char -= 26 return chr(char)
08432ec9a935dd600544710ee5d80edc7964a973
633,126
def read_dependency_file(path): """ Scan a gcc-generated dependency file for targets and their dependencies. Returns a dictionary of target : [dependencies] pairs """ def get_target_from_line(line): """ Return target, remainder if a target found in the line. Otherwise re...
ccfccf9168db45a37677ac3058e58d5485d63933
633,127
def read(k2400): """Do and Read measurement. args: k2400 (pyvisa.instrument): K2400 returns: reading (str) """ return k2400.query(":READ?").replace("\n", "")
07b0dda1c52b22f8667d17cf5225c6e276f7ed07
633,128
import sys def make_energy_list (opts, roots): """Computes the list of spectrum energies, and potentially adjusts peak widths""" epad = 20.0*opts.width emin = roots[0][0] - epad # if emin < opts.width: # emin = opts.width emax = roots[-1][0] + epad de = (emax - emin) / opts.n...
7373fdf240032a7c520813ed0110b370c9886855
633,131
from typing import Tuple import math def near_duplicate_similarity_cached( gold: Tuple[str], pred: Tuple[str], threshold: float = 0.1, ) -> float: """ Computes the approximate token-level accuracy between gold and pred. Returns: token-level accuracy - if not exact match an...
68734870a9797f8d9eed43704577f5f7df306acb
633,132
def deltatime_str(deltatime_seconds: float) -> str: """ Convert time in a format appropriate of time. Parameters ---------- deltatime_seconds : float Represents the elapsed time in seconds Returns ------- time_str : str Represents time in a format hh:mm:ss Examples...
bd0b79c13377538271e6ff758115b1fc8d30374f
633,133
def grouping_len(grouping): """ Get the length of a grouping. The length equal to the number of scalar values contained in the grouping, which is equivalent to the length of the list that would result from calling flatten_grouping on the grouping value. :param grouping: The grouping value to calcul...
c86050e6528372e71928985b4badd208c5deca12
633,135
import argparse def TypeNone(type): """Test input value for being 'type', but also accepts None as default Arguments: type [type]: specifies the type (int or float) the input argument has to obey Returns: type_text [function]: function that takes 'value' as argumen...
d65248bc3e1b462f63274a81bd39e799f77929e3
633,136
import functools def on_flow(initializer, alias): """ Use this decorator to create an updater that responds to flows of nodes between parts of the partition. Decorate a function that takes: - The partition - The previous value of the updater on a fixed part P_i - The new nodes that are ju...
97b0532a4f1b32d3b2b3c1d6e3911377c4dfe393
633,138
import unicodedata import re def clean_filename(name, replace_empty=""): """ Make a user-supplied string safe for filename use. Returns an ASCII-encodable string based on the input string that's safe for use as a component of a filename or URL. The returned value is a string containing only lower...
0538b729a08b3622fc303b8193ed5b301a514af1
633,139
import argparse def get_default_arg_parser(desc): """ Define an argument parser for use with Tigris Components and mandatory arguments """ parser = argparse.ArgumentParser(description=desc) parser.add_argument('-programDir', type=str, help='the component program direct...
df9ff2abc58d7d7083c8e4f0b42f86c99038fd44
633,140
def attrs(**kwds): """Decorator to add attributes to a function. Example: @attrs(versionadded="2.2", author="Guido van Rossum") def mymethod(f): ... """ def decorate(f): for k in kwds: setattr(f, k, kwds[k]) return f return dec...
fb207a7c85cc6f2bef213fca60d6a2567a8890a3
633,141
def datadir(request): """get, read, open test files from the tests "data" directory.""" class D: def __init__(self, basepath): self.basepath = basepath def open(self, name, mode="r"): return self.basepath.join(name).open(mode) def join(self, name): r...
cabd73e41d0343a9db59800bf5419b747897a43d
633,142
async def check_permissions(ctx, perms): """Checks if the user has the specified permissions in the current channel.""" if await ctx.bot.is_owner(ctx.author): return True permissions = ctx.channel.permissions_for(ctx.author) return all(getattr(permissions, name, None) == value for name, value i...
80b5602ba5edb4cff9bffc5038af2ad69cc55f7c
633,143
def _get_tags(tags): """Translate the {Name:x, Value:y} crap we get back from aws into a dictionary.""" if tags is None: return {} return {x['Key']: x['Value'] for x in tags}
07635bfa034c7124c0b47dba072c56974631b01e
633,144
import argparse def getarg(): """ read time period and station name from argument(std input) rd_cwbDay.py -d 2017-12-31 """ ap = argparse.ArgumentParser() ap.add_argument("-d", "--DATE", required=True, type=str, help="yyyy-mm-dd") args = vars(ap.parse_args()) return args['DATE']
59250d1a13a20d872fc1dae5214912a33f91137c
633,145
import pickle def get_context_and_sents(path, doc_db): """get context ans sentences""" context = {} sents = {} for title in path: para_info = doc_db.get_doc_info(title) if title.endswith('_0'): title = title[:-2] context[title] = pickle.loads(para_info[1]) s...
6173cb53e1fe665aec4f545baca25d40135d239e
633,146
import os def get_predefined_config_path(framework: str, domain: str) -> str: """Get predefined config for specified model domain.""" config_path = os.path.join( os.path.dirname(__file__), "configs", "predefined_configs", f"{framework}", f"{domain}.yaml", ) if c...
e85b3493c85c0f047a8fb52964e359740d06ef18
633,147
def get_hello(): """Get the intialization variables See `importing` for explanation of arguments and `introduction` for introduction""" return 'foo'
a6c11625ec3947238022f2777a49a9a9df331447
633,148
import math def logistic_loss(f_x,y_true): """ Compute the logistic_loss loss given the returned value f_x from a linear discrimination function on the feature x and its label y. Please use logarithm with base = 2 """ return math.log(1+math.exp(-f_x*y_true),2)
ad507b1d5b871cdf65b505966188e0db7baa3fb3
633,149
import subprocess def run_eutils_uids(args): """Runs the NCBI E-utilities to download the unique identifier numbers for all sequences returned by the query.""" esearch_cmd = 'esearch -db nucleotide -query "{}"'.format(args.query) efetch_cmd = 'efetch -format uid' eutil_subproc = subprocess.Pope...
d1b2688be5096f659401ab2c16d995c508222723
633,150
from typing import Dict from typing import Any def remove_none_values_recursively(dictionary: Dict[Any, Any]) -> Dict[Any, Any]: """ Recursively removes the key value pairs where the value is None. This is a recursive function which tries to find key value pairs where the value is None and then remove ...
2394eaa2a6f503cd4250a69ebfa52affe4621ee1
633,151
from typing import Optional from typing import Union from typing import Mapping from typing import Tuple from typing import Dict def get_compression_method( compression: Optional[Union[str, Mapping[str, str]]] ) -> Tuple[Optional[str], Dict[str, str]]: """ Simplifies a compression argument to a compressio...
f24de541b10e5f77956b5a6e466fa23640fe535b
633,152
import os def run(ctx, cmd): """Run a command with some default settings.""" return ctx.run(cmd, pty=True, env=os.environ)
f76da433aa5f62f0164d35ffdbc5b34763f66802
633,153
import torch def reshape_data(data_list, batch_first=True, collapse_dims=False): """Concat input/output data and clear buffers Args: data_list (list): list of tensors of equal, arbitrary shape where the batch_dim is either 0 or 1 depending on self.batch_first. batch_first (bool, optiona...
5c626dd7a34c2bca73fe6649b707fbdcea01fe39
633,154
import subprocess def get_kernel_name_for_vart(model): """Parse the kernel name out of the given elf file for VART. This method will leverage the command `dpu_model_inspect` to return the model name. Parameters ---------- model : str The name of the ML model binary. Can be absolute o...
3c7c7905d109d67fcb168fa2b5bdc421875f3edb
633,155
def merge_sites_into_messages(found_sites): """ Join links to found accounts and make telegram messages list """ if not found_sites: return ['No accounts found!'] found_accounts = len(found_sites) found_sites_messages = [] found_sites_entry = found_sites[0] for i in range(l...
0589c3cf5419b8fecb78be81932599aecf27174d
633,156
def set_prompt(scope, prompt=None): """ Defines the pattern that is recognized at any future time when Exscript needs to wait for a prompt. In other words, whenever Exscript waits for a prompt, it searches the response of the host for the given pattern and continues as soon as the pattern is fou...
d5fa89b23b9eeb757d37484de6f92906dffe71f2
633,157
def tostr(data): """convert bytes to str""" if type(data) is bytes and bytes is not str: data = data.decode('utf8') return data
cb774974f0ebe643862af5058ccd57eafe2b9d13
633,158
from typing import Any def get_object_name(obj: Any) -> str: """Get a human-readable name of a Python object, e.g. a pipeline component. obj (Any): The Python object, typically a function or class. RETURNS (str): A human-readable name. """ if hasattr(obj, "name") and obj.name is not None: ...
ccd8022fc560297d8e6c94c0561127a622758525
633,159
def required_error(name): """ The error message presented when a required field is not present """ return "You must specify a value for {0}".format(" ".join(name.split("_")))
a60b000632b6304618820d00c65f0716dc21020c
633,160
def deep_merge(first: dict, second: dict) -> dict: """ Dict deep merge function Merge recursive second dict in first and return it >>> deep_merge({},{}) {} >>> deep_merge({'key': 'value'}, {'key': 'value'}) {'key': 'value'} >>> deep_merge({'key': 'value'}, {'key': 'new_value', 'second_k...
8306b925f8c7b69044135e0e8387d082553bda4e
633,161
import re def unfold(text): """Unfold multi-lines attributes. Read rfc5545-3.1 for info. """ return re.sub('\r\n( |\t)', '', text).splitlines()
d4f975b8695a63a85ac236b806fd919824b04e18
633,162
import random def exponential_backoff(max_tries, max_sleep=20): """ Returns a series of floating point numbers between 0 and min(max_sleep, 2^i-1) for i in 0 to max_tries """ return [random.random() * min(max_sleep, (2**i - 1)) for i in range(0, max_tries)]
f9ce33e8934cfe7e8c4256614fe524e7d50c0706
633,163
def MCTopM_RandomNewChosenArm(j, state, decision, collision): """RandTopMC chooses a new arm after if the chosen arm lies outside of its estimatedBestArms set, uniformly from the set of estimated M best arms, or keep the same.""" player = state.players[j] chosen_arm, sitted = state.memories[j] if not si...
3c5abe313f9c736ec6bfff71f58556a3ad3c7b1f
633,164
def reply_only(*user_id, default=None): """user_idに指定されているユーザーIDからの メッセージにのみ返信させるデコレータ""" def _reply_only(router): router.reply_only += user_id router.default = default return router return _reply_only
6763c16ada64c1c15b02422a4212d361c3b9bb08
633,165
from typing import Tuple def _do_check_power_limit( power_ratio: float, power_limit: float, ) -> Tuple[int, str]: """Check if the power ratio exceeds the limit. :param power_ratio: :param power_limit: :return: _overstress, _reason :rtype: tuple """ if power_ratio <= power_limit: ...
e49fe0abb95f47540b934d42e75f409b0132ffd5
633,167
def play_one(env, model, eps, gamma, copy_period): """ Plays a single episode. During play, the model is updated, and the total reward is accumulated and returned. Parameters ---------- env : gym.Env Environment. model : NumpyDQNObsSingle Model instance. eps : numeric ...
eac4fb1bfeb425b3f87b2bba459122d1c1b31371
633,168
def _convert_to_nM(unit, bioactivity): """ Convert IC50 from predefined units to nM. """ conversion_factors = { "pM": 1e-3, "10'-11M": 1e-2, "10'-10M": 1e-1, "nM": 1e+0, "nmol/L": 1e+0, "10'-8M": 1e+1, "10'-1microM": 1e+2, "10'-7M": 1e...
a96487d63c2ea5ca910b25ed1925956605d8fa78
633,169
def curvature(cs, x): """ Return the curvature (inverse radius of curvature) of the lane. Parameters: cs: CubicSpline Instance of the CubicSpline calss x: float or array of floats Points at which to evaluate the curvature >>> from eksternlab import curvature >>> x = [0.23...
e7cfb95be1073a27d176f52e582fd3a462239296
633,170
def ipaddress_dialogs(context, request, eip=None, landingpage=False, associate_form=None, disassociate_form=None, release_form=None): """Modal dialogs for Elastic IP landing and detail page.""" return dict( eip=eip, landingpage=landingpage, associate_form=associate_...
d9d033337c6eb82c3123ca82102c9e791d20fba1
633,171
from typing import Tuple def pad(left: int, right: int, top: int, bottom: int) -> Tuple[Tuple[int, int], Tuple[int, int]]: """Set padding of element. Args: left: Left padding. right: Right padding. top: Top padding. bottom: Bottom padding. Returns ---------- padding: The padding ...
4e49571b59e6dc5becadf9c2786b363ca515f2b8
633,173
def wiki_strip_circumflex(txt): """ Removes the (deeply nested) circumflex characters from wiki text. """ circumflex = 0 txt = list(txt) for i in range(len(txt)): if txt[i] == '{': circumflex += 1 elif txt[i] == '}': circumflex -= 1 txt[i] = ''...
3ba6387a016a903957fe20c258a318a3d68aeb4f
633,174
def leiafloat(msg): """ :param msg: Texto a ser mostrado no input :return: Retorna um valor real """ while True: try: nfloatl = float(input(msg)) except (TypeError, ValueError): print(f'\033[31mO valor digitado não é Real.\033[m') continue ...
cb01f30527b27a3a70e8e464210544338deb5865
633,175
def calc_rsr(txt): """Calculates the ratio of characters in the right-side of the QWERTY keyboard, also known as RSR (Right-Side Ratio), given a lower-case text object. """ lside = ['q','w','e','r','t', 'a','s','d','f','g', 'z','x','c','v','b'] rside = ['y','u','i...
1764a72364516c8e50e1171303c0dbe74ec702a4
633,176
import yaml def _parse_yaml(path, file='**/*', ext='.yaml'): """Parse `file` in `path` (or all files in subfolders if `file='**/*'`)""" dct = {} for f in path.glob(f'{file}{ext}'): with open(f, 'r', encoding='utf-8') as stream: _dct = yaml.safe_load(stream) # add `file` att...
fe3c4bd5264bf23e25a9e467a9666cab001f24f9
633,177
def all_validate_to(func): """ Validate that all elements in the given list pass the validation of the given validator function. >>> f = all_validate_to(positive()) >>> f([10, 20, 30]) True >>> f([10, 0, 30]) False >>> f([10, 10, -100]) False >>> f = all_validate_to(in_range...
c6be2c5430285691cc31f5e036fbad26122fce46
633,179
def get_neighbor_distances(ntw, v0, l): """Get distances to the nearest vertex neighbors along connecting arcs. Parameters ---------- ntw : spaghetti.Network A spaghetti network object. v0 : int The vertex ID. l : dict The key is a tuple (start vertex, end vertex...
ed54dcdff7abadcf99c2f6892cb0abc3daa94b7d
633,180
def stations_by_river(stations): """ Groups stations by the river they are on. Args: stations: list of MonitoringStation objects Returns: A dictionary mapping river names (string) to a list of MonitoringStation objects """ ret = {} for s in stations: river = s.river ...
80f55713bffe82883309f26bd24c2d7a9460bf11
633,181
def truncate_name(text): """Ensure the comic name does not exceed 100 characters.""" return text[:100]
4fbaf6f0122b852306c78c7a06da53e73f392302
633,182
def with_prefix(prefix, name): """Adds prefix to name.""" return "/".join((prefix, name))
03e82480cee3bb9cdf0b73c4e26a792c271e202d
633,183
def split_stream_name(ui_stream_name): """ Splits the hyphenated reference designator and stream type into a tuple of (mooring, platform, instrument, stream_type, stream) """ mooring, platform, instrument = ui_stream_name.split('-', 2) instrument, stream_type, stream = instrument.split('_', 2) s...
4c01dd99d8c6e1963af03a241a3a1a8a517af06d
633,184
from typing import List def get_first_solution(tam: int, first_solution: List[int] = []) -> List[int]: """Get the first solution""" return list(range(tam)) if len(first_solution) == 0 else first_solution
46fe70b9efdbdc518897e5c77ddfca5127df9d47
633,185
import pandas as pd def to_ns(x): """convert timestamp to nanosec since 1970-1-1""" return pd.to_datetime(x).value
580ea07e7a660a3b135c1c83fef00c71943a1934
633,186
def linear_search(array, val): """ Time Complexity: O(n) Space Complexity: O(1) :param array: List[int] :param val: int :return: bool """ for i in array: if i == val: return True return False
5ab4544051d46b6e10038c47e1bfafdfa5a82d9d
633,187
import pickle def _load_command_store_from_pickle(file_name): """Load the command store from a pickle file.""" return pickle.load(open(file_name, "rb"))
2b35e37af9736f983f232261140f2db516198678
633,188
def fstatus(plus, minus, lines): """ returns git file change status in three digit string """ status = [] if plus == 0: status.append('0') else: status.append('1') if minus == 0: status.append('0') else: status.append('1') if lines == 0: status...
93a76b59385f2d85788ee0a33d0a08d63df73c78
633,189
def plateInput_files(pldef_params): """ Get ordered list of plateInput files given plate_definitio pararmeters. Parameters ---------- pldef_params : dictionary Should likely be the output of io.fp_platedef_params() """ return [pldef_params[f'plateInput{N+1}'] for N in r...
98cfeb7585206d70f804bca76556de9ccf4c614e
633,190
def decode(x): """Decode in case input is bytes-like """ try: x = x.decode() return x except: return x
b96bf301b8c8ed99251e39aaa80f869a5cf49bcc
633,191
import builtins def _get_py_lower_name(name: str, esc_builtins: bool = False): """Gen name for Python packages, modules, functions, methods, properties, variables.""" py_name = '' n = len(name) for i in range(n): c = name[i] if c.islower() and i < n - 1 and name[i + 1].isupper(): ...
243f74c0139793c091a06fcd3c73a1d27a713b23
633,192
def getNameBuiltwithpip(lines): """ Used if buildWithPip == True. If the file contains "%define pipname packagename", returns packagename. None otherwise """ name = None for line in lines: if line.startswith("%define"): if "pip_name" in line: name = line.s...
f6fee367af20f9c687ef0cedf651e8a799bde660
633,193
import re def filter_abbrevs(abbrevs): """Removes abbreviations that are more than one word or don't end with '.' Args: abbrevs (list): String abbreviations from wiktionary Returns: filtered (list): a subset of the list of abbreviations passed by caller """ ...
ca9d3f6f6c81b26e2e06800ee2c775b367f246c4
633,194
def get_totrup(data): """ :param data: a record with a field `totrup`, possibily missing """ try: totrup = data['totrup'] except ValueError: # engine older than 2.9 totrup = 0 return totrup
05728ee248d3e69a039980716d4b1c95e943607f
633,195
def is_answerable(example): """ unchanged from @chrischute """ return len(example['y2s']) > 0 and len(example['y1s']) > 0
566cc20a1da6ae5a6b3d79da0b7b82f6f549b760
633,196
def tickDiff(t1, t2): """ Returns the microsecond difference between two ticks. t1:= the earlier tick t2:= the later tick ... print(pigpio.tickDiff(4294967272, 12)) 36 ... """ tDiff = t2 - t1 if tDiff < 0: tDiff += (1 << 32) return tDiff
a08b74432ccaae8f4a4223aad6758aa4742d5ea5
633,198
def limit(num, minimum=1, maximum=255): """Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.""" return max(min(num, maximum), minimum)
fac54ad0bba741f14f97341a6331c025b5bd49fd
633,199
def occursInEq(var, deq): """ Detects if a variable appears within a delta equation. """ return (var == deq.clo1.expr) or (var == deq.clo2.expr)
f2d6a6b9888cc3eb685e90a72f726811408a6945
633,200
import hashlib def Digest(manifest): """Compute the digest of the manifest.""" return 'sha256:' + hashlib.sha256(manifest).hexdigest()
b26378a68390eb57d6f7e8210d87c346ab7f8c14
633,201
def fromHomogeneous(M): """ Return the linear and affine parts of a homogenous matrix :math:`M = [A, b]`. Parameters ---------- M : numpy array of float, shape (*, num_dims, num_dims + 1) or (*, num_dims + 1, num_dims + 1) Matrix representing an affine transformation in homogeneous coordinates....
80eedff60073a95030c9a7a574efc0231703a589
633,202
def info_carro(fabricante: str, modelo: str, **info_extra) -> dict: """ -> Guarda as informações de um imagem em um dicionário. :param fabricante: Nome do fabricante do imagem. :param modelo: Nome do modelo do imagem. :param info_extra: Dicionário contendo informações extras do imagem. :return: ...
b64cf16474db57acdb61ce12d6d12454a24d7720
633,203
import os def is_this_circleci(): """ Return if we are currently running in CircleCI. """ return bool(os.environ.get('CIRCLECI'))
2a1d9e1f0f7649383ab55887b6b5578d263e079f
633,204
def W_mol(W_mass, M_waste): """ Calculates the molar flow rate of waste. Parameters ---------- W_mass : float The mass flow rate of waste, [kg/s] M_waste : float The molar mass of waste, [kg/kmol] Returns ------- P_mol : float The molar flow rate of waste, [k...
f1f0745664d93e4e7a3e6937e347cfecb587911d
633,205
import platform def is_on_grid(): """Returns True if the current machine is on the maia grid. Implemented by checking if host name ends with ".cluster". """ return platform.node().endswith(".cluster")
b192f72aed037625e2a0cbab9395b9b2bac8d547
633,206
from typing import Any def route_shortcuts(cls): """A decorator used to add route shortcuts for `Flask` and `Blueprint` objects. Includes `get()`, `post()`, `put()`, `patch()`, `delete()`. Examples: ```python from flask import Flask @route_shortcuts class APIFlask(Flask): pass ...
75090655f3a5dd4b348b9bcbc0a1064511360e6a
633,208
import random def generate_random_path(R, C): """Generates path randomly. Returns None if failed.""" def valid_jump(a, b): """Returns True if jump from a to b is valid.""" return (a[0] != b[0] and a[1] != b[1] and a[0] - a[1] != b[0] - b[1] and a[0] + a[1] != b[0] + b[1]) ...
456c193bd282a02a2945772e7dc3d7b8c92b020a
633,209
import torch def apply_filterbank(specgram, filterbank): """ Apply a filterbank on specgram Args: specgram: [..., F, T] filterbank: [F, N]. N is the number of filters Returns: [..., N, T] """ # Pack batch shape = specgram.size() specgram = specgram.reshape(-1,...
c03424276de8ee17b4b991f6f116bbcf9d478ec2
633,210
def readProcessed( serverName, itemIds, startDate, endDate, resampleIntervalMS, aggregates ): """Reads processed values from the OPC-HDA server. Processed values are calculated values, based on the aggregate function requested for each item. The list of aggregates can be obtained by calling system....
f34ace2196426a392e79a652888e00e0a92b60c2
633,211
def cont(args): """FILTERING Retain elements containing substring """ s = args.split()[1] def _f(input): return [ i for i in input if s in i ] return _f
b820846069eda5d2b4ce05b6568427c3b90c0276
633,212
def filter_rules_action(user_actions, rules): """ Divide the list of rules by user_actions to editable and viewonly subsets :param user_actions: list of actions allowed for normal user :param rules: list of rules to be filtered :return: editable, viewonly lists """ editable = [] viewonly...
84b668e2d470e81e92b8f1d85365d18cd0d39207
633,213
def has_compatible_scheme(url): """Check whether the given URL uses a scheme compatible with and intended to be used by apt.""" return url.startswith(('http://', 'https://'))
69e1d2854ce7b69f73c9863a84de54db3aacf9af
633,214
def mean_degree(graph): """ function that computes mean edge degree for a DAG """ degree = 0 for i in graph: degree += graph.degree(i) #print(graph.degree(i)) #print("\nIn total: " +str(degree)) mean = degree / len(graph) return mean
6e278a31b699393987d23f2fad9afc9841c36764
633,215
import torch def vec_like(n, tensor): """ Returns a 2-D tensor with a vector containing zeros with same size as the input. """ assert n > 0, (type(n), n) assert len(tensor.shape) >= 1, tensor.shape vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype) return vec[None].rep...
cb039684f129a6d078dd545d826906202b3a94b7
633,216
def alter_data(df, context): """ Perform any alterations here on the Pandas DataFrame "df". For example, here is how you might drop the "education" column from indicator ENV1-3-2: if context['indicator_id'] == 'ENV1-3-2': df = df.drop(columns=['education']) """ # Don't forget to re...
d8fac6c47028a68e7240d5a84659e314da73aef8
633,217
def arg_neither_empty_nor_all_whitespace(_, arg: str) -> bool: """ Tests if the single argument is not None :param _: Ignored (typically mapped to `self` for bound methods) :param arg: The argument to be tested :return: True if arg is neither an empty string nor a string consisting only of whitespa...
9c0c79c1d9f8e092bdc914e662b677ab379a7952
633,218
def sumlist(x, y): """ Sums two lists of the same shape elementwise. Returns the sum. """ z = x for i in range(0, len(z)): if isinstance(x[i], list) and isinstance(y[i], list): z[i] = sumlist(x[i], y[i]) else: z[i] = x[i] + y[i] return z
c59a576694ffde673943abf0cf0973382ed7b2b4
633,219
import json def transform_to_vw(x): """ Transform context(feature) to VW format. """ x = json.loads(x) # feature:feature_value return " ".join(["%s:%s" % (i + 1, j) for i, j in enumerate(x)])
29c3edd344891a5c3a7410309656df4b90c3c9a9
633,222
def same_channel_sets(channel_sets: list): """Validate that all the channel sets are consistent, return false if not""" for chs in channel_sets[1:]: if chs.shape[0] != channel_sets[0].shape[0] or chs.shape[1] != channel_sets[0].shape[1]: return False # if not np.all(channel_sets[0] =...
ebf68d507b25ee5b0816cdc1af9727785e5a7308
633,223
import itertools def dict_list_cartesian_product(**kwargs) -> list: """ Given a dictionary whose values are lists, creates a list with every possible dictionary combination and regular unpacked values. Adapted from the Propheticus function in propheticus.shared.Utils.cartesianProductDictionaryLists. """ keys, valu...
de09b3450ac11496e7e34187b0853c89d09396b2
633,224
def split_mtx(X, n_folds=200): """ Split a matrix/Tensor into n parts. Useful for processing large matrices in batches """ X_folds = [] fold_len = X.shape[0]//n_folds for i in range(n_folds): start = i * fold_len if i == n_folds -1: end = X.shape[0] else: end = (i + 1) * fold_len ...
6a40af2e58ee8dc2156362ccf65cff8faa168ac4
633,225
def merge_dicts_lists(parent_dict, merge_dict): """ Function to add two dictionaries by adding lists of matching keys :param parent_dict: The Dict to which the second dict should be merged with :param merge_dict: Dict to be merge with the parent :return: Dict having the two inputs merged """ ...
d1d130d1fc58e1b2e293459bae37d0440686a17a
633,226
from typing import List def get_all_mod_inverse_list(m: int, max_n: int) -> List[int]: """ Computes a^-1 mod m for all a in [1, a-1] https://cp-algorithms.com/algebra/module-inverse.html#mod-inv-all-num """ ls_inv = [0, 1] for i in range(2, max_n+1): ls_inv.append(m - (m // i) * ls_inv...
81e71936b2ae1e6a360811b9fb4d8e36c9403e2c
633,227
def avg_options() -> list: """Print out and select the averages the user can choose of.""" print("Enter \n\n0: All\n1: Average delivery time per kitchen\n2: Average delivery cost per kitchen\n3: Average minimum order cost per kitchen\n4: Average rating per kitchen\n") selections = [] # get (only relev...
af918eee86be139c0fb89cb71a19cf84e76830e1
633,228
def bedslice_series(beds, region): """ Slice a series multi-indexed by ['chrom', 'start', 'end']. Assumes no proper nesting of intervals. """ chrom, start, end = region return beds.loc[chrom].loc[start:end]
5f6d3827e52a2fc1bffc64c7035de9dc6ef39ed1
633,229
def _dump_linestring(obj, fmt): """ Dump a GeoJSON-like LineString object to WKT. Input parameters and return value are the LINESTRING equivalent to :func:`_dump_point`. """ coords = obj['coordinates'] ls = 'LINESTRING (%s)' ls %= ', '.join(' '.join(fmt % c for c in pt) for pt in coords...
f4dd504b494873fdf67a1ac7a7377e9bcb8ccb39
633,230
def translate_confidence_level(level): """ return confidence level """ if level is None or level == 'LOW': return '-i' if level == 'MEDIUM': return '-ii' if level == 'HIGH': return '-iii' raise ValueError(f'{level} is not a valid confidence level')
d5d49e47144083d3a685f0d79a592e17d9171fe0
633,231