content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def standardize(train_data, test_data):
"""
Standardize Data Set
"""
train_mean = train_data.mean()
train_std = train_data.std()
train_data = (train_data - train_mean) / train_std
test_data = (test_data - train_mean) / train_std
return train_data, test_data | b66a363cd37f7ebc2accd021866b7d34c415f528 | 74,133 |
import torch
def spread_feature(container, learned_uv, feature, mask1c):
"""
:param container: B,C,R,R
:param learned_uv: B,2,H,W
:param feature: B,C,H,W aligned with latent uv map
:param mask1c: B,1,H,W used to mask latent uv and feature
:return: container
"""
assert float(mask1c.max(... | 38f7602124792bf3f0e3395cd8952aec428ab43e | 74,134 |
def verify_working_dir(pkg):
"""Verify if a package working directory has uncommitted changes or is
outdated and ask the user what to do. Return True if it's ok to continue.
"""
if is_uncommitted(pkg):
if not utils.ask_yn("""\
Package working directory %s has uncommitted changes that will not b... | 514cbd92220c7c62bc01f4162b03e23054311a6a | 74,136 |
def snap_to_lines(fixation_sequence, text_block, method="warp", **kwargs):
"""
Given a `eyekit.fixation.FixationSequence` and `eyekit.text.TextBlock`,
snap each fixation to the line that it most likely belongs to, eliminating
any y-axis variation or drift. Operates directly on the sequence and does
... | 67c4a6cc70af352654396a921a85c2c6cfc0b93c | 74,137 |
def get_total_paper(boxes):
"""Get all paper needed for a list of boxes"""
return sum(get_box_paper(b) for b in boxes) | 92364ace778c777f85b0ad62c5ded154657d2e41 | 74,138 |
def expected_wrt_occupancy(value, occupancy, miss=0.):
"""
:param value: (N, C, D, H, W) / float
:param occupancy: (N, C, D, H, W)
:param miss: float / (N, C, D, H, W)
:return:
"""
return expected_wrt_prob(value, occupancy_to_prob(occupancy), miss) | 357a2d76d576d4a877c9bff8172667d00e259102 | 74,139 |
import tqdm
def download_url(url, destination=None, progress_bar=True):
"""Download a URL to a local file.
Parameters
----------
url : str
The URL to download.
destination : str, None
The destination of the file. If None is given the file is saved to a temporary directory.
pro... | 12b00d4eb426d2441fdfa419a1ae3c706ff6e783 | 74,140 |
def get_app_runtime(yaml_paths):
"""Examines all app's yamls making sure they specify single runtime.
Raises:
ValueError if multiple (or unknown) runtimes are specified.
"""
runtimes = sorted(set(get_module_runtime(p) for p in yaml_paths))
if len(runtimes) != 1:
raise ValueError('Expecting single run... | 6fa6c19dabcfdc67ea81fcd44275c17a28a0eef0 | 74,141 |
from typing import Optional
def bg(col=None) -> Optional[int]:
"""
Get or set the default background color for space objects.
"""
global BACKGROUND_COLOR
if col is None:
return BACKGROUND_COLOR
else:
BACKGROUND_COLOR = int(col)
return BACKGROUND_COLOR | 90caac2fb037e3d561266179c8d97aca817a624d | 74,142 |
from typing import Tuple
def pink_spatial_transform(
img: np.ndarray, transform: Tuple[np.int8, np.float32], reverse: bool = False
) -> np.ndarray:
"""Applying the PINK spatial transformation to an image
Arguments:
img {np.ndarray} -- Image to spatially transform
transform {Tuple[np.i... | 53862b1d2176fddb1858dec0adda1131c43a090f | 74,143 |
import pandas
from typing import Tuple
from typing import List
def gc_skew_shift_detection(
data: "pandas.DataFrame",
) -> Tuple[List[int], int]:
"""Function to detect GC skew shift.
Parameters:
-----------
data : pandas.DataFrame
For columns table with the GC skew.
Returns:
----... | 26e7c49cecb09f40d8bbfb0a1ff6980d18e19108 | 74,144 |
def proposal_layer_fixate(rpn_bbox_pred, im_info, anchors):
"""
Simply returns every single RoI; LRP-HAI later decides
which are forwarded to the class-specific module.
"""
# Get the bounding boxes
batch_sz, height, width = rpn_bbox_pred.shape[0: 3]
rpn_bbox_pred = rpn_bbox_pred.reshape((-1... | 4e3030721f9b39faddad40fce80b98c11421d84e | 74,145 |
from typing import Concatenate
def dense_block(x, nb_layers, nb_channels, growth_rate, dropout_rate=None, bottleneck=False, weight_decay=1e-4):
"""
Creates a dense block and concatenates inputs
"""
x_list = [x]
for i in range(nb_layers):
cb = convolution_block(x, growth_rate, dropout_... | f15dcb9aeb3d6e46ebf6bf70c090fd7b9c9a6383 | 74,146 |
def corr(data1, data2, max_lag):
"""Calculate correlation of two time series for a range
of lags between them.
Uses pandas.Series.corr() to calculate correlation between
two columns of data (i.e. a pandas.Series), with data2
shifted relative to data1 by a range of lags up to max_lag.
:param da... | d1765bd43c93b37494456ee7dac0bdf2c6a37b36 | 74,147 |
def addingbookmark(userkey):
""" Add the bookmark from form submit by /add """
tags = get_cached_tags(userkey)
if request.method == 'POST':
bookmark = updatebookmark(userkey)
if not bookmark:
return redirect(url_for('addbookmark', userkey=userkey, message='No url provided', tags... | ff9df2eff11ba0b1fea80da16595e4bc8a32eb93 | 74,149 |
def p_independent(N_hypercolumns, units_per_hypercolumn,
X, low_noise=10e-10, normalize=True):
"""
This and that
"""
p = np.zeros((N_hypercolumns, units_per_hypercolumn))
for i in range(units_per_hypercolumn):
p[:, i] = np.sum(X == i, axis=0)
if normalize:
p ... | 1abc4e3a53b6b9e6069900bada1254b03294175f | 74,150 |
import re
import itertools
import numpy
def read_cst_ascii(source):
"""
Reads data from ASCII data file, exported by CST Microwave Studio. Since
CST can put multiple signals into a single file, this function returns
a hash of signals, where signal names are keys.
"""
if type(source) is str:
... | fb4557c2065b8cbc16f498b3786cc63a1509d31a | 74,152 |
import struct
def check_equiv(ins):
"""Checks whether this instruction can be changed with an equivalent one.
'cbytes' is changed if an equivalent instrucion does exist."""
opcode = ord(ins.bytes[ins.opc_off])
modrm = ord(ins.bytes[ins.modrm_off])
# check for equivalent instructions when both op... | f316b11166e7d9ee152dbc4134477e1c8ccd82ad | 74,156 |
def wkt_to_dataframe(wkt_list, geom_name='geometry'):
"""Convert list of WKT strings to a DataFrame."""
df = pd.DataFrame({'wkt': wkt_list})
df[geom_name] = df['wkt'].apply(wkt.loads)
return df | 6ba1e2a6f253a84d0e31913d8b87c70ca8771b84 | 74,157 |
def fetch_eeprom():
"""
See TRM 3.4.2, 3.4,3.
This function dynamically determines how much data to read for c2 eeprom data and downloads
the eeprom iic file.
"""
assert f.isopen()
# fetch 1st 8 bytes
prom=get_eeprom(0,8)
if prom[0] == '\xc0':
return prom # c0 blocks are 8 bytes long
if prom[0] != '... | 45431548d66eacd0df1d317785243ec127ac91f9 | 74,158 |
def run_testsets(testsets):
""" Execute a set of tests, using given TestSet list input """
request_handle = None
total_results = list()
for testset in testsets:
run_testset(testset, request_handle=request_handle, test_results=total_results)
return total_results | e3daf0a85cdb44e4a22bbf8230c7d4b428f45799 | 74,159 |
def init(id, cfg):
"""Previous version init function.
..note:: This function is still supported for backwards compatibility when
the init_standard function is missing. When init_standard is
present this function SHOULD be omitted to avoid confusion to the
reader.
"""
... | 8076f694908bbe8edb8e0297d62a35b26fc1afcb | 74,160 |
import math
def radiacion_solar_onda_larga(tmax, tmin, p_vapor_real, r_solar, r_solar_cielo_despejado):
"""
calcula la radiación neta de onda larga saliente en MJ/m2 y día
param: tmax : temperatura máxima
param: tmin : temperatura mínima
param: p_vapor_real ... | 5404500ff08e5a886f3e000fd8d301faec78cff7 | 74,161 |
def requirements(filename):
"""Reads requirements from a file."""
with open(filename) as f:
return [x.strip() for x in f.readlines() if x.strip()] | 81e5fa3d2a11b9152be6f55ab879b1875fd0b07d | 74,162 |
import socket
def test_internet(host="8.8.8.8", port=53, timeout=3):
"""Returns True if internet is connected
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host,... | b4d87a122028c398c2a55dc37faa359e930a5dc1 | 74,164 |
def basic_block(inputs, filters, training, strides, data_format):
"""Build basic block for ResNet."""
shortcut = inputs
inputs = batch_norm(inputs, training, data_format)
inputs = tf.nn.relu(inputs)
chn_axis = 1 if data_format == 'channels_first' else 3
in_filters = inputs.get_shape()[chn_axis]... | b10bb19cfacda7fb1c161bd463163a882bfa3e51 | 74,165 |
def branch_uptodate(branch, true_on_missing_origin=True):
"""Return True is branch is up to date with origin, otherwise False,
also returns True if no remote defined"""
if branch['upstream']:
if branch['ahead'] or branch['behind']:
return False
return True
if true_on_missing_... | 2c0db03ea469b6f75e94ab6a73ace360e73948a3 | 74,166 |
import json
def sync_issue_status_server(erpnext_support_user, erpnext_support_issues, bench_site):
"""
returns a dict of support issue statuses
{
"erpnext_support_issue_name_1": [{status}]
"erpnext_support_issue_name_2": [{status}]
}
"""
authenticate_erpnext_support_user(erpnext_support_user)
issues... | 6814f39680773b807504007b6d96ca228e1b10e1 | 74,167 |
import hashlib
import base64
def encode(text):
"""[summary]
Base64 Encoder.
Args:
text (str): String to be encoded.
Returns:
str: base64.urlsafe_b64encode
"""
fill_up = hashlib.blake2s(f"{text}".encode("utf-8"), digest_size=8).hexdigest()
text = f"{ text }::{ fill_up }"
... | f9da7bf0ba9455fd37277c8617332d78b11223bd | 74,168 |
def extra_datefield(_, title, code, doc, sidebar_items):
"""
A Basic Line Chart using QuerySet.extra() with DateField
--------------------------------------------------------
This chart plots sales quantities per day from the first book store.
We're using QuerySet.extra() to format the date value di... | 35406b1a165b700301511a9aed2960e6761349b2 | 74,169 |
from typing import List
from typing import Set
def validate_dataframe(df: pd.DataFrame, columns: List[str]) -> Set[str]:
"""Validates that the input dataframe has all given columns, that the
'time' column has a datetime type, a 'month' column parsed as 1-12 or Jan-Dec,
and that all other columns are float... | d689946c0eeb8f65af87d74c9e51b38efa4f6c08 | 74,170 |
def get_progress_groups(qt_viewer):
"""Given viewer, find all QtProgressBarGroups in activity dialog"""
return qt_viewer.window()._activity_dialog.findChildren(QtProgressBarGroup) | d78338e3face60705cfc2003dae58992c28282cf | 74,171 |
def multiply_ith_dimension(Pi, i, X):
"""If Pi is a matrix, multiply Pi times the ith dimension of X and return"""
X = X.swapaxes(0, i)
shape = X.shape
X = X.reshape((shape[0], -1))
# iterate forward using Pi
X = Pi @ X
# reverse steps
X = X.reshape((Pi.shape[0], *shape[1:]))
retur... | 98edc89389910d4361232350b0ad440fd785f74a | 74,173 |
import six
import socket
import contextlib
def is_port_open(port_or_url, timeout=1):
"""Check if TCP port is open."""
if isinstance(port_or_url, six.string_types):
url = six.moves.urllib.parse.urlparse(port_or_url)
port = url.port
host = url.hostname
else:
port = port_or_ur... | ad8d6e80cc2eaee6a5955f4f5bc0e69cac8f60b2 | 74,174 |
import logging
def getRootLogger(logrNameSuffix, handlerList=[], formatter=None, rootRank=0):
"""
Returns logger for logging events from only the MPI process with
rank rootRank.
:type logrNameSuffix: str
:param logrNameSuffix: Name of returned logger is "root." + logrNameSuffix.
:type handler... | 9231af80869a7997f9a88d0da777b95d5e59152b | 74,175 |
def merge_two_dicts(x, y):
"""Given two dicts, merge them."""
z = x.copy()
z.update(y)
return z | d2f6b0afb82b88e8a27fb4204016ddde817bf5ed | 74,176 |
import socket
def find_free_port():
"""Find a free port on the localhost.
Adapted from https://stackoverflow.com/a/45690594
"""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("localhost", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
... | faedf9ca89fb68ec045c05b30a9ea0f25e730437 | 74,177 |
def validate_name(*args):
"""validate_name(char name) -> char"""
return _idaapi.validate_name(*args) | b045a03c94fed4395eab2ba662ba57dbf890d587 | 74,178 |
import re
def clean_node(config, ctx, category_data, value, template_fn=None):
"""Expands the node to text, cleaning up any HTML and duplicate spaces.
This is intended for expanding things like glosses for a single sense."""
assert isinstance(config, WiktionaryConfig)
assert isinstance(ctx, Wtp)
a... | 5b10d105173ed8b3d140176d69d592aca9f0df81 | 74,179 |
def BBHBonds(allPos, pepAccInds, pepDonInds, distCut = 2.1, angCut = 30.0):
"""Finds H bonds between two list of acceptors and donors. Intended for just peptide backbone.
Inputs:
allPos - full position array for trajectory frame
pepAccInds - global indics of peptide acceptors
pepDonInds - global i... | ddca9baf77911b94bc1e1bcfe88407162d7c47fc | 74,180 |
def is_possible_cat(arrow_type: DataType, /) -> bool:
"""Check if data type is possibly categorical."""
return (is_boolean(arrow_type) or
is_string(arrow_type) or
is_num(arrow_type)) | 1b9b00e8432a2c7ae01b5e87e946a4435d215cd8 | 74,181 |
def lte(value):
"""Matches any value that is less than or equal to given value (`<=`)"""
return Lte(value) | cbb61ff84a2658fad64960b27c67a9037e37bc75 | 74,183 |
def should_sync_locations(last_sync, location_db):
"""
Determine if any locations (already filtered to be relevant
to this user) require syncing.
"""
if not last_sync or not last_sync.date:
return True
for location in location_db.by_id.values():
if not location.last_modified or ... | d61612473f2842f69628d273198549a55abf66be | 74,185 |
from typing import Tuple
import re
def parse_prefixed_json(data: str) -> Tuple[str, str]:
"""Find the potential JSON body from `data`.
Sometimes the JSON body is prefixed with a XSSI magic string, specific to the server.
Return a tuple (data prefix, actual JSON body).
"""
matches = re.findall(PR... | b6a7639edcd0f7e3086c44f58c416b3d232a5648 | 74,186 |
import tokenize
async def index(request):
"""Endpoint, that does entity recognition."""
text = request['data']['text']
model = request.app['model']
if text:
result = model.analyze(text, tokenizer=tokenize)
else:
result = {}
return web.json_response(result) | d0730f6b750d15d05a6501e86aa5b472c3d32bad | 74,187 |
def _runs_ending_in_block_range(block, mask):
"""Return the runs that end within the block range and may start before
"""
return [
run for run in _get_black_runs(mask)
if block.start <= run.end and run.end <= block.end
] | 47a9cc109c9fa571df2a56d935eee07592efdf51 | 74,188 |
def tfidf(termFrequency):
""" The student must code this. """
gf = np.sum(termFrequency,axis=1).astype(float)
p = (termFrequency.T/gf).T
g = np.sum(p*np.log(p+1)/np.log(len(p[0,:])),axis=1) + 1
a = (np.log(termFrequency + 1).T*g).T
return a | baa00755682ebca54c48a536d4d04b48bac2b42a | 74,189 |
def local_patch_f(arr, patch_size=7, f=np.mean):
"""local_patch_f(arr, patch_size=7, f=np.mean)
Describe local patches around each value of the array
Parameters
----------
arr : ndarray
The input data.
patch_size : int
The size :math:`w` of the patches.
f : function
... | b16f2c40f83decd1609185e05a6a85f72fce05d3 | 74,190 |
import scipy
def interpolate_precision_recall(precision, recall, nSamples=11):
"""
Interpolates precision as a function of recall p_{interp}(r)
Reduce wiggles in average precision curve by taking interpolated values
along a uniform sample.
References:
http://en.wikipedia.org/wiki/Informa... | 34da282092666a2a6e90935b9242914ac41dfdf3 | 74,191 |
def get_feature_dimensions(parameters):
""" Returns dimensions (`int`s) of all node features.
"""
n_atom_types = len(parameters["atom_types"])
n_formal_charge = len(parameters["formal_charge"])
n_numh = int(
not parameters["use_explicit_H"]
and not parameters["ignore_H"]
) * len(... | f1409d1dc2f4785bb2c2452b9bc08395a598f16d | 74,192 |
from ctypes import POINTER, byref, cdll, c_int, windll
from ctypes.wintypes import LPCWSTR, LPWSTR
def win32_utf8_argv():
"""Uses shell32.GetCommandLineArgvW to get sys.argv as a list of UTF-8
strings.
Versions 2.5 and older of Python don't support Unicode in sys.argv on
Windows, with the underlying ... | 42ca67d04455148134c7027619c4519dcbd70639 | 74,193 |
def removeGenesWithExcessiveReplicationVariance(df_X, max_var=None):
"""
Removes Genes with excessive variation in the variance of their
trinary values. Assumes a single digit replication.
Parameters
----------
df_X: DataFrame
index: str <instance>.replication-digit
ex: T10.2
max_var: floa... | e6b6950e2694792e03940caadbeda85c8e32717c | 74,194 |
def getQuadrantID(d):
"""
Returns a scale factor ID based on direction of the derivative. Index starts
at 1 in direction (1, 0, 0) and progresses in anti-clockwise direction.
:param d: directional derivative
:return: scale factor ID
"""
maps = [(1, 0, 0), (1, 1, 0), (0, 1, 0), (-1, 1, 0), (-... | 33d1bf4ed488d2da2a4925fc21a5a9c2a1cb8ecb | 74,195 |
def make_resource_graph(model):
"""
資源の使用量と残差(容量-使用量)を図示する関数
"""
horizon = 0
for a in model.act:
horizon = max(a.completion, horizon)
#print("planning horizon=",horizon)
count = 0
for res in model.res:
if len(res.terms) == 0: # renwable resource
count += 1
... | 2f88b0315d6d8f4d9efb16665b4c5e9bd21486e0 | 74,196 |
def _StripComments(json_string):
"""Strip comments from a json-with-comments string.
Any line beginning with a pound sign, or with whitespace followed by a pound
sign, is removed. Comments are not allowed on the same line as json
constructs.
Args:
json_string: (str) A json string which may contain comm... | 98a73f251064df1e441abc4f22626418257b3aa7 | 74,197 |
def str_to_py(obj):
"""Encode Python object `obj` as python string.
Parameters
----------
obj : :obj:
Python object to be encoded (typically a str or int).
Returns
-------
str
An encoded python string.
"""
encoding = vim.eval('&encoding') or 'utf-8'
if isinstanc... | af17a88a3b8520343f98d99e62ae15d6f4c9c7a3 | 74,198 |
def extract_entities(text, dates_extractor=None, ner_tagger=None, names_extractor=None):
"""
Extract DATE, ORG, PERSON, COURSE
return info = {
'ORG': first_org in text,
'ORG_TEXT': txt
'DATE': first_date in text,
'NAME': first name in text,
'COURSE': is_courses_block... | d94da496a9d63141dd46a7745d1076d7918d07c2 | 74,199 |
from typing import Tuple
from typing import Dict
import functools
def run_filters(df: pd.DataFrame, req_filters: FilterMap,
opt_filters: FilterMap = None) -> Tuple[pd.Series, Dict[str, pd.Series]]:
"""
Runs a list of filters on the input dataframe, returning a dictionary of Boolean Series
... | 933969819b5aa63dc1db23f6623802852c7c1682 | 74,200 |
from typing import Callable
from re import T
from typing import Optional
def wrap_exceptions(
fn: Callable[[], T], context: Optional[ParserRuleContext] = None
) -> T:
"""
Wrap the given call to `fn` in a proper try/except block to convert as many
exceptions as possible to WizardError.
"""
try... | 5cbc5627ddcdd878c214d7cd876bd09d321f1748 | 74,201 |
def generate_selected_torsions(input_json):
"""Identify torsions that can be driven.
Parameters
----------
input_json: str,
JSON file name to the output json of generate.py (prepared as if for an OptimizationDataset)
The data in the json file should be a list of {'initial_molecules': [.... | 52d9f89bd783f91e9dda64397d5ecd39c62e925f | 74,202 |
import multiprocessing
import tqdm
def mean(data, block_shape=None, n_threads=None, mask=None, verbose=False, roi=None):
""" Compute the mean of the data in parallel.
Arguments:
data [array_like] - input data, numpy array or similar like h5py or zarr dataset
block_shape [tuple] - shape of the... | 115beccc01453ed97bc9fc1e4e9d698f73d9bd84 | 74,203 |
import types
import re
from textwrap import dedent
async def bot_added(message: types.Message, state: FSMContext):
"""
Пользователь добавляет бота и мы ждём от него токен
"""
token = re.findall(token_pattern, message.text)
async def on_invalid_token():
await message.answer(dedent("""
... | 465a5ddbe8b7ca2c197cceaa59e9bd09a2252a65 | 74,204 |
from datetime import datetime
def interface():
"""Kies het weerstation, de begindatum en de einddatum
Returns:
df, het weerstation, begindatum en einddatum (laatste drie als string)
"""
mode = st.sidebar.selectbox(
"Modus (kies HELP voor hulp)", ["doorlopend per dag", "aantal keren", ... | b5ecbd61820dc991870844fa28c678ac3c47805f | 74,205 |
def Ads(line):
"""Decode Automatic Device Status (ADS)."""
try:
fields = ADS_RE.match(line).groupdict()
except TypeError:
return
TimeUtc(fields)
result = {
'msg': 'ADS',
'talker': fields['talker'],
'id': fields['id'],
'alarm': fields['alarm'],
'time_sync_method': util.M... | 475382b82d4cb048b61fd56ccd5e91c8263dab7b | 74,206 |
def vertical_relative_vorticity(od):
"""
Compute vertical component of relative vorticity.
.. math::
\\zeta =
\\frac{\\partial v}{\\partial x}
-\\frac{\\partial u}{\\partial y}
Parameters
----------
od: OceanDataset
oceandataset used to compute.
Returns
... | acbee12299b0a6732148f800c499129005e9f60a | 74,208 |
def get_documentation(path=""):
"""
create documentation as simple HTML, using the supplied path, which is interpreted as the project root.
The documentation will be surroundeded with very basic HTML boilerplate, i.e. you probably do not want to
use this method, which is a wrapper around get_documentat... | 7422c1730e88a32b3649c9f004109ff10cdd2e7d | 74,209 |
def import_cbisddsm_training_dataset(label_encoder):
"""
Import the dataset getting the image paths (downloaded on BigTMP) and encoding the labels.
Originally written as a group for the common pipeline. Later amended by Adam Jaamour.
:param label_encoder: The label encoder.
:return: Two arrays, one ... | 16cb020e67486c9d613080cc422d9bdb3d09d7e6 | 74,210 |
def _py_lazy_and(cond, b):
"""Lazy-eval equivalent of "and" in Python."""
return cond and b() | 872f382ac72d8253c61043dfe146d05775b4748d | 74,211 |
def get_response_ctx_view(func):
"""
add only the response object with the view function.
"""
response_param = signature(func).parameters.get('response', None) \
or signature(func).parameters.get('res', None)
is_response = True if response_param is not None else Fals... | b63472497d12203eaa3291e24ed5661d35bbf41f | 74,212 |
def vit_b_p16(pooling_arch=None, distilled=False, num_classes=1000, dropout_ratio=0., image_size=224, early_stride=None):
""" ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transfor... | a998bb1e44cdbfb09a14871592c3afc71f2d24f8 | 74,213 |
def find_gt(a, x):
"""Locate the leftmost value greater than x"""
i = bisect_right(a, x)
if i != len(a):
return i
raise ValueError | aa70fe51d590887a26720c49cdb55f74e8da1bb6 | 74,214 |
async def cringo_stat_embed(user: DiscordUser) -> Embed:
"""Return a big ol' embed of Cringo! stats"""
s = await CringoStatistic.get_by_discord_user(user)
if s.plays == 0:
embed = c.crimbed(
title='Hold up—',
descr="You haven't played any games of CRINGO yet!",
... | 027612631bf9516c43983cbccb3701a97b8e6876 | 74,215 |
def create_design_matrix(long_form,
specification_dict,
alt_id_col,
names=None):
"""
Parameters
----------
long_form : pandas dataframe.
Contains one row for each available alternative, for each observation.
specifica... | f405ca442d2b1a9d173f1982632861ac4694013b | 74,216 |
def transform(sample):
"""Sample is an ordered dictionary of dataset elements"""
image, label = sample["images"], sample["labels"]
image = augment(image=image)["image"]
return image, label | 30a23eab8be5fea5e407343a19fb4fa14d10e104 | 74,217 |
def get_matrices(src):
"""Reads the STIX and returns a list of all matrices in the STIX"""
matrices = src.query([
stix2.Filter('type', '=', 'x-mitre-matrix'),
])
return matrices | 41c97b4cdf16cb07378463c53d20499736362126 | 74,218 |
def split_dataset(dataset):
""" split dataset into train, test, validate """
dataset_train, dataset_test, dataset_validate = train_test_split(dataset, test_size=0.2, random_state=0)
return dataset_train, dataset_test, dataset_validate | 9dfe9de512d2c162aae9bffca6d27ff67748a34d | 74,219 |
from typing import Dict
def validate(incorporation_json: Dict):
"""Validate the Incorporation filing."""
if not incorporation_json:
return Error(HTTPStatus.BAD_REQUEST, [{'error': babel('A valid filing is required.')}])
msg = []
err = validate_offices(incorporation_json)
if err:
m... | 290a776ba6e034f1fc14c9d659f5710395514817 | 74,220 |
def get_y_var(plot_spec: pd.Series):
"""
Return the observable which should be plotted on the y-axis
Arguments:
plot_spec: A single row of a visualization df
Return:
observable which should be plotted on the y-axis
"""
y_var = "" # default value
if ptc.Y_VALUES in plot_spec.... | 2864417304a27375f51c4e91a61b2935316f8b1a | 74,221 |
def load_providers_to_delete():
"""
Build a list of Sources that need to be deleted from the Koku provider database.
The primary use case where this is when the Koku API is down and the Source has
been removed from the Platform-Sources backend. Additionally this is also needed
to re-load the proce... | 970f7eca3aec00ab25ba3c0661ba8d5cf7b8df63 | 74,222 |
from datetime import datetime
def decode_datetime(encoded_datetime):
"""Decode a DateTimeField parameter from a string to a python datetime.
Args:
encoded_datetime: A string in RFC 3339 format.
Returns:
A datetime object with the date and time specified in encoded_datetime.
Raises:
ValueError: ... | 2b2b7ca6ece65f6b6f480d5c8c47a18897b52614 | 74,223 |
def test_strain_bias(data,
value,
sample='sample',
strain='t2onc_type',
samples=None,
incl_neg=True):
"""Tests if a given property is biased towards a specific mouse strain.
Test is performed using a Fisher... | 43f4a1fd2f62eb5cfccc30993ec2f5bd34d7124d | 74,224 |
def beadplot_serial(lineage, features, args, callback=None):
""" Compute distance matrices and reconstruct NJ trees """
# bootstrap sampling and NJ tree reconstruction, serial mode
trees, labels = clustering.build_trees(features, args, callback=callback)
if trees is None:
# lineage only has one ... | c515f325950dea6275cf6c6123ec6b359434c2a9 | 74,225 |
def hermite_fft(a, n=None, axis=-1):
"""hermite_fft(a, n=None, axis=-1)
inverse_hermite_fft(a, n=None, axis=-1)
These are a pair analogous to real_fft/inverse_real_fft, but for the
opposite case: here the signal is real in the frequency domain and has
Hermite symmetry in the time domain. So here it... | 962abd336e77e94efa972c4c70ac3cfdeadf24c5 | 74,226 |
def get_negatives(all_contexts, vocab, counter, K):
"""返回负采样中的噪声词。
Defined in :numref:`sec_word2vec_data`"""
# 索引为1、2、...(索引0是词表中排除的未知标记)
sampling_weights = [counter[vocab.to_tokens(i)]**0.75
for i in range(1, len(vocab))]
all_negatives, generator = [], RandomGenerator(sampl... | 40eb2454530a0f3c3aec419a0c3f99fcb89e825d | 74,227 |
import torch
def calc_iou_tensor(box1, box2):
"""Calculation of IoU based on two boxes tensor, Reference to https://github.com/kuangliu/pytorch-ssd."""
N = box1.size(0)
M = box2.size(0)
be1 = box1.unsqueeze(1).expand(-1, M, -1)
be2 = box2.unsqueeze(0).expand(N, -1, -1)
# Left Top & Right Bot... | efff3eafc8dc33aee5e1f3e5cca9266421e4197e | 74,228 |
def _type_to_type_string(object_type):
"""Converts a type to a serializable string.
Parameters
----------
object_type: type
The type to convert.
Returns
-------
str
The converted type.
"""
if (issubclass(object_type, unit.Unit) or
f'{object_type.__module__}... | d392182cae4c07ba06dd9e5383946f235ee4a4ac | 74,229 |
def get_id(obj, context):
"""Get record id."""
pid = context.get('pid')
return pid.pid_value if pid else missing | 24f9f62483713fe27117e746ddb39895ce492398 | 74,230 |
def conditional(Xnew, X, kern, f, full_cov=False, q_sqrt=None, whiten=False):
"""
Given F, representing the GP at the points X, produce the mean and
(co-)variance of the GP at the points Xnew.
Additionally, there my be Gaussian uncertainty about F as represented by
q_sqrt. In this case `f` represen... | 02f4c7acad1a68079a2807ea8398efa203d0d2f2 | 74,231 |
def parse_id(hardware_id):
"""Parse Nuki ID."""
return hex(hardware_id).split("x")[-1].upper() | 483fb1c7a864242335288f53653c461a50eab638 | 74,234 |
def _load_level(handler, level, pathtable):
"""
Loads level and builds appropriate type, handling softlinks if necessary
"""
if isinstance(level, tables.link.SoftLink):
# this is a link, so see if target is already loaded, return it
pathname = level.target
node = level()
else... | 9f833b57b51fe0fac75c0d5f2a64c87cf3c7510e | 74,235 |
def unfreezeTransformations():
"""Unfreeze selected objects translation.
Returns:
True: If succeed.
"""
sel = om2.MGlobal.getActiveSelectionList()
for s in range(sel.length()):
obj = sel.getDagPath(s)
fnTrans = om2.MFnTransform(obj)
rp = fnTrans.rotatePivot(om2.MSpac... | 628cb99aec1e3a8ff9593f468cc9fa5e97707aed | 74,236 |
from typing import Dict
from typing import Any
from typing import OrderedDict
def sort_dict(item: dict) -> Dict[str, Any]:
"""
Sort nested dict
Input: {"b": 1, "a": {"c": 1,"b": 2}, "c": "c_st[ring]"}
Output: OrderedDict([
('a', OrderedDict([('b', 2), ('c', 1)])),
('b', 1),
('... | 0f4c042df4ea2f00dbda249f9d2c7c3488824559 | 74,237 |
def create_handle_decorator(registry, filter=Always()):
"""
Create a key handle decorator, which is compatible with `Registry.handle`,
but will chain the given filter to every key binding.
:param filter: `CLIFilter`
"""
assert isinstance(filter, CLIFilter)
def handle(*keys, **kw):
... | 2d75f400099a6362c73cddebd024ad1c21756482 | 74,238 |
def filter_term_freqs(term_freqs, where):
"""
Subset term-freqs of a dataframe by specified filters.
"""
# Build a new dataset with just the index.
index = (
term_freqs.index
.to_frame(index=False)
)
index_cols = index.columns
# Run the user-provided filter on this i... | 08113cfce8fb4a29b4def72749b80330164e092c | 74,239 |
import json
def load_dict(filename):
"""
Loads a dictionary stored in JSON format
:param filename:
:return:
"""
data = json.load(open(filename))
return data | 88f286417bbdd43d4499e83750c92843a9f6231a | 74,240 |
def Main(operation, args):
"""
:param operation:a
:param args:
:return:
"""
# 'init' has to be invokded first after deploying the contract to store the necessary and important info in the blockchain
if operation == 'init':
return init()
if operation == 'name':
return name... | f4d5d085c9dc3c18459c90b8d9dd36653b176e68 | 74,241 |
from typing import Optional
def stream_type(stream_type_str: Optional[str]) -> Optional[StreamType]:
"""Converts a string with a command stream type to the corresponding type.
Args:
stream_type_str (str): The string with the command stream type.
Returns:
Optional[StreamType]: The type of... | 0691d224063557cb4f685fa9c31af8d1368edc58 | 74,242 |
def getStorageElementEndpoint(seName):
""" Get endpoints of a StorageElement
:param str seName: name of the storage element
:returns: S_OK() or S_ERROR
for historical reasons, if the protocol is SRM, you get 'httpg://host:port/WSUrl'
For other protocols, you get :py:meth... | 9ca3f6c02f1b2a133dc39711daa40c096240c8c7 | 74,243 |
def lift(fn=None, prior=None):
"""
Given a stochastic function with param calls and a prior distribution,
create a stochastic function where all param calls are replaced by sampling from prior.
Prior should be a callable or a dict of names to callables.
Consider the following Pyro program:
... | 8c80dccd18173b420752c6a87a57690779986c8e | 74,244 |
from typing import Union
from pathlib import Path
from typing import AsyncGenerator
def exchange_pack(
git_repo: Union[Path, str],
pack_type: str,
input_stream: AsyncGenerator[bytes, None]) -> AsyncGenerator[bytes, None]:
"""
Used to exchange packs between client and remote.
:para... | 1bed4611947850a7e231e54f036735e2d2e51c3c | 74,245 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.