content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import _queue
def read_event(suppress=False):
"""
Blocks until a keyboard event happens, then returns that event.
"""
queue = _queue.Queue(maxsize=1)
hooked = hook(queue.put, suppress=suppress)
while True:
event = queue.get()
unhook(hooked)
return event | 2ec5159c6fb886a71f19c8f5a8f81f36b0fe8442 | 12,700 |
import re
import requests
from bs4 import BeautifulSoup
def searchCVE(service, version):
"""Return a list of strings"""
re.search
url = "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword="+service+"+"+version
res = requests.get(url)
soup = BeautifulSoup(res.content, "lxml")
listCVE = []
for elt in soup.find_a... | f9daf52e0c508496273c8a07b279051ebf662198 | 12,701 |
def config_from_args(args) -> config.TestConfig:
"""Convert args read from cli to config"""
return config.TestConfig(program=args.p,
test_dir=args.d,
verifier=args.v,
break_on_error=args.b == 'true',
... | 664b55566839fe6eb80ba99c3ecdb9c8fd082485 | 12,702 |
def build_json(
spec_filename: str,
package_name: str,
dist_path: str,
format_: PackageFormat = PackageFormat.NONE,
) -> None:
"""
Create an OpenAlchemy distribution package with the SQLAlchemy models.
The package can be uploaded to, for example, PyPI or a private repository for
distrib... | 714cf4c71136b50ad75bf9d46066b8c17dfee9c1 | 12,703 |
from sys import path
def get_default_plugins_folder():
"""
:returns: Default location for the plugins folder.
:rtype: str
"""
return path.join(get_install_folder(), "plugins") | 5d7e5e2b7d156bd5687543eb3f50de8cc2da13f1 | 12,704 |
def importFromDotSpec(spec):
"""
Import an object from an arbitrary dotted sequence of packages, e.g.,
"a.b.c.x" by splitting this into "a.b.c" and "x" and calling importFrom().
:param spec: (str) a specification of the form package.module.object
:return: none
:raises PygcamException: if the im... | d33eef3a086bec399ab82d2a3b28acffadc9b8dc | 12,705 |
import io
def usgs_graphite_call(*, resp, year, **_):
"""
Convert response for calling url to pandas dataframe, begin parsing
df into FBA format
:param resp: df, response from url call
:param year: year
:return: pandas dataframe of original source data
"""
df_raw_data = pd.io.excel.rea... | e2077e05096fd304f5c5f60e497f5c0b797135b8 | 12,706 |
import types
import numpy
import typing
def _gen_np_divide(arg1, arg2, out_ir, typemap):
"""generate np.divide() instead of / for array_expr to get numpy error model
like inf for division by zero (test_division_by_zero).
"""
scope = arg1.scope
loc = arg1.loc
# g_np_var = Global(numpy)
g_np... | 8caa3a26fd240b7b247ccf78ae7c4c0adcbf8b3e | 12,707 |
import math
def pseudo_volume_watson(eos, r, temp, press_eos, rho_eos, a_mix, b_mix, desired_phase):
"""
Calculates a pseudo volume based on the algorithm described by Watson (2018)
in thesis "Robust Simulation and Optimization Methods for Natural Gas Liquefaction Processes"
Available at https://dspac... | dc45d0318cf12784571c1d0a43cf63715713efd1 | 12,708 |
def layer_norm(x, axes=1, initial_bias_value=0.0, epsilon=1e-3, name="var"):
"""
Apply layer normalization to x
Args:
x: input variable.
initial_bias_value: initial value for the LN bias.
epsilon: small constant value to avoid division by zero.
scope: scope or name for the LN... | 786715f6e43e89fa2372421cf3e8c5ef11c63949 | 12,709 |
def P2D_p(df, attr):
"""
Calcul de la probabilité conditionnelle P(target | attribut).
*les parametres:
df: dataframe avec les données. Doit contenir une colonne nommée "target".
attr: attribut à utiliser, nom d'une colonne du dataframe.
*le return:
de type dictionnaire de dictionnaire, dic... | 4d76ef75f0fd821d60b0364de8e5f337fe19039e | 12,710 |
def has_entries(*keys_valuematchers, **kv_args):
"""Matches if dictionary contains entries satisfying a dictionary of keys
and corresponding value matchers.
:param matcher_dict: A dictionary mapping keys to associated value matchers,
or to expected values for
:py:func:`~hamcrest.core.core.i... | 20892046695b337483b768fa3e3cf3ae6fcf7cad | 12,711 |
def giou_loss(y_true: TensorLike,
y_pred: TensorLike,
mode: str = 'giou') -> tf.Tensor:
"""
Args:
y_true: true targets tensor. The coordinates of the each bounding
box in boxes are encoded as [y_min, x_min, y_max, x_max].
y_pred: predictions tensor. The co... | e12e51fa11cf7e89eb4cf99f0342a34d5b068a8c | 12,712 |
from typing import List
from typing import Dict
def generate_one_frame(
df_dict: dict,
tag_list: list,
fig,
up_to_index,
time_column,
batch_ids_to_animate: list,
animation_colour_assignment,
show_legend=False,
hovertemplate: str = "",
max_columns=0,
) -> List[Dict]:
"""
... | b16c41725d24f292a06e352af5a051f78492efe6 | 12,713 |
def invite_contributor_post(node, **kwargs):
"""API view for inviting an unregistered user. Performs validation, but does not actually invite the user.
Expects JSON arguments with 'fullname' (required) and email (not required).
"""
fullname = request.json.get('fullname').strip()
email = request.jso... | 67793d5dc18705a6133d5e9c29354de724ca6d47 | 12,714 |
def requires_roles(*roles):
""" """
def wrapper(f):
@wraps(f)
def wrapped(*args, **kwargs):
try:
if current_user.role.name not in roles:
abort(403)
except AttributeError:
pass
return f(*args, **kwargs)
... | b1d3f55fed3a5075a4e63a27712fc531aba84064 | 12,715 |
def home(request):
"""
Homepage, user must login to view
"""
context = {
'posts': BlogPost.objects.all().order_by('-date'), #Get all event announcement blog posts
'master': MasterControl.objects.get(identifier="MASTER") #Get the master control object
}
return render(request, 'b... | 023b788363e769c323f5625dcf08bc8953b1e802 | 12,716 |
def user_login_success(request):
""" Success login page """
return core.render(request, 'login/login-conf.html') | df58c15630e6d82232eea372b13abe12b3a75db1 | 12,717 |
def use_scope() -> Scope:
"""Get the current ASGI scope dictionary"""
return use_websocket().scope | a819b1c2dc8707cecd6298e73835e35ebb7c232c | 12,718 |
import sys
def cli(method, *kargs, **arguments):
"""Simulates testing a hug cli method from the command line"""
collect_output = arguments.pop('collect_output', True)
command_args = [method.__name__] + list(kargs)
for name, values in arguments.items():
if not isinstance(values, (tuple, list))... | 72139e74a5d61dd6a7f50f248dad190e11748774 | 12,719 |
def set_start_stop_from_input(spiketrains):
"""
Sets the start :attr:`t_start`and stop :attr:`t_stop` point
from given input.
If one nep.SpikeTrain objects is given the start :attr:`t_stop `and stop
:attr:`t_stop` of the spike train is returned.
Otherwise the aligned times are returned, which a... | 243ec7be75a11959cb3d9802536e10b7add356ee | 12,720 |
def less(data_str):
"""Pretty print JSON and pipe to less."""
p = Popen('less', stdin=PIPE)
p.stdin.write(data_str.encode())
p.stdin.close()
p.wait()
return True | 3a1af46386d80c1c0f6082c019b27d9fb55554c3 | 12,721 |
def get_extensions(f, v):
"""
Get a dictionary which maps each extension name to a bool whether it is
enabled in the file
Parameters
----------
f : an h5py.File or h5py.Group object
The object in which to find claimed extensions
v : bool
Verbose option
Returns
-... | 0d62788b01732c32b2f227a7c8d5ffe87a810d9e | 12,722 |
import argparse
def init_parser():
"""
initialize argument parser for S1 processing utilities
"""
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--transform', action='store_true', help='transform the final DEM to UTM coordinates')
parser.add_argument('-l', '--logfiles', action='... | 427eeff31ee83105afba1a9e22e8c789059efb23 | 12,723 |
async def remove_device(ws_client, device_id, config_entry_id):
"""Remove config entry from a device."""
await ws_client.send_json(
{
"id": 5,
"type": "config/device_registry/remove_config_entry",
"config_entry_id": config_entry_id,
"device_id": device_id,... | 59fc29f8fd7672ea9ea4cd1a3cf9300f4feaf539 | 12,724 |
def deco_inside_ctx_method_self(target):
"""decorator: wrap a class method inside a `with self: ...` context"""
def tgt(self, *args, **kwargs):
with self:
return target(self, *args, **kwargs)
return tgt | 6a29ad468840229c026e6abf87556018a3e16718 | 12,725 |
def c_get_mechanism_info(slot, mechanism_type):
"""Gets a mechanism's info
:param slot: The slot to query
:param mechanism_type: The type of the mechanism to get the information for
:returns: The result code, The mechanism info
"""
mech_info = CK_MECHANISM_INFO()
ret = C_GetMechanismInfo(C... | c2570874d29bdb48ee4b3146137e19133afdbff4 | 12,726 |
def make_legend(names, colors):
"""
Make a list of legend handles and colours
:param names: list of names
:param colors: list of colors
:return: list of matplotlib.patches.Patch objects for legend
"""
legend_elements = []
for idx, name in enumerate(names):
el = Patch(color=color... | 99d4ea06b70b8b4cf1a868179ca2218aa446296d | 12,727 |
def create_visitor_id(visitor_id, options):
"""Creates new VisitorId"""
if not visitor_id:
visitor_id = VisitorId()
if not options:
options = {}
device_id = options.get("device_id")
visitor = options.get("visitor")
if not visitor_id.tnt_id:
visitor_id.tnt_id = device_id... | 168c31347334a51bcc75506c22e5846dfc26ec0f | 12,728 |
def validate_crc(response: str, candidate: str) -> bool:
"""Calculates and validates the response CRC against expected"""
expected_crc = '{:04X}'.format(crc(response))
return expected_crc == candidate.replace('*', '') | 387581b4aa42d6dedfde32b374071369d9423b20 | 12,729 |
import torch
def z_gate():
"""
Pauli z
"""
return torch.tensor([[1, 0], [0, -1]]) + 0j | 9bd6276a1d60b260f3ad41b609f29e0414c0dc95 | 12,730 |
def numpy_ewma(data, window):
"""
:param data:
:param window:
:return:
"""
alpha = 1 / window
scale = 1 / (1 - alpha)
n = data.shape[0]
scale_arr = (1 - alpha) ** (-1 * np.arange(n))
weights = (1 - alpha) ** np.arange(n)
pw0 = (1 - alpha) ** (n - 1)
mult = data * pw0 * s... | e612e510ffb1b2feb726559cf6c1f3676f4aa0b8 | 12,731 |
import os
import json
def read(home_dir=os.path.expanduser('~')):
"""Read user profile from .pgdocs config"""
outfile = config_file(home_dir)
# create empty file and return empty profile with empty sessions
if not os.path.exists(outfile):
open(outfile, "w").close()
return Profile([])
... | 0f6309c0c07743ff9d9b9b0a9667b43098dc4e07 | 12,732 |
import ctypes
def tagged_sha256(tag: bytes, msg: bytes) -> bytes:
"""
Compute a tagged hash as defined in BIP-340.
This is useful for creating a message hash and achieving domain separation
through an application-specific tag. This function returns
SHA256(SHA256(tag)||SHA256(tag)||msg).
:par... | b3bea5c80f09740c63a5b896e487684a0a15f6f9 | 12,733 |
def validate_blacklist(password):
""" It does not contain the strings ab, cd, pq, or xy """
for blacklisted in ['ab', 'cd', 'pq', 'xy']:
if blacklisted in password:
return False
return True | 93ad092d5622e0567171f487522c2db824089eb9 | 12,734 |
def get_mobilenet(model, method, num_classes):
"""Returns the requested model, ready for training/pruning with the specified method.
:param model: str
:param method: full or prune
:param num_classes: int, num classes in the dataset
:return: A prunable MobileNet model
"""
ModuleInjection.pru... | f7ee264dc5db6bddc41242a9fbd90a3d6059755b | 12,735 |
import time
def f(x):
"""Squares something"""
time.sleep(10)
return x * x | 6c1ab07ebaaeca6258601ec33f181e75086a355a | 12,736 |
def get_added_after(
fetch_full_feed, initial_interval, last_fetch_time=None, filter_args=None
):
"""
Creates the added_after param, or extracts it from the filter_args
:param fetch_full_feed: when set to true, will limit added_after
:param initial_interval: initial_interval if no
:param last_fe... | 281cb7d7429071bf8dca0d04eedee9130a29b28d | 12,737 |
def gdf_lineStrings():
"""Construct a gdf that contains two LineStrings."""
ls_short = LineString([(13.476808430, 48.573711823), (13.506804, 48.939008), (13.4664690, 48.5706414)])
ls_long = LineString([(13.476808430, 48.573711823), (11.5675446, 48.1485459), (8.5067847, 47.4084269)])
a_list = [(0, ls_sh... | d14318ed1765b20151e28718938d611d6359bfd5 | 12,738 |
import math
import os
import torch
def createFormattedDir(source, dirname, batchSize = 128, cleanDir=False, verbose=True):
"""Given a source that supports __len__ and __getitem__,
and a directory that's empty, create a formatted directory that's
then used by BatchDataset. This only needs to be run once, so it's... | 9a8615ec02a8cb6316a98f889f74a8c440041854 | 12,739 |
from typing import Callable
from typing import Coroutine
from typing import Any
from typing import Optional
from typing import Dict
import functools
import anyio
def runnify(
async_function: Callable[T_ParamSpec, Coroutine[Any, Any, T_Retval]],
backend: str = "asyncio",
backend_options: Optional[Dict[str,... | 64f8e826dce8d35b5b7307289346eb5bfdb1bbee | 12,740 |
import os
import msvcrt
import sys
def _binary_stdio():
"""Construct binary stdio streams (not text mode).
This seems to be different for Window/Unix Python2/3, so going by:
https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin
NOTE: this method is borrowed from python-langua... | 7a8d6155d0142e92267175f8e6b1a8b5ca6182fd | 12,741 |
from typing import Dict
from typing import Any
from typing import Iterable
def _get_properties(rsp: Dict[Text, Any]) -> Iterable[CdProperty]:
""" Retrieve key properties to be passed onto dynatrace server. """
return [
CdProperty("Status", rsp.get("status", "N/A")),
CdProperty("Entry point", r... | e409ae450ca948f63d4588714cc09f17efe8525a | 12,742 |
def photo_fit_bprior(time, ptime, nflux, flux_err, guess_transit, guess_ew, rho_star, e, w, directory, nwalk, nsteps, ndiscard, plot_transit=True, plot_burnin=True, plot_corner=True, plot_Tburnin=True, plot_Tcorner=True):
"""Fit eccentricity for a planet.
Applies Bayesian beta-dist prior from Kipping 2014
... | 1ede4401a1f0b486cfa30bfc31fe5696e0fa4551 | 12,743 |
def runSwitchVerifier(node_address):
"""Wrap the SwitchVerifier binary.
Configuration parameters of the switchVerifier binary are retrieved
from the driverHPESettings class.
"""
logger.debug("Running switchVerifier binary")
# Run switchVerifier -c config.json -k pub.key -conf refconf -json [ip... | 015d025630c020a0ba1bdd4aec32e2a14cbbcf87 | 12,744 |
def unary_op(op, suty):
"""/Users/mahmoud/src/py-in-java/pycryptodome/lib/transform.py
/Users/mahmoud/src/py2star/transform1.py
Converts a method like: ``self.failUnless(True)`` to
asserts.assert_that(value).is_true()
"""
sut = _codegen.code_for_node(suty.value)
return cst.parse_expression... | 211329aa099bdf551279f56d12df7ef602fdd537 | 12,745 |
def canny_edges(image, minedges=5000, maxedges=15000, low_thresh=50, minEdgeRadius=20, maxEdgeRadius=None):
"""
Compute Canny edge detection on an image
"""
t0 = time.time()
dx = ndimage.sobel(image,0)
dy = ndimage.sobel(image,1)
mag = numpy.hypot(dx, dy)
mag = mag / mag.max()
ort = numpy.arctan2(dy, dx)
e... | 06984375fa2bebf362136c00870b88d0753ed25c | 12,746 |
def scale_matrix(t):
"""
Given a d-dim vector t, returns (d+1)x(d+1) matrix M such that
left multiplication by M on a homogenuous (d+1)-dim vector v
scales v by t (assuming the last coordinate of v is 1).
"""
t = asarray(t).ravel()
d = len(t)
m = identity(d+1)
for i in xrange(d):
... | 6688ac945b0da7228edf3e54e1310655434e8c93 | 12,747 |
def validate_rule_paths(sched: schedule.Schedule) -> schedule.Schedule:
"""A validator to be run after schedule creation to ensure
each path contains at least one rule with a temperature expression.
A ValueError is raised when this check fails."""
for path in sched.unfold():
if path.is_final an... | 99cbb35083f6bcd10b58fe320379d074f3a6fa3f | 12,748 |
def check_input_array(xarr,shape=None,chunks=None,\
grid_location=None,ndims=None):
"""Return true if arr is a dataarray with expected shape, chunks at
grid_location attribute. Raise an error if one of the tests fails.
Parameters
----------
xarr : xarray.DataArray
xarra... | acc589dcd757c34362ed46e4944f9cee58e08e47 | 12,749 |
def ancestor_width(circ, supp, verbose=False):
"""
Args:
circ(list(list(tuple))): Circuit
supp(list): List of integers
Returns:
int: Width of the past causal cone of supp
"""
circ_rev= circ[::-1]
supp_coded = 0
for s in supp:
supp_coded |= (1<<s)
for uni... | 6284b80bc2aefa22cf96198e3f27f885d7074273 | 12,750 |
import multiprocessing
import psutil
import os
import csv
def find_genes(
interactions,
fragment_database_fp,
gene_bed_fp,
gene_dict_fp,
output_dir,
suppress_intermediate_files=False):
"""Identifies genes in fragments that interact with SNP fragments.
Args:
... | cbbace27105c15178457ef45fdd8cfcab60f88e7 | 12,751 |
def get_bprop_argmax(self):
"""Generate bprop for Argmax"""
def bprop(x, out, dout):
return (zeros_like(x),)
return bprop | a92f3fc1fd31428d4097ec9a185475343432e7f4 | 12,752 |
import logging
from datetime import datetime
def register_extensions(app):
"""Register models."""
db.init_app(app)
login_manager.init_app(app)
# flask-admin configs
admin.init_app(app)
admin.add_view(ModelView(User))
admin.add_view(ModelView(Role))
login_manager.login_view = 'auth.lo... | 342d396cc40292d5a1412b8acd5f218bd3451b8a | 12,753 |
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['cache'] = 86400
desc['description'] = """This plot presents a histogram of the change
in some observed variable over a given number of hours."""
desc['arguments'] = [
dict(type='zstation'... | 08a4fad8df13f89e5764f36ec7c2e6b7e3697cbe | 12,754 |
import os
from pathlib import Path
def extract_content(basepath, exclude=None):
"""
Get all non-comment lines from BUILD files under the given basepath.
:param Path basepath: The path to recursively crawl
:param list exclude: The paths to exclude
:rtype: str
"""
if basepath.is_file():
... | 21a2e7cb560d213b27b583de6d6c5be88413e51c | 12,755 |
def read_format_from_metadata(text, ext):
"""Return the format of the file, when that information is available from the metadata"""
metadata = read_metadata(text, ext)
rearrange_jupytext_metadata(metadata)
return format_name_for_ext(metadata, ext, explicit_default=False) | 6b57dbbc7cf9763d1623aa37a57911eb82e7e24c | 12,756 |
def request_requires_retry(err: Exception) -> bool:
"""Does the error mean that a retry should be performed?"""
if not isinstance(err, ClientError):
return False
code = err.response.get('Error', {}).get('Code', '').lower()
message = err.response.get('Error', {}).get('Message', '')
# This cov... | 3b3805820d3d009e6a52482b90afeacb3db5233b | 12,757 |
def to_jd(y, m, d, method=None):
"""Convert Armenian date to Julian day count. Use the method of Sarkawag if requested."""
# Sanity check values
legal_date(y, m, d, method)
yeardays = (m - 1) * 30 + d
if method == "sarkawag":
# Calculate things
yeardelta = y - 533
leapdays = ... | f39cfa83a02bac9273fc92fb7b1a2725cb5ff8cc | 12,758 |
def unitVector(vector):
"""
Returns the unit vector of a given input vector.
Params:
vector -> input vector.
Returns:
numpy.array().
"""
# Divide the input vector by its magnitude.
return vector / np.linalg.norm(vector) | 840d184febbc1ebbb753278705649d649be900d6 | 12,759 |
def find_poly_intervals(p):
"""
Find the intervals of 1D-polynomial (numpy.polynomial) where the polynomial is negative.
"""
assert(np.abs(p.coef[-1]) > 1e-14)
r=p.roots()
# remove imaginary roots, multiple roots, and sort
r=np.unique(np.extract(np.abs(r.imag)<1e-14, r).real)
ints = []
... | a3c9d7622b1ab142b92da61a75febf6c46151a81 | 12,760 |
def user_numforms_next(*args):
"""
user_numforms_next(p) -> user_numforms_iterator_t
Move to the next element.
@param p (C++: user_numforms_iterator_t)
"""
return _ida_hexrays.user_numforms_next(*args) | 85bd741496befa0fc57e8d20325fa1a7b1b89c0b | 12,761 |
from typing import Dict
import logging
def list_cms() -> Dict[Text, CalculationModule]:
"""List all cms available on a celery queue."""
app = get_celery_app()
try:
app_inspector = app.control.inspect()
nodes = app_inspector.registered("cm_info")
except (redis.exceptions.ConnectionError... | a6ce2cc5392d6b793c52cb32a8abff2967eebb18 | 12,762 |
def _a_in_b(first, second):
"""Check if interval a is inside interval b."""
return first.start >= second.start and first.stop <= second.stop | e4ca21e1861b691510252eb3be53eed16c8bc8cf | 12,763 |
import time
import torch
def validate(val_loader, c_model, r_model, c_criterion, r_criterion):
"""
One epoch's validation.
: param val_loader: DataLoader for validation data
: param model: model
: param criterion: MultiBox loss
: return: average validation loss
"""
c_model.eval() # ev... | af90f709c73364865b5c3610b0b5058f699203fb | 12,764 |
def radixsort(list, k=10, d=0):
""" Sort the list.
This method has been used to sort punched cards.
@param k: number different characters in a number (base)
@param d: maximum number of digits of list elements
"""
if len(list) == 0:
return []
elif d == 0:
d = max... | a437032df03a5a3c97f976a9b0d5804175b7c9c6 | 12,765 |
def create_datacatalog(glue_client):
"""
used to create a data catalog
"""
# TODO:
# check if this is needed
# and to be improved accordingly
response = glue_client.create_data_catalog(
Name="string",
Type="LAMBDA" | "GLUE" | "HIVE",
Description="Test catalog",
... | 010ce96c8e878b8691bef89c349966e6817cc55f | 12,766 |
def feature_stat_str(x, y, delimiter='~', n_lines=40, width=20):
"""Compute the input feature's sample distribution in string format for printing.
The distribution table returned (in string format) concains the sample sizes,
event sizes and event proportions of each feature value.
Parameters
-----... | 947886e5cb8210cda4fcdc6c91d29d7a569939be | 12,767 |
import torch
def dice_similarity_u(output, target):
"""Computes the Dice similarity"""
#batch_size = target.size(0)
total_dice = 0
output = output.clone()
target = target.clone()
# print('target:',target.sum())
for i in range(1, output.shape[1]):
target_i = torch.zeros(target.shape... | ce21637f33306adb13aea10e04f40bdac9d5d441 | 12,768 |
import os
import pickle
def establish_service():
"""
Authorizes and establishes the Gmail service using the API.
:return: authorized Gmail service instance
"""
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
creds = None
... | 595ec1a5b7eddc0cfdebba94299b609fbc292c0a | 12,769 |
import time
import json
def get_meaning(searchterm):
"""
Fetches the meaning of the word specified
:param searchterm: the word for which you want to fetch the meaning
:return: json object of the meaning
"""
# finds the input field by id in the webpage
sbox = driver.find_element_by_... | 6a0608d59598a8f75fb30d17b172e48bef548031 | 12,770 |
def get_state(entity_id):
"""
Return the state of an entity
"""
try:
entity_state = ''
entity_state = Gb.hass.states.get(entity_id).state
if entity_state in IOS_TRIGGER_ABBREVIATIONS:
state = IOS_TRIGGER_ABBREVIATIONS[entity_state]
else:
state = G... | 4f5e3e09b2a263fd4176d11e2ae23964fa8b804e | 12,771 |
def loss_eval(net, data, labels, numclass=2, rs=40):
"""Evaluate the network performance on test samples"""
loss = np.zeros([labels.shape[0]])
for i in range(len(loss)):
label_input = condition_reshape(
label=labels[i,np.newaxis], numclass=numclass, imgshape=(rs, rs))
img_est = n... | 69df9b25c56439e7fd7472e7ec7318db6a0bd51b | 12,772 |
def wide_resnet101(input_shape, num_classes, dense_classifier=False, pretrained=False):
""" return a ResNet 101 object
"""
return _resnet('resnet101', BottleNeck, [3, 4, 23, 3], 64 * 2, num_classes, dense_classifier, pretrained) | e1a2e42ee432bd44d43b4091fcda60ce73e4f2d3 | 12,773 |
def is_empty(ir: irast.Base) -> bool:
"""Return True if the given *ir* expression is an empty set
or an empty array.
"""
return (
isinstance(ir, irast.EmptySet) or
(isinstance(ir, irast.Array) and not ir.elements) or
(
isinstance(ir, irast.Set)
and ir.e... | b70d58149d0818dc09b7c5e2a2bf13001580b11e | 12,774 |
from scipy.io import loadmat
def read_official_corner_lut(filename, y_grid='lat_grid', x_grid='lon_grid',
x_corners = ['nwlon', 'swlon', 'selon', 'nelon'],
y_corners = ['nwlat', 'swlat', 'selat', 'nelat']):
"""
Read a MATLAB file containing corner point lookup data.
Returns lons, lat... | 755455a3f2bfb1bedff634776367bf0a825ff36b | 12,775 |
import re
def get_component_name(job_type):
"""Gets component name for a job type."""
job = data_types.Job.query(data_types.Job.name == job_type).get()
if not job:
return ''
match = re.match(r'.*BUCKET_PATH[^\r\n]*-([a-zA-Z0-9]+)-component',
job.get_environment_string(), re.DOTALL)
i... | e0cc2db3b81c7bc729c87165dadc7da88156e21c | 12,776 |
def group_by(source: ObservableBase, key_mapper, element_mapper=None) -> ObservableBase:
"""Groups the elements of an observable sequence according to a
specified key mapper function and comparer and selects the resulting
elements by using a specified function.
1 - observable.group_by(lambda x: x.id)
... | 12c32c22a1077fa171135aabeb0dd7d8e759a0a3 | 12,777 |
import scipy
def gauss_pdf(x, norm, mu, sigma):
"""
The method calculates the value of the Gaussian probability
density function (using matplotlib routines) for a value/array x.
for a given mean (mu) and standard deviation (sigma). The results
is normalized (multiplied by) 'norm', and so 'norm' sh... | 076b6a5141e1262e826b7a62b280023f2166bae6 | 12,778 |
def max_dbfs(sample_data: np.ndarray):
"""Peak dBFS based on the maximum energy sample.
Args:
sample_data ([np.ndarray]): float array, [-1, 1].
Returns:
float: dBFS
"""
# Peak dBFS based on the maximum energy sample. Will prevent overdrive if used for normalization.
return rms_... | e88fd81b0bff2b1e08f611587ed8f4e7276e2d3e | 12,779 |
from scipy.ndimage.filters import gaussian_filter1d
def get_deltaF_v2(specfile, res, spec_res, addpix=int(10), CNR=None, CE=None, MF_corr=True, domask=True):
"""Get the optical depth and return the realistic mock spectra
specfile : Address to the spectra. It should be in the foramt as the fale_spectra output... | b3520eaccb209107bffd119d8fea4421e1c9411b | 12,780 |
def quick_amplitude(x, y, x_err, y_err):
"""
Assume y = ax
Calculate the amplitude only.
"""
#x[x<0] = 1E-5
#y[y<0] = 1E-5
xy = x*y
xx = x*x
xy[xy<0] = 1E-10
A = np.ones(x.shape[0])
for i in np.arange(5):
weight = 1./(np.square(y_err)+np.square(A).reshape(A.size,1)*n... | 2331bc4ce9f258d9c0972de56abb2becd9d979e1 | 12,781 |
def get_password(config, name):
"""Read password"""
passfile = config.passstore / name
with open(passfile, 'r') as fd:
return fd.read() | caae733030077eedc4428555eb0b106cfe586e50 | 12,782 |
def attribute_string(s):
"""return a python code string for a string variable"""
if s is None:
return "\"\""
# escape any ' characters
#s = s.replace("'", "\\'")
return "\"%s\"" % s | 9ed9d4f26e797119a339d2a3827772b945e29839 | 12,783 |
def inflate_cell(cell, distance):
"""
Expand the current cell in all directions and return the set.
"""
newset = set(cell)
if distance==0:
return(newset)
# recursively call this based on the distance
for offset in direction.all_offsets():
# FIXME: If distance is large t... | 1b1e5ca4e1b3287e72d662b702fe69e6bb67a726 | 12,784 |
import os
def read_dfcpp_test_results(d4cpp_output_dir):
"""
Returns test results
"""
test_results = {}
for dir_name in os.listdir(d4cpp_output_dir):
path_to_dir = os.path.join(d4cpp_output_dir, dir_name)
if not os.path.isdir(path_to_dir):
continue
case = dir_na... | d99f749dbf20179bc317a026d0e0112aea17ae12 | 12,785 |
import json
def poi(request, id=None):
"""
*/entry/pois/<id>*, */entry/pois/new*
The entry interface's edit/add/delete poi view. This view creates
the edit page for a given poi, or the "new poi" page if it
is not passed an ID. It also accepts POST requests to create or edit
pois.
If call... | cce95c37bfee855adab817f50d50d53324f00ae1 | 12,786 |
def relativeScope(fromScope, destScope):
"""relativeScope variant that handles invented fromScopes"""
rs = idlutil.relativeScope(fromScope, destScope)
if rs[0] is None:
try:
rd = idlast.findDecl(destScope)
except idlast.DeclNotFound:
return rs
new_rs = rs
... | f2cdfa67bcedbbe4bcb9f2fb1b89a167df66ae13 | 12,787 |
def srbt(peer, pkts, inter=0.1, *args, **kargs):
"""send and receive using a bluetooth socket"""
s = conf.BTsocket(peer=peer)
a,b = sndrcv(s,pkts,inter=inter,*args,**kargs)
s.close()
return a,b | 77b087b31a6fc23b7b0122ebe827d7b868fc66a8 | 12,788 |
def rotation_matrix_from_vectors(vector1, vector2):
"""
Finds a rotation matrix that can rotate vector1 to align with vector 2
Args:
vector1: np.narray (3)
Vector we would apply the rotation to
vector2: np.narray (3)
Vector that will ... | a36c9b2a77bc3be91538e7768fd1688465d7cd4f | 12,789 |
from typing import Union
def read_LUT_SonySPI1D(path: str) -> Union[LUT1D, LUT3x1D]:
"""
Read given *Sony* *.spi1d* *LUT* file.
Parameters
----------
path
*LUT* path.
Returns
-------
:class:`colour.LUT1D` or :class:`colour.LUT3x1D`
:class:`LUT1D` or :class:`LUT3x1D` c... | d09ad11a0b21ebd1aa7132911b3b5dc9f67d4607 | 12,790 |
def jaxpr_replicas(jaxpr) -> int:
"""The number of replicas needed for a jaxpr.
For a eqn, multiply the `axis_size` with the `jaxpr_replicas` of the
subjaxprs. For a list of eqns, take the maximum number of replicas.
"""
if isinstance(jaxpr, core.ClosedJaxpr):
jaxpr = jaxpr.jaxpr
return max(unsafe_map(... | e4664a06ef778976fa31ce40906dbb561c2812cd | 12,791 |
import torch
def tokens2ELMOids(tokens, sent_length):
"""
Transform input tokens to elmo ids.
:param tokens: a list of words.
:param sent_length: padded sent length.
:return: numpy array of elmo ids, sent_length * 50
"""
elmo_ids = batch_to_ids([tokens]).squeeze(0)
pad_c = (0, 0, 0, se... | 8343a05ec250f0d2ea607fb1db27ee11c42d1975 | 12,792 |
import warnings
def get_section_endpoints(section_name):
"""Get the [lon, lat] endpoints associated with a pre-defined section
e.g.
>> pt1, pt2 = get_section_endpoints('Drake Passage')
pt1 = [-68, -54]
pt2 = [-63, -66]
These sections mirror the gcmfaces definitions, see
gcmf... | 505e098c9e0a7b7612ab08299e8009525a2125ed | 12,793 |
from datetime import datetime
def get_vm_metrics(monitor_client, resource_id):
"""Get metrics for the given vm. Returns row of cpu, disk, network activity"""
today = datetime.utcnow().date()
last_week = today - timedelta(days=7)
metrics_data = monitor_client.metrics.list(
resource_id,
... | a9cca3cf8f823bdff58a9b3b8bae5e12e79b2cdc | 12,794 |
import os
def geo_api():
"""
GeoAPI fixture data.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
return GeoApi(os.getenv("TEST_AIRBUS_API_KEY")) | 83a5ae60ede9fd0349d97d9675c21f4caab4ca10 | 12,795 |
import time
def current_time_id():
""" Returns the current time ID in milliseconds """
return int(round(time.time() * 1000)) | c59c02151b7575804039f64292f0aed5ca4ebc44 | 12,796 |
import sqlite3
def get_db():
"""
Connects to the database.
Returns a database object that can be queried.
"""
if 'db' not in g:
g.db = sqlite3.connect(
'chemprop.sqlite3',
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
ret... | 87267da29d562d5b66e528f0a5d58031bf666c65 | 12,797 |
def computePatientConfusionMatrix(patient_prediction_location, patient_ground_truth_location, labels_names_file):
"""
@brief: Compute the patient confusion matrix given the location of its prediction and ground truth.
@param patient_prediction_location : folder containing the prediction data
@param pa... | 6aa97a98eddddd7ff79d8ddf099d81673ca2fd61 | 12,798 |
async def ping_server():
"""
Ping Server
===========
Returns the message "The Optuna-server is alive!" if the server is running.
Parameters
----------
None
Returns
-------
msg : str
A message witnessing that the server is running.
"""
msg = 'The Optuna-server is alive!'
return msg | 2098f2167a14f08105824490824d62dd34b4c49e | 12,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.