content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import json
def get_netsel_urls(netsel_file):
"""Return list of CSK urls."""
# use sorted list of urls of the InSAR inputs to create hash
with open(netsel_file) as f:
netsel_json = json.load(f)
urls = []
for i in netsel_json:
for j in i: urls.append(j['url'])
return urls | 42bb95f73d6fff96685a950dc2a4f286f9d1e25e | 662,079 |
def get_or_insert(etcd_cl, key, value, **kwargs):
"""
Performs atomic insert for a value if and only if it does not exists.
If the value exists, no insert/update is performed.
No exception is raised if value already exists.
:param etcd_cl:
:param key:
:param value:
:param kwargs:
:r... | 5d37e910b3c8662e834258dc398842bde0f57d52 | 662,080 |
def sum_squared_xy_derivative(xy_point, coeff_mat):
"""For a coordinate, and function, finds df/dx and df/dy and returns the
sum of the squares
Arguments:
xy_point (tuple): (x,y)
coeff_mat (np.array): Matrix of coefficients of the n order polynomial
Returns:
(float): (df/dx + d... | ad962444a67c0361256ea133911789901dc48fb3 | 662,081 |
def reversed_string(node):
"""
Print out string representation of linked list but in reverse order
:param node: value of head node, start of list
:return: string: string of linked list, comma delimited
"""
if node is not None and node.next_node is not None: # not last element in linked list
... | 36161944a34523c3f90289a0f2262ab65ece4be9 | 662,083 |
def get_option_usage_string(name, option):
"""Returns a usage string if one exists
else creates a usage string in the form of:
-o option_name OPTIONNAME
"""
usage_str = option.get("usage")
if not usage_str:
usage_str = f"-o {name} {str.upper(name.replace('_',''))}"
return usage_... | 7c824d0b4488759fcf68af42f51d04eb40fcabeb | 662,085 |
import argparse
def get_parser() -> argparse.ArgumentParser:
"""
Return the CLI argument parser.
Returns:
An argparse parser.
"""
parser = argparse.ArgumentParser(
prog="moving-stars", description="Command line tool to copy GitHub stars to GitLab."
)
mxg = parser.add_mutua... | c8720c3797fe56b1e08ed865c7818a135b92582c | 662,087 |
import sys
def public(f):
""""Use a decorator to avoid retyping function/class names.
* Based on an idea by Duncan Booth:
http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a
* Improved via a suggestion by Dave Angel:
http://groups.google.com/group/comp.lang.python/msg/3d400fb22d8... | b8bf69cbb3755be85cc7b584c3110412cd227743 | 662,088 |
import re
def split_execution_info_into_groups(execution_info):
"""Splits execution information into groups according to '--' separator.
Args:
execution_info:
A textual representation of the execution_info.
Returns:
A grouped representation of the execution_info
"""
r... | ffbf1b62779443cfbdc1cfc1de47c1705ac0cf65 | 662,090 |
def parse_code(net_code: str):
"""
:param net_code: format <a>g[m]<b>f
"""
assert net_code[1]=="g"
assert net_code[-1]=="f"
nb_gnn_layers = int(net_code[0])
nb_dense_layers = int(net_code[-2])
is_max = True if net_code[2] == "m" else False
return nb_gnn_layers, nb_dense_layers, is_ma... | 98026f8625f84c33ee61f8a527bf6020bcd3f570 | 662,091 |
def div_list(ls,n):
"""
"""
if not isinstance(ls,list) or not isinstance(n,int):
return []
ls_len = len(ls)
if n<=0 or ls_len==0:
return []
if n>ls_len:
return []
elif n == ls_len:
return [[i] for i in ls]
else:
j = (int)(ls_len/n)
k = ls_len%n
ls_return = []
for i in range(0,(n-1)*j,j):
ls... | 0e187192cb3ad7322db53700b47b38e725cf5136 | 662,093 |
def is_short_option(argument):
"""
Check if a command line argument is a short option.
:param argument: The command line argument (a string).
:returns: ``True`` if the argument is a short option, ``False`` otherwise.
"""
return len(argument) >= 2 and argument[0] == '-' and argument[1] != '-' | d64497d9cfaa28957fda35cc644801b37af70f52 | 662,095 |
import logging
def logger_for_transaction(name: str, t_id: int):
"""Provide a specific default_logger for a transaction. The provided transaction id
will always be logged with every message.
Parameters
----------
name: str
The default_logger ID
t_id: int
Th... | 1b2a205efacfacfc5a205d417b956d8019af4a78 | 662,096 |
def is_guess_good(word, guess):
"""Returns whether guess is in the word
For example, is_guess_good('hello', 'e') should return True while
is_guess_good('hello', 'p') should return False.
Args:
word: a string
guess: a string
Returns:
bool: True if guess is in word, else returns ... | f61f58a2c90a0e48f149dff66b373ac3da2b7125 | 662,097 |
import platform
def is_bsd():
"""
Checks if we are within the BSD family of operating systems. This currently
recognizes Macs, FreeBSD, and OpenBSD but may be expanded later.
:returns: **bool** to indicate if we're on a BSD OS
"""
return platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD', 'NetBSD') | c2b5185045f4e0bc52a0e8606a4b650b44f6010c | 662,098 |
def path_subst(path, mapping):
"""Replace the sort sting elements by real values.
Non-elements are copied literally.
path = the sort string
mapping = array of tuples that maps all elements to their values
"""
# Added ugly hack to prevent %ext from being masked by %e
newpath = []
plen = l... | 051e4b689a83c1b8177a6202cc48a9b239195e04 | 662,099 |
def match_resource(resource, bid, cid):
"""Helper that returns True if the specified bucket id and collection id
match the given resource.
"""
resource_name, matchdict = resource
resource_bucket = matchdict['id'] if resource_name == 'bucket' else matchdict['bucket_id']
resource_collection = matc... | edf2592cb6330781f79a31fba2f5147170013b77 | 662,100 |
from typing import List
import heapq
def kNN(distances: List[float], k: int):
"""
Computes k-nearest-neighbors.
:param distances: A collection of distances from some point of interest.
:param k: The number of neighbors to average over.
:return: The mean of the smallest 'k' values in 'distances'.
... | 745098bec253b701ef96ada02ffa5033a104743c | 662,101 |
import os
import logging
def get_env_var(var):
""" Return an environment variable """
value = os.environ[var]
if value is None:
logging.warning("Environment variable %s is not set. Returning value None.", var)
return value | 77dff78b29a4ff5a093e5c2cdca7551bfab9ad2a | 662,102 |
import os
def delete_file(file_path):
"""
Takes str file_path with the full path to the file to delete
Returns dict with boolean status and str msg
"""
if os.path.exists(file_path):
os.remove(file_path)
return {"status": True, "msg": "File deleted"}
else:
return {"statu... | a2b2d9c13da87fcd167c7496b1908ff6aaf65999 | 662,103 |
def insertmany_query(tablename,objects):
"""
Function to process the query for insert many process
"""
if isinstance(tablename, str):
pass
else:
raise ValueError("Tablename should be a String")
"""
Sanity check of bulk insert
"""
# same length check
len_ob... | 1593b2c245ef5aa784e486296993fcb8734c16c8 | 662,104 |
import random
def randomer(n):
"""
Generate random DNA (not a randomer (NNNNN) which is a mix of random DNA)
:param n: length
:return: string
"""
alphabet = ['A', 'T', 'G', 'C']
return ''.join([random.choice(alphabet) for x in range(n)]) | 51515fe0d094993a15e7e30a05c4e0aca9a3b872 | 662,106 |
def get_field_meta(field):
"""
returns a dictionary with some metadata from field of a model
"""
out = { 'name' : field.name, 'is_relation' : field.is_relation, 'class_name' : field.__class__.__name__}
if field.is_relation:
out['related_model'] = "%s.%s" % (field.related_model._meta.app_labe... | 7d9801c4c94babde5c88ec15184c2d820ffe7d87 | 662,107 |
def get_slurm_dict(arg_dict,slurm_config_keys):
"""Build a slurm dictionary to be inserted into config file, using specified keys.
Arguments:
----------
arg_dict : dict
Dictionary of arguments passed into this script, which is inserted into the config file under section [slurm].
slurm_conf... | 99505e588911583d93ff32befc4a09092fd0e269 | 662,108 |
import time
def Retry(retry_checker, max_retries, functor, sleep_multiplier,
retry_backoff_factor, *args, **kwargs):
"""Conditionally retry a function.
Args:
retry_checker: A callback function which should take an exception instance
and return True if functor(*args, *... | 72db1202f30fcb79732d8171657353153c127647 | 662,109 |
import requests
def get_youtube_url(url):
"""
gets the list of url from a channel url
"""
st = requests.get(url).content.decode()
stop = 0
li = []
for i in range(10):
a = st.find("/watch?v", stop)
b = st.find('"', a)
li = li + ["https://www.youtube.com" + st[a:b]]
... | 3c8a2ba1358a32ac4964d69c3ef0ae130f11679a | 662,110 |
import os
import imp
def get_secrets():
""" Return a secrets module """
root = os.path.dirname(os.path.abspath(__file__))
return imp.find_module('secrets', [root]) | 2d0321937ff15e76e77c9dc3f49969ca9a93f309 | 662,111 |
import os
def run_in_conda_env(conda_path, env, cmds_list, verbose=True):
"""
conda_path - path to comda command
env - conda environment name
cmds_list - a list of commands
This function runs all the commands in cmds_list in the specified
conda environment.
"""
add_path = "export PATH=... | 297d3421c06cd2998e48e142b38bd2447e65472f | 662,112 |
def cleanse(tarinfo):
"""Cleanse sources of nondeterminism from tar entries.
To be passed as the `filter` kwarg to `tarfile.TarFile.add`.
Args:
tarinfo: A `tarfile.TarInfo` object to be mutated.
Returns:
The same `tarinfo` object, but mutated.
"""
tarinfo.uid = 0
tarinfo.gid =... | d602288d95cde6e6a50ff2132dd68a58b1e49fe9 | 662,113 |
def StateToBinary(state):
"""
Binary String converter
"""
binary = ""
for col in range(4):
for row in range(4):
si = state[row, col]
binary += bin(si)[2:].zfill(8)
return binary | fefea2cac2099215fa75424d629ceeb3e23f2d03 | 662,115 |
def get_states(event_data):
"""
Returns a tuple containing the old and new state names
from a state_changed event.
"""
try:
old_state = event_data["old_state"]["state"]
except Exception as e:
old_state = None
try:
new_state = event_data["new_state"]["state"]
exce... | aa0938ab755943e58fe65243588fe8feac78302e | 662,117 |
def return_empty_query():
""" Wrapper for malformed query from URL
"""
return '', '', None | c7d6ef1f9965ab043208b000e56f59e2aa07a3f8 | 662,118 |
def get_roll_direction(index_list):
""" Return roll direction of sequence of indeces """
if (len(index_list) < 2):
return 'short'
is_out = True
is_in = True
for i in range(len(index_list) - 1):
if index_list[i + 1] <= index_list[i]:
is_out = False
if index_list[i ... | 693768c75db025a9b9d5fcf397da3be5d3584af2 | 662,119 |
def translate(word, language, T):
"""
Force the translation of "word" in "language".
Restore the state of T before returning.
@param word: Word or text translate.
@param language: The language used by the translator.
@param T: The usual "T" translator.
@return: The text translated in the req... | 6a8428afe5b9eac69645d979a6a386e5eed2a2cb | 662,120 |
import itertools
def get_lag_sizes(list_times, kappa, varpi):
"""
Compute the number of event of type :math:`i` with at least :math:`h`
predecessors of type :math:`j`, for all :math:`i,j \\in [d]`,
:math:`h \\in [\\kappa(j,i,N^i_T)]`.
Parameters
----------
list_times : `list` of np.ndarra... | 02c57f14e0127b948e3654f4a0ae6a5d63e5f97b | 662,121 |
def inherits_from(obj, a_class):
"""
Return:
True if obj is instance of class that it inherits from or is subcls of
"""
return (type(obj) is not a_class and issubclass(type(obj), a_class)) | 5d39ee3502e5b9d8abfa0857cbffa6e4c44be8d8 | 662,122 |
def cd2d(cd, e):
"""Transform from *cd* index value to *d* count value, using the
*e.css('ch')* (column depth) as column measure."""
if cd is None:
d = 0
else:
# Overwrite style from here.
d = cd * (e.css('cd', 0) + e.gd) - e.gd
return d | 38c2b7236738f0ece42c818ff79a1b88e0c26493 | 662,123 |
def num2filename(x,d):
"""
Takes a number and returns a string with the value of the number, but in a
format that is writable into a filename.
s = num2filename(x,d) Gets rid of decimal points which are usually
inconvenient to have in a filename.
If the number x is an integer, then s = s... | 505b7917ba6a578302b467868ffe7f84c9004e3f | 662,124 |
import unicodedata
import re
def clean(value):
"""Replaces non-ascii characters with their closest ascii
representation and then removes everything but [A-Za-z0-9 ]"""
normalized = unicodedata.normalize('NFKD', value)
cleaned = re.sub(r'[^A-Za-z0-9 ]','',normalized)
return cleaned | e9e11d4828f0b87a704b6f92ea2fd98058c8fd67 | 662,125 |
def filter_params(model, prefix):
"""Return a list of model parameters whose names begin with a prefix"""
return [p for p in model.parameters if p.name.startswith(prefix)] | 2d07d654e373a334bbf91ef60852ebf620bfc68b | 662,126 |
def add_classes_to_field(field, extra_classes):
""" Adds extra CSS classes to the form widget """
classes = field.field.widget.attrs.get("class", "").split()
classes.extend(extra_classes.split())
field.field.widget.attrs["class"] = " ".join(sorted(set(classes)))
return field | ceefd62930f9fbefd25e0e59344121c9fd2993dd | 662,127 |
import os
import time
import logging
def markdown_trace_handler(dir_name: str, rank: int = 0):
"""This handler can be used inside torch.profiler call to output
tables in markdown format"""
def _handler_fn(prof) -> None:
if not os.path.isdir(dir_name):
try:
os.makedirs(... | f592f329ab99f1e34e6ecdc6bdc1f54a8e79e0f9 | 662,128 |
import click
import os
def validate_input(ctx, param, value):
"""Validate the "-i" option"""
result = list()
for input_str in value:
parts = input_str.strip().split(",")
if len(parts) == 2:
parts = tuple(parts)
elif len(parts) == 1:
parts = tuple(["Filename:... | a473ee102ae4212c019288416389438064d7c663 | 662,129 |
from typing import List
from typing import Optional
from typing import Tuple
from typing import Dict
def make_dataset(
paths: List[str],
extensions: Optional[Tuple[str, ...]] = None,
) -> Tuple[List[Tuple[str, int]], Dict[bytes, int]]:
"""
Map folder+classnames into list of (imagepath, class_i... | 1e33b85dc1b304e47a2a8000634a3bff73eb5dbc | 662,130 |
def do_nothing(list_of_words):
"""Return the argument unchanged."""
return list_of_words | bf37ebf6f980d6df5633ac27ec3888667df9b0a9 | 662,131 |
import argparse
def parse_arguments():
"""
Parse arguments for remove variants by annoation and hotspot tagging module
:return:
"""
parser = argparse.ArgumentParser(prog='Remove_by_Annotation_w_hotspots.py', description=' This tool helps to remove variant by annotation and genomic region, and tag... | 2b95f8dfb1befceea396a829b3fed631b98b21f6 | 662,133 |
def camel_case_to_lower(name):
"""
:Examples:
>>> camel_case_to_lower('squareRoot')
'square_root'
>>> camel_case_to_lower('SquareRoot')
'square_root'
>>> camel_case_to_lower('ComputeSQRT')
'compute_sqrt'
>>> camel_case_to_lower('SQRTCompute')
'sqrt_compute'
"""
lowername ... | 3172601fd2e827fc0c34fb61135d713901c54a08 | 662,134 |
def num_examples_per_epoch(split):
"""Returns the number of examples in the data set.
Args:
split: name of the split, "train" or "validation".
Raises:
ValueError: if split name is incorrect.
Returns:
Number of example in the split.
"""
if split.lower().startswith('train'):
return 100000
el... | 05362a25d28838994d3cf0b6dbc3818cff6a7e37 | 662,135 |
import re
def find_(word, stream, ignore_case=True):
"""Find the `word` in the `stream`.
:param word: str, word or pattern to be searched in stream
:param stream: str, stream to be searched in
:param ignore_case: whether to ignore the case
:returns: the corresponding `word` (could be of different... | 005b79edc262559386465ef2436c5d0841bdf822 | 662,136 |
def flipcheck(content):
"""Checks a string for anger and soothes said anger
Args:
content (str): The message to be flipchecked
Returns:
putitback (str): The righted table or text
"""
# Prevent tampering with flip
punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─"""
tamperdict =... | 9f27f2682ee21385120f1bd2ca5da4174ed2cd37 | 662,137 |
import json
import importlib
def load_mesh(filename):
"""
Open a json file and load the mesh into the target class
As long as there are no namespace conflicts, the target __class__
will be stored on the properties.HasProperties registry and may be
fetched from there.
:param str filename: nam... | 2ef7f4148a79c4015cfa6ec1077fb993c6091e45 | 662,138 |
def coroutine(func):
"""
A decorator to create our coroutines from generator definitions.
Calling a generator function does not start running the function!
Instead, it returns a generator object. All co-routines must be "primed"
by calling ``next`` or ``send` to run up until the first ``yield``.
... | 58ff0bd1f9597b8168d4bb35b794c039791623d3 | 662,139 |
def clean_component(doc):
""" Clean up text. Make lowercase and remove punctuation and stopwords """
# Remove punctuation, symbols (#) and stopwords
doc = [tok.text.lower() for tok in doc if (not tok.is_stop
and tok.pos_ != 'PUNCT' and
... | a22af7eb061360ae65ef1a90eedda3df74c16837 | 662,140 |
import json
def convert_to_nameshark(group_name, contacts):
"""
Convert a list containing contact info into JSON for Name Shark.
:param group_name: the Name Shark group to use.
:param contacts:
:return: the list containing contact info extracted from a vCard.
"""
shark = {'name': group_na... | df07ad16cf4b40879c4d7f85e670ecb379e3b365 | 662,141 |
def OBJ_SET(key, value):
"""this is the same as lambda obj, eng: obj.__setitem__(key, value)
@var key: str, key of the object to retrieve
@var value: anything
@attention: this call is executed when the workflow is created
therefore, the key and value must exist at the time
(obj and eng d... | d267d6eef479703ac833a0b597ce6cac299a905c | 662,142 |
from typing import List
def _get_key_hashes(rec: dict) -> List[str]:
"""Get key hashes in ledger state snapshot record."""
return [r[0]["key hash"] for r in rec] | 0a4d2684f1c38c5dce2c711d6852f9e43c42faa7 | 662,143 |
from pathlib import Path
import pandas
def readasc(fn: Path, Nrows: int) -> pandas.DataFrame:
"""Use Pandas to load 100s of MB SAC_ASC text data."""
dat = pandas.read_csv(fn, sep=r"\s+", nrows=Nrows, skiprows=30)
return dat | e4066d7fda676d569c8d0a2f12a074c303fec05f | 662,144 |
import re
def parse_output_areas(msg):
"""Parse create area message and return area number"""
res = re.search(r"(OUTPUT AREAS =\s*)([0-9]+)", msg)
if res is not None:
return int(res.group(2)) | 9265a6e8501b513549872264788c23655dd3f106 | 662,145 |
def filter(df,column_name,field_value):
"""Filter a data frame to only include matches with field value in column_name"""
tmp_df = df[df[column_name].isnull() == False]
return tmp_df[tmp_df[column_name]==field_value] | f42eee7f02c0ff1e4e8b5766558f27dc3f5737d5 | 662,146 |
import torch
def g(x):
"""
R.H.S of PDE
"""
return torch.sin(x) + 4*torch.sin(4*x) - 8*torch.sin(8*x) + 16*torch.sin(24*x) | d8e41a801e1a4ad6b6dd588e8060056af8018bff | 662,147 |
from typing import List
from typing import Dict
def get_col_index(name: List, worksheet) -> Dict:
""" return a list of the column numbers if it matches """
indexes = dict()
for rows in worksheet.iter_rows(min_row=1, max_row=1, min_col=1):
for column in rows:
if column.value in name:
... | af3ac199dec317a2ec3666c3152ecbe96e7c031f | 662,148 |
from typing import Iterable
import os
import glob
def check_output_files(
output_folder: str,
file_regex: Iterable[str]
) -> str:
"""
Check if given files can be found within given output folder, based on
given file regexes.
If no corresponding file is found, an OSError is raised.
... | 85f8fc5b9ca0a62c6d39b0ded6f289a2abe98a62 | 662,149 |
import fnmatch
def ignore_rule_matches_result(ignore_rule, pa11y_result):
"""
Returns a boolean result of whether the given ignore rule matches
the given pa11y result. The rule only matches the result if *all*
attributes of the rule match.
"""
return all(
fnmatch.fnmatch(pa11y_result.g... | e3596b41fe8fbcc910154d0514c62dc29096fa6c | 662,150 |
def remove_namedtuple_defaultdoc(cls):
"""This decorator removes the __doc__ which namedtuples get
automatically for their __new__() constructor and their fields
"""
for f in cls._fields:
getattr(cls, f).__doc__ = None
cls.__new__.__doc__ = "{}({})".format(cls.__name__, ",".join(cls._fields)... | 7ff633df03a29cf12d7f24d7d2f86a20db9352e3 | 662,151 |
def DecodeMAC(macbin):
"""Turn the given binary MAC address into a printable string."""
assert len(macbin) == 6
return ':'.join(['%02x' % ord(i) for i in macbin]) | 4c44f6e5d4a5d7430a2ccef6c94ff238ac71a894 | 662,152 |
import pkg_resources
def get_data(filename):
"""Gets a data file from the package.
Args:
filename: The name of the data file as located in the package data
directory.
Returns:
A readable file-like object for the data file.
"""
path = "data/" + filename
return pkg_r... | 91a55af8e6446fa896bd1f6fc3253dfbae0b4e57 | 662,153 |
def get_time_groupby_name(time_groups):
"""Return a name reflecting the temporal groupby operation."""
# Define time groupby name
time_groups_list = []
for k, v in time_groups.items():
if v == 1:
time_groups_list.append(k)
else:
time_groups_list.append(str(v) +... | 22bd58bb533c2c85f2cb4d6342d122d6e3b8ad41 | 662,154 |
def to_numpy(tensor):
"""
If the tensor requires gradients, then detach it from the computation graph, move it to the CPU, and
convert it to a NumPy array. Otherwise, just move it to the CPU and convert it to a NumPy array
:param tensor: A PyTorch tensor
:return: the tensor as a numpy array.
... | e343e1e07e0b5e22ddaeb546fef84a88a2ba83cd | 662,155 |
import os
def find_packages(top):
"""
Find all of the packages.
"""
packages = []
for d, dirs, _ in os.walk(top, followlinks=True):
if os.path.exists(os.path.join(d, '__init__.py')):
packages.append(os.path.relpath(d, top).replace(os.path.sep, '.'))
elif d != top:
... | ca9df302443ae951e88177627891f014953bc48d | 662,156 |
def _create_tf_matrix(freq_matrix: dict) -> dict:
"""
Returns a term frequency matrix for the given frequency matrix.
:param freq_matrix: The frequency matrix to be summarized.
:return: A term frequency matrix for the given frequency matrix.
"""
tf_matrix = {}
for sentence, freq_table in fre... | e399ebd02c4533bdac3d9ff346adc7a2b5477e09 | 662,157 |
def BinsTriangleInequality(d1, d2, d3):
""" checks the triangle inequality for combinations
of distance bins.
the general triangle inequality is:
d1 + d2 >= d3
the conservative binned form of this is:
d1(upper) + d2(upper) >= d3(lower)
"""
if d1[1] + d2[1] < d3[0]:
return False
i... | fa0a20f5471badd9a8436d4f03102becf306d26d | 662,158 |
def checkout(cash: float, list: dict) -> float:
"""
build a function that sums up the value of the grocery list and subtracts that
from the cash passed into the function.
return the "change" from the cash minus the total groceries value.
"""
# values = list.values()
total = sum(list.values()... | 6c00524580d31c5e0f7295a73d451742923c497c | 662,159 |
def ConfitureBackwards(k, V, S, M):
""" int x list[int] x int x list[list[int]] -> list[int]
returns a list of integers corresponding to
the number of jars used of each capacity
type V[i] in the optimum solution given by M
"""
# A: list[int]
A = [0]*k
# s, i: int
s = S
i = k
while s != 0:
if (i > 0) and (M... | 4f68b86ae0bc9274d6065c79e94742c92c9834fb | 662,160 |
def dump(objs, docid, changed_only=True):
""" Serialize a sequence of Bokeh objects into JSON
Args:
objs (seq[obj]) : a sequence of Bokeh object to dump
docid (str) : an ID for a Bokeh Document to dump relative to
changed_only (bool, optional) : whether to dump only attr... | d7386a285889d57f0ef7b807b553f12cbee5e30c | 662,161 |
from pathlib import Path
from typing import Set
def get_local_projects(path: Path) -> Set[str]:
"""
Returns all the projects (directories) under
`path`.
"""
return {f.name for f in path.iterdir() if f.is_dir() and not f.name.startswith(".")} | 0fe6c86e09c93a7026ba7d497ba2ee869cb64bd4 | 662,162 |
from typing import Any
import lzma
import pickle
def load(input_path: str) -> Any:
"""
Unpickle the object.
:param input_path: Input path of pickled object.
:return: The object.
"""
with lzma.open(input_path, 'rb') as reader:
reto = pickle.load(reader)
return reto | f306614cb286ebc393dc211bcd5d839d39bef5b2 | 662,163 |
def _parse_values(value_string):
"""Parse comma-delimited values from a string"""
values = list()
for raw in value_string.split(','):
raw = raw.strip()
if len(raw) > 1 and raw[0] == '"' and raw[-1] == '"':
raw = raw[1:-1].strip()
values.append(raw)
return values | 178119c2ae59d97e297c6d58abeb85c4e94deb99 | 662,164 |
def replace_url_func_wrap(func):
"""替换调试url"""
def _func(*args, **kwargs):
url = func(*args, **kwargs)
if not url:
return url
url = url.replace("?ws=127.0.0.1/", "?ws=/") # 避免最后生成的url错误
return url.replace(
"chrome-devtools-frontend.appspot.com",
... | 1f128ca251c43154cdf4f556145610915e43fae6 | 662,165 |
import time
def datecode(t=None, local=False):
"""The date code incorporates both the unix time and the date in either the local timezone (respecting DST) or UTC (aka GMT). It is convenient for naming ops subdirectories or tagging events for easy sorting."""
if t == None:
t = time.time()
zt = tim... | dbf5b38dc47eff225fbe394374cd61ed589d68ee | 662,166 |
def valid_request_body_with_existing_priority(valid_request_model):
"""
A fixture for creating a request body with existing priority number
for a client.
Args:
valid_request_model (Model): a valid request model created by a
fixture.
"""
return {
'title': 'Add PayPal ... | 2745a966e13742353f870ee6f049b9271a9e8eb2 | 662,167 |
def read_elastodyn_dat(path):
"""Get dictionary from an elastodyn dat file"""
d = {}
with open(path, 'r') as ed:
end = False
for line in ed:
contents = line.split()
if contents[0] == 'OutList':
end = True
if end:
break
... | 4867050aab1b5497f6f9b9a91014113978e69103 | 662,168 |
def evaluate(pop,fitness_func,fit_col=-1,extra_cols=2):
"""
Args
pop (np.array) : The matrix of solution to score
fitness_func (obj): The fitness function
Returns
np.array :
"""
for i in range(pop.shape[0]):
pop[i,fit_col] = fitness_func(pop[i,... | 4d6bfa733ca13b91174ca0d34465b68757d2ee94 | 662,169 |
import stat
def hardlinkable(mode):
"""return True if we support hardlinked items of this type"""
return stat.S_ISREG(mode) or stat.S_ISBLK(mode) or stat.S_ISCHR(mode) or stat.S_ISFIFO(mode) | 76f83d0000111a96168984cf88acb4017e6dc859 | 662,170 |
import importlib
def import_obj(obj_str):
"""
handles input string as module.object
and imports the module and returns the object
"""
if ':' in obj_str:
modname, objname = obj_str.split(':')
else:
modname, objname = obj_str.rsplit('.', 1)
mod = importlib.import_module(modn... | 3c37e0139c89485ae4816f53efb002a796255d0d | 662,171 |
import json
def get_file_json(path):
"""Read a file and return parsed JSON object."""
with open(path, 'r') as f:
return json.load(f) | 1fd08b5b196ed03f5c871abd117e15ba67b02fcf | 662,172 |
def levenshtein(s1, s2):
"""
The levensteins distance of two strings.
"""
s1 = s1.lower()
s2 = s2.lower()
if len(s1) < len(s2):
return levenshtein(s2, s1)
if len(s2) == 0:
return len(s1)
previous_row = list(range(len(s2) + 1))
for i, c1 in enumerate(s1):
curre... | 13e8a868f12914ec4da90e7fbbf8da145a0defb8 | 662,174 |
def read_gold_props(gold_props_file):
""" Read gold predicates from CoNLL-formatted file.
"""
gold_props = []
props = []
with open(gold_props_file, 'r') as f:
for line in f:
line = line.strip()
if line == '':
gold_props.append(props)
props = []
else:
props.append(... | f4b4481b2f2180afba6e1153712b8d2f281cda95 | 662,175 |
def radix(input_list):
"""Radix sort function."""
if isinstance(input_list, list):
buckets = {x: [] for x in range(10)}
num_sorts = len(str(max(input_list)))
input_list = [str(num) for num in input_list]
for idx, num in enumerate(input_list):
if len(num) < num_sorts:
... | 1761b3efb626ce66b9b49c4352643897227aeb1a | 662,177 |
def swagger_escape(s): # pragma: no cover
"""
/ and ~ are special characters in JSON Pointers,
and need to be escaped when used literally (for example, in path names).
https://swagger.io/docs/specification/using-ref/#escape
"""
return s.replace('~', '~0').replace('/', '~1') | 8f6e7112a565a6840fd046446cff77e11ee8425a | 662,178 |
def custom_telnet_service(device, dest_prompt, ip, username, password, opts="", cmd=[]):
"""Telnet service connection
:param device: client device from which the telnet session is initiated
:type device: object
:param dest_prompt: target device prompt
:type dest_prompt: list of prompt
:param ip... | 96b469bd6c30c874b90f34fa0a69524f059bce1d | 662,179 |
import sys
from pathlib import Path
def create_marge_pdf_file_name(pdf_files_):
"""
保存ファイル名を返す(先頭と末尾のファイル名で作成)
arg2:
指定あり: 指定したファイル名を返す
指定なし: 先頭と末尾のファイル名をハイフンで結合したファイル名を返す
:param
pdf_files_(list): pdfファイルのリスト
:return:
保存するファイル名を返す
"""
args = sys.argv
... | 2d6e32d4da445f6bdc3bcf933ad4b7fcc45ef441 | 662,180 |
import argparse
def parse_args():
"""Define and handle command-line args, computing defaults as needed."""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter, # disable line wrapping, and assume help strings are already formatted
description="Describe what your program does.... | 24c53cc386e1abe72a6cf5d77120967f0d495f6e | 662,181 |
def argument_encoding(arg):
"""Encodes the argument according to Contract ABI specifications."""
encoded_argument = str(hex(len(arg)))[2:].zfill(64)
encoded_argument = (
encoded_argument + arg.encode("utf8").hex().ljust(64, "0").upper()
)
return encoded_argument | 9d65c8134d622c47830db1535940fee5a726df85 | 662,183 |
def make_ffmpeg_section_args(
filename,
start,
length,
*,
before_options=(),
options=(),
):
"""Returns a list of arguments to FFmpeg
It will take the required amount of audio starting from the specified start
time and convert them into PCM 16-bit stereo audio to be piped to stdout.
... | 4599368c2b44a51da1ea1c2935305a4423ae581d | 662,184 |
def mse_node(w_samples, y_sum, y_sq_sum):
"""Computes the variance of the labels in the node
Parameters
----------
w_samples : float
Weighted number of samples in the node
y_sum : float
Weighted sum of the label in the node
y_sq_sum : float
Weighted sum of the squared ... | cd637bb01bc334a20d83179f5e9925e505fb9912 | 662,186 |
def GetKeyIdFromResourceName(name):
"""Gets the key id from a resource name. No validation is done."""
return name.split('/')[5] | 3f6d2a06adfebe684e8b1f637ebfc12417169b2a | 662,187 |
def encode(value, encoding='utf-8'):
"""Encode given Unicode value to bytes with given encoding
:param str value: the value to encode
:param str encoding: selected encoding
:return: bytes; value encoded to bytes if input is a string, original value otherwise
>>> from pyams_utils.unicode import enc... | bd417a0ef50ef0f9a48594fd2b9c049e98932bc8 | 662,188 |
def intersect(bboxA, bboxB):
"""Return a new bounding box that contains the intersection of
'self' and 'other', or None if there is no intersection
"""
new_top = max(bboxA[1], bboxB[1])
new_left = max(bboxA[0], bboxB[0])
new_right = min(bboxA[0]+bboxA[2], bboxB[0]+bboxB[2])
new_bottom = min(bboxA[1]+bboxA[3], bb... | d902da880f1c833ed9899d6e4165647edef8642d | 662,189 |
import math
def rotate(x, y, alpha, xCenter = 0, yCenter = 0):
"""
rotate a point by a given angle
@param x x-coordinate of the point that needs to be rotated
@param y y-coordinate of the point that needs to be rotated
@param alpha rotation angle [0..2pi radians]
@param xCenter x-coordinate of the origin (0 is ... | e043e58d28089a972238eafaa669ea29f8efd669 | 662,190 |
import click
from pathlib import Path
def cv_options(f):
"""Options specific for CV (not used in CCCV)."""
f = click.option('--out', type=click.Path(), help='Output file path for misclassification file.')(f)
f = click.option('--optimize_n_iter', type=int, default=10,
help='Number of p... | a02978a2304f88be0a027a53e2f1a82049f87532 | 662,191 |
import re
def remove_tag(entry, alltag=False):
"""remove SRT and ASS tags
if alltag, NoTagApp specials ([b]/[i]/[u]) tag are removed too
"""
tag_pattern = r"{\\.*?}|</?font.*?>|</?.*?>"
if alltag:
tag_pattern += r"|\[/?.?\]"
return re.sub(tag_pattern, "", entry) | 5d9197888cb727d97f713fed3cb1d09defd89adf | 662,192 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.