content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _h1_cmp_chi2_ ( h1 ,
h2 ,
density = False ) :
"""Compare histograms by chi2
>>> h1 = ... ## the first histo
>>> h2 = ... ## the second histo (or function or anything else)
>>> chi2ndf , probability = h1.cmp_chi2 ( h2 )
"""
... | ff2e5c191491c18adc29edf08a5bb837fabf045f | 13,300 |
def _questionnaire_metric(name, col):
"""Returns a metrics SQL aggregation tuple for the given key/column."""
return _SqlAggregation(
name,
"""
SELECT {col}, COUNT(*)
FROM participant_summary
WHERE {summary_filter_sql}
GROUP BY 1;
""".format(
col=col, su... | abd477798670733788461ed35fc0b4814ee7081d | 13,301 |
import re
def xyzToAtomsPositions(xyzFileOrStr):
"""
Returns atom positions (order) given a molecule in an xyz format.
Inchi-based algorithm.
Use this function to set the atoms positions in a reference
molecule. The idea is to assign the positions once and to never
change them again.
Arg... | 8db5c81d0e8aca2eef686d955ed810b4b166d0db | 13,302 |
async def modify_video_favorite_list(
media_id: int,
title: str,
introduction: str = '',
private: bool = False,
credential: Credential = None):
"""
修改视频收藏夹信息。
Args:
media_id (int) : 收藏夹 ID.
title (str) : 收藏夹名。
introducti... | e3618fc59785b63cf7f6810a0f2683bcd18d5277 | 13,303 |
def get_salesforce_log_files():
"""Helper function to get a list available log files"""
return {
"totalSize": 2,
"done": True,
"records": [
{
"attributes": {
"type": "EventLogFile",
"url": "/services/data/v32.0/sobjects/... | 1c182898517d73c360e9f2ab36b902afea8c58d7 | 13,304 |
def remove_true_false_edges(dict_snapshots, dict_weights, index):
"""
Remove chosen true edges from the graph so the embedding could be calculated without them.
:param dict_snapshots: Dict where keys are times and values are a list of edges for each time stamp.
:param dict_weights: Dict where keys are t... | 3f833fda22710c20703aa7590eae0fd649b69634 | 13,305 |
def addFavoriteDir(name:str, directory:str, type:str=None, icon:str=None, tooltip:str=None, key:str=None):
"""
addFavoriteDir(name, directory, type, icon, tooltip, key) -> None.
Add a path to the file choosers favorite directory list. The path name can contain environment variables which will be expanded w... | 28cbabd79d35151877112dd76ffe2a513a2bfcec | 13,306 |
def save(data):
"""Save cleanup annotations."""
data_and_frames = data.split("_")
data = data_and_frames[0]
frames = data_and_frames[1]
if len(data) == 1:
removed = []
else:
removed = [int(f) for f in data[1:].split(':')]
frames = [int(f) for f in frames[:].split(':')]
... | be62bd3933374ebac8e735be0f66ca79a6273b35 | 13,307 |
import re
def list_runs_in_swestore(path, pattern=RUN_RE, no_ext=False):
"""
Will list runs that exist in swestore
:param str path: swestore path to list runs
:param str pattern: regex pattern for runs
"""
try:
status = check_call(['icd', path])
proc = Popen(['ils'... | 616089f049129b284ae6575609741620f2ac48f6 | 13,308 |
def linear_regression(
XL: ArrayLike, YP: ArrayLike, Q: ArrayLike
) -> LinearRegressionResult:
"""Efficient linear regression estimation for multiple covariate sets
Parameters
----------
XL
[array-like, shape: (M, N)]
"Loop" covariates for which N separate regressions will be run
... | 3059987940eefce0a4a401c096d8b7be0d3ce1d7 | 13,309 |
import math
def orthogonal_decomposition(C, tr_error, l_exp):
"""
Orthogonal decomposition of the covariance matrix to determine the meaningful directions
:param C: covariance matrix
:param tr_error: allowed truncation error
:param l_exp: expansion order
:return: transformation matrix Wy, nu... | d6920b31a0503ad15b98631de352da690b6761b8 | 13,310 |
import http
import json
def get_data():
"""Reads the current state of the world"""
server = http.client.HTTPConnection(URL)
server.request('GET','/data')
response = server.getresponse()
if (response.status == 200):
data = response.read()
response.close()
return json.loads(d... | 3c0563f2776c60ea103db154c63e2053b1d7d045 | 13,311 |
def chi_angles(filepath, model_id=0):
"""Calculate chi angles for a given file in the PDB format.
:param filepath: Path to the PDB file.
:param model_id: Model to be used for chi calculation.
:return: A list composed by a list of chi1, a list of chi2, etc.
"""
torsions_list = _sidechain_torsio... | 85c192fe6c272cad5cdd7dbb4f570f1f78284057 | 13,312 |
def surface_sphere(radius):
"""
"""
phi, theta = np.mgrid[0.0:np.pi:100j, 0.0:2.0*np.pi:100j]
x_blank_sphere = radius*np.sin(phi)*np.cos(theta)
y_blank_sphere = radius*np.sin(phi)*np.sin(theta)
z_blank_sphere = radius*np.cos(phi)
sphere_surface = np.array(([x_blank_sphere,
... | 25750b7c4a57dd3a2f3ebb5a2a041fa1f5e56c89 | 13,313 |
import re
def format_bucket_objects_listing(bucket_objects):
"""Returns a formated list of buckets.
Args:
buckets (list): A list of buckets objects.
Returns:
The formated list as string
"""
out = ""
i = 1
for o in bucket_objects:
# Shorten to 24 chars max, remove... | f5268d148687338ed606b1593065a0c1842cac00 | 13,314 |
def charts(chart_type, cmid, start_date, end_date=None):
"""
Get the given type of charts for the artist.
https://api.chartmetric.com/api/artist/:id/:type/charts
**Parameters**
- `chart_type`: string type of charts to pull, choose from
'spotify_viral_daily', 'spotify_viral_weekly',
... | 2dfafd09f53bf2add20afcba8c85a6f081e551af | 13,315 |
import sys
def fake_traceback(exc_value, tb, filename, lineno):
"""Produce a new traceback object that looks like it came from the
template source instead of the compiled code. The filename, line
number, and location name will point to the template, and the local
variables will be the current template... | fd89728b7703e344e2ffe1b5217f21cbccc8f322 | 13,316 |
def search_candidates(api_key, active_status="true"):
"""
https://api.open.fec.gov/developers#/candidate/get_candidates_
"""
query = """https://api.open.fec.gov/v1/candidates/?sort=name&sort_hide_null=false&is_active_candidate={active_status}&sort_null_only=false&sort_nulls_last=false&page=1&per_page=20... | 9ec1c39541cda87f1d1618d4e5497b8215a5f4b4 | 13,317 |
def load_dat(file_name):
"""
carga el fichero dat (Matlab) especificado y lo
devuelve en un array de numpy
"""
data = loadmat(file_name)
y = data['y']
X = data['X']
ytest = data['ytest']
Xtest = data['Xtest']
yval = data['yval']
Xval = data['Xval']
return X,y,Xtest,ytest,... | 5c3de04f60ea803e1c70dbc2103425b10ee58567 | 13,318 |
def get_specific_pos_value(img, pos):
"""
Parameters
----------
img : ndarray
image data.
pos : list
pos[0] is horizontal coordinate, pos[1] is verical coordinate.
"""
return img[pos[1], pos[0]] | 3929b29fa307a7e8b5282783c16639cacb2ab805 | 13,319 |
from typing import List
from typing import Tuple
from typing import Dict
from typing import Any
from typing import Set
def transpose_tokens(
cards: List[MTGJSONCard]
) -> Tuple[List[MTGJSONCard], List[Dict[str, Any]]]:
"""
Sometimes, tokens slip through and need to be transplanted
back into their appr... | 339e8d18a4c80e168411c874f8afac97b14db77b | 13,320 |
from datetime import datetime
def from_local(local_dt, timezone=None):
"""Converts the given local datetime to a universal datetime."""
if not isinstance(local_dt, datetime.datetime):
raise TypeError('Expected a datetime object')
if timezone is None:
a = arrow.get(local_dt)
else:
... | 6b4eb44aa66c04a23aa8dac2bbe882e5619cd45f | 13,321 |
import re
def mrefresh_to_relurl(content):
"""Get a relative url from the contents of a metarefresh tag"""
urlstart = re.compile('.*URL=')
_, url = content.split(';')
url = urlstart.sub('', url)
return url | 90cc3dbace5d4b001698612f9263309fa95aac8b | 13,322 |
import torch
def simclr_loss_func(
z1: torch.Tensor,
z2: torch.Tensor,
temperature: float = 0.1,
extra_pos_mask=None,
) -> torch.Tensor:
"""Computes SimCLR's loss given batch of projected features z1 from view 1 and
projected features z2 from view 2.
Args:
z1 (torch.Tensor): NxD Te... | b9d7880ec1c8a66321623a0061d201f9bbaaa426 | 13,323 |
def find_node_types(G, edge_type):
"""
:param G: NetworkX graph.
:param edge_type: Edge type.
:return: Node types that correspond to the edge type.
"""
for e in G.edges:
if G[e[0]][e[1]][e[2]]['type'] == edge_type:
u, v = e[0], e[1]
break
utype = G.nodes[u]['... | 970bbbabe172460a974dbf961500def2280b9fe1 | 13,324 |
import scipy
def distance_point_point(p1, p2):
"""Calculates the euclidian distance between two points or sets of points
>>> distance_point_point(np.array([1, 0]), np.array([0, 1]))
1.4142135623730951
>>> distance_point_point(np.array([[1, 1], [0, 0]]), np.array([0, 1]))
array([1., 1.])
>>> di... | 481733330a99576540d2a80676d51d315b6406f7 | 13,325 |
def switch(
confs=None, remain=False, all_checked=False, _default=None, **kwargs
):
"""
Execute first statement among conf where task result is True.
If remain, process all statements conf starting from the first checked
conf.
:param confs: task confs to check. Each one may contain a task a... | aba656d4a6d06f721551aa49ec1521d0fa9444d3 | 13,326 |
def makeProcesses(nChildren):
"""
Create and start all the worker processes
"""
global taskQueue,resultsQueue,workers
if nChildren < 0:
print 'makeProcesses: ',nChildren, ' is too small'
return False
if nChildren > 3:
print 'makeProcesses: ',nChildren, ' is too large... | 748372d9c83917841eeba5e400f37a5ecf5961dd | 13,327 |
def create_moleculenet_model(model_name):
"""Create a model.
Parameters
----------
model_name : str
Name for the model.
Returns
-------
Created model
"""
for func in [create_bace_model, create_bbbp_model, create_clintox_model, create_esol_model,
create_free... | 19f15eb4fd1a5c1befaef306cb7d146d7933919e | 13,328 |
from typing import Collection
from typing import Optional
def detect_daml_lf_dir(paths: "Collection[str]") -> "Optional[str]":
"""
Find the biggest Daml-LF v1 version in the set of file names from a Protobuf archive, and return
the path that contains the associated files (with a trailing slash).
If t... | acd2b99236a3534ec64c375893b40511995e6dfc | 13,329 |
def random_mini_batches(X, Y, mini_batch_size):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (m, n_H, n_W, c)
Y -- true "label" vector of shape (m, num_classes)
mini_batch_size -- size of mini-batches, integer
Returns:
mini_ba... | fbad986073bfb867f5e35bf1a0ee639b644f00bb | 13,330 |
import types
def classifyContent(text):
"""
Uses the NLP provider's SDK to perform a content classification operation.
Arguments:
text {String} -- Text to be analyzed.
"""
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT,
language='... | eebb4ebef4811748d5fb9e130e582dae289f9ce7 | 13,331 |
def print_instance_summary(instance, use_color='auto'):
""" Print summary info line for the supplied instance """
colorize_ = partial(colorize, use_color=use_color)
name = colorize_(instance.name, "yellow")
instance_type = instance.extra['gonzo_size']
if instance.state == NodeState.RUNNING:
... | e250645e040fba4bbd9df0e86bc3711d3f8ac51e | 13,332 |
from datetime import datetime
def generate_blob_sas_token(blob, container, blob_service, permission=BlobPermissions.READ):
"""Generate a blob URL with SAS token."""
sas_token = blob_service.generate_blob_shared_access_signature(
container, blob.name,
permission=permission,
start=dateti... | e3993c3dd075516bce07221cf9351ab74a431a27 | 13,333 |
from typing import Sequence
def rewrite_complex_signature(function, signature: Sequence[tf.TensorSpec]):
"""Compatibility layer for testing complex numbers."""
if not all([spec.dtype.is_complex for spec in signature]):
raise NotImplementedError("Signatures with mixed complex and non-complex "
... | e541ef96c6b4f2492847443e8ca45f18fc9383ff | 13,334 |
def get_args(argv: list):
"""gets the args and dictionarize them"""
if len(argv) not in [5,7]:
Errors.args_error()
data = {}
# getting the type of the title
if "-" in argv[1]:
data["type"] = "series" if argv[1] == "-s" else "movie" if argv[1] == "-m" else None
else:
... | 6f29e63bc19b57cdf9f49cf2dd7b099c62a604a0 | 13,335 |
def fund_with_erc20(
to_fund_address, erc20_token_contract, ether_amount=0.1, account=None
):
"""Send a specified amount of an ERC20 token to an address.
Args:
to_fund_address (address): Address to send to the tokens to.
erc20_token_contract (Contract): Contract of the ERC20 token.
... | 6eaf46519645b8b6bbf36b39ea106c05924ab51f | 13,336 |
from carbonplan_trace.v1.glas_preprocess import select_valid_area # avoid circular import
def energy_adj_ground_to_sig_end(ds):
"""
Waveform energy from the ground peak. We calculated senergy_whrc as the energy of the waveform (in digital counts) from the ground peak
to the signal end multiplied by two.... | b1f2f9acacb2186694aec3249632fea1fd4f7a58 | 13,337 |
import logging
def get_previous_version(versions: dict, app: str) -> str:
"""Looks in the app's .version_history to retrieve the prior version"""
try:
with open(f"{app}/.version_history", "r") as fh:
lines = [line.strip() for line in fh]
except FileNotFoundError:
logging.warnin... | d3a4aec5c3bc842181aa3901971774761866c3e5 | 13,338 |
def healthcheck() -> bool:
"""FastAPI server healthcheck."""
return True | 1767229ccda121e88264093c479d2bccf994a7e9 | 13,339 |
def ToHexStr(num):
"""
将返回的错误码转换为十六进制显示
:param num: 错误码 字符串
:return: 十六进制字符串
"""
chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
hexStr = ""
if num < 0:
num = num + 2**32
while num >= 16:
digit = num % 16
hexStr = chaDic.get(digit, str(digit)) ... | b6cf482defdc9f4fcf9ce64903e7a718e096bacb | 13,340 |
import requests
def getSBMLFromBiomodelsURN(urn):
""" Get SBML string from given BioModels URN.
Searches for a BioModels identifier in the given urn and retrieves the SBML from biomodels.
For example:
urn:miriam:biomodels.db:BIOMD0000000003.xml
Handles redirects of the download page.
:p... | 9a28f4a0619ebed6f9e272d84331482442ae9fb8 | 13,341 |
def draw(k, n):
"""
Select k things from a pool of n without replacement.
"""
# At k == n/4, an extra 0.15*k draws are needed to get k unique draws
if k > n/4:
result = rng.permutation(n)[:k]
else:
s = set()
result = np.empty(k, 'i')
for i in range(k):
... | d7135d659fc4e702942ea2da0f794fcb9d77bfd2 | 13,342 |
def print_version(args):
"""Print the version (short or long)"""
# Long version
if len(args) > 0 and args[0] == '--full':
apk_version = dtfglobals.get_generic_global(
dtfglobals.CONFIG_SECTION_CLIENT, 'apk_version')
bundle_version = dtfglobals.get_generic_global(
dt... | b7bec22239e765d3e9c2131302144b0e44360f2a | 13,343 |
from datetime import datetime
def naturalTimeDifference(value):
"""
Finds the difference between the datetime value given and now()
and returns appropriate humanize form
"""
if isinstance(value, datetime):
delta = datetime.now() - value
if delta.days > 6:
return val... | ce285358b1b99a4b2df460e6193d2a0970aa4eff | 13,344 |
def raises_Invalid(function):
"""A decorator that asserts that the decorated function raises
dictization_functions.Invalid.
Usage:
@raises_Invalid
def call_validator(*args, **kwargs):
return validators.user_name_validator(*args, **kwargs)
call_validator(key, data, error... | b1dcaea71cfe95e25029be360645c68a0906346d | 13,345 |
from pathlib import Path
def load_dataset(dataset_path: Path) -> [Instruction]:
"""Returns the program as a list of alu instructions."""
with open_utf8(dataset_path) as file:
program = []
for line in file:
if len(line.strip()) > 0:
instruction = line.strip().split("... | 6d9fd90401c750a4aa5d83491c9610984b95ebd1 | 13,346 |
import json
def process_info(args):
"""
Process a single json file
"""
fname, opts = args
with open(fname, 'r') as f:
ann = json.load(f)
f.close()
examples = []
skipped_instances = 0
for instance in ann:
components = instance['components']
if len(... | 8ade5b21db3cca57d9de91311fc57754161673de | 13,347 |
def logout():
"""
退出登录
:return:
"""
# pop是移除session中的数据(dict),pop会有一个返回值,如果移除的key不存在返回None
session.pop('user_id', None)
session.pop('mobile', None)
session.pop('nick_name', None)
# 要清除is_admin的session值,不然登录管理员后退出再登录普通用户又能访问管理员后台
session.pop('is_admin', None)
return jsonify(er... | a60e91457ddb32bceeda01a66027209adaf8eecb | 13,348 |
def lift_to_dimension(A,dim):
"""
Creates a view of A of dimension dim (by adding dummy dimensions if necessary).
Assumes a numpy array as input
:param A: numpy array
:param dim: desired dimension of view
:return: returns view of A of appropriate dimension
"""
current_dim = len(A.shape... | bc21d0af45e8073f2e8da6ed57c441739a7385f5 | 13,349 |
def search(keyword=None):
"""
Display search results in JSON format
Parameters
----------
keyword : str
Search keyword. Default None
"""
return get_json(False, keyword) | 558a34fedb4e05e7a31b655effa47287cbc46202 | 13,350 |
from typing import List
def min_offerings(heights: List[int]) -> int:
"""
Get the max increasing sequence on the left and the right side of current index,
leading upto the current index.
current index's value would be the max of both + 1.
"""
length = len(heights)
if length < 2:
r... | 952ea82815ecb4db6d4d0347f16b0cf5b299f7d3 | 13,351 |
def pretty(value, width=80, nl_width=80, sep='\n', **kw):
# type: (str, int, int, str, **Any) -> str
"""Format value for printing to console."""
if isinstance(value, dict):
return '{{{0} {1}'.format(sep, pformat(value, 4, nl_width)[1:])
elif isinstance(value, tuple):
return '{}{}{}'.form... | d2af8d83c2e116ebb1a6e65cd369c3a33adf4585 | 13,352 |
import os
def get_csv_file_path(file_name: str) -> str:
"""
Get absolute path to csv metrics file
Parameters
----------
file_name
Name of metrics file
Returns
-------
file_path
Full path to csv file
"""
return os.path.join(os.getcwd(), file_name) | 67b80193a75669a0635cf70ab1325e755424d654 | 13,353 |
import os
def failed(config: dict, app_logger: logger.Logger) -> bool:
"""
Set migration status to FAILED.
:param config: pymigrate configuration.
:param app_logger: pymigrate configured logger.
:return: True on success, False otherwise.
"""
app_logger.log_with_ts('Running status_failed ... | 4d902be5c42c3485a087ef384708e48fcdcd947f | 13,354 |
def niceNumber(v, maxdigit=6):
"""Nicely format a number, with a maximum of 6 digits."""
assert(maxdigit >= 0)
if maxdigit == 0:
return "%.0f" % v
fmt = '%%.%df' % maxdigit
s = fmt % v
if len(s) > maxdigit:
return s.rstrip("0").rstrip(".")
elif len(s) == 0:
return ... | d57f83272a819d5abf12d71fdac84fe8e92eeb05 | 13,355 |
def query_incident(conditions: list, method=None, plan_status="A", mulitple_fields=False):
"""
Queries incidents in Resilient/CP4S
:param condition_list: list of conditions as [field_name, field_value, method] or a list of list conditions if multiple_fields==True
:param method: set all field conditions... | 9c037b5d864248bd280db644f4c3868557b59721 | 13,356 |
def get_banner():
"""Return a banner message for the interactive console."""
global _CONN
result = ''
# Note how we are connected
result += 'Connected to %s' % _CONN.url
if _CONN.creds is not None:
result += ' as %s' % _CONN.creds[0]
# Give hint about exiting. Most people exit wi... | 5c5e1f2d32548d112f75c933ce4c4e842cdfc993 | 13,357 |
def generate_fish(
n,
channel,
interaction,
lim_neighbors,
neighbor_weights=None,
fish_max_speeds=None,
clock_freqs=None,
verbose=False,
names=None
):
"""Generate some fish
Arguments:
n {int} -- Number of fish to generate
channel {Channel} -- Channel instance... | 58d8fb4626d18caa5b093b30588603f335074e4b | 13,358 |
import functools
def log_exception(function):
"""Exception logging wrapper."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except:
err = "There was an exception in "
err += function.__name__
... | f2c86b168550c12d73d87f1b2001a3caab46ceda | 13,359 |
def calculate_triad_connectivity(tt1, tt2, tt3, ipi1, ipi2, tau_z_pre, tau_z_post,
base_time, base_ipi, resting_time, n_patterns):
"""
This function gives you the connectivity among a triad, assuming that all the other temporal structure outside of
the trial is homogeneus
... | 6497a68bfdbf9db12a6cbef0784c0aacc3f5e055 | 13,360 |
from datetime import datetime
import random
def random_date_from(date,
min_td=datetime.timedelta(seconds=0),
max_td=datetime.timedelta(seconds=0)):
"""
Produces a datetime at a random offset from date.
Parameters:
date: datetime
The reference ... | 2392e6684de81f5e693a7e6fbe4934940df5eada | 13,361 |
def generate_log_normal_dist_value(frequency, mu, sigma, draws, seed_value):
"""
Generates random values using a lognormal distribution,
given a specific mean (mu) and standard deviation (sigma).
https://stackoverflow.com/questions/51609299/python-np-lognormal-gives-infinite-
results-for-big-average... | f0613688a5af83a867825b3e91c8f1f8a99c05ba | 13,362 |
from re import VERBOSE
def compute_mean_field(
grain_index_field,
field_data,
field_name,
vx_size=(1.0, 1.0, 1.0),
weighted=False,
compute_std_dev=False,
):
"""
Compute mean shear system by grains.
Args:
grain_index_field : VTK field containing index
field_dat... | 8baa187a853c1d44597cae0417b455c74db2072d | 13,363 |
def evaluate_argument_value(xpath_or_tagname, datafile):
"""This function takes checks if the given xpath_or_tagname exists in the
datafile and returns its value. Else returns None."""
tree = ET.parse(datafile)
root = tree.getroot()
if xpath_or_tagname.startswith(root.tag + "/"):
xpath_or_ta... | be4597e039717a535a86edfa4b04761417d0eaf4 | 13,364 |
def normalise_genome_position(x):
"""
Normalise position (circular genome)
"""
x['PositionNorm0'] = np.where(x['Position'] > (x['GenomeLength'] / 2),
(x['GenomeLength'] - x['Position']),
x['Position'])
x['PositionNorm'] = x['Positio... | 251808a0c7ea2b4f83e8c82ec06fc2d1d9e9b887 | 13,365 |
from faker import Faker
def random_address(invalid_data):
"""
Generate Random Address
return: string containing imitation postal address.
"""
fake = Faker(['en_CA']) # localized to Canada
return fake.address().replace('\n',', '), global_valid_data | 3375f2eefd05e1575ec8caf2944ee7960a17ca46 | 13,366 |
import math
def rot_poly(angle, polygon, n):
"""rotate polygon into 2D plane in order to determine if a point exists
within it. The Shapely library uses 2D geometry, so this is done in order
to use it effectively for intersection calculations.
Parameters
----------
angle : float
... | 3048d6fac8a5e2dffb3d621c8bec2a25aa6b31d0 | 13,367 |
def bytes_isspace(x: bytes) -> bool:
"""Checks if given bytes object contains only whitespace elements.
Compiling bytes.isspace compiles this function.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object to examine.
Returns:
Result of che... | 6c28b904cb6e0ef515ce7a16725fb99a535c3192 | 13,368 |
import re
def snake_case(name: str):
"""
https://stackoverflow.com/a/1176023/1371716
"""
name = re.sub('(\\.)', r'_', name)
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
name = re.sub('__([A-Z])', r'_\1', name)
name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)
return name.lower() | 4696ca3c1a50590aa6617ee3917b8364c11f3910 | 13,369 |
import glob
def get_loss_data():
"""
This function returns a list of paths to all .npy loss
files.
Returns
-------
path_list : list of strings
The list of paths to output files
"""
path = "./data/*_loss.npy"
path_list = glob.glob(path, recursive=True)
return path_lis... | bc98b0bdf60ac3f7125da82fd68956957e89a777 | 13,370 |
def ranked_avg_knn_scores(batch_states, memory, k=10, knn=batch_count_scaled_knn):
"""
Computes ranked average KNN score for each element in batch of states
\sum_{i = 1}^{K} (1/i) * d(x, x_i)
Parameters
----------
k: k neighbors
batch_states: numpy array of size [batch_size x state_size]
... | 56d60d97e7c10b06deb417e0d6b52a5a76f9150e | 13,371 |
def login_exempt(view_func):
"""登录豁免,被此装饰器修饰的action可以不校验登录."""
def wrapped_view(*args, **kwargs):
return view_func(*args, **kwargs)
wrapped_view.login_exempt = True
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) | d0853317260d68e9ea3d3a70a02c2f1ca67681a2 | 13,372 |
def to_uint8_image(message : ImageMessage) -> ImageMessage:
"""Convert image type to uint8.
Args:
message (ImageMessage): Image to be converted
Returns:
ImageMessage: Resulting iamge
"""
message.image = np.uint8(message.image*255)
if message.mask is not None:
message.ma... | fd9626800b5c0fec284ab185c1ff29e9cfefb3e7 | 13,373 |
import string
def list_zero_alphabet() -> list:
"""Build a list: 0, a, b, c etc."""
score_dirs = ['0']
for char in string.ascii_lowercase:
score_dirs.append(char)
return score_dirs | 6cd9fc9e93257dcc7729235ac3cffa01dbd80c95 | 13,374 |
def proxy(values=(0,), names=('constant',), types=('int8',)):
""" Create a proxy image with the given values, names and types
:param values: list of values for every band of the resulting image
:type values: list
:param names: list of names
:type names: list
:param types: list of band types. Op... | b57c4a625d8fa8c7a76bb0f1d2202e0e5cf2d41e | 13,375 |
import six
def _to_versions(raw_ls_remote_lines, version_join, tag_re, tag_filter_re):
"""Converts raw ls-remote output lines to a sorted (descending)
list of (Version, v_str, git_hash) objects.
This is used for source:git method to find latest version and git hash.
"""
ret = []
for line in raw_ls_remote... | 9113d26dbec144bbc72c89ca41935305a7321a18 | 13,376 |
def arraysum(x: int)->int:
"""
These function gives sum of all elements of list by iterating through loop and adding them.
Input: Integer
Output: Interger
"""
sum = 0
for i in x:
sum += i
return sum | aa14eaf4e2bb800ad5e61a63ab0bc17c56dbd86d | 13,377 |
def get_sensitivity_scores(model, features, top_n):
"""
Finds the sensitivity of each feature in features for model. Returns the top_n
feature names, features_top, alongside the sensitivity values, scores_top.
"""
# Get just the values of features
x_train = features.values
# Apply min max no... | a955c93691b09073be20fc65a2c6958a620f5548 | 13,378 |
def mad(data):
"""Median absolute deviation"""
m = np.median(np.abs(data - np.median(data)))
return m | 6b32901a94aca256736c1cb936c8b1c1794857d7 | 13,379 |
async def get_intents(current_user: User = Depends(Authentication.get_current_user_and_bot)):
"""
Fetches list of existing intents for particular bot
"""
return Response(data=mongo_processor.get_intents(current_user.get_bot())).dict() | 2a62bc579f6b392bc0038bf4f555941f764d456c | 13,380 |
from typing import Union
from typing import AnyStr
import os
from typing import Optional
from typing import Callable
def open_beneath(
path: Union[AnyStr, "os.PathLike[AnyStr]"],
flags: int,
*,
mode: int = 0o777,
dir_fd: Optional[int] = None,
no_symlinks: bool = False,
remember_parents: bo... | 9801c48c3e10416f4355499a584ee295e696faef | 13,381 |
import time
from datetime import datetime
import os
def train():
"""Train CIFAR-10/100 for a number of steps."""
with tf.Graph().as_default(), tf.device('/cpu:0'):
# Create a variable to count the number of train() calls. This equals the
# number of batches processed * FLAGS.num_gpus.
... | c2660e782dbc4f1a1a4603da83d756483d314bf8 | 13,382 |
def find_offset(
ax: Numbers, ay: Numbers, bx: Numbers, by: Numbers, upscale: bool = True
) -> float:
"""Finds value, by which the spectrum should be shifted along x-axis to best
overlap with the first spectrum. If resolution of spectra is not identical,
one of them will be interpolated to match resolut... | 64e0c13a16b3ead30227ab80398fea296674385d | 13,383 |
def And(*xs, simplify=True):
"""Expression conjunction (product, AND) operator
If *simplify* is ``True``, return a simplified expression.
"""
xs = [Expression.box(x).node for x in xs]
y = exprnode.and_(*xs)
if simplify:
y = y.simplify()
return _expr(y) | 5f25e8b2f37a4bbc077f10eee561936e41defefa | 13,384 |
def get_assignment_submissions(course_id, assignment_id):
""" return a list of submissions for an assignment """
return api.get_list('courses/{}/assignments/{}/submissions'.format(course_id, assignment_id)) | eb1a6143b551298efdb6c4181e2356d759c6fd6c | 13,385 |
def send_email(to, content=None, title=None, mail_from=None,
attach=None, cc=None, bcc=None, text=None, html=None, headers=None):
"""
:param to: 收件人,如 'linda@gmail.com' 或 'linda@gmail.com, tom@gmail.com' 或 ['linda@gmail.com, tom@gmail.com']
:param content: 邮件内容,纯文本或HTML str
:param title:... | c68c4db3c96890d1e82f33666b69cd4e1ac4c116 | 13,386 |
def get_abbreviation(res_type, abbr):
"""
Returns abbreviation value from data set
@param res_type: Resource type (html, css, ...)
@type res_type: str
@param abbr: Abbreviation name
@type abbr: str
@return dict, None
"""
return get_settings_resource(res_type, abbr, 'abbreviations') | 91831f10fc2be1d7c7201b02e0d044939ce82e83 | 13,387 |
import time
def get_stock_list(month_before=12, trade_date='20200410', delta_price=(10, 200), total_mv=50, pe_ttm=(10, 200)):
"""
month_before : 获取n个月之前所有上市公司的股票列表,
默认为获取一年前上市公司股票列表
delta_price :用于剔除掉金额大于delta_price的股票,若为空则不剔除
TIPS : delta_price 和今天的股价进行比较
"""
... | 13f0dd7b31c297ea643ad42efb519a88907bbfd5 | 13,388 |
def dim_axis_label(dimensions, separator=', '):
"""
Returns an axis label for one or more dimensions.
"""
if not isinstance(dimensions, list): dimensions = [dimensions]
return separator.join([d.pprint_label for d in dimensions]) | f03e4eb02fc57890421bdcdaa0aea7d6541b8678 | 13,389 |
def get_random_idx(k: int, size: int) -> np.ndarray:
"""
Get `k` random values of a list of size `size`.
:param k: number or random values
:param size: total number of values
:return: list of `k` random values
"""
return (np.random.rand(k) * size).astype(int) | eedcc9953e878c9b475cc18666eb621de2811dbe | 13,390 |
def bitmask_8bit(array, pad_value=None):
"""Return 8-bit bitmask for cardinal and diagonal neighbours."""
shape, padded = shape_padded(array, pad_value=pad_value)
cardinals = get_cardinals(shape, padded)
diagonals = get_diagonals(shape, padded)
# TODO: https://forum.unity.com/threads/2d-tile-bitmas... | 680f6ad7319af36a23d0e3b174cc5df7021a9920 | 13,391 |
from typing import Union
def fhir_search_path_meta_info(path: str) -> Union[tuple, NoneType]:
""" """
resource_type = path.split(".")[0]
properties = path.split(".")[1:]
model_cls = resource_type_to_resource_cls(resource_type)
result = None
for prop in properties:
for (
na... | 2117e9f09c401e2b027d3c3eb7347650eaa03582 | 13,392 |
def _is_camel_case_ab(s, index):
"""Determine if the index is at 'aB', which is the start of a camel token.
For example, with 'workAt', this function detects 'kA'."""
return index >= 1 and s[index - 1].islower() and s[index].isupper() | c21ec7d8aa7e786d1ea523106af6f9426fea01d8 | 13,393 |
import os
def create_folder():
"""
This Function Create Empty Folder At Begin
:return:folder status as boolean
"""
folder_flag = 0
list_of_folders = os.listdir(SOURCE_DIR)
for i in ["doc", "image", "output", "font"]:
if i not in list_of_folders:
os.mkdir(i)
... | d4f1864fb4b5158682d414a09e1391f78600fbb2 | 13,394 |
def create_bulleted_tool_list(tools):
"""
Helper function that returns a text-based bulleted list of the given tools.
Args:
tools (OrderedDict): The tools whose names (the keys) will be added to the
text-based list.
Returns:
str: A bulleted list of tool names.
"""
r... | d75fb7793c019f2499b549c2af627bb2038876e7 | 13,395 |
def _c3_merge(sequences, cls, context):
"""Merges MROs in *sequences* to a single MRO using the C3 algorithm.
Adapted from http://www.python.org/download/releases/2.3/mro/.
"""
result = []
while True:
sequences = [s for s in sequences if s] # purge empty sequences
if not sequence... | 6453f151fe227226f3fcbc29d4e5fffd800683cb | 13,396 |
def rgb2hex(rgb: tuple) -> str:
"""
Converts RGB tuple format to HEX string
:param rgb:
:return: hex string
"""
return '#%02x%02x%02x' % rgb | 1ecb1ca68fa3dbe7b58f74c2e50f76175e9a0c5a | 13,397 |
import warnings
def min_var_portfolio(cov_mat, allow_short=False):
"""
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance... | 2efd839b8ca8ea6fe7b26f645630beb78699a8ea | 13,398 |
def relu(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.relu"""
data, res = fd.args[0], fd.dest
num_dims = get_dims(data.comp)
args = data.comp.args
indices = ""
var_name = CHARACTER_I
for _ in range(num_dims):
indices += f'[{var_name}]'
... | 30eefb572f632e91993d715ecc70570d38030657 | 13,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.