content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate_enum(datum, schema, **kwargs):
"""
Check that the data value matches one of the enum symbols.
i.e "blue" in ["red", green", "blue"]
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
kwargs: Any
Unused kwargs
"""
retur... | 5,293,100 |
def plot_fleur_sn(node, show_dict=False, **kwargs):
"""
This methods takes any single AiiDA node and starts the standard visualization for
if it finds one
"""
plot_nodes, workflow_name, _ = classify_node(node)
if show_dict:
pprint(plot_nodes[0])
try:
plotf = FUNCTIONS_DICT... | 5,293,101 |
def skip_mpi(request):
"""Skip tests marked ``serial`` when running with MPI."""
if request.node.get_closest_marker('serial'):
if 'device' in request.fixturenames:
if request.getfixturevalue('device').communicator.num_ranks > 1:
pytest.skip('Test does not support MPI executio... | 5,293,102 |
def confounds_correlation_plot(
confounds_file,
columns=None,
figure=None,
max_dim=20,
output_file=None,
reference="global_signal",
):
"""
Generate a bar plot with the correlation of confounds.
Parameters
----------
confounds_file: :obj:`str`
File containing all conf... | 5,293,103 |
def _run_cli(cls, *args):
"""Handle command line interface invocation of this script"""
# Create argument parser from fields
parser = argparse.ArgumentParser(description=cls.__doc__)
used_prefixes = set("-h") # keep track of -X options used; -h -> help
for name, field in cls.declared_fields.items()... | 5,293,104 |
def create_user(user_data, status=200):
"""Create a new user throught the API"""
user_data = user_data
res = app.post_json('/v1/users',
user_data,
status=status,
expect_errors=status != 200)
return res | 5,293,105 |
def close_db_conn(conn):
"""
Close note db connection
:param conn: db connection
:return:
"""
try:
if conn is not None:
conn.close()
finally:
if conn is not None:
conn.close() | 5,293,106 |
def _fullpacket_test_case(dut):
"""
Test case to test FULLPACKET behavior.
This test is hardcoded to the parameters:
FLIT_WIDTH = 8
DEPTH = 4
FULLPACKET = 1
"""
yield FallingEdge(dut.clk)
_set_inputs(dut, 0x01, 0, 0, 0)
yield FallingEdge(dut.clk)
# Fill buffer ... | 5,293,107 |
def get_google(
query, n_answers=3, best_so=False, mute=False, break_on_best=False
):
"""
Prints links to the top hits on google given a search query (str)
and returns a link to the top one.
:param query: str, search query
:param n_answers: int, number of max results to get
:param best_so: ... | 5,293,108 |
def eval_triangle(x, h, n):
"""
Compute triangle histogram for given latent variables
Input:
x [num_batch, num_latent] latent values
h [num_latent, num_tri] triangle heights
n [num_tri] number of triangles to use
x is broadcasted to [num_batch, num_latent, num_tri] (replicated nu... | 5,293,109 |
def makePartialJac(spec_pair, varnames, select=None):
"""Use this when parameters have been added to a modified Generator which
might clash with aux fn argument names. (E.g., used by find_nullclines).
'select' option (list of varnames) selects those entries from the Jac of the varnames,
e.g. fo... | 5,293,110 |
def get_valid_filename(s):
"""Sanitize string to make it reasonable to use as a filename.
From https://github.com/django/django/blob/master/django/utils/text.py
Parameters
----------
s : string
Examples
--------
>>> print get_valid_filename(r'A,bCd $%#^#*!()"\' .ext ')
'a_bcd__.ex... | 5,293,111 |
def merge_lists(config, path, base, nxt):
""" a list strategy to merge lists """
for i in range(len(nxt)):
base[i]=my_merger.merge(base[i], nxt[i])
return base | 5,293,112 |
def normalize_shape(shape):
"""Normalize a shape ``tuple`` or ``array`` to a shape ``tuple``.
Parameters
----------
shape : tuple of int or ndarray
The input to normalize. May optionally be an array.
Returns
-------
tuple of int
Shape ``tuple``.
"""
if isinstance(s... | 5,293,113 |
def getLogger(name: str, event_handlers=[]):
"""Creates a logger with .
:type name: str
:param name: the name of the logger to be constructed.
:type event_handlers: list
:param name: list of event handlers
:rtype: :class:`logging.Logger`
:returns: Logger created.
"""
return logger... | 5,293,114 |
def echo_shout(word):
"""Change the value of a nonlocal variable"""
# Concatenate word with itself: echo_word
echo_word=word+word
#Print echo_word
print(echo_word)
# Define inner function shout()
def shout():
"""Alter a variable in the enclosing scope"""
#Use echo_word in... | 5,293,115 |
def parse_shortform_block_annotation(description):
"""Parses shortform version of the block annotation from a string.
Parameters
----------
description : str
Returns
-------
dict
Returns a dictionary with keys 'ref_version', 'chromosome',
'chromosome_scaffold', 'genome_pos'... | 5,293,116 |
def main(inmap, medianfilter):
"""Load input paramters, remove cosmic rays and NaNs,
then make all off-limb pixels zero, and clean up limb,
rotate map and do a cosine correction.
"""
## Load configuration file
config = ConfigParser()
config.read("config.ini")
## Rotate
inmap = inmap.... | 5,293,117 |
def clean_data(data: DataFrame) -> DataFrame:
"""
Clean the titanic data by converting all the data
into int64s.
Drops the passenger id since it does not contribute
to survivability.
We drop the ticket attribute since the vast majority of them
are unique, which makes it tough to convert th... | 5,293,118 |
def get_days_where_1percent_plus_of_requests_lead_to_errors():
"""Return days which more than 1% of requests lead to errors."""
conn = psycopg2.connect("dbname=news")
cur = conn.cursor()
cur.execute(days_which_more_than_1percent_of_requests_lead_to_errors)
results = cur.fetchall()
conn.close()
... | 5,293,119 |
def warp(x, flow):
"""
x: [B, C, H, W] (im2)
flo: [B, 2, H, W] flow
"""
n, c, h, w = x.size()
# mesh grid
w_grid = torch.linspace(0., w-1, w).view(1, 1, 1, w).expand(n, 1, h, w).cuda()
h_grid = torch.linspace(0., h-1, h).view(1, 1, h, 1).expand(n, 1, h, w).cuda()
grid = torc... | 5,293,120 |
def utils_fft(series):
"""
Computes the inverse fast foyer transform.
Parameters
Input
series : array_like
Output
The transformed array.
"""
return numpy.fft.fft(series) | 5,293,121 |
def not_operator(a: PrimitiveExpression) -> Union[HTCBool, Undefined, Error]:
"""
Logical not operator as defined by classad specification.
.. code:: python3
parse("!False").evaluate() # result: HTCBool(True)
"""
return a.__htc_not__() | 5,293,122 |
def _go_marshal_impl(ctx):
"""Execute the go_marshal tool."""
output = ctx.outputs.lib
output_test = ctx.outputs.test
(build_dir, _, _) = ctx.build_file_path.rpartition("/BUILD")
decl = "/".join(["gvisor.dev/gvisor", build_dir])
# Run the marshal command.
args = ["-output=%s" % output.path... | 5,293,123 |
def create_inception_graph():
"""
저장된 GraphDef 파일에서 그래프를 만들고
Graph 오브젝트를 리턴한다.
"""
with tf.Graph().as_default() as graph:
model_filename = os.path.join(model_dir, 'classify_image_graph_def.pb')
with gfile.FastGFile(model_filename, 'rb') as f:
graph_def = tf.GraphDef()
... | 5,293,124 |
def BackwardElimination(x, y, Threshold):
"""
This function apply a backard elimination for a linear regression model, based on P Value level.
Argument:
----------
- x: pandas dataframe
The dependent variables
- y: pandas dataframe
The independent variable
... | 5,293,125 |
def test_indexer(
dask_client, # pylint: disable=redefined-outer-name,unused-argument
arg,
request,
):
"""Test the update of a dataset."""
tested_fs = request.getfixturevalue(arg)
zcollection = create_test_collection(tested_fs)
indexers = zcollection.map(
lambda x: slice(0, x.dimen... | 5,293,126 |
def ListToString(list_items):
"""Convert a list of items into a unicode string of a comma-separated."""
str_list = [unicode(v) for v in list_items]
return u', '.join(str_list) | 5,293,127 |
def test(carousels: List[element.Tag], warning: StringIO):
"""Test."""
assert not carousels
warnings = warning.getvalue().strip()
assert "index.rst:3: WARNING: No images specified in carousel." in warnings | 5,293,128 |
def allstate(update, context):
""" STATEWISE COVID CASES """
for data in range(total_states):
state_wise_data = f"State / UT : *{regional_data[data]['loc']}*\n\
Active Indian Cases : *{regional_data[data]['confirmedCasesIndian']:,}*\n\
Active Foreign Cases : *{regional_data[data]['confirmedC... | 5,293,129 |
def doubleFromQString(string):
"""
Return a double precision floating point conversion of a QString object.
"""
d, ok = string.toDouble()
if not ok:
raise ValueError('ValueError converting : %s' % string)
return d | 5,293,130 |
def restore_files(key, archive_file):
"""Restore the orgiginal files from the compressed archive."""
with open(archive_file, 'r') as f:
lines = f.readlines()
for ciphertext in lines:
cipher = AESCipher(key)
decrypted = cipher.decrypt(ciphertext)
fname, data = decrypted.decod... | 5,293,131 |
def load_primers_as_re(primer_fasta, mm, rc=False):
"""Load primers as regular expressions.
Read primer file and record all specified sequences.
"""
primers = set()
in_handle = open(primer_fasta, "rU")
reader = fastaReader(in_handle)
count = 0
for record in reader:
if rc:
... | 5,293,132 |
def get_foot_marker(foot: Literal["left", "right"]) -> List[str]:
"""Get the names of all markers that are attached ot a foot (left or right)"""
sensors = ["{}_fcc", "{}_toe", "{}_fm5", "{}_fm1"]
return [s.format(foot[0]) for s in sensors] | 5,293,133 |
def get_price_history(data, date, beta_window, sid, benchmark):
"""
Create a DataFrame containing the data for the necessary sids within that time frame
"""
if not beta_window:
history_index = data.index.searchsorted(date)
history_index_start = data.index.searchsorted(data[data[sid] != 0... | 5,293,134 |
def _validate_string(s, accept_none = False):
"""
A validation method to convert input s to string or raise error if it is not convertable
"""
if s is None and accept_none :
return None
try:
if isinstance(s,list):
return [six.text_type(item) for item in s]
elif isinstance(s,dict):
return dict((six.tex... | 5,293,135 |
def main():
"""
"""
u = Unhappy()
for pieces in range(NORMALGAME):
u.to_draw = pieces
u.draw() | 5,293,136 |
def get_layer_size_iterator(int_or_iterable):
"""
get an iterator for different inputs:
iterable -> iterate over iterable
other type -> repeat this type ad infinitum
"""
try:
iter_ = iter(int_or_iterable)
except TypeError:
# layer size is a single integer
iter... | 5,293,137 |
def test_get_element_in_pif_composition_():
"""
tests that _check_if_element_exists_in_pif_composition_() can check for both element names and element symbols
"""
assert _get_element_in_pif_composition_(test_pif_eight, "Ca") == False
correct_comp = Composition(element="Zirconium")
assert dumps(_... | 5,293,138 |
def geocode(**kwds):
"""A factory for Geocode"""
from .Geocode import Geocode
return Geocode(**kwds) | 5,293,139 |
def mfn_multiply_slepc(mat, vec,
fntype='exp',
MFNType='AUTO',
comm=None,
isherm=False):
"""Compute the action of ``func(mat) @ vec``.
Parameters
----------
mat : operator
Operator to compute function ac... | 5,293,140 |
def iter_matrix_power(matrix: torch.Tensor, max_iter: int) -> Iterable[torch.Tensor]:
"""
Iterate over matrix powers.
:param matrix: shape: `(n, n)`
the square matrix
:param max_iter:
the maximum number of iterations.
:yields: increasing matrix powers
"""
yield matrix
a... | 5,293,141 |
def plot_learning_curves(learning_curves, xscale = 'sqrt', yscale = 'linear', hang = None, title = None, figure_name = None, y_title = 'Score'):
"""
Plot a set of PredictionResults. These can be obtained by running compare_predictors.
See module test_compare_predictors for an example.
:param learning_... | 5,293,142 |
def test_restricted_access_denied(client, path):
"""
Visitors not logged, XHR request denied.
"""
rv = client.post("/qmapshack/" + path, follow_redirects=True)
assert rv.status_code == 404 or b"Password required" in rv.data | 5,293,143 |
def sdffile2selfies_lst(sdf):
"""convert sdffile into a list of SELFIES strings.
Args:
sdffile: str, file
Returns:
selfies_lst: a list of SELFIES strings.
"""
smiles_lst = sdffile2smiles_lst(sdf)
selfies_lst = list(map(smiles2selfies, smiles_lst))
return selfies_lst | 5,293,144 |
def get_gl_handle(schema, vineyard_id, engine_hosts, engine_config):
"""Dump a handler for GraphLearn for interaction.
Fields in :code:`schema` are:
+ the name of node type or edge type
+ whether the graph is weighted graph
+ whether the graph is labeled graph
+ the number of int attributes
... | 5,293,145 |
def has_single_gpu() -> bool:
"""Return whether there is only a GPU available."""
return get_available_gpus_number() == 1 | 5,293,146 |
def is_config_or_test(example, scan_width=5, coeff=0.05):
"""Check if file is a configuration file or a unit test by :
1- looking for keywords in the first few lines of the file.
2- counting number of occurence of the words 'config' and 'test' with respect to number of lines.
"""
keywords = ["unit ... | 5,293,147 |
def ParseVariationsCmdFromFile(filename):
"""Parses commandline switches string into internal representation.
Same as ParseVariationsCmdFromString(), except the commandline switches
string comes from a file.
"""
with open(filename, 'r') as f:
data = f.read().replace('\n', ' ')
return ParseVariationsCmd... | 5,293,148 |
def select_period(xr_data: xr.DataArray, period: TimePeriod) -> xr.DataArray:
"""Function to temporally subset an xarray dataset from a tuple of
start date and end date
"""
return xr_data.sel(time=slice(period.start, period.end)) | 5,293,149 |
def pytest_html_results_table_header(cells):
"""
添加带有测试函数docstring的description列,添加可排序的time列,并删除test与links列
:param cells:
:return:
"""
cells.insert(2, html.th('Description'))
cells.insert(1, html.th('Time', class_='sortable time', col='time'))
cells.pop()
cells.pop(2) | 5,293,150 |
def list_policies(Scope=None, OnlyAttached=None, PathPrefix=None, PolicyUsageFilter=None, Marker=None, MaxItems=None):
"""
Lists all the managed policies that are available in your AWS account, including your own customer-defined managed policies and all AWS managed policies.
You can filter the list of poli... | 5,293,151 |
def process_snr(procstatus, dscfg, radar_list=None):
"""
Computes SNR
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of dictionaries
data set configuration. Accepted Configuration Keywor... | 5,293,152 |
def norm_router(synset_mappings: dict[str, list], category_mappings: dict[str, list]):
"""Generate node-normalization router."""
router = APIRouter()
def normalize_one(curie):
"""Get normalizer response for CURIE."""
if curie not in synset_mappings:
return None
return {
... | 5,293,153 |
def record(cmd, out):
"""Record timings of a `nix-build`/`nix build` invocation."""
subprocess.run(f"\\time {' '.join(cmd)} --log-format internal-json 2>&1 | ts -s -m \"[%.s]\" > {out}", shell=True, check=True) | 5,293,154 |
def print_bbclex_instructions(fname,size):
"""Print suitable instructions for a BBC Micro lexicon of the given filename and size (the exact nature of the instructions depends on the size). If appropriate, create a .key file containing keystrokes for transferring to an emulator."""
if os.environ.get("MAKE_SPEECH_RO... | 5,293,155 |
def test_sff_breakindex():
"""Regression test for #616."""
lc = LightCurve(flux=np.ones(20))
corr = SFFCorrector(lc)
corr.correct(breakindex=[5, 10],
centroid_col=np.random.randn(20),
centroid_row=np.random.randn(20))
assert 5 in corr.window_points
assert 10 in ... | 5,293,156 |
def getROI(arr, win ='ROI selector', title = "", preview=True, crop = True, form="rect"):
"""
:param arr: array to crop
:param win: window title or instance
:param title: cropping image title
:param preview: (True) if true it shows the resulting ROI before
cropping. It could be more lig... | 5,293,157 |
def generate_trappingtable(data):
"""Generates master table of when each plot has been sampled or missed.
Input: Pandas Dataframe with the containing the following columns
plot - plot number
period - portal project period code, unique for each month of trapping
yr - year sample occured
mo - mon... | 5,293,158 |
def get_by_slug(*, db_session, slug: str) -> Plugin:
"""Fetches a given plugin or creates a new one."""
return db_session.query(Plugin).filter(Plugin.slug == slug).one_or_none() | 5,293,159 |
def authentication(req, required_roles, doctorid='', patientid=''):
"""
required_roles is a list of role's string
TODO: change back to the decorator way of authentication
may get params value (value of field expression) here by:
params['doctorid'], see docstring in falcon.hooks.before(action)
... | 5,293,160 |
def get_payment_url(order_id):
"""This method will pass order data (customer details, item data)
to the GetUrl API (iCredit) and get payment url
:param order_id: Sales Order No.
:return: payment url(iCredit) (String)"""
try:
order = frappe.get_doc("Sales Order", order_id)
icredit_settings = frappe.get_doc("i... | 5,293,161 |
def estimate_snn(model_dat, do_print=True):
"""estimate direct effects in identified structural form
using PyTorch AD automatic differentiation
forcasting y is done by reduced form since it is already solved for dy
structural form:
dy = my @ dy + mx @ dx
mx, my is a linear network of at... | 5,293,162 |
def plot_var(
data_frame,
x_var="flow",
y_var="CO_TP",
label_var="mpr",
pivot="distance",
x_label="Flow [veh/m]",
y_label="CO2 %",
t_label="Distance [m]: ",
legends=[r"0 \%", r"10 \%", r"20 \%", r"30 \%", r"40 \%"],
fnt_size={"fontsize": 16},
x_size=5,
y_size=7.5,
tra... | 5,293,163 |
async def decide_content_and_extension(
accept_header: Optional[str] = None, accept_language_header: Optional[str] = None
) -> Tuple[str, str, str]:
"""Return content_language, content_type and extension based on request."""
# Default content-type/content-language/extension:
content_language = ""
co... | 5,293,164 |
def mendel(ctx):
"""Check mendelian errors in all trios"""
logger.info("Running variant_integrity mendel {0}".format(
variant_integrity.__version__))
print_columns = ['ind_id', 'fraction_of_errors', 'mendelian_errors', 'number_calls']
# Children is a dictionary of children that counts the n... | 5,293,165 |
def end_2_end(start_date, end_date, time_step=3):
"""
Run all working tools from submitJob to download_output.
Currently only runs for tools that work.
"""
job = submit_job(start_date, end_date, time_step, kriging_method="Empirical Bayesian",
air_temperature="true", constants="true"... | 5,293,166 |
def score_segmented_edges(pred_seg, pred_edges, lbl_seg, lbl_edges):
"""
Find the precision & recall scores for a set of predictions tied to
segments within a volume. Each predicted segment is mapped to its
maximally overlapping segment within the label segments.
"""
overlaps, pred_ids, lbl_ids ... | 5,293,167 |
def test_generate_unique_sha_512_returns_random_hashes():
"""Check that function returns two random sha-512 hashes."""
hash1 = generate_unique_sha_512()
hash2 = generate_unique_sha_512()
assert re.fullmatch(r'[\da-f]{64}', hash1)
assert re.fullmatch(r'[\da-f]{64}', hash2)
assert hash1 != hash2 | 5,293,168 |
def bundle_to_json(fh):
"""
Convert the received HG10xx data stream (a mercurial 1.0 bundle created using hg push from the
command line) to a json object.
"""
# See http://www.wstein.org/home/wstein/www/home/was/patches/hg_json
hg_unbundle10_obj = readbundle(get_configured_ui(), fh, None)
gr... | 5,293,169 |
def FindUniqueTopologies(traces):
"""
Find all of the unique topologies within this set of traces. A unique topology
either differs in graph structure (parent/child) or function called at a node.
@param traces: the list of traces to compare topologies
"""
# node labels must match
node_match... | 5,293,170 |
def check_triton_and_model_analyzer_gpus(config):
"""
Check whether Triton Server and Model Analyzer are using the same GPUs
Parameters
----------
config : namespace
The arguments passed into the CLI
Raises
------
TritonModelAnalyzerException
If they are using different... | 5,293,171 |
def test_kl_loss():
"""
Test kl_loss.
"""
probs1_a = 0.7
probs1_b = 0.5
probs0_a = 1 - probs1_a
probs0_b = 1 - probs1_b
expect_kl_loss = np.log(probs1_a / probs1_b) + (probs0_a / probs1_a) * np.log(probs0_a / probs0_b)
kl_loss = KL()
output = kl_loss(Tensor([probs1_b], dtype=dtyp... | 5,293,172 |
def rotate_velocities(a,d,mua,mud):
"""eq 3.68, """
mu = return_muicrs(a,d,mua,mud)
mugal = np.dot(return_gaia_Agprime(),mu) # eq. 3.68
# solve for positions
ricrs = return_ricrs(a,d)
rgal = np.dot(return_gaia_Agprime(),ricrs)
# implement eq 3.63
ell,b = np.arctan2(rgal[1],rgal[0])... | 5,293,173 |
def save_fig_filebox_button(fig, filename):
"""
Create ipython widgets to allow the user to save a figure to the
specified file.
Parameters
----------
fig : matplotlib.Figure
The figure to be saved.
filename : str
The filename the figure should be saved to
Returns
-... | 5,293,174 |
def open_api(version):
"""
:param version:
:return:
"""
def fn(method):
@wraps(method)
def wrapper(*args, **kwargs):
openClass = get_api(version)
code, msg = openClass.check_header()
if code != 0:
return response_json(code=code, msg... | 5,293,175 |
def plotModuleCorr(cyDf, labels, plotLabel, sampleStr='M', dropped=None, compCommVar=None):
"""Make a corr plot for a module."""
modDf = makeModuleVariables(cyDf[labels.index], labels, dropped=dropped, sampleStr=sampleStr)
modVar = '%s%s' % (sampleStr, plotLabel)
cyVars = labels2modules(labels, dropped ... | 5,293,176 |
def calc_eomday(year, month):
"""end of month day"""
if isinstance(year, Iterable):
assert isinstance(month, Iterable)
return np.array([calendar.monthrange(y, m)[-1] for y, m in zip(year, month)])
else:
return calendar.monthrange(year, month)[-1] | 5,293,177 |
def prepare_clean_listing_record(listing_serializer_record):
"""
Clean Record
Sample Record (record_json) after clean
{
"id": 316,
"title": "JotSpot 28",
"description": "Jot things down",
"unique_name": "ozp.test.jotspot.28",
"description_short": "Jot stuff down",
"a... | 5,293,178 |
def retrieve_path_dict(parse_tree, path):
"""
retrieves the parameter values of an path instance
:param parse_tree: the json parse tree of the swagger document
:param path: path value of the dict to find
:return:
"""
keys = path.split("/")
my_tree = parse_tree
for key in key... | 5,293,179 |
def has_shape(data, shape, allow_empty=False):
"""
Determine if a data object has the provided shape
At any level, the object in `data` and in `shape` must have the same type.
A dict is the same shape if all its keys and values have the same shape as the
key/value in `shape`. The number of keys/val... | 5,293,180 |
def get_unmatched(repo_path: str, language: str, original_commit: str, translated_commit: str) -> List[PropEntry]:
"""
Get all original key values that have not been translated.
:param repo_path: Path to repo.
:param language: The language identifier (i.e. 'ja')
:param original_commit: The commit to... | 5,293,181 |
def to_ref(dm_cls, dm_doc_id):
"""
TODO: check doc_ref._document_path alternatives that are compatible
with firestore listeners
:param val:
:return:
"""
from onto.database.firestore import FirestoreReference
doc_ref: FirestoreReference = dm_cls._get_collection() / dm_doc_id
re... | 5,293,182 |
def rst(pkg_names):
"""Print out information on all packages in restructured text."""
pkgs = [spack.repo.get(name) for name in pkg_names]
print('.. _package-list:')
print()
print('============')
print('Package List')
print('============')
print()
print('This is a list of things you... | 5,293,183 |
def augment_specs(prefix, specs, pinned=True):
"""
Include additional specs for conda and (optionally) pinned packages.
Parameters
----------
prefix : str
Environment prefix.
specs : list of MatchSpec
List of package specifications to augment.
pinned : bool, optional
... | 5,293,184 |
def trainer(
model: Union[nn.Module, nn.Sequential],
loss_fn: Callable,
dataloader: DataLoader,
device: torch.device,
optimizer: Callable = torch.optim.Adam,
learning_rate: float = 1e-3,
preprocess_fn: Callable = None,
epochs: int = 20,
reg_loss_fn... | 5,293,185 |
def Pendulum(a0=0, v0=0):
"""
Main function for calling matplotlib animation
a0: float
starting angle (rad)
v0: float
starting angular velocity
"""
aVec = [a0]
vVec = [v0]
fig, ax = plt.subplots(figsize=(12,12))
line, = ax.plot([0, np.sin(aVec[0])], [0, np.cos(aVec[0])])
ax.set_xlim(-1.2,1.2)
... | 5,293,186 |
def metrics(self, **kwargs):
"""
History of your Blockfrost usage metrics in the past 30 days.
https://docs.blockfrost.io/#tag/Metrics/paths/~1metrics~1/get
:param return_type: Optional. "object", "json" or "pandas". Default: "object".
:type return_type: str
:returns A list of objects.
:rt... | 5,293,187 |
def build_word_pattern(word, language):
"""Given a word and a language, calculate the word pattern and the number of unique character is has."""
pattern = ""
unique = 0
char_map = {}
for char in word:
if char not in char_map.keys():
char_map[char] = unique
unique += 1... | 5,293,188 |
def validate_arguments(sys_param):
"""
Validate command line arguments passed to the script
:param sys_param: Command line arguments : Script Name,
File Path, Build Information, Deployment Type, Deactivate Old Product are required
and Options
:return: void
"""... | 5,293,189 |
def plot_spectra_by_type(frequency, spectra, classes, title=''):
"""Plot mean spectrum with its variance for a given class.
Parameters
----------
frequency : pandas Series, shape (n_freq_points,)
Frequencies for which the Raman spectra were acquired.
spectra : pandas DataFrame, shape (n_sp... | 5,293,190 |
def RR_calc(classes, TOP):
"""
Calculate Global performance index (RR).
:param classes: confusion matrix classes
:type classes: list
:param TOP: number of positives in predict vector per class
:type TOP: dict
:return: RR as float
"""
try:
class_number = len(classes)
... | 5,293,191 |
def divide_chunks(seq: Sequence[Any], n: int):
"""
Yield successive n-sized chunks from l.
"""
# looping till length l
for i in range(0, len(seq), n):
yield seq[i:i + n] | 5,293,192 |
def harvest_state_cadastre(limit=None):
"""Query the cadastre WFS for features. ``limit`` is optional integer of the
maximum number of features to query.
"""
GEOSERVER_URL = os.environ['GEOSERVER_URL']
params = {
'service': 'WFS',
'version': '1.1.0',
'request': 'GetFeature',
... | 5,293,193 |
def test_get_workspace_no_config(
mock_is_running_in_azure: mock.MagicMock,
tmp_path: Path) -> None:
"""
Test if the workspace config path setting is ignored if a workspace is already given, and there is no config.json
file in the current directory.
"""
mock_is_running_in_azure.retur... | 5,293,194 |
def isctime(sys, strict=False):
"""
Check to see if a system is a continuous-time system
Parameters
----------
sys : LTI system
System to be checked
strict: bool (default = False)
If strict is True, make sure that timebase is not None
"""
# Check to see if this is a con... | 5,293,195 |
def stddev(data, ddof=0):
"""Calculates the population standard deviation
by default; specify ddof=1 to compute the sample
standard deviation."""
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/(n-ddof)
return pvar**0.5 | 5,293,196 |
def getmask(a: object):
"""
usage.matplotlib: 1
"""
... | 5,293,197 |
def build_model_with_cfg(
model_cls,
variant: str,
pretrained: bool,
default_cfg: dict,
model_cfg= None,
feature_cfg= None,
pretrained_strict: bool = True,
pretrained_filter_fn = None,
pretrained_custom_load = False,
kwargs_filter = None,
... | 5,293,198 |
def process_s3():
"""Parent function for processing S3"""
s3_client = boto3.client('s3')
if block_s3 == 'true':
s3_buckets = get_s3_buckets(s3_client)
if s3_buckets:
for bucket in s3_buckets:
print(bucket['Name'])
block_s3_public_access(s3_client, ... | 5,293,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.