content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def RandomImageDetection(rows=None, cols=None):
"""Return a uniform random color `vipy.image.ImageDetection` of size (rows, cols) with a random bounding box"""
rows = np.random.randint(128, 1024) if rows is None else rows
cols = np.random.randint(128, 1024) if cols is None else cols
return ImageDetectio... | 41,000 |
def upsample(x, stride, target_len, separate_cls=True, truncate_seq=False):
"""
Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
"""
if stride == 1:
return x
if separate_cls:
cls = x[:, :1]
x = x[:, 1:]
outp... | 41,001 |
def torsional_scan_linspaces(zma, tors_names, increment=0.5,
frm_bnd_key=None, brk_bnd_key=None):
""" scan grids for torsional dihedrals
"""
sym_nums = torsional_symmetry_numbers(
zma, tors_names, frm_bnd_key=frm_bnd_key, brk_bnd_key=brk_bnd_key)
intervals = tuple(2*... | 41,002 |
def test_equal():
"""Test for equality"""
assert Q.positive(x) == Q.positive(x)
assert Q.positive(x) != ~Q.positive(x)
assert ~Q.positive(x) == ~Q.positive(x) | 41,003 |
def get_output_to_console(p_state):
"""Returns a bool indicating whether the Log is output to the console."""
return bool(_Get_Output_To_Console(ctypes.c_void_p(p_state))) | 41,004 |
async def calling_all_units(message: types.Message, config: Config, lang: Lang, bot: Bot):
"""
Handle messages starting with "@admin". No additional checks are done, so
"@admin", "@admin!!!", "@administrator" and other are valid
:param message: Telegram message with /report command
:param config: c... | 41,005 |
def check_valid_column(observation):
"""
Validates that our observation only has valid columns
Returns:
- assertion value: True if all provided columns are valid, False otherwise
- error message: empty if all provided columns are valid, False otherwise
"""
valid... | 41,006 |
def _params_to_filename(job_id, run_id, extra_run_id):
"""
Prepare file name based on params.
Args:
job_id (str): Job Uid
run_id (str): Job Run Uid
extra_run_id (str): Extra Job Uid
Returns:
str: filenames
"""
with current_app.app_context():
_logs_store... | 41,007 |
def load_starting_page(config_data):
"""
Load starting page into the CMS
:param config_data: configuration data
"""
with chdir(os.path.abspath(config_data.project_directory)):
env = deepcopy(dict(os.environ))
env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data... | 41,008 |
def test_rescale_nowf(generate_structure):
"""Test to rescale some structure """
from aiida_fleur.tools.StructureData_util import rescale_nowf
from aiida_fleur.tools.StructureData_util import rescale
from aiida.orm import Dict, Float
structure = generate_structure()
old_cell = np.array(structur... | 41,009 |
def w_getopt(args, options):
"""A getopt for Windows.
Options may start with either '-' or '/', the option names may
have more than one letter (/tlb or -RegServer), and option names
are case insensitive.
Returns two elements, just as getopt.getopt. The first is a list
of (option, valu... | 41,010 |
def remove_files(ll, d, debug_level):
"""
Returns a list of all the lines in the file
:param ll: list of all files
:param d: directory
:param debug_level: debug level
:return: a list of all the lines in the file
"""
for l in ll:
bash_command = "rm -f " + d + l
if debug_le... | 41,011 |
def insert_new_img(data_dir):
"""
Insert new images into point cloud using image matching.
New images must be saved in <data_dir>/images, along with the original images used to create an existing
reconstruction with openSFM
:param data_dir: directory of data
:return: None; updates reconstructio... | 41,012 |
def swc(name, srcs = None, args = [], data = [], output_dir = False, swcrc = None, source_maps = False, out_dir = None, **kwargs):
"""Execute the swc compiler
Args:
name: A name for the target
srcs: source files, typically .ts files in the source tree
data: runtime dependencies to be pr... | 41,013 |
def cards_to_textfile(cards, outfile):
"""Take an iterable of cards, and turn them into a text file that Anki can read."""
for card in cards:
outfile.write(card.to_character_separated_line()) | 41,014 |
def get_alt_for_density(density: float, density_units: str='slug/ft^3',
alt_units: str='ft', nmax: int=20, tol: float=5.) -> float:
"""
Gets the altitude associated with a given air density.
Parameters
----------
density : float
the air density in slug/ft^3
densi... | 41,015 |
def parse_date_string(date: str) -> datetime:
"""Converts date as string (e.g. "2004-05-25T02:19:28Z") to UNIX timestamp (uses UTC, always)
"""
# https://docs.python.org/3.6/library/datetime.html#strftime-strptime-behavior
# http://strftime.org/
parsed = datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ')... | 41,016 |
def levenshtein_distance(s, t, ratio_calc = False):
""" levenshtein_distance:
Calculates levenshtein distance between two strings.
If ratio_calc = True, the function computes the
levenshtein distance ratio of similarity between two strings
For all i and j, distance[i,j] will con... | 41,017 |
def jupyter_supervisor_conf(
path=JUPYTER_SERVICE_SETTINGS['default_conf_file'],
command=JUPYTER_SERVICE_SETTINGS['command'],
args=JUPYTER_SERVICE_SETTINGS['args'],
log_dir=SERVICES_DIR,
autostart=JUPYTER_SERVICE_SETTINGS['autostart'],
):
"""Generates Supervisor config for Ju... | 41,018 |
def no_warnings(func):
""" Decorator to run R functions without warning. """
def run_withoutwarnings(*args, **kwargs):
warn_i = _options().do_slot('names').index('warn')
oldwarn = _options()[warn_i][0]
_options(warn=-1)
try:
res = func(*args, **kwargs)
except ... | 41,019 |
def _dump(df, fmt='presto', idx='never'):
"""Dumps df to terminal"""
print('\n', tabulate(df, headers='keys', tablefmt=fmt, showindex=idx)) | 41,020 |
def test_returns_None_in_bucket_if_key_is_not_preset():
"""Successfull returns appended None to bucket if both keys are not present"""
h1 = HashMap(1)
h2 = HashMap(1)
h1.add('wrath', 'anger')
h2.add('flow', 'jam')
expected = [[['wrath', 'anger', None]]]
actual = left_join(h1, h2)
assert ... | 41,021 |
def ParseKindsAndSizes(kinds):
"""Parses kind|size list and returns template parameters.
Args:
kinds: list of kinds to process.
Returns:
sizes_known: whether or not all kind objects have known sizes.
size_total: total size of objects with known sizes.
len(kinds) - 2: for template rendering of gr... | 41,022 |
def load_3D(path,
n_sampling=10000,
voxelize=True,
voxel_mode="binary",
target_size=(30, 30, 30)):
"""Load 3D data into numpy array, optionally voxelizing it.
Parameters
----------
path : srt
Path to 3D file.
n_sampling : int
Number o... | 41,023 |
def test_list_unsigned_int_max_length_nistxml_sv_iv_list_unsigned_int_max_length_1_1(mode, save_output, output_format):
"""
Type list/unsignedInt is restricted by facet maxLength with value 5.
"""
assert_bindings(
schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsignedIn... | 41,024 |
def create_vector2d(vec):
"""Returns a vector as a numpy array."""
return array([vec[0],vec[1]]) | 41,025 |
def make_pdirs(fn):
"""Like mkdir -p `dirname fn`"""
import os.path
dn = os.path.dirname(fn)
if not os.path.exists(dn): os.makedirs(dn) | 41,026 |
def get_chrom_start_end_from_string(s):
"""Get chrom name, int(start), int(end) from a string '{chrom}__substr__{start}_{end}'
...doctest:
>>> get_chrom_start_end_from_string('chr01__substr__11838_13838')
('chr01', 11838, 13838)
"""
try:
chrom, s_e = s.split('__substr__')
start, ... | 41,027 |
def test_org_parser():
"""Test the OrgParser parser."""
p = OrgParser()
# this parser is not fully implemented yet
with pytest.raises(NotImplementedError):
p.parse("content") | 41,028 |
def Remove_Invalid_Tokens(tokenized_sentence, invalidating_symbols):
"""
Returns a tokenized sentence without tokens that include
invalidating_symbols
"""
valid_tokens_sentence = [] + tokenized_sentence # forcing a copy, avoid pass by reference
for token in tokenized_sentence:
for invalid_symbol in invalidat... | 41,029 |
def _get_protocol(url):
"""
Get the port of a url.
Default port is 80. A specified port
will come after the first ':' and before the next '/'
"""
if url.find('http://') == 0:
return 'http'
elif url.find('https://') == 0:
return 'https'
else:
return 'h... | 41,030 |
def convert_spectral_axis(mywcs, outunit, out_ctype, rest_value=None):
"""
Convert a spectral axis from its unit to a specified out unit with a given output
ctype
Only VACUUM units are supported (not air)
Process:
1. Convert the input unit to its equivalent linear unit
2. Convert t... | 41,031 |
def row_to_str(row):
"""Convert a df row to a string for insert into SQL database."""
return str(list(row)).replace("[", "(").replace("]", ")") | 41,032 |
def interpolate_affines(affines):
"""
"""
# get block grid
block_grid = affines.shape[:3]
# construct an all identities matrix for comparison
all_identities = np.empty_like(affines)
for i in range(np.prod(block_grid)):
idx = np.unravel_index(i, block_grid)
all_identities[id... | 41,033 |
def notify(subject, message, to="herbemalveillante@gmail.com"):
"""
Permet d'envoyer un mail à mon adresse pro pour me notifier de quelque chose d'important.
"""
msg = EmailMessage()
msg.set_content(message)
msg["subject"] = subject
user = "alerts.herbemalveillante@gmail.com"
msg["from"... | 41,034 |
def getLineMeasures(file_list, orders, names, err_cut=0):
"""
Find line center (in pixels) to match order/mode lines
"""
# Load in x values to match order/mode lines
x_values = np.empty((len(file_list),len(orders)))
x_values[:] = np.nan # want default empty to be nan
x_errors = np.empty((len... | 41,035 |
def is_slackware():
"""
Checks if we are running on a Slackware system.
:returns: **bool** to indicate if we're on a Slackware system
"""
return os.path.exists('/etc/slackware-version') | 41,036 |
def save_data(url, file):
"""Save a dict into a file"""
with open(file, 'w') as f:
json.dump(get_json_data(url), f) | 41,037 |
def create_dropout_masks(route, fname, dimensionality, ks=1000):
"""
route = path where to create a file
fname = filename
ks = thousand of masks to create (1e6 masks by default)
"""
hdf5_backend = Backends.HDF5(route, fname)
# set_trace()
for i in xrange(ks):
mask = random.random... | 41,038 |
def signature_exempt(view_func):
"""Mark a view function as being exempt from signature and apikey check."""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.signature_exempt = True
return wraps(view_func)(wrapped_view) | 41,039 |
def main():
""" Main function. """
args = arg_parser().parse_args()
config = load_config(args.config)
freeze(args, config) | 41,040 |
def setup(args):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
add_tridentnet_config(cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
# if args.eval_only:
# cfg.MODEL.WEIGHTS = "/root/detectron2/projects/TridentNet/log_80_20/model_0... | 41,041 |
def emscript_fastcomp(infile, outfile, memfile, libraries, compiler_engine,
temp_files, DEBUG):
"""Runs the emscripten LLVM-to-JS compiler.
Args:
infile: The path to the input LLVM assembly file.
outfile: An open file object where the output is written.
"""
assert shared.Settings... | 41,042 |
def get_intersections(line, potential_lines, nodes, precision):
"""
Get the intersection points between the lines defined by two planes
and the lines defined by the cost area (x=0, y=0, y=-x+1)
and the lines defined by the possible combinations of predictors
"""
slope, intercept = line
# In... | 41,043 |
def subtract_loss_from_gain(gain_load, loss_load):
"""Create a single DataCollection from gains and losses."""
total_loads = []
for gain, loss in zip(gain_load, loss_load):
total_load = gain - loss
total_load.header.metadata['type'] = \
total_load.header.metadata['type'].replace(... | 41,044 |
def zero_out_noisy_epochs(psg, sample_rate, period_length_sec,
max_times_global_iqr=20):
"""
Sets all values in a epoch of 'period_length_sec' seconds of signal to zero
(channel-wise) if any (absolute) value within that period exceeds
'max_times_global_iqr' times the IQR of all... | 41,045 |
def reduce_language_model(language_model_path, out_language_model_path):
"""
TODO DOCUMENTATION
:param language_model_path:
:param out_language_model_path:
:return:
"""
command = 'sphinx_lm_convert'
script = [command,
'-i', language_model_path,
'-o', out_lang... | 41,046 |
def start_training(channel: Channel) -> Tuple[List[ndarray], int, int]:
"""Start a training initiation exchange with a coordinator.
The decoded contents of the response from the coordinator are returned.
Args:
channel (~grpc.Channel): A gRPC channel to the coordinator.
Returns:
~typin... | 41,047 |
def has_forbidden(mylist) -> bool:
""" Does the string contain one of the forbidden substrings "ab" "cd" "pq"
"xy"? """
return bool(re.search(FORBIDDEN, mylist)) | 41,048 |
def classFactory(iface): # pylint: disable=invalid-name
"""Load PagLuxembourg class from file PagLuxembourg.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
from main import PAGLuxembourg
return PAGLuxembourg(iface) | 41,049 |
def is_official_target(target_name, version):
""" Returns True, None if a target is part of the official release for the
given version. Return False, 'reason' if a target is not part of the
official release for the given version.
target_name: Name if the target (ex. 'K64F')
version: The release ver... | 41,050 |
def test_ibd_1():
"""
Test with custom distortion.
"""
ibd = InformationBottleneckDivergence(dist, beta=0.0, divergence=relative_entropy)
ibd.optimize()
pmf = ibd.construct_joint(ibd._optima)
assert float(ibd.complexity(pmf)) == pytest.approx(0.0, abs=1e-4)
assert float(ibd.relevance(pmf... | 41,051 |
def _convert_to_dict_or_str(elements_map: Dict[str, Element]) -> Dict[str, Union[str, Dict[Any, Any]]]:
"""Combines a dictionary of xml elements into a dictionary of dicts or str"""
return {
key: XmlDictElement(value) if value or value.items() else value.text
for key, value in elements_map.items... | 41,052 |
def vsi_tecaji():
"""
Funkcija vrne vse tečaje PGD Hrušica.
"""
poizvedba = """
SELECT id, naziv
FROM tecaji
"""
tecaji = conn.execute(poizvedba).fetchall()
return tecaji | 41,053 |
def cosine(u, v, dim=-1):
"""cosine similarity"""
return (u * v).sum(dim=dim) / (u.norm(dim=dim, p=2) * v.norm(dim=dim, p=2)) | 41,054 |
def retrive_cache_data(format: str, query: str) -> dict[int, Book]:
"""
Retrive the cached data for the query.
"""
date_now = datetime.now()
# save the search results in the cache if not already there or if the cache is expired
if format not in book_cache:
book_cache[format] = {}
if... | 41,055 |
def get_orders_loadings_palette_number(client_orders, value):
"""
Searches OrdersLoadingPlaces objects linked with client orders and that contain value
:param client_orders: orders of profile
:param value: value of palettes number for which OrdersLoadingPlaces objects are searching
:return: List wit... | 41,056 |
def rotmat(x=0,y=0,z=0):
"""Rotation Matrix function
This function creates and returns a rotation matrix.
Parameters
----------
x,y,z : float, optional
Angle, which will be converted to radians, in
each respective axis to describe the rotations.
The default is 0 for ea... | 41,057 |
def dump_db():
"""Dumps the database into the tmp/ folder"""
env.box_datetime = datetime.now().strftime('%Y-%m-%d-%s')
env.box_dump_filename = os.path.join(
os.getcwd(),
'tmp',
'%(box_database_local)s-local-%(box_datetime)s.sql' % env,
)
run_local('pg_dump -Ox %(box_database... | 41,058 |
def set_path_effects(object,**kwargs):
""" Print a nice warning if withStroke doesn't exist. """
try:
from matplotlib.patheffects import withStroke
object.set_path_effects([withStroke(**kwargs)])
except ImportError, er:
print 'Nicer plots require a newer version of matplotlib with pa... | 41,059 |
def add_model_components(m, d, scenario_directory, subproblem, stage):
"""
:param m:
:param d:
:return:
"""
m.Horizon_Energy_Target_Shortage_MWh = Var(
m.ENERGY_TARGET_ZONE_BLN_TYPE_HRZS_WITH_ENERGY_TARGET,
within=NonNegativeReals
)
def violation_expression_rule(mod, z... | 41,060 |
def process(order):
""" Process this timestamp """
cursor = PGCONN.cursor()
for tarfn in glob.glob("NWSTG*tar.Z"):
subprocess.call("uncompress %s" % (tarfn,), shell=True)
ts = datetime.datetime.strptime(tarfn[6:14], '%Y%m%d')
ts = ts.replace(hour=23, minute=59, tzinfo=pytz.utc)
... | 41,061 |
def grow_rate(n, k, nu_c, nu_d, sigma, g, dp, rho_c, rho_d, K):
"""
Compute the instability growth rate on a gas bubble
Write instability growth rate equation in Grace et al. as a root
problem for n = f(k)
Returns
-------
res : float
The residual of the growth-rate equation... | 41,062 |
def cg_semirelaxed_fused_gromov_wasserstein(C1:th.Tensor,
A1:th.Tensor,
p:th.Tensor,
C2:th.Tensor,
A2:th.Tensor,
... | 41,063 |
def add_bounding_boxes(axis, bboxes):
"""
:param axis: axis to modify
:param bboxes: bounding boxes to draw on the axis
:return: None
"""
for bbox in bboxes:
rect = patches.Rectangle((bbox[0], bbox[1]),
bbox[2], bbox[3],
l... | 41,064 |
def Vinv_terminal_time_series(m_t,Vdc_t):
"""Function to generate time series inverter terminal voltage."""
try:
assert len(m_t) == len(Vdc_t) != None
return m_t*(Vdc_t/2)
except:
LogUtil.exception_handler() | 41,065 |
def render(ob, ns):
"""Calls the object, possibly a document template, or just returns
it if not callable. (From DT_Util.py)
"""
if hasattr(ob, '__render_with_namespace__'):
ob = ZRPythonExpr.call_with_ns(ob.__render_with_namespace__, ns)
else:
# items might be acquisition wrapped
... | 41,066 |
def GetFlakeInformation(flake, max_occurrence_count, with_occurrences=True):
"""Gets information for a detected flakes.
Gets occurrences of the flake and the attached monorail issue.
Args:
flake(Flake): Flake object for a flaky test.
max_occurrence_count(int): Maximum number of occurrences to fetch.
... | 41,067 |
def get_prop_cycle():
"""Get the prop cycle."""
prop_cycler = rcParams['axes.prop_cycle']
if prop_cycler is None and 'axes.color_cycle' in rcParams:
clist = rcParams['axes.color_cycle']
prop_cycler = cycler('color', clist)
return prop_cycler | 41,068 |
def binary_crossentropy(target, output, from_logits=False):
"""Binary crossentropy between an output tensor and a target tensor.
Arguments:
target: A tensor with the same shape as `output`.
output: A tensor.
from_logits: Whether `output` is expected to be a logits tensor.
By default, we... | 41,069 |
def create_all_snapshots(volume_ids):
"""
Creates the snapshots of all volumes in the provided list.
Params:
volume_ids (list): List of volumes attached to the instance
Returns:
None
"""
for i in volume_ids:
snapshot(i)
return True | 41,070 |
def GenerateSSHConfig(vms):
"""Generates an SSH config file to simplify connecting to "vms".
Writes a file to GetTempDir()/ssh_config with SSH configuration for each VM in
'vms'. Users can then SSH with 'ssh -F <ssh_config_path> <vm_name>'.
Args:
vms: List of virtual machines.
"""
target_file = os.pa... | 41,071 |
def repopulate(particles,celllist):
"""Make new list of the nearest neighbors."""
for p in particles:
celllist[p] = []
for p2 in particles:
if p != p2 and np.linalg.norm(odleglosc(p.r - p2.r)) < 3.5:
celllist[p].append(p2) | 41,072 |
def stack_subsample_frames(x, stacking=1, subsampling=1):
""" Stacks frames together across feature dim, and then subsamples
x.shape: FEAT, TIME
output FEAT * stacking, TIME / subsampling
"""
# x.shape: FEAT, TIME
seq = []
x_len = tf.shape(x)[1]
for n in range(0, stacking):
tm... | 41,073 |
def compute_TVL1(prev, curr, TVL1, bound=20):
"""
Args:
prev (numpy.ndarray): a previous video frame, dimension is
`height` x `width`.
curr (numpy.ndarray): a current video frame, dimension is
`height` x `width`.
bound (int): specify the maximum and minimux of op... | 41,074 |
def main() -> None:
"""Check the guard records."""
test_answer = 240 # Guard #10 * common minute 24
file = config.TestFile(test_answer, sort=True)
test = determine_sleepiest_guard(file.contents)
file.test(test)
file = config.File(sort=True)
file.write_to_file()
result = determine_sleepi... | 41,075 |
def show():
"""Show the window."""
qapp = QtWidgets.QApplication(sys.argv)
toolbar = Toolbar()
toolbar.show()
qapp.setStyle(QtWidgets.QStyleFactory.create("Fusion"))
sys.exit(qapp.exec_()) | 41,076 |
def _fetch_all_namespace_permissions(cursor):
"""
Fetches all user-namespace-permissions mapping registered with Herd
:param: cursor to run hive queries
:return: list of all users that have READ on each respective namespace
"""
namespaces = _fetch_all_namespaces()
user_namespace_permissions... | 41,077 |
def for_in_right(obj, callback=None):
"""This function is like :func:`for_in` except it iterates over the
properties in reverse order.
Args:
obj (list|dict): Object to process.
callback (mixed): Callback applied per iteration.
Returns:
list|dict: `obj`.
Example:
>... | 41,078 |
def test_equal(mongo_client):
"""Should compare the equality of two Frame instances by Id"""
# Create some dragons
burt = Dragon(
name='Burt',
breed='Cold-drake'
)
burt.insert()
fred = Dragon(
name='Fred',
breed='Fire-drake'
)
fred.insert()
... | 41,079 |
def evaluate_on_real(model_name: str):
"""Evaluates a model on real scanned music pages"""
from app.Network import Network
network = Network.load(model_name)
print("\n")
total_metric_aggregate = _initialize_metrics_aggregate()
for file, staves in REAL_RAW_ANNOTATIONS.items():
print("\... | 41,080 |
def metadata_fake(batch_size):
"""Make a xr dataset"""
# get random OSGB center in the UK
lat = np.random.uniform(51, 55, batch_size)
lon = np.random.uniform(-2.5, 1, batch_size)
x_centers_osgb, y_centers_osgb = lat_lon_to_osgb(lat=lat, lon=lon)
# get random times
t0_datetimes_utc = make_t... | 41,081 |
def delete_document(ix: str, docid: str):
"""
delete a document
PUT request body should be a json {field: value} mapping of fields to update
"""
check_role(Role.WRITER, _index(ix))
try:
elastic.delete_document(ix, docid)
except elasticsearch.exceptions.NotFoundError:
abort(4... | 41,082 |
def sentence_segment(doc, candidate_pos):
"""Store those words only in cadidate_pos"""
sentences = []
for sent in doc.sents:
selected_words = []
for token in sent:
# Store words only with cadidate POS tag
if token.pos_ in candidate_pos and token.is_stop is False and l... | 41,083 |
def get_speckle_spatial_freq(image, pos, cx, cy, lambdaoverd, angle=None):
""" returns the spatial frequency of the speckle defined in the area of aperture mask """
""" lambdaoverd = nb of pixels per lambda/D """
nx, ny =image.shape[0], image.shape[1]
k_xy = (np.roll(pos,1,axis=0)-[cx,cy])/lambdaoverd ... | 41,084 |
def verify_ping(
device,
address,
loss_rate=0,
count=None,
max_time=30,
check_interval=10):
""" Verify ping loss rate on ip address provided
Args:
device ('obj'): Device object
address ('str'): Address value
loss_rate ('int... | 41,085 |
def add_server_arguments(parser):
"""Add the --bind option to an argparse parser"""
def hostportsplit_helper(arg):
"""Wrapper around hostportsplit that gives better error messages than
'invalid hostportsplit value'"""
try:
return hostportsplit(arg)
except ValueError... | 41,086 |
async def test_sensor_events():
"""Test event_handler works."""
session = DeconzSession(AsyncMock(), HOST, PORT, API_KEY, add_device=Mock())
# Add sensor
session.event_handler(
{
"e": "added",
"id": "1",
"r": "sensors",
"sensor": {
... | 41,087 |
def get_default(key):
""" get the default value for the specified key """
func = registry.defaults.get(key)
return func() | 41,088 |
def log_compute_hindcast_header(metric, comparison, dim, alignment):
"""Add header to the log for a `compute_hindcast` instance."""
logging.info(
f'`compute_hindcast` for metric "{metric.name}", '
f'comparison "{comparison.name}", dim "{dim}", and alignment "{alignment}" at '
f"{str(date... | 41,089 |
def antisymmetric(r: Relation) -> (bool, List):
"""Kiểm tra tính phản xứng của r"""
antisymmetric_tuple = []
for x, y in r:
if x == y:
continue
if (y, x) in r:
return False, [((x, y), (y, x))]
antisymmetric_tuple.append(((x, y), (y, x)))
return True, antis... | 41,090 |
def docstring_func_parameters(arg1, arg2):
"""Test parameters docstring.
:param arg1: first argument
:param arg2: second argument
"""
pass | 41,091 |
def status(job_id: str):
"""
Start the service.
"""
from job_api.jobapi import JobApi
api = JobApi()
pprint(api.status(job_id)) | 41,092 |
def calc_negative_predictive_value(cause, actual, predicted):
"""Calculate negative predictive value (NPV) for a single cause
Negative predictive value is the number of prediction correctly determined
to not belong to the given cause over the total number of predicted to
not be the cause:
.. math:... | 41,093 |
def print_atom_swap(swap):
"""Return atom swap string for DL CONTROL"""
return "{} {}".format(swap["id1"], swap["id2"]) | 41,094 |
def set_alarm_time(month, day, year, hour, minute, second):
"""Set the desired alarm event time"""
rtc_set_alarm(month, day, year, hour, minute, second) | 41,095 |
def export_onnx_model(model, inputs):
"""
Trace and export a model to onnx format.
Args:
model (nn.Module):
inputs (torch.Tensor): the model will be called by `model(*inputs)`
Returns:
an onnx model
"""
assert isinstance(model, torch.nn.Module)
# make sure all module... | 41,096 |
def dot_product_area_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=None,
attention... | 41,097 |
def update_docs(cfid, docs) -> bool:
"""Updates the documentation of an already existing model
The update_docs function can be used to upload the documentation of an already existing model
by simply providing the cfid and the new docs object.
Args:
cfid: a string with a valid computeFunction I... | 41,098 |
def test_ssd_mean_pos():
"""
Compare to online calculators the result of Sample Size Determination for proportions. Due to approximations,
the test passes if sample_size belongs to the right neighbourhood of the result given by the online calculator;
in other words the test passes if sample_size is in r... | 41,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.