content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def controllerWalkLeft(node, add=False, multi=False):
"""Pick walks the next sibling to the left using controller tag
Arguments:
node (TYPE): Description
add (bool, optional): If true add to selection
multi (bool, optional): If true, selects all the siblings
"""
nodes = _getCont... | 22,400 |
def register_remap(remap_function, overwrite=False):
"""
Register a remap function for general usage.
Parameters
----------
remap_function : RemapFunction|Type
overwrite : bool
Should we overwrite any currently existing remap of the given name?
Returns
-------
None
"""
... | 22,401 |
def ape_insert_new_fex(cookie, in_device_primary_key, in_model, in_serial, in_vendor):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("ApeInsertNewFex")
method.cookie = cookie
method.in_device_primary_key = in_device_primary_key
method.in_model = in_model
method.in_serial = ... | 22,402 |
def save_data(df, database_file_path):
"""Save the data frame into a SQL database file in the specified path.
Parameters:
df (pandas.core.frame.DataFrame): The data frame to be saved as a SQL database file.
database_file_path (str): The path to save the SQL database file.
Returns:
... | 22,403 |
async def get_pool_info(address, api_url="https://rest.stargaze-apis.com/cosmos"):
"""Pool value and current rewards via rest API.
Useful links:
https://api.akash.smartnodes.one/swagger/#/
https://github.com/Smart-Nodes/endpoints
"""
rewards_url = f"{api_url}/distribution/v1beta1/delega... | 22,404 |
def check_for_unused_inames(kernel):
"""
Check if there are any unused inames in the kernel.
"""
# Warn if kernel has unused inames
from loopy.transform.iname import get_used_inames
unused_inames = kernel.all_inames() - get_used_inames(kernel)
if unused_inames:
warn_with_kernel(
... | 22,405 |
def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height:... | 22,406 |
def mnist_reader(numbers):
"""
Read MNIST dataset with specific numbers you needed
:param numbers: A list of number from 0 - 9 as you needed
:return: A tuple of a numpy array with specific numbers MNIST training dataset,
labels of the training set and the length of the training dataset.
... | 22,407 |
def _ensure_list(alist): # {{{
"""
Ensure that variables used as a list are actually lists.
"""
# Authors
# -------
# Phillip J. Wolfram, Xylar Asay-Davis
if isinstance(alist, six.string_types):
# print 'Warning, converting %s to a list'%(alist)
alist = [alist]
return ... | 22,408 |
def _parse_einsum_input(operands):
"""Parses einsum operands.
This function is based on `numpy.core.einsumfunc._parse_einsum_input`
function in NumPy 1.14.
Returns
-------
input_strings : str
Parsed input strings
output_string : str
Parsed output string
operands : list ... | 22,409 |
def convert_to_numpy(*args, **kwargs):
"""
Converts all tf tensors in args and kwargs to numpy array
Parameters
----------
*args :
positional arguments of arbitrary number and type
**kwargs :
keyword arguments of arbitrary number and type
Returns
-------
list
... | 22,410 |
async def delete_contact(
contact_key: int, hash: str, resource: Resource = Depends(get_json_resource)
):
"""
Delete the contact with the given key.
If the record has changed since the hash was obtained, a 409 error is returned.
"""
try:
await resource.delete(contact_key, hash)
excep... | 22,411 |
def update_model_instance_meta_schema(request, file_type_id, **kwargs):
"""copies the metadata schema from the associated model program aggregation over to the model instance aggregation
"""
# Note: decorator 'authorise_for_aggregation_edit' sets the error_response key in kwargs
if 'error_response' in ... | 22,412 |
def mypy_run(args):
"""Run mypy with given arguments and return the result."""
logger.log_cmd(["mypy"] + args)
try:
stdout, stderr, exit_code = run(args)
except BaseException:
logger.print_exc()
else:
for line in stdout.splitlines():
yield line, False
for ... | 22,413 |
def _calculate_permutation_scores_per_col(estimator, X, y, sample_weight, col_idx,
random_state, n_repeats, scorer):
"""Calculate score when `col_idx` is permuted."""
random_state = check_random_state(random_state)
# Work on a copy of X to to ensure thread-safety i... | 22,414 |
def get_statement_at_line(source: str, lineno: int, checker):
"""Get statements at line *lineno* from a source string.
:param source: The source to get the statements from.
:param lineno: Line number which the statement must include. Counted from 1.
:param checker: A function that checks each statement... | 22,415 |
def ptrace(Q, sel):
"""
Partial trace of the Qobj with selected components remaining.
Parameters
----------
Q : :class:`qutip.Qobj`
Composite quantum object.
sel : int/list
An ``int`` or ``list`` of components to keep after partial trace.
Returns
-------
oper : :cla... | 22,416 |
def createConformations(outputfile, forcefield, smiles, sid):
"""Generate the conformations for a molecule and save them to disk."""
print(f'Generating {index}: {smiles}')
try:
mol = Molecule.from_smiles(smiles, allow_undefined_stereo=True)
fftop = Topology()
fftop.add_molecule(mol)
... | 22,417 |
def two_angle_circular_correlation_coef(angles1, angles2, mean1, mean2):
"""
Circular correlation measure. SenGupta 2001
"""
centered_a = angles1-mean1
centered_b = angles2-mean2
sin_centered_a = numpy.sin(centered_a)
sin_centered_b = numpy.sin(centered_b)
sin2_a = sin_centered_a*sin_cen... | 22,418 |
def format_data(data: Union[dict, list]) -> str:
"""
:param data: input data
:return: pretty formatted yaml representation of a dictionary
"""
return yaml.dump(data, sort_keys=False, default_flow_style=False) | 22,419 |
def fasta2select(fastafilename, is_aligned=False,
ref_resids=None, target_resids=None,
ref_offset=0, target_offset=0, verbosity=3,
alnfilename=None, treefilename=None, clustalw="clustalw2"):
"""Return selection strings that will select equivalent residues.
The... | 22,420 |
def eval_on_dataset(
model, state, dataset,
pmapped_eval_step):
"""Evaluates the model on the whole dataset.
Args:
model: The model to evaluate.
state: Current state associated with the model (contains the batch norm MA).
dataset: Dataset on which the model should be evaluated. Should already
... | 22,421 |
def create_directory(path):
"""Creates the given directory and returns the path."""
if not os.path.isdir(path):
os.makedirs(path)
return path | 22,422 |
def factorize(n):
""" Prime factorises n """
# Loop upto sqrt(n) and check for factors
ret = []
sqRoot = int(n ** 0.5)
for f in xrange(2, sqRoot+1):
if n % f == 0:
e = 0
while n % f == 0:
n, e = n / f, e + 1
ret.append((f, e))
if n >... | 22,423 |
def createSimpleDataSet( numOfAttr, numOfObj ):
"""
This creates a simple data base with 3 attributes
The second one is 2 times the first one with some
Gauss noise. The third one is just random noise.
"""
database = []
for i in range(numOfObj):
data = dataObject(numOfAttr... | 22,424 |
def clean_data(
data,
isz=None,
r1=None,
dr=None,
edge=0,
bad_map=None,
add_bad=None,
apod=True,
offx=0,
offy=0,
sky=True,
window=None,
darkfile=None,
f_kernel=3,
verbose=False,
*,
mask=None,
):
"""Clean data.
Parameters:
-----------
... | 22,425 |
def describe_dataset_group(datasetGroupArn=None):
"""
Describes the given dataset group. For more information on dataset groups, see CreateDatasetGroup .
See also: AWS API Documentation
Exceptions
:example: response = client.describe_dataset_group(
datasetGroupArn='string'
)
... | 22,426 |
def test_update_nonexisting_subscription(rest_client, auth_token):
""" SUBSCRIPTION (REST): Test the update of a non-existing subscription """
subscription_name = uuid()
data = {'options': {'filter': {'project': ['toto', ]}}}
response = rest_client.put('/subscriptions/root/' + subscription_name, headers... | 22,427 |
def select_points():
""" Select points (empty) objects.
Parameters:
None
Returns:
list: Empty objects or None.
"""
selected = bpy.context.selected_objects
if selected:
return [object for object in selected if object.type == 'EMPTY']
print('***** Point (e... | 22,428 |
def _get_best_encoding(stream):
"""Returns the default stream encoding if not found."""
rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
if _is_ascii_encoding(rv):
return 'utf-8'
return rv | 22,429 |
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
p... | 22,430 |
def mask_conv1d1(in_channels,
out_channels,
strides=1,
groups=1,
use_bias=False,
data_format="channels_last",
**kwargs):
"""
Masked 1-dim kernel version of the 1D convolution layer.
Parameters:
-------... | 22,431 |
def isready_cluster(ctx, project_name, cluster_name):
"""Check if the Atlas Cluster is 'IDLE'."""
project = ctx.obj.groups.byName[project_name].get().data
state = ctx.obj.groups[project.id].clusters[cluster_name].get().data.stateName
if state == "IDLE":
click.echo("True")
exit(0)
cl... | 22,432 |
def decimal_from_tuple(signed, digits, expo):
"""Build `Decimal` objects from components of decimal tuple.
Parameters
----------
signed : bool
True for negative values.
digits : iterable of ints
digits of value each in [0,10).
expo : int or {'F', 'n', 'N'}
exponent of de... | 22,433 |
def metadata_update(
repo_id: str,
metadata: Dict,
*,
repo_type: str = None,
overwrite: bool = False,
token: str = None,
) -> str:
"""
Updates the metadata in the README.md of a repository on the Hugging Face Hub.
Example:
>>> from huggingface_hub import metadata_update
>>> ... | 22,434 |
async def test_command_with_optional_arg(hass, client):
"""Test generic command functionality."""
await setup_webostv(hass)
data = {
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_COMMAND: "test",
ATTR_PAYLOAD: {"target": "https://www.google.com"},
}
await hass.services.async_call(DOMAIN, ... | 22,435 |
def add_children_layer_before_parent_layer(cur_layer: tf.keras.layers.Layer, node_layer_map: dict, layer_out_node_map: dict, visited_layers: set, reversed_ordered_layers: list):
"""
Function to use topological sorting for finding all the layers which are accessible from the specific input_layer in the opposite ... | 22,436 |
def test_baked_django_with_git_initiated(cookies):
"""Test Django git init has generated correctly."""
default_django = cookies.bake()
assert ".git" in os.listdir(default_django.project_path)
git_remote = bake_checker(
"git",
"remote",
"-v",
cwd=default_django.project_p... | 22,437 |
def convertStringToArabic(numStr, stripChars=0):
"""
Convert a string to an arabic number;
Always returns numeric!
12-09-2004: Changed default stripChars to 0, because otherwise a roman I was
stripped before processing! Need to watch for programs that need
to now explicitly set stripChar... | 22,438 |
def _process_location(loc: location.NormalizedLocation) -> None:
"""Run through all of the methods to enrich the location"""
_add_provider_from_name(loc)
_add_source_link(loc)
_add_provider_tag(loc)
_normalize_phone_format(loc) | 22,439 |
def set_logging():
"""Sets additional logging to file for debug."""
logger_migrator = logging.getLogger('migrator')
logger_migrator.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - '
'%(message)s - \n '
'[... | 22,440 |
def system_types():
"""
系统类型(工作空间类型)
:return:
"""
return Workspace.sys_types().values() | 22,441 |
def get_rnd_simplex(dimension, random_state):
"""
Uniform random point on a simplex, i.e. x_i >= 0 and sum of the coordinates is 1.
Donald B. Rubin, The Bayesian bootstrap Ann. Statist. 9, 1981, 130-134.
https://cs.stackexchange.com/questions/3227/uniform-sampling-from-a-simplex
Parameters
----... | 22,442 |
def backup_generate_metadata(request, created_at='', secret=''):
"""
Generates metadata code for the backup.
Meant to be called by the local handler only with shared secret (not directly).
"""
if not secret == settings.GAEBAR_SECRET_KEY:
return HttpResponseForbidden()
backup = models.GaebarBackup.all... | 22,443 |
def test_bs_godec_trained_noise(noise_path, gif_name, preview):
"""Test bs_godec Implementation with trained noise
Keyword Arguments:
noise_path {string}
gif_name {string}
preview {boolean}
---
This test shows you how to run the bs_godec method.
"""
N = get_frame(noise_p... | 22,444 |
def hard_prune_repo(repo_path):
"""
1. Delete all files, except git metadata and files with names that match *.py.
2. Delete all empty folders.
3. Delete all symbolic links.
4. Set permission for all files to 440.
"""
assert os.path.exists(repo_path)
prune_commands = (
"find {} -... | 22,445 |
def contains_conv(module: torch.nn.Module) -> bool:
""" Returns `True` if given `torch.nn.Module` contains at least one convolution module/op (based on `deepcv.meta.nn.is_conv` for convolution definition) """
return any(map(module.modules, lambda m: is_conv(m))) | 22,446 |
def _construct_cell(empty=False):
"""Constructs a test cell."""
cell = scheduler.Cell('top')
if empty:
return cell
rack1 = scheduler.Bucket('rack:rack1', traits=0, level='rack')
rack2 = scheduler.Bucket('rack:rack2', traits=0, level='rack')
cell.add_node(rack1)
cell.add_node(rack2)... | 22,447 |
def gaussian_kernel(F: np.ndarray) -> np.ndarray:
"""Compute dissimilarity matrix based on a Gaussian kernel."""
D = squared_dists(F)
return np.exp(-D/np.mean(D)) | 22,448 |
def _parse_yearweek(yearweek):
"""Utility function to convert internal string representations of calender weeks into datetime objects. Uses strings of format `<year>-KW<week>`. Weeks are 1-based."""
year, week = yearweek_regex.search(yearweek).groups()
# datetime.combine(isoweek.Week(int(year), int(week)).w... | 22,449 |
def correction_file(namefile, namefile_corrected):
""" Correct the orthograph of a tokenized file"""
out = open(namefile_corrected, 'w')
with open(namefile, 'r') as f:
for line in f:
new_line = line.replace('\n', '')
new_line = new_line.split(';')
out.write(new_li... | 22,450 |
def exportSchemaAsJSONSchema(schema, versionNumber, filePath):
"""
Exports the given schema as a JSON Schemas document.
Parameters
----------
schema : Schema
The schema to export.
versionNumber : string
The version number of the schema.
filePath : string
The path to ... | 22,451 |
def classified_triplets(ctx: callable, config: callable, statsd: callable, logger: callable, run_id: int,
conn: callable, metadata_conn: callable, command: str, metrics_root: callable,
metrics_run_root: callable, output_dir: str, conditions: list) -> None:
"""Generate... | 22,452 |
def test_scs_invalid_params(dev, apdev):
"""SCS command invalid parameters"""
tests = ["",
"scs_id=1",
"scs_id=1 foo",
"scs_id=1 add ",
"scs_id=1 add scs_up=8",
"scs_id=1 add scs_up=7",
"scs_id=1 add scs_up=7 classifier_type=1",
... | 22,453 |
def save_as_pdf_pages(plots, filename=None, path=None, verbose=True, **kwargs):
"""
Save multiple :class:`ggplot` objects to a PDF file, one per page.
Parameters
----------
plots : collection or generator of :class:`ggplot`
Plot objects to write to file. `plots` may be either a
coll... | 22,454 |
def get_subpixel_indices(galtable, hpix=[], border=0.0, nside=0):
"""
Routine to get subpixel indices from a galaxy table.
Parameters
----------
galtable: `redmapper.Catalog`
A redmapper galaxy table master catalog
hpix: `list`, optional
Healpix number (ring format) of sub-region.... | 22,455 |
def main():
"""creating the function in order to call all other functions inside of it"""
make_bear(bear_size, bear_color, sun_or_cloud)
make_sun() | 22,456 |
def is_common_secret_key(key_name: str) -> bool:
"""Return true if the key_name value matches a known secret name or pattern."""
if key_name in COMMON_SECRET_KEYS:
return True
return any(
[
key_name.lower().endswith(key_suffix)
for key_suffix in COMMON_SECRET_KEY_SUFF... | 22,457 |
def check_md5(func):
""" A decorator that checks if a file has been changed. """
@wraps(func)
def wrapper(*args, **kwargs):
ret = func(*args, **kwargs)
assert _check_md5(path, original_path), 'The file has been changed after {}().'.format(func.__name__)
return ret
return wrapper | 22,458 |
def showgraphwidth(context, mapping):
"""Integer. The width of the graph drawn by 'log --graph' or zero."""
# just hosts documentation; should be overridden by template mapping
return 0 | 22,459 |
def test_get_scores_from_invalid_ratings_dataframe(tenor):
"""Tests if function can correctly handle pd.DataFrame objects."""
act = rtg.get_scores_from_ratings(ratings=conftest.input_invalid_df, tenor=tenor)
expectations = conftest.exp_invalid_df
expectations.columns = ["rtg_score_Fitch", "rtg_score_DBR... | 22,460 |
def set_hud_visibility(bool_value, displays = None):
"""
Set the viewport hud display visibility.
Args:
bool_value (bool): True turns visiliblity on, False turns it off.
displays (list): List of heads up displays by name.
"""
if not displays:
displays = cm... | 22,461 |
def diff_last_filter(trail, key=lambda x: x['pid']):
""" Filter out trails with last two key different
"""
return trail if key(trail[-1]) != key(trail[-2]) else None | 22,462 |
def read_items(source, n, target):
"""This function reads and prints n items from the given iterable, also
putting them to the given target queue."""
for i in range(0, n):
item = source.__next__()
print((i, item))
target.put((i, item)) | 22,463 |
def cli():
"""Command Line Interface for the Reproducible Open Benchmark REANA
workflow controller."""
pass | 22,464 |
def cpu_times():
"""Return a named tuple representing the following system-wide
CPU times:
(user, nice, system, idle, iowait, irq, softirq [steal, [guest,
[guest_nice]]])
Last 3 fields may not be available on all Linux kernel versions.
"""
procfs_path = get_procfs_path()
set_scputimes_n... | 22,465 |
def calc_centeroid(x, network: DTClustering, n_clusters: int):
"""クラスタ中心を計算します.
Notes:
Input x: [batch, sequence, feature, 1]
Output: [n_clusters, hidden sequence, hidden feature, 1]
"""
code = network.encode(x)
feature = code.view(code.shape[0], -1) # [batch, sequence * feature]
... | 22,466 |
def start_run():
"""
Starts at test run..
TODO all of it.
"""
uuid = request.form.get('uuid', default='none', type=str)
print('Starting a run: %s' % uuid)
return "ok" | 22,467 |
def softXrayMono1(eV, k, m, c, rb_mm, bounce, inOff_deg, outOff_deg, verbose):
"""
# calculate premirror and grating angles for NSLS-II soft xray monos
# eV: energy
# k: central line density in mm-1
# m: diffraction order
# c: cff 0 < cff < infinity
# bounce = 'up' or 'down'
# inOff_deg ... | 22,468 |
def createHelmholtz3dExteriorCalderonProjector(
context, hminusSpace, hplusSpace, waveNumber,
label=None, useInterpolation=False, interpPtsPerWavelength=5000):
"""
Create and return the exterior Calderon projector for the
Helmholtz equation in 3D.
*Parameters:*
- context (Context)
... | 22,469 |
def setup(bot: commands.Bot) -> None:
"""
This is a necessary method to make the cog loadable.
Returns
-------
None
"""
bot.add_cog(Timeline(bot)) | 22,470 |
def prepare_xrf_map(data, chunk_pixels=5000, n_chunks_min=4):
"""
Convert XRF map from it's initial representation to properly chunked Dask array.
Parameters
----------
data: da.core.Array, np.ndarray or RawHDF5Dataset (this is a custom type)
Raw XRF map represented as Dask array, numpy ar... | 22,471 |
def colorbar_factory(cax, mappable, **kwargs):
"""
Create a colorbar on the given axes for the given mappable.
.. note::
This is a low-level function to turn an existing axes into a colorbar
axes. Typically, you'll want to use `~.Figure.colorbar` instead, which
automatically handle... | 22,472 |
def fourth_measurer_I_R(uniquePairsDf):
"""
fourth_measurer_I_R: computes the measure I_R that is based on the minimal number of tuples that should
be removed from the database for the constraints to hold.
The measure is computed via an ILP and the Gurobi optimizer is used to solve the ILP.
- T... | 22,473 |
def import_hopdb_fossil_elements(path):
"""
Function to import fossil elements from xml file downloaded from the HOP DB.
This function populates both the FossilElement table and the Fossils table.
Fossils are aggregated from elements based on values in the HomininElement field
:param path:
:retu... | 22,474 |
def is_sublist_equal(list_one, list_two):
"""
Compare the values of two lists of equal length.
:param list_one: list - A list
:param list_two: list - A different list
:return EQUAL or UNEQUAL - If all values match, or not.
>>> is_sublist_equal([0], [0])
EQUAL
>>> is_sublist_equal([1],... | 22,475 |
def black_box_function(x, y):
"""Function with unknown internals we wish to maximize.
This is just serving as an example, for all intents and
purposes think of the internals of this function, i.e.: the process
which generates its output values, as unknown.
"""
return -x ** 2 - (y - 1) ** 2 + 1 | 22,476 |
def convert(
*,
csv,
tfrecords_template,
volume_shape,
examples_per_shard,
to_ras,
gzip,
verify_volumes,
num_parallel_calls,
multi_resolution,
start_resolution,
verbose,
):
"""Convert medical imaging volumes to TFRecords.
Volumes must all be the same shape. This ... | 22,477 |
def reduce_wires_to_segments(wires, segments):
""" Reduce wire names to segment definitions.
For purposes of creating the routing heuristic, it is assumed that if two
source wires share a prefix, they can be considered segments for the
purposes of the routing heuristic.
This is definitely true for... | 22,478 |
def test_vmrun_begin_replay():
"""Test begin_replay method."""
vmrun = mech.vmrun.VMrun('/tmp/first/some.vmx', executable='/tmp/vmrun',
provider='ws', test_mode=True)
expected = ['/tmp/vmrun', '-T', 'ws', 'beginReplay', '/tmp/first/some.vmx', 'a_name']
got = vmrun.begin_repl... | 22,479 |
def file_extension(path):
"""Lower case file extension."""
return audeer.file_extension(path).lower() | 22,480 |
def locate(verbose):
"""Print location of the current workspace.
:param verbose: Unused.
"""
if not os.path.islink(ws_file):
print('no current workspace found, see "ros-get ws-create --help" how to create one')
return 1
else:
print(os.path.realpath(ws_file)) | 22,481 |
def motion(x, u, dt):
"""
motion model
"""
x[2] += u[1] * dt
x[0] += u[0] * math.cos(x[2]) * dt
x[1] += u[0] * math.sin(x[2]) * dt
x[3] = u[0]
x[4] = u[1]
return x | 22,482 |
def sweep(
sweep: Union[dict, Callable], entity: str = None, project: str = None,
) -> str:
"""Initialize a hyperparameter sweep.
To generate hyperparameter suggestions from the sweep and use them
to train a model, call `wandb.agent` with the sweep_id returned by
this command. For command line func... | 22,483 |
def connection_end_point (id, node_uuid, nep_uuid, cep_uuid):
"""Retrieve NodeEdgePoint by ID
:param topo_uuid: ID of Topology
:type uuid: str
:param node_uuid: ID of Node
:type node_uuid: str
:param nep_uuid: ID of NodeEdgePoint
:type nep_uuid: str
:param cep_uuid: ID of ConnectionEndP... | 22,484 |
def remove_melt_from_perplex(perplex,melt_percent=-1):
""" Extrapolate high temperature values to remove melt content using sub-solidus values.
The assumption is that alpha and beta are constant and temperature-independent at high temperature."""
Tref = 273
Pref = 0
rho = perplex.rho.re... | 22,485 |
def _delete_empty_source_bucket(cloud_logger, source_bucket):
"""Delete the empty source bucket
Args:
cloud_logger: A GCP logging client instance
source_bucket: The bucket object for the original source bucket in the source project
"""
spinner_text = 'Deleting empty source bucket'
... | 22,486 |
def similarity_score(text_small, text_large, min_small = 10, min_large = 50):
"""
complexity: len(small) * len(large)
@param text_small: the smaller text
(in this case the text which's validity is being checked)
@param text_large: the larger text (in this case the scientific stud... | 22,487 |
def consume(command):
"""
Example of how to consume standard output and standard error of
a subprocess asynchronously without risk on deadlocking.
"""
# Launch the command as subprocess.
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Launch the asynch... | 22,488 |
def print_status(exp, offset=0, all_trials=False, collapse=False):
"""Print the status of the current experiment.
Parameters
----------
offset: int, optional
The number of tabs to the right this experiment is.
all_trials: bool, optional
Print all trials individually
collapse: bo... | 22,489 |
def abline(a_coords, b_coords, ax=None, **kwargs):
"""Draw a line connecting a point `a_coords` with a point `b_coords`.
Parameters
----------
a_coords : array-like, shape (2,)
xy coordinates of the start of the line.
b_coords : array-like, shape(2,)
xy coordiantes of the end of th... | 22,490 |
def get_extensions():
"""
Returns supported extensions of the DCC
:return: list(str)
"""
return ['.hip', '.hiplc', '.hipnc', '.hip*'] | 22,491 |
def precheck_data_format(idir, hlsp_name):
"""
Generates parameter file for check_metadata_format based on file endings.
:param idir: The directory containing HLSP files to check.
:type idir: str
:param hlsp_name: The name of the HLSP.
:type hlsp_name: str
"""
# Start logging to an ... | 22,492 |
def calc_spatially_diffusion_factors(
regions,
fuel_disagg,
real_values,
low_congruence_crit,
speed_con_max,
p_outlier
):
"""
Calculate spatial diffusion values
Arguments
---------
regions : dict
Regions
fuel_disagg : dict
Disa... | 22,493 |
def get_set(path):
"""Returns a matrix of data given the path to the CSV file. The heading row and NaN values are excluded."""
df = pd.read_csv(path, sep=';', encoding='latin')
return df.dropna(subset=['PMID1', 'PMID2', 'Authorship'], how='any').values | 22,494 |
def add_landmark(soup: BeautifulSoup, textf: str, landmarks: list):
"""
Adds an item to landmark list with appropriate details.
INPUTS:
soup: BeautifulSoup representation of the file we are indexing in ToC
textf: path to the file
landmarks: the list of landmark items we are building
OUTPUTS:
None
"""
epub_... | 22,495 |
def _client_get(client_create_fn: Callable[..., Any], params: ClientGetParams) -> Any:
"""
:param client_create_fn: the `boto3.client` or `boto3.resource` function
"""
which_service = params.boto3_client_name
endpoint_url = os.getenv(params.endpoint_url_key)
access_key_id = os.getenv(params.acce... | 22,496 |
def parse_metadata_from_sensorcommunity_csv_filename(filename):
"""Parse sensor id, sensor type and date from a raw luftdaten.info AQ .csv
filename.
Parameters:
filename (path): the file to parse. Format of the file is expected to be
the one used by the luftdaten.info project and saved ... | 22,497 |
def gaussian_target(img_shape, t, MAX_X=0.85, MIN_X=-0.85, MAX_Y=0.85, MIN_Y=-0.85, sigma2=10):
"""
Create a gaussian bivariate tensor for target or robot position.
:param t: (th.Tensor) Target position (or robot position)
"""
X_range = img_shape[1]
Y_range = img_shape[2]
XY_range = np.arang... | 22,498 |
def _old_process_multipart(entity):
"""The behavior of 3.2 and lower. Deprecated and will be changed in 3.3."""
process_multipart(entity)
params = entity.params
for part in entity.parts:
if part.name is None:
key = ntou('parts')
else:
key = part.name
... | 22,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.