content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def ignore_paths(path_list, ignore_patterns, process=str):
"""
Go through the `path_list` and ignore any paths that match the patterns in `ignore_patterns`
:param path_list: List of file/directory paths.
:param ignore_patterns: List of nukeignore patterns.
:param process: Function to apply to every ... | 39,900 |
def check_static(url):
"""
Check viability of static links on cf.gov home page and sub-pages.
Example call to check static assets in production:
./cfgov/scripts/static_asset_smoke_test.py -v /ask-cfpb/ /owning-a-home/
Example of local check of home page:
./cfgov/scripts/static_asset_smoke_test... | 39,901 |
def test_multi_range_indexes_empty():
"""Return empty index array if all ranges of zero length."""
ranges = np.array([[0, 0], [0, 0]])
indexes_exp = np.array([])
np.testing.assert_equal(pu.multi_range_indexes(ranges), indexes_exp) | 39,902 |
def validation_error_handler(err):
"""
Used to parse use_kwargs validation errors
"""
headers = err.data.get("headers", None)
messages = err.data.get("messages", ["Invalid request."])
schema = ResponseWrapper()
data = messages.get("json", None)
error_msg = "Sorry validation errors occurr... | 39,903 |
def handle_ec2_launch_event(instance_id):
"""
Purpose: Handler for EC2 launch event
Parameters: Instance Id
Returns:
Raises:
"""
utl.put_line_in_log('EC2 Launch Handler', 'thin')
if instance_id is not None:
logger.info("Received EC2 launch notification for instance-id: " + str... | 39,904 |
def is_element(a, symbol="C"):
""" Is the atom of a given element """
return element(a) == symbol | 39,905 |
def create_call_status(job, internal_storage):
""" Creates a call status class based on the monitoring backend"""
monitoring_backend = job.config['lithops']['monitoring']
Status = getattr(lithops.worker.status, '{}CallStatus'
.format(monitoring_backend.capitalize()))
return Status(j... | 39,906 |
def file_handler() -> RotatingFileHandler:
"""Create a file-based error handler."""
handler = RotatingFileHandler(
Path("log") / "error.log",
maxBytes=50_000,
backupCount=5,
delay=True,
)
handler.setLevel(logging.ERROR)
handler.setFormatter(
logging.Formatter(... | 39,907 |
def help(
section,
device=None,
fout=sys.stdout,
show_other_sections=True,
markdown_format=False):
"""Generates help text.
Args:
section: A section number.
device: Which device to create help for.
fout: Where to stream the help text.
show_other_sections: Whether or n... | 39,908 |
def get_additional_node_groups(node_name, deployment_id):
"""This enables users to reuse hosts in multiple groups."""
groups = []
try:
client = get_rest_client()
except KeyError:
return groups
deployment = client.deployments.get(deployment_id)
for group_name, group in deployment.... | 39,909 |
def is_requirement(line):
"""
Return True if the requirement line is a package requirement.
Returns:
bool: True if the line is not blank, a comment, a URL, or
an included file
"""
return line and not line.startswith(('-r', '#', '-e', 'git+', '-c')) | 39,910 |
def test_create_pad_account_user_error(session):
"""Test create account."""
# Create a pending account first, then call the job
account = factory_create_pad_account(auth_account_id='1')
cfs_account: CfsAccount = CfsAccount.find_effective_by_account_id(account.id)
assert cfs_account.status == CfsAcco... | 39,911 |
def sort_even(l: list):
"""This function takes a list l and returns a list l' such that
l' is identical to l in the odd indicies, while its values at the even indicies are equal
to the values of the even indicies of l, but sorted.
>>> sort_even([1, 2, 3])
[1, 2, 3]
>>> sort_even([5, 6, 3, 4])
... | 39,912 |
def get_element_material_name(element: int) -> str:
"""Gets the element material name
Args:
element (int): element ID
Returns:
bool: element material name
""" | 39,913 |
def handler(event, _):
"""
Handler entrypoint - see stack_outputs for implementation details
:param event: The CloudFormation custom resource event
:return: PhysicalResourceId
"""
helper(event, _) | 39,914 |
def pden(s, t, p, pr=0):
"""
Calculates potential density of water mass relative to the specified
reference pressure by pden = dens(S, ptmp, PR).
Parameters
----------
s(p) : array_like
salinity [psu (PSS-78)]
t(p) : array_like
temperature [℃ (ITS-90)]
p : array_li... | 39,915 |
def menuevnikto():
"""
Menu Nikto Metodo de Evasion
"""
# os.system('clear')
print ("Seleccione un metodo de evasion para el analisis de NIKTO")
print ("\t1 - 1 Random URI encoding (non-UTF8)")
print ("\t2 - 2 Directory self-reference (/./)")
print ("\t3 - 3 Premature URL ending")
pri... | 39,916 |
def SWAP(first: int, second: int, control: typing.Union[int, list] = None, power: float = None) -> QCircuit:
"""
Notes
----------
SWAP gate, order of targets does not matter
Parameters
----------
first: int
target qubit
second: int
target qubit
control
int or... | 39,917 |
def stable_normalize(x, etha=1.0e-8):
""" Numerically stable vector normalization
"""
n = np.linalg.norm(x, axis=-1, keepdims=True)
if n < etha:
n = etha
return x / n | 39,918 |
def Word2VecFeatureGenerator(df):
"""
Finds and returns word embedding for the head and body
and computes cosine similarity.
Input: DataFrame
Returns list(headlineVec, bodyVec, simVec)"""
t0 = time()
print("\n---Generating Word2Vector Features:---")
df["Headline_unigram_vec"] = df... | 39,919 |
def help():
"""launch the pyABF project page in a browser."""
import webbrowser
webbrowser.open("http://github.com/swharden/pyABF") | 39,920 |
def reachable(Adj, s, t):
"""
Adj is adjacency list rep of graph
Return True if edges in Adj have directed path from s to t.
Note that this routine is one of the most-used and most time-consuming
of this whole procedure, which is why it is passed an adjacency list
rep rather than a list of ver... | 39,921 |
def a_test2_predict_is_nans():
"""
Tests that the predictions in-sample are not NaNs
"""
model = ARIMAX(formula="y ~ x1 + x2", data=data, ar=2, ma=2, family=Exponential())
x = model.fit()
x.summary()
assert(len(model.predict_is(h=5).values[np.isnan(model.predict_is(h=5).values)]) == 0) | 39,922 |
def remove_links(
actor: Actor, company: Company, *, facebook=False, linkedin=False, twitter=False
) -> Response:
"""Remove links to all existing Online Profiles."""
response, _ = update_profiles(
actor,
company,
facebook=facebook,
linkedin=linkedin,
twitter=twitter,
... | 39,923 |
def get_basis_psd(psd_array, notes):
"""Get avg psd from the training set (will serve as a basis)"""
psd_dict = {}
psd_basis_list = []
syl_basis_list = []
unique_note = unique(notes) # convert note string into a list of unique syllables
# Remove unidentifiable note (e.g., '0' or 'x')
if '... | 39,924 |
def _get_columns(statement):
"""Get the available columns in the query `statement`.
:param statement: A SQL SELECT statement.
:returns: A list of columns that are being selected.
"""
expecting_columns = False
for token in statement.tokens:
if token.is_whitespace():
pass
... | 39,925 |
def config_logging(level=logging.INFO, section="main", mp=False) -> Path:
"""Configures logging to log to a file and screen
mp stands for multiprocessing, didn't want to override that package
"""
# NOTE: it turns out that subprocess calls, pytest, etc
# Seems to automatically add handlers, even if... | 39,926 |
def date_time(watch, dt):
"""
This method updates clock every second.
:param watch: It is clock.
:param dt: It is for handling callback input.
:return:
"""
watch.text = strftime("%H:%M:%S",
localtime()
) | 39,927 |
def convert_yaml(source: str, target: str, replace: bool = True) -> None:
"""Convert the given YAML source file into its JSON equivalent.
If the ``replace`` flag is set, this will additionally extract any
keys stored under the top-level ``variables`` key of the YAML file.
These keys will not be includ... | 39,928 |
def generate_final_json():
"""
Final dict structure:
{
"LASOT": {
"seq1": {
"00": {
"query1": [.......]
}
}
},
"GOT10K": {
......
}
}
"""
final_dict = {}
with open("final_... | 39,929 |
def create_conv(in_channels, out_channels, kernel_size, order, num_groups, padding=1):
"""
Create a list of modules with together constitute a single conv layer with non-linearity
and optional batchnorm/groupnorm.
Args:
in_channels (int): number of input channels
out_channels (int): numb... | 39,930 |
def logging_config(level, log_file=None):
"""
Set desired log level and designate a log file.
:param level: Available levels : debug, info, notset
:type level: str
:param log_file: path to log file
:type log_file: str or None
"""
if level == "debug":
logger_factory.level = loggi... | 39,931 |
def expand_json(metadata, context=DEFAULT_CONTEXT):
"""
Expand json, but be sure to use our documentLoader.
By default this expands with DEFAULT_CONTEXT, but if you do not need this,
you can safely set this to None.
# @@: Is the above a good idea? Maybe it should be set to None by
# default... | 39,932 |
def prepare_test_data():
"""
Load data01.nc and manipulate to create additional test data.
Used to load data into data_dict below.
"""
# Dictionary in which to store data
data_dict = {}
# Load data01.nc Dataset
data01 = xr.open_dataset(os.path.dirname(__file__)+'/data/data01.nc',
... | 39,933 |
def path(path_list):
"""
Returns an absolute path for the given folders structure
:path_list: receives a list type object where each element is an folder and
it can end in a file name
"""
path = MAIN_FOLDER
for folder in path_list:
path = os.path.join(path, folder)
return path | 39,934 |
def get_kubernetes_bearer_token():
"""Reads the bearer token required to call the Kubernetes master from a file.
The file is installed in every container within a Kubernetes pod by the
Kubelet. The path to the file is documented at
https://github.com/GoogleCloudPlatform/kubernetes/blob/master/docs/accessing-th... | 39,935 |
def show(c, verbose, config):
"""Show current position."""
file = os.path.expanduser(config["file"])
move = config["move"]
level = int(config["level"])
pointer = config['pointer']
maxtime = int(config['maxtime'])
bookmark = config["bookmark"]
# If filename is written in bookmark, read bo... | 39,936 |
def main():
"""Wrapper around tokenization that takes care of argument parsing and prints change stats to STDERR."""
# parse arguments
parser = argparse.ArgumentParser(description='Tokenizes a given text')
parser.add_argument('-i', '--input', type=argparse.FileType('r', encoding='utf-8', errors='surroga... | 39,937 |
def test_item_delete(rocreate, roitemdelete):
"""
GIVEN: Running order and roItemDelete message (STORY 1 for STORY ONE)
EXPECT: Running order with STORY ONE and no STORY 1
"""
ro = RunningOrder.from_file(rocreate)
id = ItemDelete.from_file(roitemdelete)
d = ro.dict
assert len(d['mos']['r... | 39,938 |
async def amireallyalive(alive):
""" For .alive command, check if the bot is running. """
await alive.edit("`என்னைப் பயன்படுத்தியதற்கு நன்றி🤖") | 39,939 |
def update_requirements(name, version=None, requirements_file='requirements.txt'):
"""
Upgrade or add `package_name` with `new_version` to the `requirements_file`
requirements file. Write back requirements sorted with name and version
canonicalized. Note: this cannot deal with hashed or unpinned require... | 39,940 |
def test_parseDepthData(df):
"""
test the generation of sample_pd
"""
df['DPR'] = df['A'] + ',' + df['B'] # emulate the DPR data
parseDepthData(df) | 39,941 |
def ci_build(ctx, full=False, recreate=False):
"""Simulate a CI build."""
tox_cmd = "tox -r" if recreate else "tox"
if full:
ctx.run(f"rm -rf {DOCS_BUILD_PATH} docs/source")
ctx.run(tox_cmd)
else:
ctx.run(f"{tox_cmd} -e clean,lint,py38,docs,report") | 39,942 |
def parsemsg(s, encoding="utf-8"):
"""Parse an IRC Message from s
:param s bytes: bytes to parse
:param encoding str: encoding to use (Default: utf-8)
:returns tuple: parsed message in the form of (prefix, command, args)
"""
s = s.decode(encoding, 'replace')
prefix = u("")
trailing =... | 39,943 |
def concatenate_unique(la, lb):
"""Add all the elements of `lb` to `la` if they are not there already.
The elements added to `la` maintain ordering with respect to `lb`.
Args:
la: List of Python objects.
lb: List of Python objects.
Returns:
`la`: The list `la` with missing elements from `lb`.
""... | 39,944 |
def email_last_send_for_sub(sub_id):
"""Return when an email was last sent for a subscription, or None."""
last_sent = db.get('email_sub_last_sent:{}'.format(sub_id))
if last_sent is not None:
return datetime.datetime.strptime(last_sent, '%Y-%m-%dT%H:%M:%SZ') | 39,945 |
def is_output_op(node):
"""Return true when the node is the output of the graph."""
return node.WhichOneof("op_type") == "output_conf" | 39,946 |
def plot_samples_close_to_score(ood_dict: dict, dataset_name: str, min_score: float, max_score: float, n: int = 32,
do_lesional: bool = True, show_ground_truth: bool = False,
print_score: bool = False) -> None:
"""Arrange slices in a grid such that eac... | 39,947 |
def avail_images(call=None):
"""
REturns available upcloud templates
"""
from salt.cloud.exceptions import SaltCloudException
if call == 'action':
raise SaltCloudException(
'The avail_locations function must be called with -f or --function.'
)
manager = _get_manager... | 39,948 |
def batch_dataset(x, batch_size):
"""
partitions dataset x into args.batch_size batches
TODO: ensure that x.shape[0] is divisible by batch_size so no leftovers
"""
size_modulo = len(x) % batch_size # hack to ensure data is batches successfully
if size_modulo != 0:
x = x[:-size_modulo]
partitioned = np... | 39,949 |
def _verify_email_upload(transfer_id: str, session: requests.Session) -> str:
"""Given a transfer_id, read the code from standard input.
Return the parsed JSON response.
"""
code = input('Code:')
j = {
"code": code,
"expire_in": WETRANSFER_EXPIRE_IN,
}
r = session.post(WET... | 39,950 |
def read_file(filename=""):
"""
read_file - read a file and print it to stdout
"""
with open(filename, encoding="utf-8") as f:
print(f.read(), end="") | 39,951 |
def plot(density_map, name):
"""
@brief density map contour and heat map
"""
print(np.amax(density_map))
print(np.mean(density_map))
fig = plt.figure(figsize=(4, 3))
ax = fig.gca(projection='3d')
x = np.arange(density_map.shape[0])
y = np.arange(density_map.shape[1])
x, y = np... | 39,952 |
def run(cfg: config.Loader, logger: logging.Logger, uri: str, **kwargs) -> str:
"""
Download the URI and return the local filename.
kwargs are passed through to ``run_local_task``, so ``run_dir`` and ``logger_prefix`` may be
useful in particular.
"""
from .error import RunFailed, DownloadFaile... | 39,953 |
def extract_eqhazard_data(input_file, output_file):
"""
Runs SimCenter's EQHazard tool and extracts the data in the desired format
The EQHazard tool documentation is available at:
https://github.com/NHERI-SimCenter/GroundMotionUtilities/tree/master/EQHazard
Notes:
This ... | 39,954 |
def envelope_generic(pshape, *args, **kwargs):
"""
Envelope for a given pulse shape at a given time or times.
Parameters
----------
pshape : str or function object
Pulse shape type or user-provided function.
Allowed string values are 'square', 'gauss', 'cos',
'flattop_gauss'... | 39,955 |
def sdb_longitude(longitude):
"""Return an 8 character, zero padded string version of the
longitude parameter.
**Arguments:**
* *longitude* -- Longitude.
"""
adjusted = (180 + float(longitude)) * 100000
return str(int(adjusted)).zfill(8) | 39,956 |
def run_qemu(kernel, machine='lm3s811evb', dump_file=None, dump_range=None):
""" Runs qemu on a given kernel file """
if not has_qemu():
return ''
# Check bin file exists:
assert os.path.isfile(kernel)
logger.debug('Running qemu with machine=%s and image %s', machine, kernel)
args = [... | 39,957 |
def is_allowed_location(location, allowed_location):
""""
Returns true if the location is allowed_location
Args:
location: location id
allowed_location: allowed_location
Returns:
is_allowed(bool): Is location allowed.
"""
if allowed_location == 1:
return True
... | 39,958 |
def gsl_isinf(*args, **kwargs):
"""gsl_isinf(double x) -> int"""
return _gslwrap.gsl_isinf(*args, **kwargs) | 39,959 |
def test_create_calculate_namespace_call(
mocked_get_function: mock.MagicMock, mocked_calculate_namespace: mock.MagicMock
):
"""
GIVEN mocked body and mocked get_function that returns a client function and True
for namespaced and mocked calculate_namespace
WHEN create is called with the body
... | 39,960 |
def abstract_clone(__call__, self, x, *args):
"""Clone an abstract value."""
def proceed():
if isinstance(x, AbstractValue) and x in cache:
return cache[x]
result = __call__(self, x, *args)
if not isinstance(result, GeneratorType):
return result
cls = resu... | 39,961 |
def Layout(
align_baseline: bool = None,
align_center: bool = None,
align_content_center: bool = None,
align_content_end: bool = None,
align_content_space_around: bool = None,
align_content_space_between: bool = None,
align_content_start: bool = None,
align_end: bool = None,
align_st... | 39,962 |
def plot_hist(df, cn, bins, xlabel=None, ylabel=None, fig_fn='hist.png', fig_fp=figure_fp):
"""
Plot histogram for any bin size
"""
if os.path.exists(figure_fp) == False:
os.makedirs(figure_fp)
data = df[cn].values
hist, bin_edges = np.histogram(data,bins) # make the hist... | 39,963 |
async def test_doorbell_event(hass, aioclient_mock):
"""Test doorbell press reports."""
aioclient_mock.post(TEST_URL, text="", status=202)
hass.states.async_set(
"binary_sensor.test_doorbell",
"off",
{"friendly_name": "Test Doorbell Sensor", "device_class": "occupancy"},
)
... | 39,964 |
def paint_hull(inputfile, hull={}):
"""Launches the emergency hull painting robot with the specified Intcode source file
Parameters
----------
inputfile: str
Path/Filename of Intcode source code
hull : dict<(int,int): int>
Initial state of the hull
"""
robot_pos = (0, 0)
... | 39,965 |
def get_token_expiration(parser: ConfigParser, profile: str) -> Tuple[str, str]:
"""Return token expiration date and whether it is expired.
Parameters
----------
parser : ConfigParser
Parser with all configuration files.
profile : str
Profile name.
Returns
-------
Tuple... | 39,966 |
def ensure_format(s: str, n_chars: int = None) -> str:
"""
Removes spaces within a string and ensures proper format
------
PARAMS
------
1. 's' -> input string
2. 'n_chars' -> Num characters the string should consist of. Defaults to None.
"""
assert isinstance(s, str), "Input... | 39,967 |
def test_hobolink_handles_erroneous_csv(app, monkeypatch):
"""
Tests that the code supports when Hobolink erroneously returns
a CSV where some column headers are repeated and only one contains
the actual data.
"""
with io.open('tests/static/split_columns_hobolink_export.pickle', 'rb') as f:
... | 39,968 |
def gamma_boundary_condition(gamma=-3):
"""
Defines boundary condition parameterized by either a scalar or list/iterable.
In the latter case, piecewise-interpolation on an equispaced grid over
the interior of (0, 1). In the former, the scalar defines the minimum displacement
value of the boundary co... | 39,969 |
def test_js_autoregister(settings, manifesto, name, expected_assets):
"""Checking js assets after autoregister"""
manifesto.autoregister()
# Expected is base JS files plus expected files from params
expected = settings.CODEMIRROR_BASE_JS + expected_assets
import json
print("== FROM MANIFESTO ... | 39,970 |
def toggleDateSyncButton(click):
"""Change the color of on/off date syncing button - for css."""
if not click:
click = 0
if click % 2 == 0:
children = "Date Syncing: On"
style = {**on_button_style, **{"margin-right": "15px"}}
else:
children = "Date Syncing: Off"
... | 39,971 |
async def test_update_version(
mocker,
test_repo,
versioning_strategy,
expected_python,
expected_js,
expected_version_file,
readonly,
):
"""Call update_version on project"""
repo_info = RepoInfo(
**{
**test_repo._asdict(),
"versioning_strategy": versio... | 39,972 |
def test_propane(pcff_assigner):
"""Test of atom-type assignment for propane"""
assert pcff_assigner.assign("CCC") == [
"c3",
"c2",
"c3",
"hc",
"hc",
"hc",
"hc",
"hc",
"hc",
"hc",
"hc",
] | 39,973 |
def exportjson():
"""
Export the database as a JSON file
:return: None
"""
global is_inio
while True:
if not is_inio:
break
is_inio = True
res = {}
for i in data:
res[i[0]] = {}
for j in range(cols):
if j > 0:
... | 39,974 |
def _find_path(image):
"""Searches for the given filename and returns the full path.
Searches in the directory of the script that called (for example)
detect_match, then in the directory of that script's caller, etc.
"""
if os.path.isabs(image):
return image
# stack()[0] is _find_path... | 39,975 |
def pacf(x, nlags=40, method='ywunbiased', alpha=None):
"""
Partial autocorrelation estimated
Parameters
----------
x : 1d array
observations of time series for which pacf is calculated
nlags : int
largest lag for which the pacf is returned
method : str
specifies whi... | 39,976 |
def list_system_outage(**kwargs):
"""
List system outages
"""
import sfa_api.utils.storage_interface as storage
import pprint
outages = storage._call_procedure(
'list_system_outages',
with_current_user=False
)
click.echo(pprint.pformat(outages)) | 39,977 |
def _opt(spc_info, mod_thy_info, geo, run_fs,
script_str, opt_cart=True, **kwargs):
""" Run an optimization
"""
# Optimize displaced geometry
geom = geo if opt_cart else automol.geom.zmatrix(geo)
success, ret = es_runner.execute_job(
job=elstruct.Job.OPTIMIZATION,
script_st... | 39,978 |
def test_general_plot1d():
"""
Test general plot1d -- whether 1d-Hist can be plotted properly.
"""
h = Hist(
axis.Regular(
50, -5, 5, name="A", label="a [units]", underflow=False, overflow=False
),
).fill(np.random.normal(size=10))
assert h.plot1d(color="green", ls=... | 39,979 |
def fi(x, y, z, i):
"""The f1, f2, f3, f4, and f5 functions from the specification."""
if i == 0:
return x ^ y ^ z
elif i == 1:
return (x & y) | (~x & z)
elif i == 2:
return (x | ~y) ^ z
elif i == 3:
return (x & z) | (y & ~z)
elif i == 4:
return x ^ (y | ~... | 39,980 |
def th_accuracy(pad_outputs, pad_targets, ignore_label):
"""Calculate accuracy.
Args:
pad_outputs (Tensor): Prediction tensors (B * Lmax, D).
pad_targets (LongTensor): Target label tensors (B, Lmax, D).
ignore_label (int): Ignore label id.
Returns:
float: Accuracy value (0.... | 39,981 |
def filter_dot_in_xml_formulas(xmlfile):
"""Replace \\dot with \dot in xml input.
dot is confusing for doxygen (may be latex or graphviz),
so in latex formula inside \rst
we need to use \\dot and replace it later,
when breathe/sphinx comes into action.
Parameters
----------
xmlfile: ... | 39,982 |
def staff_level():
""" Staff Levels Controller """
mode = session.s3.hrm.mode
def prep(r):
if mode is not None:
auth.permission.fail()
return True
s3.prep = prep
output = s3_rest_controller()
return output | 39,983 |
def aa_status_string (status):
"""usage: str return = aa_status_string(int status)"""
if not AA_LIBRARY_LOADED: return AA_INCOMPATIBLE_LIBRARY
# Call API function
return api.py_aa_status_string(status) | 39,984 |
def echo(context, args):
""" echo text
Echo back the following text."""
info(args)
return context | 39,985 |
def release(ctx, release_type):
"""Releases the project in one swift command!"""
if release_type not in ('patch', 'minor', 'major'):
raise Exit('The release type parameter is invalid.\nMust be one of: major, minor, patch')
# Run checks
ctx.run('invoke check test')
# Bump version and git ta... | 39,986 |
def wait_for_visibility(element, wait_time=1):
"""Wait until an element is visible before scrolling.
Args:
element (ElementAPI): The splinter element to be waited on.
wait_time (int): The time in seconds to wait.
"""
end_time = time.time() + wait_time
while time.time() < end_time:... | 39,987 |
async def meta(request):
"""Return ffprobe metadata"""
async def stream_fn(response):
async with sem:
cmd = ['ffprobe',
'-v',
'quiet',
'-i',
request.args.get('url'),
'-print_format',
... | 39,988 |
def tpictr(
sample: str, lenout: int = _default_len_out, lenerr: int = _default_len_out
) -> Tuple[str, int, str]:
"""
Given a sample time string, create a time format picture
suitable for use by the routine timout.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tpictr_c.html
:param ... | 39,989 |
def survey_page(request):
"""View extracts the data that a volunteer fills out from the monthly survey
and updates the data on app side accordingly"""
if request.method == 'GET':
request.session['vol_id'] = request.GET.get('id')
request.session['vol_email'] = request.GET.get('email')
... | 39,990 |
def chebyu(n, monic=0):
"""Return nth order Chebyshev polynomial of second kind, Un(x). Orthogonal
over [-1,1] with weight function (1-x**2)**(1/2).
"""
base = jacobi(n,0.5,0.5,monic=monic)
if monic:
return base
factor = sqrt(pi)/2.0*_gam(n+2) / _gam(n+1.5)
base._scale(factor)
r... | 39,991 |
def spm(name, path, size, bos= -1, eos= -1, unk= 0, coverage= 0.9995):
"""-> SentencePieceProcessor
trains a sentence piece model of `size` from text file on `path`
and saves with `name`.
"""
SentencePieceTrainer.train(
"--model_prefix={name} \
--input={path} \
--vocab_size... | 39,992 |
def pubsub_trigger(data, context):
"""
Used with Pub/Sub trigger method to evaluate bucket for public access and remediate if public access exists.
"""
# Integrates cloud logging handler to python logging
create_logger()
logging.info('Received GCS permissions update log from Pub/Sub. Checking f... | 39,993 |
def list_reshape_bywindow(longlist, windowlen, step=1):
"""
A function to use window intercept long list into several component
A list could like below,
[a, b, c, d, e]
Output could be
[[a,b], [c,d]]
where windowlen as 2,
step as 2
Parameters:
------------
longlist: ... | 39,994 |
def generate_test_repo() -> Repository:
""" gets you a test repo """
test_requester = Requester(
login_or_token="",
retry=False,
password=None,
jwt=None,
base_url="https://github.com/yaleman/github_linter/",
timeout=30,
pool_size=10,
per_page=100,
... | 39,995 |
def _configure_rgw_daemons(node: CephNode, config: Dict) -> None:
"""
Updates the RGW daemons with the provided configuration.
Args:
node Server that has privilege to perform ceph config set commands.
config Key/value pairs to be used for configuration
Returns:
None
... | 39,996 |
def syslog_local_console_exists(handle, **kwargs):
"""
Checks if the syslog local console already exists
Args:
handle (UcsHandle)
**kwargs: key-value pair of managed object(MO) property and value, Use
'print(ucscoreutils.get_meta_info(<classid>).config_props)'
... | 39,997 |
def filter_inputs(inputlist, minimum_members, number_of_families):
"""
Removes functions that have fewer than minimum_members different hashes,
and returns a subset (number_of_families) different ones.
"""
temp = defaultdict(list)
for i in inputlist:
temp[i[1]].append((i[0], i[2]))
result = []
#... | 39,998 |
def get_dataloader_workers():
"""在非Windows的平台上,使用4个进程来读取的数据。"""
return 0 if sys.platform.startswith('win') else 4 | 39,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.