content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
closure = o.__closure__
except AttributeError:
return
if closure:
for cell in closure:
# avoid infinite recursion
... | 8bfd0c45615e747ab95b045c028cea7d8b332c17 | 76,678 |
def get_machine_precision():
"""Calculate the machine precision for Floats
Depends on static variable machine_precision in this module
as this would otherwise require too much computation.
"""
global machine_precision
if machine_precision is None:
epsilon = 1.
while epsilon/2 ... | 9a0e61686fc42ba9e64675aba3b0016e2df5bf9f | 76,679 |
def likelihood_analysis(*args):
""" Converts misfit to likelihood and multiplies together contributions
from different data categories
"""
arrays = [arg[0] for arg in args]
covs = [arg[1] for arg in args]
values = []
for _i, array in enumerate(arrays):
values += [np.exp(-array.va... | 06ead015e88c615fae0a74e7658cef9e492b2828 | 76,680 |
from typing import Dict
from typing import Tuple
import warnings
def create_clade_colors(
tree: CassiopeiaTree, clade_colors: Dict[str, Tuple[float, float, float]]
) -> Tuple[
Dict[str, Tuple[float, float, float]],
Dict[Tuple[str, str], Tuple[float, float, float]],
]:
"""Assign colors to nodes and bra... | eb40298b736217a62c8163a615bf7031b3f05805 | 76,681 |
import logging
def get_logger(name, path, size, level):
"""
Returns a Logger that logs of severity `level` and above to the specified
path up to `size` MBs before rotating out to up to `BACKUPCOUNT` files.
"""
logger = logging.getLogger(name)
handler = logging.handlers.RotatingFileHandler(
... | d4895ad3213832def6eb8d0895c294ae68fae7ba | 76,682 |
def umap(model, **kwargs):
"""Compute UMAP embeddings."""
_optional_neighbors(model)
return sc.tl.umap(setup_cache(model).factor_adata, **kwargs) | 6b91684a45a27299a30e692f06963138be4885af | 76,683 |
def estimate_sigma(values):
"""Estimates standard deviation using median to exclude outliers.
Up to 50% can be bad.
Reference:
Rousseeuw, Peter & Croux, Christophe. (1993). Alternatives to Median Absolute
Deviation. Journal of the American Statistical Association. 88. 1273 - 1283.
10.1080/0162... | 509a7a53b66e3913adddd227eec8e76d4beeef00 | 76,684 |
def cos(t: Tensor) -> Tensor:
"""
Cosinus of elements of `Tensor`. Also it is calculate its gradient of
operation if tensor's have_grad = True.
Cosinus in radian.
Arguments:
----------
t : Tensor
For example:
-----------
y = cos(a) + cos... | 2c2a3f240907a38e745270fe74a6cf6e3a65c966 | 76,686 |
def get_links(links, row):
"""
Process & flatten the links section in the yaml. Values within the subgroup
are comma separated & the subgroups are pipe separated.
"""
l_name_str = []
l_backref_str = []
l_label_str = []
l_target_str = []
l_multiplicity_str =... | 8d2233ffc5180cb2fc9411665e6b5021f7961a76 | 76,687 |
import tqdm
def score_dataset(X, y, model, n_splits=5, categorical=[]):
"""Cross-validates (X,y) to evaluate the quality of its data points given the model
Args:
D (numpy.array): 2D matrix of data points, N x F, with N points of F features.
model (catboost model): easiest to pass with make_ca... | d519b86577b50b547029b102c6e6c3948bad736e | 76,688 |
import builtins
import pathlib
def expandvars(path):
"""Expand shell variables of the forms $var, ${var} and %var%.
Unknown variables are left unchanged."""
env = builtins.__xonsh__.env
if isinstance(path, bytes):
path = path.decode(
encoding=env.get("XONSH_ENCODING"), errors=env.g... | 6d005d81352e2b11a7e2c3b83541cff2c3d2d296 | 76,689 |
def compile_column(name: str, data_type: str, nullable: bool) -> str:
"""Create column definition statement."""
null_str = 'NULL' if nullable else 'NOT NULL'
return '{name} {data_type} {null},'.format(name=name,
data_type=data_type,
... | e1db7bfc78509d394de645b90394f8d796f97a5b | 76,690 |
def flairAdded(newImage):
"""Compare fetch of flairs with an existing copy to see if new flairs were added.
Args:
newImage (Image): picture containing result of request for flairs.
Returns:
Boolean: result of comparing images.
"""
# Look for differences between images.
diff = Ima... | 02b4feb8beaa53c9c84b69fe1a33b6b5bf680697 | 76,692 |
def logistic(loc=0.0, scale=1.0, size=None):
"""This function has the same `nlcpy.random.RandomState.logistic`
See Also
--------
nlcpy.random.RandomState.logistic : Draws samples from a logistic distribution.
"""
rs = generator._get_rand()
return rs.logistic(loc, scale, size=size) | 273fefefbfb2dae4c0cc8639b01326f96f6da91b | 76,693 |
import random
def random_string(min_length=5, max_length=30, title=False):
"""A random string consisting of Latin letters, optionally title-cased"""
result = ''.join([random.choice(_letters_source)
for _ in range(random.randint(min_length, max_length))])
return result if not title el... | 75e659cd2962570a82451ea78eb45e4b4699a61c | 76,694 |
def get_current_epoch(state: BeaconState) -> Epoch:
"""
Return the current epoch.
"""
return compute_epoch_at_slot(state.slot) | d197249a41a9cb4d67af7f98f07515aafb181b39 | 76,695 |
def request(cm_response, **data):
"""
@clmview_user
@cm_request_transparent{user.network.requests()}
"""
return cm_response | f30bffa2811be24ece5f3469d9a7dc43f07a55f0 | 76,696 |
from pathlib import Path
def _find_rootdir_path(datadir=None, configfile=CONFIGFILE_NAME):
"""Return root pathname of mklists repo wherever executed in repo."""
if not datadir:
datadir = Path.cwd()
parents = list(Path(datadir).parents)
parents.insert(0, Path.cwd())
for directory in parents... | c9c1867a1f3dc4bff5a10cd34dfae10baa170aa8 | 76,698 |
import requests
def get_data(session, logger):
"""Requests generation data in json format."""
s = session or requests.session()
json_data = s.get(url).json()
return json_data | 0b0a2c5ca398ce293b87e9134ed6b3bfda1ed2d5 | 76,699 |
from operator import sub
import warnings
def element_by_symbol(symbol):
"""Search for an element by its symbol.
Look up an element from a list of known elements by symbol.
Return None if no match found.
Parameters
----------
symbol : str
Element symbol to look for, digits and spaces ... | f4b4e6fc03f8ace990e1a07252d61746ca0b76ec | 76,700 |
from typing import Optional
def load_kubernetes_service_config_no_cache(
service: str,
instance: str,
cluster: str,
load_deployments: bool = True,
soa_dir: str = DEFAULT_SOA_DIR,
) -> "KubernetesDeploymentConfig":
"""Read a service instance's configuration for kubernetes.
If a branch isn'... | 08ca7a2bbf00ccc54598afe9c1b81b4e621e0886 | 76,701 |
def _create_image_registry_credentials(registry_login_server, registry_username, registry_password, image):
"""Create image registry credentials. """
image_registry_credentials = None
if registry_login_server:
if not registry_username:
raise CLIError('Please specify --registry-username i... | f82c045c8ceaa8bc958818455517ca6331fbd3ab | 76,702 |
def prepend_global_admin_user(other_users, server):
"""
When making lists of administrative users -- e.g., seeding a new server --
it's useful to put the credentials supplied on the command line at the head
of the queue.
"""
cred0 = get_global_login_user(server, "admin")
if cred0 and cred0["... | 011d01c11badfa7eb387df7fc380f8a1858ee9a6 | 76,705 |
def convert_255_to_hex(color255):
"""
>>> color255 = [255, 51, 0]
target_rgb01 = pt.FALSE_RED[0:3]
target_rgb = np.array([[target_rgb01]]).astype(np.float32) / 25
target_lab = vt.convert_colorspace(target_rgb, 'lab', 'rgb')
# Find closest CSS color in LAB space
dist_lab = {}
dist_rgb =... | 355ad47715a3c188b1b6660a76d816b0124a3f69 | 76,707 |
def _handle_date(sheet, val):
"""
Convert date to string.
Input is a cell of type 'date'.
"""
if val:
return xlrd.xldate.xldate_as_datetime(val, sheet.book.datemode).strftime("%Y-%m-%d %H:%M:%S")
else:
return None | b3256857e033bfc23e29a2481c653df6424c7162 | 76,708 |
def max_pool2d(inputs,
kernel_size,
scope,
stride=[2, 2],
padding='VALID'):
""" 2D max pooling.
Args:
inputs: 4-D tensor BxHxWxC
kernel_size: a list of 2 ints
stride: a list of 2 ints
Returns:
Variable tensor
"""
with tf.variable_... | 758193bb924d80268adb663be249ec6603a070e8 | 76,709 |
import tqdm
def _ir_precision(emb, d_mat, labels, validation_pairs):
"""Compute IR precision."""
for k in tqdm([1, 2, 4, 8, 16], desc='Computing recall'):
correct_precision, cnt_precision = 0.0, 0.0
for i in range(emb.shape[0]):
d_mat[i, i] = 1e10
nns = np.argpartition(... | 5acd423b6290deaedc5082917519ab5c9658ec6f | 76,710 |
def head_html(**kwargs):
"""
Return the HTML code to be placed into the <head> section of a HTML document.
:param hl: User language (optional); If not specified, the language is auto-detected
:return: HTML code
"""
s = '<script src="https://www.google.com/recaptcha/api.js{}" async defer></scri... | f9a1b78b952f687bcb03655faccf0bcb00559a58 | 76,711 |
from typing import Any
def create_file(client: Any, parent_id: str, name: str, file_type: str = "folder"):
"""Creates a new folder with the specified parents."""
if file_type == "folder":
mimetype = "application/vnd.google-apps.folder"
file_metadata = {"name": name, "mimeType": mimetype, "parents... | a661bd3eb58d867a407d0e10dfbe3e581fc25bb9 | 76,712 |
def norm(A):
"""computes the L2-norm along axis 1 (e.g. genes or embedding dimensions) equivalent to np.linalg.norm(A, axis=1)
"""
return np.sqrt(A.multiply(A).sum(1).A1) if issparse(A) else np.sqrt(np.einsum('ij, ij -> i', A, A)) | 5cc975dc57bf17baf2dbf7c1617411eacb574d39 | 76,713 |
def build_reid_head(cfg, input_shape):
"""
Build a box head defined by `cfg.MODEL.ROI_BOX_HEAD.NAME`.
"""
name = "ROI_REID_HEAD"
return REID_HEAD(cfg, input_shape) | d18454f4b114c4125eac23bc002a3a44e8935f84 | 76,715 |
def marketing_busifavor_coupon_deactivate(self, coupon_code, stock_id, deactivate_request_no, deactivate_reason=None):
"""使券失效
:param coupon_code: 券code,券的唯一标识。示例值:'sxxe34343434'
:param stock_id: 批次号。示例值:1212
:param deactivate_request_no: 失效请求单据号。示例值:'1002600620019090123143254436'
:param deactivate_... | b244e48e6256d760e50d0d62e59cdf34440120d1 | 76,716 |
import logging
def group_samples(samples, tokenizer):
"""Groups generated and ground truth texts."""
groups = {}
for i, row in enumerate(samples):
gt = tokenizer.decode(row['ground_truth_text'])
sample = tokenizer.decode(row['sample_tokens'])
if gt not in groups:
groups[gt] = (gt.split(), [sam... | b8bbdb02157d20fd3a9aed774c3a90a24fe18e86 | 76,717 |
from cupyimg._misc import _reshape_nd
from fast_upfirdn.cupy import convolve1d as _convolve1d_gpu
def convolve1d(
input,
weights,
axis=-1,
output=None,
mode="reflect",
cval=0,
origin=0,
*,
crop=True, # if False, will get a "full" convolution instead
backend="ndimage",
dtyp... | a314c77e197f67ba9fb11a7403ca9cc9416ab77e | 76,718 |
def bg_green(msg):
""" return msg with a green background """
return __apply_style(__background_colors['green'],msg) | c2f961fcf57942dadfffa34a3e075fa859d64032 | 76,720 |
import re
def _parseGeneral(lines, efifilepath):
""" For MSFT, ICC, EBC
@param lines line array for map file
@return a list which element hold (PcdName, Offset, SectionName)
"""
status = 0 #0 - beginning of file; 1 - PE section definition; 2 - symbol table
secs = [] # key =... | 62c2d480d8c2d15bebd6040e30951d96e6cc1ac8 | 76,721 |
from typing import Callable
from typing import Union
from typing import Awaitable
from re import T
import time
import asyncio
def add_logging(func: Callable[P, Union[Awaitable[T], T]]) -> Callable[P, Union[Awaitable[T], T]]:
"""
Used to add logging to a coroutine or function.
.. code-block:: pyt... | b8562a41ce66abe49a95b8e60f167a10009581ec | 76,723 |
import threading
def task(_fn=None, defer=False, wait=False):
"""Decorate a function or method for Task-based execution.
By default calling the function will return a mock Task which will lazily execute the target callable the first
time its result is requested, in the thread that requested it. You can change t... | 696554addc8bdb5b8afcb3fccddb7fc443885611 | 76,724 |
def read_partialmap(filename, nside=256):
""" read partial systematic map """
data = ft.read(filename, lower=True)
if 'ivar' in filename.lower(): # in case there was IVAR
signal = IvarToDepth(data['signal'])
else:
signal = data['signal']
output = np.empty(12*nside*nside)
o... | f66cc8e2539ee4ced771fa004c5dde86f7127609 | 76,727 |
def rfeCV(x, y, step, cv, n_jobs,
permutation=0):
"""equal to nested rfe"""
n_samples, n_features = x.shape
estimator = SVC(kernel="linear") # TOO: Add other classifiers
selector = RFECV(estimator, step=step, cv=cv, n_jobs=n_jobs)
selector = selector.fit(x, y)
mask = selector.support_... | 90195d5f253612baa404dc7e8b0491e7675b64fd | 76,728 |
def xy_data(dataset, variable):
"""X-Y line/circle data related to a dataset"""
# import time
# time.sleep(5) # Simulate expensive I/O or slow server
if dataset == "takm4p4":
return {
"x": [0, 1e5, 2e5],
"y": [0, 1e5, 2e5]
}
else:
return {
... | 153e6ccd16c86bebb5c4597a02e64d0f90c10e63 | 76,729 |
from datetime import datetime
def get_datetime_utcnow():
"""Returns local datetime in UTC"""
return datetime.utcnow() | a64843d111344b30eacc5e99258e28f12376a321 | 76,730 |
from re import S
def sub_pre(e):
""" Replace y - x with -(x - y) if -1 can be extracted from y - x.
"""
# replacing Add, A, from which -1 can be extracted with -1*-A
adds = [a for a in e.atoms(Add) if a.could_extract_minus_sign()]
reps = {}
ignore = set()
for a in adds:
na = -a
... | 442107e979f3d0eb33d5f7fcb59968fc3d590753 | 76,731 |
from pathlib import Path
def replace_extension(infile):
"""Replace extensions of file."""
extensions = "".join(Path(str(infile)).suffixes[-2:])
new_ext = ".tab.gz"
outfile = str(infile).replace(extensions, new_ext)
return outfile | 685905d3c55aa7422c6cc8422e8278150d1dce20 | 76,732 |
def to_join_tree(bbn: Bbn) -> JoinTree:
"""
Converts a BBN to a Join Tree.
:param bbn: BBN.
:return: Join Tree.
"""
return InferenceController.apply(bbn) | 8a14367826ad179f888047e2d46b080c0a0fb8da | 76,733 |
from typing import Union
from typing import Sequence
from typing import Any
from typing import Mapping
import torch
import collections
def default_collate_fn(
batch: Union[Sequence[Any], Mapping[str, Any]],
device: torch.device,
pin_memory: bool = False,
non_blocking: bool = False):
... | d69c2dbdb0a1e179ead54e0816fbc9b856de18a1 | 76,734 |
def test_equalodds(obs: _np.ndarray) -> _pd.DataFrame:
"""Return the results test of the null hypothesis that the odds
ratio is the same in all _k_ strata.
This is the Tarone test.
Args:
adjust: If true, use the Tarone adjustment to achieve the chi^2\
asymptotic distribution.
... | 45fb55f6aa13bbf1d9943b427e824890c400cda3 | 76,735 |
def is_bench_config_file(file_name):
"""
Check if the given file is a BenchConfig
:param file_name: string
:param file_name: File to check
:rtype: boolean
:return: If the file is a bench config or not
"""
status = False
try:
# MUST BE xml file
if file_name.endswit... | d816e90053fbd99f839447a5be989801d0de0d80 | 76,736 |
def get_text_list(list_, last_word=gettext_lazy('or')):
"""
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>>> get_text_list(['a', 'b'], 'and')
'a and b'
>>> get_text_list(['a'])
'a'
>>> get_text_list([])
''
"... | e06a72876a696ef3a529b2d596c6216e51133c2d | 76,737 |
def convert_signed_tx_to_raw_hex(signed_tx_ascii):
"""Converts a signed tx from armory's offline format to a raw hex tx that bitcoind can broadcast/use"""
print("REQUEST(convert_signed_tx_to_raw_hex) -- signed_tx_ascii:\n'%s'\n" % (signed_tx_ascii,))
try:
utx = UnsignedTransaction()
utx.uns... | 05fe9b68afe0d96e6144fc9f36993539ae2f4be2 | 76,738 |
def exercise_4_10_8(v):
"""
Take a point and reflect about the y-axis (e.g. (x, y) -> (-x, y)
This is a linear function because it satisfies properties L1 and L2 above.
:param v: 2-vector x, y
:return: v translated about the y-axis
>>> L = exercise_4_10_8(a * u)
>>> L == list2vec([-2, 0])
... | 7e8d0a7a9dc972bfecb779a8e4917e9ffc3d2e2e | 76,740 |
import time
def fg(model, x, y, mag_list, target=True, mask=None):
"""
Fast Gradient attack. Similar to iterative attack but only takes one step
and then clip result afterward.
Parameters
----------
model : Keras Model
Model to attack
x : np.array, shape=(n_sample... | f52d486645e77d67c429cedc7890232ea0b25b6c | 76,742 |
def mocked_api_response():
"""Mocked response returned by mock_api."""
response_mock = MagicMock()
response_mock.status_code = 200
response_mock.json.return_value = [{"create_time": "2019-03-10T02:43:49.330"}]
return response_mock | ad2931ace2e365b68e3b1de3118feb09e0d85b4d | 76,743 |
async def trigger_delete(trigger=Depends(get_trigger)):
"""Deletes trigger with id **trigger_id** for hood with id **hood_id**."""
await trigger.delete()
return Response(status_code=status.HTTP_204_NO_CONTENT) | 20432d97d5d18878da18580fd9aa64c13655a1d4 | 76,744 |
def GetConstEx(enum_id, value, serial, bmask):
"""
Get id of constant
@param enum_id: id of enum
@param value: value of constant
@param serial: serial number of the constant in the
enumeration. See OpEnumEx() for details.
@param bmask: bitmask of the constant
ordinar... | 2d7c94ec0a9745939ee39faa9371719351f2417a | 76,745 |
def expand_grid(grid):
"""Expand grid by one in every direction."""
new_length = len(grid) + 2
row = [0 for _ in range(new_length)]
new_grid = [[0] + row + [0] for row in grid]
return [row[:]] + new_grid + [row[:]] | 773ccd3f0bb308ed294f6c3b202818e9a8f7511a | 76,746 |
def _L(dfs_data):
"""L(T) contains leaves and branch points for the DFS-tree T."""
"""L(T) = {v | the first w in Adj[v] corresponds to a frond vw}."""
node_set = set()
for v, adj in list(dfs_data['adj'].items()):
w = adj[0]
if is_frond(v, w, dfs_data):
node_set.add(v)
ret... | 620f11fbda880f987087e65a96ae43ff613e4fa4 | 76,747 |
def parse_style(style_string: str) -> Style:
"""
Parses a style string, returning a #Style object with the foreground and
background color and the attributes per the string. A style string is a
sequence of words each of one of the following formats:
* `fg:<color_string>`: #Foreground
* `bg:<color_string>`:... | aea37d04ab68d7bcc0a60d382ed97a7004378368 | 76,748 |
def stratify(all_labels, types):
"""
Divide label into three categories.
"""
coarse = types[:9]
fine = types[9:130]
return ([l for l in all_labels if l in coarse],
[l for l in all_labels if ((l in fine) and (not l in coarse))],
[l for l in all_labels if (not l in coarse) and (not l in fi... | 699a632786249d0f1ea59db34bfe4b50c7a93080 | 76,749 |
def parse_file_entities_with_pipelines(filename, entities=None, config=None,
include_unmatched=False) -> t.Dict[str, str]:
"""
bids.extract_pipelines_from_path extended with ability to
"""
et_dict = parse_file_entities(filename, entities, config, include_unmatched)... | 7aab01b53a3c0784fcc665bcef916361a3c2397d | 76,751 |
import json
async def get_system_summary() -> dict:
"""
Returns device status information:
- IP address
- CPU utilization
- Memory usage
- Disk utilization
- Device temperature
"""
ip = await get_local_ipv4_async()
# determine CPU load
cmd = "top -bn1 | grep load | awk '{... | 375093d535a08896bb1de41268d10c0237d62a7f | 76,752 |
def requires_nltk_corpus(func):
"""Wraps a function that requires an NLTK corpus. If the corpus isn't
found, raise a :exc:`MissingCorpusError`.
Credit: borrowed from Steve Loria's TextBlob package.
"""
@wraps(func)
def decorated(*args, **kwargs):
try:
return func(*args, **kw... | 5707b5264a01cbaf267e53601f8d8b717365f8f9 | 76,753 |
def _device_description_required(func):
"""
Decorator for checking whether the device description is available on a device.
"""
@wraps(func)
def wrapper(device, *args, **kwargs):
if device.description is None:
raise exceptions.NotRetrievedError('No device description retrieved ... | 74c8cdc611af1f19e7f21f2c8d087a8a182d8bfb | 76,754 |
def dbdisconnect(connection) -> bool:
"""Close connection to SQLite-Database
:param connection:
:return: Result of success (true/false)
"""
if connection:
connection.close()
return True
return False | 6c5d17d14e898696885730ef86fad9eab03af02f | 76,755 |
def _weighted_min(y, axis=1, weights=None):
"""Calculate weighted minimum.
Parameters
----------
y : np.ndarray, pd.Series or pd.DataFrame
Values to take the weighted minimum of.
weights: np.ndarray
Weights for each value in `array`. Must be same shape as `array` or
of shape... | 1954548690640b8a0f218ab8897209b8046643a6 | 76,756 |
from .xgboost_ray import _train
def train(
params: Dict,
dtrain: ModinDMatrix,
*args,
evals=(),
nthread: Optional[int] = cpu_count(),
**kwargs,
):
"""
Train XGBoost model.
Parameters
----------
params : dict
Booster params.
dtrain : ModinDMatrix
Data to... | cc6a5e4a5845e9dfce604a903bba61e225cd66be | 76,757 |
def calculate_area(res):
"""
Args:
Takes the transformed image as input
Returns:
:tot_area_acre_land: empty area in acres.
:trees: rounded number of trees in the possible area.
"""
# printing output
print(res.shape) # (640, 622, 3)
print(np.count_nonzero(res)) # 67908... | 47600a011422718edca6a299857ab7699c9a4a0c | 76,758 |
def likes_count(obj):
"""
Something like:
<div class="likes_count">{{ obj|likes_count }}</div>
will render:
<div class="likes_count">34</div>
"""
return Like.objects.filter(
receiver_content_type=ContentType.objects.get_for_model(obj),
receiver_object_id=obj.pk
... | 2307ece8f681838cc5bfa49b358f856b579998cb | 76,759 |
def normalize(X, norm='l2', copy=False):
"""Normalize sparse or dense matrix
Arguments:
---------
X: csr_matrix or csc_matrix
sparse matrix
norm: str, optional, default='l2'
normalize with l1/l2
copy: boolean, optional, default=False
whether to copy data or not
"""
... | ac5f86210b850bc4373cacab65b9f610f77eb793 | 76,760 |
def verify_embedding(emb, source, target, ignore_errors=()):
"""A simple (exception-raising) diagnostic for minor embeddings.
See :func:`diagnose_embedding` for a more detailed diagnostic / more information.
Args:
emb (dict): a dictionary mapping source nodes to arrays of target nodes
sour... | 55d58eff6cebcd6ff018035acee044cf365a217d | 76,761 |
def jacobi_symbol(n: int, k: int) -> int:
"""Pure Python Jacobi symbol function by unknown.
Published by Jacobi in 1837.
Ported from Lua jacobi https://en.wikipedia.org/wiki/Jacobi_symbol#Implementation_in_Lua
assert not implemented.
"""
#assert(k > 0 and k % 2 == 1)
n %= k
t = 1
wh... | 4277a6bc35a46fff237c200248be050c1921734c | 76,762 |
def get_readable_optimized_test(test_name):
"""Returns the path to the readable opt JS file the given test."""
return READABLE_OPT_TEST_PATTERN % parse_name(test_name) | 860b11d8d5b5ba970bb4189b53a2040bf0ed107c | 76,763 |
def schedule_dense_cblas(_, outs):
"""Create schedule for dense_cblas"""
return generic.schedule_extern(outs) | 6060411c0af75960418bfa196a8545f52422266d | 76,765 |
def is_subclass_of(node_a: astroid.ClassDef,
node_b: astroid.ClassDef) -> bool:
"""
Check if first node is a subclass of second node.
:param node_a: Node to check for subclass.
:type node_a: astroid.ClassDef
:param node_b: Node to check for superclass.
:type node_b: astroid.Cl... | abe76e6e2944f935d6456d511f165c67d3813e91 | 76,767 |
def _predict_variance(depth_values, curr_keep_window, gc_windows, min_windows=10):
"""
To estimate variance loess use all GC contents with more than min_windows_ratio out of total number of used windows.
"""
x = []
y = []
w = []
total_count = sum(curr_keep_window)
for gc_content, curr_gc... | 966eec1fe8f822af164674c6057787adb273d227 | 76,769 |
def helmholtz_illposed(n):
"""For given mesh division 'n' solves ill-posed problem
(-Laplace - 5*pi^2) u = x + y on [0, 1]*[0, 1],
u = 0 on boundary,
and returns space dimension, energy_error (on discrete subspace) and energy."""
mesh = UnitSquareMesh(n, n)
V ... | e7b2b3a8a5964c2d52b6efede24785a4e78f8b95 | 76,771 |
def AVGPRICE(df):
"""
函数名:AVGPRICE
名称:平均价格函数
python API
real=AVGPRICE(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low = df['low']
close = df['close']
return talib.AVGPRICE(open, high, low, close) | 79163b5482bc929e13349e620dfc5ff576043b9b | 76,772 |
from typing import Optional
from typing import List
from pathlib import Path
def plot_categorical_against_errors_boxplots(
data: Optional[pd.DataFrame] = None,
) -> List[Path]:
"""
Input data should be the "flattened" dataset.
"""
# Load default data
if data is None:
data = flatten_acc... | 5588cd370765db4a89edbd12a8d8bf6b7fec3fd8 | 76,773 |
def get_bprop_layer_norm_grad(self):
"""Grad definition for `LayerNormGrad` operation."""
layer_norm_grad_grad = G.LayerNormGradGrad(self.begin_norm_axis, self.begin_params_axis)
def bprop(x, dy, variance, mean, gamma, out, dout):
d_x, d_dy, d_gamma = layer_norm_grad_grad(
x, dy, varian... | 776e3bbf2c2cde946b29773446ae8a49b2e44011 | 76,774 |
from typing import Callable
from typing import Dict
from typing import Any
from typing import Optional
def robot_set_source_type_params(
testing_global_em_config: OpentronsEmulationConfiguration,
) -> Callable:
"""Create a runnable fixture that builds a RuntimeComposeFileModel."""
def robot_set_source_ty... | f5f4da644070675d8c537ff8c13f96c2773400d8 | 76,775 |
from typing import List
from typing import Tuple
def services(
ctx: Configuration, args: List, incomplete: str
) -> List[Tuple[str, str]]:
"""Services."""
_init_ctx(ctx)
try:
response = api.get_services(ctx)
except HTTPError:
response = []
completions = [] # type: List[Tuple[... | 3309ba79f7f15424721bb0e4ed7b0f53dc7c7f93 | 76,776 |
def split_in_seqs(data):
""" Splits a large spectrogram or label array into a sequence length units. """
nr_frames = data.shape[1]
nr_sequences = nr_frames // sequence_length
remainder = None
if nr_frames % sequence_length:
last_frame_index = -(nr_frames % sequence_length)
trimmed ... | 1d060e3ffa70484c75e3b09bf3e1584574b8827b | 76,777 |
def GetAllocationAffinity(args, client):
"""Returns the message of allocation affinity for the instance."""
if not args.IsSpecified('allocation_affinity'):
return None
type_msgs = (client.messages.
AllocationAffinity.ConsumeAllocationTypeValueValuesEnum)
if args.allocation_affinity == 'none... | c52f4a95120aa2ca13b2ec37857ad2f398634d77 | 76,779 |
def is_defect(pull_req, params, auth):
"""Checks the given pull request data against our criteria for
identifying defects
Args:
pull_req - dict representing a single pull request
params - list of parameter tuples
auth - authorization information
Returns:
True if our analy... | ea0dfbe6cbbb6f5b7003b453ea1edfe41fbd48d3 | 76,780 |
def api_all_tasks():
""" Tasks API: retrieve by filters, delete all tasks
"""
# retrieve tasks (plus completions and predictions) with pagination & ordering
if request.method == 'GET':
batchid = request.values.get('batchid', None)
# get filter parameters from request
batch_id = d... | dc7d3c521576ac8bf3f3466236b2956cf84be231 | 76,781 |
def boom_7_for(number):
"""itirate from zero to number with for,if number is divisable by 7 or contain 7 as a digit we'll add 'BOOM' to the list else we'll add the number"""
ls = []
for num in range(number +1):
if '7' in str(num) or num % 7 == 0:
ls.append("BOOM")
else:
... | ca3126849aa48d9b1578678d5679837304037fb7 | 76,782 |
import torch
def FPN_feature_key(mask):
"""Compute which FPN layer to use.
Args:
mask: a [H x W] torch tensor with values in {0,1}
Returns:
a string
"""
x_min, y_min, x_max, y_max = util_.mask_to_tight_box(mask)
roi_w = x_max-x_min+1; roi_h = y_max-y_min+1;
roi_w = roi_w.... | f1e775d11896418d275f100be01ac5f3c071c2b1 | 76,783 |
def update_profile(session: Session, auth: Auth, data: ProfileUpdate,
settings: Settings):
"""
This endpoint updates current user profile
"""
user = session.query(User).filter(User.id == auth.user.id).first()
if data['username'] != user.username and session.query(User).filter(
... | 0581a91c640fe1dea3069ba6c44e5e24494f629d | 76,784 |
def lcase(i):
"""
>>> lcase("Cat")
'cat'
"""
return i.lower() | 88eb1d7681c442757a372aeb06338412eac869ae | 76,785 |
import torch
import math
def attention(query, key, value, mask=None, dropout=None):
"""一个attention运算
Args:
query (tensor): Q
key (tensor): K
value (tensor): V
mask (tenosr, optional): mask. Defaults to None.
dropout (double, optional): dropout. Defaults to None.
R... | 5ebce63b59e4ac28f7ab3ab5c01ad2f98d3aad3b | 76,786 |
def generate_prior(n_poly: int = 5):
"""Generate prior distribution for fit."""
return {f"a{n}": gv.gvar(0, n + 1) for n in range(n_poly)} | 02b954ab1fc8377f5fbdb9fc00086aba7ce0f1d5 | 76,787 |
def inverse(mag, phs, **kwargs):
"""Inverse Short Time Discrete Fourier Transform from mag/phs.
Parameters
----------
mag : TYPE
Description
phs : TYPE
Description
**kwargs : TYPE
Description
Returns
-------
name : TYPE
Description
Deleted Param... | ce20c0974d78c5cc9b7b7822eef1f214430956b7 | 76,788 |
def query(cx, stmt, args=()):
"""Send query stmt to connection (with parameters) and return rows."""
return execute(cx, stmt, args, return_result=True) | e94286aa62b032dc9e97c252284a8e9ad8b57985 | 76,789 |
def _get_kwarg_as_str_attr(attr_name, value):
"""Creates an AttrValue for a python object."""
if isinstance(value, str):
return attr_value_pb2.AttrValue(s=compat.as_bytes(value))
else:
raise ValueError("Unsupported attribute type for %s with type %s" %
(attr_name, type(value))) | 3e79f50db684e7b9aab8b4d7e17927dfc74877b9 | 76,790 |
from phovea_processing_queue.task_definition import get_result
def get_result(task_id):
"""
returns the result of a task with blocking
:param task_id:
:return:
"""
res = get_result(task_id)
return jsonify(res.get()) | 720b499de2a540d620aef24338fcf8152c7666e8 | 76,791 |
def page_not_found(**ignore):
"""Return page not found for all undefined routes."""
return make_response(
render_template('page_not_found.html', url_root=request.url_root),
404
) | b81a2eb7a57e0ea301c624683d0f474e7f54dfc1 | 76,792 |
def __validate_patchset(remote, ticket, patchset):
"""
__validate_patchset(remote, ticket, patchset)
Validates that the specified ticket patchset exists.
"""
nps = 0
patchset_ref = 'refs/tickets/{:02d}/{:d}/{:d}'.format(ticket % 100, ticket, patchset)
for line in __call(['git', 'ls-remote'... | 5a1664f02231e7796161cb1f5f349ef74111d56d | 76,793 |
def viewshed(input_points: FeatureSet = {'exceededTransferLimit': False,
'spatialReference': {'latestWkid': 3857, 'wkid': 102100},
'geometryType': 'esriGeometryPoint',
'fields': [{'name': 'OID', 't... | d4732a1b238d2889be4af4a79ee4c37a9e3cb9bf | 76,794 |
import re
def GetBuildID(build_bot, date):
"""Get the build id for a build_bot at a given date."""
day = '{day:02d}'.format(day=date % 100)
mon = MONTHS[date / 100 % 100]
date_string = mon + ' ' + day
if build_bot in WATERFALL_BUILDERS:
url = 'https://uberchromegw.corp.google.com/i/chromeos/' + \
... | 6a0b8b908a94d536b7fb698d4bc93d96afe049f6 | 76,796 |
from typing import List
def transla(name_row: List[str], language_1: List[str], language_2: List[str]):
"""
:param name_row: The name in row
:param language_1: List of the first language
:param language_2: List of the second language
:return: translated name for each row
Usage:
gdf['type_... | 038536ed52970a077aca4e98961f5ef52c98e2c8 | 76,797 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.