content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_time_dependent_dataset(filename, cache=False, record_zero_counts=True):
"""
Load time-dependent (time-stamped) data as a DataSet.
Parameters
----------
filename : string
The name of the file
cache : bool, optional
Reserved to perform caching similar to `load_dataset`. ... | 55,900 |
def Log_SetTraceMask(*args, **kwargs):
"""Log_SetTraceMask(TraceMask ulMask)"""
return _misc_.Log_SetTraceMask(*args, **kwargs) | 55,901 |
def find_max_burst(burst_list: list, offset_start, offset_end):
"""[summary]
Args:
burst_list (list): [description]
offset_start ([type]): [description]
offset_end ([type]): [description]
Returns:
[type]: [description]
"""
burst_levels = set()
burst_lev... | 55,902 |
def center_text(baseline, text):
"""Return a string with the centered text over a baseline"""
gap = len(baseline) - (len(text) + 2)
a1 = int(gap / 2)
a2 = gap - a1
return '{} {} {}'.format(baseline[:a1], text, baseline[-a2:]) | 55,903 |
def pytest_collection_modifyitems(config: pytest.Config, items: List[pytest.Item]) -> None:
"""Filter tests by world_size (for multi-GPU tests) and duration (short, long, or all)"""
threshold = float(getattr(config, "_env_timeout", DEFAULT_TIMEOUT))
duration = config.getoption("duration")
world_size = c... | 55,904 |
def test_rules(rule: rules.BaseRule, ok: bool, checker: Checker):
"""Test all rules
+ `rule` goes from parametrize and used to filter errors by this rule code.
+ `ok` goes from parametrize and indicates that this rule must return error
for given text.
+ `text` goes from parametrize into `checke... | 55,905 |
def delete_dir_gcp(
cloud_settings: dict,
number_of_connect_tries: int = 5,
):
"""Delete a directory in a GCS bucket."""
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
try:
from google.cloud import storage
except ImportError:
raise ImportError(
... | 55,906 |
def test_get_report(_mock1, _mock2):
"""Test sucess Get Report."""
res, ing_res = r.get_report('2018-10-10', '2018-10-18')
assert res is True | 55,907 |
def test_cli_analysis():
"""Test for cli_analysis() function."""
parsed_args = argparse.Namespace(
x=1, y=2, sum=False, max=False, combined=False, verbose=False
)
output = cli_analysis(parsed_args)
# Default analysis is product: 1 * 2 = 2
assert output == 2
parsed_args = argparse.Na... | 55,908 |
def _find_executable_linenos(filename):
"""
A re-implementation of trace.find_executable_linenos working around
compile's problems with missing EOLS
"""
try:
prog = open(filename, "rU").read()
except IOError, err:
print >> sys.stderr, ("Not printing coverage data for %r: %s"
... | 55,909 |
def print_metallicity(dataset, params, logNHI, err=0.1):
"""
Print the metallicity derived from different species.
This will add the column densities for all components of a given ion.
Parameters
----------
dataset : :class:`VoigtFit.DataSet`
An instance of the :class:`VoigtFit.DataSet`... | 55,910 |
def dict_allocations(dojo):
"""
input: dojo
returns a dict of allocations
"""
rooms = list(dojo.office) + list(dojo.livingspace)
# makes a dictionary, allocation with key-> roomname: -> value(occupants)
allocations = {room.name: people_inroom(dojo, room.name) for room in rooms}
return al... | 55,911 |
def variance(lA):
"""
compute the variance elementwise of this list of arrays
"""
n = len(lA)
sX = reduce(np.add, lA)
sX2 = reduce(np.add, [A*A for A in lA])
s2 = (sX2 - sX*sX / n) / (n-1)
return s2 | 55,912 |
def single_rvs(n0, psi, size=1):
"""Generate random deviates from the single division model, still
is not working properly possibily needs to be checked"""
cdf = single_cdf(1,n0,2,psi)
xvals = [0] * size
for i in range(size):
rand_float = uniform(0,1)
temp_cdf = list(cdf + [rand_floa... | 55,913 |
def get_BRISK_descriptions(image, keyPoints, **kwargs):
"""
Computes BRISK descriptions for given keypoints.
input: image (that was returned with the keypoints!)
keyPoints - detected keypoints
**kwargs = detection arguments
output: list of descriptions for given keypoints
""... | 55,914 |
def printh(s, filename=None, overwrite=False, save_to_desktop=False):
"""
>>> filename = "pico8_printh_test.txt"
>>> printh('pico8 printh test', filename, overwrite=True, save_to_desktop=True)
>>> open(os.path.join(os.environ["HOMEPATH"], "Desktop", os.path.split(filename)[1])).read()
'pico8 printh ... | 55,915 |
def make_mask(index):
"""
Create observation selection vector using major and minor
labels, for converting to wide format.
"""
N, K = index.levshape
selector = index.labels[1] + K * index.labels[0]
mask = np.zeros(N * K, dtype=bool)
mask.put(selector, True)
return mask | 55,916 |
def verify_request(func):
"""
verify user request
"""
def wrapper(request):
uid = request.POST.get('uid', '')
if not uid:
return HttpResponseForbidden()
else:
try:
if is_visit_today(uid):
pass
else:
... | 55,917 |
def LTL_world(W, var_prefix="obs",
center_loc=None, restrict_radius=1):
"""Convert world matrix W into an LTL formula describing transitions.
Syntax is that of gr1c; in particular, "next" variables are
primed. For example, x' refers to the variable x at the next time
step.
The va... | 55,918 |
def feat_net(img_shape):
"""Returns a keras Model for feature extract
Args:
img_shape: tuple (h,w)
Returns:
model: Keras model
"""
IMAGE_H, IMAGE_W = img_shape
input_image = Input(shape=(IMAGE_H, IMAGE_W, 3))
base_model = keras.applications.resnet50.ResNet50(include_top=False,
... | 55,919 |
def siconc_cubes():
"""Sample cube."""
time_coord = iris.coords.DimCoord([0.0], standard_name='time',
var_name='time',
units='days since 6543-2-1')
lat_coord = iris.coords.DimCoord([-30.0], standard_name='latitude',
... | 55,920 |
def criterion_1b(psych, n_trials, perf_easy, rt):
"""
Returns bool indicating whether criterion for trained_1b is met.
"""
criterion = (abs(psych[0]) < 10 and psych[1] < 20 and psych[2] < 0.1 and psych[3] < 0.1 and
np.all(n_trials > 400) and np.all(perf_easy > 0.9) and rt < 2)
... | 55,921 |
def get_midpoints(z, midpoint_div_1, midpoint_div_2):
""" Gets this midpoints in Z space between a batch of images
"""
# reshape z
shape_z = shape(z)
z = tf.reshape(z, [shape_z[0], np.prod(shape_z[1:])])
hidden_size = np.prod(shape_z[1:])
batch_size = shape(z)[0]
# get the first half of ... | 55,922 |
def check_neighbors_completeness(
adata: AnnData,
conn_key="connectivities",
dist_key="distances",
result_prefix="",
check_nonzero_row=True,
check_nonzero_col=False,
) -> bool:
"""Check if neighbor graph in adata is valid.
Parameters
----------
adata : AnnData
conn_k... | 55,923 |
def get_measure(axis, qr, cr):
"""
For X, Y, Z axes, construct a QuantumCircuit that measures a single QuantumRegister
:param axis: Axes to be measured, can be multiple. e.g. 'X' , 'XYZ' -- one for each qubit
:param qr: QuantumRegister to measure
:param cr: ClassicalRegister to measure into
:re... | 55,924 |
def tbn_pyramid_level(sizes, ai, fdm, a, b):
"""
Downsize an image to appropriate sizes.
A discrete interpolation method is used for images with discrete vs
continuous values.
"""
result = []
result.append(downsize(ai, sizes[0]))
if fdm is not None:
result.append(downsize(fdm, ... | 55,925 |
def apply_density(rho: np.ndarray, op: np.ndarray) -> np.ndarray:
"""Applies a operator O to a density matrix ρ.
.. math::
ρ' = O ρ O^†
Parameters
----------
rho : (N) np.ndarray
The input density matrix ρ.
op : (N, N) np.ndarray
The operator O to apply on the density m... | 55,926 |
def _direct_read(array: tables.CArray,
patch_reads: List[PatchRowRW],
mask_reads: List[PatchMaskRowRW],
npatches: int,
patchwidth: int
) -> np.ma.MaskedArray:
"""Build patches from a data source given the read/write operations."""
... | 55,927 |
def cover_get(title):
"""
Retrieve the cover image of the give movie
:param title: the title of the movie
:return: a json representing the title and the path toward the cover image
"""
return jsonify({
'title': title,
'path': get_cover_path(title)
}) | 55,928 |
def send_confirmation_block_history_request():
"""Request missing blocks from the primary validator"""
self_configuration = get_self_configuration(exception_class=RuntimeError)
primary_validator = self_configuration.primary_validator
address = format_address(
ip_address=primary_validator.ip_add... | 55,929 |
def DateTime_GetCountry(*args):
"""DateTime_GetCountry() -> int"""
return _misc_.DateTime_GetCountry(*args) | 55,930 |
def main():
"""
Entry-point for the function.
"""
email_connection_params = {
"host": "smtp.gmail.com",
"port": 587,
"user": "sender@gmail.com",
"password": "xxxxxxx",
"use_tls": True
}
send_email = Email(**email_connection_params)
send_email.send(to_... | 55,931 |
def update_code_location(code, newfile, newlineno):
"""Take a code object and lie shamelessly about where it comes from.
Why do we want to do this? It's for really shallow reasons involving
hiding the hypothesis_temporary_module code from test runners like
py.test's verbose mode. This is a vastly dispr... | 55,932 |
def xcorr(a,b,lags,medfilt=0) :
""" Cross correlation function between two arrays, calculated at lags
Args:
a, b : input 1D arrays
lags : array (1D) of x-corrlation lags
medfilt : size of median filter for arrays (default=0)
Returns :
fit peak of cro... | 55,933 |
def gist_earth(range, **traits):
""" Generator for the 'gist_earth' colormap from GIST.
"""
_data = dict(
red = [(0.0, 0.0, 0.0),
(0.0042016808874905109, 0.0, 0.0),
(0.0084033617749810219, 0.0, 0.0),
(0.012605042196810246, 0.0, 0.0),
(0.016806723549962... | 55,934 |
def test_SIP_create(app, db, mocker):
"""Test the create method from SIP API."""
# we setup a file storage
tmppath = tempfile.mkdtemp()
db.session.add(Location(name='default', uri=tmppath, default=True))
db.session.commit()
# we create a file
content = b'test lol\n'
bucket = Bucket.creat... | 55,935 |
def exponentially_distribute(exponent, dist_max, dist_min, num_exp_distributed_values):
"""
:param exponent: An exponent of 0 results in a linear distribution,
otherwise the exp distribution is sampled from e^(exponent)*2e - e^(exponent)*e
:param dist_max: Maximum of newly exponential distribution
:... | 55,936 |
def new_issue(
session,
repo,
title,
content,
user,
issue_id=None,
issue_uid=None,
private=False,
related_prs=[],
status=None,
close_status=None,
notify=True,
date_created=None,
milestone=None,
priority=None,
assignee=None,
tags=None,
):
""" Create... | 55,937 |
def options():
"""Parse command line options.
Args:
Returns:
argparse object
Raises:
"""
parser = argparse.ArgumentParser(description="Share Clowder Datasets by associating them with a Clowder Space.",
formatter_class=argparse.ArgumentDefaultsHel... | 55,938 |
def memory_usage(obj):
"""Returns the memory usage in a human readable format."""
def get_size(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
ret... | 55,939 |
def setEmployeeAssignement(employ):
""" Updates the member details in the database if he or she is assigned to a project """
if connection.is_connected():
cursor = connection.cursor()
sql = "UPDATE Member SET IsAssigned= %s WHERE MemberId = %s ;"
cursor.execute(sql, (1, employ))
... | 55,940 |
def update_databases(databases: {str: mara_db.dbs.DB}):
"""
Creates or updates a list of databases in the Metabase metadata db (and removes all others)
Args:
databases: A mapping of database names to database configurations
"""
with mara_db.postgresql.postgres_cursor_context(config.metabase... | 55,941 |
def read(path_to_image):
"""
Read MCCD image from file.
Parameters
----------
path_to_image : str
Path to MCCD image to read
Returns
-------
(image, metadata, mccdheader) : tuple
Returns tuple containing the ndarray of the image, experimental
metadata and the m... | 55,942 |
def test_ingest_selective_epv_into_graph3():
"""Tests for 'ingest_epv_into_graph'."""
result = ingest_selective_epv_into_graph(None)
expected = ({"message": "Failed to initiate worker flow."}, 500)
assert result == expected | 55,943 |
def test_cp_description_vs_title():
"""
There are two partitions:
Case 1: description longer than title (expect
product creation to fail
Case 2: description shorter than title (expect
successful product creation)
"""
# list of input/output files used to test each partitio... | 55,944 |
def fit_circle_to_data(in_data, verbose=False):
"""
Wrapper around _fit_circle_impl that takes care of unwrapping shapes and so on...
Returns
-------
"""
slope, intercept, r_value, p_value, std_err = linregress(in_data[0], in_data[1])
if verbose:
print("R-square of linear fit : {}"... | 55,945 |
def dilated_components(output, dil_param, cc_thresh):
"""
Performs a version of connected components with dilation
Expands the voxels over threshold by dil_param in 2D
Runs connected components on the dilated mask
Removes the voxels which weren't originally above threshold
"""
if dil_param... | 55,946 |
def test_print_from_ms():
"""
Verify output of print from ms
"""
assert print_from_ms(10) == "10ms"
assert print_from_ms(1010) == "1s 10ms"
assert print_from_ms(60010) == "1m 0s 10ms"
assert print_from_ms(61010) == "1m 1s 10ms" | 55,947 |
def get_model(sess, image_shape=(80, 160, 3), gf_dim=64, df_dim=64,
batch_size=64, name="autoencoder", gpu=0):
"""
Compiles and outputs models and functions for training and running models.
"""
K.set_session(sess)
checkpoint_dir = './outputs/results_' + name
with tf.variable_scope(... | 55,948 |
def define_model() -> Tuple[Model, Model]:
"""Defines the architecture of the model."""
i = Input([None, None, 3], dtype=tf.uint8)
x = tf.cast(i, tf.float32)
x = preprocess_input(x)
# base_model = MobileNetV2(include_top=False, weights='imagenet', input_shape=(192, 192, 3))
# base_model = ResNe... | 55,949 |
def reset_sess(config=None):
"""
Convenience function to create the TF graph & session or reset them.
"""
if config is None:
config = session_options()
global sess
tf.compat.v1.reset_default_graph()
try:
sess.close()
except:
pass
sess = tf.compat.v1.Interactiv... | 55,950 |
def get_pid(pidfile, default=None):
"""
Get the PID (Process ID) by trying to access an PID file.
Args:
pidfile (str): The path of the pid file.
default (int, optional): What to return if file does not exist.
Returns:
pid (str): The process id or `default`.
"""
if os.p... | 55,951 |
def get_case_forms(case_id):
"""
Get all forms that have submitted against a case (including archived and deleted forms)
wrapped by the appropriate form type.
"""
form_ids = get_case_xform_ids(case_id)
return [fetch_and_wrap_form(id) for id in form_ids] | 55,952 |
def write_tla_match(tla_match, filename):
"""
Write the `tla_match` table.
"""
with open(filename, "w", encoding="utf-8") as handler:
handler.write("entry_id\ttla_id\n")
for entry_id, tla_ids in tla_match.items():
for tla_id in tla_ids:
handler.write(entry_id... | 55,953 |
def get_generic_data():
"""
Get generic variables.
Parameters
----------
gendata: str
path to generic data directory.
Returns
-------
dict: the generic variables.
"""
gen_data = {
'instance_display_name': _get_display_name(),
'auth': _get_authenticat... | 55,954 |
def test_multiline_record_mol_read(
single_multiline_record_mol_sdf: Pathy,
) -> None:
"""An sdf of a multiline record valued molecule contains the expected data.
Args:
single_multiline_record_mol_sdf: pytest fixture of a Path to the sdf
"""
mol = next(Chem.SDMolSupplier(str(single_multilin... | 55,955 |
def test_dimensionless():
"""
Create dimensionless unit and check attributes.
"""
u1 = Unit()
assert u1.is_dimensionless
assert u1.expr == 1
assert u1.base_value == 1
assert u1.dimensions == 1
assert u1 != "hello!"
assert (u1 == "hello") is False
u2 = Unit("")
assert ... | 55,956 |
def generate_embeddings_of_one_image(model, dataloader, repeats=50):
"""Generates representations for all images in the dataloader with
the given model
"""
embeddings = []
filenames = []
with torch.no_grad():
for _ in range(repeats):
for (img1, img2), _, _ in dataloader:
... | 55,957 |
def get_status_code(url, opts):
"""
Open connection to the given url and check status code.
:param url: URL of the website to be checked
:return: (availibility, success, HTTP code)
"""
availibility, success, code = (False, False, None)
timeout_duration_seconds = get_opt(opts, 'timeout_durat... | 55,958 |
async def clearstatus(ctx):
"""Efface les listes d'état des raids de raid.
Utilisation:!clearstatus
Seulement utilisable par les administrateurs."""
msg = _("Are you sure you want to clear all status for this raid? Everybody will have to RSVP again. If you are wanting to clear one user's status, use ... | 55,959 |
def get_default_kubernetes_metadata_config(
) -> metadata_store_pb2.ConnectionConfig:
"""Returns the default metadata connection config for a kubernetes cluster.
Returns:
A config proto that will be serialized as JSON and passed to the running
container so the TFX component driver is able to communicate wi... | 55,960 |
def camb_fisher_derivs(p):
"""
Get derivatives (as a function of ell) for the full set of CAMB Fisher
parameters. Includes TT, EE, TE derivatives.
"""
# Get derivatives for various parameters
# {n_s, w0, wa, w_b, omega_k, w_cdm, h}
d_ns = camb_deriv("scalar_spectral_index__1___", 0.004, p)
... | 55,961 |
def compute_hard_volumes(labels, voxel_volume=1., label_list=None, skip_background=True):
"""Compute hard volumes in a label map.
:param labels: a label map
:param voxel_volume: (optional) volume of voxel. Default is 1 (i.e. returned volumes are voxel counts).
:param label_list: (optional) list of label... | 55,962 |
def pairwise(iterable, pairs=2):
"""
a generator to return n consecutive values from an iterable, e.g.:
pairs = 2
s -> (s0,s1), (s1,s2), (s2, s3), ...
pairs = 3
s -> (s0, s1, s2), (s1, s2, s3), (s2, s3, s4), ...
adapted from https://docs.python.org/3.7/library/itertools.ht... | 55,963 |
def logical_intervals(vals, x=None):
"""
Determine contiguous intervals during which ``vals`` is True.
Returns an Astropy Table with a row for each interval. Columns are:
* idx_start: index of interval start
* idx_stop: index of interval stop
* x_start: x value at idx_start (if ``x`` is supplie... | 55,964 |
def coords2uv(coords, width, height):
"""
Image coordinates (xy) to uv
"""
middleX = width / 2 + 0.5
middleY = height / 2 + 0.5
uv = np.hstack([
(coords[:, [0]] - middleX) / width * 2 * np.pi,
-(coords[:, [1]] - middleY) / height * np.pi])
return uv | 55,965 |
def _compute_teleport_distribution_from_ratings(user_rating, all_movies):
"""
returns the teleporting distribution as explained in the homework
if a movie M has been rated, its probability is: RATE_M / SUM_OF_ALL_RATINGS
else, its probability is: 0
:param user_rating: a dict of (movie_id, rating)
:param all_movie... | 55,966 |
def extract_subdomain(url):
"""Uses teldextract to retrieve the subdomain of the url"""
return tldextract.extract(url).subdomain | 55,967 |
def check_empty(value: Optional[Any]):
"""Validate whether the value provided is of class `Empty`."""
if isinstance(value, Empty):
return True
return False | 55,968 |
def get_env_config(env_name=None, config_file=None):
"""Fetch an environment name and config object from the config.json file.
If the name is None and there's only one environment, we'll select the
first, otherwise we'll die to avoid ambiguity.
:param config_file: a `file`-like object that contains the... | 55,969 |
def path_base_and_leaf(path):
"""
Splits path to a base part and a file or directory name, as in the following example:
path: '/a/b'; base: '/a'; leaf: 'b'
"""
head, tail = ntpath.split(path)
if not tail: # in case there is trailing slash at the end of path
return {'base': ntpath.split(... | 55,970 |
def mutate_input(model, input_list, input_of_interest=0, output_extract_fn=lambda x: x, mutate_val=0,
return_diff=True, max_batch_size=128, **kwargs):
""" Switches each value in input_list[input_of_interest].size(1) to mutate_val
one-by-one and collects output_extract_fn(model(<input>)).
... | 55,971 |
def UnsignedShortCast(value):
"""Explicitly cast a value to type 'usigned short'."""
return UnsignedCast(And(value, ConstInt(0xFFFF))) | 55,972 |
def Normalize_C3V(vec):
"""Scales the argument by its Euclidean length, assuming its a 3d vector
(indexable object of length 3)."""
length = Hypot_C3V(vec);
vec[0] /= length
vec[1] /= length
vec[2] /= length
return None; | 55,973 |
def extract_coefficients(equation: sympy.Expr,
local_map: dict,
global_coords: list) -> tuple:
"""
Args:
equation: The equation in local coordinates.
local_map: The mapping from local coordinates to the index of a
global coordinate.
... | 55,974 |
async def test_flow_already_configured(hass):
"""Test device already configured flow."""
flow = upnp_config_flow.UpnpFlowHandler()
flow.hass = hass
# discovered device
udn = 'uuid:device_1'
hass.data[upnp.DOMAIN] = {
'discovered': {
udn: {
'friendly_name': '1... | 55,975 |
def read_variables(fh: TextIO) -> Dict[str, str]:
"""Read variables from file"""
reader = csv.reader(fh, delimiter=',')
headers = filter_map(normalize, next(reader))
assert all(f in headers
for f in ['variable_id', 'label_in_vars_csv', 'concept'])
num_headers = len(headers)
de... | 55,976 |
def _is_dunder(name):
"""Returns True if a __dunder__ name, False otherwise."""
return (name[:2] == name[-2:] == '__' and
name[2:3] != '_' and
name[-3:-2] != '_' and
len(name) > 4) | 55,977 |
def get_oidc_fxa_setting(attr):
"""Helper method to return the appropriate setting for Firefox Accounts authentication."""
FXA_CONFIGURATION = {
'OIDC_OP_TOKEN_ENDPOINT': settings.FXA_OP_TOKEN_ENDPOINT,
'OIDC_OP_AUTHORIZATION_ENDPOINT': settings.FXA_OP_AUTHORIZATION_ENDPOINT,
'OIDC_OP_US... | 55,978 |
def detect_nb_doctype(path):
"""Dectect what sort of document we are dealing with."""
# This is inefficient because we end up opening the file twice?
with io.open(fp, encoding="utf-8") as f:
txt = f.read()
typ = jupytext.formats.divine_format(txt)
return typ | 55,979 |
def populate_transitions(simplified_individuals):
"""
List transition rates from one node to all other upstream and downstream.
This method populates Node.specimens and begins the process of side-effecting Nodes.
To rebuild a fresh Graph copy, you must start at get_all_signatures()
:param simplified... | 55,980 |
def test_bogus_environment(saltworker_client):
"""
Ensure a bogus environment throws InvalidValue.
Args:
saltworker_client: (:obj:`src.workers.SaltBase`)
"""
# ensure InvalidValue is raised when a bogus environment type is selected
with pytest.raises(InvalidValue):
saltworker_cl... | 55,981 |
def from_cell_to_heatmap(slide, trans, cell_table, filter_out="LBP", level=7, n_comp=2):
"""
Parameters
----------
slide : wsi object,
openslide object from which we extract.
trans : function,
infers the new coordinates of a given point. It is or:
- the sequential ap... | 55,982 |
def get_genome_subsequence(gseq=None, start=None, end=None):
"""
The letters of nucleotides in the reference are shown in upper case.
"""
subseq = gseq[start-1:end]
return subseq.upper() | 55,983 |
def mvee(atoms, tol = 0.00001):
"""
Find the minimum volume ellipse around a set of atom objects.
Return A, c where the equation for the ellipse given in "center form" is
(x-c).T * A * (x-c) = 1
[U Q V] = svd(A);
where r = 1/sqrt(Q)
V is rotation matrix
U is ???
"""
points_asar... | 55,984 |
async def list_credentials(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 3.0.0
Lists the login credentials for the specified container registry.
:param name: The name of the container registry.
:param resource_group: The name of the resource group to which the container registr... | 55,985 |
def main(path, string, ext):
"""It is just a wrapper
"""
walk_and_find(path, string, ext) | 55,986 |
def analyze_hash_miss(hashchain, htask, hcomp, taskname, skipcache):
"""
Function that analyzes and gives out a printout of
possible hass miss reasons. The importance of a
candidate is calculated as Ic = Nm/Nc where:
- Ic is an imporance coefficient;
- Nm is the number of subhashes match... | 55,987 |
def set_cv_folds(dataset_name, k):
"""
Split data into different folds. The resulting split names have the
form cv_<k>-<i>, where i is the current folds used for testing.
param dataset_name: name of dataset without .csv
param k: number of folds
"""
return sd.cross_validation_folds(dataset_name, k, return_... | 55,988 |
def fetch_test_names(app, host_app, release, enabled_tests_only=True):
"""Determine the list of (TestCase, testMethod) for the app.
Args:
app: (string) path to app
host_app: (string) path to host app. None or "NO_PATH" for EG1.
release: (bool) whether this is a release build.
enab... | 55,989 |
def augment_data(X_train, Y_train):
"""
Augments the data 8-fold by 90 degree rotations and flipping.
Parameters
----------
X_train : array(float)
Array of source images.
Y_train : float
Array of label images.
Returns
-------
X_train_aug : array(float)
Augmen... | 55,990 |
def load_config(run_name):
""" Load configuration json """
with open(get_config_loc(run_name)) as data_file:
data = json.load(data_file)
return data | 55,991 |
def generate_graphs(data_frames, hardware_info, steps, outdir,
verbose=False):
"""Generate all graphs for a bcbio run."""
_setup_matplotlib()
# Hash of hosts containing (data, hardware, steps) tuple
collectl_info = collections.defaultdict(dict)
for host, data_frame in data_frame... | 55,992 |
def get_nmdc_jsonschema_string() -> str:
"""Retruns the nmdc.schema.json file as a string.
Returns
-------
str
A string containing the contents of nmdc.schema.json file.
"""
nmdc_json = get_nmdc_jsonschema_bytes()
return nmdc_json.decode("utf-8") | 55,993 |
def test_invalid_user_manager_company_id(
audit_companies, dynamodb, company_table, user_table
):
"""
Test invalid company_manager_id that references invalid user_id
"""
company_id = str(uuid.uuid4())
user_id = str(uuid.uuid4())
company_table.put_item(Item={"company_id": company_id, "company... | 55,994 |
def stackmean(array):
"""Cacluate the mean of a stack
This function calculates the mean of a stack of images (or any array).
It ignores values that are np.NAN and does not include them in the mean
calculation. It assumes an array of shape (.. i, j, x, y) where x and y
are the size of the returned a... | 55,995 |
def nfs_remap(path, depth, autofs=None):
"""Remap filesystems that are exported over NFS to their path on GPFS.
Eg:
radonc-ljungman-dataden.dataden.arc-ts.umich.edu:/gpfs/locker0/ces/dataden/g/radonc-ljungman-dataden /nfs/dataden/radonc-ljungman-dataden
umms-bleu.dataden.arc-ts.umich.edu:/gpfs/locker0/... | 55,996 |
def cvSetReal3D(*args):
"""cvSetReal3D(CvArr arr, int idx0, int idx1, int idx2, double value)"""
return _cv.cvSetReal3D(*args) | 55,997 |
def api_settings(_request):
"""Repond with user prefs in JSON."""
account = models.Account.current_user_account
return {
'xsrf_token': account.get_xsrf_token(),
'email': account.email,
'nickname': account.nickname,
'deprecated_ui': account.deprecated_ui,
'default_context': account.default_cont... | 55,998 |
def get_config(parse=True, **optional_kwargs):
"""
Get configurations as attributes of class
1. Parse configurations with argparse.
2. Create Config class initialized with parsed kwargs.
3. Return Config class.
"""
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHel... | 55,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.