content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_api_all_item():
"""Get map of class name to class for all ApiItem subclasses.
Returns:
:obj:`dict`
"""
return {c.__name__: c for c in ApiItem.__subclasses__()} | 621a867b0f4b28eb3d1b5721e22ea4914a5f577d | 35,000 |
def get_image_url(soup_object: object) -> str:
"""Return book image url."""
image_url = soup_object.find("img")["src"]
return image_url.replace("../..", "https://books.toscrape.com/") | 5a52145eacc2489762d3f32b63e092e26d4fc4c8 | 35,001 |
import requests
def request_nwis(site, service, start_date, end_date):
"""Request stream gauge data from the USGS NWIS.
Args:
site (str):
a valid site is 01585200
service (str):
can either be 'iv' or 'dv' for instantaneous or daily data.
start_date (str):
... | 712b22f8ba36d972718f83705ecc72672ce153c5 | 35,002 |
def concat_train_val(train_df, val_df):
"""Utility function to concatenate the train and validation set, while maintaining globally unique ids."""
# increment id tags
max_article_id = train_df['Article_ID'].max() + 1
max_ner_tag_id = train_df['NER_Tag_ID'].max() + 1
increment_article_id = partial(in... | b4c949e08061a724441caf0abf8a2a14f1e494c3 | 35,003 |
def drop_project_by_id(project_id: int):
"""Drop a project.
---
tags:
- project
parameters:
- name: project_id
in: path
description: The identifier of a project
required: true
type: integer
format: int32
"""
project = manager.cu_authenticated_... | 2f7e54f0e35bb4ffbaa2890c6d37b5583c17ed12 | 35,004 |
import math
def frequencyToMidi(frequency):
"""
Convert a given frequency in Hertz to its corresponding MIDI pitch number (60 = Middle C)
"""
return int(round(69 + 12 * math.log(frequency / 440.0, 2))) | 29d4b92b9deacb81f768b554200c4b63b632bf23 | 35,005 |
def lower(value): # Only one argument.
"""Converts a string into all lowercase
How to Use
{{ value|lower|lower|.... }}
"""
return value.lower() | a6c290276aa777cee5e948d0c89202c67a97e6d1 | 35,006 |
def stdp2rbp_non_linear_calcium(*args, **kwargs):
"""Rate-based plasticity from STDP using the non linear calcium model.
Same arguments as ~cbsp.population_1.non_linear_calcium(u, v, w0, seed)
Returns:
float: the population average change of synapse strength at time point 0
"""
w_rec, ... | 454990dc4783641c2da2da17297dd77abc95e3cd | 35,007 |
def create_RevPAR(dataframe):
"""Calculate revpar from answer_num_rooms converted to supply of
room nights divided by answer_ann_revenue"""
dataframe['CREATED_revpar'] = dataframe['ANSWER_ann_revenue'].astype(float)/(dataframe['ANSWER_num_rooms'].astype(float)*365)
return dataframe | 0d3c91ff3909ea693fdde4b0ea8baae43a31a9a0 | 35,008 |
def get_find_response_normal_field_dict(model):
"""
:param model:
:return:
"""
normal_fields = get_normal_field_list_by_model(model) # 普通字段
find_response_allow_fields = {}
for normal_field in normal_fields:
response_key = newbee_model.get_attr_by_model_field_key(model, normal_fiel... | c55da5f2a573857dc7f349bac79b467cd2345450 | 35,009 |
import os
import fnmatch
def get_locale_directory(project, locale):
"""
Get path to the directory with locale files.
Args:
project: Project instance
locale: Locale instance
Returns:
Dict with directory name and path as keys.
"""
path = get_repository_path_master(proje... | cbf797cff314ff30471f02a417ff44d30cda15ba | 35,010 |
def predict():
"""Return Cell with Summary"""
global CLEAN_SUMMARY
global model
summary = CLEAN_SUMMARY
in_count = None
out_count = None
logger.info('Received Text Input')
if request.method == 'POST':
out = request.form['rawtext']
# preprocess text
text = prepr... | 94fbc9d75b9d488e371185912c54741596a23506 | 35,011 |
import random
import string
def id_generator(N=10):
"""
Generator a random string of characters.
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) | 3e454a583f00f9218a8305dc5f7dca5d0bd27243 | 35,012 |
def transform_covariance(cov_in, transform):
"""
Apply a given transform to a covariance matrix.
:param cov_in: Covariance matrix
:param transform: The transform that will be applies
:returns: The transformed covariance matrix
"""
# Converting the Quaternion to a Rotation Matrix first
#... | 0926bf95e58702f6594de572c7eeb1be2053b0c5 | 35,013 |
def delete_vocabulary(vid):
"""
Delete an existing vocabulary
:return:
"""
try:
vocs.delete_vocabulary(vid)
except IndexError:
raise APIError('Ontology URI not found')
except vocs.UnknownVocabulary, e:
raise NotFound(e.message)
__analyse_vocabularies([vid])
_... | 49e1be4b8132d3db2533ea6e5155d9891a3c221c | 35,014 |
import numpy as np
def available_kurucz_models():
"""These hard-code the available Kurucz models, as present on Nov 22, 2019 on
'http://kurucz.harvard.edu/grids/grid'"""
T_a = np.concatenate((np.arange(3500,13250,250),np.arange(13000,1000,51000)))
logg_a = np.arange(0,5.5,0.5)
Z_a = np.round(np.co... | 2779e39e55127783986a71b65e0b7f09373551f7 | 35,015 |
import numpy as np
def draw_skill_prices(
T,
J,
pi_fun='pi_fixed',
low=-0.2,
high=0.2,
const=[0.0, 0.05]
):
""" Draws initial skill prices and simulates random prices changes.
With the normalization of wages in task 1 to zero, some parts
of this function are redundent. However, the... | a14af64fae651d3728fe4be2eae3f3e51eeecfe5 | 35,016 |
def deal_with_categorical(feasible_values, one_hot_values):
""" function to do the one hot encoding of the categorical values """
index = np.argmax(one_hot_values)
#index = one_hot_values.argmax()
return feasible_values[int(index)] | f57d4c8ae3dbe7183849eced8c42a4561ab910f0 | 35,017 |
def pretty_size(n, pow=0, b=1024, u='B', pre=[''] + [p + 'i' for p in 'KMGTPEZY']):
""" origin: https://stackoverflow.com/a/31178618 """
pow, n = min(int(m_log(max(n * b ** pow, 1), b)), len(pre) - 1), n * b ** pow
return "%%.%if %%s%%s" % abs(pow % (-pow - 1)) % (n / b ** float(pow), pre[pow], u) | dbef4901c93f240847f37755712a57a225a98900 | 35,018 |
def launch_container(container, **kwargs):
"""
Launch a specific container
:param container:
:return: the container ID
"""
# Build the container if it doesn't exist
logger.info("Building %s container..." % container)
client.images.build(path='../%s' % container,
t... | fdeda303a6bc36a3d9a0a828a69cd0bc2a31275d | 35,019 |
def collatz_function(n):
"""
This function, collatz function, takes a number n and the entire part on the division
with 2 if n is even or 3*n+1 is n is odd.
"""
if n % 2 == 0:
return n//2
else:
return 3*n+1 | bd9b061e9651e46e4c6efd3f6e45524d824040ff | 35,020 |
def has_enabled_clear_method(store):
"""Returns True iff obj has a clear method that is enabled (i.e. not disabled)"""
return hasattr(store, 'clear') and ( # has a clear method...
not hasattr(store.clear, 'disabled') # that doesn't have a disabled attribute
or not store.clear.disabled
) | 28ee30f92d44d14300e30fec0de37a2a241c8e92 | 35,021 |
import argparse
def _parser():
"""Take care of all the argparse stuff.
:returns: the args
"""
parser = argparse.ArgumentParser(description="Arxiv Text-To-Speach")
parser.add_argument('arxivID', help='Arxiv Identifier')
parser.add_argument('-o', '--output', default=False,
... | 43b5e7f52751e889d664ca7ba1cc6c493c24d5d8 | 35,022 |
def get_module_for_handler(handler_name):
"""
Gets the module for a handler using naming convention. First the name of the handler is capitalized and appended by the
string "Handler". Then it is converted from camel to snake case to get the name of the module that will be loaded. Raises an
ImportError e... | 1aace2db3658c4309501bb13deeaa0cbd3647654 | 35,023 |
def create_model(activations_outfeed_queue, gradient_accumulation_steps_per_replica):
""" Create the model using the Keras Model class.
Outfeed the activations for a single layer.
"""
input_layer = keras.layers.Input(shape=(28, 28, 1), dtype=tf.float32, batch_size=32)
x = keras.layers.Flatten()... | d7f536becc97a0cb7a4d6465b784a6ce828faeda | 35,024 |
def project_config(opts):
"""Template of project_config.yaml
Args:
opts: mapping parameters as dictionary
Returns:
str: file content as string
"""
template = get_template("project_config")
return template.safe_substitute(opts) | 12ce2cfbf967912586dd6c7a9a9dfe8e7eb00717 | 35,025 |
def _make_dense_split(quantile_accumulator_handle, stats_accumulator_handle,
stamp_token, next_stamp_token, multiclass_strategy,
class_id, feature_column_id, l1_regularization,
l2_regularization, tree_complexity_regularization,
min_... | 0d688a7290ebe05ab13488fc2ab0a04044beb29b | 35,026 |
from service import instance as instance_service
from datetime import datetime
def destroy_instance(instance_alias, user, core_identity_uuid):
"""
NOTE: Argument order changes here -- instance_alais is used as the first argument to make chaining this taks easier with celery.
"""
try:
celery_lo... | 29ce033a60cc5423a6074bbf26d9718ab7d7610e | 35,027 |
import torchvision
import torch
def load_data(dataset='cifar10', batch_size=128, num_workers=4):
"""
Loads the required dataset
:param dataset: Can be either 'cifar10' or 'cifar100'
:param batch_size: The desired batch size
:return: Tuple (train_loader, test_loader, num_classes)
"""
print(... | 2983bb2d350c5c6b8ad613186490815f954313e7 | 35,028 |
import netrc
import errno
def get_auth_from_netrc(hostname):
"""Try to find login auth in ``~/.netrc``. Return ``(user, pwd)`` tuple. """
try:
auth = netrc(file=NETRC)
except IOError as cause:
if cause.errno != errno.ENOENT:
raise
return None, None
username, _, pas... | da35fec0c9981166b14cce8870319eb9f1fb8e87 | 35,029 |
def _add_rows_by_count(df, amount, count, alloc_id, constraint, stuff=False):
"""
Add rows to a table so that the sum of values in the `count` column
is increased by `amount`.
Parameters
----------
df : pandas.DataFrame
amount : float
Amount by which to increase sum of `count` colum... | 1bb28f8e58116c469f100c65e9ec2f703f62cc6f | 35,030 |
def rot2(theta, deg=True):
"""returns 2D rotation matrix :math:`R \in SO(2)` to rotate a vector/point in a
plane in counter-clockwise direction
Parameters
----------
theta : float
the angle of rotation
deg : bool
``True`` = degree (default), ``False`` = radians
Returns
... | 557ff9b7135c62043ff767f4a33c8ca0484832bc | 35,031 |
import torch
def coin_flip(prob):
"""
Return the outcome of a biased coin flip.
Args:
prob: the probability of True.
Returns: bool
"""
return prob > 0 and torch.rand(1).item() < prob | 672929fb49a0e65101a4bdfdd13e981ae5eae31c | 35,032 |
import warnings
def _pair_exp_cov(X, Y, span=180):
"""
Calculate the exponential covariance between two timeseries of returns.
:param X: first time series of returns
:type X: pd.Series
:param Y: second time series of returns
:type Y: pd.Series
:param span: the span of the exponential weigh... | ffd64bb660d54444b64f11fc1a46c0a7c26169b4 | 35,033 |
def _protected_division(x1, x2):
"""Closure of division (x1/x2) for zero denominator."""
with np.errstate(divide='ignore', invalid='ignore'):
return np.where(np.abs(x2) > 0.001, np.divide(x1, x2), x1) | 676e8a2f72f076773d33501d2888871674ab6346 | 35,034 |
def get_config(client, config_type, basefolder="/config"):
"""
Return an object that can be used to push/pull configurations inside
an etcd database.
Examples:
import etcd3
import etcdgo
client = etcd3.Etcd3Client()
# push a json configuration inside database
... | db0eabbe025a924a18188cbc02c0fe934531986a | 35,035 |
def get_file_attribute_dtypes(filename):
# type: (str) -> Dict[str, str]
"""
Get the dtypes of the attributes of the file
:param filename:
:return:
"""
with h5py.File(filename, 'r') as infile:
return {key: type(value).__name__ for key, value in infile.attrs.items()} | ae03efa9210f898cf3fc120a87e313c1edbeae6e | 35,036 |
def default_input_format(content_type='application/json', apply_globally=False, api=None):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if apply_globally:
... | 1bbfb2cb23dbb2353804e701938d005aea941e86 | 35,037 |
import inspect
def popargs(*args, **kwargs):
"""A decorator for _cp_dispatch
(cherrypy.dispatch.Dispatcher.dispatch_method_name).
Optional keyword argument: handler=(Object or Function)
Provides a _cp_dispatch function that pops off path segments into
cherrypy.request.params under the names spec... | 9139de9770e5e295656331a31d44ca38d4dcecbc | 35,038 |
def to_pass(line):
"""
Replace a line of code with a pass statement, with
the correct number of leading spaces
Arguments
----------
line : str, line of code
Returns
----------
passed : str, line of code with same leading spaces
but code replaced with pass statemen... | f8444ecc38523aaef13d535258974881956e30b9 | 35,039 |
import numpy
def reverse_sort_C(C, sorted_index):
"""
Perform the reverse of sort described in sort_by_sorted_index, on rows in a numpy array.
Args:
C (numpy.array): array with C.shape[0] = len(sorted_index)
sorted_index (list of ints): desired order for rows of C
"""
m,n = C.shape
C_new = numpy.zeros(C.s... | a0865dba6479104bb1442ea185ec7913ed8cb53c | 35,040 |
def auto_reconnect_connection(func):
"""
Attempt to safely reconnect when an error is hit that resembles the
bouncer disconnecting the client due to a timeout/etc.
"""
@wraps(func)
def inner(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Except... | 88d69a885004d4c683aa653d8c79d43fb9408476 | 35,041 |
def windices_of_references(string, sen_dict):
"""
returns a list of word/sentence indices for all coreferences to
the given string in sen_dict.
returns [(0,0,0)] if there were no coreferences found.
"""
indices = []
coreferences = coreferences_for(string, sen_dict)
if not coreferences:
... | 2bf13beb67aa3e519fb40c06d59a018f89037890 | 35,042 |
def radius(x,y,z,xa,ya) :
"""
Compute distances between the control points (x,y) and a potential center (xa, ya)
in UTM coord, and sort the results depending on the elevation
of the control points (z)
Parameters
----------
x,y,z : UTM coordinates and Elevation of the control point
... | 3bbe20677dfd921c6c6d561f34b76ed54a12d266 | 35,043 |
def remove_labels(data):
"""
Keep only sqrt(n) of the real labels. To find the others, use k=sqrt(sqrt(n))
nearest neighbors from the labels we know, and use the mode.
"""
# "Remove" labels
# lost_idx = np.random.choice(
# len(data.y_train), size=int(len(data.y_train) - np.sqrt(len(data.y... | 4a13ab58309c7ca104375f47c4cdb6dee076fa19 | 35,044 |
import asyncio
async def async_setup(hass, config):
"""Set up the Ais Files platform."""
# register services
@asyncio.coroutine
async def async_transfer_file(call):
if "path" not in call.data or "name" not in call.data:
return
await _async_transfer_file(hass, call.data["pa... | 22bec0569edf73774100b5f8a70dcbd6d6d65de3 | 35,045 |
from typing import Iterable
import itertools
def expand(curr_state: State, params: FindPathParams) -> Iterable[Identifier]:
"""
Expand a state into it's children states
"""
per_agent_expansion = []
for agent in curr_state.identifier.actual:
agent: Agent
# if an agent is colliding... | 1aebb5701b22d26a250aded9ee1e8aede0a87eac | 35,046 |
import time
def SSDR(poses, rest_pose, num_bones, sparseness=4, max_iterations=20):
"""
Computes the Smooth Skinning Decomposition with Rigid bones
inputs: poses |num_poses| x |num_verts| x 3 matrix representing coordinates of vertices of each pose
rest_pose |num_verts| x ... | b4bf6b7d4a6c184b79ad0dcf2122ba31e1faef4f | 35,047 |
import itertools
def string_permutations(test_list, list_to_permutate):
"""Takes a list and a set, and returns a list of all the permutations as strings"""
str_perms = [list(permutation) for permutation in itertools.permutations(list_to_permutate)]
return [str(test_list + str_perm) for str_perm in str_pe... | b4cee2f34e0382a7cd2b49f5b5f22bc85712731a | 35,048 |
def to_cols(d):
"""Make a square matrix with columns equal to 'd'.
>>> print ker.to_cols(np.array([1,2,3,4]))
[[1 1 1 1]
[2 2 2 2]
[3 3 3 3]
[4 4 4 4]]
"""
return np.tile(d.reshape(len(d), -1), (1, len(d))) | 1a5dc76a86d3b5d83b6ac5360af3df041237dbce | 35,049 |
def captured_sensor(hass):
"""Create a captured today ArloSensor."""
data = _get_named_tuple({"captured_today": [0, 0, 0, 0, 0]})
return _get_sensor(hass, "Captured Today", "captured_today", data) | 045b78cf8929517b4f15f479503ed82814182cce | 35,050 |
def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
"""
Create a polar axes containing the matplotlib radar plot.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to draw into.
ax_position : (float, float, float, float)
The position of the ... | 1ea5e6248ab6b9053afe543d4ed3d8d31ec02d57 | 35,051 |
import time
def baseline_multiclass(train_data, train_labels, test_data, test_labels, args):
"""Train various classifiers to get a baseline."""
clf, train_accuracy, test_accuracy, train_f1, test_f1, exec_time = [], [], [], [], [], []
clf.append(sklearn.neighbors.KNeighborsClassifier(n_neighbors=15, n_jobs... | eb1a63b1921d54faa1141becdcc5d13716b08b7c | 35,052 |
def zeno_data(word: str)->[str]:
"""returns all available zeno data"""
result = [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None]
for pos in range(zeno.nrows):
if (word == zeno.cell(pos,0).value):
result[0] = zeno.cell(pos,1).value #sfi
... | 12981f05acfe9c7d272f7f907ec0ec51ddcf0d6a | 35,053 |
from operator import index
def transfer():
"""Logic for transferring $$"""
data = decode_url(request.get_data().decode())
otheruser = data.get("name", None)
amount = data.get("amount", None)
if not (otheruser and get_user(otheruser)):
return index(f"Other user is not found")
if not req... | 9afbda60cfb193a2d2852dfdc1accebe6d4fb845 | 35,054 |
from typing import Optional
def get_object_detection_by_id(odid: int) -> Optional[ObjectDetection]:
"""
Gets an object detection by id.
:param odid: The object detection's id.
:return: An object detection or None.
"""
try:
return ObjectDetection.objects.get(id=odid)
except ObjectD... | 3d3605326aa507d856c055edda787d2d407ac673 | 35,055 |
from cacao_accounting.contabilidad.registros.entidad import RegistroEntidad
from cacao_accounting.database import Entidad
def activar_entidad(id_entidad):
"""Estable una entidad como inactiva."""
REGISTRO = RegistroEntidad()
TRANSACCION = obtener_registro_desde_uuid(tabla=Entidad, uuid=id_entidad)
TR... | 10d9da05b464c924471cb316b4b2dbd9e778a79a | 35,056 |
import warnings
def trans_expected(clr, chromosomes, chunksize=1000000, use_dask=False):
"""
Aggregate the signal in intrachromosomal blocks.
Can be used as abackground for contact frequencies between chromosomes.
Parameters
----------
clr : cooler.Cooler
Cooler object
chromosomes... | 809d03501f6d6018da5133b65665f5046be36ca7 | 35,057 |
def exp_trans(base=None, **kwargs):
"""
Create a exponential transform class for *base*
This is inverse of the log transform.
Parameters
----------
base : float
Base of the logarithm
kwargs : dict
Keyword arguments passed onto
:func:`trans_new`. Should not include
... | fbd7ef154be3675d8b7010ae700e5b34d0f398c2 | 35,058 |
def broadcastable_to_str(b):
"""Return string representation of broadcastable."""
named_broadcastable = {
(): "scalar",
(False,): "vector",
(False, True): "col",
(True, False): "row",
(False, False): "matrix",
}
if b in named_broadcastable:
bcast = named_b... | 35dbe968a8341d076a264333c68fb597212439bc | 35,059 |
def avg_weapon_count_character(db):
"""Returns the average number of weapons per character from MongoDB
database.
Args:
db (pymongo.database.Database): MongoDB database
Returns:
(float) Average number of weapons per character
"""
agg_dict = [
{
"$lookup":
... | 0f65cad267d7b1d52730134e98e738dda56b2430 | 35,060 |
def partition(sort_list, low, high):
"""
All the elements smaller than the pivot
will be on the left side of the list
and all the elements on the right side
will be greater than the pivot.
"""
i = (low - 1)
pivot = sort_list[high]
for j in range(low, high):
if sort_list[j] ... | 3ae3a569fc5c3968ae047bf20df7a7a59bdfb0cf | 35,061 |
from argo.workflows.client import ApiClient
from typing import Dict
from typing import Any
def sanitize_for_serialization(obj: Dict[str, Any]) -> Dict[str, Any]:
"""Return object sanitized for serialization.
May be used with a V1alpha1Workflow to sanitize it
back to the original state (i.e. per manifest)... | 5a975e347ee529ac4db7777a0bc31750092f5442 | 35,062 |
def is_valid_degree_sequence(deg_sequence, method='hh'):
"""Returns True if deg_sequence is a valid degree sequence.
A degree sequence is valid if some graph can realize it.
Parameters
----------
deg_sequence : list
A list of integers where each element specifies the degree of a no... | 0ce013847902b002dcde32fbc0e818a5a506028c | 35,063 |
import collections
import itertools
def actor_critic(env, estimator_policy, estimator_value, num_episodes, discount_factor=1.0):
"""
Actor Critic Algorithm. Optimizes the policy
function approximator using policy gradient.
Parameters
----------
env: object
OpenAI environment.
estim... | d5df4121bb24d487e48c8f6e25a87c81e48dbc93 | 35,064 |
import os
import csv
def readMatSubfile(main_datafile, filename, header_list, args_dict):
"""
"""
value_separator = ','
comment_types = ['#', '!']
mat_subfile_enum = dataobj.SubfileMatEnum()
path = os.path.join(main_datafile.root, filename)
root = main_datafile.root
header1 = 'None'
... | 61c430b78908564c8d2a0abddec59bd149ac4c17 | 35,065 |
def get_vpc_id(ec2, subnet_id: str = None) -> str:
"""Returns VPC ID that should be used for deployment."""
if subnet_id:
vpc_id = Subnet.get_by_id(ec2, subnet_id).vpc_id
else:
default_vpc = Vpc.get_default_vpc(ec2)
if not default_vpc:
raise ValueError('Default VPC not fo... | b345b840b0efadec62c68f74f4a69fc06c45b81e | 35,066 |
from datetime import datetime
def _get_dates(request):
"""Obtain the start and end dates."""
today = date.today()
date_start = request.POST.get('date_start')
if not date_start:
date_start = today - timedelta(days=1)
else:
date_start = datetime.strptime(date_start, '%Y-%m-%d').date(... | d6313e9175de5e91965d162d066fbbbebe797914 | 35,067 |
import ast
import sys
def Test(argv, need_right_bracket):
"""The test/[ builtin.
The only difference between test and [ is that [ needs a matching ].
"""
if need_right_bracket:
if not argv or argv[-1] != ']':
util.error('[: missing closing ]')
return 2
del argv[-1]
w_parser = _StringWo... | 56661eb28ccff333100a6d686e71c8dbe9d0c4cb | 35,068 |
import numpy
def detect_model(items: numpy.ndarray) -> int:
"""Detects which logistic model an item matrix fits into.
:param items: an item matrix
:return: an int between 1 and 4 denoting the logistic model of the given item matrix
"""
a, b, c, d = _split_params(items)
if any(d != 1):
... | f24881dd125638bf559e129e2871863ce24fdb91 | 35,069 |
import typing
def split_value(input_val) -> (typing.Union[dict, list], typing.Union[dict, list]):
"""Split input_val into data for params.yaml and zntrack.json
Parameters
----------
input_val: dict
A dictionary of shape {_type: str, value: any} from ZnJSON
Returns
-------
params_... | be858fbfe5e65f02b79d37a54f7fd4d8123d1fc2 | 35,070 |
def assert_http_ok(resp, msg=None):
"""
Ensures the response is returning a HTTP 200.
"""
return assert_equal(resp.status_code, 200, resp.content if msg is None else msg) | 8758d78ed248aa39c92c5aacdda02d9cf3df3fbe | 35,071 |
def segnet_vgg13_bn(pretrained=False, progress=True, **kwargs):
"""Constructs a DeepLabV3+ model with a mobilenet backbone.
"""
model = SegNet(arch='segnet_vgg13_bn', **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls['segnet_vgg13_bn'], progress=progress)
model.lo... | 512f03e3e24bcfd143caacb77a6619c868738da0 | 35,072 |
def New_Dataframe(old_df,indicator_name):
""" create a new dataframe that is composed of only one indicator
Args:
old_df (dataframe): general dataframe from which we extract the new one
indicator_name (string): Name onf the indicator that will composed the new dataframe
Re... | 5ccd394a01a70b39b64d2a12ed0aac6f39296a0a | 35,073 |
def get_long_description():
"""Compose a long description for PyPI."""
long_description = None
try:
long_description = read_file('README.rst').decode('utf-8')
changelog = read_file('CHANGES.rst').decode('utf-8')
changelog = "\n".join(first_sections(changelog, '=', 4)) + """
Older ver... | 52352c9515f6e04aba2bb85f24a146ca25a42128 | 35,074 |
import re
def _create_matcher(utterance):
"""Create a regex that matches the utterance."""
# Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL
# Pattern matches (GROUP|OPTIONAL): Change light to [the color] {item}
parts = re.split(r'({\w+}|\[[\w\s]+\] *)', utterance)
# Pattern to... | 78b1fc8b2096d5dcc2c2b6dc4112d562b1e365de | 35,075 |
def change_video_state(player_name, state):
"""
:param player_name: video_player or topic_player or live or vr_live or pic_player or local_player
:param state: play or pause
:return:
"""
response = context.agent.call('ChangeVideoState', player_name, state)
if response.name == 'Fail':
... | d0f64b8e1266eed6df31db9ca2b072877f8e3ba9 | 35,076 |
import codecs
def generate(converter, input_file, format='xml', encoding='utf8'):
"""
Given a converter (as returned by compile()), this function reads
the given input file and converts it to the requested output format.
Supported output formats are 'xml', 'yaml', 'json', or 'none'.
:type conve... | 41a0c12387453b2e58972abe3c0f7d505036bb57 | 35,077 |
def compute_SS_TAS(df, cpds_median_score, num_L1000_feats = n_L1000_feats):
"""
Computes both Transcriptional activity score (TAS) and
signature strength per compound based on its replicates across all doses"""
dose_list = list(set(df['dose'].unique().tolist()))[1:7]
for dose in dose_list... | 451fce4e361ac8a6144d2d9aefed949d236f0db2 | 35,078 |
def check_args(args):
"""
Checks validity of command line arguments and, in some cases
modifies them a little bit.
:param args: The command-line arguments.
:type args: argparse.ArgumentParser Namespace
:returns: argparse.ArgumentParser Namespace -- The updated command-line
argumen... | 04270a50fce1003ee3960576b60bdcdc21f69767 | 35,079 |
import os
def GetIncludeGuardSymbol(file_name):
"""Returns include guard symbol for .h file.
For example, returns 'SOME_EXAMPLE_H' for '/path/to/some_example.h'
Args:
file_name: a string indicating output file path.
Returns:
A string for include guard.
"""
return os.path.basename(file_name).uppe... | 865d798a9a589e6de459d7e5bd8b3b250e74d069 | 35,080 |
import os
import logging
def build_contrastive_dataframe(df,
save_location,
num_samples,
sample_fn,
seed=None):
"""Builds a contrastive dataframe from scratch.
Given a universe of examp... | 8c29968e72843998743dff6790f515a3db9697ce | 35,081 |
from aiida.engine import Process
from aiida.orm.utils.node import is_valid_node_type_string
from typing import Tuple
def _get_ormclass_from_cls(cls: EntityClsType) -> Tuple[EntityTypes, Classifier]:
"""
Return the correct classifiers for the QueryBuilder from an ORM class.
:param cls: an AiiDA ORM class ... | c0471544887f614e6d98b90d38c595e0eb3fe5ad | 35,082 |
import warnings
def norm_diff(a):
"""Calculate average of (a[i] - a[i+1]) / (a[i] + a[i+1])."""
if len(a) <= 1:
return np.nan
a = a.astype(float)
if np.allclose((a[1:] + a[:-1]), 0.):
return 0.
norm_diffs = (a[1:] - a[:-1]) / (a[1:] + a[:-1])
norm_diffs[(a[1:] == 0) & (a[:-1]... | 1755b357ad9b84e742e0c432db420df9161d8dc5 | 35,083 |
def expand_batch_dims(structure, batch_sizes):
"""Expands the first dimension of each tensor in structure to be batch_sizes.
Args:
structure: A structure (tuple, namedtuple, list, dictionary, ...).
batch_sizes: A 1-D tensor of shapes describing the batch dims.
Returns:
A structure matching the input ... | 1c72fc555b42d4dbc0f066ba399dc8f4c96b7245 | 35,084 |
def VLBAAIPSName( project, session):
"""
Derive AIPS Name. AIPS file name will be project+session with project
truncated to fit in 12 characters.
* project = project name
* session = session code
"""
################################################################
Aname = Aname=projec... | 1a9009c01f00fbb47d7355fa1b8513177dbd3784 | 35,085 |
import torch
def test_unbalanced_logging_with_multiple_optimizers(tmpdir):
"""This tests ensures reduction works in unbalanced logging settings."""
class TestModel(MultiOptModel):
actual = {0: [], 1: []}
def training_step(self, batch, batch_idx, optimizer_idx):
out = super().tra... | b1c85a2ddba18af5c0e16c35e67a7b1757616805 | 35,086 |
from typing import Optional
def dot_general(lhs: Array, rhs: Array, dimension_numbers: DotDimensionNumbers,
precision: PrecisionLike = None,
preferred_element_type: Optional[DType] = None) -> Array:
"""More general contraction operator.
Wraps XLA's `DotGeneral
<https://www.tenso... | 824edf24f3130de598652e03da3aa2269f9e9b60 | 35,087 |
from typing import Tuple
def random(n: int, area: Tuple[float, float]):
"""
Generate random lines.
By default, 10 lines are randomly placed in a square with corners at (0, 0) and
(10mm, 10mm). Use the `--area` option to specify the destination area.
"""
lines = np.random.rand(n, 2) + 1j * np... | c3cfda6d9ccf133adf494b30d626d55fbb354b6a | 35,088 |
from pathlib import Path
def check_path_in_dir(file_path, directory_path):
"""
Check if a file path is in a directory
:param file_path: Full path to a file
:param directory_path: Full path to a directory the file may be in
:return: True if the file is in the directory
"""
directory = Path(... | 5e96abd89c72ea39a944e75b4548fc20b67892cd | 35,089 |
def trace_eyes(im, wnd_pos, wnd_dim, threshold, image_scale, filter_size, color_invert):
"""
Parameters
----------
im :
image (numpy array);
win_pos :
position of the window on the eyes (x, y);
win_dim :
dimension of the window on the eyes (w, h);
threshold :
... | 651c3a219d9e69d8e261659272f05e6ef9dc2519 | 35,090 |
def get() -> DslContextRegistry:
"""Gets the current active registry that observes DSL definitions."""
return _registry_holder.current | 31029f0996716266e0f14b5155eadf21c3fbd8ad | 35,091 |
def scalebar(length,slon='auto',slat='auto',az=90,label=True,ax=None,**kwargs):
"""
Plot scalebar of given length in meters.
Parameters:
length: Length of scalebar in meters
slon: Starting longitude (decimal degrees) for scalebar
slat: Starting latitude (decimal degrees) for sca... | 1981816449291cf8cf2ffe7a8afef1ea638dac47 | 35,092 |
def to_str(bytes_or_str):
"""
Return Instance of str
"""
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value | 5578e52f72fa5ee5d629748e0388cde4dffe62ee | 35,093 |
def flat_out(f, *a, **kw):
"""Flatten the output of target function."""
return f(*a, **kw).flatten() | ffe09ffbaae93657fde818de8a03cc17fee962f1 | 35,094 |
def delete_question(id):
""" Delete question. """
question = Question.query.get(id)
if question is not None:
question.delete()
response = {"message": "Object deleted."}
return make_response(jsonify(response), 200)
abort(404) | fd826877712efad3ea1344188f4571fd7e6bd9f3 | 35,095 |
def vgg16_cinic10_bn(pretrained=False, progress=True, **kwargs):
"""
VGG 16-layer model (configuration "D") with batch normalization
Inspired by: https://github.com/geifmany/cifar-vgg/blob/master/cifar100vgg.py to follow
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7486599 and then gave up on Dr... | f7c86108208352dd89b34fb64c7a9875e594e470 | 35,096 |
import argparse
def _parser():
"""Take care of all the argparse stuff.
:returns: the args
"""
parser = argparse.ArgumentParser(
description='Interactively normalize fits spectra.')
parser.add_argument("fitsname", type=str,
help="Specturm to continuum normalize.")
... | ef5b682909925ef95f7d1388f8c28e1bd8d27027 | 35,097 |
from .apiv1 import blueprint as api1
def create_app(config_name):
"""
初始化Flask的应用对象,并初始化数据库等内容
:param config_name: str 配置模式的模式的名字 ("develop", "product")
:return:
"""
# 创建app
app = Flask(__name__)
@app.after_request
def after_request(response):
response.headers.add('Acces... | 79288b830a2ec8809253ecf98c1b610e1dce3c52 | 35,098 |
def add_vote_and_redirect(event, _):
"""
Handle add vote requests and redirect to a info page
:param event: event
:return: redirect to a page explaining that the vote was added
"""
# Save the vote
do_vote(event, None)
redirect_url = "/voted"
# Find the user and determine the redire... | 7db963fb8a0f17f7e8221038f70e06f14dd931fd | 35,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.