content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def rytz_axis_construction(d1: Vector, d2: Vector) -> Tuple[Vector, Vector, float]:
"""
The Rytz’s axis construction is a basic method of descriptive Geometry to find the axes, the semi-major
axis and semi-minor axis, starting from two conjugated half-diameters.
Source: `Wikipedia <https://en.m.wikiped... | 5,341,300 |
def _join_ljust(words, width=9):
"""join list of str to fixed width, left just"""
return ' '.join(map(lambda s: s.ljust(width), words)).strip() | 5,341,301 |
def construct_dictionaries(color,marker,size,
scatter_ecolor='k',
alpha=1.0,
fill_scatter=False,
elinewidth=1,capsize=0):
"""
Example usage:
halo_kws = construct_dictionaries('k','o', 20, alpha=.3)
... | 5,341,302 |
def to_file(exp_dir, chain):
"""Write results to file
:param exp_dir: directory to export
:param chain: Chain object
:raise RoutineErr: on file I/O error
:return True: on success
"""
now = datetime.datetime.today().strftime('%Y%m%d-%H%M%S-%f')
file_name = os.path.join(exp_dir, 'chains... | 5,341,303 |
def override_config(config):
"""Overrides the above global parameters used by the Agent."""
global BUFFER_SIZE, BATCH_SIZE
global GAMMA, TAU, TAU_INCREASE
global LR_ACTOR, LR_CRITIC, WEIGHT_DECAY
global NOISE_THETA, NOISE_SIGMA
global ALPHA, EPSILON_ERROR, MAXIMUM_ERROR
global RANDOM_A... | 5,341,304 |
def test_slurm(region, pcluster_config_reader, clusters_factory):
"""
Test all AWS Slurm related features.
Grouped all tests in a single function so that cluster can be reused for all of them.
"""
scaledown_idletime = 3
max_queue_size = 5
cluster_config = pcluster_config_reader(scaledown_id... | 5,341,305 |
def rename_lab(lab_list: ui.layers.ListLayer, lab):
"""Rename a lab"""
window = ui.get_window()
labs = data.get_labs()
text_input = ui.layers.TextInputLayer("Rename Lab")
text_input.set_prompt(["Enter Lab's new name"])
text_input.set_text(lab.name)
window.run_layer(text_input)
if not te... | 5,341,306 |
def arrows(m) -> str:
"""One or more arrows separate by a space"""
return m.arrow_list | 5,341,307 |
def hex2int(hex_str):
"""
Convert 2 hex characters (e.g. "23") to int (35)
:param hex_str: hex character string
:return: int integer
"""
return int(hex_str, 16) | 5,341,308 |
def lat_2_R(lat):
"""Takes a geodetic latitude and puts out the distance from the center of an ellipsoid Earth to the surface
Arguments:
lat (float): Geodetic Latitude angle [degrees].
Returns:
(float): Geocentric distance [km]
"""
R_polar = 6356.752314245
R_eq = 6378.137
... | 5,341,309 |
def compare_records(old_list, new_list):
"""Compare two lists of SeqRecord objects."""
assert isinstance(old_list, list)
assert isinstance(new_list, list)
assert len(old_list) == len(new_list)
for old_r, new_r in zip(old_list, new_list):
if not compare_record(old_r, new_r):
retur... | 5,341,310 |
def embed_owners_wallet(address, asset_name) -> Embed:
"""Return discord embed of wallet owner"""
title = f"{asset_name} is owned by"
description = f"`{address}`"
color = Colour.blurple()
embed = Embed(title=title, description=description, color=color)
name = "This address belongs to wallet...... | 5,341,311 |
def Qdist_H_lm_jk_FGH(a, b, c , d, N_x, N_y, h, par, model):
"""
Parameters
----------
a : TYPE
left end point of the interval in x coordinate chosen for solving the time independent schrodinger equation.
b : TYPE
right end point of the interval in x coordinate chosen ... | 5,341,312 |
def test_gateway_bad_protocol():
"""Test initializing gateway with a bad protocol_version."""
gateway = Gateway(protocol_version=None)
assert gateway.protocol_version == '1.4' | 5,341,313 |
def get_log_configuration_retention_backup_log_days(host_id):
"""Return LOG_CONFIGURATION_RETENTION_BACKUP_LOG_DAYS"""
from django.core.exceptions import ObjectDoesNotExist
from physical.models import Host
from backup.models import LogConfiguration
try:
host = Host.objects.get(id=host_id)
... | 5,341,314 |
def createLabelsAndWeightsFromRois(image, roiimage):
"""Create class labels and instance labels.
Args:
image: input image
roiimage: input mask image
Returns:
classlabelsdata, instancelabelsdata, total_instances
"""
logger.info("Creating class and instance labels ...")
... | 5,341,315 |
def write_poscar(structure, filepath='POSCAR', newformat=True, direct=True, comment=None, heterostructure=False):
"""
Takes an structure from pychemia and save the file
POSCAR for VASP.
:param comment: Optional comment to the first line of the POSCAR
:param structure: (pychemia.Structure) Structure... | 5,341,316 |
def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K):
"""One bisection step of complex root refinement algorithm. """
hx, hy = dx/2, dy/2
cx, cy = x + hx, y + hy
F1, F2, F3, F4 = F
Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K)
Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K)
... | 5,341,317 |
def print_dataset_info(superclasses,
subclass_splits,
label_map,
label_map_sub):
"""
Obtain a dataframe with information about the
superclasses/subclasses included in the dataset.
Args:
superclasses (list): WordNet IDs of super... | 5,341,318 |
def mock_sync_cavatica_account(mocker):
""" Mocks out sync Cavatica account functions """
sync_cavatica_account = mocker.patch(
"creator.projects.cavatica.sync_cavatica_account"
)
sync_cavatica_account.return_value = [], [], []
return sync_cavatica_account | 5,341,319 |
def test_name():
"""Test get a random name"""
name1 = helper.role.name()
name2 = helper.role.name()
assert isinstance(name1, str)
assert isinstance(name2, str)
assert len(name1) > 4
assert len(name2) > 4
assert name1 != name2 | 5,341,320 |
def check_illegal(s):
"""
:param s: (String) user input
:return: (Bool) check user input is illegal or not
"""
check = 0
for ch in s:
if len(ch) > 1:
check = 1
if check == 0:
return True
else:
print("Illegal input")
return False | 5,341,321 |
def test_directory_update(runcutty: RunCutty, template: Path, project: Path) -> None:
"""It uses the template directory specified when updating."""
directory = "a"
move_repository_files_to_subdirectory(template, directory)
runcutty("update", f"--cwd={project}", f"--template-directory={directory}")
... | 5,341,322 |
def phasefold(time, rv, err, period):
"""Phasefold an rv timeseries with a given period.
Parameters
----------
time : array_like
An array containing the times of measurements.
rv : array_like
An array containing the radial-velocities.
err : array_like
An array containing ... | 5,341,323 |
def get_att_mats(translate_model):
"""
Get's the tensors representing the attentions from a build model.
The attentions are stored in a dict on the Transformer object while building
the graph.
:param translate_model: Transformer object to fetch the attention weights from.
:return:
"""
... | 5,341,324 |
def get_resource_string(package, resource):
"""Return a string containing the contents of the specified resource.
If the pathname is absolute it is retrieved starting at the path of
the importer for 'fullname'. Otherwise, it is retrieved relative
to the module within the loader.
"""
provider, ... | 5,341,325 |
def get_initialize_cams(number_of_camera = 7,use_camera=True):
""" initialize all camera
Args:
number_of_camera (int, optional): [description]. Defaults to 7.
Returns:
list : in list cap object
"""
cap_list=[]
if use_camera:
for _ in range(1,number_of_camera+1):
... | 5,341,326 |
def vpc_security_group_list(rds_instance):
""" If VPC security group rule is open to public add to List and return.
Args:
rds_instance (dict):
All the running rds instance on the region
Returns:
list: List of VPC Security Group Id's
"""
vpc_list = []... | 5,341,327 |
def parse_commands(docstring):
# type: (str) -> Generator[Tuple[List[str], List[str]], None, None]
"""Parse a docopt-style string for commands and subcommands.
Args:
docstring: A docopt-style string to parse. If the string is not a valid
docopt-style string, it will not yield and values... | 5,341,328 |
def check_host(host):
"""Check Server IP."""
error_msg = "Check server IP and port! Wrong format of server name or no connection."
if not host:
print(error_msg)
exit(1)
try:
socket.gethostbyname(host)
except:
print(error_msg)
exit(1) | 5,341,329 |
def tests(session):
"""Run tests."""
session.install('-r', 'requirements.txt')
session.run('pytest') | 5,341,330 |
def register_root_api(app: Flask):
"""Register the API with the flask app."""
ROOT_API.init_app(app)
# register API blueprints (only do this after the API is registered with flask!)
ROOT_API.register_blueprint(ROOT_ENDPOINT)
ROOT_API.register_blueprint(API_V1) | 5,341,331 |
def expectation_l(u_values, params_list):
"""
compute proba for each copula mix to describe the data
:param u_values:
:param params_list:
:return:
"""
l_state = np.zeros((u_values.shape[0], len(COPULA_DENSITY)))
dcopula = np.zeros((u_values.shape[0], len(COPULA_DENSITY)))
for copula ... | 5,341,332 |
def test_load_dataset_generator():
"""Testing if the function load_dataset_generator() works."""
generator = dataset.load_dataset_generator(dataset_path)
data = next(generator)
assert data["steering"] == -0.6 and data["throttle"] == 0.7
data = next(generator)
assert data["steering"] == 0.33 an... | 5,341,333 |
def lanczosSubPixShift( imageIn, subPixShift, kernelShape=3, lobes=None ):
""" lanczosSubPixShift( imageIn, subPixShift, kernelShape=3, lobes=None )
imageIn = input 2D numpy array
subPixShift = [y,x] shift, recommened not to exceed 1.0, should be float
Random values of kernelShape ... | 5,341,334 |
def test_retry_timeout_retries_timeouts():
"""Test retrying timeout."""
calls = []
def api(*args, **kwargs):
"""Mock api"""
calls.append((args, kwargs))
if len(calls) == 1:
raise RequestTimeout()
retry_api = retry_timeout(api, retries=2)
retry_api(1, 2, hello=... | 5,341,335 |
def open_pdb(file_location):
"""
Opens PDB File.
Parameters
__________
file_location : str
The Location for the PDB File.
Returns
_______
symbols : list
Gives Atomic Symbols for Atoms from PDB File.
coordinates: np.ndarray
Gives Atomic... | 5,341,336 |
def _remove_statements(evaluator, stmt, name):
"""
This is the part where statements are being stripped.
Due to lazy evaluation, statements like a = func; b = a; b() have to be
evaluated.
"""
types = []
# Remove the statement docstr stuff for now, that has to be
# implemented with the e... | 5,341,337 |
def transform_vector_global_to_local_frame(
vector: Tuple[float, float, float], theta: float
) -> Tuple[float, float, float]:
"""
Transform a vector from global frame to local frame.
:param vector: the vector to be rotated
:param theta: the amount to rotate by
:return the transformed vector.
... | 5,341,338 |
def given_source_ids_get_tic8_data(source_ids, queryname, n_max=10000,
overwrite=True,
enforce_all_sourceids_viable=True):
"""
Args:
source_ids (np.ndarray) of np.int64 Gaia DR2 source_ids
queryname (str): used for files
... | 5,341,339 |
def kadane_algorithm(sequence: List[int]):
"""Greedy algorithm to track max sum so far - O(n) time and O(1) space"""
if len(sequence) < 1:
return 0
max_sum = sequence[0]
curr_sum = sequence[0]
for curr_index in range(1, len(sequence)):
curr_sum = max(sequence[curr_index], curr_sum... | 5,341,340 |
def allow_domains(request: HttpRequest, domains: Iterable[str]) -> HttpResponse:
"""
Serves a cross-domain access policy allowing a list of domains.
Note that if this is returned from the URL ``/crossdomain.xml`` on
a domain, it will act as a master policy and will not permit other
policies to exis... | 5,341,341 |
def get_Cs_OR():
"""その他の居室の照明区画iに設置された照明設備の人感センサーによる補正係数
Args:
Returns:
float: Cs_OR その他の居室の照明区画iに設置された照明設備の人感センサーによる補正係数
"""
return 1.0 | 5,341,342 |
def test_get_by_call_once_behavior() -> None:
"""It should consume any behavior marked with the `once` flag."""
subject = StubStore()
rehearsal = WhenRehearsal(spy_id=42, spy_name="my_spy", args=(1, 2, 3), kwargs={})
behavior = StubBehavior(return_value="fizzbuzz", once=True)
subject.add(rehearsal=... | 5,341,343 |
def build_url(station, d1, d2):
"""
Return the URL to fetch the response record for USArray MT station
identifier *station* for the time range *d1* to *d2*.
"""
return 'http://service.iris.edu/irisws/resp/1/query?net=EM&sta={}&loc=--&cha=*&starttime={:%Y-%m-%dT%H:%M:%S}&endtime={:%Y-%m-%dT%H:%M:%S}'... | 5,341,344 |
def FindGitSubmoduleCheckoutRoot(path, remote, url):
"""Get the root of your git submodule checkout, looking up from |path|.
This function goes up the tree starting from |path| and looks for a .git/ dir
configured with a |remote| pointing at |url|.
Arguments:
path: The path to start searching from.
re... | 5,341,345 |
def get_tlinks(timeml_doc):
""" get tlinks from annotated document """
root = xml_utilities.get_root(timeml_doc)
tlinks = []
for e in root:
if e.tag == "TLINK":
tlinks.append(e)
return tlinks | 5,341,346 |
def stack(xs: Sequence[Any], axis: int = 0) -> Any:
"""
Stack the (leaf) arrays from xs
:param xs: list of trees with the same shape, where the leaf values are numpy arrays
:param axis: axis to stack along
"""
return multimap(lambda *xs: np.stack(xs, axis=axis), *xs) | 5,341,347 |
def load_LAC_geocodes_info(path_to_csv):
"""Import local area unit district codes
Read csv file and create dictionary with 'geo_code'
PROVIDED IN UNIT?? (KWH I guess)
Note
-----
- no LAD without population must be included
"""
with open(path_to_csv, 'r') as csvfile:
read_lines ... | 5,341,348 |
def singleton(class_):
"""Decorator for singleton class."""
instances = {}
def get_instance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return get_instance | 5,341,349 |
def convert_model_to_half(model):
"""
Converts model to half but keeps the batch norm layers in 32 bit for precision purposes
"""
old_model = model
new_model = BN_convert_float(model.half())
del old_model # Delete previous non-half model
return new_model | 5,341,350 |
def tokenize_sentences(sentences):
"""
Tokenize sentences into tokens (words)
Args:
sentences: List of strings
Returns:
List of lists of tokens
"""
# Initialize the list of lists of tokenized sentences
tokenized_sentences = []
### START CODE HERE (Replace i... | 5,341,351 |
def optimize_syscalls(declares):
"""Disables filesystem if only a limited subset of syscalls is used.
Our syscalls are static, and so if we see a very limited set of them - in particular,
no open() syscall and just simple writing - then we don't need full filesystem support.
If FORCE_FILESYSTEM is set, we can'... | 5,341,352 |
def verify_credential_info():
"""
This url is called to verify and register the token
"""
challenge = session["challenge"]
username = session["register_username"]
display_name = session["register_display_name"]
ukey = session["register_ukey"]
user_exists = database.user_exists(username)
... | 5,341,353 |
def makeId(timestamp = 0, machine = 0, flow = 0):
"""
using unix style timestamp, not python timestamp
"""
timestamp -= _base
return (timestamp<<13) | (machine << 8) | flow | 5,341,354 |
def chi2Significant(tuple, unigrams, bigrams):
"""Returns true, if token1 and token2 are significantly coocurring,
false otherwise. The used test is the Chi2-test.
Parameters:
tuple: tuple of tokens
unigrams: unigrams dictionary data structure
bigrams: bigrams dictionary... | 5,341,355 |
def excel2schema(schema_excel_filename, schema_urlprefix, options, schema_dir=None):
""" given an excel filename, convert it into memory object,
and output JSON representation based on options.
params:
schema_excel_filename -- string, excel filename
schema_urlprefix -- strin... | 5,341,356 |
def assign_id_priority(handle):
"""
Assign priority according to agent id (lower id means higher priority).
:param agent:
:return:
"""
return handle | 5,341,357 |
def setup_logging(
filename,
print_level="INFO",
file_level="DEBUG",
multiprocessing_aware=True,
):
"""
Sets up (possibly multiprocessing aware) logging.
:param filename: Where to save the logs to
:param print_level: What level of logging to print to console.
Default: 'INFO'
:par... | 5,341,358 |
def learning_rate_with_decay(
batch_size, batch_denom, num_images, boundary_epochs, decay_rates):
"""Get a learning rate that decays step-wise as training progresses.
Args:
batch_size: the number of examples processed in each training batch.
batch_denom: this value will be used to scale the... | 5,341,359 |
def test_custom_class(
content_view: Tuple[str, ContentView],
serialization_format: Tuple[str, SerializationFormat],
):
"""Ensure an error is provided when something can't be serialized.
A typing error does not exist here because the content is Dict[str, Any].
:param content_view: The content view... | 5,341,360 |
def run_parent():
"""
Running in the parent process.
"""
print("启动行情记录守护父进程")
# Chinese futures market trading period (day/night)
DAY_START = time(8, 45)
DAY_END = time(15, 30)
NIGHT_START = time(20, 45)
NIGHT_END = time(2, 45)
child_process = None
while True:
cur... | 5,341,361 |
def change_lock_status(title, new_lock_status, default=False, forced=False):
"""
This is called when a user starts or stops editing a
page
"""
title = title.replace(" ", "_")
if default:
return
# If this function is called from
# is_locked due to the page being expired...
if ... | 5,341,362 |
def stepedit_SignType(*args):
"""
* Returns a SignType fit for STEP (creates the first time)
:rtype: Handle_IFSelect_Signature
"""
return _STEPEdit.stepedit_SignType(*args) | 5,341,363 |
def create_heatmap(out, data, row_labels, col_labels, title, colormap, vmax, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Arguments:
data : A 2D numpy array of shape (N,M)
row_labels : A list or array of len... | 5,341,364 |
def flip(c1, c2):
"""last 8 secs in total"""
for i in range(0, 10): # 10*0.2 = 4secs
setColor(c1)
time.sleep(0.2)
setColor(c2)
time.sleep(0.2)
for i in range(0, 20): # 20*0.1 = 4secs
setColor(c1)
time.sleep(0.1)
setColor(c2)
time.sleep(0.1)
... | 5,341,365 |
def ccw(a: complex, b: complex, c: complex) -> int:
"""The sign of counter-clockwise angle of points abc.
Args:
a (complex): First point.
b (complex): Second point.
c (complex): Third point.
Returns:
int: If the three points are not colinear, then returns the sign of
... | 5,341,366 |
def uninitializePlugin(obj):
"""
"""
pluginFn = om.MFnPlugin(obj)
try:
omr.MDrawRegistry.deregisterDrawOverrideCreator(DRAW_DB_CLASSIFICATION, DRAW_REGISTRANT_ID)
except:
om.MGlobal.displayError("Failed to deregister draw override: {0}".format(PLUGIN_NAME))
try:
pluginF... | 5,341,367 |
def _tree_selector(X, leaf_size=40, metric='minkowski'):
"""
Selects the better tree approach for given data
Parameters
----------
X : {array-like, pandas dataframe} of shape (n_samples, n_features)
The input data.
leaf_size : int, default=40
Number of points to switch to brute-... | 5,341,368 |
def test_rxcui_output():
"""
Test that get_rxcui() outputs a string
with the correct format.
"""
output = get_rxcui(drug_id='lipitor', id_type='name')
assert(isinstance(output, str))
assert(output=="153165") | 5,341,369 |
def get_diff_objects(diff_object_mappings, orig_datamodel_object_list):
"""获取diff_objects
:param diff_object_mappings: 变更对象内容mapping
:param orig_datamodel_object_list: 操作前/上一次发布内容列表
:return: diff_objects: diff_objects列表
"""
# 1)从diff_object_mappings中获取diff_objects
diff_objects = []
fie... | 5,341,370 |
def find_lcs(s1, s2):
"""find the longest common subsequence between s1 ans s2"""
m = [[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)]
max_len = 0
p = 0
for i in range(len(s1)):
for j in range(len(s2)):
if s1[i] == s2[j]:
m[i + 1][j + 1] = m[i][j] + 1... | 5,341,371 |
def calculate_vertical_vorticity_cost(u, v, w, dx, dy, dz, Ut, Vt,
coeff=1e-5):
"""
Calculates the cost function due to deviance from vertical vorticity
equation. For more information of the vertical vorticity cost function,
see Potvin et al. (2012) and Shapiro et a... | 5,341,372 |
def fetch_hero_stats() -> list:
"""Retrieves hero win/loss statistics from OpenDotaAPI."""
r = httpx.get("https://api.opendota.com/api/heroStats")
heroes = r.json()
# Rename pro_<stat> to 8_<stat>, so it's easier to work with our enum
for hero in heroes:
for stat in ["win", "pick", "ban"]:
... | 5,341,373 |
def test_source_locations_are_within_correct_range(tokamak_source):
"""Tests that each source has RZ locations within the expected range.
As the function converting (a,alpha) coordinates to (R,Z) is not bijective,
we cannot convert back to validate each individual point. However, we can
determine wheth... | 5,341,374 |
def print_blue(txt, with_bgc=None, no_end=False):
"""
普通蓝色
:param txt:
:param with_bgc: 需要添加的背景色,默认不显示
:return:
"""
if plat == "Linux":
print(color(txt, "default", with_bgc or "ordinary", "blue"), end='' if no_end else '\n')
elif plat == "Windows":
print(Fore.BLUE + win_b... | 5,341,375 |
def GetTDryBulbFromEnthalpyAndHumRatio(MoistAirEnthalpy: float, HumRatio: float) -> float:
"""
Return dry bulb temperature from enthalpy and humidity ratio.
Args:
MoistAirEnthalpy : Moist air enthalpy in Btu lb⁻¹ [IP] or J kg⁻¹
HumRatio : Humidity ratio in lb_H₂O lb_Air⁻¹ [IP] or kg_H₂O kg... | 5,341,376 |
def test_vector_interpolation_projection():
"""Test projection interpolation."""
vec = plonk.visualize.interpolation.vector_interpolation(
x_data=X_DATA,
y_data=Y_DATA,
x_position=XX,
y_position=YY,
z_position=ZZ,
extent=EXTENT,
smoothing_length=HH,
... | 5,341,377 |
def calibration_runs(instr, exper, runnum=None):
"""
Return the information about calibrations associated with the specified run
(or all runs of the experiment if no specific run number is provided).
The result will be packaged into a dictionary of the following type:
<runnum> : { 'calibrations... | 5,341,378 |
def fetch_eia(api_key, plant_id, file_path):
"""
Read in EIA data of wind farm of interest
- from EIA API for monthly productions, return monthly net energy generation time series
- from local Excel files for wind farm metadata, return dictionary of metadata
Args:
api_key(:obj:`string`): 32... | 5,341,379 |
def print_version():
"""
Prints the version of the package and the license.
"""
version_text = """
This is mk-deps, version {version}
Copyright (C) 2017 Livio Brunner
This program comes with ABSOLUTELY NO WARRANTY.
You are free to redistribute this code under the terms of the
GNU General Public License... | 5,341,380 |
def gen_fathers():
"""
:return:
"""
return | 5,341,381 |
def calc_dist_mat(e: Extractor, indices: list) -> np.array:
"""
Calculates distance matrix among threads with indices specified
Arguments:
e : Extractor
extractor object
indices : list of ints
list of indices corresponding to which threads are present for the distance matrix calculation
"""
# initiali... | 5,341,382 |
def spitzer_conductivity2(nele, tele, znuc, zbar):
"""
Compute the Spitzer conductivity
Parameters:
-----------
- nele [g/cm³]
- tele [eV]
- znuc: nuclear charge
- zbar: mean ionization
Returns:
--------
- Spitzer conductivity [cm².s⁻¹]
"""
lnLam = coulomb_loga... | 5,341,383 |
def assert_tree_all_finite(tree_like: ArrayTree):
"""Assert all tensor leaves in a tree are finite.
Args:
tree_like: pytree with array leaves
Raises:
AssertionError: if any leaf in the tree is non-finite.
"""
all_finite = jax.tree_util.tree_all(
jax.tree_map(lambda x: jnp.all(jnp.isfinite(x)),... | 5,341,384 |
def parse_benchmark_results(benchmark_output, min_elements=None, max_elements=None):
"""
:type benchmark_output list[str]
:type min_elements int|None
:type max_elements int|None
:rtype BenchmarkResults
:return The parsed benchmark results file. The data member dict looks like this:
{
... | 5,341,385 |
def test_find_by_id_as(session):
"""Assert that find an amemdment registration by ID contains all expected elements."""
registration = Registration.find_by_id(200000008)
assert registration
assert registration.registration_id == 200000008
assert registration.registration_num
assert registration.... | 5,341,386 |
def test_load_config_rules(neo4j_session, *args):
"""
Ensure that expected delivery channels get loaded with their key fields.
"""
data = tests.data.aws.config.LIST_CONFIG_RULES
cartography.intel.aws.config.load_config_rules(
neo4j_session,
data,
TEST_REGION,
TEST_ACC... | 5,341,387 |
def is_doctest_running() -> bool:
"""
>>> if not is_setup_test_running(): assert is_doctest_running() == True
"""
# this is used in our tests when we test cli-commands
if os.getenv("PYTEST_IS_RUNNING"):
return True
for argv in sys.argv:
if is_doctest_in_arg_string(argv):
... | 5,341,388 |
def read_float_with_comma(num):
"""Helper method to parse a float string representation that has
a comma as decimal separator.
Can't use locale as the page being parsed could not be in the
same locale as the python running environment
Args:
num (str): the float string to parse
Returns... | 5,341,389 |
def rds_print_instance(dbinstanceid, full=False):
"""
Print RDS instance info.
:param dbinstanceid:
The id/name of the RDS instance.
:param full:
Print all attributes, or just the most useful ones? Defaults to
``False``.
"""
dbinstancewrapper = RdsInstanceWrapper.get_dbi... | 5,341,390 |
def remote_repr(arg):
"""Return the `repr()` rendering of the supplied `arg`."""
return arg | 5,341,391 |
def log(pathOrURL, limit=None, verbose=False, searchPattern=None, revision=None, userpass=None):
"""
:param pathOrURL: working copy path or remote url
:param limit: when the revision is a range, limit the record count
:param verbose:
:param searchPattern:
- search in the limited record... | 5,341,392 |
def value_cards(cards: [Card], trump: Suite, lead_suite: Suite) -> (Card, int):
"""Returns a tuple (card, point value) which ranks each card in a hand, point value does not matter"""
card_values = []
for card in cards:
if vm.is_trump(card, trump):
card_values.append((card, vm.trump_value... | 5,341,393 |
def com_google_fonts_check_ftxvalidator_is_available(ftxvalidator_cmd):
"""Is the command `ftxvalidator` (Apple Font Tool Suite) available?"""
if ftxvalidator_cmd:
yield PASS, f"ftxvalidator is available at {ftxvalidator_cmd}"
else:
yield WARN, \
Message("ftxvalidator-available... | 5,341,394 |
def submit_scraper_job(job_type, tag, params):
"""
Submits job
:param job_type:
:param tag:
:param params:
:return:
"""
rule = {
"rule_name": "bos_sarcat_scraper",
"queue": CRAWLER_QUEUE,
"priority": '8',
"kwargs": '{}'
}
print('submitting jobs wi... | 5,341,395 |
def mount_raw_image(path):
"""Mount raw image using OS specific methods, returns pathlib.Path."""
loopback_path = None
if PLATFORM == 'Darwin':
loopback_path = mount_raw_image_macos(path)
elif PLATFORM == 'Linux':
loopback_path = mount_raw_image_linux(path)
# Check
if not loopback_path:
std.pr... | 5,341,396 |
def timer(start, end, description=''):
"""https://stackoverflow.com/questions/27779677/how-to-format-elapsed-time-from-seconds-to-hours-minutes-seconds-and-milliseco
"""
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("{} {:0>2}:{:0>2}:{:05.2f}".format(description, int(... | 5,341,397 |
def calculate_weights_indices(in_length, out_length, scale, kernel_width, antialiasing):
"""
Get weights and indices
"""
if (scale < 1) and (antialiasing):
# Use a modified kernel to simultaneously interpolate and antialias- larger kernel width
kernel_width = kernel_width / scale
# ... | 5,341,398 |
def inject_config_into_engines(engine_prefix, config_path):
"""
Copy the current config into all engines that are managed by `sgr engine`. This
is so that the engine has the right credentials and settings for when we do
layered querying (a Postgres client queries the engine directly and it
has to do... | 5,341,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.