content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def rel_to_rect(bb, sz_norm=None):
"""Inverts the effect of rect_to_rel. See above."""
sz = torch.exp(bb[...,2:])
if sz_norm is None:
c = bb[...,:2] * sz
else:
c = bb[...,:2] * sz_norm
tl = c - 0.5 * sz
return torch.cat((tl, sz), dim=-1) | ed2c31d1add58b1d5af843159eab4fa20471f76d | 3,596,271 |
def arrays_avg(values_array, weights_array=None):
"""
Computes the mean of the elements of the array.
Parameters
----------
values_array : array.
The numbers used to calculate the mean.
weights_array : array, optional, default None.
Used to calculate the weighted average, indic... | 2f24da412c548c1da53338f2f66d57d18473f798 | 3,596,272 |
def api_all_completion_ids():
""" Get all completion ids
"""
ids = db.get_completions_ids()
return make_response(jsonify(ids), 200) | 3a67ae783ef0e77290fc67638f8c0eefda8ea72e | 3,596,273 |
def data_source_count(context, **kwargs):
"""Count Data Sources filtered by **kwargs.
Uses sqlalchemy "in_" clause for any tuple values
Uses sqlalchemy "like" clause for any string values containing %
"""
return IMPL.data_source_count(context, **kwargs) | 8873a90c98c4bd3150dc29fb57a27481211d7215 | 3,596,274 |
import re
async def handle_webhook(hass, webhook_id, request):
"""Handle webhook callback.
iOS sets the "topic" as part of the payload.
Android does not set a topic but adds headers to the request.
"""
context = hass.data[DOMAIN]["context"]
try:
message = await request.json()
exc... | f453e2975dadd06f1f24924a0826aa755549c064 | 3,596,276 |
import re
def identify_all_potential_shifts(mut_desc, chain_sequence,allowed_shifts):
"""
identify all potential shifts
"""
md_re=r'(?P<wt>[A-Z])(?P<pos>[0-9]+)(?P<mut>[A-Z\(\)]+)$'
saved_shifts=[]
for shift in allowed_shifts:
proposed_shift=shift
... | 4938a498ed696e590892f701a393d74e5d1786b9 | 3,596,279 |
from bgflow.utils.internal_coordinates import dist, angle, torsion
import torch
def xyz2ic(x, Z_indices, torsion_cut=None):
""" Computes internal coordinates from Cartesian coordinates
Parameters
----------
x : array
Catesian coordinates
Z_indices : array
Internal coordinate index... | c799eabd283bce361ee8bc4ac8faa2cfe79dc30c | 3,596,280 |
import warnings
import scipy
def find_projected_joint_HPDI(samples, weights=None,
coverage_1d_threshold=0.683,
MAP=None,
sort_idx=None, log_posterior=None,
method="interpolate", twosided=True,
... | 0fb0702c6da95926c567681721ce54250a7456b1 | 3,596,281 |
def change_email_address_form(erroneous_form=None):
"""Show a form to change the current user's email address."""
form = erroneous_form if erroneous_form else ChangeEmailAddressForm()
return {
'form': form,
} | 13348646a78e05eb9dc320097d275c206c87c4c9 | 3,596,282 |
def curried(func):
"""
A decorator that converts a multi-parameter function into a set of single-parameter functions
:param func: The function to convert
:return: A curried version of the specified function
"""
def inner(arg):
"""
The inner function that curries the first par... | 5f984b1122f1df2add686478e318560bef5fa758 | 3,596,283 |
from pydantic import BaseModel # noqa: E0611
def unprocessable_entity(data: bytes | str | BaseModel) -> HTTPHandler:
"""Sets status code UNPROCESSABLE_ENTITY and respond with passed data.
Args:
data (bytes | str | BaseModel): to respond with.
"""
return set_unprocessable_entity >> negotiate(... | 74142542c5de1a28d0d0d11c071dcc9ff29162c3 | 3,596,284 |
def make_dataset():
"""Make a dataset with three targets"""
return np.arange(0, 10, 1), np.arange(10, 20, 1) | 6cf231beaf0a514ea36ad49bd5dfc2a73a0d3c88 | 3,596,285 |
def is_valid_ds(s: str) -> bool:
"""Check whether this string is a valid decimal string.
Valid decimal strings must be 16 characters or fewer, and contain only
characters from a limited set.
Parameters
----------
s: str
String to test.
Returns
-------
bool
True if ... | 1beb1b1ab4c24e2f29fb4c22ed0f686f62618a7d | 3,596,286 |
def edit_creel_space(request, slug, space):
"""
Arguments:
- `request`:
- `slug`:
- `space`:
"""
space = get_object_or_404(FN026, creel__slug=slug, space=space)
if request.method == "POST":
form = FN026Form(request.POST, instance=space)
if form.is_valid():
f... | 1bbd591a5f81f204b44bca885dc1e36d92344f7b | 3,596,287 |
def modelformset_factory(model, form=ModelForm, formfield_callback=None,
formset=BaseModelFormSet, extra=1, can_delete=False,
can_order=False, max_num=None, fields=None, exclude=None,
widgets=None, validate_max=False, localized_fields=None,
... | 25b4427da4b4ca094a9d53e57bc4a18925b68fac | 3,596,288 |
def train_model(train, target):
"""
The method creates 5 different learning models.
Then, these 5 models are combined in a voting classifier.
That voting classifier is trained with training data.
Parameters
----------
train: features of training data
target: labels of training data
... | ac9df52455a775c8a9d8861419cf716aeefa7794 | 3,596,289 |
def get_spatial_bounds(gtfs, as_dict=False):
"""
Parameters
----------
gtfs
Returns
-------
min_lon: float
max_lon: float
min_lat: float
max_lat: float
"""
stats = get_stats(gtfs)
lon_min = stats['lon_min']
lon_max = stats['lon_max']
lat_min = stats['lat_min'... | cd9ae8a127fa2bf2293ddefd7aa757403295ced7 | 3,596,290 |
def image_fetch_fixture(image, name, scope='module'):
"""
Create a fixture to fetch an image.
"""
@pytest.fixture(name=name, scope=scope)
def fixture(docker_helper):
return docker_helper.images.fetch(image)
return fixture | 1466f4633c264263f7019f941b077cd4a78f56e0 | 3,596,291 |
def issue_dictionary_from(column, issue) -> dict:
"""Map issue to dictionary with field names."""
return {
"project column": column.name,
"issue title": issue.title,
"issue description": f"{issue.body}\n\n---\n\n{issue.html_url}",
"labels": ";".join(
f"'{label.name}'"... | eae9e6cdf7ea3d715ad2e1dc8c31672c8c53762e | 3,596,292 |
def age_bin(age, labels, bins):
""" Return a label for a given age and bin.
Argument notes:
age -- int
labels -- list of strings
bins -- list of tuples, with the first tuple value being
the inclusive lower limit, and the higher tuple
value being the exclusive upper lim... | 9caccc667b55f66824bcf8802161384590cc2a08 | 3,596,293 |
def filter_out_background(voxel_data, black_white, eigen2, eigen3):
"""
Set black_white to true if vessels are darker than the background and to false if
vessels are brighter than the background.
"""
if black_white:
voxel_data[eigen2 < 0] = 0
voxel_data[eigen3 < 0] = 0
else:
... | 48d5bb053c7f77e790be7c8e63e8f3694dca525b | 3,596,294 |
def allocation_taoyuandahanriver_agriwater():
"""
Real Name: Allocation TaoYuanDaHanRiver AgriWater
Original Eqn: IF THEN ELSE( ShiMen Reservoir Depth>=ShiMenReservoir Operation Rule Lower Limit , Water Right TaoYuanDaHanRiver AgriWater, IF THEN ELSE( ShiMen Reservoir Depth>=ShiMenReservoir Operation Rule L... | 54819970ef89476c9677853f81974635039e3846 | 3,596,295 |
def load_configuration( filename ):
"""
Load configuration from a file.
@param filename The name of the file where the configuration is stored
@return A populated Configuration object
"""
try:
config = Configuration( filename )
except VerificationError:
retur... | 86e24e20917986644bafed2467d886ff71b0bd57 | 3,596,296 |
def list_endpoint_security_template_command(client: Client) -> CommandResults:
"""Retrieve a list of all endpoint security templates.
Args:
client (Client): Cymulate client.
Returns:
CommandResults: A CommandResults object that is then passed to 'return_results',
co... | c6527bac1377d02aae85138cc3512047c62277ad | 3,596,297 |
def svdvals(a, overwrite_a=False):
"""Compute singular values of a matrix.
Parameters
----------
a : array, shape (M, N)
Matrix to decompose
overwrite_a : boolean
Whether data in a is overwritten (may improve performance)
Returns
-------
s: array, shape (K,)
Th... | ab4481ff1ccae9957ba47bb16306f0991aa36fa2 | 3,596,299 |
import torch
def pseudolabel_detection_discard_empty(preds, confidence_threshold):
"""
Input:
preds (List): List of len batch_size. Each entry is a dict containing
the keys 'boxes', 'labels', 'scores', and 'losses'
('losses' is empty)
confidence_thre... | 430b5f93b61c650e0de6706cac07fb6875497283 | 3,596,300 |
def nose_on_mask(mask, side, shape):
"""
Return mask that gets the nose shape
:param mask:
:param side:
:param shape:
:return:
"""
points = [shape[i] for i in side]
points = np.array(points, dtype=np.int32)
mask = cv2.fillConvexPoly(mask, points, 255)
return mask | 6c4964c97189797308667257965cf336dca05762 | 3,596,301 |
def list_intersect(first, second):
"""
Returns elements found in first that are in second
:param first:
:param second:
:return:
"""
second = set(second)
return [item for item in first if item in second] | 74cf1fc791a57c299f7fcf2369c105d68bda772e | 3,596,302 |
def process_covid_csv_data(covid_csv_data: list) -> tuple:
"""Function takes a list of data from an argument called covid csv data,
and returns three variables; the number of cases in the last 7 days,
the current number of hospital cases and the cumulative number of deaths,
as contained in the given csv... | 1fd7937656d25072aaba9a0cbf0ab16919f91b38 | 3,596,303 |
import json
def vroom():
"""
Compute the vroom request on the server.
:Example:
/vroom /path/to/json
/vroom?malus=x /path/to/json
malus has to be a float greater than 0
"""
global MALUS
data = request.get_json()
if ru.json_is_ok(data):
MALUS = request.args.get('malus'... | 8f0fd737a202d85d39cba26f7e103327651213c0 | 3,596,304 |
def lstm_forward(xs, w, u, b, h_n1=None, c_n1=None):
"""
Computes the forward pass for a long short term memory layer.
ref: https://blog.aidangomez.ca/2016/04/17/Backpropogating-an-LSTM-A-Numerical-Example/
The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N
examples, where each ... | 69acf357086c7fd519cb5e662481838c47f2bd22 | 3,596,305 |
def simulate_violence_reduction_plan():
"""
Simulate the violence reduction plan over five years, assuming
a 10% annual reduction in homicides. This calculates:
1. The number of lives saved.
2. The annual plan costs, assuming a funding level of $30K per homicide.
3. The added tax revenue f... | 3db93f7569fb148168cee4559b884e16fb3b7324 | 3,596,306 |
import io
import base64
def image_file_to_b64(image_file: io.BytesIO) -> bytes:
"""
Encodes an image file as Base64.
To obtain the stringified Base64 version of the image,
you can convert the output like so:
````python
image_file_to_b64(my_image_file).decode()
````
Arguments:
... | 2606f21fca825ea22c06f6372576110c64dc511c | 3,596,307 |
def _resolve_placeholder_2(name, template=None, local_vars=None,
global_vars=None, default=Unspecified):
"""A slightly different version of resolve_placeholder that relies mostly on
the accelerated C resolving stuff.
"""
search_list = [local_vars, template]
search_list += template.s... | f697f4585d7e7f8bee9345685376f9a5a616e0da | 3,596,309 |
def protect_regex_curly_brackets(query: str) -> str:
"""Protects curly brackets coming from regex patterns from interfering with str.format python call.
Example: select regexpr(a, '^[0-9]{4}-[0-9]{2}-[0-9]{2}') --> select regexpr(a, '^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}')
Args:
query (str): Input quer... | 0067134d854b1535bb6f003131918a042828dd03 | 3,596,310 |
def kB(n, width = 7):
"""Get a nicely formatted string for integer n with the suffixes B, kB, MB, GB, TB, PB, EB.
width must be >= 5
Examples:
987B
9.876KB
98.76KB
987.6KB
9.876MB
98.76MB
987.6MB
9.876GB
98.76GB
987.6GB
9.876TB
...
"""
n = int(n)
... | 450bfe8d71f70d0fe47cce03c41bbaf98bb311b1 | 3,596,311 |
def dataclassRepr(obj) -> str:
"""
Provide a culled representation of the given ``dataclass`` instance,
showing only the fields with a non-default value.
"""
attrs = dataclassNonDefaults(obj)
clsName = obj.__class__.__qualname__
kwargs = ', '.join(f'{k}={v!r}' for k, v in attrs.items())
... | 060008f5975b302a827092c1f5ddb6dd96707539 | 3,596,312 |
def search_theme(plot):
"""
>>> search_theme(['get up', 'discussion'])
['loss', 'loss']
"""
plot = ['loss', 'loss']
return plot | 9eb2104ba2f31a0386eccb13a3b1ad15a74f7fe6 | 3,596,313 |
def pad_dataset_bart_inctxt(dataset, padding=1):
""" Pad the dataset. This could be optimized by defining a Dataset class and padding at the batch level, but this is simpler. """
max_enc_l = max(len(x) for x in dataset["input_ids"])
max_l = max(len(x) for x in dataset["decoder_input_ids"])
max_l_reply =... | bc2726ba92f17fda89a6079435bda7191528d556 | 3,596,314 |
from typing import Mapping
def merge_with_functions(*dicts, mergers, factory=dict):
"""Merge 'dicts', using 'mergers'.
Parameters
----------
*dicts
The dictionaries / mappings to merge
mergers
Mapping from keys in 'dicts' to functions. Each function
accepts a list of value... | 96af3ea8f3d713dbb41d9c5b6ab160edaa9dc6ed | 3,596,316 |
def PutFile(message=None, fileName=None):
"""
An put file dialog.
Optionally a `message` and `fileName` can be provided.
::
from fontParts.ui import PutFile
print(PutFile())
"""
return dispatcher["PutFile"](message=message, fileName=fileName) | a929b1c084bffaedce5837f96025c341bae63c9d | 3,596,317 |
import json
def get_pretty_print(json_object):
""" print json """
return json.dumps(json_object, sort_keys=True, indent=4, separators=(',', ': ')) | 2539d3572c260e4b4fe2061d4e3f6112d7ee8dd5 | 3,596,319 |
def get_json_template(entity_types):
"""Return json template for entity types"""
return json_dumps_formatted([
entity_to_template(entity_type, file_format='json')
for entity_type in entity_types
]) | 8b6249aef930c197ddcf6bbd8fa6b31282f49653 | 3,596,320 |
def train_data_idx(train_data) -> pd.DataFrame:
"""
train_data in integer index form. This maps each column into values from 0..n
"""
df = train_data.copy(deep=True) # type: pd.DataFrame
df["a"] = df["a"].map({"a": 0, "b": 1, "c": 2, "d": 3})
df["b"] = df["b"].map({"x": 0, "y": 1, "z": 2})
... | c7a16081b91591b42d51fb733c7069c4af5bc9a8 | 3,596,321 |
def base41_encode(input):
"""Encode an array of bytes to a Base41 string.
input is the array of bytes to encode.
The encoded string is returned.
If input has an odd number of bytes, a TypeError is raised.
"""
rslt = ""
i = 0
while i + 1 < len(input):
x = input[i] + 256 * i... | 46ef331084a9932d8bd7ccf574dd9f5afa9face2 | 3,596,323 |
def get_world_to_view_matrix(mlab_scene):
"""returns the 4x4 matrix that is a concatenation of the modelview transform and
perspective transform. Takes as input an mlab scene object."""
if not isinstance(mlab_scene, MayaviScene):
raise TypeError('argument must be an instance of MayaviScene')
... | be6057246dd7bb4119aefbdda45ee180157cd608 | 3,596,324 |
def make_protein_record(nuc_record):
"""Returns a new SeqRecord with the translated sequence (default table)."""
return SeqRecord(seq = nuc_record.seq.translate(to_stop=True), \
id = "trans_" + nuc_record.id, \
description = "translation of CDS, using default table") | f8ebdcf09264ce5a8ceda4c71d423ffbe9e9854e | 3,596,325 |
def run_sanity_check(config):
"""Runs a simple job that performs some sanity tests, determines
AMBER version, etc.
"""
resource_name = config['resource']
username = config['username']
workdir = config['workdir']
allocation = config['allocation']
##########################... | fbe99313efcecf42a16b3054562006114a15af0a | 3,596,326 |
from typing import Dict
from typing import Tuple
def read_multiscale_params(cfg: Dict[str, dict]) -> Tuple[int, int]:
"""
Returns the multiscale parameters
:param cfg: configuration
:type cfg: dict
:return:
- num_scales: number of scales
- scale_factor: factor by which each coarse... | 8021cc90c4a4740854a92a7d56524d7037e01988 | 3,596,328 |
import copy
def EDA_binning_numeric_column_displaying_bins(dft, target, bins=4, test=""):
"""
This splits the data column into the number of bins specified and returns labels, bins, and dataframe.
Outputs:
labels = the names of the bins
edges = the edges of the bins
dft = the datafram... | 88d4a9db002bb7c53d7417bec2ba2c7ed01dcc27 | 3,596,329 |
def load_ref_system():
""" Returns alpha-d-xylopyranose as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C 1.4893 -0.0425 0.0928
C 0.3596 -0.5545 1.0139
C -0.9836 0.192... | defbf2f14791dbcfeb8bf3b71c2d667edd9abfcc | 3,596,330 |
from typing import Any
def safeStrip(value: Any) -> Any:
"""Strip whitespace from a string value, if value is a string.
Arguments:
value {Any} -- possible string to strip
Returns:
Any -- Stripped string if value was string, else original value.
"""
if isinstance(value, st... | 0b16a89c2e34ad8a1bafe89dd1550a82680075a4 | 3,596,333 |
def filterchain_all(request, app, model, field, foreign_key_app_name,
foreign_key_model_name, foreign_key_field_name, value):
"""Returns filtered results followed by excluded results below."""
model_class = get_model(app, model)
keywords = get_keywords(field, value)
# SECURITY: Make... | 9722066c760555b317870c3ac63bd774b5cedb6e | 3,596,334 |
def cartesian_product_iterator(X):
"""
Iterate over the Cartesian product.
INPUT:
- ``X`` - list or tuple of lists
OUTPUT: iterator over the Cartesian product of the elements of X
EXAMPLES::
sage: list(cartesian_product_iterator([[1,2], ['a','b']]))
[(1, 'a'), (1, 'b'), (... | 3c2f12f36f8e6dac4dd1f8023858066c29b1710c | 3,596,335 |
import time
def timeMS():
"""Gives a count of miliseconds from 1.1.1970.
Returns:
int: Miliseconds form 1.1.1970
"""
return round(time.time() * 1000) | c42a220499c528ecde869e2c74dc383a84c71ea4 | 3,596,336 |
def vqa_schedule(step, warmup_interval, decay_interval,
decay_start, decay_rate):
""" VQA schedule from MCAN """
if step < warmup_interval:
return 1/4
elif step < 2 * warmup_interval:
return 2/4
elif step < 3 * warmup_interval:
return 3/4
elif step >= decay_s... | e54ba330e7eba608491e7e044a66d64e6d623e64 | 3,596,337 |
def get_keywords(project_id):
"""
retrieve the list of keywords for the search
:param project_id: the ID of the current project
:return:
"""
try:
search = es.search(index=project_id, doc_type='all_data', size=1000, scroll='3m')
except IOError:
return Response('no keywords ', ... | b0eae94f4a92d498cb28975db57fa42d951b6af1 | 3,596,339 |
def encode_position(pos, emb_dim=10):
"""The sinusoid position encoding"""
# keep dim 0 for padding token position encoding zero vector
if pos == 0:
return np.zeros(emb_dim)
position_enc = np.array(
[pos / np.power(10000, 2 * (j // 2) / emb_dim) for j in range(emb_dim)])
# apply si... | cd107a0b1eb3024513054c6390fff0f5fc3638ee | 3,596,341 |
def maxpool(inputs, kernel_size, name, padding = 'SAME'):
"""
Max pooling layer:
----------
Args:
inputs: Tensor, [batch_size, height, width, channels]
kernel_size: List, filter size [height, width]
name: String, scope name
stride_size: List, convolution stide [height, wi... | 22bbb8679490a68a8b61f5b94399f41fb7b8213a | 3,596,344 |
from typing import Optional
from typing import Tuple
def create_dl(df:pd.DataFrame, b:Optional[np.array]=None, train_size:float=0.8, random_state=None, bs:int=128)\
-> Tuple[DataBunch, MaxAbsScaler, StandardScaler]:
"""
Take dataframe and split into train, test, val (optional)
and convert to Fastai da... | 2b806995f1399b02caf1d499f3a1f8e92cba535e | 3,596,346 |
import torch
def predict(data_loader, encoder, dfc, device='cpu', encoder_type = 'vae'):
"""
Args:
data_loader:
encoder:
dfc:
device:
encoder_type:
Returns:
feature, label
"""
features = []
labels = []
encoder.eval()
dfc.eval()
wit... | 1369ebb5d24a14371da6af5765b741cff2d42d35 | 3,596,348 |
def simulate(model, simulator, ti_controls, sampling_times, model_parameters):
""" fixing the control variables """
# time-invariant
model.beta.fix(model_parameters[0])
model.tau.fix(max(sampling_times))
model.ca[0].fix(ti_controls[0])
# no time-varying control for this example
""" ensuring... | fd39ac6094479ef3b140261e2233ed3ec85d879e | 3,596,349 |
def get_image_type(data):
"""Return a tuple of (content type, extension) for the image data."""
if data[:2] == "\xff\xd8":
return ("image/jpeg", ".jpg")
return ("image/unknown", ".bin") | 1677cb375a7b405b8a229f1246bdb27ed36dc654 | 3,596,350 |
from datetime import datetime
def arg_startdate(args):
"""Parse the startdate from the command line."""
startdate = datetime.date.today().strftime('%Y%m%d')
if len(args) >= 1 and is_int(args[0]) and int(args[0]) > 0:
startdate = args[0]
dbg_print(1, "Startdate: %s" % startdate)
return star... | 4dc3388d4b17aa53a2119600e300461dc96d4dc2 | 3,596,351 |
def random_zoom(x, zoom_range, row_axis=1, col_axis=2, channel_axis=0,
fill_mode='nearest', cval=0., interpolation_order=1):
"""Performs a random spatial zoom of a Numpy image tensor.
# Arguments
x: Input tensor. Must be 3D.
zoom_range: Tuple of floats; zoom range for width and ... | 9d30c4f396d6618748b5456303826ddeb006052f | 3,596,352 |
def rotateMask(image_mask, angle = None, reshape = True, new_width = None, new_height = None):
"""Rotate a mask.
Input:
image_mask -- 2D binary mask to be rotated.
angle -- float, rotation angle in degrees.
reshape -- Boolean, whether to give a different shape for the output.
... | 0e970c2bbe59158996276fdf360b394aa1441d11 | 3,596,353 |
def parse_conjugations(group):
"""
Parse conjugations in a word group.
:param group: string of a word group
:return: list of parsed conjugations
"""
return list(
map(
lambda x: x.split('/')[0].strip(),
group.split(' – ')
)
) | 0a1eca118a1f194a51a889a0fe30fe72488d6ada | 3,596,354 |
def datagram_large():
"""Returns a big datagram, along with a verification function."""
dg = core.Datagram()
for x in range(2000000):
dg.add_uint32(x)
dg.add_string('the magic words are squeamish ossifrage')
def readback_function(dgi):
assert dgi.get_remaining_size() > 0
... | 81942c76657f186baa1780a11d5ad83faa499470 | 3,596,355 |
from typing import Callable
def http_code(func: Callable) -> Callable:
"""
Decorator to generate HTTP status response code automatically
according to the key ``code`` in json.
:param func: Your view function.
"""
@wraps(func)
def wrapper(*args, **kwds):
result = func(*args, **kw... | 193d7c07f61ffaee1e21beb811d5a1ca47c05896 | 3,596,358 |
def figletscript(txt):
""" FigletNeatWriting Text """
f = Figlet(font='slscript')
return f'{f.renderText(txt)}' | e6181c17ab536af045a91a15619d8281b2ab68bd | 3,596,359 |
def get_batched_tensor(dataset):
"""Gets the tensor representing a single batch from a `tf.data.Dataset`.
Batch and epoch options are passed on the command line.
Args:
dataset: A `tf.data.Dataset` containing single examples.
Returns:
A dict of tensors, which contains the concatenated features from ea... | e6e33922dff6a88ef3f0e1cb3fa30af23c560e3b | 3,596,360 |
import ast
def check_and_compile(expression_string):
"""Parse a string into an expression, check that it has no illegal
nodes, importantly including function calls and attribute access.
If it passes, compile it, and return a wrapped function which calls
eval ensuring that globals is empty, including __builtins__"... | 4a54df3f3d0e13a2ca21edd5de8bf7a3002d55fb | 3,596,361 |
def get_data(dt_id, nrows=10):
"""
取得预览数据
:param dt_id: 数据表编号
:param nrows: 读取行数
"""
ds_conf = get_data_source()
dt_conf = get_data_table(dt_id)
data_type = ds_conf.type
data_uri = ds_conf.uri
if data_type == 'csv':
data_uri += dt_conf.type + '.csv'
df = read_data(dat... | 37116c8503c06b5a5c5b72cb58492af0f44185dc | 3,596,363 |
def load_dataset(train_test_all):
"""Loads 20 News Groups data set."""
# The selection of categories is optional. If empty we will obtain samples from all categories
categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
# subset can be: train, test or all
data_set = fet... | a3b943ade12215601f7c7f9f5b1d6b126d261936 | 3,596,364 |
def at_left_edge(ball, screen_width):
""" (int, int) -> bool
Handle ball when it hits the left edge of the screen
"""
if ball.xcor() < -screen_width / 2:
return True
else:
return False | 96f19bb503ae24da9d7371f938479e745f84ed0d | 3,596,365 |
import inspect
def test_types_and_optional_in_docstring():
"""Parse optional types in docstring."""
def f(x=1, y=None):
"""
The types are written in the docstring.
Parameters
----------
x : int
X value.
y : int, optional
Y value.
... | 60fdb6659abf690f37a88ca0c2c4d6825e33f632 | 3,596,366 |
def backprojection_hsv(image, m, bins=16, threshold=0.4):
"""Create a fire color mask using histogram backprojection in the HSV color space.
References: Swain and Ballard (1991); Wirth and Zaremba (2010).
Parameters
----------
image : numpy.ndarray
OOriginal image (RGB).
m : numpy.ndarr... | da014eb481bb63fb41b9d9452f900cfca0d269ff | 3,596,367 |
def update_license_plate(person_id: str = None, license_plate: str = None):
"""
Updates a person's license plate.
:param person_id: The numeric ID of the person.
:param license_plate: The person's license plate.
:returns: String containing xml or an lxml element.
"""
return get_anonymous(
... | 6a4b32912637c714af72acd9aa3a0894c9e0c0e1 | 3,596,368 |
def get_mmat_name(mmat):
"""
Return the maturity name of the given mba_maturity_t.
"""
for value, name in MMAT:
if value == mmat:
return name
return None | 71e482f5fef54858b6f2b32c5f9ddf1846705488 | 3,596,369 |
def is_int(obj) -> bool:
"""Check whether object is int, numpy.int32, or numpy.int64."""
if isinstance(obj, (int, np.int32, np.int64)):
return True
return False | e3348f27b424a66eebe548274560e3a46ae8204b | 3,596,370 |
def _paradox_follower_url_from_main(url, ident):
"""Create a usable URL."""
url = sa_url.make_url(url)
if all(
(
str(url).casefold().startswith("paradox+pyodbc://"),
any(("dsn" in str(url).casefold(), "test" in str(url).casefold())),
)
):
return url
r... | b90b0a3f2474ead37e6e6d4d4ea90da705e94d4a | 3,596,371 |
def register():
""" Show register form """
session.clear()
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
cpassword = request.form.get("confirm_password")
if not username:
flash("Must provide a User... | 8c2f87aae621aa2b14893253b2d5a5fc647b5fb4 | 3,596,372 |
def get_param(param):
"""Read parameter and convert to proper type"""
pname, ptype, pvalue = param.split(',')
pvalue = get_type(ptype, pvalue)
return pname, ptype, pvalue | a21ad9fd968cfdea505eeca9879fa7b5a1a2437f | 3,596,374 |
import warnings
def preprocess_onnx(onnx_model):
"""Modify onnx model to match with TensorRT plugins in mmcv.
There are some conflict between onnx node definition and TensorRT limit.
This function perform preprocess on the onnx model to solve the conflicts.
For example, onnx `attribute` is loaded in ... | 90a018535d8f3d81711b07f24d583ce60d5310c2 | 3,596,375 |
def get_trunk(trunk_name):
"""Retrieve the pretrained network trunk and channel counts"""
if trunk_name == 'efficientnet_b4':
backbone = EfficientNet_B4(pretrained=True)
s2_ch = 24
s4_ch = 32
high_level_ch = 1792
elif trunk_name == 'efficientnet_b0':
backbone = Effici... | b73742eb0496b8f4ff9dad788a6fd13ecc15b4ce | 3,596,376 |
def read_thresholds(path):
"""
Read the p-value thresholds for each tumour type
"""
thresholds = {}
with open(path) as f:
for line in f:
line = line.strip()
line = line.split('\t')
tumour = line[0]
threshold = float(line[1])
thresh... | 2615cd3b38e4ce1d80baacd06cf955895f0984ee | 3,596,377 |
from typing import Iterable
def _sample_parameters(param_grid):
"""
Given a param_grid with callables and lists, execute callables and sample lists to return of random combination
of parameters.
Parameters
----------
param_grid: dict
Parameter configurations.
Example::
... | cb9516e75058969ff4723b0a1ba49201ddc20a3d | 3,596,378 |
from operator import lt
def corrupt(offset_standard_deviation: float,
multiplier_standard_deviation: float,
noise_standard_deviation: lt.LabeledTensor,
labeled_tensor: str = None,
name=None) -> lt.LabeledTensor:
"""Corrupt the given image tensor with pseudo-random noi... | d0d664fff4a8f8d453a219430ffc07c5fe4faa31 | 3,596,379 |
import re
def path_parameter(payload, **kwargs):
"""Extract container name from the path parameters
"""
path = urlsplit(payload.uri).path
if payload.method == "DELETE":
match = re.match(r"^/v\d.\d{2}/[^/]+/([a-zA-Z0-9/:_.-]+)/?", path)
else:
match = re.match(
r"^/v\d.\d... | db69ae3ab48d75c0891dd6a4741abb3ef0cf2499 | 3,596,380 |
def _one_contains_other(s1, s2):
"""
Whether one set contains the other
"""
return min(len(s1), len(s2)) == len(s1 & s2) | f7313cc0cbee823e39c30da22455e228162555be | 3,596,381 |
def get_sharding_entity_class(hashid):
"""
@param hashid: hashid
@type hashid: int
@rtype AbsClientUserAuth
"""
if hashid not in ENTITY_CLASS_DICT:
class_name, table_name = get_class_name_and_table_name(hashid)
cls = type(class_name, (SpiderResult,),
{'__table... | 5a459d048753f29167c179424d7a72c7994b1a06 | 3,596,382 |
def _get_phred_quality(record) :
"""Extract PHRED qualities from a SeqRecord's letter_annotations (PRIVATE).
If there are no PHRED qualities, but there are Solexa qualities, those are
used instead after conversion.
"""
try :
return record.letter_annotations["phred_quality"]
except KeyEr... | 9fddd6fcc3171298dcb952fa6d3eeb2ec87b747f | 3,596,383 |
def full_connected(x, weight_shape, initializer):
""" fully connected layer
- weight_shape: input size, output size
"""
weight = tf.Variable(initializer(shape=weight_shape))
bias = tf.Variable(tf.zeros([weight_shape[-1]]), dtype=tf.float32)
return tf.add(tf.matmul(x, weight), bias) | fdda062f7109998a96507026c6b363410ac9ec35 | 3,596,384 |
def get_manager():
""" Try to locate a ``CubeManager`` on the Flask app which is currently
processing a request. This will only work inside the request cycle. """
return current_app.extensions['babbage'] | a3150f8e632b1b4291cc9ce41ba170b750c6d6aa | 3,596,385 |
import psutil
def get_available_cpu_count() -> int:
"""Determine the count of available CPUs.
:return: The count of available CPUs
:rtype: int
"""
os_type = get_os()
if os_type in (OperatingSystem.Linux, OperatingSystem.Windows,):
return len(psutil.Process().cpu_affinity())
else:... | ee6d807d4282330722ab60319f1b0cdea4c75b1f | 3,596,387 |
import sqlite3
def get_observed_data(db, table, startYear=False, endYear=False, noisy=False):
"""
Extract the tidal data from the SQLite database for a given station.
Specify the database (db), the table name (table) which needs to be the
short name version of the station of interest.
Optionally ... | 29962b4d795d501ca1bf50de6726b61ce6d7e00a | 3,596,388 |
def linear_regression_line(mb):
"""
Given the output of ``linear_regression()`` function, or provided with
a tuple of ``(m, b)``, where ``m`` is the slope and ``b`` is the intercept,
``inear_regression_line()`` returns a function that calculates y values
based on given x values.
Args:
m... | dbc61ffafe603e8e6ec21f87debc170e3b6eb289 | 3,596,389 |
from typing import Optional
def create(env_name: str,
episode_length: int = 1000,
action_repeat: int = 1,
auto_reset: bool = True,
batch_size: Optional[int] = None,
**kwargs) -> Env:
"""Creates an Env with a specified brax system."""
env = _envs[env_name](**k... | 1d7e8bf147843799f01e7a894b86fce74ca86da7 | 3,596,390 |
def values(df, field, **kwargs):
"""
Return values from a specific field of the data frame within a given time extent
Args:
df (pd.DataFrame): The exported TAP tool data
field (str): The field representing the column name
Returns:
np.ndarray: An array of the time-specified valu... | 6416c18ba3891a133c9ed0d487ca4b82d7a5291d | 3,596,391 |
def render_or_404(template_name, dictionary=None, context_instance=None):
"""Helper for testing template existence."""
try:
return render_to_response(template_name, dictionary, context_instance)
except TemplateDoesNotExist:
raise Http404 | ab1354978a792bbf0a2e31d6fea636ce71226595 | 3,596,392 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.