content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def cross_validation(df, K, hyperparameters):
"""
Perform cross validation on a dataset.
:param df: pandas.DataFrame
:param K: int
:param hyperparameters: dict
"""
train_indices = list(df.sample(frac=1).index)
k_folds = np.array_split(train_indices, K)
if K == 1:
K = 2
... | 72cdf91efa029eb8c029eb84d596057d13a7c515 | 3,657,218 |
from typing import List
from typing import Dict
def solve_cities(cities: List, gdps: List, sick: List, total_capacity: int,
value_r=0, weight_r=0, num_reads=1, verbose=False) -> Dict:
"""
Solves problem: "Which cities should I should I shut down in order to stay
within healthcare resource... | 52bef06069ee6975fbc5dea50cbb44349c96b9db | 3,657,219 |
def catalog():
"""Render the mapping catalog page."""
if request.args.get(EQUIVALENT_TO):
mappings = current_app.manager.get_mappings_by_type(EQUIVALENT_TO)
message = Markup("<h4>You are now visualizing the catalog of equivalent mappings</h4>")
flash(message)
elif request.args.get(I... | b28904fff79b978225eda1bb3ed4f6e04c817737 | 3,657,220 |
def apply_inverse_rot_to_vec(rot, vec):
"""Multiply the inverse of a rotation matrix by a vector."""
# Inverse rotation is just transpose
return [rot[0][0] * vec[0] + rot[1][0] * vec[1] + rot[2][0] * vec[2],
rot[0][1] * vec[0] + rot[1][1] * vec[1] + rot[2][1] * vec[2],
rot[0][2] * ve... | 1108ac6caa30b3562a2af1bcc83e1c1a1bfd8d4d | 3,657,222 |
def gsl_blas_dsdot(*args, **kwargs):
"""gsl_blas_dsdot(gsl_vector_float const * X, gsl_vector_float const * Y) -> int"""
return _gslwrap.gsl_blas_dsdot(*args, **kwargs) | 6b8f45a773fca936913b2653df9ab8c96f1e974a | 3,657,223 |
def cost(weights):
"""Cost function which tends to zero when A |x> tends to |b>."""
p_global_ground = global_ground(weights)
p_ancilla_ground = ancilla_ground(weights)
p_cond = p_global_ground / p_ancilla_ground
return 1 - p_cond | 3b33292c63b42d110efe0d7cbe4dae85f095472f | 3,657,224 |
import time
def runOptimization(
cfg,
optimize_cfg,
n_iter=20,
split_runs=1,
model_runs=1,
filename="optimize_result",
):
"""Optimize the model parameter using hyperopt.
The model parameters are optimized using
the evaluations on validation dataset.
Args:
cfg(di... | ef2e2c85f5b0b8f6889da49ed1e964d432bb1886 | 3,657,225 |
def _capabilities_for_entity(config, entity):
"""Return an _EntityCapabilities appropriate for given entity.
raises _UnknownEntityDomainError if the given domain is unsupported.
"""
if entity.domain not in _CAPABILITIES_FOR_DOMAIN:
raise _UnknownEntityDomainError()
return _CAPABILITIES_FOR_... | 5fe541778ede415020377a0c989fa47ad2ae4d05 | 3,657,226 |
def apply_torsion(nodes, suffix=""):
""" Torsion energy in nodes. """
if (
"phases%s" % suffix in nodes.data
and "periodicity%s" % suffix in nodes.data
):
return {
"u%s"
% suffix: esp.mm.torsion.periodic_torsion(
x=nodes.data["x"],
... | 37310291ddb769587d9d14a8dedcda3b528a78f3 | 3,657,228 |
import decimal
def parse_summary_table(doc):
"""
Parse the etree doc for summarytable, returns::
[{'channel': unicode,
'impressions': int,
'clicks': int,
'ctr': decimal.Decimal,
'ecpm': decimal.Decimal,
'earnings': decimal.Decimal}]
"""
for t... | 7d188478dc5539b4c8020af09cb052140def63c9 | 3,657,229 |
import math
def tileset_info(hitile_path):
"""
Get the tileset info for a hitile file.
Parameters
----------
hitile_path: string
The path to the hitile file
Returns
-------
tileset_info: {'min_pos': [],
'max_pos': [],
'tile_size': 1024,... | 3ea467898e15ac6aca21c219398aa1249b795e55 | 3,657,230 |
def delete_user():
""" Deletes the current user's account. """
DB.session.delete(current_user)
DB.session.commit()
flash("Account deleted", 'success')
return redirect('/login') | bc22d6287738c676cec3c780a9fb01513ddd5530 | 3,657,231 |
def setup_code_gen(no_of_accessories):
""" Generate setup code
"""
try:
invalid_setup_codes = ['00000000','11111111','22222222','33333333','44444444','55555555',\
'66666666','77777777','88888888','99999999','12345678','87654321']
setup_code_created = []
... | 253272cc27de1ead05d12f2e1798d91a3c4571dd | 3,657,232 |
def letter_difference(letter_1: str, letter_2: str) -> int:
"""
Return the difference in value between letter_1 and letter_2
"""
assert len(letter_1) == 1
assert len(letter_2) == 1
diff = letter_to_value[letter_2] - letter_to_value[letter_1]
if diff > 13:
diff -= 27
return diff | 66d88efff92acebef06275d244d560ca5071e974 | 3,657,233 |
import requests
def refresh_access_token(request):
"""Updates `accessToken` in request cookies (not in browser cookies) using `refreshToken`. """
try:
refresh_token = request.COOKIES['refreshToken']
url = urljoin(settings.TIT_API_HOST, '/api/auth/token/refresh/')
response = requests.... | 378f4129fa9cc6af8cc961560e3e4063fcd0495b | 3,657,234 |
def ngrams(string, n=3, punctuation=PUNCTUATION, **kwargs):
""" Returns a list of n-grams (tuples of n successive words) from the given string.
Punctuation marks are stripped from words.
"""
s = string
s = s.replace(".", " .")
s = s.replace("?", " ?")
s = s.replace("!", " !")
s = [w.... | 1e0e99f01c8aa46f4c44cca02d9bdb2b1c52d4c5 | 3,657,235 |
def binstringToBitList(binstring):
"""Converts a string of '0's and '1's to a list of 0's and 1's"""
bitList = []
for bit in binstring:
bitList.append(int(bit))
return bitList | d8ff10651d9fc2d02aba3b4a57a0a768032783b7 | 3,657,236 |
def file_revisions(request, repo_id):
"""List file revisions in file version history page.
"""
repo = get_repo(repo_id)
if not repo:
raise Http404
# perm check
if check_folder_permission(request, repo_id, '/') is None:
raise Http404
return render_file_revisions(request, rep... | c9ec0e1c159a4efdd8f4c3287cb9d8339ba9a9d2 | 3,657,237 |
def textctrl_info_t_get_tabsize(*args):
"""
textctrl_info_t_get_tabsize(self) -> unsigned int
"""
return _ida_kernwin.textctrl_info_t_get_tabsize(*args) | 7aff89906aebacb3664a73d26f52dd4317031790 | 3,657,238 |
def node_is_hidden(node_name):
"""
Returns whether or not given node is hidden
:param node_name: str
:return: bool
"""
if python.is_string(node_name):
return not maya.cmds.getAttr('{}.visibility'.format(node_name))
return not maya.cmds.getAttr('{}.visibility'.format(node.get_name(n... | 0927d2424b64b9b81b52ced335823963d7ec9fe2 | 3,657,239 |
import torch
def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor, PS: int = 32) -> torch.Tensor:
"""Helper function for affine grid generation.
Args:
img: image tensor of shape :math:`(B, CH, H, W)`.
LAF: laf with shape :math:`(B, N, 2, 3)`.
PS: patch size... | 288572e4ff8577a8bd664732c79408b71ec58c0d | 3,657,240 |
from typing import Union
from typing import Tuple
def _resolve_condition_operands(
left_operand: Union[str, pipeline_channel.PipelineChannel],
right_operand: Union[str, pipeline_channel.PipelineChannel],
) -> Tuple[str, str]:
"""Resolves values and PipelineChannels for condition operands.
Args:
... | fde07e14af8f9ae610cfcd64e6a3f2219f0ee8e9 | 3,657,241 |
def int_to_bitstr(int_value: int) -> str:
"""
A function which returns its bit representation as a string.
Arguments:
int_value (int) - The int value we want to get the bit representation for.
Return:
str - The string representation of the bits required to form the int.
"""
... | cafbf151ce0404081a0a8e1327d85e61ea7ddc52 | 3,657,243 |
def target_reached(effect):
"""target amount has been reached (100% or more)"""
if not effect.instance.target:
return False
return effect.instance.amount_raised >= effect.instance.target | 0101cd9c3c51a1e03ba7cfd8844c3821a156e2fe | 3,657,244 |
def resid_mask(ints, wfs_map=read_map(wfs_file), act_map=read_map(act_file), num_aps=236):
"""
Returns the locations of the valid actuators in the actuator array
resids: Nx349 residual wavefront array (microns)
ints: Nx304 intensity array (any units)
N: Number of timestamps
"""
# Check input... | 98c818db8d2d5040c5a20857693f3f3116ab8e13 | 3,657,245 |
import requests
def session():
"""Sets up a HTTP session with a retry policy."""
s = requests.Session()
retries = Retry(total=5, backoff_factor=0.5)
s.mount("http://", HTTPAdapter(max_retries=retries))
return s | d5cb89f04017718983834a0b4008972f393f56ae | 3,657,246 |
def handle_index():
"""
Kezeli az index oldalat, elokesziti es visszakulti a html-t a kliensnek.
:return:
"""
return render_template("index.html") | eaaa2c3028983c1e5ed29a45fe6ff3db0a8a7482 | 3,657,248 |
def get_polynomial_coefficients(degree=5):
"""
Return a list with coefficient names,
[1 x y x^2 xy y^2 x^3 ...]
"""
names = ["1"]
for exp in range(1, degree + 1): # 0, ..., degree
for x_exp in range(exp, -1, -1):
y_exp = exp - x_exp
if x_exp == 0:
... | 9369841215045e925a3453b83be9dc49c9be7b92 | 3,657,249 |
from typing import Dict
import pickle
def _get_configured_credentials() -> Dict[str, bytes]:
"""
Get the encryupted credentials stored in disk
"""
path = get_credentials_path()
credentials: Dict[str, bytes]
with open(path, "rb") as file_handle:
credentials = pickle.load(file_handle)
... | 824aeb18f4e5bed609008c6594d86666502b2339 | 3,657,250 |
def kabsch_rotate(P, Q):
"""
Rotate matrix P unto matrix Q using Kabsch algorithm
"""
U = kabsch(P, Q)
# Rotate P
P = np.dot(P, U)
return P | 2be9c94901b27205ec4720b16ab6e81f34b1c6d6 | 3,657,252 |
def matrix(
odoo=ODOO_VERSIONS, pg=PG_VERSIONS, odoo_skip=frozenset(), pg_skip=frozenset()
):
"""All possible combinations.
We compute the variable matrix here instead of in ``.travis.yml`` because
this generates faster builds, given the scripts found in ``hooks``
directory are already multi-versio... | 034e791d2e10e9f691df3e6c458722549c59a89a | 3,657,253 |
import copy
def iterate_pagerank(corpus, damping_factor):
"""
Return PageRank values for each page by iteratively updating
PageRank values until convergence.
Return a dictionary where keys are page names, and values are
their estimated PageRank value (a value between 0 and 1). All
PageRank va... | bc51bd946d8fc617222303ffe30507695ee5ae33 | 3,657,254 |
def user_enabled(inst, opt):
"""
Check whether the option is enabled.
:param inst: instance from content object init
:param url: Option to be checked
:return: True if enabled, False if disabled or non present
"""
return opt in inst.settings and inst.settings[opt] | 3b2a5a1534ff779178eb4bd6b839b66c0b07864f | 3,657,255 |
async def get_buttons_data(client: Client, message: Message):
"""
Get callback_data and urls of all the inline buttons of the message you replied to.
"""
reply_message = message.reply_to_message
if reply_message and reply_message.reply_markup:
if reply_message.reply_markup.inline_keyboard:
... | 6567455d95781515fc6236bf867a042ba550736f | 3,657,256 |
def update_document(
*, db_session: Session = Depends(get_db), document_id: PrimaryKey, document_in: DocumentUpdate
):
"""Update a document."""
document = get(db_session=db_session, document_id=document_id)
if not document:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
... | 15dc23aeb10950da19a6732c43d7675447f6a45c | 3,657,257 |
def from_jabsorb(request, seems_raw=False):
"""
Transforms a jabsorb request into a more Python data model (converts maps
and lists)
:param request: Data coming from Jabsorb
:param seems_raw: Set it to True if the given data seems to already have
been parsed (no Java class hin... | 78e8eefc0b234a5b6cd09cebff76e5cb716b54c2 | 3,657,258 |
def write_board_to_svg_file(board, file_name, hex_edge=50, hex_offset=0,
board_padding=None, pointy_top=True, trim_board=True, style=None):
"""
Writes given board to a svg file of given name.
:param board: 2 dimensional list of fields, each represented as a number
:param fil... | 4cbf895a4a91e0434e31fdad459c3354927c5e2b | 3,657,259 |
def ensure_conf(app):
"""
Ensure for the given app the the redbeat_conf
attribute is set to an instance of the RedBeatConfig
class.
"""
name = 'redbeat_conf'
app = app_or_default(app)
try:
config = getattr(app, name)
except AttributeError:
config = RedBeatConfig(app)
... | 673680aafbc4d76b1ae7f7740e53fd7f54740acf | 3,657,260 |
def check_if_process_present(string_to_find):
"""Checks if process runs on machine
Parameters:
string_to_find (string): process we want to find
Returns:
found (bool): True if found process running
"""
output = check_output(["ps", "-ax"], universal_newlines=True)
if string_to_find in ... | 3a153e2160000ec1c9d4c0c28d1631179f9e88c3 | 3,657,261 |
def consulta_dicionario(nivel):
"""
Entrada: Parâmetro do nível selecionado (fácil, médio, difícil)
Tarefa: Determinar qual dicionário a ser consultado
Saída: Parâmetros do dicionário (texto, lacunas, gabarito)
"""
nivel_dicionario = nivel
if nivel_dicionario == 'facil':
texto = dici... | 1453298f791cca010f75abad9d0d37a28c1c8ae5 | 3,657,262 |
from typing import List
def stats_check(
main_table: Table,
compare_table: Table,
checks: List[OutlierCheck] = [],
max_rows_returned: int = 100,
):
"""
:param main_table: main table
:type main_table: table object
:param compare_table: table to be compared
:type compare_table: table... | 39f0c0b2bad74a7878453a3fe11def36f1971a5f | 3,657,263 |
async def get_collectible_name(collectible_id: int, db: AsyncSession = Depends(get_db_session)):
"""Gets the collectible name"""
result = await destiny_items.get_collectible(db=db, collectible_id=collectible_id)
return NameModel(name=result.name) if result else NameModel(name=None) | 18fd3856d5145a004cf20343b5e8782a13a35845 | 3,657,264 |
def prime_factors(n):
"""
Return a list of prime factors of n
:param n: int
:return: list
"""
# check if 2 is the largest prime
all_factors = set()
t = n
while t % 2 == 0:
t /= 2
all_factors.add(2)
# check the divisors greater than 2
d = 3
while d < n ** ... | 09aad44a7b04492c225447eaa15590fa630a43cd | 3,657,265 |
def calculate_central_age(Ns, Ni, zeta, seZeta, rhod, Nd, sigma=0.15):
"""Function to calculate central age."""
Ns = np.array(Ns)
Ni = np.array(Ni)
# We just replace 0 counts with a low value, the age will be rounded to
# 2 decimals. That should take care of the zero count issue.
Ns = np.wher... | 29b360ce1df7cfa376a86b989fb7899137d110cc | 3,657,266 |
import requests
def _get_cross_reference_token(auth_cookie: str) -> str:
"""Gets a new cross reference token affiliated with the Roblox auth cookie.
:param auth_cookie: Your Roblox authentication cookie.
:return: A fresh cross reference token.
"""
session: requests.Session = _get_session(auth_co... | 63041ddeb31ccdc0a72a721d000968588580e816 | 3,657,267 |
def erase_not_displayed(client):
"""Erase all non-displayed models from memory.
Args:
client (obj): creopyson Client.
Returns:
None
"""
return client._creoson_post("file", "erase_not_displayed") | c3981fcce00b5d5440fcbdbe8781e9e6229a8fa7 | 3,657,268 |
def reset_position_for_friends_image_details_from_voter(voter, twitter_profile_image_url_https,
facebook_profile_image_url_https):
"""
Reset all position image urls in PositionForFriends from we vote image details
:param voter:
:param twitter_profi... | e2483bf781029a7481dead0a168775b1a9223978 | 3,657,269 |
def get_analysis(panda_data):
"""
Get Analysis of CSV Data
:param panda_data: Panda dataframes
:return: panda data frames
"""
# Create Object for Analysis0
sentiment_object = SentimentConfig.sentiment_object
ner_object = SentimentConfig.ner_object
# Get list of sentences
list =... | 014bc1543f67dfe561bce62d9b5e5f974b28db2a | 3,657,270 |
def create_coordinate_string_dict():
"""31パターンのヒモ。"""
w = 120
h = 120
return {
47: (0, 0),
57: (1*-w, 0),
58: (2*-w, 0),
16: (4*-w, 0),
35: (5*-w, 0),
36: (6*-w, 0),
38: (0, 1*-h),
13: (1*-w, 1*-h),
14: (2*-w, 1*-h),
15: (3*... | 4abc2b246345569780db2dc9f6ef71c56ae86528 | 3,657,271 |
def all_but_ast(check):
"""Only passes AST to check."""
def _check_wrapper(contents, ast, **kwargs):
"""Wrap check and passes the AST to it."""
del contents
del kwargs
return check(ast)
return _check_wrapper | 71f3e3b8649a3a9885ded7eec248894cca8083c4 | 3,657,272 |
import readline
def get_history_items():
"""
Get all history item
"""
return [
readline.get_history_item(i)
for i in xrange(1, readline.get_current_history_length() + 1)
] | b3600ca6581c11a46c2ea92d82b9d5aefcded49b | 3,657,273 |
def normalize(*args):
"""Scale a sequence of occurrences into probabilities that sum up to 1."""
total = sum(args)
return [arg / total for arg in args] | 49b0f998fe58b2c85da5a993e542d91bb5dd5382 | 3,657,275 |
import requests
def _make_request(
resource: str,
from_currency_code: str,
to_currency_code: str,
timestamp: int,
access_token: str,
exchange_code: str,
num_records: int,
api_version: str
) -> requests.Response:
"""
API documentation for cryp... | 4da7c3cab42b742b106fafb4c1585e6ecb250121 | 3,657,277 |
def projective_error_function(params, args):
"""
:param params:
:param args:
:return:
"""
# fx fy cx cy k0 k1
project_params = params[0:5]
f, cx, cy, k0, k1 = project_params
K = eye(3, 3)
K[0,0] = f
K[1,1] = f
K[0, 2] = k0
K[1, 2] = k1
... | 5b1fe8265478a379d91178474e392797798c9c0f | 3,657,279 |
import warnings
def _transform_masks(y, transform, data_format=None, **kwargs):
"""Based on the transform key, apply a transform function to the masks.
Refer to :mod:`deepcell.utils.transform_utils` for more information about
available transforms. Caution for unknown transform keys.
Args:
y ... | 278615037d78b35cacb641eca89918010cf9b2fd | 3,657,280 |
def get_cur_version():
"""
Get current apk version string
"""
pkg_name = cur_activity.getPackageName()
return str(
cur_activity.getPackageManager().getPackageInfo(
pkg_name, 0).versionName) | 015d3368238edc10344c633d9cc491c79569f5f6 | 3,657,283 |
def checkpointload(checkpointfile):
"""Loads an hyperoptimizer checkpoint from file
Returns a list of tuples (params, loss) referring to previous hyperoptimization trials
"""
try:
with open(checkpointfile, "rb") as f:
return pkl.load(f)
except (FileNotFoundError, EOFError):
... | 906df00fcb209c979fd57c49a426f4c752b45753 | 3,657,284 |
def get_case_color_marker(case):
"""Get color and marker based on case."""
black_o = ("#000000", "o")
teal_D = ("#469990", "D")
orange_s = ("#de9f16", "s")
purple_v = ("#802f99", "v")
bs = case["batch_size"]
sub = case["subsampling"]
mc = case["mc_samples"]
if sub is None and mc =... | 4a42fc784b9034e3996753bc6da18fbfebc66b16 | 3,657,287 |
def clean_integer_score(x):
"""Converts x from potentially a float or string into a clean integer, and replace NA and NP values with one string character"""
try:
x = str(int(float(x)))
except Exception as exc:
if isinstance(x, basestring):
pass
else:
raise
... | 9ff2c911653421d51738bdb1bf8f381d3aa59820 | 3,657,288 |
def do_stuff2():
"""This is not right."""
(first, second) = 1, 2, 3
return first + second | dbb6f503e73cc0365dfa20fca54bebb174fcdadd | 3,657,289 |
def get_extra(item_container):
""" liefert die erste passende image_url """
if item_container.item.extra != '':
return get_extra_data(item_container)
item_container = item_container.get_parent()
while item_container.item.app.name == 'dmsEduFolder':
if item_container.item.extra != '':
return get_ex... | c9ac2ad65d05d13deaad8a6031f2f9ee8ab8aee4 | 3,657,291 |
import torch
def pt_accuracy(output, target, topk=(1,)):
"""Compute the accuracy over the k top predictions for the specified values of k."""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
c... | 5c0ddcd57163987b00e09a6677ddc41928810874 | 3,657,292 |
from typing import Counter
def compute_phasing_counts(variant_to_read_names_dict):
"""
Parameters
----------
variants_to_read_names : dict
Dictionary mapping varcode.Variant to set of read names
Returns
-------
Dictionary from variant to Counter(Variant)
"""
read_names_to... | ba13a6d6c76e018cb1072e9fba635aad5593437b | 3,657,293 |
def _inputs_and_vae(hparams):
"""Constructs a VAE."""
obs_encoder = codec.MLPObsEncoder(hparams)
obs_decoder = codec.MLPObsDecoder(
hparams,
codec.BernoulliDecoder(squeeze_input=True),
param_size=1)
inputs = context_mod.EncodeObserved(obs_encoder)
vae = vae_mod.make(hparams, ... | 0e6af8a7d17312f99435426907a0dca062981225 | 3,657,294 |
def read_grid_hdf5(filepath, name):
"""Read a grid from HDF5 file.
Parameters
----------
filepath : string or pathlib.Path object
Path of the HDF5 file.
name : string
Name of the grid.
Returns
-------
x : numpy.ndarray
The x-coordinates along a gridline in the x... | f9ad79da36cfa24028562cdaeefba8ca9b48e572 | 3,657,295 |
import xml
def cff2provn(filename):
"""Parse cml xml file and return a prov bundle object"""
#filename = "/Users/fariba/Desktop/UCI/freesurfer/scripts/meta-MC-SCA-023_tp1.cml"
tree = xml.dom.minidom.parse(filename)
collections = tree.documentElement
g = prov.ProvBundle()
g.add_namespace(xsd)
... | c8e44bd627173a17d45eadcc5ab73062c4e27ff6 | 3,657,297 |
def optional(idx, *args):
"""A converter for functions having optional arguments.
The index to the last non-optional parameter is specified and a list of types for optional arguments follows.
"""
return lambda ctx, typespecs: _optional_imp(ctx, typespecs[idx], args) | e5491588090beaf4730f18c1b54193104a8f62be | 3,657,298 |
def calc_plot_ROC(y1, y2):
"""
Take two distributions and plot the ROC curve if you used the difference
in those distributions as a binary classifier.
:param y1:
:param y2:
:return:
"""
y_score = np.concatenate([y1, y2])
y_true = np.concatenate([np.zeros(len(y1)), np.ones(len(y2))])... | 428aa54ebe92ff1df6df4ebcae800a0b692f09d5 | 3,657,299 |
def degrees(x):
"""Converts angle x from radians to degrees.
:type x: numbers.Real
:rtype: float
"""
return 0.0 | 87fe22113f8286db6c516e711b9cf0d4efe7e11d | 3,657,301 |
def account_credit(account=None,
asset=None,
date=None,
tp=None,
order_by=['tp', 'account', 'asset'],
hide_empty=False):
"""
Get credit operations for the account
Args:
account: filter by account code
... | a690d1352344c6f8e3d8172848255adc1fa9e331 | 3,657,302 |
import torch
def verify(model):
"""
测试数据模型检验
:param model: 网络模型以及其参数
:return res: 返回对应的列表
"""
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = model.to(device)
if device == 'cuda':
model = torch.nn.DataParallel(model)
cudnn.benchmark = True
res = []
... | 9ad2fd6280018aacbb2501f6b5eb862924b361a1 | 3,657,304 |
import csv
def parse_solution_file(solution_file):
"""Parse a solution file."""
ids = []
classes = []
with open(solution_file) as file_handle:
solution_reader = csv.reader(file_handle)
header = next(solution_reader, None)
if header != HEADER:
raise ValueError(
... | 19a553bd9979ca1d85d223b3109f3567a3a84100 | 3,657,305 |
def fibonacci_modulo(number, modulo):
"""
Calculating (n-th Fibonacci number) mod m
Args:
number: fibonacci number
modulo: modulo
Returns:
(n-th Fibonacci number) mod m
Examples:
>>> fibonacci_modulo(11527523930876953, 26673)
10552
"""
period = _pi... | 5a7692597c17263ba86e81104762e4c7c8c95083 | 3,657,306 |
from typing import Union
def _str_unusual_grades(df: pd.DataFrame) -> Union[str, None]:
"""Print the number of unusual grades."""
grades = np.arange(0, 10.5, 0.5).astype(float)
catch_grades = []
for item in df["grade"]:
try:
if float(item) not in grades:
catch_grade... | 0998b112438685523cadc60eb438bee94f3ad8fd | 3,657,307 |
from typing import Any
from typing import Dict
def _adjust_estimator_options(estimator: Any, est_options: Dict[str, Any], **kwargs) -> Dict[str, Any]:
"""
Adds specific required classifier options to the `clf_options` dictionary.
Parameters
----------
classifier : Any
The classifier objec... | 4ff98d8a3b3e647e129fb0ffbc9bc549caa60440 | 3,657,308 |
def _prettify(elem,indent_level=0):
"""Return a pretty-printed XML string for the Element.
"""
indent = " "
res = indent_level*indent + '<'+elem.tag.encode('utf-8')
for k in elem.keys():
res += " "+k.encode('utf-8')+'="'+_escape_nl(elem.get(k)).encode('utf-8')+'"'
children = elem.getch... | 8f46637cdbb8daf488fd668a197aee5495b8128a | 3,657,309 |
def predict(text):
"""
Predict the language of a text.
Parameters
----------
text : str
Returns
-------
language_code : str
"""
if language_models is None:
init_language_models(comp_metric, unicode_cutoff=10**6)
x_distribution = get_distribution(text, language_model... | 713d8cd8df040703ee7f138314f5c14f5a89ef26 | 3,657,310 |
def distance_loop(x1, x2):
""" Returns the Euclidean distance between the 1-d numpy arrays x1 and x2"""
return -1 | abd35a27cbeb5f5c9fe49a2a076d18f16e2849d9 | 3,657,312 |
def get_ps_calls_and_summary(filtered_guide_counts_matrix, f_map):
"""Calculates protospacer calls per cell and summarizes them
Args:
filtered_guide_counts_matrix: CountMatrix - obtained by selecting features by CRISPR library type on the feature counts matrix
f_map: dict - map of feature ID:fea... | 18aecb335655fb62459350761aeffd4ddbe231ae | 3,657,313 |
def symbol_by_name(name, aliases={}, imp=None, package=None,
sep='.', default=None, **kwargs):
"""Get symbol by qualified name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
... | 10921d715abc9c83891b26b884f3c88e86c4a900 | 3,657,314 |
from typing import Tuple
def coefficients_of_line_from_points(
point_a: Tuple[float, float], point_b: Tuple[float, float]
) -> Tuple[float, float]:
"""Computes the m and c coefficients of the equation (y=mx+c) for
a straight line from two points.
Args:
point_a: point 1 coordinates
poi... | b4d89f2bb3db48723f321e01658e795f431427e1 | 3,657,315 |
import tifffile
def read_tiff(fname, slc=None):
"""
Read data from tiff file.
Parameters
----------
fname : str
String defining the path of file or file name.
slc : sequence of tuples, optional
Range of values for slicing data in each axis.
((start_1, end_1, step_1), .... | 39b48229719dd8210059a3a9ed7972e8398728ab | 3,657,317 |
def sorted_non_max_suppression_padded(scores,
boxes,
max_output_size,
iou_threshold):
"""A wrapper that handles non-maximum suppression.
Assumption:
* The boxes are sorted by scores unless the box ... | 5d882acb6b9559eb541d49f6784798e5d342c673 | 3,657,318 |
def create_session() -> Session:
"""
Creates a new session using the aforementioned engine
:return: session
"""
return Session(bind=engine) | 8b480ee216c30b2c6b8652a6b6239ab6b83df4d9 | 3,657,319 |
import torch
def fft_to_complex_matrix(x):
""" Create matrix with [a -b; b a] entries for complex numbers. """
x_stacked = torch.stack((x, torch.flip(x, (4,))), dim=5).permute(2, 3, 0, 4, 1, 5)
x_stacked[:, :, :, 0, :, 1] *= -1
return x_stacked.reshape(-1, 2 * x.shape[0], 2 * x.shape[1]) | 9fb38004041280da0d6d53830761501aebf7969a | 3,657,320 |
import copy
def mcais(A, X, verbose=False):
"""
Returns the maximal constraint-admissible (positive) invariant set O_inf for the system x(t+1) = A x(t) subject to the constraint x in X.
O_inf is also known as maximum output admissible set.
It holds that x(0) in O_inf <=> x(t) in X for all t >= 0.
... | e162a1aed724166f373f8afbd6541622254e8b42 | 3,657,321 |
def evaluation_seasonal_srmse(model_name, variable_name='mean', background='all'):
"""
Evaluate the model in different seasons using the standardized RMSE.
:type model_name: str
:param model_name: The name of the model.
:type variable_name: str
:param variable_name: The name of the variable wh... | 39fb7ae64ab32fc5092e46c77c8593f1aeaf4c92 | 3,657,322 |
def _async_device_ha_info(
hass: HomeAssistant, lg_device_id: str
) -> dict | None:
"""Gather information how this ThinQ device is represented in Home Assistant."""
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
hass_device = device_registry.async_get_device(
iden... | 47af173daba91aa70ea167baf58c05e9f6f595f6 | 3,657,324 |
from typing import Optional
def get_travis_pr_num() -> Optional[int]:
"""Return the PR number if the job is a pull request, None otherwise
Returns:
int
See also:
- <https://docs.travis-ci.com/user/environment-variables/#default-environment-variables>
""" # noqa E501
try:
... | 86ef6ce3f9bf3c3e056b11e575b1b13381e490fe | 3,657,325 |
from typing import List
import json
def get_updated_records(table_name: str, existing_items: List) -> List:
"""
Determine the list of record updates, to be sent to a DDB stream after a PartiQL update operation.
Note: This is currently a fairly expensive operation, as we need to retrieve the list of all i... | 631c21836614731e5b53ed752036f1216d555196 | 3,657,326 |
def normalize_record(input_object, parent_name="root_entity"):
"""
This function orchestrates the main normalization.
It will go through the json document and recursively work with the data to:
- unnest (flatten/normalize) keys in objects with the standard <parentkey>_<itemkey> convention
- identi... | 73647b04ba943e18a38ebf2f1d03cca46b533935 | 3,657,327 |
def rmse(f, p, xdata, ydata):
"""Root-mean-square error."""
results = np.asarray([f(p, x) for x in xdata])
sqerr = (results - ydata)**2
return np.sqrt(sqerr.mean()) | 2b8afdb1742aad5e5c48fbe4407ab0989dbaf762 | 3,657,328 |
import logging
def get_logger(name=None, propagate=True):
"""Get logger object"""
logger = logging.getLogger(name)
logger.propagate = propagate
loggers.append(logger)
return logger | 3ad4dbc39f9bf934b02e2dc6e713a4793a28298b | 3,657,329 |
import requests
from typing import Match
def getMatches(tournamentName=None, matchDate=None, matchPatch=None, matchTeam=None):
"""
Params:
tournamentName: str/List[str]/Tuple(str) : filter by tournament names (e.g. LCK 2020 Spring)
matchDate: str/List[str]/Tuple(str) : date in the format of yy... | 89525caa9da0a3b546e0b8982e96469f32f8c5bc | 3,657,333 |
def get_fields(fields):
"""
From the last column of a GTF, return a dictionary mapping each value.
Parameters:
fields (str): The last column of a GTF
Returns:
attributes (dict): Dictionary created from fields.
"""
attributes = {}
description = fields.strip()
description = [x.strip() for x in description... | 30777838934b18a0046017f3da6b3a111a911a9c | 3,657,336 |
def add_log_group_name_params(log_group_name, configs):
"""Add a "log_group_name": log_group_name to every config."""
for config in configs:
config.update({"log_group_name": log_group_name})
return configs | a5fce8143c3404257789c1720bbfefc49c8ea3f5 | 3,657,337 |
from typing import Union
def on_update_user_info(data: dict, activity: Activity) -> (int, Union[str, None]):
"""
broadcast a user info update to a room, or all rooms the user is in if no target.id specified
:param data: activity streams format, must include object.attachments (user info)
:param activ... | 735486cad96545885a76a5a18418db549869304d | 3,657,338 |
def discover(isamAppliance, check_mode=False, force=False):
"""
Discover available updates
"""
return isamAppliance.invoke_get("Discover available updates",
"/updates/available/discover") | 04c68b0ce57d27bc4032cf9b1607f2f1f371e384 | 3,657,339 |
from re import A
def ltistep(U, A=A, B=B, C=C):
""" LTI( A B C ): U -> y linear
straight up
"""
U, A, B, C = map(np.asarray, (U, A, B, C))
xk = np.zeros(A.shape[1])
x = [xk]
for u in U[:-1]:
xk = A.dot(xk) + B.dot(u)
x.append(xk.copy())
return np.dot(x, C) | 5d7c7550a9a6407a8f1a68ee32e158f25a7d50bf | 3,657,340 |
def _registry():
"""Registry to download images from."""
return _registry_config()["host"] | ee7c724f3b9381c4106a4e19d0434b9b4f0125fc | 3,657,341 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.