content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def get_angle(p1, a1, p2) -> float:
"""
Izračunaj kot, za katerega se mora zavrteti robot, da bo obrnjen proti točki p2.
Robot se nahaja v točki p1 in ima smer (kot) a1.
"""
a = math.degrees(math.atan2(p2.y-p1.y, p2.x - p1.x))
a_rel = a - a1
if abs(a_rel) > 180:
if a_re... | 93ad2d8b1a8a98e1669f2b9c1553e507850f0384 | 3,608,300 |
def get_mnist_loader(batch_size, classes=[9, 4], n_items=5000, proportion=0.9, n_val=5, mode='train'):
"""Build and return data loader."""
dataset = MNISTImbalanced(classes=classes, n_items=n_items, proportion=proportion, n_val=n_val,mode=mode)
shuffle = False
if mode == 'train':
shuffle = Tru... | eb49de9693f9a2fc1c8a9681353c897bab259935 | 3,608,301 |
from typing import Iterable
from typing import Mapping
from typing import Set
def is_ordered_sequence(caster):
"""Caster can be ordered sequence of another casters."""
return (isinstance(caster, Iterable)
and not isinstance(caster, (Mapping, Set))) | cbefae7359f112b5ab13f377b3c9552d286d14d0 | 3,608,302 |
def entityRegister(name, type="business", subtype=0, ipfsData=None):
"""
Build an entity registration.
Arguments:
name (str): entity name
type (str): entity type. Possible values are `business`, `product`,
`plugin`, `module` and `delegate`. Default to `business`.
subtype... | 37c0926f14839b6e9d97f839d07585d3e10cbdac | 3,608,303 |
def isiterable(obj: any) -> bool:
"""Check if the input is iterable.
Note that this function does not capture all possible cases
and is subject to change in the future if issues arise.
Parameters
----------
obj
The object to check.
Returns
-------
bool
True if the o... | 840ddab4fc1d50fa7de40c6dccd2d6dc9bffc4cb | 3,608,304 |
def get_ipv4_network(cidrs):
"""Get the IPv4 network from the given CIDRs or None"""
return {net.version: net for net in get_networks(cidrs)}.get(4) | d1cedc434419f845bdd59d880c651c0580995f7b | 3,608,305 |
def get_case_for_doc(doc):
"""Retrieves case for a document.
"""
s = """SELECT * FROM cases WHERE id=?"""
db.cursor.execute(s, (doc['case_id'],))
rows = db.cursor.fetchone()
if not rows:
return None
else:
return db._convert_to_cases_dict([rows])[0] | be5e36900348217cb12e765b6d8f45eefdd85eb4 | 3,608,306 |
def read_data(path, actuals=False):
"""
Read fcst and actuals arrays from disc
"""
with Resource(path) as f:
fcst = f['fcst']
if actuals:
acts = f['actuals']
if actuals:
return fcst, acts
else:
return fcst | e22df659915d962e57bfb26bcfce4a11fe4ed7b7 | 3,608,307 |
import unicodedata
def clean_for_search(text_html):
""" Clean up for searching """
text_html = to_unicode(text_html)
text = remove_html(text_html).replace('\n',' ').lower() # Remove html, line breaks, and make lower case
text = unicodedata.normalize('NFKD', text).encode('ascii','ignore') # https://www... | 84ff49fffa92859f65d2296ea8c556a9a4268e4e | 3,608,308 |
def broken_track():
"""Mark a track as broken for later investigation."""
youtube_id = request.form['youtube_id']
name = request.form['name']
Track.save_broken_track(youtube_id, name)
return Response() | 186606417c89d3dddefa21f559f152ee460f22f9 | 3,608,309 |
def _height_metrics(box_center_z, box_height, boxes_center_z, boxes_height):
"""Compute 3D height intersection and union between a box and a list of boxes.
Args:
box_center_z: A scalar.
box_height: A scalar.
boxes_center_z: A Numpy array of size [N].
boxes_height: A Numpy array of size [N].
Retu... | ec18243b9da72b82f4c8f8075b9c17ea2f73eff9 | 3,608,310 |
def _inv_QR(M, iszerofunc=_iszero):
"""Calculates the inverse using QR decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.QRsolve(M.eye(M.rows)) | 84fa6910bebe0bb598bd0acb899ed8e281dec132 | 3,608,311 |
import re
def parseQuestion(sentence, translate_language='Translate Here...'):
"""
parse sentence and return correct answer for each gap
"""
sentence = sentence.replace("{", "[").replace("}", "]")
gaps = re.findall(r"[^[]*\[([^]]*)\]", sentence)
first_option = gaps[0].split('|')[0]
# text... | 982a560bd15c00f49322242e970a8c366f0ec3fd | 3,608,312 |
from datetime import datetime
def _purge_legacy_format(
instance: Recorder, session: Session, purge_before: datetime, using_sqlite: bool
) -> bool:
"""Purge rows that are still linked by the event_ids."""
(
event_ids,
state_ids,
attributes_ids,
data_ids,
) = _select_leg... | ec0e5337dd43cc41882237b9b3fedd775e7aef38 | 3,608,313 |
def summary(value_dict, global_step, writer):
"""Make tf.Summary for tensorboard"""
summary = tf.Summary(value=[tf.Summary.Value(tag=k, simple_value=v) for k, v in value_dict.items()])
writer.add_summary(summary, global_step)
return None | 4f435aaf8277e22ac8fa6d7b320a73c42335367d | 3,608,314 |
def inference_network(x, latent_dim, hidden_size):
"""Construct an inference network parametrizing a Gaussian.
Args:
x: A batch of MNIST digits.
latent_dim: The latent dimensionality.
hidden_size: The size of the neural net hidden layers.
Returns:
mu: Mean parameters for the variational family N... | a2c2d5f461a9bd0787309fe838a5da05fae057f5 | 3,608,315 |
import torch
def align(src_tokens, tgt_tokens):
"""
Given two sequences of tokens, return
a mask of where there is overlap.
Returns:
mask: src_len x tgt_len
"""
mask = torch.ByteTensor(len(src_tokens), len(tgt_tokens)).fill_(0)
for i in range(len(src_tokens)):
for j in ra... | 0408ae7148c4bed9e3c24b71acdbd1a182dd6e69 | 3,608,316 |
import logging
def apply_change_list(question_id, change_list):
"""Applies a changelist to a pristine question and returns the result.
Args:
question_id: str. ID of the given question.
change_list: list(QuestionChange). A change list to be applied to the
given question. Each entry... | 16df354a6096b96c915e167b0c4b8e059b77de57 | 3,608,317 |
def set_identity_pool_roles(
IdentityPoolId,
AuthenticatedRole=None,
UnauthenticatedRole=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given an identity pool id, set the given AuthenticatedRole and UnauthenticatedRole (the Role
can be an iam arn, or a role name) ... | 6ebcd259d901094474bcf867cd018487b318ac56 | 3,608,318 |
from typing import Any
def is_listy(x: Any) -> bool:
"""
Grabbed this from fast.ai
"""
return isinstance(x, (tuple, list)) | 331791b4d1e1f4047ab99b54a58441805bc71311 | 3,608,319 |
def ResolveApiInfoFromFlags():
"""Determine an api and api_version."""
api_version = FLAGS.api_version
api = FLAGS.api
return {'api': api, 'api_version': api_version} | 0978fd96017ce1e8870407f0e5eb1e706c7a7a72 | 3,608,320 |
import psutil
def get_disk_space(path: str) -> tuple:
"""_summary_
Args:
path (str): _description_
Returns:
tuple: _description_
"""
usage = psutil.disk_usage(path)
space_total = bytes2human(usage.total)
space_used = bytes2human(usage.used)
space_free = bytes2human(us... | 77c9b16441703d6a1644e28fb5dd5a4c9f91790d | 3,608,321 |
def lnglat_to_meters(longitude, latitude):
"""
Projects the given (longitude, latitude) values into Web Mercator
coordinates (meters East of Greenwich and meters North of the
Equator).
Longitude and latitude can be provided as scalars, Pandas columns,
or Numpy arrays, and will be returned in th... | 20540a5c2cf74ee0b8a2c01f3daa2cd32dcdd369 | 3,608,322 |
def _scrub_parameters(parameters):
"""Returns a scrubbed list of RayParameters."""
return [
RayParameter(
name=param.name,
kind_int=_convert_from_parameter_kind(param.kind),
default=param.default,
annotation=param.annotation,
partial_kwarg=para... | 19029bf360c8061e56a0287527e4d90779be1da7 | 3,608,323 |
def get_parsers(klass, key):
"""Return tuple of 2 parsers related to current key and class"""
fulltext_parser = get_fulltext_parsed_value(klass, key)
if fulltext_parser:
if isinstance(fulltext_parser, DatetimeValue):
return (fulltext_parser, None)
else:
return (None, fulltext_parser)
columns... | 69c68d9cdf1ed03abe829884c9a0511a73cc906c | 3,608,324 |
def create_alert():
"""
Create an alert. Must be an advocate.
"""
form = AlertForm()
if not form.validate_on_submit():
return api_error(form.errors)
send_out_alert(form)
return '', 201 | 35770137480d27b0e91c1abd2f354980cd873b5c | 3,608,325 |
def register_env(name):
"""Registers a env by name for instantiation in plaidrl."""
def register_env_fn(fn):
if name in ENVS:
raise ValueError("Cannot register duplicate env {}".format(name))
if not callable(fn):
raise TypeError("env {} must be callable".format(name))
... | 0efde537098dfdb92d67ae6d77615c79998c12a0 | 3,608,326 |
from re import T
def acl():
"""
Preliminary controller for ACLs
for testing purposes, not for production use!
"""
table = auth.permission.table
tablename = table._tablename
table.group_id.requires = IS_ONE_OF(db, "auth_group.id", "%(role)s")
table.group_id.represent = lambda o... | fd23fbae798f34bd9a5652d87d5c33025d8cef77 | 3,608,327 |
import torch
def real(a: torch.Tensor):
"""Real part."""
if is_real(a):
raise ValueError('Last dimension must have length 2.')
return a[..., 0] | 19f81a29a404c232de9a837509a96f84a80fc07b | 3,608,328 |
from pathlib import Path
from typing import Dict
import yaml
def _load_yaml_doc(path: Path) -> Dict:
"""Load a yaml document."""
with open(path, "r") as src:
doc = yaml.load(src, Loader=yaml.FullLoader)
return doc | 4b049909c5e6eac6e7772b3311f928ccd6cf528c | 3,608,329 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/datesearch/<start><br/>"
f"/api/v1.0/datesearch/<start>/<end>"
) | b9d63139680f5bd41349c34642ca4d1608542978 | 3,608,330 |
import binascii
def encrypt(bdata, encr_key):
"""
Encrypt some data.
"""
# Enhance user password with PBKDF2
pwd = PBKDF2(password=encr_key, salt='^0Twister-Salt9$', dkLen=32, count=100)
crypt = AES.new(pwd)
pad_len = 16 - (len(bdata) % 16)
padding = (chr(pad_len) * pad_len)
# Encr... | 167b5e1e72466a5a02f491dda1bd6e116a70d1a9 | 3,608,331 |
from typing import Iterable
from typing import List
def get_all_dangling(nodes: Iterable[AbstractNode]) -> List[Edge]:
"""Return the set of all dangling edges."""
edges = []
for node in nodes:
edges += node.get_all_dangling()
return edges | 64624655a4f53a673e437fc08f4cc781931aeb56 | 3,608,332 |
def parse_reroute_domain_query(project_id, dataset_id, dest_table):
"""
This function generates a query that reroutes the records from all domain tables for the given dest_table.
It uses _mapping_alignment_table to determine in which domain table the records should land.
:param project_id: the project_... | bc7379b2eae3fb31ba8a3157220ff8e0baa35f21 | 3,608,333 |
def getFloat (Float):
"""
Float input verification
usage: x = getFloat ('mensage to display ')
"""
while True:
try:
user_input = float(input(Float))
return user_input
except ValueError:
print('Use only numbers and separete decimals with point') | 27d9128441cadd00627d88bbfdb45144bf5a55f3 | 3,608,334 |
def histogram_of_pixel_projection(img):
"""
This method is responsible for licence plate segmentation with histogram of pixel projection approach
:param img: input image
:return: list of image, each one contain a digit
"""
# list that will contains all digits
character_list_image = list()
... | 8f3c528557ca44b76f4b534fa1c42912ebb06a12 | 3,608,335 |
import sys
def find_closest_frame_index(color_time, other_timestamps):
""" finds the closest (depth or NIR) frame to the current (color) frame.
Parameters
----------
color_time : int
Timestamp [ms] of the current color frame
other_timestamps: dict
Dictionary with the frame index and the
corres... | 67cc6f8d4a56057105e820546d5e8720ea2d8786 | 3,608,336 |
def head_status(request, persistence):
"""Respond with OK."""
return web.Response() | c19fbd1ba01ecc855ffd9e0106e005430b6a679c | 3,608,337 |
def Cl_flat_plate(alpha, Re_c):
"""
Returns the approximate lift coefficient of a flat plate, following thin airfoil theory.
:param alpha: Angle of attack [deg]
:param Re_c: Reynolds number, normalized to the length of the flat plate.
:return: Approximate lift coefficient.
"""
Re_c = cas.fab... | fd7e976819a50cfd951e9df90ebf11adbd63aae9 | 3,608,338 |
import os
def exists(subsystem, group):
"""os.path.exists the cgroup"""
fullpath = makepath(subsystem, group)
return os.path.exists(fullpath) | 6fea42a570ab9ae58a55403fbf1989373cb8fa85 | 3,608,339 |
import warnings
def weight_list(spam, weights, warn=True):
""" Returns weighted list
Args:
spam(list): list to multiply with weights
weights (list): of weights to multiply the respective distance with
warn (bool): if warn, it will warn instead of raising error
Returns:
(l... | 6b2258675a5c346c50ecc8f7d8aba466a7b216ef | 3,608,340 |
import tqdm
def jitter(traces, exp=1):
"""
Simulates jitter using the given rate parameter. Applies it to the supplied traces.
"""
res = np.zeros_like(traces)
for ix in tqdm(range(len(traces)), desc=f"Applying jitter with exp={exp}"):
res[ix] = jitter_trace(traces[ix], exp)
return re... | 1f43057936ca3f9bab0242798b0e4f5961f001c2 | 3,608,341 |
def harvest_index(prof, Soil_zTop, Crop, InitCond, Et0, Tmax, Tmin, GrowingSeason):
"""
Function to simulate build up of harvest index
<a href="../pdfs/ac_ref_man_3.pdf#page=119" target="_blank">Reference Manual: harvest index calculations</a> (pg. 110-126)
*Arguments:*
`Soil`: `SoilClass` : ... | 1406c3416cbdadcdd454397b42fd69e4459ea521 | 3,608,342 |
from astropy.nddata.ccddata import _generate_wcs_and_update_header
from reproject import reproject_interp
def wcs_project(ccd, target_wcs, target_shape=None, order='bilinear'):
"""
Given a CCDData image with WCS, project it onto a target WCS and
return the reprojected data as a new CCDData image.
Any... | 663ef4893de19c51a8a2be0e030db1c237252e91 | 3,608,343 |
from typing import Callable
import click
def test_env_run_option(command: Callable[..., None]) -> Callable[..., None]:
"""
A decorator for choosing whether to run commands in a test environment.
"""
function = click.option(
'--test-env',
'-te',
is_flag=True,
help=(
... | 33de24e435aa258f8bd3474ee2ca3a3358651584 | 3,608,344 |
def get_paged_jobs(rc, url, basic_auth, cafile, tower_job_status_list, last_update_epoch):
"""
get jobs results, returning paged results
:param rc: RequestsCommon
:param url:
:param basic_auth:
:param cafile:
:param tower_job_status_list: list of pending, failed, successful
:param last_u... | 803c902a7cdd90a7b5179c7e8b5bf17289f99663 | 3,608,345 |
import types
def _prepare_schema(
*, schema: types.Schema, schemas: types.Schemas, array_context: bool = False
) -> types.Schema:
"""
Check and transform readOnly schema to consistent format.
Args:
schema: The readOnly schema to operate on.
schemas: Used to resolve any $ref.
a... | ef42166792b23a424ee43a073b51917916ca3443 | 3,608,346 |
def rinex_name(station, year, month, day):
"""
author: kristine larson
given station (4 char), year, month, day, return rinexfile name
and the hatanaka equivalent
"""
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
fnameo = station + cdoy + '0.' + cyy + 'o'
fnamed = station + cdoy + '0.' +... | adf90ae9e05718a910a8f6818590539f73e24ea9 | 3,608,347 |
def threshold_otsu(image, nbins=256):
"""Return threshold value based on Otsu's method.
Parameters
----------
image : (N, M) ndarray
Grayscale input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
Returns
... | 65872502a886d97d2ac999aa767ad749af1832e5 | 3,608,348 |
def create(cart_id: str):
"""
Endpoint. Creates a cart.
:param str cart_id: cart id
:return: dict with message
:rtype: dict
"""
logger.info(f'Request@/create/{cart_id}')
return cart.create_cart(cart_id=cart_id) | 10d8955699b7780fd35020adbb2fc568ce604d30 | 3,608,349 |
def get_speed_soft_current():
"""
for line chart and radar
:return:
"""
soft_speed_list = speed_softgame_current("soft")
if soft_speed_list != "no data":
return jsonify({"softtop5": soft_speed_list[0: 5],
"softtop10": soft_speed_list[5: 10]})
else:
ret... | a942dedc85434e71145837a9c843feb5402c649c | 3,608,350 |
import os
import requests
import json
def call_crawlers() -> bool:
"""
Fetches the list of all shops, does some load balancing magic and calls all registered crawler
instances to start them
:return: If the calls have been successful
"""
product_ids = sql.getProductsToCrawl()
# crawler_url... | acf141035d7f9d179c901981c4c53137621e2b56 | 3,608,351 |
import random
def create_population(size, result):
"""
Creates a population of chromosomes
Args:
size : size of the population
result : the target chromosome
Returns:
a population of chromosomes each having length equal to 'result'
and made up of random character
"""
length = len(result.co... | 2478cdb8e1fb5214cdbc3ff021d7a79aa38a288b | 3,608,352 |
def get_old_ip(security_group_obj, current_ip):
"""
Loop over aws security group ips for current ip or set description
:param security_group_obj: aws security group obj
:param current_ip: current ip
:return: ip from security group that has the set description, or is the current ip if remove_ip is Tr... | 6c4e5e224dd758cd3c5e9ceb608ef204fcf34476 | 3,608,353 |
import argparse
def parse_args():
"""命令行参数设置。"""
parser = argparse.ArgumentParser(description='语音合成命令行。')
parser.add_argument('-i', '--interaction', type=int, default=1,
help='是否交互,如果1则交互,如果0则不交互。交互模式下:如果不输入文本或发音人,则为随机。如果输入文本为exit,则退出。')
parser.add_argument('-t', '--text', type... | 339592ef0d30459ffe40378b9bfe501321d82503 | 3,608,354 |
from typing import Iterable
from typing import Any
from typing import Union
from typing import Dict
def any_in_dict(
values: Iterable[Any], d: Union[Dict[Any, Any], TxData, TxParams]
) -> bool:
"""
Returns a bool based on whether ANY of the provided values exist among the keys of the provided
dict-lik... | ed6a1be6405a534c9a0afce6f1a4ec4975fa096b | 3,608,355 |
def privacy_policy(request):
"""Privacy Policy"""
return render(request, 'dublinbus/privacy_policy.html') | 5a5fba069cf39cb33d65f0e5130c47ad872be241 | 3,608,356 |
import numpy
def compute_features(net, im):
"""
Compute fc7 features for im
"""
fc7 = numpy.array(lasagne.layers.get_output(net['fc7'], im, deterministic=True).eval())
return fc7 | 380a32771ba53d0c9310985d96dc835d8d5480ca | 3,608,357 |
def bout_boundaries_ts(ts, bname):
"""Gets the bout boundaries for a specific behavior from a male within
a FixedCourtshipTrackingSummary.
Parameters
----------
ts : FixedCourtshipTrackingSummary
Should contain ts.male and ts.female attributes.
bname : string
Behavior to calcul... | c9c4351e18ff3e089cc7a925101ad77116b1f571 | 3,608,358 |
import timeit
def mclp_batch_solver(env_path, road_network, demand_point, potential_facility_site, service_distance, list_num_facility, demand_weight_attr):
"""
Solve multiple MCLPs using the given inputs and a list of number of facilities. This function will call the function of mclp_solver
:param env_pa... | 8e21380c1fed383c062cea18092363be00a62538 | 3,608,359 |
import torch
def locations_to_boxes(
*,
locations: torch.Tensor,
priors: torch.Tensor,
center_variance: float,
size_variance: float
) -> torch.tensor:
"""Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
The conversion:
$$predicted\_center * ... | dbe72b796c38f1705e377d8f6668562bb5b1fc96 | 3,608,360 |
def get_metric_fqdd_mapping(connection: str):
"""get_metric_fqdd_mapping Get Metric-FQDD Mapping
Get metric-fqdd mapping
Args:
connection (str): connection string
"""
engine = db.create_engine(connection)
metadata = db.MetaData()
connect = engine.connect()
mapping = {}
me... | d41dbd051d4f6f3eebab62eeb16fc812bf58fbb9 | 3,608,361 |
def __extract_digits__(string):
"""
Extracts digits from beginning of string up until first non-diget character
Parameters
-----------------
string : string
Measurement string contain some digits and units
Returns
-----------------
digits : int
... | 6613e56dc33c88d9196c2ec95412155ad0aaf382 | 3,608,362 |
def scatterkwargs(kwargs):
"""
Get a subset of keyword arguments to pass to a matplotlib scatter call.
Parameters
-----------
kwargs : :class:`dict`
Dictionary of keyword arguments to subset.
Returns
--------
:class:`dict`
"""
kw = subkwargs(
kwargs,
plt... | ead7da23f7726a9fdd8a7e600b83b01bbfe2f7c7 | 3,608,363 |
def _proxy_user(environ, username):
"""
Load up the correct user information for the user being proxied
in a mapping.
"""
store = environ['tiddlyweb.store']
try:
user = User(username)
user = store.get(user)
return {'name': user.usersign, 'roles': user.list_roles()}
ex... | 8ace13f8c1a6481e6fb4493af90c56ec3f8128c0 | 3,608,364 |
import csv
def class_names_from_csv(class_map_csv):
"""Read the class name definition file and return a list of strings."""
if tf.is_tensor(class_map_csv):
class_map_csv = class_map_csv.numpy()
with open(class_map_csv) as csv_file:
reader = csv.reader(csv_file)
next(reader) # Skip... | f03b85dc412a2f11608cb0c24ae6c1cc0b272316 | 3,608,365 |
def add_attachment(manager, issue, path):
"""
Replace jira's method 'add_attachment' while don't well fixed this issue
https://github.com/shazow/urllib3/issues/303
And we need to set filename limit equaled 252 chars.
:param manager: [jira.JIRA instance]
:param issue: [jira.JIRA.resources.Issue i... | 0bb2b910e1e92f1ebfe9272959ba61b07cc36091 | 3,608,366 |
def is_valid_array_size(x, lower=1e-10, upper=1e10):
"""Checks whether a vector or matrix norm is within lower and upper bounds.
Parameters
----------
x : array-like
The data to be checked
lower : float (default = 1e-10)
The lower bound vector or matrix norm.
upper : float... | 68a257fa63ccd6e0a24e07d06d82a6c8d946a293 | 3,608,367 |
def array_rotation():
"""Solution to exercise R-11.10.
Explain why performing a rotation in an n-node binary tree when using
the array-based representation of Section 8.3.2 takes Ω(n) time.
---------------------------------------------------------------------------
Solution:
------------------... | f448fede21496701509e2399f1ebc1b3fbf50954 | 3,608,368 |
def collisional_model(q, system, ancillae, collision_number=None,
g=1., tau=1., measure=False,
environment_qubits=None, **kwargs):
"""Prepare QuantumCircuit for the collisional model
Args:
q (QuantumRegister): the register
system (i... | 11810909b0c003fca830ceef97d8bdb347533d7c | 3,608,369 |
def update_sulfuras(item):
"""
sulfuras keeps it quality and has not to be sold
"""
return item.sell_in, item.quality | 7ed10720aa7543719383f73923f2f64bf1439021 | 3,608,370 |
def prune_punc(a_toks):
"""Remove tokens representing punctuation from set.
Args:
a_toks (iterable): original tokens
Returns:
frozenset: tokens without punctuation marks
"""
return frozenset([tok for tok in a_toks if not _ispunct(tok[-1])]) | 9be17ba73841aee4d16380b71a2107bc9bbbd16c | 3,608,371 |
def cases_list(request):
"""List caseversions."""
return TemplateResponse(
request,
"manage/case/cases.html",
{
"caseversions": model.CaseVersion.objects.select_related(
"case",
"productversion",
"productversion__product",
... | f159de0330cc66155056101604400c424c510391 | 3,608,372 |
import functools
import errno
def wrap_exceptions(fun):
"""Decorator which translates bare OSError and WindowsError
exceptions into NoSuchProcess and AccessDenied.
"""
@functools.wraps(fun)
def wrapper(self, *args, **kwargs):
try:
return fun(self, *args, **kwargs)
exce... | f2ce0079b193065bae725b144cdd1d759af50c9c | 3,608,373 |
import random
def draw_box(pred, orig_img, cls, colors):
"""
draw the predicted bounding boxes on a given image.
designed for single images.
For multi batch support, supply singular image iteratively
"""
coords1 = tuple(pred[1:3].int())
coords2 = tuple(pred[3:5].int())
label = "{0}".... | d04494b8736f76f94ab69d491ba71b17dc40665f | 3,608,374 |
from typing import Tuple
def compute_climatology(
data: xr.DataArray,
base_period: Tuple = (None, None),
) -> xr.DataArray:
"""
Computes the seasonal mean of a DataArray that has a time
dimension
Parameters
----------
data
base_period
"""
_check_dimensions(data)
return... | e211800d0b7a0c4127e369a4c7132b3e8d0a5f64 | 3,608,375 |
def name_by_arg(sex: str, name: str = None, id: int = None):
"""Get name object by passed `name` or `id` argument.
Args:
sex (str): male/female/all
Returns:
dict: Name object if successful, otherwise error.
If no argument passed, return all names.
"""
if sex == "male":
... | 61a7db60c5360ece9f1457947ed027ba507f8d56 | 3,608,376 |
def plugin_info():
""" Returns information about the plugin
Args:
Returns:
dict: plugin information
Raises:
"""
return {
'name': 'ds18b20 Plugin',
'version': '1.0',
'mode': 'poll', ''
'type': 'south',
'interface': '1.0',
'config': _DEFAUL... | 97ce0e5b7e1f7cdd1eaa72b0258cd394ded65366 | 3,608,377 |
def LP():
"""
load prototype
"""
return builder.lp() | 124c3034fecbd7e3abf9186e1749bfa970668408 | 3,608,378 |
def maxkcolor_edges(num_vertices: int, num_edges: int):
"""Generates edges for MaxKColor problems randomly
Args:
num_vertices: Number of vertices
num_edges: Number of edges
Returns:
List of randomly generated undirected edges
`[..., (v1, v2) ,...]`. Note that (v1, v2) and
... | 1febf58f50102fb95317fc8b3680b555a6b442fc | 3,608,379 |
def _standard_normalize(values, axes=(0,)):
"""Standard normalizes values `values`.
Args:
values: Tensor with values to be standardized.
axes: Axes used to compute mean and variances.
Returns:
Standardized values (values - mean(values[axes])) / std(values[axes]).
"""
values_mean, values_var = tf... | d1103b725c462c01e37d503dfdcb68c936fea505 | 3,608,380 |
import array
def dimcollapse_csr(v, indexes=(), normalize=True):
"""dimensional collapse of a vector
:param v: csr vector
:param indexes: allowed dimensional indexes
:param normalize: logical, set True to rescale values to unit norm
:return: new csr vector, values outside indexes reset to zero
... | a12d065190c47728755e40c0ce5ac3fb53d77ac3 | 3,608,381 |
import re
import sys
def parse_tree(infile):
""" Parse newick formatted tree file and returns a tuple consisted of a
Tree object, and a HPD dictionary if 95%HPD is found in the newick string,
otherwise None
Args:
infile (str): Path to the tree file
"""
with open(infile) as fp:
... | 60b5662e32d1c958416faf1fc581cf50116085f1 | 3,608,382 |
def inslit(slit, decker, p, q):
"""
Determine whether an exposure is in the slit based on the slit size and offsets.
:param slit: Slit name [string]
:param decker: Decker name [string]
:param p: Absolute P offset (arcseconds) [float or string]
:param q: Absolute Q offset (arcseconds) [float or s... | 2f694953aedfa61ae64d5092ae1684a40c247133 | 3,608,383 |
import requests
def openei_api_request(data, pause_duration=None, timeout=180,
error_pause_duration=None):
"""
Args:
data (dict or OrderedDict): key-value pairs of parameters to post to
the API
pause_duration:
timeout (int): how long to pause in seco... | ad228a80bd7d4c7d2ffe8db148a4ebd48fa4aa23 | 3,608,384 |
def downside_risk_nb(returns, ann_factor, required_return_arr):
"""2-dim version of `downside_risk_1d_nb`.
`required_return_arr` should be an array of shape `returns.shape[1]`."""
result = np.empty(returns.shape[1], dtype=np.float_)
for col in range(returns.shape[1]):
result[col] = downside_ris... | 4a56b95824dc9d13d6cd401b86d7eb700942309d | 3,608,385 |
import json
def shorten():
"""
Input a youtube id from the client and we will
return a jsonified array of subclips. [(s1, e1), (s2, e2)]
We cache all extracted yt hot clips with their respective yt
id's. We maintain the 10 most recent hot clips per yt id.
"""
yt_id = request.form['yt_id']... | 76dc5f137957d7dbe8052eb6ce6c0823af620f3d | 3,608,386 |
import random
def generate_masked_image(image, boxes, masks, class_ids, class_names,
scores=None,
show_mask=True, show_bbox=True, show_score=True,
colors=None, captions=None):
"""
boxes: [num_instance, (y1, x1, y2, x2, class_id)] in image coord... | 5155f9d0226f47fb6dc7e47435994f57da5ecc55 | 3,608,387 |
def msbe(P, R, Γ, v):
"""Mean squared Bellman error (MSBE)."""
assert linalg.is_ergodic(P)
d_pi = linalg.stationary(P)
return np.sum(d_pi * bellman_error(P, R, Γ, v) ** 2) | 2905987f5dcf83499d96c29a77c191d9da9ed683 | 3,608,388 |
def new_indicator_request(category):
"""
Create a new indicator
"""
url = '{}/indicators/{}'.format(BASE_PATH, category)
response = http_request(
'POST',
url,
headers=GET_HEADERS
)
try:
return response.json().get('data')
except Exception as e:
LO... | 3419b0e108d095799a9301ee521ebd8d5c4f96cf | 3,608,389 |
def parse_default(
filename, data=None, metadata=None, read_write='r'):
"""
Default parser for data. Assumes there is a single line of metadata at the top line in the form of a dictionary and the remainder is tabular and can be imported as a pandas DataFrame
:param filename: Name of the file to be ... | 839a845af95622a908f0c4f8958a72747b7bdbf3 | 3,608,390 |
from typing import Counter
def filter_adjoined_candidates(candidates, min_freq):
"""
Funcao que filtra apenas os candidatos proximos que aparecem com certa frequencia
"""
candidates_freq = Counter(candidates)
filtered_candidates = []
for candidate in candidates:
freq = candidates_freq[... | be9c8618dc9e8efd086cc3c8cc51d5ffdb5d8254 | 3,608,391 |
def tune_model(X_train, y_train, X_test, y_test, model,
space, metric, n_calls=25, minimize=True, min_func=gp_minimize):
"""
:param X_train: array-like, shape = [n_samples, n_features] The input samples.
:param y_train: array of shape = [n_samples] The training values.
:param X_train: arr... | 79d8f0f689e2d1d52b4346c5fc29a0f1e1eee074 | 3,608,392 |
def gcd(a, b):
"""Find the greatest common denominator of two integers.
Using Euclid's algorithm.
"""
b = abs(b)
while b != 0:
a, b = (b, a % b)
return a | 3c636a00c73fbc26a2dbcf5d3a99bc1ca26c887e | 3,608,393 |
from typing import Iterable
def load_data(pairs_db_obj):
""" Load currency pair's data
"""
data = _schema.dump(pairs_db_obj, many=isinstance(pairs_db_obj, Iterable))
return data | c8b7ffeffe6ccc45a3f61307e3f02347e9426bb0 | 3,608,394 |
import os
def check_group_dir(settings, data_key='filt_dir', csv_key='true_dir'):
"""
Check if folders exist and if h5 files in filt directory match csv files.
Parameters
----------
settings : dict, with config settings
data_key : str, settings key for filtered data directory
csv_key : st... | 7a34c14f307e5d3efc871e3b1992d89a2884671c | 3,608,395 |
def logout_view(request):
"""
logout
"""
logout(request)
return redirect('/') | 6a2a2dcbd904b19ccff6ffbc9cad3997439f78be | 3,608,396 |
def a2tf(ndp, angle):
"""
Wrapper for ERFA function ``eraA2tf``.
Parameters
----------
ndp : int array
angle : double array
Returns
-------
sign : char array
ihmsf : int array
Notes
-----
The ERFA documentation is below.
- - - - - - - -
e r a A 2 t f
... | 04070aef38a558146d7e3c68fc5769e28ebbd91e | 3,608,397 |
def calc_distance_matrix(all_seqs: list):
"""
Uses BLAST to calculate pairwise distances between sequences
:param all_seqs: A list of sequences to write to file
:return: a symmatrical matrix of distances and a list of the row/colnames
"""
# align_output, header = blast_seqs(all_seqs, all_seqs, b... | 8dd7f224a7bce14cd420892bfc51f7ea23f197c9 | 3,608,398 |
def getCache(request):
"""
测试方法
:param request:
:return:
"""
dict = settings.ZK_HARPC.get_resource()
return JsonResponse({'test': dict}, safe=False) | 145f25bba8625a61d67e8ae295c602e1886dc333 | 3,608,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.