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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10c4de970bcfa9f68a962adf | train | class | class I64BETestCase(NumericTestCase):
h5fname = 'smpl_i64be.h5'
type = 'int64'
byteorder = 'big'
| class I64BETestCase(NumericTestCase):
| h5fname = 'smpl_i64be.h5'
type = 'int64'
byteorder = 'big'
| type = 'float64'
byteorder = 'big'
class F64LETestCase(NumericTestCase):
h5fname = 'smpl_f64le.h5'
type = 'float64'
byteorder = 'little'
class I64BETestCase(NumericTestCase):
| 64 | 64 | 39 | 11 | 53 | crs4/PyTables | tables/tests/test_hdf5compat.py | Python | I64BETestCase | I64BETestCase | 121 | 124 | 121 | 121 | c954b578c2729c50ce585ba37adf0f56696b56d1 | bigcode/the-stack | train |
551ec661a131ea6ec21095c2 | train | class | class ContiguousCompoundAppendTestCase(HDF5CompatibilityTestCase):
"""
Test for appending data to native contiguous compound datasets.
"""
h5fname = 'non-chunked-table.h5'
def _test(self):
self.assertTrue('/test_var/structure variable' in self.h5file)
self.h5file.close()
#... | class ContiguousCompoundAppendTestCase(HDF5CompatibilityTestCase):
| """
Test for appending data to native contiguous compound datasets.
"""
h5fname = 'non-chunked-table.h5'
def _test(self):
self.assertTrue('/test_var/structure variable' in self.h5file)
self.h5file.close()
# Do a copy to a temporary to avoid modifying the original file
... | rows():
self.assertEqual(row['a'], 3.0)
self.assertEqual(row['b'], 4.0)
self.assertTrue(allequal(row['c'], numpy.array([2.0, 3.0],
dtype="float64")))
self.assertEqual(row['d'], b"d")
self.h5file.close()
c... | 89 | 89 | 299 | 14 | 75 | crs4/PyTables | tables/tests/test_hdf5compat.py | Python | ContiguousCompoundAppendTestCase | ContiguousCompoundAppendTestCase | 243 | 271 | 243 | 244 | cf236cfbaa81541742c3f6db863e6e51731dff89 | bigcode/the-stack | train |
53a721e2d16313a829622517 | train | class | class HDF5CompatibilityTestCase(common.PyTablesTestCase):
"""
Base class for HDF5 compatibility tests.
Test cases deriving from this class must define an ``h5fname``
attribute with the name of the file to be opened, and a ``_test()``
method with checks on the opened file.
"""
def setUp(se... | class HDF5CompatibilityTestCase(common.PyTablesTestCase):
| """
Base class for HDF5 compatibility tests.
Test cases deriving from this class must define an ``h5fname``
attribute with the name of the file to be opened, and a ``_test()``
method with checks on the opened file.
"""
def setUp(self):
self.h5file = None
def tearDown(self):
... | # $Id$
#
########################################################################
"""Test module for compatibility with plain HDF files"""
import unittest
import tempfile
import shutil
import os
import numpy
import tables
from tables.tests import common
from tables.tests.common import allequal
class HDF5Compatibili... | 64 | 64 | 156 | 14 | 49 | crs4/PyTables | tables/tests/test_hdf5compat.py | Python | HDF5CompatibilityTestCase | HDF5CompatibilityTestCase | 27 | 48 | 27 | 28 | fecf9f55da3a0e39eb9ca75245819b1542497500 | bigcode/the-stack | train |
a2eec0bf06395f3d51e255de | train | class | class I32LETestCase(NumericTestCase):
h5fname = 'smpl_i32le.h5'
type = 'int32'
byteorder = 'little'
| class I32LETestCase(NumericTestCase):
| h5fname = 'smpl_i32le.h5'
type = 'int32'
byteorder = 'little'
| type = 'int64'
byteorder = 'little'
class I32BETestCase(NumericTestCase):
h5fname = 'smpl_i32be.h5'
type = 'int32'
byteorder = 'big'
class I32LETestCase(NumericTestCase):
| 64 | 64 | 39 | 11 | 53 | crs4/PyTables | tables/tests/test_hdf5compat.py | Python | I32LETestCase | I32LETestCase | 139 | 142 | 139 | 139 | 1974d5034a40bc72452176e33000189865697ac6 | bigcode/the-stack | train |
c32a28e51e9ab899b8c67198 | train | function | def get_members_list(lst, idxs):
# Return specific elements from a list
return [lst[it] for it in idxs]
| def get_members_list(lst, idxs):
# Return specific elements from a list
| return [lst[it] for it in idxs]
| flatten = pooled.view(pooled.shape[0], -1)
flatten = self.drop(flatten)
# import ipdb; ipdb.set_trace()
out = self.fc(flatten)
return out
def get_members_list(lst, idxs):
# Return specific elements from a list
| 64 | 64 | 30 | 18 | 45 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | get_members_list | get_members_list | 389 | 391 | 389 | 390 | a781e1987344fab5f1ff50bd4ee84fa5fcf51c32 | bigcode/the-stack | train |
78b4a82dfe3aa26625f28e02 | train | class | class TrojNet(nn.Module):
def __init__(self, max_class=24, p=0.5, embedding_dim=16):
super(TrojNet, self).__init__()
self.max_class = max_class
# self.all_classes = all_classes
# self.embed = nn.Embedding(len(all_classes), embedding_dim)
self.encoder = nn.Se... | class TrojNet(nn.Module):
| def __init__(self, max_class=24, p=0.5, embedding_dim=16):
super(TrojNet, self).__init__()
self.max_class = max_class
# self.all_classes = all_classes
# self.embed = nn.Embedding(len(all_classes), embedding_dim)
self.encoder = nn.Sequential(
nn.C... | ]
self.feats = np.zeros((len(_curves), max_class, feat_sz))
self.valid = np.zeros((len(_curves), max_class))
for idx, en in enumerate(_curves):
val = en.shape[0]
self.feats[idx][:val, : en.shape[1]] = en
self.valid[idx][:val] = 1
def __len__(self):
... | 143 | 143 | 477 | 7 | 136 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | TrojNet | TrojNet | 334 | 386 | 334 | 334 | 07a4ef8fa0c838ec69c74fdc7e61c2166be80205 | bigcode/the-stack | train |
0fb66cf724ae971490590e3d | train | function | def get_data_info(args, meta_data):
if args.dataset == "round3":
# all_archs = [
# "densenet169",
# "densenet121",
# "densenet169",
# ]
# meta_data = meta_data[meta_data.model_architecture.isin(all_archs)]
trigger_type = ["None", "polygon", "inst... | def get_data_info(args, meta_data):
| if args.dataset == "round3":
# all_archs = [
# "densenet169",
# "densenet121",
# "densenet169",
# ]
# meta_data = meta_data[meta_data.model_architecture.isin(all_archs)]
trigger_type = ["None", "polygon", "instagram"]
all_archs = meta_dat... | (
os.path.join(troj_root, "round1-dataset-train", "METADATA.csv")
)
feature_dir = os.path.join(cvpr_root, "troj_round1/curve_features_gradxact")
if use_holdout:
holdout_dir = os.path.join(
cvpr_root, "troj_round1", "/holdout/curve_features_gradxact"
... | 256 | 256 | 1,008 | 9 | 246 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | get_data_info | get_data_info | 72 | 170 | 72 | 72 | f3c13368ec63bcb9c3bf06c1b9fc41afbd9e2a77 | bigcode/the-stack | train |
60119f858bc25ad2949215ca | train | class | class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(
self, patience=7, verbose=False, delta=0, path="checkpoint.pt", trace_func=print
):
self.patience = patience
self.verbose = verbose
self.counter = 0
... | class EarlyStopping:
| """Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(
self, patience=7, verbose=False, delta=0, path="checkpoint.pt", trace_func=print
):
self.patience = patience
self.verbose = verbose
self.counter = 0
self.best_scor... | db.set_trace()
# pooled = emb.unsqueeze(-1)*pooled
flatten = pooled.view(pooled.shape[0], -1)
flatten = self.drop(flatten)
# import ipdb; ipdb.set_trace()
out = self.fc(flatten)
return out
def get_members_list(lst, idxs):
# Return specific elemen... | 97 | 97 | 326 | 4 | 93 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | EarlyStopping | EarlyStopping | 394 | 436 | 394 | 394 | 5768644e9c104dc3651af3c83b32f836e34fa9d0 | bigcode/the-stack | train |
46e165f335a1a8eb95e3039b | train | function | def get_split_data(all_data, model_names):
labels, feats, archs, names = all_data
labels_ret = [f for f, n in zip(labels, names) if n in model_names]
feats_ret = [f for f, n in zip(feats, names) if n in model_names]
archs_ret = [f for f, n in zip(archs, names) if n in model_names]
names_ret = [f fo... | def get_split_data(all_data, model_names):
| labels, feats, archs, names = all_data
labels_ret = [f for f, n in zip(labels, names) if n in model_names]
feats_ret = [f for f, n in zip(feats, names) if n in model_names]
archs_ret = [f for f, n in zip(archs, names) if n in model_names]
names_ret = [f for f, n in zip(names, names) if n in model_n... | test_perc=test_split
# )
# model_idx_train += train_lst
# model_idx_test += test_lst
# model_idx_val += val_lst
return model_idx_train, model_idx_val, model_idx_test
def get_split_data(all_data, model_names):
| 64 | 64 | 130 | 10 | 53 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | get_split_data | get_split_data | 239 | 247 | 239 | 239 | e44100bdd8266fd5ca18967f1ac9f12b263f11ca | bigcode/the-stack | train |
2bc04c87050706ba5f39d2ee | train | function | def adjust_learning_rate(optimizer, decay=0.1):
"""Sets the learning rate to the initial LR decayed by 0.5 every 20
epochs"""
for param_group in optimizer.param_groups:
param_group["lr"] = decay * param_group["lr"]
| def adjust_learning_rate(optimizer, decay=0.1):
| """Sets the learning rate to the initial LR decayed by 0.5 every 20
epochs"""
for param_group in optimizer.param_groups:
param_group["lr"] = decay * param_group["lr"]
| Set correct paths in init_data_path
"""
import pickle
import os
import numpy as np
from torch.utils.data import Dataset
import torch.nn as nn
import torch
import random
from sklearn import metrics
import pandas as pd
#################################################
def adjust_learning_rate(optimizer, decay=0.1):
| 64 | 64 | 60 | 13 | 51 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | adjust_learning_rate | adjust_learning_rate | 17 | 21 | 17 | 17 | 63c6b847100457852aafa6bc89ba2374aadd5d7d | bigcode/the-stack | train |
c284a5f648a7fb59edfb13e1 | train | function | def init_data_path(dataset_name, use_holdout, use_kubernetes=False):
holdout_dir = None
holdout_metadata = None
if not use_kubernetes:
troj_root = "/data/SRI/projects_2020/trojAI"
cvpr_root = (
"/data/SRI/mount/rebel/SRI/k8s/trinityTrojAI/users/SRI/cvpr_exp"
)
else:
... | def init_data_path(dataset_name, use_holdout, use_kubernetes=False):
| holdout_dir = None
holdout_metadata = None
if not use_kubernetes:
troj_root = "/data/SRI/projects_2020/trojAI"
cvpr_root = (
"/data/SRI/mount/rebel/SRI/k8s/trinityTrojAI/users/SRI/cvpr_exp"
)
else:
troj_root = "/data"
cvpr_root = "/data/k8s/trinityTroj... | """
Loader, model, utility fns related to the classifier
Set correct paths in init_data_path
"""
import pickle
import os
import numpy as np
from torch.utils.data import Dataset
import torch.nn as nn
import torch
import random
from sklearn import metrics
import pandas as pd
############################################... | 143 | 163 | 544 | 16 | 127 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | init_data_path | init_data_path | 27 | 69 | 27 | 27 | 9e6ecf2f62450c61e0f364c5147b1fa5a37e26a8 | bigcode/the-stack | train |
3ee5594b2e41b067f82de2fe | train | function | def train_model(
model,
patience,
n_epochs,
train_loader,
valid_loader,
optimizer,
criterion,
device,
ckt_path="checkpoint.pt",
):
# if os.path.exists(ckt_path):
# model.load_state_dict(torch.load(ckt_path))
train_losses = []
valid_losses = []
avg_tr... | def train_model(
model,
patience,
n_epochs,
train_loader,
valid_loader,
optimizer,
criterion,
device,
ckt_path="checkpoint.pt",
):
# if os.path.exists(ckt_path):
# model.load_state_dict(torch.load(ckt_path))
| train_losses = []
valid_losses = []
avg_train_losses = []
avg_valid_losses = []
train_acc = []
valid_acc = []
avg_train_acc = []
avg_valid_acc = []
early_stopping = EarlyStopping(patience=patience, verbose=True, path=ckt_path)
for epoch in range(1, n_epochs + 1):
model... |
if self.best_score is None:
self.best_score = score
self.save_checkpoint(val_loss, model)
elif score < self.best_score + self.delta:
self.counter += 1
self.trace_func(
f"EarlyStopping counter: {self.counter} out of {self.patience}"
... | 256 | 256 | 865 | 64 | 191 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | train_model | train_model | 439 | 555 | 439 | 453 | b8862666fd425dcd7f20af47aafa915932fa564b | bigcode/the-stack | train |
afea350eb721d28ccf10abec | train | class | class filters_ablation:
def triggered_classes(self, triggered_classes):
if triggered_classes == "None":
return True
else:
triggered_classes = [int(k) for k in triggered_classes[1:-1].split(" ")]
if len(triggered_classes) > 2:
return True
... | class filters_ablation:
| def triggered_classes(self, triggered_classes):
if triggered_classes == "None":
return True
else:
triggered_classes = [int(k) for k in triggered_classes[1:-1].split(" ")]
if len(triggered_classes) > 2:
return True
else:
... | .project_name,
config=vars(args),
sync_tensorboard=True,
name=args.env_name,
entity="SRI",
tags=args.tags.split(","),
dir="/home/SRI/troj",
)
else:
wandb = None
return wandb
class filters_ablation:
| 64 | 64 | 73 | 5 | 58 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | filters_ablation | filters_ablation | 577 | 586 | 577 | 577 | 6413db66dbdca131c76c44cde2f024f46f805d81 | bigcode/the-stack | train |
d7a16260d93619cf5637fd9f | train | function | def load_data(feature_dir, meta_data, models_lst):
labels = []
feats = []
archs = []
model_name_all = []
for model_name in models_lst:
file_name = os.path.join(feature_dir, "{}.pkl".format(model_name))
if os.path.exists(file_name):
archs.append(
meta_data[... | def load_data(feature_dir, meta_data, models_lst):
| labels = []
feats = []
archs = []
model_name_all = []
for model_name in models_lst:
file_name = os.path.join(feature_dir, "{}.pkl".format(model_name))
if os.path.exists(file_name):
archs.append(
meta_data[meta_data["model_name"] == model_name][
... | n in zip(archs, names) if n in model_names]
names_ret = [f for f, n in zip(names, names) if n in model_names]
return labels_ret, feats_ret, archs_ret, names_ret
def load_data(feature_dir, meta_data, models_lst):
| 64 | 64 | 171 | 12 | 51 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | load_data | load_data | 250 | 270 | 250 | 250 | 42c802e5cd7830541fecf9a745e19be8c53644e6 | bigcode/the-stack | train |
f02390b111f586b59c3b27e9 | train | function | def _get_split(df, _a, val_perc=10, test_perc=10):
if isinstance(_a, str):
_lst = df[df.model_architecture == _a].model_name.to_list()
elif isinstance(_a, list):
_lst = df[df.model_architecture.isin(_a)].model_name.to_list()
random.shuffle(_lst)
_val_split = len(_lst) * val_perc // 100
... | def _get_split(df, _a, val_perc=10, test_perc=10):
| if isinstance(_a, str):
_lst = df[df.model_architecture == _a].model_name.to_list()
elif isinstance(_a, list):
_lst = df[df.model_architecture.isin(_a)].model_name.to_list()
random.shuffle(_lst)
_val_split = len(_lst) * val_perc // 100
_test_split = len(_lst) * test_perc // 100
r... | -00000359")
except:
pass
try:
models_lst.remove("id-00000587")
except:
pass
return all_archs, models_filter, models_lst
def _get_split(df, _a, val_perc=10, test_perc=10):
| 64 | 64 | 156 | 21 | 42 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | _get_split | _get_split | 173 | 185 | 173 | 173 | e8db6dcd979169e1167ace54eafd97ab5f2187f6 | bigcode/the-stack | train |
71487ae24656b374d24a52e8 | train | function | def initialize_wandb(args):
# Initialize wandb
if args.use_wandb:
import wandb
wandb.init(
project=args.project_name,
config=vars(args),
sync_tensorboard=True,
name=args.env_name,
entity="SRI",
tags=args.tags.split(","),
... | def initialize_wandb(args):
# Initialize wandb
| if args.use_wandb:
import wandb
wandb.init(
project=args.project_name,
config=vars(args),
sync_tensorboard=True,
name=args.env_name,
entity="SRI",
tags=args.tags.split(","),
dir="/home/SRI/troj",
)
else:... | _stop:
# print("Early stopping")
# break
model.load_state_dict(torch.load(ckt_path))
# return model, avg_train_losses, avg_valid_losses, avg_train_acc, avg_valid_acc
return auc
def initialize_wandb(args):
# Initialize wandb
| 64 | 64 | 93 | 13 | 50 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | initialize_wandb | initialize_wandb | 558 | 574 | 558 | 559 | 143a23695f57b20651a51dcaef9e5b598a4f32bf | bigcode/the-stack | train |
29bdd9a0253e6a4e122086ae | train | function | def get_splits(models_filter, all_archs, val_split, test_split):
models_poison = models_filter[models_filter.poisoned == True]
models_clean = models_filter[models_filter.poisoned == False]
model_idx_train = []
model_idx_val = []
model_idx_test = []
for _a in all_archs:
train_lst, val_ls... | def get_splits(models_filter, all_archs, val_split, test_split):
| models_poison = models_filter[models_filter.poisoned == True]
models_clean = models_filter[models_filter.poisoned == False]
model_idx_train = []
model_idx_val = []
model_idx_test = []
for _a in all_archs:
train_lst, val_lst, test_lst = _get_split(
models_clean, _a, val_perc=... | c // 100
return (
_lst[(_val_split + _test_split) :],
_lst[_val_split : (_val_split + _test_split)],
_lst[:_val_split],
)
def get_splits(models_filter, all_archs, val_split, test_split):
| 64 | 64 | 210 | 17 | 47 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | get_splits | get_splits | 188 | 209 | 188 | 188 | 8d1f8612a8786037da64999d3b9a5d1d30532103 | bigcode/the-stack | train |
1466b98e532bdc07ebf83c71 | train | function | def get_splits_random(models_filter, all_archs, val_split, test_split):
model_idx_train, model_idx_val, model_idx_test = _get_split(
models_filter, all_archs.tolist(), val_perc=val_split, test_perc=test_split
)
# models_poison = models_filter[models_filter.poisoned == True]
# models_clean = mode... | def get_splits_random(models_filter, all_archs, val_split, test_split):
| model_idx_train, model_idx_val, model_idx_test = _get_split(
models_filter, all_archs.tolist(), val_perc=val_split, test_perc=test_split
)
# models_poison = models_filter[models_filter.poisoned == True]
# models_clean = models_filter[models_filter.poisoned == False]
# model_idx_train = []
... | = _get_split(
models_poison, _a, val_perc=val_split, test_perc=test_split
)
model_idx_train += train_lst
model_idx_test += test_lst
model_idx_val += val_lst
return model_idx_train, model_idx_val, model_idx_test
def get_splits_random(models_filter, all_archs, val_split, ... | 84 | 84 | 282 | 18 | 65 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | get_splits_random | get_splits_random | 212 | 236 | 212 | 212 | 437fca37458f03ecdcdb62859ee86b9f9be8805a | bigcode/the-stack | train |
746885543c939036d8bcd0a9 | train | class | class neuron_ds(Dataset):
def __init__(
self,
feats,
_labels,
_archs,
_names,
max_class=24,
diff=False,
normalize=True,
feat_sz=2048,
collapse_graph=True,
):
self.labels = _labels
self.archs = _archs
self.nam... | class neuron_ds(Dataset):
| def __init__(
self,
feats,
_labels,
_archs,
_names,
max_class=24,
diff=False,
normalize=True,
feat_sz=2048,
collapse_graph=True,
):
self.labels = _labels
self.archs = _archs
self.names = _names
div =... | for model_name in models_lst:
file_name = os.path.join(feature_dir, "{}.pkl".format(model_name))
if os.path.exists(file_name):
archs.append(
meta_data[meta_data["model_name"] == model_name][
"model_architecture"
].item()
)
... | 145 | 145 | 485 | 6 | 138 | frkl/Trinity-TrojAI | AttributionBased/utils_temporal_nn/utils_nn.py | Python | neuron_ds | neuron_ds | 273 | 331 | 273 | 273 | d6022a68302809d013c2eb62b7f433de26294327 | bigcode/the-stack | train |
42a0da93e820789ecefcd9f5 | train | function | def run_processes():
my_env = os.environ.copy()
my_env["PYTHONPATH"] = ".:/home/pi/Development/rpi_ws281x/python/build/lib.linux-arm7l-2.7/:/home/pi/Development/rpi_ws281x/pyton/examples/"
proc1 = Popen("%s %s %s" % ('sudo', '/usr/bin/python', 'examples/scroll_text.py'), env=my_env, stdout=PIPE, shell=True)... | def run_processes():
| my_env = os.environ.copy()
my_env["PYTHONPATH"] = ".:/home/pi/Development/rpi_ws281x/python/build/lib.linux-arm7l-2.7/:/home/pi/Development/rpi_ws281x/pyton/examples/"
proc1 = Popen("%s %s %s" % ('sudo', '/usr/bin/python', 'examples/scroll_text.py'), env=my_env, stdout=PIPE, shell=True)
proc2 = Popen("%... | from subprocess import Popen, call, PIPE
import os
def run_processes():
| 18 | 64 | 180 | 5 | 12 | xHeliotrope/led_tweet_writer | python/runner.py | Python | run_processes | run_processes | 4 | 12 | 4 | 4 | 300ab0a611d8f33ff77b55da3f39e199122c4581 | bigcode/the-stack | train |
f56dd19eff5dc3799508191f | train | function | def make_batches(lines, args, task, max_positions, encode_fn):
def encode_fn_target(x):
return encode_fn(x)
if args.constraints:
# Strip (tab-delimited) contraints, if present, from input lines,
# store them in batch_constraints
batch_constraints = [list() for _ in lines]
... | def make_batches(lines, args, task, max_positions, encode_fn):
| def encode_fn_target(x):
return encode_fn(x)
if args.constraints:
# Strip (tab-delimited) contraints, if present, from input lines,
# store them in batch_constraints
batch_constraints = [list() for _ in lines]
for i, line in enumerate(lines):
if "\t" in line:... | _tokens src_lengths constraints")
Translation = namedtuple("Translation", "src_str hypos pos_scores alignments")
def buffered_read(input, buffer_size):
buffer = []
with fileinput.input(files=[input], openhook=fileinput.hook_encoded("utf-8")) as h:
for src_str in h:
buffer.append(src_str.st... | 117 | 117 | 392 | 15 | 101 | Epsilon-Lee/fairseq-da | fairseq_cli/interactive.py | Python | make_batches | make_batches | 52 | 108 | 52 | 52 | c6bbaa222edb07037e9785edda4a94737aacbe38 | bigcode/the-stack | train |
826b89c01708cd03c5748f36 | train | function | def main(args):
start_time = time.time()
total_translate_time = 0
utils.import_user_module(args)
if args.buffer_size < 1:
args.buffer_size = 1
if args.max_tokens is None and args.batch_size is None:
args.batch_size = 1
assert (
not args.sampling or args.nbest == args.b... | def main(args):
| start_time = time.time()
total_translate_time = 0
utils.import_user_module(args)
if args.buffer_size < 1:
args.buffer_size = 1
if args.max_tokens is None and args.batch_size is None:
args.batch_size = 1
assert (
not args.sampling or args.nbest == args.beam
), "--sa... | encode_fn_target(constraint),
append_eos=False,
add_if_not_exist=False,
)
for constraint in constraint_list
]
tokens = [
task.source_dictionary.encode_line(
encode_fn(src_str), add_if_not_exi... | 256 | 256 | 1,446 | 4 | 252 | Epsilon-Lee/fairseq-da | fairseq_cli/interactive.py | Python | main | main | 111 | 301 | 111 | 111 | eb72414b67a085e2a8df535f88410a70ff74ff6d | bigcode/the-stack | train |
61619e96f9a7cbdab8b262a8 | train | function | def cli_main():
parser = options.get_interactive_generation_parser()
args = options.parse_args_and_arch(parser)
distributed_utils.call_main(args, main)
| def cli_main():
| parser = options.get_interactive_generation_parser()
args = options.parse_args_and_arch(parser)
distributed_utils.call_main(args, main)
| (id_, alignment_str))
# update running id_ counter
start_id += len(inputs)
logger.info(
"Total time: {:.3f} seconds; translation time: {:.3f}".format(
time.time() - start_time, total_translate_time
)
)
def cli_main():
| 64 | 64 | 33 | 4 | 60 | Epsilon-Lee/fairseq-da | fairseq_cli/interactive.py | Python | cli_main | cli_main | 304 | 307 | 304 | 304 | 2eef309319daab56160aa625f32efe4b66e1f7bc | bigcode/the-stack | train |
53e9986e20614108e219cbb6 | train | function | def buffered_read(input, buffer_size):
buffer = []
with fileinput.input(files=[input], openhook=fileinput.hook_encoded("utf-8")) as h:
for src_str in h:
buffer.append(src_str.strip())
if len(buffer) >= buffer_size:
yield buffer
buffer = []
if ... | def buffered_read(input, buffer_size):
| buffer = []
with fileinput.input(files=[input], openhook=fileinput.hook_encoded("utf-8")) as h:
for src_str in h:
buffer.append(src_str.strip())
if len(buffer) >= buffer_size:
yield buffer
buffer = []
if len(buffer) > 0:
yield buffer
| ", "INFO").upper(),
stream=sys.stdout,
)
logger = logging.getLogger("fairseq_cli.interactive")
Batch = namedtuple("Batch", "ids src_tokens src_lengths constraints")
Translation = namedtuple("Translation", "src_str hypos pos_scores alignments")
def buffered_read(input, buffer_size):
| 64 | 64 | 80 | 8 | 56 | Epsilon-Lee/fairseq-da | fairseq_cli/interactive.py | Python | buffered_read | buffered_read | 39 | 49 | 39 | 39 | 19d428530486bac3f6afb8c09d34eb311d3f4713 | bigcode/the-stack | train |
72457485194193f3f7bb416c | train | class | class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
size = len(prices)
bought = False
profit = 0
price = 0
for i in range(0, size - 1):
if not bought:
if prices[i] < prices[i + 1]... | class Solution:
| def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
size = len(prices)
bought = False
profit = 0
price = 0
for i in range(0, size - 1):
if not bought:
if prices[i] < prices[i + 1]:
... | class Solution:
| 3 | 64 | 148 | 3 | 0 | ZintrulCre/LeetCode_Archiver | LeetCode/python3/122.py | Python | Solution | Solution | 1 | 23 | 1 | 1 | 1767fcdc4730c24b32fe580c5735cbcdc28ba027 | bigcode/the-stack | train |
2abedaed2376408dc101c256 | train | class | @base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class GetIamPolicy(base.ListCommand):
"""Get the IAM policy for a model.
Gets the IAM policy for the given model.
Returns an empty policy if the resource does not have a policy set.
## EXAMPLES
The following command gets the IAM policy for ... | @base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class GetIamPolicy(base.ListCommand):
| """Get the IAM policy for a model.
Gets the IAM policy for the given model.
Returns an empty policy if the resource does not have a policy set.
## EXAMPLES
The following command gets the IAM policy for the model `my_model`:
$ {command} my_model
"""
@staticmethod
def Args(parser):
flags.Get... | .api_lib.ml_engine import models
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.ml_engine import flags
from googlecloudsdk.command_lib.ml_engine import models_util
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class GetIamPolicy(base.ListCommand):
| 64 | 64 | 140 | 24 | 39 | bshaffer/google-cloud-sdk | lib/surface/ml_engine/models/get_iam_policy.py | Python | GetIamPolicy | GetIamPolicy | 27 | 48 | 27 | 28 | e6a76bb328b477696cd743a8c3993dd825274a43 | bigcode/the-stack | train |
168e0b64c2d696b5505074bf | train | class | class Migration(migrations.Migration):
dependencies = [
('release', '0005_auto_20160314_1532'),
]
operations = [
migrations.CreateModel(
name='ReleaseGroup',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, prim... | class Migration(migrations.Migration):
| dependencies = [
('release', '0005_auto_20160314_1532'),
]
operations = [
migrations.CreateModel(
name='ReleaseGroup',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name',... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| 31 | 69 | 232 | 7 | 23 | hluk/product-definition-center | pdc/apps/release/migrations/0006_auto_20160512_0515.py | Python | Migration | Migration | 7 | 39 | 7 | 8 | cdbf7bf399470d36c66be008af85ac2846282f85 | bigcode/the-stack | train |
2a539a16ac168b3757426e32 | train | function | def get_bucket(expression):
key = BooleanCondition.build_key(expression)
return buckets.get(key, None)
| def get_bucket(expression):
| key = BooleanCondition.build_key(expression)
return buckets.get(key, None)
| from bucket_filter.bucket import Bucket
from bucket_filter.condition import ConditionType, BooleanCondition
from bucket_filter.resolver import parse, evaluate
buckets = {}
def get_bucket(expression):
| 37 | 64 | 22 | 5 | 32 | conlini/bucket_filters | bucket_filter/__init__.py | Python | get_bucket | get_bucket | 7 | 9 | 7 | 7 | 9ffdccdc370496146e7ad3a901f85dbcb4250f6d | bigcode/the-stack | train |
3d1658bbe6e9a77a08583788 | train | function | def solve(expression):
expressions, inner = parse(expression)
evaluated = {}
if inner:
for i in inner:
evaluate(expressions["{}".format(i)], evaluated, buckets)
bucket_final = evaluate(expressions["FINAL"], evaluated, buckets)
return bucket_final.elements.values()
| def solve(expression):
| expressions, inner = parse(expression)
evaluated = {}
if inner:
for i in inner:
evaluate(expressions["{}".format(i)], evaluated, buckets)
bucket_final = evaluate(expressions["FINAL"], evaluated, buckets)
return bucket_final.elements.values()
| =None, condition_type=ConditionType.BOOLEAN):
if condition_type == ConditionType.BOOLEAN:
key = BooleanCondition.build_key(expression)
if key not in buckets:
condition = BooleanCondition(expression)
bucket = Bucket(condition, elements)
buckets[condition.key] = buc... | 64 | 64 | 60 | 4 | 59 | conlini/bucket_filters | bucket_filter/__init__.py | Python | solve | solve | 21 | 28 | 21 | 21 | 08672a93c9bbd27e90574271bfce8215b1c4eeb8 | bigcode/the-stack | train |
fc8079e634849cb69320076b | train | function | def register_bucket(expression, elements=None, condition_type=ConditionType.BOOLEAN):
if condition_type == ConditionType.BOOLEAN:
key = BooleanCondition.build_key(expression)
if key not in buckets:
condition = BooleanCondition(expression)
bucket = Bucket(condition, elements)
... | def register_bucket(expression, elements=None, condition_type=ConditionType.BOOLEAN):
| if condition_type == ConditionType.BOOLEAN:
key = BooleanCondition.build_key(expression)
if key not in buckets:
condition = BooleanCondition(expression)
bucket = Bucket(condition, elements)
buckets[condition.key] = bucket
|
from bucket_filter.condition import ConditionType, BooleanCondition
from bucket_filter.resolver import parse, evaluate
buckets = {}
def get_bucket(expression):
key = BooleanCondition.build_key(expression)
return buckets.get(key, None)
def register_bucket(expression, elements=None, condition_type=ConditionTyp... | 64 | 64 | 66 | 16 | 48 | conlini/bucket_filters | bucket_filter/__init__.py | Python | register_bucket | register_bucket | 12 | 18 | 12 | 12 | 8bdddd11c027c45f27b235e8e7edca7e6ecb848f | bigcode/the-stack | train |
e33c8a6923a64405b1011415 | train | function | def spoof_on_hold_monthly_subscription():
return {
"status": "On Hold",
"rate": "Sentinel Rate",
"frequency": "monthly"
}
| def spoof_on_hold_monthly_subscription():
| return {
"status": "On Hold",
"rate": "Sentinel Rate",
"frequency": "monthly"
}
| TestCase
from random import random
import re
from bs4 import BeautifulSoup
# Fixtures
def spoof_current_monthly_subscription():
return {
"status": "Current",
"rate": "Sentinel Rate",
"frequency": "monthly"
}
def spoof_on_hold_monthly_subscription():
| 64 | 64 | 37 | 8 | 56 | peterk/perma | perma_web/perma/tests/test_views_user_management.py | Python | spoof_on_hold_monthly_subscription | spoof_on_hold_monthly_subscription | 28 | 33 | 28 | 28 | 073e0f7e12971f8246c9c90dba1359d08d75fffd | bigcode/the-stack | train |
363347ea9d04d6d0af599284 | train | function | def spoof_cancellation_requested_subscription():
return {
"status": "Cancellation Requested",
"rate": "Sentinel Rate",
"frequency": "Sentinel Frequency"
}
| def spoof_cancellation_requested_subscription():
| return {
"status": "Cancellation Requested",
"rate": "Sentinel Rate",
"frequency": "Sentinel Frequency"
}
| Current",
"rate": "Sentinel Rate",
"frequency": "monthly"
}
def spoof_on_hold_monthly_subscription():
return {
"status": "On Hold",
"rate": "Sentinel Rate",
"frequency": "monthly"
}
def spoof_cancellation_requested_subscription():
| 64 | 64 | 38 | 7 | 57 | peterk/perma | perma_web/perma/tests/test_views_user_management.py | Python | spoof_cancellation_requested_subscription | spoof_cancellation_requested_subscription | 36 | 41 | 36 | 36 | 326c96a727f79fe9c55ee8c4c09c7d9e51607897 | bigcode/the-stack | train |
5d6dcd993998e75816dc245e | train | function | def spoof_current_monthly_subscription():
return {
"status": "Current",
"rate": "Sentinel Rate",
"frequency": "monthly"
}
| def spoof_current_monthly_subscription():
| return {
"status": "Current",
"rate": "Sentinel Rate",
"frequency": "monthly"
}
| .urls import NoReverseMatch
from mock import patch, sentinel
from perma.models import *
from perma.exceptions import PermaPaymentsCommunicationException
from .utils import PermaTestCase
from random import random
import re
from bs4 import BeautifulSoup
# Fixtures
def spoof_current_monthly_subscription():
| 64 | 64 | 35 | 7 | 56 | peterk/perma | perma_web/perma/tests/test_views_user_management.py | Python | spoof_current_monthly_subscription | spoof_current_monthly_subscription | 21 | 26 | 21 | 21 | a87d2f1968ad8c9fa414edfd5c6310fc584d1e7d | bigcode/the-stack | train |
b17374cbd8a7bcafac51102b | train | class | class UserManagementViewsTestCase(PermaTestCase):
fixtures = ['fixtures/users.json',
'fixtures/folders.json',
'fixtures/archive.json',
]
def setUp(self):
super(UserManagementViewsTestCase, self).setUp()
self.admin_user = LinkUser.objects.get(pk=... | class UserManagementViewsTestCase(PermaTestCase):
| fixtures = ['fixtures/users.json',
'fixtures/folders.json',
'fixtures/archive.json',
]
def setUp(self):
super(UserManagementViewsTestCase, self).setUp()
self.admin_user = LinkUser.objects.get(pk=1)
self.registrar_user = LinkUser.objects.g... | # -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.core import mail
from django.conf import settings
from django.urls import NoReverseMatch
from mock import patch, sentinel
from perma.models import *
from perma.exceptions import PermaPaymentsCommunicationException
from .utils import Per... | 213 | 256 | 19,016 | 12 | 200 | peterk/perma | perma_web/perma/tests/test_views_user_management.py | Python | UserManagementViewsTestCase | UserManagementViewsTestCase | 46 | 1,948 | 46 | 47 | 9425573446a46c38e6dab9c15b76ed1ddfa9b0ee | bigcode/the-stack | train |
5afa4a82fa4a42d5533b4e1c | train | function | def main():
colors = vtk.vtkNamedColors()
# Create the RenderWindow, Renderer and Interactor.
#
renderer = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(renderer)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Create the spring profile ... | def main():
| colors = vtk.vtkNamedColors()
# Create the RenderWindow, Renderer and Interactor.
#
renderer = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(renderer)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Create the spring profile (a circle).
... | #!/usr/bin/env python
import vtk
def main():
| 12 | 205 | 686 | 3 | 8 | sankhesh/vtk-examples | src/Python/Modelling/Spring.py | Python | main | main | 6 | 82 | 6 | 6 | 42064827fe30501cff163684ee22d0e169a09174 | bigcode/the-stack | train |
1bbac3f806c13e72063f4ceb | train | class | class DenseBlock(nn.Module):
"""Implements the dense block."""
def __init__(self,
in_channels,
out_channels,
weight_gain=1.0,
lr_multiplier=0.01,
add_bias=True,
init_bias=0,
activation_type='l... | class DenseBlock(nn.Module):
| """Implements the dense block."""
def __init__(self,
in_channels,
out_channels,
weight_gain=1.0,
lr_multiplier=0.01,
add_bias=True,
init_bias=0,
activation_type='lrelu'):
"""Initialize... | = x / _weight_norm.view(batch, self.out_c, 1, 1)
if self.add_noise:
if self.randomize_noise:
noise = torch.randn(x.shape[0], 1, self.res, self.res).to(x)
else:
noise = self.noise
x = x + noise * self.noise_strength.view(1, 1, 1, 1)
i... | 145 | 145 | 485 | 6 | 138 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | DenseBlock | DenseBlock | 946 | 1,008 | 946 | 946 | 3b41726a67f48dbfab356537d81fe9c131680b3f | bigcode/the-stack | train |
20e917b9ac07c545fbece244 | train | class | class SynthesisModule(nn.Module):
"""Implements the image synthesis module.
Basically, this module executes several convolutional layers in sequence.
"""
def __init__(self,
init_resolution=4,
resolution=1024,
w_space_dim=512,
image_channe... | class SynthesisModule(nn.Module):
| """Implements the image synthesis module.
Basically, this module executes several convolutional layers in sequence.
"""
def __init__(self,
init_resolution=4,
resolution=1024,
w_space_dim=512,
image_channels=3,
architectur... | truncation_layers = 0
self.register_buffer('w_avg', torch.zeros(w_space_dim))
self.pth_to_tf_var_mapping = {'w_avg': 'dlatent_avg'}
layer_idx = np.arange(self.num_layers).reshape(1, self.num_layers, 1)
coefs = np.ones_like(layer_idx, dtype=np.float32)
coefs[layer_id... | 256 | 256 | 3,654 | 7 | 248 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | SynthesisModule | SynthesisModule | 280 | 597 | 280 | 280 | 13c9471f6fdd4d078ca3835537a89669ff450775 | bigcode/the-stack | train |
272109341c3a163317853819 | train | class | class ConvBlock(nn.Module):
"""Implements the convolutional block (no style modulation)."""
def __init__(self,
in_channels,
out_channels,
kernel_size=3,
scale_factor=1,
filtering_kernel=(1, 3, 3, 1),
weight_ga... | class ConvBlock(nn.Module):
| """Implements the convolutional block (no style modulation)."""
def __init__(self,
in_channels,
out_channels,
kernel_size=3,
scale_factor=1,
filtering_kernel=(1, 3, 3, 1),
weight_gain=1.0,
lr_... | .shape[2] * self.scale_factor,
x.shape[4] * self.scale_factor)
x = x.view(-1, 1, x.shape[2], x.shape[3])
x = F.pad(x, self.padding, mode='constant', value=0)
x = F.conv2d(x, self.kernel, stride=1)
x = x.view(-1, channels, x.shape[2], x.shape[3])
return x
... | 217 | 217 | 725 | 6 | 210 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | ConvBlock | ConvBlock | 693 | 775 | 693 | 693 | 3ae4fce4a03d8eca87e3ff240a3f72927cd0b990 | bigcode/the-stack | train |
df90048213cce109d289b626 | train | class | class MappingModule(nn.Sequential):
"""Implements the latent space mapping module.
Basically, this module executes several dense layers in sequence.
"""
def __init__(self,
input_space_dim=512,
hidden_space_dim=512,
final_space_dim=512,
nu... | class MappingModule(nn.Sequential):
| """Implements the latent space mapping module.
Basically, this module executes several dense layers in sequence.
"""
def __init__(self,
input_space_dim=512,
hidden_space_dim=512,
final_space_dim=512,
num_layers=8,
normali... | _layer:
w = self.truncation(w)
else:
pass
cur_layer += 1
if isinstance(z, tuple):
x = self.synthesis(z, which_block=which_block - cur_layer, pre_model=pre_model, post_model=post_model)
else:
x = self.synthes... | 133 | 133 | 446 | 6 | 126 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | MappingModule | MappingModule | 177 | 237 | 177 | 177 | 8581fc639afed7f48113a63301651788a94db20b | bigcode/the-stack | train |
4c54addca956a6d84f0618a3 | train | class | class TruncationModule(nn.Module):
"""Implements the truncation module."""
def __init__(self,
num_layers,
w_space_dim=512,
truncation_psi=0.7,
truncation_layers=8):
super().__init__()
self.num_layers = num_layers
self.... | class TruncationModule(nn.Module):
| """Implements the truncation module."""
def __init__(self,
num_layers,
w_space_dim=512,
truncation_psi=0.7,
truncation_layers=8):
super().__init__()
self.num_layers = num_layers
self.w_space_dim = w_space_dim
i... | = 0
y = z
for module in self:
y = module(y)
if count == which_block:
return y
count += 1
return y
elif post_model:
count = 0
y = z
for module in self:
if... | 111 | 111 | 373 | 8 | 103 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | TruncationModule | TruncationModule | 240 | 277 | 240 | 240 | f105482e0158a468a3d0332821c81abb9c38e4f7 | bigcode/the-stack | train |
7c8db1b5c49f5839c568b34e | train | class | class ModulateConvBlock(nn.Module):
"""Implements the convolutional block with style modulation."""
def __init__(self,
resolution,
in_channels,
out_channels,
kernel_size=3,
scale_factor=1,
filtering_kernel=(1,... | class ModulateConvBlock(nn.Module):
| """Implements the convolutional block with style modulation."""
def __init__(self,
resolution,
in_channels,
out_channels,
kernel_size=3,
scale_factor=1,
filtering_kernel=(1, 3, 3, 1),
w_space_... | np.sqrt(2.0)
elif activation_type == 'lrelu':
self.activate = nn.LeakyReLU(negative_slope=0.2, inplace=True)
self.activate_scale = np.sqrt(2.0)
else:
raise NotImplementedError(f'Not implemented activation function: '
f'{activatio... | 256 | 256 | 1,564 | 8 | 247 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | ModulateConvBlock | ModulateConvBlock | 778 | 943 | 778 | 778 | 1126a2d9c7eb71adc63d3e2956776fae93a90cdb | bigcode/the-stack | train |
aadd8cab4c15f409bffbbd52 | train | class | class PixelNormLayer(nn.Module):
"""Implements pixel-wise feature vector normalization layer."""
def __init__(self, dim, epsilon=1e-8):
super().__init__()
self.dim = dim
self.eps = epsilon
def forward(self, x):
norm = torch.sqrt(torch.mean(x ** 2, dim=self.dim, keepdim=True... | class PixelNormLayer(nn.Module):
| """Implements pixel-wise feature vector normalization layer."""
def __init__(self, dim, epsilon=1e-8):
super().__init__()
self.dim = dim
self.eps = epsilon
def forward(self, x):
norm = torch.sqrt(torch.mean(x ** 2, dim=self.dim, keepdim=True) + self.eps)
return x / ... | + 1])
x = (x + residual) / np.sqrt(2.0)
image = self.__getattr__(f'output{layer_idx // 2 + 1}')(
x, w[:, layer_idx + 2])
return image
class PixelNormLayer(nn.Module):
| 64 | 64 | 90 | 7 | 56 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | PixelNormLayer | PixelNormLayer | 600 | 610 | 600 | 600 | 8d5cb9b2f38e7c4f392d78cc689956d8b9638d9d | bigcode/the-stack | train |
b2ab2fd656a4f5c312753cc6 | train | class | class InputBlock(nn.Module):
"""Implements the input block.
Basically, this block starts from a const input, which is with shape
`(channels, init_resolution, init_resolution)`.
"""
def __init__(self, init_resolution, channels):
super().__init__()
self.const = nn.Parameter(
to... | class InputBlock(nn.Module):
| """Implements the input block.
Basically, this block starts from a const input, which is with shape
`(channels, init_resolution, init_resolution)`.
"""
def __init__(self, init_resolution, channels):
super().__init__()
self.const = nn.Parameter(
torch.randn(1, channels, init_r... | x = F.pad(x, self.padding, mode='constant', value=0)
x = F.conv2d(x, self.kernel, stride=1)
x = x.view(-1, channels, x.shape[2], x.shape[3])
return x
class InputBlock(nn.Module):
| 64 | 64 | 112 | 6 | 57 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | InputBlock | InputBlock | 676 | 690 | 676 | 676 | bd7c1c2b1855f9b000b5840ce50c14ec17b3e290 | bigcode/the-stack | train |
86f83f890293f597a305bc43 | train | class | class UpsamplingLayer(nn.Module):
"""Implements the upsampling layer.
This layer can also be used as filtering layer by setting `scale_factor` as 1.
"""
def __init__(self,
scale_factor=2,
kernel=(1, 3, 3, 1),
extra_padding=0,
kernel_gain=... | class UpsamplingLayer(nn.Module):
| """Implements the upsampling layer.
This layer can also be used as filtering layer by setting `scale_factor` as 1.
"""
def __init__(self,
scale_factor=2,
kernel=(1, 3, 3, 1),
extra_padding=0,
kernel_gain=None):
super().__init__()
... | _idx}')(x, w[:, layer_idx])
x = self.__getattr__(f'layer{layer_idx + 1}')(x, w[:, layer_idx + 1])
x = (x + residual) / np.sqrt(2.0)
image = self.__getattr__(f'output{layer_idx // 2 + 1}')(
x, w[:, layer_idx + 2])
return image
cla... | 189 | 189 | 631 | 7 | 181 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | UpsamplingLayer | UpsamplingLayer | 613 | 673 | 613 | 613 | 0d8c39f8904948ff1833c9fa26e25246750e2216 | bigcode/the-stack | train |
c57c0dab8c686f40a2fb7cb1 | train | class | class StyleGAN2GeneratorNet(nn.Module):
"""Defines the generator network in StyleGAN2.
NOTE: the generated images are with `RGB` color channels and range [-1, 1].
"""
def __init__(self,
resolution=1024,
z_space_dim=512,
w_space_dim=512,
i... | class StyleGAN2GeneratorNet(nn.Module):
| """Defines the generator network in StyleGAN2.
NOTE: the generated images are with `RGB` color channels and range [-1, 1].
"""
def __init__(self,
resolution=1024,
z_space_dim=512,
w_space_dim=512,
image_channels=3,
archit... | # python 3.7
"""Contains the implementation of generator described in StyleGAN2.
Different from the official tensorflow version in folder
`stylegan2_tf_official`, this is a simple pytorch version which only contains
the generator part. This class is specially used for inference.
NOTE: Compared to that of StyleGAN, th... | 246 | 256 | 1,353 | 9 | 237 | guanyuelee/DP-LaSE | models/stylegan2_generator_network.py | Python | StyleGAN2GeneratorNet | StyleGAN2GeneratorNet | 35 | 174 | 35 | 35 | 210956b2dfd11444470b7cc4bcce00b8020dfa85 | bigcode/the-stack | train |
a943e47a44b3e0dc144db597 | train | class | class Stager(object):
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Stage 0 - Reverse Shell',
'Author': ['@Cx01N'],
'Description': 'Generates a reverse shell using msfvenom to act as a stage 0.',
'Comments': ['']
}
self.... | class Stager(object):
| def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Stage 0 - Reverse Shell',
'Author': ['@Cx01N'],
'Description': 'Generates a reverse shell using msfvenom to act as a stage 0.',
'Comments': ['']
}
self.options = {
... | from __future__ import print_function
import socket
import threading
import subprocess
from builtins import object
from empire.server.common import helpers
class Stager(object):
| 35 | 225 | 750 | 5 | 29 | joewildiml/Empire | empire/server/stagers/windows/reverseshell.py | Python | Stager | Stager | 11 | 104 | 11 | 12 | 837f9a163cdd5b5930d92d9bf1e0f265a5e4150a | bigcode/the-stack | train |
15fcaa4dfe9f765795719101 | train | class | class Billed(models.Model):
address = models.CharField(max_length=64, blank=True)
acc_no = models.CharField(max_length=32, blank=True)
name = models.CharField(max_length=64, blank=True)
| class Billed(models.Model):
| address = models.CharField(max_length=64, blank=True)
acc_no = models.CharField(max_length=32, blank=True)
name = models.CharField(max_length=64, blank=True)
| Key(User, related_name='user_address', on_delete=models.CASCADE)
address = models.CharField(max_length=64, blank=True)
vat_no = models.CharField(max_length=32, blank=True)
tel_no = models.CharField(max_length=16, blank=True)
class Billed(models.Model):
| 64 | 64 | 50 | 6 | 58 | Wisani90/bidvest | document_processor/models.py | Python | Billed | Billed | 14 | 18 | 14 | 15 | fc56789b1c98f9c84d8edbc5574c2d0d6e22b883 | bigcode/the-stack | train |
3bde4bb11b5de00829facad5 | train | class | class Item(models.Model):
name = models.CharField(max_length=64)
cost = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=7) | class Item(models.Model):
| name = models.CharField(max_length=64)
cost = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=7) | Field(max_length=16, blank=True)
class Billed(models.Model):
address = models.CharField(max_length=64, blank=True)
acc_no = models.CharField(max_length=32, blank=True)
name = models.CharField(max_length=64, blank=True)
class Item(models.Model):
| 63 | 64 | 38 | 5 | 58 | Wisani90/bidvest | document_processor/models.py | Python | Item | Item | 20 | 23 | 20 | 21 | c081810321cfbddff90d54e591ff6c84de52bd0f | bigcode/the-stack | train |
c72a50ff063284e6a7916d21 | train | class | class Profile(models.Model):
user = models.ForeignKey(User, related_name='user_address', on_delete=models.CASCADE)
address = models.CharField(max_length=64, blank=True)
vat_no = models.CharField(max_length=32, blank=True)
tel_no = models.CharField(max_length=16, blank=True)
| class Profile(models.Model):
| user = models.ForeignKey(User, related_name='user_address', on_delete=models.CASCADE)
address = models.CharField(max_length=64, blank=True)
vat_no = models.CharField(max_length=32, blank=True)
tel_no = models.CharField(max_length=16, blank=True)
| from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
| 25 | 64 | 68 | 5 | 20 | Wisani90/bidvest | document_processor/models.py | Python | Profile | Profile | 6 | 11 | 6 | 7 | eeb328acd908781b70644e97358c416c0a6971f6 | bigcode/the-stack | train |
cebbaf28f905b503852f042d | train | function | def chooseWorkdir():
global workdir
try:
workdir = QFileDialog.getExistingDirectory()
except:
print("Файл не выбран!")
| def chooseWorkdir():
| global workdir
try:
workdir = QFileDialog.getExistingDirectory()
except:
print("Файл не выбран!")
| row.addLayout(col2, 80)
win.setLayout(row)
win.show()
workdir = ''
def filter(files, extensions):
result = []
for filename in files:
for ext in extensions:
if filename.endswith(ext):
result.append(filename)
return result
def chooseWorkdir():
| 64 | 64 | 35 | 5 | 58 | LeshaSid/GraphicsEditor | main.py | Python | chooseWorkdir | chooseWorkdir | 54 | 59 | 54 | 54 | 0fd2bcdcd02b28c305237bf5161a0d942eaaf4bc | bigcode/the-stack | train |
b3eecd450df8c62c568ee597 | train | function | def showChosenImage():
if lw_files.currentRow() >= 0:
filename = lw_files.currentItem().text()
workimage.loadImage(workdir, filename)
image_path = os.path.join(workimage.dir, workimage.filename)
workimage.showImage(image_path)
| def showChosenImage():
| if lw_files.currentRow() >= 0:
filename = lw_files.currentItem().text()
workimage.loadImage(workdir, filename)
image_path = os.path.join(workimage.dir, workimage.filename)
workimage.showImage(image_path)
| (image_path)
def do_sharp(self):
self.image = self.image.filter(ImageFilter.SHARPEN)
self.saveImage()
image_path = os.path.join(self.dir, self.save_dir, self.filename)
self.showImage(image_path)
workimage = ImageProcessor()
def showChosenImage():
| 63 | 64 | 59 | 5 | 58 | LeshaSid/GraphicsEditor | main.py | Python | showChosenImage | showChosenImage | 132 | 137 | 132 | 132 | 30b3a22b263cd210a95d11e4af987fc1d34e392d | bigcode/the-stack | train |
f1c191ef65e0a6706986c8c8 | train | class | class ImageProcessor():
def __init__(self):
self.image = None
self.dir = None
self.filename = None
self.save_dir = "Modified/"
def loadImage(self, dir, filename):
self.dir = dir
self.filename = filename
image_path = os.path.join(workdir, filenam... | class ImageProcessor():
| def __init__(self):
self.image = None
self.dir = None
self.filename = None
self.save_dir = "Modified/"
def loadImage(self, dir, filename):
self.dir = dir
self.filename = filename
image_path = os.path.join(workdir, filename)
self.image = ... | []
for filename in files:
for ext in extensions:
if filename.endswith(ext):
result.append(filename)
return result
def chooseWorkdir():
global workdir
try:
workdir = QFileDialog.getExistingDirectory()
except:
print("Файл не выбран!")
... | 135 | 135 | 450 | 4 | 131 | LeshaSid/GraphicsEditor | main.py | Python | ImageProcessor | ImageProcessor | 72 | 128 | 72 | 72 | 82c9d53da2f57540b04d77159fa0784c61c9c8b5 | bigcode/the-stack | train |
77eaa74dd93aab7e50e51c5f | train | function | def showFilenamesList():
extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
chooseWorkdir()
filenames = filter(os.listdir(workdir), extensions)
lw_files.clear()
for filename in filenames:
lw_files.addItem(filename)
| def showFilenamesList():
| extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
chooseWorkdir()
filenames = filter(os.listdir(workdir), extensions)
lw_files.clear()
for filename in filenames:
lw_files.addItem(filename)
| files:
for ext in extensions:
if filename.endswith(ext):
result.append(filename)
return result
def chooseWorkdir():
global workdir
try:
workdir = QFileDialog.getExistingDirectory()
except:
print("Файл не выбран!")
def showFilenamesList():
... | 63 | 64 | 59 | 6 | 57 | LeshaSid/GraphicsEditor | main.py | Python | showFilenamesList | showFilenamesList | 62 | 68 | 62 | 62 | 81e094af079e35d98a9a1862385c16ffe862a617 | bigcode/the-stack | train |
da6f8ad4628edc70687c533f | train | function | def filter(files, extensions):
result = []
for filename in files:
for ext in extensions:
if filename.endswith(ext):
result.append(filename)
return result
| def filter(files, extensions):
| result = []
for filename in files:
for ext in extensions:
if filename.endswith(ext):
result.append(filename)
return result
| .addWidget(btn_flip)
row_tools.addWidget(btn_sharp)
row_tools.addWidget(btn_bw)
col2.addLayout(row_tools)
row.addLayout(col1, 20)
row.addLayout(col2, 80)
win.setLayout(row)
win.show()
workdir = ''
def filter(files, extensions):
| 63 | 64 | 37 | 6 | 57 | LeshaSid/GraphicsEditor | main.py | Python | filter | filter | 46 | 52 | 46 | 46 | 9185fab95008238ec50d8ae52b10451b3d832093 | bigcode/the-stack | train |
011863629c2a00abc939fa8d | train | class | class ECCOBot(MARCImportBot):
''' Class reads Eighteenth Century Collections Online (ECCO) MARC file,
validates and adds/modifies fields, and generates a MARC file for
importing into TIGER.'''
def __init__(self,
marc_file):
'''
Creates instance of bot for creat... | class ECCOBot(MARCImportBot):
| ''' Class reads Eighteenth Century Collections Online (ECCO) MARC file,
validates and adds/modifies fields, and generates a MARC file for
importing into TIGER.'''
def __init__(self,
marc_file):
'''
Creates instance of bot for creating valid MARC record for
... | """
eccobots.py - MARC Bots for ECCO MARC files
"""
__author__ = 'Jeremy Nelson'
from marcbots import MARCImportBot
PROXY_LOCATION = '0-galenet.galegroup.com.tiger.coloradocollege.edu'
class ECCOBot(MARCImportBot):
| 66 | 207 | 693 | 9 | 57 | jermnelson/Discover-Aristotle | aristotle/apps/marc/bots/eccobots.py | Python | ECCOBot | ECCOBot | 10 | 98 | 10 | 10 | e344d5a214ab83fbf460437be39a955791d8986a | bigcode/the-stack | train |
823959fe54c8ce2f6f816b6c | train | class | class InferenceEnginePyTorch:
def __init__(self, checkpoint_path, device,
img_mean=np.array([128, 128, 128], dtype=np.float32),
img_scale=np.float32(1/255)):
from models.with_mobilenet import PoseEstimationWithMobileNet
from modules.load_state import load_state
... | class InferenceEnginePyTorch:
| def __init__(self, checkpoint_path, device,
img_mean=np.array([128, 128, 128], dtype=np.float32),
img_scale=np.float32(1/255)):
from models.with_mobilenet import PoseEstimationWithMobileNet
from modules.load_state import load_state
self.img_mean = img_mean
... | import numpy as np
import torch
class InferenceEnginePyTorch:
| 15 | 101 | 339 | 7 | 7 | antoniolq/lightweight-human-pose-estimation-3d-demo.pytorch | modules/inference_engine_pytorch.py | Python | InferenceEnginePyTorch | InferenceEnginePyTorch | 5 | 39 | 5 | 5 | a84001bdbf33fefd6aa4ba3edb1b2184b21f6aa9 | bigcode/the-stack | train |
6796d259e2eab3bbb02c94f0 | train | class | class Environment(object):
"""A catch reinforcement learning environment.
The implementation considers illegal actions: trying to move the paddle in the
wall direction when next to a wall will incur in an invalid action and an
error will be purposely raised.
"""
def __init__(self, discount=1.0, width=5, h... | class Environment(object):
| """A catch reinforcement learning environment.
The implementation considers illegal actions: trying to move the paddle in the
wall direction when next to a wall will incur in an invalid action and an
error will be purposely raised.
"""
def __init__(self, discount=1.0, width=5, height=10, seed=None):
s... | # Copyright 2019 DeepMind Technologies Ltd. All rights reserved.
#
# 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 appl... | 220 | 256 | 1,175 | 4 | 216 | alexminnaar/open_spiel | open_spiel/python/environments/catch.py | Python | Environment | Environment | 35 | 188 | 35 | 35 | 1b28304a6ca30f4c12cb015bf55694cc4a7388d6 | bigcode/the-stack | train |
83b6e904c90068e1cee5e4a3 | train | class | class Env:
"""Conda environment from a given specification file."""
def __init__(self, env_file, dag, container_img=None, cleanup=None):
self.file = env_file
self.frontend = dag.workflow.conda_frontend
self._env_dir = dag.workflow.persistence.conda_env_path
self._env_archive_d... | class Env:
| """Conda environment from a given specification file."""
def __init__(self, env_file, dag, container_img=None, cleanup=None):
self.file = env_file
self.frontend = dag.workflow.conda_frontend
self._env_dir = dag.workflow.persistence.conda_env_path
self._env_archive_dir = dag.wor... | .version import StrictVersion
import json
from glob import glob
import tarfile
import zipfile
import uuid
from enum import Enum
from snakemake.exceptions import CreateCondaEnvironmentException, WorkflowError
from snakemake.logging import logger
from snakemake.common import strip_prefix, ON_WINDOWS
from snakemake impor... | 256 | 256 | 2,274 | 3 | 253 | GediminasA/snakemake | snakemake/deployment/conda.py | Python | Env | Env | 56 | 372 | 56 | 57 | acbd53a83d6545e2964f983c6f8f82788915c453 | bigcode/the-stack | train |
57460c0082aaad3db60e2dc5 | train | function | def content(env_file):
if env_file.startswith("git+file:"):
return git_content(env_file).encode("utf-8")
elif urlparse(env_file).netloc:
try:
return urlopen(env_file).read()
except URLError as e:
raise WorkflowError(
"Failed to open environment fil... | def content(env_file):
| if env_file.startswith("git+file:"):
return git_content(env_file).encode("utf-8")
elif urlparse(env_file).netloc:
try:
return urlopen(env_file).read()
except URLError as e:
raise WorkflowError(
"Failed to open environment file {}:".format(env_file)... | from snakemake import utils
from snakemake.deployment import singularity
from snakemake.io import git_content
class CondaCleanupMode(Enum):
tarballs = "tarballs"
cache = "cache"
def __str__(self):
return self.value
def content(env_file):
| 64 | 64 | 130 | 5 | 58 | GediminasA/snakemake | snakemake/deployment/conda.py | Python | content | content | 39 | 53 | 39 | 39 | de088ea1c970e58a62133ccc20b233b67b960696 | bigcode/the-stack | train |
cb2b7e135ac76733afbf417c | train | class | class CondaCleanupMode(Enum):
tarballs = "tarballs"
cache = "cache"
def __str__(self):
return self.value
| class CondaCleanupMode(Enum):
| tarballs = "tarballs"
cache = "cache"
def __str__(self):
return self.value
| .exceptions import CreateCondaEnvironmentException, WorkflowError
from snakemake.logging import logger
from snakemake.common import strip_prefix, ON_WINDOWS
from snakemake import utils
from snakemake.deployment import singularity
from snakemake.io import git_content
class CondaCleanupMode(Enum):
| 64 | 64 | 33 | 7 | 56 | GediminasA/snakemake | snakemake/deployment/conda.py | Python | CondaCleanupMode | CondaCleanupMode | 31 | 36 | 31 | 31 | f1d2fcda780566ca7a72505f34d30cfd76f2ad33 | bigcode/the-stack | train |
f2d8e3a01a5f2aacf8d8c6e7 | train | class | class Conda:
instances = dict()
def __new__(cls, container_img=None):
if container_img not in cls.instances:
inst = super().__new__(cls)
inst.__init__(container_img=container_img)
cls.instances[container_img] = inst
return inst
else:
r... | class Conda:
| instances = dict()
def __new__(cls, container_img=None):
if container_img not in cls.instances:
inst = super().__new__(cls)
inst.__init__(container_img=container_img)
cls.instances[container_img] = inst
return inst
else:
return cls.ins... | (
"Environment for {} created (location: {})".format(
os.path.relpath(env_file), os.path.relpath(env_path)
)
)
except subprocess.CalledProcessError as e:
# remove potential partially installed environment
... | 214 | 214 | 716 | 4 | 209 | GediminasA/snakemake | snakemake/deployment/conda.py | Python | Conda | Conda | 375 | 470 | 375 | 375 | ad05055bf0746db790649b9c475a18d897d646f5 | bigcode/the-stack | train |
41224e01ea6f05d3a9ee3cf4 | train | function | def construct(_params,mdp):
return RandomDiscreteAgent(mdp.num_actions()) | def construct(_params,mdp):
| return RandomDiscreteAgent(mdp.num_actions()) | ):
return {}
def output_info(self):
return {}
def call(self, input_dict):
return {"u":np.random.randint(low=0,high=self.num_actions,size=(1,1))}
def initialize_lag_arrays(self):
return {}
def construct(_params,mdp):
| 64 | 64 | 18 | 8 | 56 | sfpd/rlreloaded | control4/agents/random_discrete_agent.py | Python | construct | construct | 24 | 25 | 24 | 24 | 2cffe0011b2de590b4be5461bbf7d0f84e48b848 | bigcode/the-stack | train |
8ce9d420c9b8dec0cd3b33f0 | train | class | class RandomDiscreteAgent(Agent):
def __init__(self,num_actions):
self.num_actions = num_actions
def lag_array_names(self):
return []
def input_info(self):
return {}
def output_info(self):
return {}
def call(self, input_dict):
return {"u":np.random.r... | class RandomDiscreteAgent(Agent):
| def __init__(self,num_actions):
self.num_actions = num_actions
def lag_array_names(self):
return []
def input_info(self):
return {}
def output_info(self):
return {}
def call(self, input_dict):
return {"u":np.random.randint(low=0,high=self.num_actions,... | import numpy as np
from control4.core.agent import Agent
class RandomDiscreteAgent(Agent):
| 20 | 64 | 95 | 7 | 12 | sfpd/rlreloaded | control4/agents/random_discrete_agent.py | Python | RandomDiscreteAgent | RandomDiscreteAgent | 4 | 22 | 4 | 5 | 5933bd204a24aba43f91f115d838180f602704db | bigcode/the-stack | train |
cc425a9b821978d60507ca01 | train | class | class SNDense(tf.keras.layers.Dense):
"""Paper: https://openreview.net/forum?id=B1QRgziT-
source: https://github.com/pfnet-research/sngan_projection
"""
def __init__(self,
units,
activation=None,
use_bias=True,
kernel_initializer='... | class SNDense(tf.keras.layers.Dense):
| """Paper: https://openreview.net/forum?id=B1QRgziT-
source: https://github.com/pfnet-research/sngan_projection
"""
def __init__(self,
units,
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias... | _transpose(x, self.w, output_shape=[b, nh, nw, self.w.shape[-2]],
strides=self.strides, padding=self.padding.upper())
if self.bias is not None:
out += self.bias
return out
def update_wuv(self):
"""
Spectrally Normalized Weigh... | 186 | 188 | 627 | 9 | 177 | DeepTrickLab/Self-Attention-GAN | sagan/layers.py | Python | SNDense | SNDense | 729 | 822 | 729 | 729 | 3797e199fed8c6e52ba1a08b0623dd3837720894 | bigcode/the-stack | train |
4b1d73749f17be4909f5d63d | train | class | class AttentionLayer(layers.Layer):
def __init__(self):
super(AttentionLayer, self).__init__()
def build(self, input_shape):
# to scale attention
self.sigma = self.add_weight(shape=(),
initializer='zero',
trainabl... | class AttentionLayer(layers.Layer):
| def __init__(self):
super(AttentionLayer, self).__init__()
def build(self, input_shape):
# to scale attention
self.sigma = self.add_weight(shape=(),
initializer='zero',
trainable=True,
... | self.update_wuv()
out = tf.matmul(x, self.w)
if self.use_bias:
out += self.bias
return out
def update_wuv(self):
W_mat = tf.reshape(self.w, [self.w.shape[-1], -1])
for _ in range(self.Ip):
self.v = l2normalize(tf.matmul(self.u, W_mat))
... | 146 | 147 | 490 | 7 | 139 | DeepTrickLab/Self-Attention-GAN | sagan/layers.py | Python | AttentionLayer | AttentionLayer | 824 | 872 | 824 | 824 | 22e295f8dd5e864e9b01834e9bf09f93e3f7a913 | bigcode/the-stack | train |
f3139dd2138e5a32e40deeaf | train | class | class SpectralNormalization(tf.keras.layers.Wrapper):
"""This wrapper reparameterizes a layer by decoupling the weight's
magnitude and direction.
This speeds up convergence by improving the
conditioning of the optimization problem.
Weight Normalization: A Simple Reparameterization to Accelerate
... | class SpectralNormalization(tf.keras.layers.Wrapper):
| """This wrapper reparameterizes a layer by decoupling the weight's
magnitude and direction.
This speeds up convergence by improving the
conditioning of the optimization problem.
Weight Normalization: A Simple Reparameterization to Accelerate
Training of Deep Neural Networks: https://arxiv.org/ab... | import tensorflow as tf
from tensorflow.keras import layers
class SpectralNormalization(tf.keras.layers.Wrapper):
| 21 | 256 | 1,722 | 10 | 10 | DeepTrickLab/Self-Attention-GAN | sagan/layers.py | Python | SpectralNormalization | SpectralNormalization | 5 | 210 | 5 | 5 | 3307ffe875339dd431722a15986523cb5ea4665f | bigcode/the-stack | train |
24b8bcea8e571137f2cd003c | train | class | class SNConv2DTranspose(tf.keras.layers.Conv2DTranspose):
"""Paper: https://openreview.net/forum?id=B1QRgziT-
source: https://github.com/pfnet-research/sngan_projection
"""
def __init__(self,
filters,
kernel_size,
strides=(1, 1),
paddi... | class SNConv2DTranspose(tf.keras.layers.Conv2DTranspose):
| """Paper: https://openreview.net/forum?id=B1QRgziT-
source: https://github.com/pfnet-research/sngan_projection
"""
def __init__(self,
filters,
kernel_size,
strides=(1, 1),
padding='valid',
output_padding=None,
... | )
if not self._check_param():
self._make_param()
# @tf.function
def call(self, x, training=None):
"""Applies the convolution layer.
Args:
x (tensor): Input image.
Returns:
tensor: Output of the convolution.
"""
if... | 254 | 256 | 871 | 14 | 240 | DeepTrickLab/Self-Attention-GAN | sagan/layers.py | Python | SNConv2DTranspose | SNConv2DTranspose | 606 | 726 | 606 | 606 | f2e1da28c4a3a0b52a56058c0e12252a49d7f61b | bigcode/the-stack | train |
8f497b731d40e48b254b5730 | train | class | class SNConv2D(tf.keras.layers.Conv2D):
"""Paper: https://openreview.net/forum?id=B1QRgziT-
source: https://github.com/pfnet-research/sngan_projection
"""
def __init__(self,
filters,
kernel_size,
strides=(1, 1),
padding='valid',
... | class SNConv2D(tf.keras.layers.Conv2D):
| """Paper: https://openreview.net/forum?id=B1QRgziT-
source: https://github.com/pfnet-research/sngan_projection
"""
def __init__(self,
filters,
kernel_size,
strides=(1, 1),
padding='valid',
data_format=None,
... | l2normalize(u)
self.v = l2normalize(v)
def build(self, input_shape):
self.module.build(input_shape)
if not self._check_param():
self._make_param()
def call(self, x, training=None):
if training:
self.update_uv()
return self.module.call(x)... | 227 | 227 | 757 | 12 | 215 | DeepTrickLab/Self-Attention-GAN | sagan/layers.py | Python | SNConv2D | SNConv2D | 490 | 603 | 490 | 490 | 84b86b52760848a2a55d1721012b3a7575fa662e | bigcode/the-stack | train |
bc1294e035700ac9820e2e95 | train | function | def _optimal_param(threshold, num_perm, false_positive_weight,
false_negative_weight):
'''
Compute the optimal `MinHashLSH` parameter that minimizes the weighted sum
of probabilities of false positive and false negative.
'''
min_error = float("inf")
opt = (0, 0)
for b in range(1, num... | def _optimal_param(threshold, num_perm, false_positive_weight,
false_negative_weight):
| '''
Compute the optimal `MinHashLSH` parameter that minimizes the weighted sum
of probabilities of false positive and false negative.
'''
min_error = float("inf")
opt = (0, 0)
for b in range(1, num_perm+1):
max_r = int(num_perm / b)
for r in range(1, max_r+1):
fp ... | probability = lambda s : 1 - (1 - (1 - s**float(r))**float(b))
a, err = integrate(_probability, threshold, 1.0)
return a
def _optimal_param(threshold, num_perm, false_positive_weight,
false_negative_weight):
| 64 | 64 | 171 | 19 | 44 | axellos162/datasketch-metabob-trial | datasketch/lsh.py | Python | _optimal_param | _optimal_param | 36 | 53 | 36 | 37 | 67b49152f27d41c3b0e32dffca819fabcc8370a5 | bigcode/the-stack | train |
7dbab47fd963e64c17c4e049 | train | class | class MinHashLSH(object):
'''
The :ref:`minhash_lsh` index.
It supports query with `Jaccard similarity`_ threshold.
Reference: `Chapter 3, Mining of Massive Datasets
<http://www.mmds.org/>`_.
Args:
threshold (float): The Jaccard similarity threshold between 0.0 and
1.0. The ... | class MinHashLSH(object):
| '''
The :ref:`minhash_lsh` index.
It supports query with `Jaccard similarity`_ threshold.
Reference: `Chapter 3, Mining of Massive Datasets
<http://www.mmds.org/>`_.
Args:
threshold (float): The Jaccard similarity threshold between 0.0 and
1.0. The initialized MinHash LSH wi... | , err = integrate(_probability, 0.0, threshold)
return a
def _false_negative_probability(threshold, b, r):
_probability = lambda s : 1 - (1 - (1 - s**float(r))**float(b))
a, err = integrate(_probability, threshold, 1.0)
return a
def _optimal_param(threshold, num_perm, false_positive_weight,
... | 256 | 256 | 2,227 | 7 | 248 | axellos162/datasketch-metabob-trial | datasketch/lsh.py | Python | MinHashLSH | MinHashLSH | 56 | 291 | 56 | 56 | efb85e27ba0316b52188f55cdfc9020c28aa6650 | bigcode/the-stack | train |
3308af4933edbfa06fb56578 | train | function | def _false_positive_probability(threshold, b, r):
_probability = lambda s : 1 - (1 - s**float(r))**float(b)
a, err = integrate(_probability, 0.0, threshold)
return a
| def _false_positive_probability(threshold, b, r):
| _probability = lambda s : 1 - (1 - s**float(r))**float(b)
a, err = integrate(_probability, 0.0, threshold)
return a
| += f(x+0.5*p)*p
x += p
return area, None
try:
from scipy.integrate import quad as integrate
except ImportError:
# For when no scipy installed
integrate = _integration
def _false_positive_probability(threshold, b, r):
| 64 | 64 | 56 | 12 | 51 | axellos162/datasketch-metabob-trial | datasketch/lsh.py | Python | _false_positive_probability | _false_positive_probability | 24 | 27 | 24 | 24 | 81254163e836fc12d2f259afe7deb8562f04ecc3 | bigcode/the-stack | train |
65402c8ef46d924a1d4f5f38 | train | class | class MinHashLSHInsertionSession:
'''Context manager for batch insertion of documents into a MinHashLSH.
'''
def __init__(self, lsh, buffer_size):
self.lsh = lsh
self.lsh.buffer_size = buffer_size
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_t... | class MinHashLSHInsertionSession:
| '''Context manager for batch insertion of documents into a MinHashLSH.
'''
def __init__(self, lsh, buffer_size):
self.lsh = lsh
self.lsh.buffer_size = buffer_size
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def ... | many(*key_set)
for key, Hs in zip(key_set, Hss):
for H, hashtable in zip(Hs, hashtables):
hashtable[H] = key
return [hashtable.itemcounts() for hashtable in hashtables]
class MinHashLSHInsertionSession:
| 67 | 67 | 226 | 8 | 59 | axellos162/datasketch-metabob-trial | datasketch/lsh.py | Python | MinHashLSHInsertionSession | MinHashLSHInsertionSession | 294 | 324 | 294 | 294 | fa2ad5a883c70f0971cdea8ad838e2812dbb3bb9 | bigcode/the-stack | train |
2130bb39276c43153948fdcd | train | function | def _false_negative_probability(threshold, b, r):
_probability = lambda s : 1 - (1 - (1 - s**float(r))**float(b))
a, err = integrate(_probability, threshold, 1.0)
return a
| def _false_negative_probability(threshold, b, r):
| _probability = lambda s : 1 - (1 - (1 - s**float(r))**float(b))
a, err = integrate(_probability, threshold, 1.0)
return a
| _probability(threshold, b, r):
_probability = lambda s : 1 - (1 - s**float(r))**float(b)
a, err = integrate(_probability, 0.0, threshold)
return a
def _false_negative_probability(threshold, b, r):
| 64 | 64 | 59 | 12 | 51 | axellos162/datasketch-metabob-trial | datasketch/lsh.py | Python | _false_negative_probability | _false_negative_probability | 30 | 33 | 30 | 30 | 9379a1c342ef19dc752d853d8d442b2e3063250b | bigcode/the-stack | train |
5ed237d09884bca18d980270 | train | function | def _integration(f, a, b):
p = _integration_precision
area = 0.0
x = a
while x < b:
area += f(x+0.5*p)*p
x += p
return area, None
| def _integration(f, a, b):
| p = _integration_precision
area = 0.0
x = a
while x < b:
area += f(x+0.5*p)*p
x += p
return area, None
| import pickle
import struct
from datasketch.storage import (
ordered_storage, unordered_storage, _random_name)
_integration_precision = 0.001
def _integration(f, a, b):
| 42 | 64 | 59 | 9 | 32 | axellos162/datasketch-metabob-trial | datasketch/lsh.py | Python | _integration | _integration | 8 | 15 | 8 | 8 | 6ef8219640173563cbaddec21197aa6feb761749 | bigcode/the-stack | train |
2c42e04f476015416632c14a | train | class | class StorageManager:
"""
Abstract base class for storage managers. Storage managers need to
support three operations: creating, loading, and deleting storages.
Configuration for storage managers is represented as a dictionary of key
value pairs. The primary key in the dictionary is the `type` defi... | class StorageManager:
| """
Abstract base class for storage managers. Storage managers need to
support three operations: creating, loading, and deleting storages.
Configuration for storage managers is represented as a dictionary of key
value pairs. The primary key in the dictionary is the `type` defining
which storage... | None,
format: Optional[str] = None,
) -> None:
check_gt(len(storage_id), 0, "Invalid storage ID")
self.storage_id = storage_id
self.resources = resources
self.framework = framework
self.format = format
def __json__(self) -> Dict[str, Any]:
return {
... | 256 | 256 | 1,039 | 4 | 252 | ybt195/determined | common/determined_common/storage/base.py | Python | StorageManager | StorageManager | 52 | 167 | 52 | 52 | 42f296badbfec4c257f00d3ed99b6e62cef4c3b6 | bigcode/the-stack | train |
ecdb017bd5b4632d7a00986f | train | class | class StorageMetadata:
def __init__(
self,
storage_id: str,
resources: Dict[str, int],
framework: Optional[str] = None,
format: Optional[str] = None,
) -> None:
check_gt(len(storage_id), 0, "Invalid storage ID")
self.storage_id = storage_id
self.re... | class StorageMetadata:
| def __init__(
self,
storage_id: str,
resources: Dict[str, int],
framework: Optional[str] = None,
format: Optional[str] = None,
) -> None:
check_gt(len(storage_id), 0, "Invalid storage ID")
self.storage_id = storage_id
self.resources = resources
... | import abc
import contextlib
import os
import shutil
import uuid
from typing import Any, Dict, Iterator, Optional, Tuple
from determined_common.check import check_gt, check_not_none, check_true, check_type
class StorageMetadata:
| 51 | 85 | 285 | 4 | 46 | ybt195/determined | common/determined_common/storage/base.py | Python | StorageMetadata | StorageMetadata | 11 | 49 | 11 | 11 | 58295bf3a3dc4235a1aedf8a734fe289cfc641c6 | bigcode/the-stack | train |
96b443304921174ee07e43e7 | train | class | class Test_054_SpiralMatrix(unittest.TestCase):
def test_spiralOrder_1(self):
solution = Solution()
result = solution.spiralOrder([
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
])
print(result)
AssertHelper.assertArray([1,2,3,6,9,8,7,4,5], result)... | class Test_054_SpiralMatrix(unittest.TestCase):
| def test_spiralOrder_1(self):
solution = Solution()
result = solution.spiralOrder([
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
])
print(result)
AssertHelper.assertArray([1,2,3,6,9,8,7,4,5], result)
def test_spiralOrder_2(self):
solu... | import unittest
import sys
sys.path.append('LeetCode/_0051_0100')
sys.path.append('LeetCode.Test')
from _054_SpiralMatrix import Solution
import AssertHelper
class Test_054_SpiralMatrix(unittest.TestCase):
| 55 | 240 | 800 | 12 | 42 | BigEggStudy/LeetCode-Py | LeetCode.Test/_0051_0100/Test_054_SpiralMatrix.py | Python | Test_054_SpiralMatrix | Test_054_SpiralMatrix | 11 | 114 | 11 | 11 | 04ee5a5e08cb192c503e0049c08a6c4556f287c9 | bigcode/the-stack | train |
097c0504de8cbe2020762bfa | train | class | class Activity(Base):
__tablename__ = "activities"
id = Column(Integer, primary_key=True, index=True)
created = Column(DateTime)
category_id = Column(Integer)
recipe_id = Column(Integer)
owner_id = Column(Integer, ForeignKey('users.id'))
| class Activity(Base):
| __tablename__ = "activities"
id = Column(Integer, primary_key=True, index=True)
created = Column(DateTime)
category_id = Column(Integer)
recipe_id = Column(Integer)
owner_id = Column(Integer, ForeignKey('users.id'))
| import datetime
from unicodedata import category
from core.database import Base
from sqlalchemy import (Boolean, Column, Date, DateTime, ForeignKey, Integer,
String)
from sqlalchemy.orm import relationship
class Activity(Base):
| 47 | 64 | 59 | 4 | 42 | jasonvriends/lifetracker-backend | models/activities.py | Python | Activity | Activity | 10 | 17 | 10 | 10 | 483db811f8ad40242e56c2df5ae0dee7c3281317 | bigcode/the-stack | train |
cfd94fbe6f52d45e8b480fbb | train | class | class SpotifyCred(Base):
__tablename__ = 'spotify_creds'
id = db.Column(db.Integer, primary_key=True)
user_id = \
db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
access_token = db.Column(db.String, nullable=False)
refresh_token = db.Column(db.String, nullable=False)
expires_at = db... | class SpotifyCred(Base):
| __tablename__ = 'spotify_creds'
id = db.Column(db.Integer, primary_key=True)
user_id = \
db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
access_token = db.Column(db.String, nullable=False)
refresh_token = db.Column(db.String, nullable=False)
expires_at = db.Column(db.String, nullab... | from . import *
class SpotifyCred(Base):
| 9 | 64 | 187 | 5 | 4 | cuappdev/archives | tempo-api/src/app/tempo/models/spotify_cred.py | Python | SpotifyCred | SpotifyCred | 3 | 21 | 3 | 3 | ec73e01b244b04f8658db1f450202fe4c45d3eae | bigcode/the-stack | train |
946c150d2bd61bab55cb6746 | train | function | @shellcode_reqs(arch = ['i386', 'amd64', 'arm', 'thumb', 'mips'])
def nop(arch = None):
"""Returns a no operation instruction."""
if arch in ['i386', 'amd64']:
return 'nop'
elif arch in ['arm', 'thumb']:
return 'orr r4, r4, r4'
elif arch in ['mips']:
return 'or $ra, $ra, $ra'
| @shellcode_reqs(arch = ['i386', 'amd64', 'arm', 'thumb', 'mips'])
def nop(arch = None):
| """Returns a no operation instruction."""
if arch in ['i386', 'amd64']:
return 'nop'
elif arch in ['arm', 'thumb']:
return 'orr r4, r4, r4'
elif arch in ['mips']:
return 'or $ra, $ra, $ra'
| from pwn.internal.shellcode_helper import shellcode_reqs
@shellcode_reqs(arch = ['i386', 'amd64', 'arm', 'thumb', 'mips'])
def nop(arch = None):
| 46 | 64 | 102 | 33 | 12 | Haabb/pwnfork | pwn/shellcode/misc/nop.py | Python | nop | nop | 3 | 12 | 3 | 4 | c08e8d2c15f7c2326af23e096d2ec7fd09802eaa | bigcode/the-stack | train |
e6931b163787caaf7fd3d936 | train | function | @router.post("/decrypt-share", tags=[TALLY])
def decrypt_share(
request: DecryptTallyShareRequest = Body(...),
scheduler: Scheduler = Depends(get_scheduler),
) -> Any:
"""
Decrypt a single guardian's share of a tally
"""
description = InternalManifest(Manifest.from_json_object(request.descriptio... | @router.post("/decrypt-share", tags=[TALLY])
def decrypt_share(
request: DecryptTallyShareRequest = Body(...),
scheduler: Scheduler = Depends(get_scheduler),
) -> Any:
| """
Decrypt a single guardian's share of a tally
"""
description = InternalManifest(Manifest.from_json_object(request.description))
context = CiphertextElectionContext.from_json_object(request.context)
guardian = to_sdk_guardian(request.guardian)
tally = convert_tally(request.encrypted_tally... | DecryptTallyShareRequest,
)
from ..tags import TALLY
router = APIRouter()
@router.post("/decrypt-share", tags=[TALLY])
def decrypt_share(
request: DecryptTallyShareRequest = Body(...),
scheduler: Scheduler = Depends(get_scheduler),
) -> Any:
| 64 | 64 | 166 | 42 | 22 | QPC-database/electionguard-api-python | app/api/v1/guardian/tally.py | Python | decrypt_share | decrypt_share | 21 | 39 | 21 | 25 | 7a5ad0143e80637a1057392434d87543140d1ee2 | bigcode/the-stack | train |
21d40cc113012a1e8beb4a95 | train | function | def field_code(sti, name):
if sti < 16:
if name < 16:
bytes = [(sti << 4) + name]
else:
bytes = [sti << 4, name]
elif name < 16:
bytes = [name, sti]
else:
bytes = [0, sti, name]
return ''.join(chr(i) for i in bytes)
| def field_code(sti, name):
| if sti < 16:
if name < 16:
bytes = [(sti << 4) + name]
else:
bytes = [sti << 4, name]
elif name < 16:
bytes = [name, sti]
else:
bytes = [0, sti, name]
return ''.join(chr(i) for i in bytes)
| _VECTOR256 = 19
# high level types
# cannot be serialized inside other types
STI_TRANSACTION = 10001
STI_LEDGERENTRY = 10002
STI_VALIDATION = 10003
STI_METADATA = 10004
def field_code(sti, name):
| 64 | 64 | 88 | 8 | 55 | SAN-CHAIN/sand | bin/python/ripple/ledger/SField.py | Python | field_code | field_code | 34 | 44 | 34 | 34 | e5f9862c947099a58d3e45f4055556ebb4fd600e | bigcode/the-stack | train |
6c07da47ed94f8413de902ad | train | class | class RegistrationForm(FlaskForm):
email = StringField('Enter your email address',validators=[Required(),Email()])
username = StringField('Enter your username',validators = [Required()])
password = PasswordField('Password',validators = [Required(), EqualTo('password_confirm',message = 'Passwords must match'... | class RegistrationForm(FlaskForm):
| email = StringField('Enter your email address',validators=[Required(),Email()])
username = StringField('Enter your username',validators = [Required()])
password = PasswordField('Password',validators = [Required(), EqualTo('password_confirm',message = 'Passwords must match')])
password_confirm = Password... | from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,SubmitField, ValidationError, BooleanField
from wtforms.validators import Required,Email,EqualTo
from ..models import User
class RegistrationForm(FlaskForm):
| 53 | 64 | 158 | 8 | 44 | sharonkorir/my-two-cents | app/auth/forms.py | Python | RegistrationForm | RegistrationForm | 6 | 19 | 6 | 6 | 1168fae35686d04936e984fe5865a27f16a31473 | bigcode/the-stack | train |
a767ad7fa9e57925f151a821 | train | class | class LoginForm(FlaskForm):
email = StringField('Your Email Address',validators=[Required(),Email()])
password = PasswordField('Password',validators =[Required()])
remember = BooleanField('Remember me')
submit = SubmitField('Sign In') | class LoginForm(FlaskForm):
| email = StringField('Your Email Address',validators=[Required(),Email()])
password = PasswordField('Password',validators =[Required()])
remember = BooleanField('Remember me')
submit = SubmitField('Sign In') | .query.filter_by(email =data_field.data).first():
raise ValidationError('There is an account with that email')
def validate_username(self,data_field):
if User.query.filter_by(username = data_field.data).first():
raise ValidationError('That username is taken')
class LoginForm(FlaskFo... | 64 | 64 | 54 | 8 | 56 | sharonkorir/my-two-cents | app/auth/forms.py | Python | LoginForm | LoginForm | 21 | 25 | 21 | 21 | a4096fcfa5f69f698946e2ecee2d8b4f6a4ff62a | bigcode/the-stack | train |
ab07c37ef1a40d32e79ae67d | train | function | def transcode_lccs3_classes(xml_text):
doc = etree.fromstring(xml_text)
lc_classes = doc.findall('elements/LC_LandCoverClass', namespaces)
classes_list = []
for lc_class in lc_classes:
class_dd = {}
class_dd['name'] = lc_class.find('./name').text
class_dd['map_code'] = lc_class.f... | def transcode_lccs3_classes(xml_text):
| doc = etree.fromstring(xml_text)
lc_classes = doc.findall('elements/LC_LandCoverClass', namespaces)
classes_list = []
for lc_class in lc_classes:
class_dd = {}
class_dd['name'] = lc_class.find('./name').text
class_dd['map_code'] = lc_class.find('./map_code').text
class_dd... | import re
import os
import sys
import copy
import lxml
from lxml import etree
from lxml import objectify
import pprint
from pdb import set_trace as _breakpoint
IGNORED_PROPS_LIST = ['name', 'description', 'elements',]
namespaces = {'xs':'http://www.w3.org/2001/XMLSchema',
"re": "http://exslt.org/regular-expressions"... | 102 | 214 | 715 | 11 | 91 | cnr-stiima-vci/LCMLUtils | lcmlutils/views/transcoding.py | Python | transcode_lccs3_classes | transcode_lccs3_classes | 18 | 83 | 18 | 18 | 2aca0e9191c69daec227a778001d399fc8bc695d | bigcode/the-stack | train |
a3360e516242dac0e584d3df | train | class | class Pool:
def __init__(self, procs):
self.procs = procs
if self.procs is None:
self.p = None
else:
self.p = multiprocessing.Pool(procs, init_func, maxtasksperchild=1)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
... | class Pool:
| def __init__(self, procs):
self.procs = procs
if self.procs is None:
self.p = None
else:
self.p = multiprocessing.Pool(procs, init_func, maxtasksperchild=1)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self... | This is a slightly more resilient version of multiprocessing pool when dealing
with keyboard interrupts.
It currently implements map and apply.
setting the number of processes to None makes this single threaded
'''
import multiprocessing
import signal
def init_func():
signal.signal(signal.SIGINT, signal.SIG_IGN... | 64 | 64 | 211 | 3 | 61 | dwhalen/holophrasm | withpool.py | Python | Pool | Pool | 16 | 43 | 16 | 16 | fa6ecf444c5efc8509f398867be740d9b90bca95 | bigcode/the-stack | train |
d967ffb7b27c92f96814bb80 | train | function | def init_func():
signal.signal(signal.SIGINT, signal.SIG_IGN)
| def init_func():
| signal.signal(signal.SIGINT, signal.SIG_IGN)
| '''
This is a slightly more resilient version of multiprocessing pool when dealing
with keyboard interrupts.
It currently implements map and apply.
setting the number of processes to None makes this single threaded
'''
import multiprocessing
import signal
def init_func():
| 48 | 64 | 18 | 4 | 43 | dwhalen/holophrasm | withpool.py | Python | init_func | init_func | 13 | 14 | 13 | 13 | eefc32c37e3781e8e859462352857c17b55ccb13 | bigcode/the-stack | train |
7f10a0d94dbadf745e5eb20f | train | class | class Rate(Command):
name = "ставка"
name_tg = 'rate'
help_text = "игра, определяющая, кто ближе угадал загаданное число"
help_texts = ["[ставка=рандом] - делает ставку"]
help_texts_extra = "Ставка может быть от 1 до 100"
int_args = [0]
conversation = True
platforms = [Platform.VK, Pla... | class Rate(Command):
| name = "ставка"
name_tg = 'rate'
help_text = "игра, определяющая, кто ближе угадал загаданное число"
help_texts = ["[ставка=рандом] - делает ставку"]
help_texts_extra = "Ставка может быть от 1 до 100"
int_args = [0]
conversation = True
platforms = [Platform.VK, Platform.TG]
access ... | from threading import Lock
from apps.bot.classes.Command import Command
from apps.bot.classes.consts.Consts import Platform, Role
from apps.bot.classes.consts.Exceptions import PWarning
from apps.bot.models import Profile
from apps.bot.utils.utils import random_event
from apps.games.models import Rate as RateModel
lo... | 71 | 191 | 639 | 4 | 67 | Xoma163/Petrovich | apps/bot/commands/Games/Rate.py | Python | Rate | Rate | 13 | 74 | 13 | 13 | 3b1ed31bbf29f5c8d9a783926727132ea8317804 | bigcode/the-stack | train |
0f96ab941be8af90d97c2404 | train | class | class QType(object):
""" Node in QOM type tree """
def __init__(self, name,
parent = None,
children = None,
macros = None,
arches = None
):
self.name = name
# name: reference
self.children = children if children else {}
for... | class QType(object):
| """ Node in QOM type tree """
def __init__(self, name,
parent = None,
children = None,
macros = None,
arches = None
):
self.name = name
# name: reference
self.children = children if children else {}
for c in self.children.v... | from .qemu_watcher import (
QOMTreeReverser
)
from debug import (
create_dwarf_cache,
Runtime,
GitLineVersionAdapter
)
from common import (
pypath,
co_find_eq
)
from os.path import (
join
)
from subprocess import (
Popen
)
# use ours pyrsp
with pypath("..pyrsp"):
from pyrsp.rsp impor... | 125 | 125 | 419 | 5 | 120 | ispras/qdt | qemu/qom_hierarchy.py | Python | QType | QType | 34 | 103 | 34 | 34 | 5fdfe8e4719af436ca73b978a5bc9ee4ef41735d | bigcode/the-stack | train |
a0f8f60c25dbd6bd17932a4a | train | function | def co_fill_children(qomtr_node, qtype_node, arch):
for c in qomtr_node.children:
name = c.name
if name in qtype_node.children:
# Node already exists.
# We only need to add the new CPU arch
qt = qtype_node.children[name]
else:
qt = QType(name)
... | def co_fill_children(qomtr_node, qtype_node, arch):
| for c in qomtr_node.children:
name = c.name
if name in qtype_node.children:
# Node already exists.
# We only need to add the new CPU arch
qt = qtype_node.children[name]
else:
qt = QType(name)
qtype_node.add_child(qt)
qt.arc... | be serialized first
__pygen_deps__ = ("children",)
def __gen_code__(self, gen):
gen.reset_gen(self)
gen.gen_args(self, skip_kw = ["parent"])
gen.gen_end()
def co_fill_children(qomtr_node, qtype_node, arch):
| 64 | 64 | 105 | 15 | 49 | ispras/qdt | qemu/qom_hierarchy.py | Python | co_fill_children | co_fill_children | 106 | 119 | 106 | 106 | 6cda12d53e3b882ba43b956ea63f1164b6f2640b | bigcode/the-stack | train |
c63e383113e9a69fccfedfb4 | train | function | def co_update_device_tree(qemu_exec, src_path, arch_name, root):
dic = create_dwarf_cache(qemu_exec)
gvl_adptr = GitLineVersionAdapter(src_path)
qomtr = QOMTreeReverser(dic,
interrupt = True,
verbose = True,
line_adapter = gvl_adptr
)
# Update GLV adapter cache now to use ... | def co_update_device_tree(qemu_exec, src_path, arch_name, root):
| dic = create_dwarf_cache(qemu_exec)
gvl_adptr = GitLineVersionAdapter(src_path)
qomtr = QOMTreeReverser(dic,
interrupt = True,
verbose = True,
line_adapter = gvl_adptr
)
# Update GLV adapter cache now to use it during next device tree updating.
yield True
gvl_adpt... | .name
if name in qtype_node.children:
# Node already exists.
# We only need to add the new CPU arch
qt = qtype_node.children[name]
else:
qt = QType(name)
qtype_node.add_child(qt)
qt.arches.add(arch)
yield co_fill_children(c, q... | 93 | 93 | 310 | 17 | 76 | ispras/qdt | qemu/qom_hierarchy.py | Python | co_update_device_tree | co_update_device_tree | 122 | 165 | 122 | 122 | b5d285506d7469ab261f5bac85041a85e509e8a8 | bigcode/the-stack | train |
2435680ee05e33e5460af5b8 | train | class | class PyBertData:
"""
PyBERT simulation results data encapsulation class.
This class is used to encapsulate that subset of the results
data for a PyBERT instance, which is to be saved when the user
clicks the "Save Results" button.
"""
_item_names = [
"chnl_h",
"tx_out_h",
... | class PyBertData:
| """
PyBERT simulation results data encapsulation class.
This class is used to encapsulate that subset of the results
data for a PyBERT instance, which is to be saved when the user
clicks the "Save Results" button.
"""
_item_names = [
"chnl_h",
"tx_out_h",
"ctle_out_... | 2017
This Python script provides a data structure for encapsulating the
simulation results data of a PyBERT instance. It was first
created, as a way to facilitate easier pickling, so that a particular
result could be saved and later restored, as a reference waveform.
Copyright (c) 2017 by David Banas; All rights rese... | 92 | 92 | 307 | 6 | 85 | mgielda/PyBERT | pybert/pybert_data.py | Python | PyBertData | PyBertData | 18 | 65 | 18 | 18 | 2464e1682db236f3c439d3bbf43fc50c0e55a25b | bigcode/the-stack | train |
088f09bae2d2b930b83697d1 | train | function | def preprocess_data(train,test):
id_test=test['patient_id']
train=train.drop(['patient_id'],axis=1)
test=test.drop(['patient_id'],axis=1)
train=train.drop_duplicates()
y=train['is_screener']
train=train.drop(['is_screener'],axis=1)
#train=train.drop(['activity_month','primary_physician_role... | def preprocess_data(train,test):
| id_test=test['patient_id']
train=train.drop(['patient_id'],axis=1)
test=test.drop(['patient_id'],axis=1)
train=train.drop_duplicates()
y=train['is_screener']
train=train.drop(['is_screener'],axis=1)
#train=train.drop(['activity_month','primary_physician_role','practitioner_id_y'],axis=1)
... | )
train=pd.merge(train,train_pract_screen_ratio, on='patient_id',how='left')
test=pd.merge(test,test_pract_screen_ratio, on='patient_id',how='left')
print('after merging pract_screen_ratio')
print(train.shape,test.shape)
###############################################################################################
d... | 63 | 64 | 194 | 6 | 57 | Ravirajadrangi/projects6 | cervical-cancer-screening/models/src/RFonfeatures.py | Python | preprocess_data | preprocess_data | 95 | 112 | 95 | 96 | 87248f2f864b1f0b20804b69367cf23bea6356f9 | bigcode/the-stack | train |
37c4e95d3e8112cccc265ec5 | train | function | def archive_results(filename,results,algo,script):
"""
:type algo: basestring
:type script: basestring
:type results: DataFrame
"""
#assert results == pd.DataFrame
now=time.localtime()[0:5]
dirname='../archive'
subdirfmt='%4d-%02d-%02d-%02d-%02d'
subdir=subdirfmt %now
if not ... | def archive_results(filename,results,algo,script):
| """
:type algo: basestring
:type script: basestring
:type results: DataFrame
"""
#assert results == pd.DataFrame
now=time.localtime()[0:5]
dirname='../archive'
subdirfmt='%4d-%02d-%02d-%02d-%02d'
subdir=subdirfmt %now
if not os.path.exists(os.path.join(dirname,str(algo))):
... | from __future__ import print_function
import os
import pandas as pd
import xgboost as xgb
import time
import shutil
from sklearn import preprocessing
from sklearn.cross_validation import train_test_split
import numpy as np
def archive_results(filename,results,algo,script):
| 60 | 64 | 181 | 11 | 48 | Ravirajadrangi/projects6 | cervical-cancer-screening/models/src/RFonfeatures.py | Python | archive_results | archive_results | 12 | 33 | 12 | 12 | ec94a4799f13f60d83d5dda9c9615db0a92cc504 | bigcode/the-stack | train |
8c2f2c455396dfade16cc1e0 | train | class | class Poly():
def __init__(self) -> None:
self.functions = {}
def get_default_args(_, func):
signature = inspect.signature(func)
return {
k: v.default
for k, v in signature.parameters.items()
if v.default is not inspect.Parameter.empty
}
... | class Poly():
| def __init__(self) -> None:
self.functions = {}
def get_default_args(_, func):
signature = inspect.signature(func)
return {
k: v.default
for k, v in signature.parameters.items()
if v.default is not inspect.Parameter.empty
}
def poly_wrapp... | import inspect
from typing import Callable
from python_polymorphism.lib.types import PolyFunc, PolyMethodArgumentsException
class Poly():
| 27 | 81 | 271 | 3 | 23 | KiraPC/python-polymorphism | python_polymorphism/lib/poly.py | Python | Poly | Poly | 5 | 46 | 5 | 5 | e109ad36df25e98ffa94655e520ef6aa81a21061 | bigcode/the-stack | train |
ae69b4cf25497765a7a409a0 | train | function | def make_circuit(n:int) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0]) # number=1
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.cx(input_qubit[0],input_qubit[2]) # number=9
pro... | def make_circuit(n:int) -> QuantumCircuit:
# circuit begin
| input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0]) # number=1
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.cx(input_qubit[0],input_qubit[2]) # number=9
prog.x(input_qubit[2]) # number=10
prog.cx(input_qubit[0],inpu... | Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'... | 94 | 94 | 315 | 16 | 78 | UCLA-SEAL/QDiff | data/p4VQE/R4/benchmark/startQiskit_Class484.py | Python | make_circuit | make_circuit | 18 | 48 | 18 | 19 | bf2b3e899a71b929fb18d8c74a8a86ebdfd21271 | bigcode/the-stack | train |
14c5ce888887332c7adeb0c8 | train | class | class ExportRepositoryManager( object ):
def __init__( self, app, user, tool_shed_url, repository, changeset_revision, export_repository_dependencies, using_api ):
self.app = app
self.capsule_filename = 'capsule'
self.capsule_with_dependencies_filename = 'capsule_with_dependencies'
... | class ExportRepositoryManager( object ):
| def __init__( self, app, user, tool_shed_url, repository, changeset_revision, export_repository_dependencies, using_api ):
self.app = app
self.capsule_filename = 'capsule'
self.capsule_with_dependencies_filename = 'capsule_with_dependencies'
self.changeset_revision = changeset_revisi... | import contextlib
import logging
import os
import shutil
import tarfile
import tempfile
import threading
from time import gmtime, strftime
from six.moves.urllib.request import urlopen
from sqlalchemy import and_, false
import tool_shed.repository_types.util as rt_util
from galaxy import web
from galaxy.util import as... | 224 | 256 | 3,884 | 8 | 216 | ramezrawas/galaxy-1 | lib/tool_shed/capsule/capsule_manager.py | Python | ExportRepositoryManager | ExportRepositoryManager | 33 | 377 | 33 | 34 | 7d6ed788a2c168c1e778a70db82fffcb759efa3c | bigcode/the-stack | train |
4f0e143fb56ae6681b360b1b | train | class | class ExportedRepositoryRegistry( object ):
def __init__( self ):
self.exported_repository_elems = []
| class ExportedRepositoryRegistry( object ):
| def __init__( self ):
self.exported_repository_elems = []
| hed.metadata import repository_metadata_manager
from tool_shed.util import (basic_util, commit_util, common_util, encoding_util,
hg_util, metadata_util, repository_util, shed_util_common as suc, xml_util)
log = logging.getLogger( __name__ )
class ExportedRepositoryRegistry( object ):
| 64 | 64 | 25 | 9 | 55 | ramezrawas/galaxy-1 | lib/tool_shed/capsule/capsule_manager.py | Python | ExportedRepositoryRegistry | ExportedRepositoryRegistry | 27 | 30 | 27 | 28 | 66c3671b34a4d2f7735d8c38ae0c00d13514ae4b | bigcode/the-stack | train |
7a45400cba9984f6d31622bd | train | class | class ImportRepositoryManager( object ):
def __init__( self, app, host, user, user_is_admin ):
self.app = app
self.host = host
self.user = user
self.user_is_admin = user_is_admin
def check_status_and_reset_downloadable( self, import_results_tups ):
"""Check the status o... | class ImportRepositoryManager( object ):
| def __init__( self, app, host, user, user_is_admin ):
self.app = app
self.host = host
self.user = user
self.user_is_admin = user_is_admin
def check_status_and_reset_downloadable( self, import_results_tups ):
"""Check the status of each imported repository and set downloa... | repo_info_dict )
if repository and changeset_revision:
ordered_repository_ids.append( repository_id )
ordered_repositories.append( repository )
ordered_changeset_revisions.append( changeset_revision )
# Process the repository associate... | 256 | 256 | 5,897 | 8 | 248 | ramezrawas/galaxy-1 | lib/tool_shed/capsule/capsule_manager.py | Python | ImportRepositoryManager | ImportRepositoryManager | 380 | 932 | 380 | 381 | 482638e6e7aeca1eb58655307da1e9e7d764b70b | bigcode/the-stack | train |
8d0f0f82a1ac68b004d0f215 | train | class | class QuicksightMigrationStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
self.current_dir = os.path.dirname(__file__)
self.bucket = s3.Bucket(
self, "qs-migration-bucket",
bucket_name=f'q... | class QuicksightMigrationStack(core.Stack):
| def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
self.current_dir = os.path.dirname(__file__)
self.bucket = s3.Bucket(
self, "qs-migration-bucket",
bucket_name=f'quicksight-migration-{core.Aws.ACCOUNT_ID}',
... | import os
from aws_cdk import (
aws_apigateway as apigw,
aws_lambda as _lambda,
aws_lambda_event_sources as event_sources,
aws_iam as iam,
aws_s3 as s3,
aws_sqs as sqs,
core
)
from aws_solutions_constructs.aws_apigateway_sqs import (
ApiGatewayToSqs,
ApiGatewayToSqsProps
)
class Qui... | 101 | 256 | 1,345 | 9 | 92 | yingliao422/amazon-quicksight-sdk-proserve | Migration-scripts/cdk/cdk/quicksight_migration_stack.py | Python | QuicksightMigrationStack | QuicksightMigrationStack | 17 | 201 | 17 | 18 | d2bacd0ddbb09f3b99ddbdd9649fe029125cc114 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.