content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
"""
internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
"""
fmt = u("{%s}")
pairs = []
pfmt = u("%s: %s")
if max_seq_items is False:
nitems = len(seq)
els... | 2ed161c2d9e15b5636dd1c554a313f3e771320f9 | 54,000 |
def userTagOrDiscrim(userID : str, guild : Guild = None) -> str:
"""If a passed user mention or ID is valid and shares a common server with the bot,
return the user's name and discriminator. TODO: Should probably change this to display name
Otherwise, return the passed userID.
:param str userID: A user... | 82f6edb6fc92f70a96eb61482e2d8a457fd36d5f | 54,001 |
import time
def acquire_lock(conn, lockname, identifier, acq_timeout=ACQ_TIMEOUT,
timeout=DEFAULT_TIMEOUT):
"""
Wait for and acquire a lock. Returns identifier on success and False
on failure.
Args:
conn: redis connection object
lockname: name of the lock
iden... | 4a9daca713b22ec9ad66aac9cd39a5addf133dfe | 54,002 |
def make_entries(screen, settings):
"""This function makes entries with keys, default values and labels from
settings. It returns a dictionary with entry widgets as values."""
entries = dict()
# For each setting, create a text field and put it next to the
# corresponding label.
for i, (key, def... | 80ee191b355b7802759848bd9dc5a40ef38d4788 | 54,003 |
def template_view_factory(template_name, context={}):
"""Returns a generic view which renders a template using the optional
context and request. """
return lambda request: render_to_response(template_name, context, request) | 3972d19a2884aadc848e62629ba6434cd505a118 | 54,004 |
from typing import Sequence
from typing import Mapping
from typing import Counter
def calculate_resource_utilization_for_kube_nodes(
nodes: Sequence[V1Node], pods_by_node: Mapping[str, Sequence[V1Pod]],
) -> ResourceUtilizationDict:
""" Given a list of Kubernetes nodes, calculate the total available
resou... | 6d3a8b6123d778975d33ad7fcf6e75354e125e0c | 54,005 |
def unfuse_right(A, shp):
"""
Reverses fuse_right.
"""
d, chiL, chiR = shp
A = A.reshape((chiL, d, chiR)).transpose((1, 0, 2))
return A | 31d2e50d3a5ca715dc04ee9305db76cbc566de3e | 54,006 |
from saq.database import get_db_connection
def delete_password(key):
"""Deletes the given password from the database. Returns True if the password was deleted."""
with get_db_connection(name=saq.CONFIG['global']['encrypted_passwords_db']) as db:
c = db.cursor()
c.execute("DELETE FROM `encrypte... | 4c00f0b70075a031cfb458dec62f10d478d16a67 | 54,007 |
def gaussion_f(mu, sigma2, x):
"""
Gaussian function
:param mu:
:param sigma2:
:param x:
:return:
"""
return 1 / sqrt(2 * pi * sigma2) * exp(-0.5 * (x - mu) / sigma2) | dbd299debe98d2c5dcc135edcab311f83881c93f | 54,008 |
def validate_owner_repo(ctx, param, value):
"""Ensure that owner/repo is formatted correctly."""
# pylint: disable=unused-argument
form = 'OWNER/REPO'
return validate_slashes(param, value, minimum=2, maximum=2, form=form) | 685bd4a14ee5e5fbb9df0627624ce37bf63d790b | 54,009 |
def squiggleFig(x1,y1,d1,a1,w1, x2,y2,d2,a2,w2):
"""Return a rounded bezier curve -- something like ~.
This is the naive implementation, using 2 identical slightly-offset
bezier curves to outline the figure. It looks uneven or calligraphic.
xn,yn = endpoints
dn = distance of control point from end... | d85b0a9d311fed24b95b2cf55feae58c53f5277d | 54,010 |
def check_free_space(min_free_space: int) -> bool:
"""
Check available free space in filesystem and return True/False if there is enough free space
or not.
min_free_space is measured in kB
"""
if not any([isinstance(min_free_space, int), isinstance(min_free_space, float)]):
log.warning(... | 8aa34685790fe3444a97795cbd7522969b10f0ac | 54,011 |
def spechum2mixr(q):
"""
Calculate mixing ratio from specific humidity.
**Inputs/Outputs**
Variable I/O Description Units
-------- --- ----------- -----
q I Specific humidity kg/kg
r O Mixing ratio kg/kg
"""
return q/(1-q) | 88a5109c00dedaba03f6f323437f661ef72b794e | 54,012 |
def get_formato_series(series, entidades):
"""
Convierte groupby a formato tidy (columnas son estados e indice es la fecha).
Input:
- series:
DataFrame en formato groupby agrupada for una columna que corresponde a
entidades federativas y otra columna que corresponde a una fecha.
- e... | 391202594898864390e52acd2806ef80cb96f9d0 | 54,013 |
def numpy_image_to_float(img, out_range=(0, 1)):
"""
Convert a numpy image (3d tensor, h x w x channels) into float format where
the output range is as given in out_range.
Return a numpy array.
"""
# http://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.img_as_float
new_img = s... | 223340546802b966754b2eba02c62d44c9d6d657 | 54,014 |
def dataset_get_table_table_name_post(tableName): # noqa: E501
"""Returns the specified table
Returns the HTML Representation of the table. # noqa: E501
:param tableName: Should be equal to either bitcoin, bitconnect, dash, ethereum, iota, litecoin, monero, nem, neo, numeraire, omisego, qtum, ripple, str... | 3219a03cce5527da6d96271679e4c645cb949f45 | 54,015 |
def timeEvolutionMatrix(n, E, G, Q, Q_decay, tau, laser_wavelength, laser_intensity,
tau_f = None, detuning = None, symbolic_print = None, numeric_print = None,
rabi_scaling = None, rabi_factors = None, atomic_velocity = None):
"""Function to create and populate the co... | 77bf2bba3fff1fe3d9f644eedc3df8320171d3ef | 54,016 |
def load_focalplanes(args, comm, schedules, verbose=False):
""" Attach a focalplane to each of the schedules.
Args:
schedules (list) : List of Schedule instances.
Each schedule has two members, telescope
and ceslist, a list of CES objects.
Returns:
detweights (dict)... | 103010dcd05d9b37c10cb16c5e79789cf22901bd | 54,017 |
def in_cluster_scvelo_coh(adata, k_cluster, k_confidence, return_raw=False):
"""In-Cluster Confidence Score.
Args:
adata (Anndata): Anndata object.
k_cluster (str): key to the cluster column in adata.obs DataFrame.
k_confidence (str): key to the column of cell velocity confidence in... | 0032d75b447d03dfbf3d104d61bca585808a428e | 54,018 |
import asyncio
async def discover():
"""Discover and return devices on local network."""
discover = TuyaDiscovery()
try:
await discover.start()
await asyncio.sleep(DEFAULT_DISCOVER_TIMEOUT)
except Exception:
_LOGGER.exception("failed to discover devices")
finally:
d... | 7e30507ee4dc994971642c6b051820e5cbbf965b | 54,019 |
import time
import re
import types
def serve_responses(responses, passwords, pubkeys, port):
"""
Return a threading TCP based SocketServer listening on ``port``.
Used as a fake SSH server which will respond to commands given in
``responses`` and allow connections for users listed in ``passwords``.
... | a4c4b8950151a75476f68a7e3b81495a732165c4 | 54,020 |
def svn_client_mkdir2(*args):
"""svn_client_mkdir2(apr_array_header_t paths, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t"""
return _client.svn_client_mkdir2(*args) | 9a7a2e39f331c757d0be4e234d6452efccd16044 | 54,021 |
def factory_share_class(business_identifier: str):
"""Create a share class."""
business = factory_business(business_identifier)
share_class = ShareClass(
name='Share Class 1',
priority=1,
max_share_flag=True,
max_shares=1000,
par_value_flag=True,
par_value=0.8... | 7c2cf069e91c36ce3f314c753c8ddb8f86a9abb4 | 54,022 |
def update_output(list_of_contents, list_of_names, list_of_dates):
"""
check for upload of the files
"""
if list_of_names:
if len(list_of_names) == 1:
if list_of_contents is not None:
children = [
parse_contents(c, n, d) for c, n, d in
... | 9d462947e82687030d22047bef8b53f9f7106d91 | 54,023 |
import logging
def upload(csv_file, bucket_name, blob_name):
"""Uploads csv_file to bucket_name.
Args:
csv_file: CSV file to upload.
bucket_name: Bucket to upload the files to.
blob_name: Path of the file in the bucket.
Returns:
The path of the uploaded file in GCS.
""... | 8f8d4d9ce1722d1356093209a19e81aca4754fa8 | 54,024 |
def lift(cra, crb):
"""Returns the relative uplift in conversion rate.
Parameters
----------
cra: float
Conversion rate of Group A
crb: float
Conversion rate of Group B
Returns
-------
float
Relative uplift in conversion rate
"""
return ((crb - cra) / cra)... | 2489fef702153657f007751bc5234d11d8333f75 | 54,025 |
import logging
def get_asso_words(txt, stopwords, w, window=2, t=2, s=0.5, m=10):
"""Main method for getting keywords
Keyword arguments:
txt -- txt-file address
stopwords -- stopwords-file address
word -- the keyword to query
window -- adjacent window ... | 3d99735e2372a35b3fd03e7eef816d5d38e6241b | 54,026 |
def convert_object_to_float(x):
"""
Convert input object to float
:param x: input series/signal as datatype not a float
:return: same series/signal with datatype float.
"""
if isinstance(x, str):
x = x.strip('\'')
try:
return float(x)
except ValueError:
... | 6b862b1202e0180bf2ee6d1d0916c0cf4aed09ae | 54,027 |
import numpy
def _get_pressures(sounding_dict):
"""Returns pressure levels in soundings.
:param sounding_dict: Dictionary created by
`_convert_interp_table_to_soundings` or `_pressure_to_height_coords`.
:return: pressure_matrix_pascals: N-by-P numpy array of pressures.
"""
if PRESSURE_LE... | 3032dfc577743b64c229b68be56708b36ad920af | 54,028 |
import ast
def load(symbol_id: str) -> ast.Name:
"""Returns an AST Name node that loads a variable."""
return ast.Name(id=symbol_id, ctx=ast.Load()) | 94a76bdac89a9e7b1f766832dd2aef63469704ac | 54,029 |
import tests
async def subprocess() -> tests.helpers.Subprocess:
"""Return an asynchronous executor for testing subprocesses."""
return tests.helpers.Subprocess() | 00016d30b7033c72c85742aa2e43566ec8fbd9b0 | 54,030 |
def controller_encryption_key_id_generate(handle, controller_type,
controller_slot, server_id=1):
"""
Generates a random key id for the given controller
Args:
handle (ImcHandle)
controller_type (str): Controller type
'... | 3c29230b745bf61f09f7ba390b17c5e3f60e4602 | 54,031 |
def is_videoid_in_db(videoid):
"""Return True if the video is in the database, else False"""
if videoid.mediatype == common.VideoId.MOVIE:
return G.SHARED_DB.movie_id_exists(videoid.value)
if videoid.mediatype == common.VideoId.SHOW:
return G.SHARED_DB.tvshow_id_exists(videoid.value)
if ... | cf6df695e6d6ce33e02a22267416069570762d3d | 54,032 |
def image_frame_to_camera_frame(image_frame, camera_intrinsics):
"""Un-project points that are in image frame to the camera fame.
Given a camera intrinsics matrix K, and a set of 2d points in image frame,
this functions returns the 3D points at unit depth.
Currently this function only supports a linear camera... | e8f2bb1fd5d4cb393977ef7fd1cc9d65e08c9043 | 54,033 |
def descent(X, targets, thetas, hypothesis, calc_cost, **kwargs):
"""Gradient descent"""
MAX_ITS = kwargs.pop('max_its', DEF_MAX_ITERATIONS)
LRN_RT = kwargs.pop('lrn_rt', DEF_LEARNING_RATE)
REG_P = kwargs.pop('reg_p', DEF_REG_P)
MIN_DELTA = kwargs.pop('min_delta', DEF_MIN_DELTA)
m = len(targets)
cost_his... | 8a1416fe0b1bc261f0282e3df444e06840d8112b | 54,034 |
def sharpe(returns, rfr=0, expanding=0):
"""
returns: periodic return string
rfr: risk free rate
expanding: bool
"""
if expanding:
excess = excess_returns(returns, rfr)
return pd.expanding_mean(excess) / pd.expanding_std(returns)
else:
return excess_returns(returns, r... | 1d8fff9ea219fb8a3ccbb56ede4d36414080f571 | 54,035 |
def _NegGrad(_, grad):
"""Returns -grad."""
return -grad | c2a2800e1d80c3151019425e3871c235485c9324 | 54,036 |
def utilize_ListOf(schema, data, **kwargs):
""" Validate a list with arbitrary length.
Validate each value from `data` against `schema.schema`.
`schema` is a `ListOf` instance. """
schema_list = [schema.schema for item in data]
return utilize_list(schema=schema_list, data=data, **kwargs) | 180bcdf358615075d705ea8614e4eec75ea273c9 | 54,037 |
from typing import OrderedDict
def init_vec(f, names, data):
"""Initialize resizable 1d arrays to hold the outputs."""
# Iterate over 'names' and columns of 'data'
dset = [
(name, f.create_dataset(name, data=d, maxshape=(None,)))
for name, d in zip(names, data.T)
] # -> list
retu... | ed024e176da68d1a6753da305cea0a36d21e0e7a | 54,038 |
import base64
def powershell(
cmd,
cwd=None,
stdin=None,
runas=None,
shell="powershell",
env=None,
clean_env=False,
template=None,
rstrip=True,
umask=None,
output_encoding=None,
output_loglevel="debug",
hide_output=False,
timeout=None,
reset_system_locale=Tr... | 23520a1699cd123b72b0f5b8a17ad1c3810f7523 | 54,039 |
import os
import gc
import random
def play_one_file(idx, filename, folder, title, playlist_size):
"""Play one file, reacting to user input"""
board.DISPLAY.auto_refresh = False
playback_display.set_bitmap([
filename.rsplit('.', 1)[0] + ".bmp",
filename.rsplit('/', 1)[0] + ".bmp",
... | 432e8d1e8bcd557561ad69c73b5c591dc9a7a72d | 54,040 |
import inspect
import builtins
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be re... | 4e726ed1d748b9b3331cf5f6556702a015ccc31e | 54,041 |
def clean_url(url):
"""
Reformat a URL with all querystrings stripped
:param url: The URL
:return: A clean URL
"""
return url[:url.find('?')] | 56edc6db7b59e1550a68377dcdcb80a83b79e854 | 54,042 |
import tqdm
def get_camera_bouma(df, fieldfile='../data/camera_boresights_SNE-shifted.csv'):
"""
Like get_camera, only better
"""
camdf = get_camera_coords(fieldfile)
observed = np.zeros((df.shape[0], camdf.shape[0]), dtype='int')
for ix, row in tqdm(camdf.iterrows(), total=camdf.shape[0]):
... | f516a780b7bbbf13fc9073c260b875007c114a20 | 54,043 |
def animal_categories():
"""Return list of strings"""
categories = open(CATEGORIES_ANIMAL_PATH).readlines()
categories = [c.strip() for c in categories]
return categories | 2dfeb18cd3819565b18933e71b6b39ef7345fa56 | 54,044 |
import json
def read_json(path: str) -> dict:
"""
This method reads the file specified in
:param path: resource path
:return: json object
"""
with open(path) as f:
data = json.load(f)
return data | 9bb4b4c43fb3585dfd004f2d297997b99a68b19b | 54,045 |
def rmseff(x, c=0.68):
"""Compute half-width of the shortest interval
containing a fraction 'c' of items in a 1D array.
"""
x = np.sort(x, kind="mergesort")
m = int(c * len(x)) + 1
return np.min(x_sorted[m:] - x_sorted[:-m]) / 2.0 | c69c26da13a5c26c85f572360d0e2cd1eb2e39c9 | 54,046 |
def small_movies_json_file():
"""
Runs once per session. Provides the content of small_movies.json from read.
"""
with open('./datasets/small_movies.json', 'r', encoding='utf-8') as movie_json_file:
return movie_json_file.read().encode('utf-8') | b6a744a01411b93aa96580a75c3cfb3786f49a35 | 54,047 |
def get_router_connection(deploy_config: dict) -> paramiko.SSHClient:
"""
Opens a connection to the configured router
Can throw:
- ValueError
- BadHostKeyException
- AuthenticationException
- SSHException
- socket.error
"""
router_config = deploy_config["rout... | 470e84210981cac27021d6be13d69c5a4c137b4d | 54,048 |
import re
def isValid(text):
"""
Returns True if the input is related to the meaning of life.
Arguments:
text -- user-input, typically transcribed speech
"""
return bool(
re.search(
r'email',
text,
re.IGNORECASE)) or bool(
re.sea... | a03fc94f223397f163382b40bee885101ef4420a | 54,049 |
def _has_abstract_methods(node):
"""Determine if the given `node` has abstract methods.
The methods should be made abstract by decorating them
with `abc` decorators.
"""
return len(utils.unimplemented_abstract_methods(node)) > 0 | a2276ede374bb9d12ec0de81d03646f631cd291e | 54,050 |
def simplify_tags(tags):
"""
>>> simplify_tags([set([('defined(world)', True), ('defined(hello)', True)]),
... set([('defined(world)', False), ('defined(hello)', True)])])
[set([('defined(hello)', True)])]
>>> simplify_tags([set([('defined(LIBEV_EMBED)', True), ('defined(_WIN32)', Tru... | 43f8a7aa16ea054daaa8f948144304beef998668 | 54,051 |
import torch
def mol_to_graph_data_obj_simple(
mol,
partial_charge=False,
substruct_input=False,
pattern_path=None,
mask=False,
hops=5,
pooling_indicator=False,
):
"""
Converts rdkit mol object to graph Data object required by the pytorch
geometric package. NB: Uses simplified ... | b8f9e1f5bcd9be90882b0695e1543209200189c8 | 54,052 |
def level_is_rtl(lev):
"""
Return True if `lev' is a Right-to-Left level, False otherwise.
"""
return lev & 1 | 5c3d6127bcef2f17b347c7c26a86f723f25ab6a7 | 54,053 |
from datetime import datetime
def bpcalc(request):
"""Calculate blueprint production details for X number of days"""
# Get a valid number of days
try:
days = max(1, int(request.GET.get('days', '7')))
except ValueError:
days = 7
# Initialise variabls
bpis = []
bpi_totals = ... | e7221802f64b98feedf85bbc24b974ef8ff878a5 | 54,054 |
def calc_E_E_L_d_t(n_p, A_A, A_MR, A_OR, L):
"""1 時間当たりの照明設備の消費電力量(kWh/h)
Args:
n_p(float): 仮想居住人数
A_A(float): 床面積の合計[m^2]
A_MR(float): 主たる居室の床面積[m^2]
A_OR(float): その他の居室の床面積[m^2]
L(dict): 照明設備仕様辞書
Returns:
ndarray: E_E_L_d_t 日付dの時刻tにおける 1 時間当たりの照明設備の消費電力量[kWh/h]
"... | efe38cbfbc414109f2e7036651d3b1cf9e57ace5 | 54,055 |
def safe_divide(numerator, denominator, ones=False):
"""Divide ignoring div by zero warnings"""
if isinstance(numerator, pd.Series):
numerator = numerator.values
if isinstance(denominator, pd.Series):
denominator = denominator.values
numerator = numerator.astype(float)
denominator ... | 29c1a8d98838996fb5803f9d663ca51b37662413 | 54,056 |
def fgt_set_sensorRegulation(sensor_index, pressure_index, setpoint):
"""Sets the flow rate on the specified flow rate channel, using the
specified pressure channel as an actuator"""
c_error = c_ubyte(lib.fgt_set_sensorRegulation(c_uint(sensor_index),
c_uint(pressure_index), c_f... | b501de599d588cc35e0a3ccb24fec9d1656805a0 | 54,057 |
def _read_solvr(f):
"""Read SOLVR block data."""
fmt = block_to_format["SOLVR"]
solvr = {}
line = next(f)
data = read_record(line, fmt)
solvr["solver"] = {
"method": data[0],
"z_precond": data[2],
"o_precond": data[4],
"rel_iter_max": data[5],
"eps": data... | 2322711f2dbe934e53a7ab67db812b82e6e0de1c | 54,058 |
from datetime import datetime
import argparse
import sys
import logging
import os
import requests
def main() -> int:
"""
Runs the program
:returns: an exit code for the script
"""
global TO_COOKIE, TO_LOGIN, TO_URL, LOG_LEVELS, MODE, needInstall, DISTRO, TS_ROOT, FMT
# I have no idea why, but the old ORT scri... | d85edad9dee676a654c12f0e116793489789ba4c | 54,059 |
import torch
def default_states_preprocessor(states):
"""
Convert list of states into the form suitable for model. By default we assume Variable
:param states: list of numpy arrays with states
:return: Variable
Obtained from https://github.com/Shmuma/ptan/blob/master/ptan/agent.py
"""
... | 997f3e9e21cfd9dac0fa78d23ee41232b0aeea82 | 54,060 |
from typing import List
def get_candidates_for_bid(bid_id: str) -> List[helpling_schema.DecoratedPotentialCandidateEdge]:
"""
Query the API for all (i.e. the first 1000) candidates for a given bid. The bid must have been parametrized already.
Note that not all fields are actually requested from the backen... | 55a327daec333ed99613d55ce593714e1829f734 | 54,061 |
import math
def arc_svg_to_parametric(src, dst, rx, ry, x_axis_rot, large_flag, sweep_flag):
"""Convert arc from SVG arguments to parametric curve
This code mostly comes from arc implementation notes from svg sepc
(Arc to Parametric)[https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes]
Re... | 52d6de27dac64978987e11156f1f597d8910a753 | 54,062 |
def GroupBuilder(size, builderFunc, indAttr):
"""size - the number of members of the group
indAttr - a list of [size, possList, probList] for IndividualBuilder
file - the csv file to rebuild an existing group from"""
individualSize = indAttr[0]
possList = indAttr[1]
probList = indAttr[2]
... | 8bd144c71acd177518b12ce2dd209d2838c6fff4 | 54,063 |
import os
import subprocess
def detect_number_of_cores():
"""
Detects the number of cores on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROC... | c2cc555526545640c4908715aa62d2b593c0de32 | 54,064 |
def _read_timestamp(file):
"""Get start and end time from timestamp csv file."""
try:
with open(file, 'r') as f:
rows = f.readlines()
starttime, endtime = float(rows[0].split(",")[0]), float(rows[-1].split(",")[0])
starttime, endtime = starttime / (10**3), endtime / (10**... | be403b62623f45e6cf43c6239c1c068a48987183 | 54,065 |
from typing import Dict
def _refine_resourcedetails(response: Dict, Translator: DataFields) -> ResourceDetails:
"""Parse the resource details response.
Args:
response: Ganttic API response
Translator: Description of fields
Returns: task Details Pydantic.
"""
res = response.copy(... | ed237682657b44a33cef0d914d702989c7672540 | 54,066 |
def plot_sim_matrix(clusterings, scoring):
"""
Plot a similarity matrix between a list of clusterings, using the provided scoring function.
:param clusterings: list of clusterings to compare
:param scoring: the scoring function to use
:return: a ClusterGrid instance
Example:
>>> from cdli... | cb6d78637dbb3f1fb94d7cd1d90a8447e98c685f | 54,067 |
def _copy_attachments(syn: Synapse, entity_wiki: Wiki) -> list:
"""Copy wiki attachments
Args:
syn: Synapse connection
entity_wiki: Wiki you are copying
Returns:
Synapse Attachment filehandleids
"""
# All attachments must be updated
if entity_wiki["attachmentFileHandle... | 6efde5c82784adab0dbcb01eeeef808c727044a4 | 54,068 |
def generic_actor(name=None, health=None,
r=None, g=None, b=None, y=None,
x=None, m=None, h=None, c=None):
"""Simple factory to keep tests focused."""
base = (50, 100)
health = health or base
r = r or base
g = g or base
b = b or base
y = y or base
x = ... | ac6bce23951eddd0edd84733017d87d214097a47 | 54,069 |
def error_not_found(message, redirect):
"""
Shows an error message that a page couldn't be found.
"""
return error('Not found: {}'.format(message), redirect) | 15ec1c261027b6e610adb06107e8e4fde2098ef6 | 54,070 |
import math
def Rz(angle:float, use_degrees:bool=False) -> np.ndarray:
"""Rotation matrix, for a rotation about the z-axis.
Args:
angle (float): Counter-clockwise angle of rotation as viewed
looking back along the postive direction of the rotation axis.
use_degrees (bool): Handle... | 541dffe668dae30fdc2f4daf12e049a8274c9991 | 54,071 |
def __folha(soup):
"""
Gets the most read news from the Folha de Sao Paulo page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Folha de Sao Paulo Page
"""
news = []
anchors = soup.find('ol', class_='c-most-read__list').find_all('a')
for a in anc... | c2f518776ac6969be93f96b4320dc596f708ecd6 | 54,072 |
def get_table_cols_w_type(table, conn_handler=None):
"""Returns the column headers and its type
Parameters
----------
table : str
The table name
conn_handler : SQLConnectionHandler, optional
The connection handler object connected to the db
Returns
-------
list of tuple... | 3663f9cb1b34adafbd43a6dc6dcecd8f9efd537b | 54,073 |
from typing import Callable
from typing import Awaitable
def _require_auth(
handler: Callable[[web.Request, "User"], Awaitable],
*,
redirect: bool = True,
admin: bool = False,
) -> Callable[[web.Request], Awaitable]:
"""This does the heavy lifting for the authorization check"""
@wraps(handler... | ffaba778620eb5eb0286733bbf4f0cf8f9adcee0 | 54,074 |
import torch
def generate_padding_mask(x: torch.Tensor, length: torch.Tensor) -> torch.Tensor:
"""
Args:
x: tensor of shape [batch_size, length]
length: tensor of shape [batch_size]
Returns:
float tensor of shape [batch_size, length]
"""
assert x.dim() == 2
assert lengt... | d475cfa6eb81525745bed8613827c59bac57aa5d | 54,075 |
def track_command(func):
"""
Decorator to track execution of a command. This method executes the function, gathers all relevant metrics,
reports the metrics and returns.
If you have a Click command, you can track as follows:
.. code:: python
@click.command(...)
@click.options(...)
... | cb60a1c2b9605a3363608b4009ea03afc9f5d13f | 54,076 |
import subprocess
def change_events_timegenerated():
"""
:return: True if successfully changed the TimeGenerated configuration
"""
collect_to_create = "s|'Timestamp' => OMS::Common::fast_utc_to_iso8601_format(Time.now.utc),|'Timestamp' =>" \
" OMS::Common::fast_utc_to_iso8601_f... | 8a9b70a44989d2855444aeba5d91e05c7e54df95 | 54,077 |
import functools
import time
def slow_down(_func=None, *, rate=1):
"""Sleep given amount of seconds before calling the function"""
def decorator_slow_down(func):
@functools.wraps(func)
def wrapper_slow_down(*args, **kwargs):
time.sleep(rate)
return func(*args, **kwargs)... | 15018e0012fb3486d10a3883a8603235c876d651 | 54,078 |
def RegularStrandCurvature(**kwargs):
"""
Returns angle and dihedral constraints strings that dictate the curvature of strands
without bulges. Given a strand, place curvature and twist constraints every 2*level positions.
Angle constraints, for curvature, are placed on CA atoms. Dihedral... | 15e5590b06b9a9c7934693504bd464abdf45f8d6 | 54,079 |
import pathlib
def test_get_save_file(mocker, tmp_path):
"""
test get_save_file
"""
def mock_user_data_dir(appname, appauthor, version):
return tmp_path / appname / appauthor / version
mocker.patch.object(resources.appdirs, "user_data_dir",
mock_user_data_dir)
m... | 07ac2e90233521c3fb6d3ccb8885c38a78105a14 | 54,080 |
def _compose_tfms(args):
"""Create a composite transform from inputs."""
in_file, in_xform, ifargs, index, newpath = args
out_file = fname_presuffix(in_file, suffix='_xform-%05d' % index,
newpath=newpath, use_ext=True)
xfm = ants.ApplyTransforms(
input_image=in_fi... | 363bc3a021a9afc297e638ad445561d37d08943a | 54,081 |
async def changelog() -> HTMLResponse:
""" Display the changelog for this API """
return HTMLResponse(content=_get_changelog_html()) | e342cd507807bcb2f4e9019e98096e012af341ba | 54,082 |
def set_level(world_number, char): # used for changing to a new level and reloading level
"""
Changes the level and soft-resets the character state.
The total gold collected is stored, while current gold is reset.
The character's position is also set to the new world's start position.
If not all t... | c7975142227b73cd47c5e466232fbb7a75d109dc | 54,083 |
def apply(df, target_func, n_cpus=None):
"""
Apply row-wise a user-defined target function to the file index. Each row
is passed as input to the function. The call for each row is done in parallel.
Parameters
----------
- df: a DataFrame with the file index.
- target_func: a user-defined f... | 5f6d5c1abf04638c0d033e7b9aecb566956d5832 | 54,084 |
def load_mnist() -> Dataset:
"""Loads the MNIST dataset using OpenML.
OpenML dataset link: https://www.openml.org/d/554
"""
mnist_openml = openml.datasets.get_dataset(554)
Xy, _, _, _ = mnist_openml.get_data(dataset_format="array")
X = Xy[:, :-1] # the last column contains labels
y = Xy[:, ... | 5f781c803dae9b609ae1b4d1912493661babed0b | 54,085 |
from typing import Union
from typing import Callable
import torch
from typing import Dict
from typing import Optional
from typing import Any
def gen_save_best_models_by_val_score(
save_handler: Union[Callable, BaseSaveHandler],
evaluator: Engine,
models: Union[torch.nn.Module, Dict[str, torch.nn.Module]],... | a78792c2ac45199100851ad2a6c6eaa88f15de4f | 54,086 |
def favicon():
""" Returns the favicon when working in dev. """
return flask.send_from_directory('static/images', 'favicon.ico') | 6298a327f0764a227e95020d7da21765e16b0521 | 54,087 |
def load_np(filename, control=False):
"""
Load the raw data from h5 files
:param filename: [string] filename to be read in
:return: 4 x [np array[float64]] leads, [np array[int]] time vector,
[np array[int]] heartrate vector from machine, [np array[float64]] abs pos sum ECG signal
"""
pr... | 2115c898d5cf6e2cce6948ce8f9ba6848b399e60 | 54,088 |
def get_ent(s):
"""
Return 1 if there is no enantiomer and 2 if there is based on
@ sign appearing in the smiles
"""
sites = 0
xyz = get_xyz(s)
s2 = get_smiles(xyz)
frags = s2.split('[')
for frag in frags:
if '@' in frag:
sites += 1
ent = 2.**sites
retu... | 62d39b6a6ce44ab018ab9108c8db6724f739a3a6 | 54,089 |
from typing import Union
def read_pkg_info(path: Union[bytes, str, PathLike]) -> Message:
"""Read a PKG-INFO or METADATA file."""
with open(path, encoding="utf-8") as headers:
return Parser().parse(headers) | 728914c88bc8eac5e02b3f537bb935166788f335 | 54,090 |
import __builtin__
def isdefined(obj, force_import=False, namespace=None):
"""Return True if object is defined in namespace
If namespace is None --> namespace = locals()"""
if namespace is None:
namespace = locals()
attr_list = obj.split('.')
base = attr_list.pop(0)
if len(base) == 0:
... | 0163770ada4122f7e690ab15fe2226da4005f885 | 54,091 |
from typing import Dict
from typing import Any
from typing import Type
from typing import Optional
from typing import Callable
from re import T
def deserialize_namedtuple(
obj: Dict[str, Any],
to: Type[NT],
attr_deserializers: Optional[Dict[str, Callable[[PrimitiveType], T]]] = None,
type_deserializer... | 5bd86c986385bfd0d54455df839417de5cdf05dc | 54,092 |
def infer_reader(file_path, word_dict):
"""
Reader interface for prediction
:param data_dir: data directory
:type data_dir: str
:param word_dict: path of word dictionary,
the dictionary must has a "UNK" in it.
:type word_dict: Python dict
"""
def reader():
UNK_ID = word... | 6c8c3bace7fc61342e048de3d383f85a1b9b9278 | 54,093 |
def object_func(x, A, b):
""" Objective function for the optimization for L-BFGS-B
"""
y = A * x - b
return 0.5 * y.dot(y) | 8a9453f6f93f4b7c7e2f5202a2a81750df5c27df | 54,094 |
def create_wallet(request):
"""Create wallet from the form data."""
if request.method == "POST":
form = CreateWalletForm(request.POST)
if form.is_valid():
wallet_id = add_wallet(
form.cleaned_data["name"], form.cleaned_data["password"]
)
if ... | 4468f6af82222045652c73dfec44a0d9e62b0eaf | 54,095 |
def random_binomial(shape, p=0.0, dtype=None, seed=None):
"""Returns a tensor with random binomial distribution of values.
# Arguments
shape: A tuple of integers, the shape of tensor to create.
p: A float, `0. <= p <= 1`, probability of binomial distribution.
dtype: String, dtype of ret... | b7e58fd0d0796d9a0b7cd9c0ea30873b34a61f64 | 54,096 |
def generate_user_data(count=1):
"""
generate a list of dictionaries containing data necessary to create a User object
:param count:
:return:
"""
return [{'username': 'user_{:03}'.format(i)} for i in range(1, count + 1)] | cd1aebc0414d7b31d5636ed3938a6bbc6d5e98bf | 54,097 |
import json
import os
def start_cloudcmd(request):
"""
Start Cloudcmd
:param request: Ajax request
:return:
"""
cmd = "node node_modules/cloudcmd/bin/cloudcmd --one-panel-mode --port "
with open("settings.json") as some_settings:
new_settings = json.loads(some_settings.read())
... | 0ac2020230111cae2f5d9703d4696dc013013e3b | 54,098 |
def fast_gen(generator, cond):
"""generate with padded input"""
p = generator.compute_padding_values()[0]
cond = jnp.pad(cond, [(0, 0), (p, p), (0, 0)], mode="reflect")
return generator(cond) | 591f967bbd10bf0a27a62f82b29babd21615f2c4 | 54,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.