content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def select_questions(db: Database) -> List[Row]:
"""
Selects a list of 20 questions from the database using a spaced-repetition
algorithm.
The questions are drawn from 3 quizzes in a set ratio: 10 from the first quiz, 7
from the second, and 3 from the third.
The quizzes and questions are selec... | 28,500 |
def process_ona_webhook(instance_data: dict):
"""
Custom Method that takes instance data and creates or Updates
an Instance Then Returns True if Instance was created or updated
"""
instance_obj = process_instance(instance_data)
if instance_obj is None:
return False
return True | 28,501 |
def test_quantized_conv2d_nonfunctional():
"""Basic test of the PyTorch quantized conv2d Node with external quantized
input on Glow."""
def test_f(a):
q = torch.nn.quantized.Quantize(1/16, 0, torch.quint8)
dq = torch.nn.quantized.DeQuantize()
conv = torch.nn.quantized.Conv2d(1, 1, [... | 28,502 |
def distance(v, w):
"""the distance between two vectors"""
return math.sqrt(squared_distance(v, w)) | 28,503 |
def configuration(monkeypatch):
"""In-memory configuration.
Args:
monkeypatch: Fixture helper.
"""
config = configparser.ConfigParser()
config.read_dict(dict(
api=dict(
project='config_project',
host='config_host',
key='config_key',
)
))
monkeypatch.s... | 28,504 |
def client_login_fixture(client):
"""Define a fixture for patching the aioridwell coroutine to get a client."""
with patch(
"homeassistant.components.ridwell.config_flow.async_get_client"
) as mock_client:
mock_client.side_effect = client
yield mock_client | 28,505 |
def createLayerOnSimFrameDepend(job, layer, onjob, onlayer, onframe):
"""Creates a layer on sim frame dependency
@type job: string
@param job: the name of the dependant job
@type layer: string
@param layer: the name of the dependant layer
@type onjob: string
@param onjob: the name of the job... | 28,506 |
def QA_SU_save_stock_min_5(file_dir, client=DATABASE):
"""save stock_min5
Arguments:
file_dir {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
return tdx_file.QA_save_tdx_to_mongo(... | 28,507 |
def get_course_by_name(name):
""" Return a course dict for the given name, or None
{ 'id':id, 'name':name, 'title':title }
"""
ret = run_sql(
"""SELECT course, title, description, owner, active, type,
practice_visibility, assess_visibility
FROM courses
... | 28,508 |
def make_nailgun_transport(nailgun_server, nailgun_port=None, cwd=None):
"""
Creates and returns a socket connection to the nailgun server.
"""
transport = None
if nailgun_server.startswith("local:"):
if platform.system() == "Windows":
pipe_addr = nailgun_server[6:]
t... | 28,509 |
def delete_chap_credentials(TargetARN=None, InitiatorName=None):
"""
Deletes Challenge-Handshake Authentication Protocol (CHAP) credentials for a specified iSCSI target and initiator pair.
See also: AWS API Documentation
Examples
Deletes Challenge-Handshake Authentication Protocol (CHAP) creden... | 28,510 |
def timedelta(string):
"""
Parse :param string: into :class:`datetime.timedelta`, you can use any
(logical) combination of Nw, Nd, Nh and Nm, e.g. `1h30m` for 1 hour, 30
minutes or `3w` for 3 weeks.
Raises a ValueError if the input is invalid/unparseable.
>>> print(timedelta("3w"))
21 days... | 28,511 |
def englishTextNull(englishInputNull):
"""
This function returns true if input is empty
"""
if englishInputNull == '':
return True | 28,512 |
def test_restrict_inputs():
"""Test a basic use of the restrict(inputs=(...)) method."""
code = 'x = a + b\ny = b - c\nz = c**2'
b = Block(code)
assert_equal(b.inputs, set(['a', 'b', 'c']))
assert_equal(b.outputs, set(['x', 'y', 'z']))
br = b.restrict(inputs=('a', ))
names = dict(a=100, b=2... | 28,513 |
def http_set(directive, values, config=None):
"""Set a directive in http context.
If directive exists, the value will be replace in place.
If directive not exists, new directive will be created at the beginning of http context.
Parameter values can be a list or a string.
If values is set to... | 28,514 |
def authority_b(request, configuration, authority_a):
"""
Intermediate authority_a
valid_authority -> authority_a -> authority_b
"""
authority = configuration.manager.get_or_create_ca("authority_b",
hosts=["*.com"],
... | 28,515 |
def filtered_data_time_stats(df):
"""Displays statistics on the most frequent times of travel for Filtered Data."""
print('-'*40)
print('\nCalculating The Most Frequent Times of Travel for Filtered Data...\n')
print('-'*40)
start_time = time.time()
# display month name
print("Month is: ",df[... | 28,516 |
def derive(pattern):
"""
Calculate the first derivative pattern pattern.
Smoothes the input first, so noisy patterns shouldn't
be much of a problem.
"""
return np.gradient(smooth_pattern(pattern)) | 28,517 |
def gaussian(nm, a, x0, sigma):
"""
gaussian function
"""
gaussian_array = a * np.exp(- ((nm - x0) ** 2.0) / (2 * (sigma ** 2.0)))
return gaussian_array | 28,518 |
def test_dual_conditions_ge_and_le_dates(df, right):
"""Test output for interval conditions."""
assume(not df.empty)
assume(not right.empty)
middle, left_on, right_on = ("E", "Dates", "Dates_Right")
expected = (
df.assign(t=1)
.merge(right.assign(t=1), on="t")
.query(f"{left_... | 28,519 |
def list_to_filename(filelist):
"""Returns a list if filelist is a list of length greater than 1,
otherwise returns the first element
"""
if len(filelist) > 1:
return filelist
else:
return filelist[0] | 28,520 |
def _get_expiration_seconds(expiration):
"""Convert 'expiration' to a number of seconds in the future.
:type expiration: int, long, datetime.datetime, datetime.timedelta
:param expiration: When the signed URL should expire.
:rtype: int
:returns: a timestamp as an absolute number of seconds.
""... | 28,521 |
def push_data_to_elastic_search(data):
"""
Post `data` to our ElasticSearch instance at `index_name`.
This script was adapted from gitlab-ci/.
The index name is hardcoded to a test index for the time being.
The ingest goes through the "add_timestamp" pipeline which was created like
so:
... | 28,522 |
def parse_encoding(format_, track, supplied_encoding, prompt_encoding):
"""Get the encoding from the FLAC files, otherwise require the user to specify it."""
if format_ == "FLAC":
if track["precision"] == 16:
return "Lossless", False
elif track["precision"] == 24:
return ... | 28,523 |
def move_logfile_to_standard_location(base_file, input_log_file, yaml_outdir=None, log_type='catalog_seed'):
"""Copy the log file from the current working directory and standard
name to a ```mirage_logs``` subdirectory below the simulation data
output directory. Rename the log to match the input yaml file n... | 28,524 |
def html_converter():
"""I'll be using pandoc as shell command as it is easier than programming it"""
folder = "/usr/share/nginx/html/feeds/support_files/rss_text/Mercury-SB4_comparison/mercury"
paths = []
for filename in os.listdir(folder):
if filename.endswith(".txt"):
paths.appen... | 28,525 |
def check_core_dump_setting():
"""
checking os core dump setting is right
"""
errors = []
ret, out = run_shell('ulimit -c')
limit = out.strip('\n').strip()
if limit != 'unlimited':
errors.append(f'core dump file setting limit="{limit}" is incorrect, should set to unlimited')
wi... | 28,526 |
def test_init():
"""Test return objects"""
fd = pf.FrequencyData([1, .5], [100, 200])
# interpolation object
interpolator = InterpolateSpectrum(
fd, "complex", ("linear", "linear", "linear"))
assert isinstance(interpolator, InterpolateSpectrum)
# interpolation result
signal = inter... | 28,527 |
def disaggregate(model, mains, model_name, num_seq_per_batch, seq_len,
appliance, target_scale, stride=1):
"""
Disaggregation function to predict all results for whole time series mains.
:param model: tf model object
:param mains: numpy.ndarray, shape(-1,)
:param model_name: name... | 28,528 |
def set_path_to_file(categoria: str) -> pathlib.PosixPath:
"""
Receba uma string com o nome da categoria da lesgilação e retorna
um objeto pathlib.PosixPath
"""
fpath = Path(f"./data/{categoria}")
fpath.mkdir(parents=True, exist_ok=True)
return fpath | 28,529 |
def transpose_nested_dictionary(nested_dict):
"""
Given a nested dictionary from k1 -> k2 > value
transpose its outer and inner keys so it maps
k2 -> k1 -> value.
"""
result = defaultdict(dict)
for k1, d in nested_dict.items():
for k2, v in d.items():
result[k2][... | 28,530 |
def auth_code():
"""
Функция для обработки двухфакторной аутентификации
:return: Код для двухфакторной аутентификации
:rtype: tuple(str, bool)
"""
tmp = input('Введи код: ')
return tmp, True | 28,531 |
def graph_file_read_mtx(Ne: int, Nv: int, Ncol: int, directed: int, filename: str,\
RemapFlag:int=1, DegreeSortFlag:int=0, RCMFlag:int=0, WriteFlag:int=0) -> Graph:
"""
This function is used for creating a graph from a mtx graph file.
compared with the graph_file_read functio... | 28,532 |
def _get_uri(tag, branch, sha1):
"""
Set the uri -- common code used by both install and debian upgrade
"""
uri = None
if tag:
uri = 'ref/' + tag
elif branch:
uri = 'ref/' + branch
elif sha1:
uri = 'sha1/' + sha1
else:
# FIXME: Should master be the default... | 28,533 |
def compute_inliers (BIH, corners):
"""
Function: compute_inliers
-------------------------
given a board-image homography and a set of all corners,
this will return the number that are inliers
"""
#=====[ Step 1: get a set of all image points for vertices of board coords ]=====
all_board_points = []
for ... | 28,534 |
def plotPayloadStates(full_state, posq, tf_sim):
"""This function plots the states of the payload"""
# PL_states = [xl, vl, p, wl]
fig8, ax11 = plt.subplots(3, 1, sharex=True ,sharey=True)
fig8.tight_layout()
fig9, ax12 = plt.subplots(3, 1, sharex=True, sharey=True)
fig9.tight_layout()
... | 28,535 |
def draw(p):
"""
Draw samples based on probability p.
"""
return np.searchsorted(np.cumsum(p), np.random.random(), side='right') | 28,536 |
def test_register_collection_archive_added_to_routes():
"""If your registered collection has an archive, Add the archive to
site.routes"""
class TestSite(Site):
routes = []
t = TestSite()
assert not t.routes # Verify that the site routes are empty on creation
@t.register_collection
... | 28,537 |
def _autoinit(func):
"""Decorator to ensure that global variables have been initialized before
running the decorated function.
Args:
func (callable): decorated function
"""
@functools.wraps(func)
def _wrapped(*args, **kwargs):
init()
return func(*args, **kwargs)
retu... | 28,538 |
def export_testing_time_result():
"""
Description:
I refer tp the answer at stockoverFlow:
https://stackoverflow.com/questions/42957871/return-a-created-excel-file-with-flask
:return: A HTTP response which is office excel binary data.
"""
target_info = request.form["target"]
workbook = ... | 28,539 |
def get_db():
"""Return a DB Session."""
db = SessionLocal()
try:
yield db
finally:
db.close() | 28,540 |
def profile_view(user_request: 'Queryset') -> 'Queryset':
"""
Функция, которая производит обработку данных пользователя и выборку из БД
вакансий для конкретного пользователя
"""
user_id = user_request[0]['id']
area = user_request[0]['area']
experience = user_request[0]['experience']
sala... | 28,541 |
def ground_generator(literal, context, D, D_index=None):
"""
This function is a generator, which generates entity and the context.
Args:
literal (a literal instance):
context (a dictionary): store the mapping of variables and constants
D (a dictionary object): a global object storin... | 28,542 |
def config_vrf(dut, **kwargs):
"""
#Sonic cmd: Config vrf <add | delete> <VRF-name>
eg: config_vrf(dut = dut1, vrf_name = 'Vrf-test', config = 'yes')
eg: config_vrf(dut = dut1, vrf_name = 'Vrf-test', config = 'no')
"""
st.log('Config VRF API')
if 'config' in kwargs:
config = kwargs['... | 28,543 |
def _worker_command_line(thing, arguments):
"""
Create a worker command line suitable for Popen with only the
options the worker process requires
"""
def a(name):
"options with values"
return [name, arguments[name]] * (arguments[name] is not None)
def b(name):
"boolean op... | 28,544 |
def get_endpoint(arn: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEndpointResult:
"""
Resource Type Definition for AWS::S3Outposts::Endpoint
:param str arn: The Amazon Resource Name (ARN) of the endpoint.
"""
__args__ = dict()
__args__['ar... | 28,545 |
def solveConsLaborIntMarg(
solution_next,
PermShkDstn,
TranShkDstn,
LivPrb,
DiscFac,
CRRA,
Rfree,
PermGroFac,
BoroCnstArt,
aXtraGrid,
TranShkGrid,
vFuncBool,
CubicBool,
WageRte,
LbrCost,
):
"""
Solves one period of the consumption-saving model with end... | 28,546 |
def append_child(node, child):
"""Appends *child* to *node*'s children
Returns:
int: 1 on success, 0 on failure
"""
return _cmark.node_append_child(node, child) | 28,547 |
def set_memory(instance):
"""Set the amount of RAM, in MB, that the virtual machine
should allocate for itself from the host.
:param instance: nova.objects.instance.Instance
"""
host_info = get_host_info()
if instance.memory_mb > host_info[constants.HOST_MEMORY_AVAILABLE]:
raise nova_ex... | 28,548 |
def test_spearman_regression(spearman_evaluator, targets, preds, uncs, spearman_exp):
"""
Tests the result of the spearman rank correlation UncertaintyEvaluator.
"""
area = spearman_evaluator.evaluate(targets, preds, uncs)
np.testing.assert_array_almost_equal(area, spearman_exp) | 28,549 |
def run_chain(init_part, chaintype, length, ideal_population, id, tag):
"""Runs a Recom chain, and saves the seats won histogram to a file and
returns the most Gerrymandered plans for both PartyA and PartyB
Args:
init_part (Gerrychain Partition): initial partition of chain
chaintype (Str... | 28,550 |
def cliquenet_s2(**kwargs):
"""CliqueNet-S2"""
model = cliquenet(input_channels=64, list_channels=[36, 80, 150, 120], list_layer_num=[5, 5, 6, 6])
return model | 28,551 |
def decConvert(dec):
"""
This is a number-word converter, but for decimals.
Parameters
-----
dec:str
This is the input value
numEngA: dict
A dictionary of values that are only up to single digits
frstDP: int
The first decimal place
scndDP: int
The second decimal place
Returns... | 28,552 |
def train_model(base_model, training_dataset, validation_dataset, output_dir,
loss=None, num_epochs=100, patience=20,
learning_rate=1e-4):
"""
Train a model with the given data.
Parameters
----------
base_model
training_dataset
validation_dataset
output_di... | 28,553 |
def fit(data, weights, model_id, initial_parameters, tolerance=None, max_number_iterations=None, \
parameters_to_fit=None, estimator_id=None, user_info=None):
"""
Calls the C interface fit function in the library.
(see also http://gpufit.readthedocs.io/en/latest/bindings.html#python)
All 2D Num... | 28,554 |
def json_get(cid, item):
"""gets item from json file with user settings"""
with open('data/%s.json' %cid) as f:
user = json.load(f)
return user[item] | 28,555 |
def debug_info():
""" This function varies version-by-version, designed to help the authors of this package when there's an issue.
Returns:
A dictionary that contains debug info across the interpret package.
"""
from . import __version__, status_show_server
debug_dict = {}
debug_dict["... | 28,556 |
def adaptive_monte_carlo(func, z_min, z_max, epsilon):
"""
Perform adaptive Monte Carlo algorithm to a specific function. Uniform random variable is used in this case.
The calculation starts from 10 division of the original function range. Each step, it will divide the region which has the largest variance.... | 28,557 |
def compute_statistics(measured_values, estimated_values):
"""Calculates a collection of common statistics comporaring the measured
and estimated values.
Parameters
----------
measured_values: numpy.ndarray
The experimentally measured values with shape=(number of data points)
estimated_... | 28,558 |
def num_encode(n):
"""Convert an integer to an base62 encoded string."""
if n < 0:
return SIGN_CHARACTER + num_encode(-n)
s = []
while True:
n, r = divmod(n, BASE)
s.append(ALPHABET[r])
if n == 0:
break
return u''.join(reversed(s)) | 28,559 |
def hard_example_mining(dist_mat, labels, return_inds=False):
"""For each anchor, find the hardest positive and negative sample.
Args:
dist_mat: pytorch Variable, pair wise distance between samples, shape [N, N]
labels: pytorch LongTensor, with shape [N]
return_inds: whether to return the indi... | 28,560 |
def failure_comment(request, comment_id):
"""Отклоняет отзыв с указанием причины"""
user = request.user
comment = Comment.objects.get(recipient_user=user.id, id=comment_id, failure=False)
form = AcceptForm(request.POST or None, initial=model_to_dict(comment), instance=comment)
if form.is_valid():
... | 28,561 |
def CodedVideoGrain(src_id_or_meta=None,
flow_id_or_data=None,
origin_timestamp=None,
creation_timestamp=None,
sync_timestamp=None,
rate=Fraction(25, 1),
duration=Fraction(1, 25),
... | 28,562 |
def test_log_likelihood(model, X_test, y_test):
""" Marginal log likelihood for GPy model on test data"""
_, test_log_likelihood, _ = model.inference_method.inference(
model.kern.rbf_1, X_test, model.likelihood.Gaussian_noise_1, y_test,
model.mean_function, model.Y_metadata)
return test_log_... | 28,563 |
def test_object_buffered_base_io():
"""Tests airfs._core.io_buffered.ObjectBufferedIOBase"""
from airfs._core.io_base_raw import ObjectRawIOBase
from airfs._core.io_base_buffered import ObjectBufferedIOBase
from airfs._core.io_random_write import (
ObjectRawIORandomWriteBase,
ObjectBuffe... | 28,564 |
def fov_geometry(release='sva1',size=[530,454]):
"""
Return positions of each CCD in PNG image for
a given data release.
Parameters:
release : Data release name (currently ['sva1','y1a1']
size : Image dimensions in pixels [width,height]
Returns:
list : A list of [id, x... | 28,565 |
def parse_descriptor(desc: str) -> 'Descriptor':
"""
Parse a descriptor string into a :class:`Descriptor`.
Validates the checksum if one is provided in the string
:param desc: The descriptor string
:return: The parsed :class:`Descriptor`
:raises: ValueError: if the descriptor string is malforme... | 28,566 |
def HHMMSS_to_seconds(string):
"""Converts a colon-separated time string (HH:MM:SS) to seconds since
midnight"""
(hhs,mms,sss) = string.split(':')
return (int(hhs)*60 + int(mms))*60 + int(sss) | 28,567 |
def create_check_warnings_reference(warnings_file):
"""Read warnings_file and compare it with the warnings the compiler
actually reported. If the reference file is missing we just check that
there are any warnings at all."""
if not os.path.isfile(warnings_file):
return check_missing_warnings
... | 28,568 |
def gis_location_onaccept(form):
"""
On Accept for GIS Locations (after DB I/O)
"""
if session.rcvars and hasattr(name_dummy_element, "onaccept"):
# HTML UI, not XML import
name_dummy_element.onaccept(db, session.rcvars.gis_location, request)
else:
location_id = form.vars... | 28,569 |
def fetch_user_profile(user_id):
"""
This function lookup a dictionary given an user ID. In production, this should be replaced
by querying external database.
user_id: User ID using which external Database will be queried to retrieve user profile.
return: Returns an user profile corresponding to th... | 28,570 |
def _replace_token_range(tokens, start, end, replacement):
"""For a range indicated from start to end, replace with replacement."""
tokens = tokens[:start] + replacement + tokens[end:]
return tokens | 28,571 |
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_train = X.shape[0]
num_classes = W.shape[1]
num_dimensions = X.shape[... | 28,572 |
def test_var_length_array():
"""Check that length of dict <= length of columns in an array when passed an array."""
plots = make_qqplot(data_array)
assert len(plots.keys()) <= data_array.shape[1] | 28,573 |
def test_calling_start_on_connection_observer_returns_itself(do_nothing_connection_observer__for_major_base_class,
connection_to_remote):
"""
connection_observer.start() is asynchronous run. Return itself to allow for acting on it.
Simplest (stupi... | 28,574 |
def norm(a):
"""normalizes input matrix between 0 and 1
Args:
a: numpy array
Returns:
normalized numpy array
"""
return (a - np.amin(a))/(np.amax(a)-np.amin(a)) | 28,575 |
def input_apply_for_lock(driver):
"""进入门锁申请页面"""
if driver.hasElement(driver.ele.WebView_TitleBar_Title):
driver.assertEqual(driver.ele.MS_XZWebViewActivit, driver.driver.current_activity, '进入门锁介绍页失败')
driver.find_element_desc_click_wait('申请门锁服务')
else:
driver.assertEqual(driver.ele.... | 28,576 |
def collect_path(rf, method="quick", verbose=True):
"""
Collect paths from RandomForest objects. This function is the most time-consuming part.
Output:
A list of outputs from get_path_to_max_prediction_terminal_node.
"""
n_tree = len(rf)
result = []
if method == "quick":
... | 28,577 |
def calculate_variance(beta):
"""
This function calculates variance of curve beta
:param beta: numpy ndarray of shape (2,M) of M samples
:rtype: numpy ndarray
:return variance: variance
"""
n, T = beta.shape
betadot = gradient(beta, 1. / (T - 1))
betadot = betadot[1]
normbetad... | 28,578 |
def get_datastore_mo(client, soap_stub,
datacenter_name, datastore_name):
"""
Return datastore managed object with specific datacenter and datastore name
"""
datastore = get_datastore(client, datacenter_name, datastore_name)
if not datastore:
return None
datastore_mo... | 28,579 |
def _merge_dictionaries(dict1: dict, dict2: dict) -> dict:
"""
Recursive merge dictionaries.
:param dict1: Base dictionary to merge.
:param dict2: Dictionary to merge on top of base dictionary.
:return: Merged dictionary
"""
for key, val in dict1.items():
if isinstance(val, dict):
... | 28,580 |
def integrate_profile(rho0, s0, r_s, r_1, rmax_fac=1.2, rmin_fac=0.01,
r_min=None, r_max=None):
"""
Solves the ODE describing the to obtain the density profile
:returns: the integration domain in kpc and the solution to the density profile in M_sun / kpc^3
"""
G = 4.3e-6 # u... | 28,581 |
def main():
""" Disable FSYNC
"""
# Disable fsync to fix saving issues
util.disable_fsync() | 28,582 |
def create_eval_dataset(
task,
batch_size,
subset):
"""Create datasets for evaluation."""
if batch_size % jax.device_count() != 0:
raise ValueError(f"Batch size ({batch_size}) must be divisible by "
f"the number of devices ({jax.device_count()}).")
per_device_batch_size = batc... | 28,583 |
def rad2deg(angle):
"""
Converts radians to degrees
Parameters
----------
angle : float, int
Angle in radians
Returns
-------
ad : float
Angle in radians
Examples
--------
>>> rad2deg(pi)
180.000000000000
>>> rad2deg(pi/2)
... | 28,584 |
def center_crop(im, size, is_color=True):
"""
Crop the center of image with size.
Example usage:
.. code-block:: python
im = center_crop(im, 224)
:param im: the input image with HWC layout.
:type im: ndarray
:param size: the cropping size.
:type size: int
:param is... | 28,585 |
def read_json(file_path: str) -> Jelm:
"""reads from a json file path"""
with open(file_path) as fp:
dump = fp.read()
return reads_json(dump) | 28,586 |
def fillCells(cell_bounds, rdx, rdy, rdbathy, dlim=0.0, drymin=0.0,
drymax=0.99, pland=None, rotated=False,
median_depth=False, smc=False, setadj=False):
"""Returns a list of depth and land-sea data to correspond
with cell bounds list"""
print('[INFO] Calculating cell ... | 28,587 |
def main(path):
"""
from dal import DAL, Field
db=DAL('sqlite://catalog.sqlite')
db.define_table('catalog_folder',
Field('root_id','reference catalog_folder'),
Field('path'),
Field('title'),
Field('header','text'),
... | 28,588 |
def convert_format(input_path, output_path):
"""Convert format."""
input_string = Path(input_path).read_text()
tree = read_newick(input_string)
output_string = write_newick(tree)
Path(output_path).write_text(output_string) | 28,589 |
def submitter(commander):
"""Submits commands directly to the command line and waits for the process to finish."""
submiting = subprocess.Popen(commander,shell=True)
submiting.wait() | 28,590 |
def mark_item_complete(todo: TodoAndCompleted, idx: int) -> TodoAndCompleted:
"""
Pop todo['todo'][idx] and append it to todo['complete'].
Parameters
----------
todo : TodoAndCompleted
A dict containing a to-do list and a list of completed tasks.
idx : int
Index of an item to mo... | 28,591 |
def draw_legs():
"""left and right leg"""
radius = constants["radius"]
legs = constants["legs"]
# I got really lazy here sorry
# leftmost
peon.seth(270)
peon.pencolor("dark gray")
peon.pu()
peon.circle(radius, legs["principal"])
peon.rt(90)
peon.pd()
peon.forward(50)
... | 28,592 |
def spatial_pyramid_pooling_2d(x, pyramid_height, pooling_class=None,
pooling=None):
"""Spatial pyramid pooling function.
It outputs a fixed-length vector regardless of input feature map size.
It performs pooling operation to the input 4D-array ``x`` with different
kerne... | 28,593 |
def test_preloadTestDbs():
"""
Test preloadTestDbs
"""
print("Testing staging dbs")
priming.setupTest()
dbEnv = dbing.gDbEnv
dbing.preloadTestDbs()
agents = dbing.getAgents()
assert agents == ['did:igo:3syVH2woCpOvPF0SD9Z0bu_OxNe2ZgxKjTQ961LlMnA=',
'did:igo:QBRK... | 28,594 |
async def retrieve_seasons_and_teams(client, url): # noqa: E999
"""
Retrieves seasons and teams for a single player.
"""
doc = await get_document(client, url)
teams = doc.xpath(
"//table[@id='stats_basic_nhl' or @id='stats_basic_plus_nhl']" +
"/tbody/tr/td[2]/a/text()")
seasons ... | 28,595 |
def plot_cartpole_policy(policy, env, deterministic, plot=True, figname="cartpole_actor.pdf", save_figure=True) -> None:
"""
Plot a policy for a cartpole environment
:param policy: the policy to be plotted
:param env: the evaluation environment
:param deterministic: whether the deterministic version... | 28,596 |
def array_match_difference_1d(a, b):
"""Return the summed difference between the elements in a and b."""
if len(a) != len(b):
raise ValueError('Both arrays must have the same length')
if len(a) == 0:
raise ValueError('Arrays must be filled')
if type(a) is not np.ndarray:
a = np... | 28,597 |
def finder(ll, lats, longs, APIs, pad, max_dist=0.05):
"""
Determine which lats and longs are within the criteria
distance of ll to be included in the same pad
The function is designed for use in a recursive program
:input ll: latitude and longitude of a point to be considered
:input lats: a sor... | 28,598 |
def data_len(system: System) -> int:
"""Compute number of entries required to serialize all entities in a system."""
entity_lens = [entity.state_size() + entity.control_size() for entity in system.entities]
return sum(entity_lens) | 28,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.