content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_download_vcs_link(script):
"""
It should allow -d flag for vcs links, regression test for issue #798.
"""
result = script.pip(
'download', '-d', '.', 'git+git://github.com/pypa/pip-test-package.git'
)
result.did_create(Path('scratch') / 'pip-test-package-0.1.1.zip')
result.d... | 5,325,100 |
def test_size():
"""Test size() function"""
mf = MasterFile(join("..","sample","cds.mst"))
record = mf[1]
expr_list = (("size(v24)", '68'),
("size(v70)", '27'),
("size('teste')", '5'),
("size('')",'0'),
("size('\n')",'1'),
... | 5,325,101 |
def find_first_in_register_stop(seq):
"""
Find first stop codon on lowercase seq that starts at an index
that is divisible by three
"""
# Compile regexes for stop codons
regex_stop = re.compile('(taa|tag|tga)')
# Stop codon iterator
stop_iterator = regex_stop.finditer(seq)
# Find n... | 5,325,102 |
def computeScaling( filt1, filt2, camera1=None, camera2=None ) :
"""determine the flux scaling factor that should be multiplied to
filt1 to match the throughput of filt2. This returns just a
single number, effectively assuming the source SED is flat across
the bandpass, so that we just need to correct ... | 5,325,103 |
def test_ch_set_with_invalid_settingpatch_find_ports():
"""Test '--ch-set with a_bad_setting'."""
return_value, out = subprocess.getstatusoutput('meshtastic --host localhost --ch-set invalid_setting foo --ch-index 0')
assert re.search(r'Choices in sorted order', out)
assert return_value == 0 | 5,325,104 |
def setup_filters():
"""Registers the voldemort filters
"""
log.info('Initializing voldemort filters')
for filter_method in filters.__all__:
env.filters[filter_method] = getattr(filters, filter_method) | 5,325,105 |
def greet_person(person: Person) -> str:
"""Return a greeting message for the given person.
The message should have the form 'Hello, <given_name> <family_name>!'
>>> david = Person('David', 'Liu', 110, '110 St. George Street')
>>> greet_person(david)
'Hello, David Liu!'
"""
return f'Hello,... | 5,325,106 |
def sw(s1, s2, pen, matrix):
"""
Takes as input two sequences, gap penalty, BLOSUM or PAM dictionary
and returns the scoring matrix(F) and traceback matrix(P)
"""
N = len(s1) + 1
M = len(s2) + 1
F = [] #initialize scoring matrix(F) and traceback matrix(P)
P = []
F = [[... | 5,325,107 |
def open_data(num=None, folder=None, groupname="main", datasetname="data", date=None):
"""Convenience Load data from an `AuspexDataContainer` given a file number and folder.
Assumes that files are named with the convention `ExperimentName-NNNNN.auspex`
Parameters:
num (int)
File num... | 5,325,108 |
def read_item() -> Any:
"""
Get item by ID.
"""
print("read item")
pass | 5,325,109 |
def random_multiplex_ER(n,l,p,directed=False):
""" random multilayer ER """
if directed:
G = nx.MultiDiGraph()
else:
G = nx.MultiGraph()
for lx in range(l):
network = nx.fast_gnp_random_graph(n, p, seed=None, directed=directed)
for edge in network.edges(... | 5,325,110 |
def download(
districts: Optional[str], areas: Optional[str], surnames: Tuple[str], headless: bool, debug: bool, console: bool
):
"""download name"""
output = f"cica-{datetime.now():%Y%m%d-%H%M}"
set_up_logger(debug, console, log_file=f"{output}.log") # set up logger
districts, areas = list(distric... | 5,325,111 |
def _save_current_regression_range_indices(testcase_id, regression_range_start,
regression_range_end):
"""Save current regression range indices in case we die in middle of task."""
testcase = data_handler.get_testcase_by_id(testcase_id)
testcase.set_metadata(
'last... | 5,325,112 |
def activation_summary(x):
"""Helper to create summaries for activations.
Creates a summary that provides a histogram of activations.
Creates a summary that measures the sparsity of activations.
Args:
x: Tensor
Returns:
nothing
"""
if FLAGS.verbose:
tf.summary.histogram('activation', x)
... | 5,325,113 |
def testTaskRunnerSuspend(databases, data):
"""Test suspend functionality."""
resourceFactory = databases.resourceDB.factory
record = resourceFactory.newTaskRunner('runner1', '', set())
record.sync(databases.jobDB, data)
# Check if initially not suspended.
assert not record.isSuspended()
#... | 5,325,114 |
def compare_structures(structure_a, structure_b):
"""Compare two StructureData objects A, B and return a delta (A - B) of the relevant properties."""
delta = AttributeDict()
delta.absolute = AttributeDict()
delta.relative = AttributeDict()
volume_a = structure_a.get_cell_volume()
volume_b = str... | 5,325,115 |
def parse_response(expected: str) -> Callable:
"""
Decorator for a function that returns a requests.Response object.
This decorator parses that response depending on the value of <expected>.
If the response indicates the request failed (status >= 400) a dictionary
containing the response status and... | 5,325,116 |
def find_parents(candidate, branches):
"""Find parents genre of a given genre, ordered from the closest to
the further parent.
"""
for branch in branches:
try:
idx = branch.index(candidate.lower())
return list(reversed(branch[:idx + 1]))
except ValueError:
... | 5,325,117 |
def swig_ptr_from_FloatTensor(x):
""" gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
assert x.is_contiguous()
assert x.dtype == torch.float32
return faiss.cast_integer_to_float_ptr(
x.storage().data_ptr() + x.storage_offset() * 4) | 5,325,118 |
def generate_reference_user_status(user,references):
"""Generate reference user status instances for a given set of references.
WARNING: the new instances are not saved in the database!
"""
new_ref_status = []
for ref in references:
source_query = ref.sources.filter(userprofile=user.userprofile)\
... | 5,325,119 |
def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2):
"""Read a file by chrom name into a bitset"""
bitset = BinnedBitSet( MAX )
for line in f:
if line.startswith("#"): continue
fields = line.split()
if fields[chrom_col] == chrom:
start, end = int( ... | 5,325,120 |
def timeperiod_contains(
timeperiod: spec.Timeperiod,
other_timeperiod: spec.Timeperiod,
) -> bool:
"""return bool of whether timeperiod contains other timeperiod"""
start, end = timeperiod_crud.compute_timeperiod_start_end(timeperiod)
other_start, other_end = timeperiod_crud.compute_timeperiod_star... | 5,325,121 |
def sort_vertices_by_degree(G, vs, within=None):
"""
Stable inplace sort of vs by degree in G, optionally
only considering neighbors in `within`.
"""
if within is None:
vs.sort(cmp=lambda u,v: cmp(G.degree(u), G.degree(v)))
else:
vs.sort(cmp=lambda u,v: cmp(degree_within(G, u, within),
... | 5,325,122 |
def PlotColumns(data_list, ax, args):
""" Plot one dimensional data as column / bar plot.
Args:
data_list: a list of Data objects.
ax: a matplotlib axis object.
args: an argparse arguments object.
"""
width = 2.0 / 3.0 / len(data_list)
data_min = min(map(numpy.min, map(lambda x: x.y, data_list)))... | 5,325,123 |
def preprocess_all(num_beats):
"""
Preprocess all patients
:return:
"""
flags = [True, False]
for control_patients in flags:
indicies = get_patient_ids(control=control_patients)
for idx, filename in zip(indicies, get_filenames(original=(not control_patients), control=control_patients)):
idx = str(idx)
... | 5,325,124 |
def asdict(obj, dict_factory=dict, filter_field_type=None):
"""
Version of dataclasses.asdict that can use field type infomation.
"""
if _is_dataclass_instance(obj):
result = []
for f in fields(obj):
if filter_field_type is None:
continue
field_ty... | 5,325,125 |
def resolve(jira_issue, resolution_name, resolve_comment):
"""
Given a JIRA ticket, mark the ticket as resolved.
:param jira_issue: the specified JIRA ticket
:param resolution_name: the specified type of resolution for this ticket
"""
state_name = config.get('jira', 'resolve_transition_name')
... | 5,325,126 |
def process_pdb_file(pdb_file, atom_info_only=False):
"""
Reads pdb_file data and returns in a dictionary format
:param pdb_file: str, the location of the file to be read
:param atom_info_only: boolean, whether to read the atom coordinates only or all atom data
:return: pdb_data, dict organizing pdb... | 5,325,127 |
def get_insns(*, cls=None, variant: Variant = RV32I):
"""
Get all Instructions. This is based on all known subclasses of `cls`. If non
is given, all Instructions are returned. Only such instructions are returned
that can be generated, i.e., that have a mnemonic, opcode, etc. So other
classes in the ... | 5,325,128 |
def get_review(cursor, hpage_html, movie_title):
"""Retrieves reviews from hpage_html.
All reviews are stored in database.
Args:
cursor: cursor of a connection to sqlite.
hpage_html: string, homepage of a movie, e.g. HTML text of URL 'https://www.imdb.com/title/tt2015381/'
movi... | 5,325,129 |
def _assert_all_equal_and_return(tensors, name=None):
"""Asserts that all tensors are equal and returns the first one."""
with backend.name_scope(name or 'assert_all_equal'):
if len(tensors) == 1:
return tensors[0]
assert_equal_ops = []
for t in tensors[1:]:
assert_equal_ops.append(check_ops... | 5,325,130 |
def _get_igraph(G, edge_weights=None, node_weights=None):
"""
Transforms a NetworkX graph into an iGraph graph.
Parameters
----------
G : NetworkX DiGraph or Graph
The graph to be converted.
edge_weights: list or string
weights stored in edges in the original graph to ... | 5,325,131 |
def add_extra_args(parser, files):
"""Add additional arguments defined in other files."""
for f in files:
m = importlib.import_module(f)
if 'setup_extra_args' in m.__dict__:
m.setup_extra_args(parser) | 5,325,132 |
def rename(isamAppliance, instance_id, id, new_name, check_mode=False, force=False):
"""
Deleting a file or directory in the administration pages root
:param isamAppliance:
:param instance_id:
:param id:
:param name:
:param check_mode:
:param force:
:return:
"""
dir_id = Non... | 5,325,133 |
def write_hdf5(filename, data, dataset_name='dataset', dtype='f'):
"""
Create hdf5 file
Inputs
filename : str
hdf5 filename
data : array, shape (n_vertices, n_times)
raw data for whose the dataset is created
dataset_name : str
name of dataset to c... | 5,325,134 |
def deepset_update_global_fn(feats: jnp.ndarray) -> jnp.ndarray:
"""Global update function for graph net."""
# we want to sum-pool all our encoded nodes
#feats = feats.sum(axis=-1) # sum-pool
net = hk.Sequential(
[hk.Linear(128), jax.nn.elu,
hk.Linear(30), jax.nn.elu,
hk.Linear(11)]) # numbe... | 5,325,135 |
def max_sum_naive(arr: list, length: int, index: int, prev_max: int) -> int:
"""
We can either take or leave the current number depending on previous max number
"""
if index >= length:
return 0
cur_max = 0
if arr[index] > prev_max:
cur_max = arr[index] + max_sum_naive(arr, lengt... | 5,325,136 |
def accuracy(X, X_ref):
""" Compute classification accuracy.
Parameters
----------
X : torch.Tensor
The classification score tensor of shape [..., num_classes]
X_ref : torch.Tensor
The target integer labels of shape [...]
Returns
-------
The average accuarcy
"""
... | 5,325,137 |
def download_dataset(filepath=DATASET_PATH, url=DATASET_URL, **kwargs) -> pd.DataFrame:
"""
Download dataset
:param: file Output filename
"""
kwargs.setdefault("session", requests.Session())
r = kwargs['session'].get(url)
# Jos lataus epäonnistuu, epäonnistu nyt.
# `raise_for_status... | 5,325,138 |
def create_cert_builder(subject, issuer_name, public_key, days=365, is_ca=False):
"""
The method to create a builder for all types of certificates.
:param subject: The subject of the certificate.
:param issuer_name: The name of the issuer.
:param public_key: The public key of the certificate.
:p... | 5,325,139 |
def _loadvid_test_vanilla(filename, width, height):
"""Tests the usual loadvid call.
The input file, an encoded video corresponding to `filename`, is repeatedly
decoded (with a random seek). The first and last of the returned frames are
plotted using `matplotlib.pyplot`.
"""
with open(filename,... | 5,325,140 |
def _table_row(line):
"""
Return all elements of a data line.
Return all elements of a data line. Simply splits it.
Parameters
----------
line: string
A stats line.
Returns
-------
list of strings
A list of strings, containing the data on the line, split at white s... | 5,325,141 |
def ack_alert_alarm_definition(definition_id):
""" Acknowledge all alert(s) or an alarm(s) associated with the definition identified by definition_id.
"""
try:
# Get definition identified in request
definition = SystemEventDefinition.query.get(definition_id)
if definition is None:
... | 5,325,142 |
def range2d(range_x, range_y):
"""Creates a 2D range."""
range_x = list(range_x)
return [ (x, y) for y in range_y for x in range_x ] | 5,325,143 |
def _auto_run(args):
"""This function executes when the script is called as a stand-alone
executable. It is used both for development/testing as well as the
primary executable for generating the cross-run-ID PDF report.
To use as a stand-alone script (primarily for development purspoes)
the script h... | 5,325,144 |
def test_sch_t3_sch_t3_v(mode, save_output, output_format):
"""
TEST :schema collection and schema location : redefine with a
attributeGroup, attribute group's content items are a subset of the
redefined group, (SRC 7.2.2)
"""
assert_bindings(
schema="msData/schema/schT3_a.xsd",
... | 5,325,145 |
def kmeans_(X, sample_weights, n_clusters, init='kmeans++', max_iter=300):
"""
Weighted K-Means implementation (Lloyd's Algorithm).
:param X:
:param sample_weights:
:param n_clusters:
:param init: string in {'random', 'kmeans++'}, default 'kmeans++'
:param max_iter: maximum number of iterati... | 5,325,146 |
def display_cim_objects(context, cim_objects, output_format, summary=False,
sort=False, property_list=None, quote_strings=True):
"""
Display CIM objects in form determined by input parameters.
Input is either a list of cim objects or a single object. It may be
any of the CIM typ... | 5,325,147 |
def CPCT_LambdaPitch(refdir,main_fastfile,Lambda=None,Pitch=np.linspace(-10,40,5),WS=None,Omega=None, # operating conditions
TMax=20,bStiff=True,bNoGen=True,bSteadyAero=True, # simulation options
reRun=True,
fastExe=None,showOutputs=True,nCores=4): # execution options
""" Computes CP ... | 5,325,148 |
def cylinders_instantiate(part, dims, dest):
"""Fonction pour creer des cylindres en serie"""
names = []
for i, d in enumerate(dims):
n = "{}_cylinder_{}".format(part, i)
names.append(n)
print("\t\t<Creation du cylindre : {} de dimension {}>".format(n, d))
dest.append(cmds... | 5,325,149 |
def segment(im, pad=0, caffemodel=None):
"""
Function which segments an input image. uses pyramidal method of scaling, performing
inference, upsampling results, and averaging results.
:param im: image to segment
:param pad: number of pixels of padding to add
:param caffemodel: path to caffemodel... | 5,325,150 |
async def test_call_with_no_args_async():
"""
It should be able to invoke functions with no-args.
"""
breaker = CircuitBreaker()
assert await breaker.call_async(func_succeed_async) | 5,325,151 |
def morpheme_tokenizer(st):
"""
Tokenize a string splitting it on typical morpheme boundaries: [ - . : = ( ) ]
:param st:
"""
pieces = re.finditer('[^\s\-\.:/\(\)=]+', st)
for match in pieces:
if match.group().strip():
yield Morph(match.group(0), start=match.start(), stop=m... | 5,325,152 |
def register(handlerclass):
"""
Adds a custom handler.
"""
if not issubclass(handlerclass, Handler):
message = u"parameter it's not a Handler class"
raise TypeError(message)
__HANDLERS.append(handlerclass) | 5,325,153 |
async def test_read_write(dut):
"""Test handle inheritance"""
tlog = logging.getLogger("cocotb.test")
cocotb.start_soon(Clock(dut.clk, 10, "ns").start())
await Timer(10, "ns")
tlog.info("Checking Generics/Parameters:")
_check_logic(tlog, dut.param_logic, 1)
_check_logic(tlog, dut.param_lo... | 5,325,154 |
def check_consistency( # pylint: disable=too-many-arguments
num_users=None,
num_items=None,
users_hat=None,
items_hat=None,
users=None,
items=None,
user_item_scores=None,
default_num_users=None,
default_num_items=None,
default_num_attributes=None,
num_attributes=None,
at... | 5,325,155 |
def verify_forgot_password(request):
"""
Check the forgot-password verification and possibly let the user
change their password because of it.
"""
# get form data variables, and specifically check for presence of token
formdata = _process_for_token(request)
if not formdata['has_userid_and_to... | 5,325,156 |
def test_noop_load() -> None:
"""
Load a checkpoint
"""
experiment_id = exp.run_basic_test(
conf.fixtures_path("no_op/single.yaml"), conf.fixtures_path("no_op"), 1
)
trials = exp.experiment_trials(experiment_id)
checkpoint = Determined(conf.make_master_url()).get_trial(trials[0].tria... | 5,325,157 |
def requirement(alpha=0.2, w=2.):
"""
Plots the requirements, both for PSF and MTF and compares them.
:param alpha: power law slope
:param w: wavenumber
:return: None
"""
#from MTF
wave = [550, 750, 900]
mtf = np.asarray([0.3, 0.35, 0.4])
forGaussian = np.sqrt(- np.log(mtf) * 4 ... | 5,325,158 |
def setup(hass, config):
"""Set up for WeMo devices."""
import pywemo
global SUBSCRIPTION_REGISTRY
SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
SUBSCRIPTION_REGISTRY.start()
def stop_wemo(event):
"""Shutdown Wemo subscriptions and subscription thread on exit."""
_LOGGE... | 5,325,159 |
def extend_node(node, out_size, axis=-1, value=0):
"""Extend size of `node` array
For now, this function works same with `extend_array` method,
this is just an alias function.
Args:
node (numpy.ndarray): the array whose `axis` to be extended.
first axis is considered as "batch" axi... | 5,325,160 |
def add_edge(graph, edge):
"""Adds an edge to a given graph.
If an edge between the two nodes already exists, the one with the largest
weight is retained.
Args:
graph: A `dict`: source_id -> (target_id -> weight) to be augmented.
edge: A `list` (or `tuple`) of the form `[source, target, weight]`, wher... | 5,325,161 |
def _post_amplitude(d, method, amp):
"""
Internal small helper function for repeated tests of method - posts the
computed amplitudes to metadata with a different key for each method
used to compute amplitude.
"""
if method == 'rms' or method == 'RMS':
d['rms_amplitude'] = amp
elif me... | 5,325,162 |
def forward(X, weights, bias):
"""
Simulate the forward pass on one layer.
:param X: input matrix.
:param weights: weight matrix.
:param bias: bias vector.
:return:
"""
a = np.matmul(weights, np.transpose(X))
b = np.reshape(np.repeat(bias, np.shape(X)[0], axis=0), np.shape(a))
o... | 5,325,163 |
def sanitize_for_params(x: Any) -> Any:
"""Sanitizes the input for a more flexible usage with AllenNLP's `.from_params()` machinery.
For now it is mainly used to transform numpy numbers to python types
Parameters
----------
x
The parameter passed on to `allennlp.common.FromParams.from_para... | 5,325,164 |
def demo(epd):
"""simple partial update demo - draw draw a clock"""
# initially set all white background
image = Image.new('1', epd.size, WHITE)
# prepare for drawing
draw = ImageDraw.Draw(image)
width, height = image.size
timestamp_font = ImageFont.truetype(FONT_FILE, TIMESTAMP_FONT_SIZE... | 5,325,165 |
def filename_fixture():
"""The name of the cities csv file for testing"""
return os.path.join('tests', 'fixtures', 'cities.csv') | 5,325,166 |
def _get_color_context():
""" Run at beginning of color workflow functions (ex start() or resume()) to orient the function.
Assumes python current working directory = the relevant AN subdirectory with session.log in place.
Adapted from package mp_phot, workflow_session.py._get_session_context(). Req... | 5,325,167 |
def validate_user(doc, method):
"""
validate user their should be only one department head
"""
if doc.name == "Administrator":
return
query = """ SELECT name FROM `tabUser` WHERE department='%s' AND
name IN (SELECT parent FROM `tabUserRole` WHERE role='Department Head')"""%(doc.department)
record = frappe... | 5,325,168 |
def host_ip():
"""Test fixture to resolve and return host_ip as a string."""
import dns.resolver
query = dns.resolver.query("scanme.nmap.org")
assert len(query) > 0, "could not resolve target host name"
return query[0].address | 5,325,169 |
def with_behavior(strict=UNSET, extras=UNSET, hook=UNSET):
"""
Args:
strict (bool | Exception | callable): False: don't perform any schema validation
True: raise ValidationException when schema is not respected
E... | 5,325,170 |
def get_subnet_from_list_by_id(subnet_id, subnets_list):
"""Get Neutron subnet by id from provided subnets list.
:param subnet_id: Neutron subnet ID
:param subnets_list: List of Neutron subnets, where target subnet should
be searched
"""
for subnet in subnets_list:
... | 5,325,171 |
def grafana_logo(dispatcher):
"""Construct an image_element containing the locally hosted Grafana logo."""
return dispatcher.image_element(dispatcher.static_url(GRAFANA_LOGO_PATH), alt_text=GRAFANA_LOGO_ALT) | 5,325,172 |
def is_json(payload):
"""Check if a payload is valid JSON."""
try:
json.loads(payload)
except (TypeError, ValueError):
return False
else:
return True | 5,325,173 |
def gram_schmidt(M):
"""
@param M:
A mxn matrix whose columns to be orthogonalized
@return ret
Matrix whose columns being orthogonalized
"""
columns = M.T
res = []
res.append(columns[0])
for x in range(1, columns.shape[0]):
tmp = np.array([0 for x in range(M.... | 5,325,174 |
def contract_variation_linear(G, A=None, K=10, r=0.5, mode='neighborhood'):
"""
Sequential contraction with local variation and general families.
This is an implemmentation that improves running speed,
at the expense of being more greedy (and thus having slightly larger error).
See contract_variati... | 5,325,175 |
def horizon_main_nav(context):
""" Generates top-level dashboard navigation entries. """
if 'request' not in context:
return {}
current_dashboard = context['request'].horizon.get('dashboard', None)
dashboards = []
for dash in Horizon.get_dashboards():
if callable(dash.nav) and dash.n... | 5,325,176 |
def _filter_out_bad_segments(img1, seg1, img2, seg2):
"""
It's possible for shearing or scaling augmentation to sample
one segment completely out of the image- use this function
to filter out those cases
"""
minval = tf.reduce_min(tf.reduce_sum(seg1, [0,1])*tf.reduce_sum(seg2, [0,1]))
if min... | 5,325,177 |
def test_rq_predict_nans():
"""
Tests that the predictions are not nans
"""
model = pf.GPNARX(data=data, ar=2, kernel=pf.RationalQuadratic())
x = model.fit()
x.summary()
assert(len(model.predict(h=5).values[np.isnan(model.predict(h=5).values)]) == 0) | 5,325,178 |
def _seconds_to_hours(time):
"""Convert time: seconds to hours"""
return time / 3600.0 | 5,325,179 |
def execute_command(api_instance, pod_info, exec_command):
"""
Execute a command inside a specified pod
exec_command = list of strings
"""
name = pod_info['name']
resp = None
try:
resp = api_instance.read_namespaced_pod(name=name,
names... | 5,325,180 |
def test_should_detect_consistency_for_notebook_and_script_with_conf(work_dir):
"""
Test check_script_consistency exit without error when there is consistency
between notebook and script with conf.
Without conf there is inconsistency but with the right ignore cell there is consistency
"... | 5,325,181 |
async def process_cmd_entry_erase(guild_id: int, txt_channel: str, bosses: list,
channel = None):
"""Processes boss `entry` `erase` subcommand.
Args:
guild_id (int): the id of the Discord guild of the originating message
txt_channel (str): the id of the channel of the originating message,
... | 5,325,182 |
def mle_iid_gamma(n):
"""Perform maximum likelihood estimates for parameters for i.i.d.
NBinom measurements, parametrized by alpha, b=1/beta"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res = scipy.optimize.minimize(
fun=lambda log_params, n: -log_like_iid_... | 5,325,183 |
def main():
""" Main function. """
set_random_seed(args)
if args.num_runs == -1: # run once
runner = Runner(args)
runner.run()
else:
xs = []
for i in range(args.num_runs):
best_acc = launch_random_run(args)
xs.append(best_acc.item())... | 5,325,184 |
def build_tabnet_results(dataset, image_ids, rois, class_ids, scores, masks):
"""Arrange resutls to match COCO specs in http://cocodataset.org/#format
"""
# If no results, return an empty list
if rois is None:
return []
results = []
for image_id in image_ids:
# Loop through dete... | 5,325,185 |
def test_sub_account_deposit_address():
"""Tests the API endpoint to get deposit history"""
client = Client(key, secret)
response = client.sub_account_deposit_history(**params)
response.should.equal(mock_item) | 5,325,186 |
def make_raw_serving_input_receiver_fn(
feature_spec: features_specs_type,
transform_input_tensor: Callable[[Dict[str, tf.Tensor]], None],
is_model_canned_estimator: bool = False,
batched_predictions: bool = True
) -> Callable[[], tf.estimator.export.ServingInputReceiver]:
"""
Build the serving_... | 5,325,187 |
def load_parentheses_dataset(path: str, depths: List[int]) -> torchtext.data.Dataset:
"""
Load equation verification data as a sequential torchtext Dataset, in infix
notation with parentheses.
The Dataset is additionally populated with `leaf_vocab`, `unary_vocab`, and
`binary_vocab` sets.
"""
... | 5,325,188 |
def configure(config, import_error="raise", unknown_key="raise"):
"""Configure xtas.
Parameters
----------
config : dict
Dict with keys ``CELERY``, ``ELASTICSEARCH`` and ``EXTRA_MODULES``
will be used to configure the xtas Celery app.
``config.CELERY`` will be passed to Celery'... | 5,325,189 |
async def test_volume_services(hass):
"""Test the volume service."""
assert await async_setup_component(
hass, mp.DOMAIN, {"media_player": {"platform": "demo"}}
)
await hass.async_block_till_done()
state = hass.states.get(TEST_ENTITY_ID)
assert state.attributes.get("volume_level") == 1.0... | 5,325,190 |
def get_angle(v1: List[int], v2: List[int]):
"""
:param v1: 2D vector
:param v2: 2D vector
:return: the angle of v1 and v2 in degree
"""
dot = np.dot(v1, v2)
norm = np.linalg.norm(v1) * np.linalg.norm(v2)
return np.degrees(np.arccos(dot / norm)) | 5,325,191 |
def get_plasma_intersection(lon, lat, alt, plasma_alt=300., tx_lon=-75.552,
tx_lat=45.403, tx_alt=0.07):
"""
This function finds where a ray from a transmitter toward a satellite
intersects the peak plasma in the middle.
*** PARAMS ***
Satellite ephemeris point(s): lon, ... | 5,325,192 |
def send_warnings_to_print(message, category, filename, lineno, file=None, *args):
"""Will be sent to stdout, formatted similar to LogRecords. """
location = filename.split('/')[-1].rstrip('.py') if isinstance(filename, str) else 'UNKNOWN'
bonus_string = ''
if file:
bonus_string += f"file: {file... | 5,325,193 |
def plot_clusters(g, c):
"""
Draws a given graph g with vertex colours corresponding to clusters c and
displays the corresponding sizes of the clusters.
===========================================================================
Parameters
--------------------------------------------------------... | 5,325,194 |
def _check(expression, section, option, message='Not a valid value'):
"""check whether an operation if valid and report error message if invalid.
Parameters
----------
expression : bool
The judgement conditions in main2.
section : string
The section of configuration file.
option... | 5,325,195 |
def make_cat_advanced(simple=True, yolo=False):
"""fill the categories manually"""
cat_list = get_cat_list(simple)
if simple:
if yolo:
cat_mapping = {
"benign": 0,
"malign": 1,
}
else:
cat_mapping = [0, 1]
return ca... | 5,325,196 |
def process_fuel(context):
"""
Reformats Fuel consumed
"""
fuel = {
0: 'Petrol',
1: 'Desiel'
}
data = []
totals = []
for index, type in enumerate(context['Fuel']):
litresSold = operator.sub(type.closing_meter, type.opening_meter)
total = operator.mul(litresS... | 5,325,197 |
def prepare_df_financials(
ticker: str, statement: str, quarter: bool = False
) -> pd.DataFrame:
"""Builds a DataFrame with financial statements for a given company
Parameters
----------
ticker : str
Company's stock ticker
statement : str
Either income, balance or cashflow
q... | 5,325,198 |
def print_transaction(context, transaction):
"""
Prints the transaction summary
"""
if transaction.success:
if transaction.changed:
title_color = "[1;34m"
status_char = "[32m+[m"
else:
title_color = "[1m"
status_char = "[37m.[m"
e... | 5,325,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.