uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d08093e8bd66ed0f58e082ee | train | function | def make_nograd_func(func):
def wrapper(*f_args, **f_kwargs):
with torch.no_grad():
ret = func(*f_args, **f_kwargs)
return ret
return wrapper
| def make_nograd_func(func):
| def wrapper(*f_args, **f_kwargs):
with torch.no_grad():
ret = func(*f_args, **f_kwargs)
return ret
return wrapper
| for k, v in args.__dict__.items():
print("{0: <10}\t{1: <30}\t{2: <20}".format(k, str(v), str(type(v))))
print("########################################################################")
# torch.no_grad warpper for functions
def make_nograd_func(func):
| 64 | 64 | 44 | 7 | 56 | Tangshengku/DDR-Net | utils.py | Python | make_nograd_func | make_nograd_func | 17 | 23 | 17 | 17 | e962d59d4abc542572ae17b7d57dc02405ef8b0a | bigcode/the-stack | train |
ae8ad09e9f854ae488c02413 | train | function | @make_nograd_func
@compute_metrics_for_each_image
def AbsDepthError_metrics(depth_est, depth_gt, mask, thres=None):
depth_est, depth_gt = depth_est[mask], depth_gt[mask]
error = (depth_est - depth_gt).abs()
if thres is not None:
error = error[(error >= float(thres[0])) & (error <= float(thres[1]))]
... | @make_nograd_func
@compute_metrics_for_each_image
def AbsDepthError_metrics(depth_est, depth_gt, mask, thres=None):
| depth_est, depth_gt = depth_est[mask], depth_gt[mask]
error = (depth_est - depth_gt).abs()
if thres is not None:
error = error[(error >= float(thres[0])) & (error <= float(thres[1]))]
if error.shape[0] == 0:
return torch.tensor(0, device=error.device, dtype=error.dtype)
retur... | depth_gt)
err_mask = errors > thres
return torch.mean(err_mask.float())
# NOTE: please do not use this to build up training loss
@make_nograd_func
@compute_metrics_for_each_image
def AbsDepthError_metrics(depth_est, depth_gt, mask, thres=None):
| 64 | 64 | 125 | 30 | 33 | Tangshengku/DDR-Net | utils.py | Python | AbsDepthError_metrics | AbsDepthError_metrics | 151 | 160 | 151 | 153 | 2a2a148584be4c7b314ac9807cd485f5d0149db9 | bigcode/the-stack | train |
26eea8be33ec525f3a38db05 | train | function | def local_pcd(depth, intr):
nx = depth.shape[1] # w
ny = depth.shape[0] # h
x, y = np.meshgrid(np.arange(nx), np.arange(ny), indexing='xy')
x = x.reshape(nx * ny)
y = y.reshape(nx * ny)
p2d = np.array([x, y, np.ones_like(y)])
p3d = np.matmul(np.linalg.inv(intr), p2d)
depth = depth.resh... | def local_pcd(depth, intr):
| nx = depth.shape[1] # w
ny = depth.shape[0] # h
x, y = np.meshgrid(np.arange(nx), np.arange(ny), indexing='xy')
x = x.reshape(nx * ny)
y = y.reshape(nx * ny)
p2d = np.array([x, y, np.ones_like(y)])
p3d = np.matmul(np.linalg.inv(intr), p2d)
depth = depth.reshape(1, nx * ny)
p3d *= d... | bisect_right(self.milestones, self.last_epoch)
for base_lr in self.base_lrs
]
def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def local_pcd(depth, intr):
| 64 | 64 | 169 | 8 | 56 | Tangshengku/DDR-Net | utils.py | Python | local_pcd | local_pcd | 263 | 275 | 263 | 263 | 632ce49d598320301f9b0e5f1ba55240f0104e7f | bigcode/the-stack | train |
b0f099dac4f8b200b1b4b66b | train | class | class AuthServiceProxyWrapper():
"""
An object that wraps AuthServiceProxy to record specific RPC calls.
"""
def __init__(self, auth_service_proxy_instance, coverage_logfile=None):
"""
Kwargs:
auth_service_proxy_instance (AuthServiceProxy): the instance
being... | class AuthServiceProxyWrapper():
| """
An object that wraps AuthServiceProxy to record specific RPC calls.
"""
def __init__(self, auth_service_proxy_instance, coverage_logfile=None):
"""
Kwargs:
auth_service_proxy_instance (AuthServiceProxy): the instance
being wrapped.
coverage_lo... | #!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for doing coverage analysis on the RPC interface.
Provides a way to track which RPC commands... | 93 | 112 | 374 | 6 | 87 | quishtv/QUISH | test/functional/test_framework/coverage.py | Python | AuthServiceProxyWrapper | AuthServiceProxyWrapper | 17 | 64 | 17 | 17 | e52d8cc0533bfb2112bb27c1b9528960577f3c84 | bigcode/the-stack | train |
d5539e7f42bccfb383ca7822 | train | function | def get_filename(dirname, n_node):
"""
Get a filename unique to the test process ID and node.
This file will contain a list of RPC commands covered.
"""
pid = str(os.getpid())
return os.path.join(
dirname, "coverage.pid%s.node%s.txt" % (pid, str(n_node)))
| def get_filename(dirname, n_node):
| """
Get a filename unique to the test process ID and node.
This file will contain a list of RPC commands covered.
"""
pid = str(os.getpid())
return os.path.join(
dirname, "coverage.pid%s.node%s.txt" % (pid, str(n_node)))
| , relative_uri):
return AuthServiceProxyWrapper(self.auth_service_proxy_instance / relative_uri,
self.coverage_logfile)
def get_request(self, *args, **kwargs):
self._log_call()
return self.auth_service_proxy_instance.get_request(*args)
def get_filename... | 64 | 64 | 70 | 8 | 56 | quishtv/QUISH | test/functional/test_framework/coverage.py | Python | get_filename | get_filename | 66 | 74 | 66 | 66 | 5e53a1a8c2d5e7769b77d5b09cd71d97ce743904 | bigcode/the-stack | train |
69f92cf0d8bda7e004ed9e23 | train | function | def write_all_rpc_commands(dirname, node):
"""
Write out a list of all RPC functions available in `QUISH-cli` for
coverage comparison. This will only happen once per coverage
directory.
Args:
dirname (str): temporary test dir
node (AuthServiceProxy): client
Returns:
boo... | def write_all_rpc_commands(dirname, node):
| """
Write out a list of all RPC functions available in `QUISH-cli` for
coverage comparison. This will only happen once per coverage
directory.
Args:
dirname (str): temporary test dir
node (AuthServiceProxy): client
Returns:
bool. if the RPC interface file was written.
... | the test process ID and node.
This file will contain a list of RPC commands covered.
"""
pid = str(os.getpid())
return os.path.join(
dirname, "coverage.pid%s.node%s.txt" % (pid, str(n_node)))
def write_all_rpc_commands(dirname, node):
| 63 | 64 | 191 | 9 | 54 | quishtv/QUISH | test/functional/test_framework/coverage.py | Python | write_all_rpc_commands | write_all_rpc_commands | 77 | 109 | 77 | 77 | cab759f589e0c67f1bc4f7b4fa1187635b24c2f0 | bigcode/the-stack | train |
7b9a19effd5c628ca82ea940 | train | class | class BooksConfig(AppConfig):
name = 'books'
def ready(self):
from . import signals
from . import models
post_delete.connect(signals.photo_cover_cleaner, sender=models.Book)
| class BooksConfig(AppConfig):
| name = 'books'
def ready(self):
from . import signals
from . import models
post_delete.connect(signals.photo_cover_cleaner, sender=models.Book)
| from django.apps import AppConfig
from django.db.models.signals import post_delete
# from books.models import Book
# from books.signals import signals
class BooksConfig(AppConfig):
| 38 | 64 | 44 | 6 | 31 | twistedTongues/django-dummy | src/books/apps.py | Python | BooksConfig | BooksConfig | 9 | 15 | 9 | 9 | abd41d4f259ebbccfaba0849db9fbbd945f2d3d7 | bigcode/the-stack | train |
b6c568164d6cf100058441da | train | class | class Migration(migrations.Migration):
dependencies = [
('stock', '0014_auto_20190908_0918'),
]
operations = [
migrations.AlterField(
model_name='stockitem',
name='URL',
field=InvenTree.fields.InvenTreeURLField(blank=True, max_length=125),
),
... | class Migration(migrations.Migration):
| dependencies = [
('stock', '0014_auto_20190908_0918'),
]
operations = [
migrations.AlterField(
model_name='stockitem',
name='URL',
field=InvenTree.fields.InvenTreeURLField(blank=True, max_length=125),
),
migrations.AlterField(
... | # Generated by Django 2.2.5 on 2019-09-13 14:07
import InvenTree.fields
from django.db import migrations
class Migration(migrations.Migration):
| 42 | 64 | 120 | 7 | 34 | ArakniD/InvenTree | InvenTree/stock/migrations/0015_auto_20190913_1407.py | Python | Migration | Migration | 7 | 24 | 7 | 8 | 1a99e094f5f5d728d9ff431dcff82fbf4c9223f5 | bigcode/the-stack | train |
c98bc7e736ce1140bac153a9 | train | class | class CreateJobRequest(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). T... | class CreateJobRequest(ModelNormal):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a c... | """
Eto API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 0.11.0
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from eto._internal.excep... | 175 | 256 | 2,096 | 7 | 168 | eto-ai/etosdk | eto/_internal/model/create_job_request.py | Python | CreateJobRequest | CreateJobRequest | 32 | 284 | 32 | 32 | cc21d6d9d8f9256e1aed398924a0d6588f5cb3ef | bigcode/the-stack | train |
1188e9456f63cf71fafd8306 | train | function | def add_noise(data,type="gaussian",p=0.1):
if type == "gaussian":
return data + p * np.random.normal(loc=0.0, scale=0.5, size=data.shape)
if type == "salt_pepper":
out = data + np.random.choice([0, 1], size=data.shape, p=[1-p, p])
return np.where(out > 1,1,out)
else:
... | def add_noise(data,type="gaussian",p=0.1):
| if type == "gaussian":
return data + p * np.random.normal(loc=0.0, scale=0.5, size=data.shape)
if type == "salt_pepper":
out = data + np.random.choice([0, 1], size=data.shape, p=[1-p, p])
return np.where(out > 1,1,out)
else:
print("wrong type")
| 4],n_comp)
plt.subplot(3,nb_pred,j+2*nb_pred)
plt.title("Reconstructed")
show_image(net.predict(np.asarray([X_test[i]])),n)
j+=1
def add_noise(data,type="gaussian",p=0.1):
| 64 | 64 | 105 | 16 | 47 | hider-toula/API-CNN | tools/basic.py | Python | add_noise | add_noise | 169 | 177 | 169 | 170 | 9f2da8a598de4b727c6b0ebebbfe5cb63fc7e039 | bigcode/the-stack | train |
9f3f180e930ed1e488f77539 | train | function | def make_grid(data=None, xmin=-5, xmax=5, ymin=-5, ymax=5, step=20):
""" Cree une grille sous forme de matrice 2d de la liste des points
:param data: pour calcluler les bornes du graphe
:param xmin: si pas data, alors bornes du graphe
:param xmax:
:param ymin:
:param ymax:
:param step... | def make_grid(data=None, xmin=-5, xmax=5, ymin=-5, ymax=5, step=20):
| """ Cree une grille sous forme de matrice 2d de la liste des points
:param data: pour calcluler les bornes du graphe
:param xmin: si pas data, alors bornes du graphe
:param xmax:
:param ymin:
:param ymax:
:param step: pas de la grille
:return: une matrice 2d contenant les points d... | """
grid, x, y = make_grid(data=data, step=step)
plt.contourf(x, y, f(grid).reshape(x.shape), colors=('gray', 'blue'), levels=[-1, 0, 1])
def make_grid(data=None, xmin=-5, xmax=5, ymin=-5, ymax=5, step=20):
| 78 | 81 | 270 | 26 | 52 | hider-toula/API-CNN | tools/basic.py | Python | make_grid | make_grid | 89 | 105 | 89 | 89 | 56926d8620c4ce74c8501402ed6bbbf3d801da50 | bigcode/the-stack | train |
c0f0aaaaaceebcbd5496f5b2 | train | function | def plot_data(data, labels=None):
"""
Affiche des donnees 2D
:param data: matrice des donnees 2d
:param labels: vecteur des labels (discrets)
:return:
"""
cols, marks = ["red", "green", "blue", "orange", "black", "cyan"], [".", "+", "*", "o", "x", "^"]
if labels is None:
... | def plot_data(data, labels=None):
| """
Affiche des donnees 2D
:param data: matrice des donnees 2d
:param labels: vecteur des labels (discrets)
:return:
"""
cols, marks = ["red", "green", "blue", "orange", "black", "cyan"], [".", "+", "*", "o", "x", "^"]
if labels is None:
plt.scatter(data[:, 0], data... | [:, 1] += np.random.normal(0, epsilon, nbex)
# on mélange les données
idx = np.random.permutation((range(y.size)))
data = data[idx, :]
y = y[idx]
return data, y
def plot_data(data, labels=None):
| 64 | 64 | 154 | 8 | 55 | hider-toula/API-CNN | tools/basic.py | Python | plot_data | plot_data | 60 | 73 | 60 | 60 | 1b54a35de956f90cc83e29da2f842a7100900f61 | bigcode/the-stack | train |
3a222dc62cb81e101250cf5d | train | function | def draw_pred(X_test,y_test,net,nb_pred=6,n=16):
random_ind = np.random.choice(np.arange(X_test.shape[0]), nb_pred, replace=False)
plt.figure(figsize=(15,5*np.ceil(nb_pred / 3)))
j = 1
for i in random_ind:
plt.subplot(np.ceil(nb_pred / 3),3,j)
plt.title("pred : {0} true : {1}".... | def draw_pred(X_test,y_test,net,nb_pred=6,n=16):
| random_ind = np.random.choice(np.arange(X_test.shape[0]), nb_pred, replace=False)
plt.figure(figsize=(15,5*np.ceil(nb_pred / 3)))
j = 1
for i in random_ind:
plt.subplot(np.ceil(nb_pred / 3),3,j)
plt.title("pred : {0} true : {1}".format(net.predict(np.asarray([X_test[i]])), y_test[i]... | [0]),np.hstack(tmp[1])
return tmpx,tmpy
def show_image(data,n=16):
plt.imshow(data.reshape((n,n)),interpolation="nearest",cmap="gray")
def draw_pred(X_test,y_test,net,nb_pred=6,n=16):
| 63 | 64 | 126 | 19 | 44 | hider-toula/API-CNN | tools/basic.py | Python | draw_pred | draw_pred | 132 | 142 | 132 | 134 | 89fc4186b1922545f1d376e9ac98db03c1e8793e | bigcode/the-stack | train |
699c818b42c47109456ca38e | train | function | def gen_arti(centerx=1, centery=1, sigma=0.1, nbex=1000, data_type = 0, epsilon=0.02):
xpos = np.random.multivariate_normal([centerx, centerx], np.diag([sigma, sigma]), nbex // 2)
xneg = np.random.multivariate_normal([-centerx, -centerx], np.diag([sigma, sigma]), nbex // 2)
data = np.vstack((xp... | def gen_arti(centerx=1, centery=1, sigma=0.1, nbex=1000, data_type = 0, epsilon=0.02):
| xpos = np.random.multivariate_normal([centerx, centerx], np.diag([sigma, sigma]), nbex // 2)
xneg = np.random.multivariate_normal([-centerx, -centerx], np.diag([sigma, sigma]), nbex // 2)
data = np.vstack((xpos, xneg))
y = np.hstack((np.ones(nbex // 2), -np.ones(nbex // 2)))
# un peu de ... | import numpy as np
import matplotlib.pyplot as plt
def gen_arti(centerx=1, centery=1, sigma=0.1, nbex=1000, data_type = 0, epsilon=0.02):
| 51 | 185 | 617 | 40 | 10 | hider-toula/API-CNN | tools/basic.py | Python | gen_arti | gen_arti | 6 | 55 | 6 | 9 | 96f67c2277e7f131de414fa46ea6e5e563dfd530 | bigcode/the-stack | train |
1f3e2bbc5b8ece4882bf3891 | train | function | def draw_noise(X_test,X_bruit,net,nb_pred=None,n=28,n_comp=4):
if nb_pred == None:
ids = [1,3,5,7,2,0,18,15,17,4]
nb_pred=10
else:
ids = np.random.choice(np.arange(X_test.shape[0]), nb_pred, replace=False)
plt.figure(figsize=(5*nb_pred,15))
j = 1
for i in ids:
... | def draw_noise(X_test,X_bruit,net,nb_pred=None,n=28,n_comp=4):
| if nb_pred == None:
ids = [1,3,5,7,2,0,18,15,17,4]
nb_pred=10
else:
ids = np.random.choice(np.arange(X_test.shape[0]), nb_pred, replace=False)
plt.figure(figsize=(5*nb_pred,15))
j = 1
for i in ids:
plt.subplot(3,nb_pred,j)
plt.title("Real")
s... | np.random.choice([0, 1], size=data.shape, p=[1-p, p])
return np.where(out > 1,1,out)
else:
print("wrong type")
def draw_noise(X_test,X_bruit,net,nb_pred=None,n=28,n_comp=4):
| 64 | 64 | 207 | 23 | 41 | hider-toula/API-CNN | tools/basic.py | Python | draw_noise | draw_noise | 179 | 200 | 179 | 180 | 03ca320ac8b59f3dbeb395eed163773abfb37fe4 | bigcode/the-stack | train |
6fa9afae033ad2978ce88fed | train | function | def show_image(data,n=16):
plt.imshow(data.reshape((n,n)),interpolation="nearest",cmap="gray")
| def show_image(data,n=16):
| plt.imshow(data.reshape((n,n)),interpolation="nearest",cmap="gray")
| return resx,resy
tmp = list(zip(*[get_usps(i,datax,datay) for i in l]))
tmpx,tmpy = np.vstack(tmp[0]),np.hstack(tmp[1])
return tmpx,tmpy
def show_image(data,n=16):
| 64 | 64 | 27 | 8 | 55 | hider-toula/API-CNN | tools/basic.py | Python | show_image | show_image | 128 | 129 | 128 | 128 | bf4658fff0637b9fe222eeb0cff4ee345fb812ba | bigcode/the-stack | train |
8c44a2d1ce52f3451ea479f7 | train | function | def draw_construction(X_test,net,nb_pred=None,n=28,n_comp=4):
if nb_pred == None:
ids = [1,3,5,7,2,0,18,15,17,4]
nb_pred=10
else:
ids = np.random.choice(np.arange(X_test.shape[0]), nb_pred, replace=False)
plt.figure(figsize=(5*nb_pred,15))
j = 1
for i in ids:
... | def draw_construction(X_test,net,nb_pred=None,n=28,n_comp=4):
| if nb_pred == None:
ids = [1,3,5,7,2,0,18,15,17,4]
nb_pred=10
else:
ids = np.random.choice(np.arange(X_test.shape[0]), nb_pred, replace=False)
plt.figure(figsize=(5*nb_pred,15))
j = 1
for i in ids:
plt.subplot(3,nb_pred,j)
plt.title("Real")
s... | plt.title("pred : {0} true : {1}".format(net.predict(np.asarray([X_test[i]])), y_test[i]))
show_image(X_test[i],n)
j+=1
def draw_construction(X_test,net,nb_pred=None,n=28,n_comp=4):
| 64 | 64 | 211 | 21 | 42 | hider-toula/API-CNN | tools/basic.py | Python | draw_construction | draw_construction | 146 | 167 | 146 | 147 | bfcac891abb222e186d95d0afc69cd7cc5cc8a18 | bigcode/the-stack | train |
170f8d6b27ff6f9ae5e77a64 | train | function | def plot_frontiere(data, f, step=20):
""" Trace un graphe de la frontiere de decision de f
:param data: donnees
:param f: fonction de decision
:param step: pas de la grille
:return:
"""
grid, x, y = make_grid(data=data, step=step)
plt.contourf(x, y, f(grid).reshape(x.shape), colo... | def plot_frontiere(data, f, step=20):
| """ Trace un graphe de la frontiere de decision de f
:param data: donnees
:param f: fonction de decision
:param step: pas de la grille
:return:
"""
grid, x, y = make_grid(data=data, step=step)
plt.contourf(x, y, f(grid).reshape(x.shape), colors=('gray', 'blue'), levels=[-1, 0, 1])... | [:, 0], data[:, 1])
return
for i, l in enumerate(sorted(list(set(labels.flatten())))):
plt.scatter(data[labels == l, 0], data[labels == l, 1], c=cols[i])
def plot_frontiere(data, f, step=20):
| 64 | 64 | 110 | 12 | 52 | hider-toula/API-CNN | tools/basic.py | Python | plot_frontiere | plot_frontiere | 75 | 83 | 75 | 75 | 888941bf37aae6c5da12ab12fa1e200378af647f | bigcode/the-stack | train |
25577be5c5a3f3657aa113ad | train | function | def get_usps(l,datax,datay):
if type(l)!=list:
resx = datax[datay==l,:]
resy = datay[datay==l]
return resx,resy
tmp = list(zip(*[get_usps(i,datax,datay) for i in l]))
tmpx,tmpy = np.vstack(tmp[0]),np.hstack(tmp[1])
return tmpx,tmpy
| def get_usps(l,datax,datay):
| if type(l)!=list:
resx = datax[datay==l,:]
resy = datay[datay==l]
return resx,resy
tmp = list(zip(*[get_usps(i,datax,datay) for i in l]))
tmpx,tmpy = np.vstack(tmp[0]),np.hstack(tmp[1])
return tmpx,tmpy
| r") as f:
f.readline()
data = [[float(x) for x in l.split()] for l in f if len(l.split())>2]
tmp=np.array(data)
return tmp[:,1:],tmp[:,0].astype(int)
def get_usps(l,datax,datay):
| 64 | 64 | 99 | 11 | 53 | hider-toula/API-CNN | tools/basic.py | Python | get_usps | get_usps | 119 | 126 | 119 | 119 | a9790d1472cc0e7919226fe66f0626ad11943d7f | bigcode/the-stack | train |
8387ef2cd327346bbde2a716 | train | function | def load_usps(fn):
with open(fn,"r") as f:
f.readline()
data = [[float(x) for x in l.split()] for l in f if len(l.split())>2]
tmp=np.array(data)
return tmp[:,1:],tmp[:,0].astype(int)
| def load_usps(fn):
| with open(fn,"r") as f:
f.readline()
data = [[float(x) for x in l.split()] for l in f if len(l.split())>2]
tmp=np.array(data)
return tmp[:,1:],tmp[:,0].astype(int)
| (xmax - xmin) * 1. / step),
np.arange(ymin, ymax, (ymax - ymin) * 1. / step))
grid = np.c_[x.ravel(), y.ravel()]
return grid, x, y
def load_usps(fn):
| 63 | 64 | 64 | 6 | 56 | hider-toula/API-CNN | tools/basic.py | Python | load_usps | load_usps | 112 | 117 | 112 | 112 | 31cb8609e44fe476598a8458ea3c42ba6e9e6022 | bigcode/the-stack | train |
62c8c340dd1cd056f5bcba73 | train | function | def get_path_string_from_root_to_node(node_name, sep='|'):
node_names = list()
for node in node_name.path:
node_names.append(node.name)
return sep.join(node_names)
| def get_path_string_from_root_to_node(node_name, sep='|'):
| node_names = list()
for node in node_name.path:
node_names.append(node.name)
return sep.join(node_names)
| def get_node_from_node_name(node_name, root_node):
nodes = search.findall(root_node, filter_=lambda node: node.name == node_name)
if len(nodes):
return nodes[0]
else:
return None
def get_path_string_from_root_to_node(node_name, sep='|'):
| 64 | 64 | 43 | 15 | 48 | gsravank/expense-tracker | expense_tracker/category_tree.py | Python | get_path_string_from_root_to_node | get_path_string_from_root_to_node | 39 | 45 | 39 | 39 | a7a837d69cf61e3aa7983a7fcd8b1237b7d10a05 | bigcode/the-stack | train |
326963c25ae7f963f9f96acf | train | function | def get_category_tree_from_file(file_name):
with open(file_name, 'r') as f:
lines = f.readlines()
tree_name = lines[0].strip()
root = Node(tree_name)
for line in lines[1:]:
strings = line.strip().split(",")
category_name = strings[0].strip()
chi... | def get_category_tree_from_file(file_name):
| with open(file_name, 'r') as f:
lines = f.readlines()
tree_name = lines[0].strip()
root = Node(tree_name)
for line in lines[1:]:
strings = line.strip().split(",")
category_name = strings[0].strip()
children = [child.strip() for child in strings[... | from anytree import Node, RenderTree, search, PreOrderIter
def get_category_tree_from_file(file_name):
| 24 | 64 | 129 | 9 | 14 | gsravank/expense-tracker | expense_tracker/category_tree.py | Python | get_category_tree_from_file | get_category_tree_from_file | 4 | 23 | 4 | 4 | cc9c139b5575d0d9c7a2b55b8f63d24538be1377 | bigcode/the-stack | train |
25406b5a17618297dca06acc | train | function | def get_all_leaf_nodes_below_any_node(node_name):
leaf_nodes = list()
for node in PreOrderIter(node_name):
if len(node.children) == 0:
leaf_nodes.append(node)
return leaf_nodes
| def get_all_leaf_nodes_below_any_node(node_name):
| leaf_nodes = list()
for node in PreOrderIter(node_name):
if len(node.children) == 0:
leaf_nodes.append(node)
return leaf_nodes
| 0]
else:
return None
def get_path_string_from_root_to_node(node_name, sep='|'):
node_names = list()
for node in node_name.path:
node_names.append(node.name)
return sep.join(node_names)
def get_all_leaf_nodes_below_any_node(node_name):
| 64 | 64 | 49 | 12 | 52 | gsravank/expense-tracker | expense_tracker/category_tree.py | Python | get_all_leaf_nodes_below_any_node | get_all_leaf_nodes_below_any_node | 48 | 55 | 48 | 48 | 5f0af2a556e915cf839ec739c155756f952e2410 | bigcode/the-stack | train |
afecb9a50d5918a72340a0e8 | train | function | def get_node_from_node_name(node_name, root_node):
nodes = search.findall(root_node, filter_=lambda node: node.name == node_name)
if len(nodes):
return nodes[0]
else:
return None
| def get_node_from_node_name(node_name, root_node):
| nodes = search.findall(root_node, filter_=lambda node: node.name == node_name)
if len(nodes):
return nodes[0]
else:
return None
| for child in children:
child_node = Node(child, parent=category_node)
return root
def print_tree(root):
for pre, fill, node in RenderTree(root):
print("%s%s" % (pre, node.name))
def get_node_from_node_name(node_name, root_node):
| 64 | 64 | 49 | 12 | 52 | gsravank/expense-tracker | expense_tracker/category_tree.py | Python | get_node_from_node_name | get_node_from_node_name | 31 | 36 | 31 | 31 | b9a71b42a34fe1cd3a6d57df1b5d378f8c4c677b | bigcode/the-stack | train |
64bc4faa241fcfbca7a230d5 | train | function | def print_tree(root):
for pre, fill, node in RenderTree(root):
print("%s%s" % (pre, node.name))
| def print_tree(root):
| for pre, fill, node in RenderTree(root):
print("%s%s" % (pre, node.name))
| strip()
children = [child.strip() for child in strings[1:] if child != '']
category_node = Node(category_name, parent=root)
if len(children):
for child in children:
child_node = Node(child, parent=category_node)
return root
def print_tree(ro... | 64 | 64 | 30 | 5 | 58 | gsravank/expense-tracker | expense_tracker/category_tree.py | Python | print_tree | print_tree | 26 | 28 | 26 | 26 | 98a1f496e4deca65c37d4eb08d9ccd9f68c1d2bb | bigcode/the-stack | train |
0f84724d4c06e80186e89649 | train | function | def accuracy_and_f1(preds, labels):
"""
Mean of Accuracy and F-Score.
.. note::
The implementation from ``sklearn.metrics`` is used to compute the
F-Score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.... | def accuracy_and_f1(preds, labels):
| """
Mean of Accuracy and F-Score.
.. note::
The implementation from ``sklearn.metrics`` is used to compute the
F-Score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground tru... | Returns
-------
f1_score : float
F-Score of the model
"""
preds = _numpyfy(preds)
labels = _numpyfy(labels)
return f1_score(y_true=labels, y_pred=preds)
def accuracy_and_f1(preds, labels):
| 64 | 64 | 181 | 10 | 54 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | accuracy_and_f1 | accuracy_and_f1 | 77 | 102 | 77 | 77 | 316b37932da35473593a0f7ed58fc52ed338adac | bigcode/the-stack | train |
82b5ffc7b00bcc4be0160577 | train | function | def accuracy(preds, labels):
"""
Accuracy.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth labels with the same number of elements as
``preds``
Returns
-------
accur... | def accuracy(preds, labels):
| """
Accuracy.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth labels with the same number of elements as
``preds``
Returns
-------
accuracy : float
Accuracy ... |
----------
x : list or numpy.ndarray
A list of numbers
Returns
-------
x : numpy.ndarray
Numpy array with the original numbers
"""
if isinstance(x, np.ndarray):
return x
return np.array(x)
def accuracy(preds, labels):
| 64 | 64 | 108 | 7 | 57 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | accuracy | accuracy | 30 | 49 | 30 | 30 | e81dfa8817377856a5f3f90aa3d513eb7a1d222d | bigcode/the-stack | train |
43c921c92fa7cd74360518a6 | train | function | def spearman(preds, labels):
"""
Spearman correlation coefficient
.. note::
The implementation from ``scipy.stats`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A ... | def spearman(preds, labels):
| """
Spearman correlation coefficient
.. note::
The implementation from ``scipy.stats`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth labels w... | preds``
Returns
-------
pearson_score : float
Pearson's correlation coefficient of the model
"""
preds = _numpyfy(preds)
labels = _numpyfy(labels)
return pearsonr(preds, labels)[0]
def spearman(preds, labels):
| 64 | 64 | 139 | 8 | 56 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | spearman | spearman | 130 | 152 | 130 | 130 | 821c2ad2087f5a3c7f8f46395b53b838a45a4102 | bigcode/the-stack | train |
9727a5b9a61b9c96aae94224 | train | function | def pearson(preds, labels):
"""
Pearson's correlation coefficient
.. note::
The implementation from ``scipy.stats`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A ... | def pearson(preds, labels):
| """
Pearson's correlation coefficient
.. note::
The implementation from ``scipy.stats`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth labels ... | = _numpyfy(preds)
labels = _numpyfy(labels)
acc = accuracy(preds, labels)
f1_s = f1_score(y_true=labels, y_pred=preds)
return (acc + f1_s) / 2
def pearson(preds, labels):
| 64 | 64 | 139 | 8 | 55 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | pearson | pearson | 105 | 127 | 105 | 105 | 7fd81d9e2ea51bbac3a46201d2e965c9cc1607da | bigcode/the-stack | train |
28890215d95a297486ae3eec | train | function | def compute_score(preds, labels, metric):
"""
Utility function to compute scores using several metrics.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth labels with the same number of ele... | def compute_score(preds, labels, metric):
| """
Utility function to compute scores using several metrics.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth labels with the same number of elements as
``preds``
metric : st... | or numpy.ndarray
A list of ground truth labels with the same number of elements as
``preds``
Returns
-------
mcc_score : float
Matthew's correlation coefficient of the model
"""
preds = _numpyfy(preds)
labels = _numpyfy(labels)
return mcc(preds, labels)
def compute_... | 84 | 84 | 280 | 10 | 74 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | compute_score | compute_score | 205 | 238 | 205 | 205 | fc27e066e615353892ab9b9fd59bd4db33199b47 | bigcode/the-stack | train |
f1c7f310d3650a096a6be980 | train | function | def matthews_corrcoef(preds, labels):
"""
Matthew's correlation coefficient
.. note::
The implementation from ``sklearn.metrics`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndar... | def matthews_corrcoef(preds, labels):
| """
Matthew's correlation coefficient
.. note::
The implementation from ``sklearn.metrics`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth lab... | Mean of Pearson and Spearman correlation coefficients of the model
"""
preds = _numpyfy(preds)
labels = _numpyfy(labels)
return (pearson(preds, labels) + spearman(preds, labels)) / 2
def matthews_corrcoef(preds, labels):
| 64 | 64 | 138 | 10 | 53 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | matthews_corrcoef | matthews_corrcoef | 180 | 202 | 180 | 180 | 8cdee89086042291012c5a132197a6b3d9280507 | bigcode/the-stack | train |
ad34b01e69862e6e4a900c98 | train | function | def pearson_and_spearman(preds, labels):
"""
Mean of Pearson and Spearman correlation coefficients.
.. note::
The implementation from ``scipy.stats`` is used to compute the scores.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels... | def pearson_and_spearman(preds, labels):
| """
Mean of Pearson and Spearman correlation coefficients.
.. note::
The implementation from ``scipy.stats`` is used to compute the scores.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list o... | Returns
-------
spearman_score : float
Spearman correlation coefficient of the model
"""
preds = _numpyfy(preds)
labels = _numpyfy(labels)
return spearmanr(preds, labels)[0]
def pearson_and_spearman(preds, labels):
| 64 | 64 | 164 | 12 | 52 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | pearson_and_spearman | pearson_and_spearman | 155 | 177 | 155 | 155 | 743708fa76c805230b136e2d68ed9450f8630e3d | bigcode/the-stack | train |
3382bbe6d281e5b65ab71d26 | train | function | def f1(preds, labels):
"""
F-Score or F1 score.
.. note::
The implementation from ``sklearn.metrics`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground... | def f1(preds, labels):
| """
F-Score or F1 score.
.. note::
The implementation from ``sklearn.metrics`` is used to compute the score.
Parameters
----------
preds : list or numpy.ndarray
A list of predictions from a model
labels : list or numpy.ndarray
A list of ground truth labels with the ... | as
``preds``
Returns
-------
accuracy : float
Accuracy of the model
"""
preds = _numpyfy(preds)
labels = _numpyfy(labels)
return (preds == labels).mean()
import json
def f1(preds, labels):
| 64 | 64 | 145 | 8 | 55 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | f1 | f1 | 52 | 74 | 52 | 52 | 7e65223b9ab8c61d30a37d46f8aed9aa1860586f | bigcode/the-stack | train |
579e5ec11ec3257d0f44a848 | train | function | def _numpyfy(x):
"""
Internal helper function to convert standard lists into numpy arrays.
Parameters
----------
x : list or numpy.ndarray
A list of numbers
Returns
-------
x : numpy.ndarray
Numpy array with the original numbers
"""
if isinstance(x, np.ndarray)... | def _numpyfy(x):
| """
Internal helper function to convert standard lists into numpy arrays.
Parameters
----------
x : list or numpy.ndarray
A list of numbers
Returns
-------
x : numpy.ndarray
Numpy array with the original numbers
"""
if isinstance(x, np.ndarray):
return ... | """
Module that wraps around several standard metrics
"""
import numpy as np
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import matthews_corrcoef as mcc, f1_score
def _numpyfy(x):
| 49 | 64 | 79 | 6 | 42 | qcri/NeuroX | neurox/interpretation/metrics.py | Python | _numpyfy | _numpyfy | 10 | 27 | 10 | 10 | 24d9ada140061df754bfdb8b10d267b92ed412fd | bigcode/the-stack | train |
785d3646c3e8de29b3fc3188 | train | class | class RevoluteSeparateHandler(SeparateController):
"""
class holding and instantiating the separate revolute controller
"""
def __init__(self, plugin, widget, unit, default_minimum, default_maximum):
self._controller_left = ControllerTool(
plugin=plugin,
unit=unit,
... | class RevoluteSeparateHandler(SeparateController):
| """
class holding and instantiating the separate revolute controller
"""
def __init__(self, plugin, widget, unit, default_minimum, default_maximum):
self._controller_left = ControllerTool(
plugin=plugin,
unit=unit,
default_minimum=default_minimum,
... | #!/usr/bin/env python
from tuw_iwos_revolute_and_steering_plugin.tool.controller_tool import ControllerTool
from tuw_iwos_revolute_and_steering_plugin.tool.separate_controller import SeparateController
class RevoluteSeparateHandler(SeparateController):
| 58 | 104 | 348 | 9 | 48 | kaltenegger/tuw_iwos | tuw_iwos_revolute_and_steering_plugin/src/tuw_iwos_revolute_and_steering_plugin/handler/revolute/revolute_separate_handler.py | Python | RevoluteSeparateHandler | RevoluteSeparateHandler | 7 | 38 | 7 | 7 | 12fa038e26830cf7506d874c2682cc0bf4362d31 | bigcode/the-stack | train |
5803d5e667ff8b84298b85f3 | train | function | def weighted_average(metrics: List[Tuple[int, Metrics]]) -> Metrics:
# Multiply accuracy of each client by number of examples used
accuracies = [num_examples * m["accuracy"] for num_examples, m in metrics]
examples = [num_examples for num_examples, _ in metrics]
# Aggregate and return custom metric (we... | def weighted_average(metrics: List[Tuple[int, Metrics]]) -> Metrics:
# Multiply accuracy of each client by number of examples used
| accuracies = [num_examples * m["accuracy"] for num_examples, m in metrics]
examples = [num_examples for num_examples, _ in metrics]
# Aggregate and return custom metric (weighted average)
return {"accuracy": sum(accuracies) / sum(examples)}
| from typing import List, Tuple
import flwr as fl
from flwr.common import Metrics
# Define metric aggregation function
def weighted_average(metrics: List[Tuple[int, Metrics]]) -> Metrics:
# Multiply accuracy of each client by number of examples used
| 54 | 64 | 88 | 28 | 25 | andreea-zaharia/flower | examples/quickstart_pytorch/server.py | Python | weighted_average | weighted_average | 8 | 14 | 8 | 9 | 82e16beff89f07eca7eefbd7ad6bd4d7b5218bc4 | bigcode/the-stack | train |
e4f3d267ad655f58687f7f65 | train | class | class SubscriptionPolicies(Model):
"""Subscription policies.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar location_placement_id: The subscription location placement ID. The
ID indicates which regions are visible for a subscription. For example, a
... | class SubscriptionPolicies(Model):
| """Subscription policies.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar location_placement_id: The subscription location placement ID. The
ID indicates which regions are visible for a subscription. For example, a
subscription with a location pl... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 88 | 101 | 338 | 5 | 82 | pjquirk/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2018_06_01/models/subscription_policies_py3.py | Python | SubscriptionPolicies | SubscriptionPolicies | 15 | 50 | 15 | 15 | 650b7676585c2feaf4862763830aacf5693aadbd | bigcode/the-stack | train |
d1726327ff3ff62fc142e115 | train | function | def prepare_image(image, target):
# if the image mode is not RGB, convert it
if image.mode != "RGB":
image = image.convert("RGB")
# resize the input image and preprocess it
image = image.resize(target)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
image = imagene... | def prepare_image(image, target):
# if the image mode is not RGB, convert it
| if image.mode != "RGB":
image = image.convert("RGB")
# resize the input image and preprocess it
image = image.resize(target)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
image = imagenet_utils.preprocess_input(image)
# return the processed image
return imag... | by Keras, but you can
# substitute in your own networks just as easily)
global model # pylint: disable=global-statement
model = ResNet50V2(weights="imagenet")
def prepare_image(image, target):
# if the image mode is not RGB, convert it
| 64 | 64 | 95 | 20 | 44 | ccaloian/simple-keras-rest-api | run_keras_server.py | Python | prepare_image | prepare_image | 30 | 42 | 30 | 31 | e5821986a6456bc3d1a7d702d3b3c217a92685bc | bigcode/the-stack | train |
5b3903a75a0997745464f371 | train | function | @app.route("/status", methods=["GET"])
def status():
return f"""{{'status': 'ok', 'model': {model.name}}}"""
| @app.route("/status", methods=["GET"])
def status():
| return f"""{{'status': 'ok', 'model': {model.name}}}"""
| preprocess it
image = image.resize(target)
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
image = imagenet_utils.preprocess_input(image)
# return the processed image
return image
@app.route("/status", methods=["GET"])
def status():
| 64 | 64 | 32 | 12 | 51 | ccaloian/simple-keras-rest-api | run_keras_server.py | Python | status | status | 44 | 46 | 44 | 45 | 44434a007fedb7d5ef595be6abb6e5ac58e00bd8 | bigcode/the-stack | train |
d8fb83f0cbff87989bd091b5 | train | function | def load_model():
# load the pre-trained Keras model (here we are using a model
# pre-trained on ImageNet and provided by Keras, but you can
# substitute in your own networks just as easily)
global model # pylint: disable=global-statement
model = ResNet50V2(weights="imagenet")
| def load_model():
# load the pre-trained Keras model (here we are using a model
# pre-trained on ImageNet and provided by Keras, but you can
# substitute in your own networks just as easily)
| global model # pylint: disable=global-statement
model = ResNet50V2(weights="imagenet")
| eras model
app = flask.Flask(__name__)
model = None
def load_model():
# load the pre-trained Keras model (here we are using a model
# pre-trained on ImageNet and provided by Keras, but you can
# substitute in your own networks just as easily)
| 64 | 64 | 74 | 49 | 14 | ccaloian/simple-keras-rest-api | run_keras_server.py | Python | load_model | load_model | 23 | 28 | 23 | 26 | 5c4116840aec434c823426440cf2f66e8cc920f0 | bigcode/the-stack | train |
3f41c6c7ee433d2666545f52 | train | function | @app.route("/predict", methods=["POST"])
def predict():
# initialize the data dictionary that will be returned from the
# view
data = {"success": False}
# ensure an image was properly uploaded to our endpoint
if flask.request.method == "POST":
if flask.request.files.get("image"):
... | @app.route("/predict", methods=["POST"])
def predict():
# initialize the data dictionary that will be returned from the
# view
| data = {"success": False}
# ensure an image was properly uploaded to our endpoint
if flask.request.method == "POST":
if flask.request.files.get("image"):
# read the image in PIL format
image = flask.request.files["image"].read()
image = Image.open(io.BytesIO(imag... | =0)
image = imagenet_utils.preprocess_input(image)
# return the processed image
return image
@app.route("/status", methods=["GET"])
def status():
return f"""{{'status': 'ok', 'model': {model.name}}}"""
@app.route("/predict", methods=["POST"])
def predict():
# initialize the data dictionary that wi... | 86 | 86 | 289 | 29 | 57 | ccaloian/simple-keras-rest-api | run_keras_server.py | Python | predict | predict | 49 | 85 | 49 | 52 | b68c26ca89aa70dbfd39316a660d89ddd5415511 | bigcode/the-stack | train |
e1dd4f71e601c70755530f1d | train | class | class Autoencoder(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(1, 16, 3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(16, 32, 3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(32, 64, 7),
)
... | class Autoencoder(nn.Module):
| def __init__(self):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(1, 16, 3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(16, 32, 3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(32, 64, 7),
)
self.decoder = nn.Sequ... | mnist_data, batch_size=64, shuffle=True
)
# Generate the batches of Image and labels
dataiter = iter(data_loader)
images, labels = dataiter.next()
# Get the minimum and maximum using torch for the images.
print(torch.min(images), torch.max(images))
class Autoencoder(nn.Module):
| 64 | 64 | 216 | 6 | 58 | janaSunrise/Autoencoder-Image-Pytorch | src/cnn_autoencoder.py | Python | Autoencoder | Autoencoder | 27 | 51 | 27 | 27 | d226459b12d452b1990c2d27dccebc78594907f9 | bigcode/the-stack | train |
255a4a1f98d1d90363902279 | train | class | class Client(Hash):
'''
Constructor
:param login str
:param password str
:param ng_type int
:param hash_type callback Hash method
'''
def __init__(self, login, password, ng_type=NG_2048, hash_type=SHA1):
super().__init__(hash_type)
self.I = login
self.p = passwor... | class Client(Hash):
| '''
Constructor
:param login str
:param password str
:param ng_type int
:param hash_type callback Hash method
'''
def __init__(self, login, password, ng_type=NG_2048, hash_type=SHA1):
super().__init__(hash_type)
self.I = login
self.p = password
self.N, se... | 50])
class Hash():
def __init__(self, hash_type):
self._hash_type = hash_type
def HI(self, *a):
return int(self.H(*a), 16)
def H(self, *a):
a = ':'.join([str(a) for a in a])
return self._hash_type(a.encode('ascii')).hexdigest()
def crypt_rand(self, N, n=1024):
... | 116 | 116 | 389 | 4 | 112 | smialy/ssrp | python/ssrp/psrp.py | Python | Client | Client | 32 | 89 | 32 | 32 | 7a5c7bb4c339bac209c4543caade555103f872ec | bigcode/the-stack | train |
dc833f55382f5aba1f38a488 | train | function | def get_ng(ng_type):
'''
Get N and g for selecte type primary numbers
:param ng_type Selected type of numbers (1024, 2048, 4096, 8192)
:return (N:int, g:int)
'''
N,g = _NGS[ng_type]
return int(N, 16), int(g,16)
| def get_ng(ng_type):
| '''
Get N and g for selecte type primary numbers
:param ng_type Selected type of numbers (1024, 2048, 4096, 8192)
:return (N:int, g:int)
'''
N,g = _NGS[ng_type]
return int(N, 16), int(g,16)
| , B:int)
'''
return self.salt, self.B
def verify_session(self, M):
'''
:param M int
'''
if M == self.M:
return self.HI(self.A, M, self.K)
return None
def get_ng(ng_type):
| 64 | 64 | 82 | 7 | 56 | smialy/ssrp | python/ssrp/psrp.py | Python | get_ng | get_ng | 142 | 150 | 142 | 142 | 6b588b2738e0ba0339cc336e613596bfc526556f | bigcode/the-stack | train |
dd42466b3676011d5bcfd6ab | train | class | class Hash():
def __init__(self, hash_type):
self._hash_type = hash_type
def HI(self, *a):
return int(self.H(*a), 16)
def H(self, *a):
a = ':'.join([str(a) for a in a])
return self._hash_type(a.encode('ascii')).hexdigest()
def crypt_rand(self, N, n=1024):
retur... | class Hash():
| def __init__(self, hash_type):
self._hash_type = hash_type
def HI(self, *a):
return int(self.H(*a), 16)
def H(self, *a):
a = ':'.join([str(a) for a in a])
return self._hash_type(a.encode('ascii')).hexdigest()
def crypt_rand(self, N, n=1024):
return random.Syste... | _1024 = 0
NG_2048 = 1
NG_4096 = 2
NG_8192 = 3
SHA1 = hashlib.sha1
SHA512 = hashlib.sha512
def pr(name, value):
print(name, str(value)[:50])
class Hash():
| 64 | 64 | 105 | 3 | 61 | smialy/ssrp | python/ssrp/psrp.py | Python | Hash | Hash | 15 | 27 | 15 | 15 | 8653c5aadc7e4834326ab36f9bddc9f6c6182784 | bigcode/the-stack | train |
d791a61fa8da208365cbf1f5 | train | function | def pr(name, value):
print(name, str(value)[:50])
| def pr(name, value):
| print(name, str(value)[:50])
| import hashlib
import random
NG_1024 = 0
NG_2048 = 1
NG_4096 = 2
NG_8192 = 3
SHA1 = hashlib.sha1
SHA512 = hashlib.sha512
def pr(name, value):
| 58 | 64 | 16 | 6 | 51 | smialy/ssrp | python/ssrp/psrp.py | Python | pr | pr | 12 | 13 | 12 | 12 | c69073ef254843a6e37a78ee377c8c967298bc6c | bigcode/the-stack | train |
0854fbb152e6c622b6b3c2eb | train | class | class Server(Hash):
'''
:param I str Login
:param salt str
:param v int
:param A int
:param ng_type int
:param hash_type callback Hash method
'''
def __init__(self, I, salt, v, A, ng_type=NG_2048, hash_type=SHA1):
super().__init__(hash_type)
self.I = I
self.s... | class Server(Hash):
| '''
:param I str Login
:param salt str
:param v int
:param A int
:param ng_type int
:param hash_type callback Hash method
'''
def __init__(self, I, salt, v, A, ng_type=NG_2048, hash_type=SHA1):
super().__init__(hash_type)
self.I = I
self.salt = salt
... | = self.HI(self.A, B)
x = self.HI(salt, self.H(self.I, self.p))
S = pow(B - self.k * pow(self.g, x, self.N), self.a + u * x, self.N)
self.K = self.HI(S)
return self.HI(self.A, B, self.K)
'''
Server
'''
class Server(Hash):
| 86 | 86 | 288 | 4 | 82 | smialy/ssrp | python/ssrp/psrp.py | Python | Server | Server | 96 | 140 | 96 | 96 | 3b6d6e0f6fc0f420e6c7ed494c82a212c761bce0 | bigcode/the-stack | train |
939e7ace00ffd352d15c88d1 | train | function | def test_gain_transfer_base():
input_power = Power(value=-50.0)
output_power = Power(value=10.0)
gain_transfer = GainTransfer(input_power=input_power, output_power=output_power)
assert isinstance(gain_transfer, GainTransfer) == True
| def test_gain_transfer_base():
| input_power = Power(value=-50.0)
output_power = Power(value=10.0)
gain_transfer = GainTransfer(input_power=input_power, output_power=output_power)
assert isinstance(gain_transfer, GainTransfer) == True
| 60.0)
assert isinstance(gain_transfer, CamelModel) == True
def test_gain_frequency():
gain_transfer = GainFrequency(value=60.0, f=Frequency(value=15.0e9))
assert isinstance(gain_transfer, GainFrequency) == True
def test_gain_transfer_base():
| 64 | 64 | 58 | 6 | 57 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_gain_transfer_base | test_gain_transfer_base | 40 | 44 | 40 | 40 | c323de226a879d1885ae5cd43b5a0aea56053765 | bigcode/the-stack | train |
ff5507ab3a4fb2f2fdfb1d8c | train | function | def test_power_improper_unit():
with pytest.raises(pydantic.error_wrappers.ValidationError):
power = Power(value=-50.0, unit="dB")
| def test_power_improper_unit():
| with pytest.raises(pydantic.error_wrappers.ValidationError):
power = Power(value=-50.0, unit="dB")
| import (
Gain,
GainFrequency,
GainTransfer,
GainTransferFrequency,
Power,
)
from fastrf.models.signals.frequency import Frequency
def test_power():
power = Power(value=-50.0)
assert isinstance(power, Power) == True
def test_power_improper_unit():
| 64 | 64 | 35 | 7 | 56 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_power_improper_unit | test_power_improper_unit | 20 | 22 | 20 | 20 | a60870128a6fcca5ba27c37cb633dfccd9829f5c | bigcode/the-stack | train |
17537fe5298d359d18733665 | train | function | def test_gain_base():
gain_transfer = Gain(value=60.0)
assert isinstance(gain_transfer, Gain) == True
| def test_gain_base():
| gain_transfer = Gain(value=60.0)
assert isinstance(gain_transfer, Gain) == True
| def test_power():
power = Power(value=-50.0)
assert isinstance(power, Power) == True
def test_power_improper_unit():
with pytest.raises(pydantic.error_wrappers.ValidationError):
power = Power(value=-50.0, unit="dB")
def test_gain_base():
| 64 | 64 | 28 | 5 | 59 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_gain_base | test_gain_base | 25 | 27 | 25 | 25 | f4b157e8d3faae18cdf2790a32d671c2459da625 | bigcode/the-stack | train |
ac8cfdbc0b69bd059e3c83b6 | train | function | def test_gain_transfer_improper_unit():
frequency = Frequency(value=10.0e9)
with pytest.raises(pydantic.error_wrappers.ValidationError):
gain_transfer_with_improper_value = GainTransfer(
f=frequency, value=2.1, unit="dBm"
)
| def test_gain_transfer_improper_unit():
| frequency = Frequency(value=10.0e9)
with pytest.raises(pydantic.error_wrappers.ValidationError):
gain_transfer_with_improper_value = GainTransfer(
f=frequency, value=2.1, unit="dBm"
)
| =-50.0)
output_power = Power(value=10.0)
gain_transfer = GainTransferFrequency(
f=frequency, input_power=input_power, output_power=output_power
)
assert isinstance(gain_transfer, GainTransferFrequency) == True
def test_gain_transfer_improper_unit():
| 64 | 64 | 62 | 8 | 55 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_gain_transfer_improper_unit | test_gain_transfer_improper_unit | 57 | 62 | 57 | 57 | 524f898777940b9309cdd90d94e665295e6761b0 | bigcode/the-stack | train |
7455e727502b43786061d647 | train | function | def test_gain_transfer_frequency():
frequency = Frequency(value=10.0e9)
input_power = Power(value=-50.0)
output_power = Power(value=10.0)
gain_transfer = GainTransferFrequency(
f=frequency, input_power=input_power, output_power=output_power
)
assert isinstance(gain_transfer, GainTransfer... | def test_gain_transfer_frequency():
| frequency = Frequency(value=10.0e9)
input_power = Power(value=-50.0)
output_power = Power(value=10.0)
gain_transfer = GainTransferFrequency(
f=frequency, input_power=input_power, output_power=output_power
)
assert isinstance(gain_transfer, GainTransferFrequency) == True
| def test_gain_transfer_base():
input_power = Power(value=-50.0)
output_power = Power(value=10.0)
gain_transfer = GainTransfer(input_power=input_power, output_power=output_power)
assert isinstance(gain_transfer, GainTransfer) == True
def test_gain_transfer_frequency():
| 64 | 64 | 80 | 6 | 57 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_gain_transfer_frequency | test_gain_transfer_frequency | 47 | 54 | 47 | 47 | 5fbfc8acd239c4957c3850478f09fe5bca582d68 | bigcode/the-stack | train |
b529826a0ed5d1494181e5cb | train | function | def test_power():
power = Power(value=-50.0)
assert isinstance(power, Power) == True
| def test_power():
| power = Power(value=-50.0)
assert isinstance(power, Power) == True
| import pydantic
import pytest
from fastapi_camelcase import CamelModel
from fastrf.models.gain_transfer import (
Gain,
GainFrequency,
GainTransfer,
GainTransferFrequency,
Power,
)
from fastrf.models.signals.frequency import Frequency
def test_power():
| 63 | 64 | 24 | 4 | 58 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_power | test_power | 15 | 17 | 15 | 15 | c04ac8beb21178c4e801983ce474f311d65de94b | bigcode/the-stack | train |
ab503b3c86c7d3c827a732b5 | train | function | def test_gain_frequency():
gain_transfer = GainFrequency(value=60.0, f=Frequency(value=15.0e9))
assert isinstance(gain_transfer, GainFrequency) == True
| def test_gain_frequency():
| gain_transfer = GainFrequency(value=60.0, f=Frequency(value=15.0e9))
assert isinstance(gain_transfer, GainFrequency) == True
| ")
def test_gain_base():
gain_transfer = Gain(value=60.0)
assert isinstance(gain_transfer, Gain) == True
def test_gain_base_class():
gain_transfer = Gain(value=60.0)
assert isinstance(gain_transfer, CamelModel) == True
def test_gain_frequency():
| 64 | 64 | 41 | 5 | 58 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_gain_frequency | test_gain_frequency | 35 | 37 | 35 | 35 | 28779a00ea27a3cafdc125069c5759923e4be3ad | bigcode/the-stack | train |
48ea63010445c9fa63a79531 | train | function | def test_gain_base_class():
gain_transfer = Gain(value=60.0)
assert isinstance(gain_transfer, CamelModel) == True
| def test_gain_base_class():
| gain_transfer = Gain(value=60.0)
assert isinstance(gain_transfer, CamelModel) == True
| _unit():
with pytest.raises(pydantic.error_wrappers.ValidationError):
power = Power(value=-50.0, unit="dB")
def test_gain_base():
gain_transfer = Gain(value=60.0)
assert isinstance(gain_transfer, Gain) == True
def test_gain_base_class():
| 64 | 64 | 30 | 6 | 57 | TheDubliner/fastrf | tests/models/test_gain_transfer.py | Python | test_gain_base_class | test_gain_base_class | 30 | 32 | 30 | 30 | 1484c9438a93dfd3e79cf583e1be2562c09bfac7 | bigcode/the-stack | train |
42c8dbde387452d39327709c | train | class | class FakeRevisionInfoClient(object):
def __init__(self, infos, revisions):
self._infos = infos
self._revisions = revisions
def GetRevisionInfoConfig(self):
return self._infos
def GetRevisions(self, test_key, revision):
return self._revisions.get(test_key.string_id(), {}).get(revision, {})
d... | class FakeRevisionInfoClient(object):
| def __init__(self, infos, revisions):
self._infos = infos
self._revisions = revisions
def GetRevisionInfoConfig(self):
return self._infos
def GetRevisions(self, test_key, revision):
return self._revisions.get(test_key.string_id(), {}).get(revision, {})
def GetRangeRevisionInfo(self, test_key,... | ._repo_commit_list = repo_commit_list or {}
def CommitInfo(self, repo, revision):
logging.debug('Called: repo = %s, revision = %s', repo, revision)
return self._repo_commit_list.get(repo, {}).get(revision, {})
class FakeRevisionInfoClient(object):
| 63 | 64 | 210 | 7 | 56 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeRevisionInfoClient | FakeRevisionInfoClient | 505 | 529 | 505 | 506 | cd27c72f39e63073a24c54720345ae93891a5c31 | bigcode/the-stack | train |
0307a6d45bca9308e42fd55b | train | class | class FakeGitiles(object):
def __init__(self, repo_commit_list=None):
self._repo_commit_list = repo_commit_list or {}
def CommitInfo(self, repo, revision):
logging.debug('Called: repo = %s, revision = %s', repo, revision)
return self._repo_commit_list.get(repo, {}).get(revision, {})
| class FakeGitiles(object):
| def __init__(self, repo_commit_list=None):
self._repo_commit_list = repo_commit_list or {}
def CommitInfo(self, repo, revision):
logging.debug('Called: repo = %s, revision = %s', repo, revision)
return self._repo_commit_list.get(repo, {}).get(revision, {})
| job_id='123456'):
self._response = {'jobId': job_id}
def SetFailure(self):
self._response = {'error': 'some error'}
def NewJob(self, request):
self.new_job_request = request
return self._response
class FakeGitiles(object):
| 64 | 64 | 76 | 6 | 57 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeGitiles | FakeGitiles | 495 | 502 | 495 | 496 | c4742ae2a64843b933743494bd8f4b8e9b8f1780 | bigcode/the-stack | train |
2830ea282508a6501a18956b | train | class | class FakeSheriffConfigClient(object):
def __init__(self):
self.patterns = {}
def Match(self, path, **_):
# The real implementation is quite different from fnmatch. But this is
# enough for testing because we shouldn't test match logic.
for p, s in self.patterns.items():
if re.match(fnmatch.... | class FakeSheriffConfigClient(object):
| def __init__(self):
self.patterns = {}
def Match(self, path, **_):
# The real implementation is quite different from fnmatch. But this is
# enough for testing because we shouldn't test match logic.
for p, s in self.patterns.items():
if re.match(fnmatch.translate(p), path):
return s, N... | })
def GetIssue(self, issue_id, project='chromium'):
return self.issues.get((project, issue_id))
def GetIssueComments(self, issue_id, project='chromium'):
return self.issue_comments.get((project, issue_id), [])
class FakeSheriffConfigClient(object):
| 63 | 64 | 92 | 8 | 55 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeSheriffConfigClient | FakeSheriffConfigClient | 446 | 457 | 446 | 447 | 00573acd1ff788877e4dd0c3611d180d66f14bd9 | bigcode/the-stack | train |
4cf59c0ae5bed0703b540bda | train | function | def _AddRowsFromDict(container_key, row_dict):
"""Adds a set of Rows given a dict of revisions to properties."""
rows = []
for int_id in sorted(row_dict):
rows.append(
graph_data.Row(id=int_id, parent=container_key, **row_dict[int_id]))
ndb.Future.wait_all([r.put_async() for r in rows] +
... | def _AddRowsFromDict(container_key, row_dict):
| """Adds a set of Rows given a dict of revisions to properties."""
rows = []
for int_id in sorted(row_dict):
rows.append(
graph_data.Row(id=int_id, parent=container_key, **row_dict[int_id]))
ndb.Future.wait_all([r.put_async() for r in rows] +
[rows[0].UpdateParentAsync()])
ret... | test_key = utils.TestKey(test_path)
container_key = utils.GetTestContainerKey(test_key)
if isinstance(rows, dict):
return _AddRowsFromDict(container_key, rows)
return _AddRowsFromIterable(container_key, rows)
def _AddRowsFromDict(container_key, row_dict):
| 64 | 64 | 94 | 12 | 52 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | _AddRowsFromDict | _AddRowsFromDict | 292 | 300 | 292 | 292 | 73133439031c26c960173f3cbf1ee4c6399d81e7 | bigcode/the-stack | train |
30dae6a79a75631485a1abcd | train | function | def AddRows(test_path, rows):
"""Adds Rows to a given test.
Args:
test_path: Full test path of TestMetadata entity to add Rows to.
rows: Either a dict mapping ID (revision) to properties, or a set of IDs.
Returns:
The list of Row entities which have been put, in order by ID.
"""
test_key = utils... | def AddRows(test_path, rows):
| """Adds Rows to a given test.
Args:
test_path: Full test path of TestMetadata entity to add Rows to.
rows: Either a dict mapping ID (revision) to properties, or a set of IDs.
Returns:
The list of Row entities which have been put, in order by ID.
"""
test_key = utils.TestKey(test_path)
containe... | tests_dict:
test_path = '%s/%s' % (parent_test_path, test_name)
t = graph_data.TestMetadata(id=test_path)
t.UpdateSheriff()
t.put()
_AddSubtest(test_path, subtests_dict[test_name])
def AddRows(test_path, rows):
| 64 | 64 | 130 | 8 | 56 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | AddRows | AddRows | 275 | 289 | 275 | 275 | 87f713b74a5038a3f11b23bf1409ea9b8160b9f2 | bigcode/the-stack | train |
8b31607b154bcad09ec293e3 | train | function | def SetSheriffDomains(domains):
"""Sets the domain that users who can access internal data belong to."""
stored_object.Set(utils.SHERIFF_DOMAINS_KEY, domains)
| def SetSheriffDomains(domains):
| """Sets the domain that users who can access internal data belong to."""
stored_object.Set(utils.SHERIFF_DOMAINS_KEY, domains)
| the domain that users who can access internal data belong to."""
utils.SetCachedIsInternalUser(user, is_internal_user)
def SetIsAdministrator(user, is_administrator):
"""Marks the user an an administrator."""
utils.SetCachedIsAdministrator(user, is_administrator)
def SetSheriffDomains(domains):
| 64 | 64 | 38 | 8 | 56 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | SetSheriffDomains | SetSheriffDomains | 323 | 325 | 323 | 323 | 2ad6e663b4647ec43c826bc54074652f69097466 | bigcode/the-stack | train |
252a80563059e188eb7ea859 | train | function | def _AddSubtest(parent_test_path, subtests_dict):
"""Helper function to recursively add sub-TestMetadatas to a TestMetadata.
Args:
parent_test_path: A path to the parent test.
subtests_dict: A dict of test names to dictionaries of subtests.
"""
for test_name in subtests_dict:
test_path = '%s/%s' % ... | def _AddSubtest(parent_test_path, subtests_dict):
| """Helper function to recursively add sub-TestMetadatas to a TestMetadata.
Args:
parent_test_path: A path to the parent test.
subtests_dict: A dict of test names to dictionaries of subtests.
"""
for test_name in subtests_dict:
test_path = '%s/%s' % (parent_test_path, test_name)
t = graph_data.T... | s/%s/%s' % (master_name, bot_name, test_name)
t = graph_data.TestMetadata(id=test_path)
t.UpdateSheriff()
t.put()
_AddSubtest(test_path, tests_dict[test_name])
def _AddSubtest(parent_test_path, subtests_dict):
| 64 | 64 | 125 | 13 | 51 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | _AddSubtest | _AddSubtest | 260 | 272 | 260 | 260 | c57937d6ed23ac269a8b7433d8c684d31fe33596 | bigcode/the-stack | train |
78548c3e2493859afc1f6f66 | train | class | class FakeCASClient(object):
_trees = {}
_files = {}
def __init__(self):
pass
@staticmethod
def _NormalizeDigest(digest):
return {
'hash': digest['hash'],
'sizeBytes': digest.get('sizeBytes') or str(digest.get('size_bytes')),
}
def GetTree(self, cas_ref, page_size=None, page_... | class FakeCASClient(object):
| _trees = {}
_files = {}
def __init__(self):
pass
@staticmethod
def _NormalizeDigest(digest):
return {
'hash': digest['hash'],
'sizeBytes': digest.get('sizeBytes') or str(digest.get('size_bytes')),
}
def GetTree(self, cas_ref, page_size=None, page_token=None):
if page_size ... | if k not in revision_start or k not in revision_end:
continue
url = info.get('url', '')
info['url'] = url.replace('{{R1}}', revision_start[k]).replace(
'{{R2}}', revision_end[k])
infos.append(info)
return infos
class FakeCASClient(object):
| 70 | 70 | 236 | 6 | 63 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeCASClient | FakeCASClient | 532 | 563 | 532 | 533 | 4c895e4f1b6c28b258a23ec19869c160e5b8adb7 | bigcode/the-stack | train |
0d70f34a322ed193cb881a08 | train | class | class FakePinpoint(object):
def __init__(self):
self.new_job_request = None
self._response = None
self.SetSuccess()
def SetSuccess(self, job_id='123456'):
self._response = {'jobId': job_id}
def SetFailure(self):
self._response = {'error': 'some error'}
def NewJob(self, request):
self... | class FakePinpoint(object):
| def __init__(self):
self.new_job_request = None
self._response = None
self.SetSuccess()
def SetSuccess(self, job_id='123456'):
self._response = {'jobId': job_id}
def SetFailure(self):
self._response = {'error': 'some error'}
def NewJob(self, request):
self.new_job_request = request
... | {'git_sha': git_sha}
def SetFailure(self):
self._response = {'error': {'message': 'some error'}}
def GetNumbering(self, *args, **kwargs):
# pylint: disable=unused-argument
return self._response
class FakePinpoint(object):
| 64 | 64 | 97 | 6 | 57 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakePinpoint | FakePinpoint | 477 | 492 | 477 | 478 | 1c85d1bafdc307f44ef5d18030197f7732cee750 | bigcode/the-stack | train |
675401b35d38776ba688c7f7 | train | function | def SetIpAllowlist(ip_addresses):
"""Sets the IP address allowlist."""
stored_object.Set(utils.IP_ALLOWLIST_KEY, ip_addresses)
| def SetIpAllowlist(ip_addresses):
| """Sets the IP address allowlist."""
stored_object.Set(utils.IP_ALLOWLIST_KEY, ip_addresses)
| the user an an administrator."""
utils.SetCachedIsAdministrator(user, is_administrator)
def SetSheriffDomains(domains):
"""Sets the domain that users who can access internal data belong to."""
stored_object.Set(utils.SHERIFF_DOMAINS_KEY, domains)
def SetIpAllowlist(ip_addresses):
| 64 | 64 | 30 | 8 | 56 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | SetIpAllowlist | SetIpAllowlist | 328 | 330 | 328 | 328 | e309c8e4be7952a5c4c07ea51d402f93cd9cac3c | bigcode/the-stack | train |
5b429cf10b319b782c26c6a4 | train | function | def SetIsInternalUser(user, is_internal_user):
"""Sets the domain that users who can access internal data belong to."""
utils.SetCachedIsInternalUser(user, is_internal_user)
| def SetIsInternalUser(user, is_internal_user):
| """Sets the domain that users who can access internal data belong to."""
utils.SetCachedIsInternalUser(user, is_internal_user)
| (row_ids):
rows.append(graph_data.Row(id=int_id, parent=container_key, value=int_id))
ndb.Future.wait_all([r.put_async() for r in rows] +
[rows[0].UpdateParentAsync()])
return rows
def SetIsInternalUser(user, is_internal_user):
| 64 | 64 | 39 | 11 | 52 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | SetIsInternalUser | SetIsInternalUser | 313 | 315 | 313 | 313 | 5d360c940655dee6d0a3bad5f0dd2110f6613557 | bigcode/the-stack | train |
40f2251394f40b05c430515a | train | function | def AddTests(masters, bots, tests_dict):
"""Adds data to the mock datastore.
Args:
masters: List of buildbot master names.
bots: List of bot names.
tests_dict: Nested dictionary of tests to add; keys are test names
and values are nested dictionaries of tests to add.
"""
for master_name in m... | def AddTests(masters, bots, tests_dict):
| """Adds data to the mock datastore.
Args:
masters: List of buildbot master names.
bots: List of bot names.
tests_dict: Nested dictionary of tests to add; keys are test names
and values are nested dictionaries of tests to add.
"""
for master_name in masters:
master_key = graph_data.Maste... | user is internal; it just checks for cached values and returns False
if nothing is found.
"""
def IsAdministrator():
return bool(utils.GetCachedIsAdministrator(utils.GetEmail()))
self.PatchObject(utils, 'IsAdministrator', IsAdministrator)
def AddTests(masters, bots, tests_dict):
| 64 | 64 | 178 | 11 | 53 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | AddTests | AddTests | 239 | 257 | 239 | 239 | bae627f8ba01c2f53489e19bde4b01d94432bcec | bigcode/the-stack | train |
5bc124430cf4ba5ae2905d96 | train | class | class FakeCrrev(object):
def __init__(self):
self._response = None
self.SetSuccess()
def SetSuccess(self, git_sha='abcd'):
self._response = {'git_sha': git_sha}
def SetFailure(self):
self._response = {'error': {'message': 'some error'}}
def GetNumbering(self, *args, **kwargs):
# pylint: ... | class FakeCrrev(object):
| def __init__(self):
self._response = None
self.SetSuccess()
def SetSuccess(self, git_sha='abcd'):
self._response = {'git_sha': git_sha}
def SetFailure(self):
self._response = {'error': {'message': 'some error'}}
def GetNumbering(self, *args, **kwargs):
# pylint: disable=unused-argument
... | real implementation is quite different from fnmatch. But this is
# enough for testing because we shouldn't test match logic.
for p, s in self.patterns.items():
if re.match(fnmatch.translate(p), path):
return s, None
return [], None
class FakeCrrev(object):
| 64 | 64 | 99 | 6 | 57 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeCrrev | FakeCrrev | 460 | 474 | 460 | 461 | bf50c73f2513d6d7fa034d5f2359a606aaf13b79 | bigcode/the-stack | train |
600744a44ac2dbcad2f561af | train | function | def SetIsAdministrator(user, is_administrator):
"""Marks the user an an administrator."""
utils.SetCachedIsAdministrator(user, is_administrator)
| def SetIsAdministrator(user, is_administrator):
| """Marks the user an an administrator."""
utils.SetCachedIsAdministrator(user, is_administrator)
| +
[rows[0].UpdateParentAsync()])
return rows
def SetIsInternalUser(user, is_internal_user):
"""Sets the domain that users who can access internal data belong to."""
utils.SetCachedIsInternalUser(user, is_internal_user)
def SetIsAdministrator(user, is_administrator):
| 64 | 64 | 31 | 10 | 54 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | SetIsAdministrator | SetIsAdministrator | 318 | 320 | 318 | 318 | 371425216b894c4e1bda6c42a2c4dc401755db22 | bigcode/the-stack | train |
664d6df6bcd190b26cd830aa | train | class | class FakeResponseObject(object):
"""Fake Response Object which can be returned by urlfetch mocks."""
def __init__(self, status_code, content):
self.status_code = status_code
self.content = content
| class FakeResponseObject(object):
| """Fake Response Object which can be returned by urlfetch mocks."""
def __init__(self, status_code, content):
self.status_code = status_code
self.content = content
| email='external@example.com', _auth_domain='example.com')
class FakeRequestObject(object):
"""Fake Request object which can be used by datastore_hooks mocks."""
def __init__(self, remote_addr=None):
self.registry = {}
self.remote_addr = remote_addr
class FakeResponseObject(object):
| 64 | 64 | 46 | 6 | 57 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeResponseObject | FakeResponseObject | 53 | 58 | 53 | 53 | 52d4f09f48e4fb3b75eb6ecfaa23708382fa57cf | bigcode/the-stack | train |
deb3229d3eb46d04fb64af6b | train | class | class TestCase(unittest.TestCase):
"""Common base class for test cases."""
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.addCleanup(self.testbed.deactivate)
self.testbed.init_datastore_v3_stub()
self.testbed.init_mail_stub()
self.testbed.init_memcache_stub(... | class TestCase(unittest.TestCase):
| """Common base class for test cases."""
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.addCleanup(self.testbed.deactivate)
self.testbed.init_datastore_v3_stub()
self.testbed.init_mail_stub()
self.testbed.init_memcache_stub()
self.testbed.init_taskqueue_s... |
import webtest
from google.appengine.api import oauth
from google.appengine.api import users
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from dashboard.common import datastore_hooks
from dashboard.common import stored_object
from dashboard.c... | 256 | 256 | 1,537 | 7 | 248 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | TestCase | TestCase | 61 | 236 | 61 | 61 | a7025cdfad2e5a8d98e8e784253b658d11aca602 | bigcode/the-stack | train |
c9eac67e1efac326574c7439 | train | class | class FakeIssueTrackerService(object):
"""A fake version of IssueTrackerService that saves call values."""
def __init__(self):
self.bug_id = 12345
self._bug_id_counter = self.bug_id
self.new_bug_args = None
self.new_bug_kwargs = None
self.add_comment_args = None
self.add_comment_kwargs = No... | class FakeIssueTrackerService(object):
| """A fake version of IssueTrackerService that saves call values."""
def __init__(self):
self.bug_id = 12345
self._bug_id_counter = self.bug_id
self.new_bug_args = None
self.new_bug_kwargs = None
self.add_comment_args = None
self.add_comment_kwargs = None
self.calls = []
self._base_i... | Async()])
return rows
def _AddRowsFromIterable(container_key, row_ids):
"""Adds a set of Rows given an iterable of ID numbers."""
rows = []
for int_id in sorted(row_ids):
rows.append(graph_data.Row(id=int_id, parent=container_key, value=int_id))
ndb.Future.wait_all([r.put_async() for r in rows] +
... | 256 | 256 | 937 | 7 | 249 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeIssueTrackerService | FakeIssueTrackerService | 334 | 443 | 334 | 334 | 4fddafbb1aaf53c3a1478c6f193746168d173659 | bigcode/the-stack | train |
51270bbf21afcaf6295e7975 | train | class | class FakeRequestObject(object):
"""Fake Request object which can be used by datastore_hooks mocks."""
def __init__(self, remote_addr=None):
self.registry = {}
self.remote_addr = remote_addr
| class FakeRequestObject(object):
| """Fake Request object which can be used by datastore_hooks mocks."""
def __init__(self, remote_addr=None):
self.registry = {}
self.remote_addr = remote_addr
| ='fake@foo.gserviceaccount.com', _auth_domain='google.com')
INTERNAL_USER = users.User(
email='internal@example.com', _auth_domain='google.com')
EXTERNAL_USER = users.User(
email='external@example.com', _auth_domain='example.com')
class FakeRequestObject(object):
| 64 | 64 | 44 | 6 | 58 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | FakeRequestObject | FakeRequestObject | 45 | 50 | 45 | 45 | 40ffeb35a5912511c8bfdb15715b1262414315eb | bigcode/the-stack | train |
d4f0eb4da5c67827eae3e532 | train | function | def _AddRowsFromIterable(container_key, row_ids):
"""Adds a set of Rows given an iterable of ID numbers."""
rows = []
for int_id in sorted(row_ids):
rows.append(graph_data.Row(id=int_id, parent=container_key, value=int_id))
ndb.Future.wait_all([r.put_async() for r in rows] +
[rows[0].U... | def _AddRowsFromIterable(container_key, row_ids):
| """Adds a set of Rows given an iterable of ID numbers."""
rows = []
for int_id in sorted(row_ids):
rows.append(graph_data.Row(id=int_id, parent=container_key, value=int_id))
ndb.Future.wait_all([r.put_async() for r in rows] +
[rows[0].UpdateParentAsync()])
return rows
| .append(
graph_data.Row(id=int_id, parent=container_key, **row_dict[int_id]))
ndb.Future.wait_all([r.put_async() for r in rows] +
[rows[0].UpdateParentAsync()])
return rows
def _AddRowsFromIterable(container_key, row_ids):
| 64 | 64 | 89 | 12 | 51 | QPC-database/catapult | dashboard/dashboard/common/testing_common.py | Python | _AddRowsFromIterable | _AddRowsFromIterable | 303 | 310 | 303 | 303 | b4e2b3eb199493f196d01964d1bd738b319a1a50 | bigcode/the-stack | train |
0575c5aea9040e9054158172 | train | class | class TestEventGridFunctions(testutils.WebHostTestCase):
@classmethod
def get_script_dir(cls):
return testutils.E2E_TESTS_FOLDER / 'eventgrid_functions'
def eventgrid_webhook_request(self, meth, funcname, *args, **kwargs):
request_method = getattr(requests, meth.lower())
url = f'{s... | class TestEventGridFunctions(testutils.WebHostTestCase):
@classmethod
| def get_script_dir(cls):
return testutils.E2E_TESTS_FOLDER / 'eventgrid_functions'
def eventgrid_webhook_request(self, meth, funcname, *args, **kwargs):
request_method = getattr(requests, meth.lower())
url = f'{self.webhost._addr}/runtime/webhooks/eventgrid'
params = dict(kwargs... | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import time
import unittest
import uuid
import requests
from azure_functions_worker import testutils
class TestEventGridFunctions(testutils.WebHostTestCase):
@classmethod
| 55 | 256 | 1,345 | 16 | 38 | gohar94/azure-functions-python-worker | tests/endtoend/test_eventgrid_functions.py | Python | TestEventGridFunctions | TestEventGridFunctions | 12 | 158 | 12 | 14 | 27496a83dede89cbe4e05cb8d9c85f8f1848f1b5 | bigcode/the-stack | train |
523359f90890e4d96ad80269 | train | class | class LMCPHandler(ss.StreamRequestHandler):
def handle(self):
self.factory = LMCPFactory.LMCPFactory()
print("Client address: %s" % (self.client_address,))
while True:
try:
data = bytearray(self.request.recv(LMCPFactory.HEADER_SIZE))
if(len(data) >... | class LMCPHandler(ss.StreamRequestHandler):
| def handle(self):
self.factory = LMCPFactory.LMCPFactory()
print("Client address: %s" % (self.client_address,))
while True:
try:
data = bytearray(self.request.recv(LMCPFactory.HEADER_SIZE))
if(len(data) >= LMCPFactory.HEADER_SIZE):
... | claimed in the United States under
## Title 17, U.S. Code. All Other Rights Reserved.
## ===============================================================================
## This file was auto-created by LmcpGen. Modifications will be overwritten.
myHost = ''
myPort = 11041
class LMCPHandler(ss.StreamRequestHandler):... | 65 | 65 | 217 | 9 | 55 | manthonyaiello/LmcpGen | src/templates/py/LMCPServer.py | Python | LMCPHandler | LMCPHandler | 23 | 45 | 23 | 23 | 713e7c7b6636cf2c46657c4c4c9984052fcac2d4 | bigcode/the-stack | train |
85f94d4b847a15b59d0980ac | train | function | def main():
paramsurvey.init(backend='multiprocessing') # or 'ray', if you installed it
stations = dict((x, {}) for x in 'ABCDEFGHIJ')
picked_stations = []
'''
Given a list of potential radio telescope stations, named A-J, which
combine together in very non-linear ways when used together,
... | def main():
| paramsurvey.init(backend='multiprocessing') # or 'ray', if you installed it
stations = dict((x, {}) for x in 'ABCDEFGHIJ')
picked_stations = []
'''
Given a list of potential radio telescope stations, named A-J, which
combine together in very non-linear ways when used together,
iteratively... | ations = pset['existing_stations']
new_station = pset['station']
# given existing telescopes existing_stations and a new station,
# compute a metric of how good this combination is:
metric = random.randrange(0, 1000)
return {'metric': metric}
def main():
| 66 | 66 | 221 | 3 | 63 | wumpus/paramsurvey | scripts/paramsurvey-greedy-example.py | Python | main | main | 22 | 44 | 22 | 22 | 0fb1b1606a2ef75eccb128c5956cd89b014acee1 | bigcode/the-stack | train |
1a0abf47b39930b02b9ee6bd | train | function | def metric(pset, system_kwargs, user_kwargs):
existing_stations = pset['existing_stations']
new_station = pset['station']
# given existing telescopes existing_stations and a new station,
# compute a metric of how good this combination is:
metric = random.randrange(0, 1000)
return {'metric': m... | def metric(pset, system_kwargs, user_kwargs):
| existing_stations = pset['existing_stations']
new_station = pset['station']
# given existing telescopes existing_stations and a new station,
# compute a metric of how good this combination is:
metric = random.randrange(0, 1000)
return {'metric': metric}
| #!/usr/bin/env python
import random
import paramsurvey
# metric() must be declared before the paramsurvey.init() call (multiprocessing)
# metric() cannot be a nested procedure (pickle)
def metric(pset, system_kwargs, user_kwargs):
| 52 | 64 | 77 | 11 | 41 | wumpus/paramsurvey | scripts/paramsurvey-greedy-example.py | Python | metric | metric | 10 | 19 | 10 | 11 | 0eeea80edf60e091bb8c2ad61c7e1df76aa35dfd | bigcode/the-stack | train |
2175e2cf4d7a24cd2b28b3a0 | train | function | def get_page(category, code):
return Page.objects.published().filter(category__code=category, code=code).first()
| def get_page(category, code):
| return Page.objects.published().filter(category__code=category, code=code).first()
| from typing import Dict, List
from page.enums import PageStatus
from page.models import Category, Page
def get_page(category, code):
| 29 | 64 | 27 | 7 | 21 | kthaisse/website | page/utils.py | Python | get_page | get_page | 7 | 8 | 7 | 7 | efb9cae12f17cbd7154c128e47e1b6079d633e79 | bigcode/the-stack | train |
6d1eef176e7ff3cf21aed047 | train | function | def get_menu_pages() -> Dict[Category, List[Page]]:
pages = Page.objects.filter(in_menu=True, status=PageStatus.PUBLISHED).order_by(
"category", "title"
)
categories = {c: [] for c in Category.objects.filter(page__in=pages)}
for page in pages:
categories[page.category].append(page)
r... | def get_menu_pages() -> Dict[Category, List[Page]]:
| pages = Page.objects.filter(in_menu=True, status=PageStatus.PUBLISHED).order_by(
"category", "title"
)
categories = {c: [] for c in Category.objects.filter(page__in=pages)}
for page in pages:
categories[page.category].append(page)
return categories
| from typing import Dict, List
from page.enums import PageStatus
from page.models import Category, Page
def get_page(category, code):
return Page.objects.published().filter(category__code=category, code=code).first()
def get_menu_pages() -> Dict[Category, List[Page]]:
| 63 | 64 | 81 | 14 | 49 | kthaisse/website | page/utils.py | Python | get_menu_pages | get_menu_pages | 11 | 18 | 11 | 11 | f84ffe6ea0337f9f029b32e7baf7a1d4f19233e5 | bigcode/the-stack | train |
d317adf1353f36186e5b88fa | train | class | @method_decorator(login_required, name="dispatch")
@method_decorator(staff_required, name="dispatch")
@method_decorator(permission_required("cms.view_organization"), name="dispatch")
class OrganizationListView(TemplateView, OrganizationContextMixin):
"""
View for listing organizations
"""
#: The templa... | @method_decorator(login_required, name="dispatch")
@method_decorator(staff_required, name="dispatch")
@method_decorator(permission_required("cms.view_organization"), name="dispatch")
class OrganizationListView(TemplateView, OrganizationContextMixin):
| """
View for listing organizations
"""
#: The template to render (see :class:`~django.views.generic.base.TemplateResponseMixin`)
template_name = "organizations/organization_list.html"
#: The context dict passed to the template (see :class:`~django.views.generic.base.ContextMixin`)
base_cont... | backend.settings import PER_PAGE
from ...decorators import staff_required, permission_required
from ...models import Organization
from .organization_context_mixin import OrganizationContextMixin
logger = logging.getLogger(__name__)
@method_decorator(login_required, name="dispatch")
@method_decorator(staff_required, n... | 93 | 93 | 312 | 51 | 42 | Integreat/integreat-cms | src/cms/views/organizations/organization_list_view.py | Python | OrganizationListView | OrganizationListView | 17 | 57 | 17 | 20 | 821c5be5a34ed912b0273ab6bd8d212a849d6d5e | bigcode/the-stack | train |
2c0991eab1161f9b5f6f65db | train | function | def __check_memory_only__(path):
if path == False:
raise ValueError("This object is only used in the local memory and is not supposed to be saved or loaded.")
| def __check_memory_only__(path):
| if path == False:
raise ValueError("This object is only used in the local memory and is not supposed to be saved or loaded.")
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# imports.
from dev0s.classes.config import *
import string
import time
# check memory only path.
def __check_memory_only__(path):
| 46 | 64 | 38 | 8 | 38 | vandenberghinc/dev0s | dev0s/classes/utils/__init__.py | Python | __check_memory_only__ | __check_memory_only__ | 10 | 12 | 10 | 10 | f8d9c8c169dca13e6e802eff8b9f312d7b9ad6f6 | bigcode/the-stack | train |
8864ec2fa78bbcc80eabc8ac | train | function | def __execute__(
# the command in array.
command=[],
# wait till the command is pinished.
wait=False,
# the commands timeout, [timeout] overwrites parameter [wait].
timeout=None,
# the commands output return format: string / array.
return_format="string",
# the subprocess.Popen.shell argument.
shell=False,... | def __execute__(
# the command in array.
command=[],
# wait till the command is pinished.
wait=False,
# the commands timeout, [timeout] overwrites parameter [wait].
timeout=None,
# the commands output return format: string / array.
return_format="string",
# the subprocess.Popen.shell argument.
shell=False,... | def __convert__(byte_array, return_format=return_format):
if return_format == "string":
lines = ""
for line in byte_array:
lines += line.decode()
return lines
elif return_format == "array":
lines = []
for line in byte_array:
lines.append(line.decode().replace("\n","").replace("\\n",""))
r... |
raise ValueError("This object is only used in the local memory and is not supposed to be saved or loaded.")
#
# execute a shell command.
def __execute__(
# the command in array.
command=[],
# wait till the command is pinished.
wait=False,
# the commands timeout, [timeout] overwrites parameter [wait].
timeo... | 124 | 124 | 415 | 91 | 33 | vandenberghinc/dev0s | dev0s/classes/utils/__init__.py | Python | __execute__ | __execute__ | 16 | 76 | 16 | 29 | c51fdb3082e1bea450708c96c8b0c5716bff23ba | bigcode/the-stack | train |
533deb698f1a35b2f36a8540 | train | class | class Generate(object):
def __init__(self):
a=1
def pincode(self, length=6, charset=string.digits):
return ''.join(random.choice(charset) for x in range(length))
#
def shell_string(self, length=6, numerical_length=False, special_length=False):
charset = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',... | class Generate(object):
| def __init__(self):
a=1
def pincode(self, length=6, charset=string.digits):
return ''.join(random.choice(charset) for x in range(length))
#
def shell_string(self, length=6, numerical_length=False, special_length=False):
charset = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'... | (f"chmod +x {path}")
output = __execute__(
command=[executable, f"{path}"],
wait=wait,
timeout=timeout,
return_format=return_format,
shell=shell,
input=input,)
os.system(f"rm -fr {path}")
return output
# the generate object.
class Generate(object):
| 75 | 75 | 252 | 4 | 71 | vandenberghinc/dev0s | dev0s/classes/utils/__init__.py | Python | Generate | Generate | 110 | 127 | 110 | 110 | b64dd68f8864e610401ef162e7e7de81c9ab3b91 | bigcode/the-stack | train |
3798af918cab12d4b33805ab | train | function | def __execute_script__(
# the script in string.
script="",
# wait till the command is pinished.
wait=False,
# the commands timeout, [timeout] overwrites parameter [wait].
timeout=None,
# the commands output return format: string / array.
return_format="string",
# the subprocess.Popen.shell argument.
shell=... | def __execute_script__(
# the script in string.
script="",
# wait till the command is pinished.
wait=False,
# the commands timeout, [timeout] overwrites parameter [wait].
timeout=None,
# the commands output return format: string / array.
return_format="string",
# the subprocess.Popen.shell argument.
shell=... | path = f"/tmp/shell_script.{generate.pincode(length=32)}.sh"
with open(path, "wb") as file:
file.write(script.encode())
os.system(f"chmod +x {path}")
output = __execute__(
command=[executable, f"{path}"],
wait=wait,
timeout=timeout,
return_format=return_format,
shell=shell,
input=input,)
os.system(... | def __execute_script__(
# the script in string.
script="",
# wait till the command is pinished.
wait=False,
# the commands timeout, [timeout] overwrites parameter [wait].
timeout=None,
# the commands output return format: string / array.
return_format="string",
# the subprocess.Popen.shell argument.
shell=... | 105 | 64 | 208 | 105 | 0 | vandenberghinc/dev0s | dev0s/classes/utils/__init__.py | Python | __execute_script__ | __execute_script__ | 79 | 107 | 79 | 94 | 583ea78795d3e63ea327e9d8d741078cd368c1d0 | bigcode/the-stack | train |
26ff57af65e74a94b9211e8d | train | function | def createNewBlock(address, currentLastBlockHash, currentHeight, coinbasevalue, bits, tx, mintime):
#
# First we build a block header
#
blockHeader = block.blockHeader(creationTime = mintime,
prevBlockId = currentLastBlockHash,
nonc... | def createNewBlock(address, currentLastBlockHash, currentHeight, coinbasevalue, bits, tx, mintime):
#
# First we build a block header
#
| blockHeader = block.blockHeader(creationTime = mintime,
prevBlockId = currentLastBlockHash,
nonce = 1,
bits = bits)
#
# Next we do the block
#
_block = block.block(blockHeader = blockHeader)
... | the coinbase transaction
# - mintime - the minimum time to use for the block as provided by getblocktemplate
def createNewBlock(address, currentLastBlockHash, currentHeight, coinbasevalue, bits, tx, mintime):
#
# First we build a block header
#
| 64 | 64 | 174 | 38 | 25 | guolinxin/bitcoin | btc/mining.py | Python | createNewBlock | createNewBlock | 168 | 189 | 168 | 171 | 1cf5b642311feeafb911557d4ff9c8b7739659df | bigcode/the-stack | train |
291c75eeed63b3bf188e89b1 | train | function | def createCoinbaseTxn(address, currentHeight, coinbasevalue, extraNonce = 1):
coinbase = txn.txn()
publicKeyHash = keys.ecAddressToPKH(address)
publicKeyHash = binascii.hexlify(publicKeyHash).decode('ascii')
#
# Create locking script
#
lockingScript = script.scriptPubKey(scriptType = script.... | def createCoinbaseTxn(address, currentHeight, coinbasevalue, extraNonce = 1):
| coinbase = txn.txn()
publicKeyHash = keys.ecAddressToPKH(address)
publicKeyHash = binascii.hexlify(publicKeyHash).decode('ascii')
#
# Create locking script
#
lockingScript = script.scriptPubKey(scriptType = script.SCRIPTTYPE_P2PKH,
pubKeyHash = public... | ().getMerkleRoot(), 32):
return False
return True
#
# Create a coinbase transaction
# Parameter:
# - address - the address to be used for the transaction output
# - coinbase value in Satoshi, including feeds
# - the current height of the chain as integer
# - an extra nonce as integer
#
def cre... | 94 | 94 | 315 | 20 | 74 | guolinxin/bitcoin | btc/mining.py | Python | createCoinbaseTxn | createCoinbaseTxn | 120 | 154 | 120 | 120 | 31bf4f766e623003c4bff234803a3ffdaeab1c34 | bigcode/the-stack | train |
58c177b92b62da308747dd85 | train | function | def checkPoW(block, bits):
#
# First determine the target in the block and verify that
# the hash does not exceed it
#
h = block.getBlockHeader().getBlockHash(byteorder="big")
h = int(h, 16)
#
# Do the same for the target
#
_bits = block.getBlockHeader().getBits()
coefficient... | def checkPoW(block, bits):
#
# First determine the target in the block and verify that
# the hash does not exceed it
#
| h = block.getBlockHeader().getBlockHash(byteorder="big")
h = int(h, 16)
#
# Do the same for the target
#
_bits = block.getBlockHeader().getBits()
coefficient = (float)(_bits & 0xFFFFFF)
size = _bits >> 24
target = int(coefficient * 2**(8*(size - 3)))
if h > target:
return... | time
#
# Check whether a given block has a valid PoW
# Arguments:
# - the block
# - the global target
#
def checkPoW(block, bits):
#
# First determine the target in the block and verify that
# the hash does not exceed it
#
| 64 | 64 | 173 | 34 | 30 | guolinxin/bitcoin | btc/mining.py | Python | checkPoW | checkPoW | 50 | 71 | 50 | 54 | 453010cc9f024932d0465b3ddd8f7c211124d6db | bigcode/the-stack | train |
4e57f874de93d4663c5d9367 | train | function | def checkBlock(block, currentLastBlock):
#
# First check that the previous block ID is equal to the current
# last block
#
if block.getBlockHeader().getPrevBlockId() != currentLastBlock:
return False
#
# Next check that the first transaction is a coinbase transaction
#
tx = b... | def checkBlock(block, currentLastBlock):
#
# First check that the previous block ID is equal to the current
# last block
#
| if block.getBlockHeader().getPrevBlockId() != currentLastBlock:
return False
#
# Next check that the first transaction is a coinbase transaction
#
tx = block.getTx()
if 0 == len(tx):
return False
if tx[0].isCoinbase() == False:
return False
#
# Check that no o... | as returned by the RPC call
# getblockchaininfo, i.e. in big endian)
# This will NOT check the PoW!
#
def checkBlock(block, currentLastBlock):
#
# First check that the previous block ID is equal to the current
# last block
#
| 64 | 64 | 205 | 33 | 31 | guolinxin/bitcoin | btc/mining.py | Python | checkBlock | checkBlock | 81 | 110 | 81 | 85 | bf1973a90d8af1d954cd4291332e922fd189adf5 | bigcode/the-stack | train |
b56b661471c795a3066d4efc | train | function | def r2(labels, pred, assignment, mean_var_tot, num_vis):
del num_vis # unused
mean, var, _ = mean_var_tot
# labels, pred: (B, L, K, n)
ss_res = tf.reduce_sum(tf.square(labels - pred) * assignment, axis=2)
ss_tot = var[tf.newaxis, tf.newaxis, :] # (1, 1, n)
return tf.reduce_mean(1.0 - ss_res / ss_tot)
| def r2(labels, pred, assignment, mean_var_tot, num_vis):
| del num_vis # unused
mean, var, _ = mean_var_tot
# labels, pred: (B, L, K, n)
ss_res = tf.reduce_sum(tf.square(labels - pred) * assignment, axis=2)
ss_tot = var[tf.newaxis, tf.newaxis, :] # (1, 1, n)
return tf.reduce_mean(1.0 - ss_res / ss_tot)
| tf.argmax(labels, axis=-1, output_type=tf.int32)
correct = tf.cast(tf.equal(labels, pred), tf.float32)
return tf.reduce_sum(correct * assignment[Ellipsis, 0]) / num_vis
def r2(labels, pred, assignment, mean_var_tot, num_vis):
| 64 | 64 | 111 | 16 | 47 | cynthiamao98/deepmind-research | iodine/modules/factor_eval.py | Python | r2 | r2 | 200 | 206 | 200 | 200 | c50565b116511735f027513a411c22bc21283764 | bigcode/the-stack | train |
bf4b52e3befff15b319cd1de | train | function | def accuracy(labels, logits, assignment, mean_var_tot, num_vis):
del mean_var_tot # unused
pred = tf.argmax(logits, axis=-1, output_type=tf.int32)
labels = tf.argmax(labels, axis=-1, output_type=tf.int32)
correct = tf.cast(tf.equal(labels, pred), tf.float32)
return tf.reduce_sum(correct * assignment[Ellipsis... | def accuracy(labels, logits, assignment, mean_var_tot, num_vis):
| del mean_var_tot # unused
pred = tf.argmax(logits, axis=-1, output_type=tf.int32)
labels = tf.argmax(labels, axis=-1, output_type=tf.int32)
correct = tf.cast(tf.equal(labels, pred), tf.float32)
return tf.reduce_sum(correct * assignment[Ellipsis, 0]) / num_vis
| :
raise KeyError(factor.type)
def sse(true, pred):
# run our own sum squared error because we want to reduce sum over last dim
return tf.reduce_sum(tf.square(true - pred), axis=-1)
def accuracy(labels, logits, assignment, mean_var_tot, num_vis):
| 64 | 64 | 93 | 15 | 49 | cynthiamao98/deepmind-research | iodine/modules/factor_eval.py | Python | accuracy | accuracy | 192 | 197 | 192 | 192 | 86d85dad7ea8e104113b62dd9cebe76b3995fbb0 | bigcode/the-stack | train |
6a12576411270abaa04f3cb3 | train | class | class FactorRegressor(snt.AbstractModule):
"""Assess representations by learning a linear mapping to latents."""
def __init__(self, mapping=None, name="repres_content"):
super().__init__(name=name)
if mapping is None:
self._mapping = [
Factor("color", 3, "scalar"),
Factor("shape",... | class FactorRegressor(snt.AbstractModule):
| """Assess representations by learning a linear mapping to latents."""
def __init__(self, mapping=None, name="repres_content"):
super().__init__(name=name)
if mapping is None:
self._mapping = [
Factor("color", 3, "scalar"),
Factor("shape", 4, "categorical"),
Factor("scale... | # Lint as: python3
# Copyright 2019 Deepmind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | 209 | 256 | 1,418 | 9 | 200 | cynthiamao98/deepmind-research | iodine/modules/factor_eval.py | Python | FactorRegressor | FactorRegressor | 28 | 184 | 28 | 28 | 85264bb28e5f3d9592ca5cfb295daa42b839f93d | bigcode/the-stack | train |
39d4544dac07bc1f6df262a1 | train | function | def sse(true, pred):
# run our own sum squared error because we want to reduce sum over last dim
return tf.reduce_sum(tf.square(true - pred), axis=-1)
| def sse(true, pred):
# run our own sum squared error because we want to reduce sum over last dim
| return tf.reduce_sum(tf.square(true - pred), axis=-1)
| Regressor.one_hot, nr_categories=factor.size)
elif factor.type == "angle":
return FactorRegressor.angle_to_vector
else:
raise KeyError(factor.type)
def sse(true, pred):
# run our own sum squared error because we want to reduce sum over last dim
| 64 | 64 | 40 | 25 | 39 | cynthiamao98/deepmind-research | iodine/modules/factor_eval.py | Python | sse | sse | 187 | 189 | 187 | 188 | e3d291fb4791d631765a0080585ee6138b470ac9 | bigcode/the-stack | train |
ecda058b56fec612eeaf23ea | train | class | class SelectorPart(object):
direct_descendant = False
unique_order = 0
def _unescape_class(self, class_name):
# separate all double slashes "\\" (replace them with "\") and remove all single slashes between them
return "\\".join([p.replace("\\", "") for p in class_name.split("\\\\")])
... | class SelectorPart(object):
| direct_descendant = False
unique_order = 0
def _unescape_class(self, class_name):
# separate all double slashes "\\" (replace them with "\") and remove all single slashes between them
return "\\".join([p.replace("\\", "") for p in class_name.split("\\\\")])
def __init__(self, tag: str,... | is_ee_enabled
from .action import Action
from .action_step import ActionStep
from .element import Element
from .element_group import ElementGroup
from .filters import Filter
from .person import Person, PersonDistinctId
from .team import Team
from .utils import namedtuplefetchall
attribute_regex = r"([a-zA-Z]*)\[(.*)... | 159 | 160 | 536 | 5 | 154 | bmann/posthog-foss | posthog/models/event.py | Python | SelectorPart | SelectorPart | 35 | 83 | 35 | 35 | 2c3c36c3ef2bb7058c674c3f8a48833a00869740 | bigcode/the-stack | train |
1582677b407421479ac3c861 | train | class | class Event(models.Model):
class Meta:
indexes = [
models.Index(fields=["elements_hash"]),
models.Index(fields=["timestamp", "team_id", "event"]),
]
def _can_use_cached_query(self, last_updated_action_ts):
if not self.team_id in LAST_UPDATED_TEAM_ACTION:
... | class Event(models.Model):
| class Meta:
indexes = [
models.Index(fields=["elements_hash"]),
models.Index(fields=["timestamp", "team_id", "event"]),
]
def _can_use_cached_query(self, last_updated_action_ts):
if not self.team_id in LAST_UPDATED_TEAM_ACTION:
return False
i... | .create(
team_id=kwargs["team_id"], elements=kwargs.pop("elements")
).hash
event = super().create(*args, **kwargs)
# Matching actions to events can get very expensive to do as events are streaming in
# In a few cases we have had it OOM Pos... | 256 | 256 | 1,057 | 5 | 250 | bmann/posthog-foss | posthog/models/event.py | Python | Event | Event | 265 | 373 | 265 | 265 | 7c95d922dad79d326620924474f8a5f88b918935 | bigcode/the-stack | train |
53d465c803a7b05f37295d7a | train | class | class Selector(object):
parts: List[SelectorPart] = []
def __init__(self, selector: str, escape_slashes=True):
self.parts = []
# Sometimes people manually add *, just remove them as they don't do anything
selector = selector.replace("> * > ", "").replace("> *", "")
tags = re.spl... | class Selector(object):
| parts: List[SelectorPart] = []
def __init__(self, selector: str, escape_slashes=True):
self.parts = []
# Sometimes people manually add *, just remove them as they don't do anything
selector = selector.replace("> * > ", "").replace("> *", "")
tags = re.split(" ", selector.strip()... | "__contains" in key:
where.append("{} @> %s::varchar(200)[]".format(key.replace("__contains", "")))
else:
where.append("{} = %s".format(key))
params.append(value)
return {"where": where, "params": params}
class Selector(object):
| 64 | 64 | 175 | 4 | 60 | bmann/posthog-foss | posthog/models/event.py | Python | Selector | Selector | 86 | 103 | 86 | 86 | ecc9811be1281d17c65dc0971c4eaa265ab4c8e1 | bigcode/the-stack | train |
87406ee549b86481f9e866a6 | train | class | class EventManager(models.QuerySet):
def _element_subquery(self, selector: Selector) -> Tuple[Dict[str, Subquery], Dict[str, Union[F, bool]]]:
filter: Dict[str, Union[F, bool]] = {}
subqueries = {}
for index, tag in enumerate(selector.parts):
subqueries["match_{}".format(index)] ... | class EventManager(models.QuerySet):
| def _element_subquery(self, selector: Selector) -> Tuple[Dict[str, Subquery], Dict[str, Union[F, bool]]]:
filter: Dict[str, Union[F, bool]] = {}
subqueries = {}
for index, tag in enumerate(selector.parts):
subqueries["match_{}".format(index)] = Subquery(
Element.o... | format(key.split("attr__")[1]))
else:
if "__contains" in key:
where.append("{} @> %s::varchar(200)[]".format(key.replace("__contains", "")))
else:
where.append("{} = %s".format(key))
params.append(value)
return {"whe... | 256 | 256 | 1,473 | 7 | 249 | bmann/posthog-foss | posthog/models/event.py | Python | EventManager | EventManager | 106 | 262 | 106 | 106 | bf100a50d41c5ec7207de0e08cac3372c7002f7c | bigcode/the-stack | train |
1298c996332b1c99aee31b3b | train | class | class DenseBlock(torch.nn.Module):
def __init__(self, input_size, output_size, bias=True, activation='prelu', norm='batch'):
super(DenseBlock, self).__init__()
self.fc = torch.nn.Linear(input_size, output_size, bias=bias)
self.norm = norm
if self.norm =='batch':
self.bn ... | class DenseBlock(torch.nn.Module):
| def __init__(self, input_size, output_size, bias=True, activation='prelu', norm='batch'):
super(DenseBlock, self).__init__()
self.fc = torch.nn.Linear(input_size, output_size, bias=bias)
self.norm = norm
if self.norm =='batch':
self.bn = torch.nn.BatchNorm1d(output_size)... | PReLU, self).__init__()
self.weight = torch.nn.Parameter(torch.Tensor(num_parameters).fill_(init))
def forward(self, input):
return -torch.nn.functional.prelu(-input, self.weight)
def __repr__(self):
return self.__class__.__name__ + '(' \
+ 'num_parameters=' + str(self.num_par... | 85 | 85 | 284 | 7 | 77 | Siyeong-Lee/Deep_Recursive_HDRI | block.py | Python | DenseBlock | DenseBlock | 20 | 54 | 20 | 20 | 733951c0d9da31d40e13700f233e69f930469682 | bigcode/the-stack | train |
ebb19ce65432329710956e90 | train | class | class MPReLU(torch.nn.Module):
def __init__(self, num_parameters=1, init=0.25):
self.num_parameters = num_parameters
super(MPReLU, self).__init__()
self.weight = torch.nn.Parameter(torch.Tensor(num_parameters).fill_(init))
def forward(self, input):
return -torch.nn.functional.pr... | class MPReLU(torch.nn.Module):
| def __init__(self, num_parameters=1, init=0.25):
self.num_parameters = num_parameters
super(MPReLU, self).__init__()
self.weight = torch.nn.Parameter(torch.Tensor(num_parameters).fill_(init))
def forward(self, input):
return -torch.nn.functional.prelu(-input, self.weight)
... | import torch
import numpy as np
class MPReLU(torch.nn.Module):
| 16 | 64 | 115 | 8 | 7 | Siyeong-Lee/Deep_Recursive_HDRI | block.py | Python | MPReLU | MPReLU | 5 | 17 | 5 | 5 | e425b83e7439249ee9815885ccb1f8037ea7e247 | bigcode/the-stack | train |
07f24f9fe2b248a08d9563c8 | train | class | class ConvBlock(torch.nn.Module):
def __init__(self, input_size, output_size, kernel_size=4, stride=2, padding=1, bias=True, activation='prelu', norm='batch'):
super(ConvBlock, self).__init__()
self.conv = torch.nn.Conv2d(input_size, output_size, kernel_size, stride, padding, bias=bias)
sel... | class ConvBlock(torch.nn.Module):
| def __init__(self, input_size, output_size, kernel_size=4, stride=2, padding=1, bias=True, activation='prelu', norm='batch'):
super(ConvBlock, self).__init__()
self.conv = torch.nn.Conv2d(input_size, output_size, kernel_size, stride, padding, bias=bias)
self.norm = norm
if self.norm... | moid':
self.act = torch.nn.Sigmoid()
elif self.activation == 'mprelu':
self.act = MPReLU()
def forward(self, x):
if self.norm is not None:
out = self.bn(self.fc(x))
else:
out = self.fc(x)
if self.activation is not None:
r... | 92 | 92 | 307 | 7 | 84 | Siyeong-Lee/Deep_Recursive_HDRI | block.py | Python | ConvBlock | ConvBlock | 57 | 91 | 57 | 57 | 657f554690872cae361734fce91158d0fde7ef2b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.