content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_endofday_bug2():
"""Found another edge case."""
times = [16.8, 17.56, 19.06, 21.63, 22.63, 22.90, 23.06, 23.10]
accum = [0, 2.03, 4.22, 6.44, 8.47, 10.73, 13.3, 14.0]
newtimes = conservative_adjust(times, accum, 0.8)
assert (newtimes[-1] - newtimes[-2]) > 0.001 | 62,300 |
def timing(unit="millisecond", message="{func.__name__}() {time:.3f} {unit}"):
"""Measures the execution time of the function.
The value that can be used for specified the ``unit`` parameter are:
======== ================= ==================
Short Long Length
======== ========... | 62,301 |
def run(ctx, report_ids):
"""
Re-run an existing report from the command line
"""
client = ctx.obj["client"]
for report_id in report_ids:
report = client.run_report(report_id)
click.secho(f"Running {report}") | 62,302 |
def exec_check():
"""Returns systemctl command actions."""
global ACTION, COMMAND, SERVICE
exec_check_random = random.SystemRandom()
systemctl_command = shutil.which("systemctl")
try:
args_services = ARGS.services
if "all" in args_services:
SERVICE = 0
else:
... | 62,303 |
def write_patches_file(origin_branch, output_file):
"""Write the patches file for |origin_branch| to |output_file|."""
# Get the latest upstream commit that's reachable from the origin branch.
# We'll use that to compare against.
upstream = run(["git", "merge-base", "upstream/master",
origin_b... | 62,304 |
def tempdir(files=None, **kw):
"""
A decorator for building a temporary directory with prepopulated files.
The temporary directory and files are created just before the wrapped function is called and are destroyed
immediately after the wrapped function returns.
The `files` keyword should be a dict... | 62,305 |
def cloud_init_interface(name, vm_=None, **kwargs):
"""
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to g... | 62,306 |
def test(x_test, y_test):
"""Test the model with highest val accuracy."""
#datagen for test
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
# load model and specify a new input shape for images
best_model_path = os.path.join(output_dir, 'model_resnet50_{}_epochs_{}_lr_{}_... | 62,307 |
def fdc_flux_and_wind(timestamp, sonicU, sonicV, sonicW, sonicT, heading,
rateX, rateY, rateZ, accX, accY, accZ, lat):
"""
Description:
Calculates the 3 L2 flux data products and the 3 L1 wind direction data products
from the FDCHP instrument. It is anticipated that wrappe... | 62,308 |
def to_class_name(value):
"""Convert the current view's object to a usable class name.
Useful for outputting a css-class for targetting specific styles or
javascript functionality on a per-view basis, for example:
<div class="siteContainer {% if request.path == '/' %}home{% else %}{{ object|to_class_n... | 62,309 |
def convert_latex_to_xml(
zip_file: str, latex_dir: str, norm_dir: str, xml_dir: str, log_dir: str, cleanup=True
) -> Optional[str]:
"""
Run expansion, normalization, xml conversion on latex
:param zip_file:
:param latex_dir:
:param norm_dir:
:param xml_dir:
:param log_dir:
:para... | 62,310 |
async def test_async_add_job_pending_tasks_executor(opp):
"""Run an executor in pending tasks."""
call_count = []
def test_executor():
"""Test executor."""
call_count.append("call")
async def wait_finish_callback():
"""Wait until all stuff is scheduled."""
await asyncio... | 62,311 |
def local(ctx, name, json):
"""
Show local policy information
"""
vmanage_session = ctx.obj
pp = pprint.PrettyPrinter(indent=2)
if name:
policy_list_dict = vmanage_session.get_policy_list_dict(type=type)
if name in policy_list_dict:
pp.pprint(policy_list_dict[name])
... | 62,312 |
def _create_fold(X, ids):
"""Create folds from the data received.
Returns
-------
Data fold.
"""
if isinstance(X, list):
return [x[ids] for x in X]
elif isinstance(X, dict):
return {k: v[ids] for k, v in X.items()}
else:
return X[ids] | 62,313 |
def kill_background_grayscale(image, bg):
"""Make the background 0
Args:
image (3-D array): Numpy array (H, W, C)
bg (tuple): RGB code of background (R, G, B)
Returns:
image (2-D array): Binarized image of shape (H, W)
The background is 0 and everything else is 1
"""
... | 62,314 |
def smooth(x: np.ndarray, window_len: int = None, window: str = "flat") -> np.ndarray:
"""Smooths the data using a window with requested size.
Code from https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html
This method is based on the convolution of a scaled window with the signal.
The signal i... | 62,315 |
def average_inter_cluster_distance(data, cluster_labels, centroids):
"""
Computes the average inter-cluster distance i.e the average distance between all clusters.
We have assumed the distance between two clusters is the distance between the centroids of
said clusters
Args:
data (ndarray):... | 62,316 |
def _get_env_defaults() -> "Mapping[str, Any]":
"""
Produce a mapping of configuration keys to values set in the environment through environment
variables.
"""
from os import getenv
kwargs = {}
for fld, param in config_fields(_FlatConfig):
if param.environment_variable:
... | 62,317 |
def test_buttontext(position, size, mouse, label):
"""Test pour la classe ButtonText."""
main.initialization(False)
button = mn.ButtonText(position, size, label)
button.print(mouse) | 62,318 |
def download_entity():
"""Get entity file corresponding to ID=entity_id
Returns:
200 OK: file (on success)
403 Forbidden
404 Not Found: Entity not found (on NotFoundWarning)
500 Internal Server Error (on error)
"""
user = set_user()
try:
if not 'ID' in reques... | 62,319 |
def is_model(val):
"""Returns true if the value represents a valid model.
This is a custom validator that Connexion uses to verify the model field
in request bodies.
Keyword arguments:
val -- the model value
"""
if val is None:
return True
model = Model()
allowed_models = ... | 62,320 |
def test_api_key_form_basic_validation(test_app, key, org_choices, org, expect):
"""Tests the basic validation of the ApiKeyForm."""
with test_app.app_context():
api_key_form = ApiKeyForm()
api_key_form.key.data = key
api_key_form.organization.choices = org_choices
api_key_form.o... | 62,321 |
def raise_on_unexpected(http_response):
# type: (IncomingResponse) -> None
"""Raise an HTTPError if the response is 5XX.
:param http_response: :class:`bravado_core.response.IncomingResponse`
:raises: HTTPError
"""
if 500 <= http_response.status_code <= 599:
raise make_http_exception(res... | 62,322 |
def general_options(mocker):
"""Generate the general options needed for the pages."""
mocker.patch('djangopress.blog.views.Option.objects.get_or_create',
new=option_get_or_create_stub(5)
)
category_mock = mocker.patch('djangopress.blog.models.Category.objects')
category... | 62,323 |
def eval_one_epoch(sess, coord, model, cv_num_batch, epoch):
""" Cross validate the model on given data. """
d_counter = 0
g_counter = 0
cv_g_adv_loss = 0.0
cv_g_mse_loss = 0.0
cv_g_l2_loss = 0.0
cv_g_loss = 0.0
cv_d_rl_loss = 0.0
cv_d_fk_loss = 0.0
cv_d_loss = 0.0
# We run D... | 62,324 |
def load_image(path):
"""Load image to memory."""
imagelist = []
for image_file in os.listdir(path):
image_path = os.path.join(path, image_file)
image = Image.open(image_path).resize([224, 224])
image = np.array(image).astype(np.float) / 128 - 1
imagelist.append(image)
... | 62,325 |
def test_string_values():
"""Check that all values are converted to strings.
1. Create a list with different values.
2. Pass the list to adjust_relations.
3. Check values of the returned tuple.
"""
relations = ["plain string", 1, None, ["nested"]]
assert adjust_relations(relations) == ("pla... | 62,326 |
def calculateCurvature(yRange, fit_cr):
"""
Returns the curvature of the polynomial `fit` on the y range `yRange`.
"""
return ((1 + (2*fit_cr[0]*yRange*ym_per_pix + fit_cr[1])**2)**1.5) / np.absolute(2*fit_cr[0]) | 62,327 |
def globals_videos_filter(find):
"""
SECTION : channel, videos, comment
DESCRIPTION : Find substrings from the channel title to narrow down the search results.
USAGE : Extraction of the comments takes less number of videos after the tile search.
"""
# ====================== Setup ===============... | 62,328 |
def Msg(schema, msg):
"""Report a user-friendly message if a schema fails to validate.
>>> validate = Schema(
... Msg(['one', 'two', int],
... 'should be one of "one", "two" or an integer'))
>>> validate(['three'])
Traceback (most recent call last):
...
InvalidList: should be on... | 62,329 |
def leaf_hyponyms(synset):
"""
Get the set of leaf nodes from the tree of hyponyms under the synset
"""
hyponyms = []
_recurse_leaf_hyponyms(synset, hyponyms)
return set(hyponyms) | 62,330 |
def left(message):
"""Sent by clients when they leave a room.
A status message is broadcast to all people in the room."""
agent = request.headers.get('User-Agent')
current_app.logger.WARNING("LEFT {}".format(agent)) | 62,331 |
def parse_args(argv):
"""Function parsing command-line arguments
Args:
argv: a list containing command line arguments
Returns:
src_dir: a list with source directory names, full path
sulcus: a string containing the sulcus to analyze
number_subjects: number of subjects to ana... | 62,332 |
def test_submit_online():
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
browser = mechanicalsoup.Browser()
page = browser.get("http://httpbin.org/forms/post")
form = page.soup.form
form.find("input", {"name": "custname"})["value"] = "Philip J. Fry"
# leave custtel b... | 62,333 |
def rand_sol(A, b):
"""Generate a random solution to the equation Ax=b."""
assert np.linalg.matrix_rank(A) <= len(b)
A_plus = np.linalg.pinv(A)
x = A_plus @ b
return x + (np.eye(x.shape[0]) - A_plus @ A) @ np.random.normal(size=x.shape) | 62,334 |
def get_fig_axes_lpr(dims=(8, 6), facecolor='#ffffff', gridcolor='#e0e0e0'):
"""
Get a matplotlib figure object, with lpr-themed face and gridcolors.
This theme is white background, gray gridlines, and .5 alpha.
"""
fig, ax = get_fig_axes(dims, facecolor, gridcolor)
fig.patch.set_alpha(0.5)
... | 62,335 |
def read_dataset(cfg, file_pattern, training=False):
"""Reads a dataset, and handles repetition and shuffling.
Args:
file_read_func: Function to use in tf.contrib.data.parallel_interleave, to
read every individual file into a tf.data.Dataset.
file_pattern: A file pattern to match.
... | 62,336 |
def master_to_sql(directories, engine):
"""
"""
metarecs = []
imagerecs = []
if isinstance(directories, str):
directories = [directories]
for directory in directories:
ID = os.path.basename(directory)
hdfs = os.path.join(directory, '{}.tif'.format(ID))
files = g... | 62,337 |
def _add_option_if_supported(repository_ctx, cc, option):
"""Checks that `option` is supported by the C compiler. Doesn't %-escape the option."""
result = repository_ctx.execute([
cc,
option,
"-o",
"/dev/null",
"-c",
str(repository_ctx.path("tools/cpp/empty.cc"))
])
return [o... | 62,338 |
def get_volume(filters: Optional[Sequence[pulumi.InputType['GetVolumeFilterArgs']]] = None,
most_recent: Optional[bool] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVolumeResult:
"""
Use this data sourc... | 62,339 |
async def getWikiSummary(message, title):
"""
Display the wikipedia article summary of the article with the given title
Parameters:
message - discord.client.message object being responded to
title - string of the wikipedia article title
"""
try:
query = (
"https://e... | 62,340 |
def tilted_L1_prox_1d(x, step, quantile=0.5):
"""
prox(x) = argmin_z rho_quantile(z) + (0.5 / step) * ||x - z||_2^2
See Lemma 1 of ADMM for High-Dimensional Sparse Penalized
Quantile Regression
"""
if step < np.finfo(float).eps:
return 0
t_a = quantile * step # tau / alpha
if x >... | 62,341 |
def make_insert_sql(
table, data, auto_update=False, update_columns=(), insert_ignore=False
):
"""
@summary: 适用于mysql, oracle数据库时间需要to_date 处理(TODO)
---------
@param table:
@param data: 表数据 json格式
@param auto_update: 使用的是replace into, 为完全覆盖已存在的数据
@param update_columns: 需要更新的列 默认全部,当指... | 62,342 |
def set_task_params(data, workspace):
"""根据request设置task的参数。只有在task是TaskStatus.XINIT状态时才有效
Args:
data为dict,key包括
'tid'任务id, 'train'训练参数. 训练
参数和数据增强参数以pickle的形式保存在任务目录下的params.pkl文件
中。
"""
tid = data['tid']
train = data['train']
assert tid in workspace.tasks, "【任务... | 62,343 |
def extractPkScriptAddrs(version, pkScript, netParams):
"""
extractPkScriptAddrs returns the type of script, addresses and required
signatures associated with the passed PkScript. Note that it only works for
'standard' transaction script types. Any data such as public keys which are
invalid are om... | 62,344 |
def process_dollar(api_dict):
"""
输入:{'value': 'xfjc@zb', 'lx': "xfxs_cfxfbz", "name": "$index", "index": "xfjc"}
输出:{'value': 'xfjc@zb', 'lx': "xfxs_cfxfbz", "name": "xfjc", "index": "xfjc"}
"""
# 处理 $引用
# order = -$index name=$timetype name=$qh
# transformer=@groupby:$name,$stack +... | 62,345 |
def dict_map(**fs):
"""Map especific elements in a dict.
Examples:
```pycon
>>> dict_map(a=int, b=str)(dict(a='1', b=123, c=True))
{'a': 1, 'b': '123', 'c': True}
>>>
```
"""
def _change_dict(d):
d = d.copy()
for k, f in fs.items():
if k in d:
... | 62,346 |
def generate_tx_dict():
"""Read files from stdin generated by print_txs.py and return a {tx_hash: tx} dictionary."""
txs = {}
for i, raw_line in enumerate(fileinput.input()):
if i % 100 == 0:
logging.debug('processing tx %d', i)
json_line = json.loads(raw_line)
# omit '... | 62,347 |
def Create(database_ref):
"""Create a database session."""
client = apis.GetClientInstance('spanner', 'v1')
msgs = apis.GetMessagesModule('spanner', 'v1')
req = msgs.SpannerProjectsInstancesDatabasesSessionsCreateRequest(
database=database_ref.RelativeName())
return client.projects_instances_databases_s... | 62,348 |
def q12_jac(qs, epsilon):
"""The Jacobian of the mapping from q1, q2 to costheta, phi
"""
s2 = sinh(epsilon*qs[1])
c2 = cosh(epsilon*qs[1])
sp = sinh(epsilon*(qs[0] + qs[1]))
sm = sinh(epsilon*(qs[0] - qs[1]))
cp = cosh(epsilon*(qs[0] + qs[1]))
cm = cosh(epsilon*(qs[0] - qs[1]))
cs... | 62,349 |
def delete_ftp_user(host: str,
username: str,
port: int = 443,
debug: bool = False,
config: Optional[str] = None) -> None:
"""Deletes an FTP user."""
setup_logging(debug)
user = b64encode(username.encode()).decode()
uri = (f... | 62,350 |
def cc_test_mozc(name, tags = [], deps = [], **kwargs):
"""
cc_test wrapper adding //:macro dependecny.
"""
requires_full_emulation = kwargs.pop("requires_full_emulation", False)
native.cc_test(
name = name,
tags = tags,
deps = deps + ["//:macro"],
**kwargs
)
... | 62,351 |
def lambda_handler(event: dict, context: Any):
"""
:param event: S3 notification event
:param context: Lambda Context runtime methods and attributes
"""
input_prefix = 'raw/'
input_suffix = '.csv'
output_prefix = 'transformed/'
output_suffix = '.snappy.parquet'
return_values = []
... | 62,352 |
def add_common_cmdline_args(argparser):
"""Add common command line args."""
argparser.add_argument(
'-esz',
'--embedding-size',
type=int,
default=300,
help='Size of all embedding layers',
)
argparser.add_argument('-nl', '--n-layers', type=int, default=2)
argpa... | 62,353 |
def normalize_name(name):
"""
Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to
the canonical representation (e.g. "left ctrl") if one is known.
"""
if not name or not isinstance(name, basestring):
raise ValueError('Can only normalize non-empty string names. Unexpect... | 62,354 |
def llegar_bus_parada(cola_personas, cola_autobuses):
"""
Función que llega un autobús a una parada.
"""
autobus = int(input("Número de autobús: "))
plazas = int(input("Número de plazas libres: "))
if plazas > len(cola_personas[autobus-1]):
plazas = len(cola_personas[autobus-1])
for ... | 62,355 |
def check_pid(pid):
"""Check whether pid exists in the current process table."""
# Copied from psutil
# https://github.com/giampaolo/psutil/blob/5ba055a8e514698058589d3b615d408767a6e330/psutil/_psposix.py#L28-L53
if pid == 0:
return True
try:
os.kill(pid, 0)
except OSEr... | 62,356 |
def bmasync(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
"""async function decorator"""
_setup_loop()
@wraps(func)
def wrapper(*args, **kwargs) -> Any:
return asyncio.ensure_future(func(*args, **kwargs))
return wrapper | 62,357 |
def goto_y(new_y):
"""
Move tool to the new_y position at speed_mm_s at high speed. Update curpos.y with new position.
If a failure is detected, sleep so the operator can examine the situation.
Since the loss of expected responses to commands indicates that the program does not know
the exact po... | 62,358 |
def section_type_must_be_defined(sec):
"""
Tests that no Section has an unspecified type and adds a warning otherwise.
:param sec: odml.Section.
"""
validation_id = IssueID.section_type_must_be_defined
if sec.type and sec.type == "n.s.":
yield ValidationError(sec, "Section type not spe... | 62,359 |
def _nested_loop_join_outer(g_list, arg_str, bindings, operands):
"""
E.g Join two Predicates P1(x,y) and P2(x,z,y) with groundings
(x1,y1) : g11 (ground object) and (x1,z1,y1) : g12
(x2,y2) : g21 (ground object) and (x2,z2,y2) : g22
(x1,y3) : g31 (ground object) and (x2,z3,y2) :... | 62,360 |
def StrContains(input_string, substring):
"""
Return True if the substring is contained in the concrete value of the input_string
otherwise false.
:param input_string: the string we want to check
:param substring: the string we want to check if it's contained inside the input_string
:return: Tr... | 62,361 |
def RemoveAllInstances(client):
""" Queries for a list of instances, then removes them all.
@type client: C{GanetiRapiClientWrapper}
@param client: A wrapped RAPI client.
"""
instances = client.GetInstances()
for inst in instances:
Finish(client, client.DeleteInstance, inst)
instances = client.GetI... | 62,362 |
def rescale_frontoparallel(p_fp,box_fp,p_im):
"""
The fronto-parallel image region is rescaled to bring it in
the same approx. size as the target region size.
p_fp : nx2 coordinates of countour points in the fronto-parallel plane
box : 4x2 coordinates of bounding box of p_fp
... | 62,363 |
def get_closest(iterable: Iterable, target):
"""Return the item in iterable that is closest to the target"""
if not iterable or target is None:
return None
return min(iterable, key=lambda item: abs(item - target)) | 62,364 |
def has_tf_tensor(input):
"""Check if a variable is a `tf.tensor` or nested list of `tf.tensor`s."""
return has_tensor(input, 'tf') | 62,365 |
def datetime_from_isformat(date_string):
"""Construct a datetime from the output of datetime.isoformat()."""
if not isinstance(date_string, str):
raise TypeError('fromisoformat: argument must be str')
# Split this at the separator
dstr = date_string[0:10]
tstr = date_string[11:]
try:
... | 62,366 |
def merge_two_reconstructions(r1, r2, config, threshold=1):
"""Merge two reconstructions with common tracks."""
t1, t2 = r1.points, r2.points
common_tracks = list(set(t1) & set(t2))
if len(common_tracks) > 6:
# Estimate similarity transform
p1 = np.array([t1[t].coordinates for t in com... | 62,367 |
def _reorder_for_extension_array_stack(arr, n_rows: int, n_columns: int):
"""
Re-orders the values when stacking multiple extension-arrays.
The indirect stacking method used for EAs requires a followup
take to get the order correct.
Parameters
----------
arr : ExtensionArray
n_rows, n_... | 62,368 |
def test_query_album_4():
"""Test query with multipl --album"""
import json
import os
import os.path
import osxphotos
from osxphotos.cli import query
runner = CliRunner()
cwd = os.getcwd()
result = runner.invoke(
query,
[
"--json",
"--db",
... | 62,369 |
def stats():
"""send admin stats everyday"""
if not ADMIN_EMAIL:
# nothing to do
return
stats_today = stats_before(arrow.now())
stats_yesterday = stats_before(arrow.now().shift(days=-1))
nb_user_increase = increase_percent(stats_yesterday.nb_user, stats_today.nb_user)
nb_alias_... | 62,370 |
def RemoveBackground(_tod, rms,x,y, sampleRate=50, cutoff=1.):
"""
Takes the TOD and set of indices describing the location of the source.
Fits polynomials beneath the source and then applies a low-pass filter to the full
data. It returns this low pass filtered data
"""
time = np.arange(_tod.siz... | 62,371 |
def utils_vlan_ports_list(duthosts, rand_one_dut_hostname, rand_selected_dut, tbinfo, ports_list):
"""
Get configured VLAN ports
"""
duthost = duthosts[rand_one_dut_hostname]
cfg_facts = duthost.config_facts(host=duthost.hostname, source="persistent")['ansible_facts']
mg_facts = rand_selected_du... | 62,372 |
def GetExtraVars():
"""Returns the captured variables by the function."""
g = tf.get_default_graph()
if isinstance(g, func_graph.FuncGraph):
return g.variable_captures
return function.get_extra_vars() | 62,373 |
def convert_mol_to_pdbqt(mol: RDKitMol, outfile: str) -> None:
"""Writes the provided ligand molecule to specified file in pdbqt format.
Creates a torsion tree and write to pdbqt file. The torsion tree
represents rotatable bonds in the molecule.
Parameters
----------
mol: rdkit.Chem.rdchem.Mol
The mol... | 62,374 |
def get_log():
"""Get the filtered setAttr commands from the logs.
:return: List of all setAttr commands.
"""
with open(FILE_NAME, "r") as f:
attr_log = [line for line in f.read().splitlines()
if line.startswith("setAttr") and not "|" in line]
return attr_log | 62,375 |
def on_epoch_complete(func: Callable) -> FunctionCallback:
"""Decorator for creating a callback from a function. The function will be
executed when the ``Events.EPOCH_COMPLETE`` is triggered. The function
should take :class:`argus.engine.State` as the first argument.
"""
return FunctionCallback(Even... | 62,376 |
def normalise(matrix):
"""Normalises the agents' cumulative utilities.
Parameters
----------
matrix : list of list of int
The cumulative utilities obtained by the agents throughout.
Returns
-------
list of list of int
The normalised cumulative utilities (i.e., utility share... | 62,377 |
def rgb_to_irg(rgb):
""" converts rgb to (mean of channels, red chromaticity, green chromaticity) """
irg = np.zeros_like(rgb)
s = np.sum(rgb, axis=-1) + 1e-6
irg[..., 2] = s / 3.0
irg[..., 0] = rgb[..., 0] / s
irg[..., 1] = rgb[..., 1] / s
return irg | 62,378 |
def basic_nmt_bilstm_luong_att():
"""Hparams for LSTM with luong attention."""
hparams = base_nmt_bilstm(base_att(base_nmt()))
hparams.add_hparam("attention_gnmt", False)
hparams.add_hparam("attention_mechanism", "luong")
return hparams | 62,379 |
def remove_projection_from_vector(v: Vector, w: Vector) -> Vector:
"""projects v onto w and subtracts the result from v"""
return subtract(v, project(v, w)) | 62,380 |
def KK_RC77_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | 62,381 |
def check_scope(
outdir: str,
logger: Logger = getLogger(__name__)
) -> int:
"""
Check if result is present in outdir.
Parameters
----------
outdir : str
The folder where results heve been written.
logger : Logger
The logger object.
Returns
-------
int Retur... | 62,382 |
def cvRetrieveFrame__Deprecated(*args):
"""cvRetrieveFrame__Deprecated(CvCapture capture, int streamIdx = 0)"""
return _highgui.cvRetrieveFrame__Deprecated(*args) | 62,383 |
def lunar_lander_main(workers=4,
env_seed=1339,
iterations=500,
log_freq=25,
n_emitters=5,
batch_size=30,
sigma0=1.0,
seed=None,
outdir="lunar_l... | 62,384 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('ups_view'... | 62,385 |
def polynomial_graph_filter(coeff: np.array, laplacian: np.ndarray):
""" Return the laplacian polynomial with coefficients 'coeff'. """
power = np.eye(laplacian.shape[0])
filt = coeff[0] * power
for n, c in enumerate(coeff[1:]):
power = laplacian @ power
filt += c * power
return filt | 62,386 |
def tellme(s):
"""
Prints a string to a plot
:param s: <string> The title to be printed
"""
plt.title(s, fontsize = 16)
plt.draw() | 62,387 |
def update_meta_dict(dst_dict, src_dict):
"""Update the meta dict by removing meaningless items"""
for item_key in src_dict:
if item_key not in dst_dict:
print(item_key, dst_dict)
raise AttributeError("The item is not in dst_dict!")
if isinstance(src_dict[item_key], dict)... | 62,388 |
def normalize(comic, face):
""" Normalize the images to [-1, 1]
"""
# YOUR CODE HERE
comic = (tf.cast(comic, tf.float32) /255.0 *2) -1
face = (tf.cast(face, tf.float32) /255.0 *2) -1
return comic, face | 62,389 |
def findFile(input):
""" Search a directory for full filename with optional path. """
_fdir, _fname = os.path.split(input)
if _fdir == '':
_fdir = os.curdir
flist = os.listdir(_fdir)
found = False
for name in flist:
if not name.find(_fname):
found = True
retu... | 62,390 |
def build_argument_parser() -> ArgumentParser:
"""Build the argument parser."""
opts = ArgumentParser()
opts.add_argument(
dest='videopath',
help='Path to the video to introspect',
nargs='*',
type=str,
)
provider_opts = opts.add_argument_group('Providers')
provid... | 62,391 |
def latent_traversal_static(model,
x: Union[np.ndarray, torch.Tensor],
device: torch.device,
save_path: Union[str, Path],
n_imgs: int,
z_min: float,
z_m... | 62,392 |
def get_latest_sha(repo):
""" Returns latest git sha of given git repo directory. """
cwd = os.getcwd()
command = "git rev-list -1 HEAD -- {0}".format(repo)
os.chdir(repo)
git_sha = process_helpers.run(command.split(" "))
os.chdir(cwd)
return git_sha.strip() | 62,393 |
def label_array_3d() -> Tuple[np.ndarray, Mapping[Coordinates, ArrayLike[Number]]]:
"""Convenience method to return a 3D label array with corresponding physical coordinates."""
label_array = np.zeros((2, 5, 6), dtype=np.int32)
label_array[0, 0] = 1
label_array[:, 3:5, 3:6] = 2
label_array[-1, -1, -1... | 62,394 |
def update_payout_monthly_earnings(sender, instance, created, **kwargs):
"""Signal updating the monthly earnings for the Payout object when creating or editing a day object."""
if created:
Payout.objects.get_or_create(month=instance.month, user=instance.user)
payout = Payout.objects.get(month=instan... | 62,395 |
def cmdline_from_pid(pid):
""" Fetch command line from a process id. """
try:
cmdline= open("/proc/%i/cmdline" %pid).readlines()[0]
return " ".join(cmdline.split("\x00")).rstrip()
except:
return "" | 62,396 |
def none_if_empty(tup):
"""Returns None if passed an empty tuple
This is helpful since a SimpleVar is actually an IndexedVar with
a single index of None rather than the more intuitive empty tuple.
"""
if tup is ():
return None
else:
return tup | 62,397 |
def rectMode(mode):
"""Alters the meaning of the arguments of the rectangle function"""
attrib.rectMode = mode | 62,398 |
def creator(data: list, q: Queue) -> None:
"""
Creates data to be consumed and waits for the consumer
to finish processing
"""
print('Creating data and putting it on the queue')
for item in data:
evt = threading.Event()
q.put((item, evt))
print('Waiting for data to be do... | 62,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.