code stringlengths 101 5.91M |
|---|
def _network(proto, default_context, batch_size, all_variables, rng):
network = Network()
network.name = proto.name
network.repeat_info = {}
for r in proto.repeat_info:
network.repeat_info[r.id] = r.times
network.variables = OrderedDict()
if (batch_size is None):
network.batch_si... |
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, target):
dst = []
for t in self.transforms:
dst.append(t(target))
return dst |
def set_color_by_material(mat_color: ti.types.ndarray()):
for i in range(n_particles):
mat = F_materials[i]
F_colors[i] = ti.Vector([mat_color[(mat, 0)], mat_color[(mat, 1)], mat_color[(mat, 2)], 1.0]) |
def get_update(x):
for z in x.split('-'):
if ('update=' in z):
return z.replace('update=', '') |
def encode_prompt(prompt_instructions, classification=False):
if classification:
prompt = 'Come up with a series of classification tasks. Try to specify the possible output labels when possible.\n'
else:
prompt = 'Come up with a series of tasks:\n'
for (idx, instruction) in enumerate(prompt_... |
class AllBuilder():
def __getattr__(self, attr):
from functools import partial
return partial(self._wrapper, attr)
def _wrapper(self, name, *args, **kwds):
start = time.time()
docs = self.get_all_documents()
refs = [x for x in docs if x.endswith('reference')]
othe... |
class BPRSlimModel(object):
def __init__(self, data, num_users, num_items, lr, lj_reg, li_reg, sampler, random_seed=42):
self._data = data
self._num_users = num_users
self._num_items = num_items
self._sp_i_train_ratings = self._data.sp_i_train_ratings
self._lr = lr
se... |
def meta_learning_loss(player):
episode_loss = torch.tensor(0)
with torch.cuda.device(player.gpu_id):
episode_loss = episode_loss.cuda()
for i in player.meta_learning_actions:
step_optimal_action = torch.tensor(player.meta_learning_actions[i]).reshape([1]).long()
with torch.cuda.devi... |
class SingleImageDataset(BaseDataset):
def __init__(self, opt):
BaseDataset.__init__(self, opt)
self.dir_A = os.path.join(opt.dataroot, 'trainA')
self.dir_B = os.path.join(opt.dataroot, 'trainB')
if (os.path.exists(self.dir_A) and os.path.exists(self.dir_B)):
self.A_paths... |
def context_decoder_fn_train(encoder_state, context_vector, name=None):
with ops.name_scope(name, 'simple_decoder_fn_train', [encoder_state]):
pass
def decoder_fn(time, cell_state, cell_input, cell_output, context_state):
with ops.name_scope(name, 'simple_decoder_fn_train', [time, cell_state, ce... |
def hirose(input: Tensor, m_sqaure: float=1):
mag_input = torch.abs(input)
return (F.tanh((mag_input / m_sqaure)) * (input / mag_input)) |
def normal_(tensor: Tensor, mean: float=0.0, std: float=1.0) -> Tensor:
return _no_grad_normal_(tensor, mean, std) |
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--data-path', type=str, required=True, help='Path to raw data')
parser.add_argument('--output-path', type=str, required=True, help='Path to save data')
parser.add_argument('--n-jobs', type=int, default=20, required=False, hel... |
class AlgoTrainer(BaseAlgo):
def __init__(self, algo_init, args):
super(AlgoTrainer, self).__init__(args)
self.bcs = algo_init['bcs']['net']
self.bcs_opt = algo_init['bcs']['opt']
self.rews = algo_init['rews']['net']
self.rews_opt = algo_init['rews']['opt']
self.vae =... |
def create_attn(attn_type, channels, **kwargs):
module_cls = None
if (attn_type is not None):
if isinstance(attn_type, str):
attn_type = attn_type.lower()
if (attn_type == 'se'):
module_cls = SEModule
elif (attn_type == 'ese'):
module_c... |
def register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter< ns3::SystemThread > > const &', 'o')])
return |
.parametrize('op, ctx, func_name', list_ctx_and_func_name(['max', 'min']))
def test_max_min_int64_add_scalar(op, ctx, func_name):
expected = {'max': [100.0], 'min': [1.0]}
nn.set_default_context(ctx)
nn.set_auto_forward(True)
x = nn.Variable((1, 100))
x.d = range(100)
func = getattr(F, op)
i... |
def prepare_nlc_data(data_dir, max_vocabulary_size, tokenizer=char_tokenizer, other_dev_path=None):
train_path = get_nlc_train_set(data_dir)
if (other_dev_path is None):
dev_path = get_nlc_dev_set(data_dir)
else:
dev_path = get_nlc_dev_set(other_dev_path)
vocab_path = os.path.join(data_d... |
def test_bipartite_change_stats_inouye():
print('testing bipartrite change stats on Inouye-Pyke example...')
start = time.time()
g = BipartiteGraph('../examples/data/bipartite/Inouye_Pyke_pollinator_web/inouye_bipartite.net')
assert (g.numNodes() == 133)
assert (g.numEdges() == 281)
assert (len(... |
def _get_init_fn(checkpoint_path, ignore_missing_vars):
if (checkpoint_path is None):
return None
variables_to_restore = slim.get_variables_to_restore()[1:]
for v in variables_to_restore:
print(v)
if tf.gfile.IsDirectory(checkpoint_path):
checkpoint_path = tf.train.latest_checkpo... |
def gap_workspace_file(system='gap', name='workspace', dir=None):
if (dir is None):
dir = os.path.join(DOT_SAGE, 'gap')
data = f'{GAP_ROOT_PATHS}'
for path in GAP_ROOT_PATHS.split(';'):
if (not path):
continue
sysinfo = os.path.join(path, 'sysinfo.gap')
if os.path... |
class IndexedFreeGroup(IndexedGroup, Group):
def __init__(self, indices, prefix, category=None, **kwds):
category = Groups().or_subcategory(category)
IndexedGroup.__init__(self, indices, prefix, category, **kwds)
def _repr_(self):
return 'Free group indexed by {}'.format(self._indices)
... |
def CalculateCompositionNormalizedVDWV(ProteinSequence):
result = CalculateComposition(ProteinSequence, _NormalizedVDWV, '_NormalizedVDWV')
return result |
def validate_ean(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(ean.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
class ProxyAlreadyVisited(object):
def __init__(self, rep):
self._rep = rep
def __repr__(self):
return self._rep |
def makeNewUserDir(username):
if invalidUsername(username):
print('Usernames cannot contain invalid characters')
return False
try:
raisePrivileges()
os.mkdir(('/home/' + username))
lowerPrivileges()
except OSError:
print(('Unable to create new user directory f... |
def write_conll(doc: Doc, clusters: List[List[Span]], f_obj: TextIO):
placeholder = (' -' * 7)
doc_id = doc['document_id']
words = doc['cased_words']
part_id = doc['part_id']
sents = doc['sent_id']
max_word_len = max((len(w) for w in words))
starts = defaultdict((lambda : []))
ends = de... |
def get_zip_manifest(zip_path: Path, zip_root: Optional[Path]=None):
_zip_path = (zip_path if (zip_root is None) else Path.joinpath(zip_root, zip_path))
with zipfile.ZipFile(_zip_path, mode='r') as f:
info = f.infolist()
manifest = {}
for i in tqdm(info):
utt_id = Path(i.filename).stem
... |
def test_control_bfgs_multiple(ocp):
ocp.solve(algorithm='bfgs', rtol=0.01, atol=0.0, max_iter=11)
assert (ocp.solver.relative_norm <= ocp.solver.rtol) |
def get_ebm(**model_cfg):
model_cfg = copy.deepcopy(model_cfg)
if ('arch' in model_cfg):
model_cfg.pop('arch')
in_dim = model_cfg['x_dim']
model_cfg.pop('x_dim')
net = get_net(in_dim=in_dim, out_dim=1, **model_cfg['net'])
model_cfg.pop('net')
return EnergyBasedModel(net, **model_cfg) |
class ValidationLogAdapter(GaugeAdapter):
re_log_line = re.compile('^(?:.*: )?([\\w\\.]+)( [\\w\\.]+)?: iterations=([0-9]+) runtime: ([0-9]+)([mu])s success: (true|false)')
re_actors = re.compile('^\\[Total\\]\\s+A#([0-9]+)\\s+M#([0-9]+)\\s+P#([0-9]+)')
re_NPB_partial_invalid = re.compile('.*Failed.*verific... |
class ParamHistoryManagerBase():
def filter(self, param_grid: List[Dict[(str, Any)]]) -> Iterable[Dict]:
pass |
class FlaxGPT2Model(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def AB2(u0, u1, rhs, dt, tstep, solver, context):
rhs = solver.ComputeRHS(rhs, u0, solver, **context)
if (tstep == 0):
u0 += (rhs * dt)
else:
u0 += (((1.5 * rhs) * dt) - (0.5 * u1))
u1[:] = (rhs * dt)
return (u0, dt, dt) |
def run_method(idx, args, file, method):
if (method == 'sf'):
graph = process_file_karate(file)
result = sf(graph, args['n_eigen'])
elif (method == 'ldp'):
subgraphs = process_file_karate(file)
result = ldp(subgraphs)
elif (method == 'fgsd'):
graph = process_file_kara... |
def profile_kv(scopename):
logkey = ('wait_' + scopename)
tstart = time.time()
try:
(yield)
finally:
get_current().name2val[logkey] += (time.time() - tstart) |
class LayerNormMLP(nn.Module):
hidden_dims: Sequence[int]
activations: Callable[([jnp.ndarray], jnp.ndarray)] = nn.gelu
activate_final: int = False
kernel_init: Callable[([PRNGKey, Shape, Dtype], Array)] = default_init()
def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
for (i, size) in enu... |
def train(train_loader, model, optimizer, epoch, save_path):
global step
model.train()
loss_all = 0
epoch_step = 0
try:
for (i, (images, gts, depths)) in enumerate(train_loader, start=1):
optimizer.zero_grad()
images = images.cuda()
gts = gts.cuda()
... |
class Recon3(Problem):
def __init__(self):
G = nx.DiGraph()
G.add_node(0, label='0', pos=((- 2), 0))
G.add_node(1, label='1', pos=((- 1), 0.5))
G.add_node(2, label='2', pos=((- 1), (- 0.5)))
G.add_node(3, label='3', pos=(0, 0.5))
G.add_node(4, label='4', pos=(0, (- 0.... |
class ProGenConfig(PretrainedConfig):
model_type = 'progen'
def __init__(self, vocab_size=50400, n_positions=2048, n_ctx=2048, n_embd=4096, n_layer=28, n_head=16, rotary_dim=64, n_inner=None, activation_function='gelu_new', resid_pdrop=0.0, embd_pdrop=0.0, attn_pdrop=0.0, layer_norm_epsilon=1e-05, initializer_r... |
def shape(tensor, dim=None):
if (dim is None):
return tensor.shape.as_list()
else:
return tensor.shape.as_list()[dim] |
def self_convert(wav, vocoder):
mel = preprocess(wav)
c = mel.transpose((- 1), (- 2)).squeeze()
with torch.no_grad():
recon_hifi = vocoder.inference(c)
recon_hifi = recon_hifi.view((- 1)).cpu().numpy()
return recon_hifi |
_cache(maxsize=200)
def _read_leapfile(ls_fpath):
f = open(ls_fpath, 'r')
jd = []
offset = []
for line in f:
a = line.split()
jd.append(float(a[4]))
offset.append(float(a[6]))
f.close()
return (jd, offset) |
class BERTFilter(object):
def __init__(self, data_file):
self.processor = DataProcessor(data_file)
self.device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
self.label_list = self.processor.get_labels()
bert_config = BertConfig.from_pretrained('bert-base-uncased', ... |
class ResnetStack(nn.Module):
num_ch: int
num_blocks: int
use_max_pooling: bool = True
def __call__(self, observations: jnp.ndarray) -> jnp.ndarray:
initializer = nn.initializers.xavier_uniform()
conv_out = nn.Conv(features=self.num_ch, kernel_size=(3, 3), strides=1, kernel_init=initiali... |
def from_inversion_vector(iv, parent=None):
p = iv[:]
open_spots = list(range(len(iv)))
for (i, ivi) in enumerate(iv):
p[open_spots.pop(ivi)] = (i + 1)
if (parent is None):
parent = Permutations()
return parent(p) |
class SmoothL1Criterion(Criterion):
def __init__(self, sizeAverage=True):
super(SmoothL1Criterion, self).__init__()
self.sizeAverage = sizeAverage
self.output_tensor = None
def updateOutput(self, input, target):
if (self.output_tensor is None):
self.output_tensor = in... |
def settings_logreg(key):
assert (key in ['mnist', '20news', 'adult'])
if (key == 'mnist'):
module = MnistModule()
module.append_one = False
(n_tr, n_val, n_test) = (200, 200, 200)
(lr, decay, num_epoch, batch_size) = (0.1, True, 5, 5)
return (module, (n_tr, n_val, n_test... |
def setup_loggers(filename, quiet):
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=filename, filemode='w')
if (not quiet):
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatt... |
def get_default_config():
cfg = CN()
cfg.model = CN()
cfg.model.name = 'resnet50'
cfg.model.pretrained = True
cfg.model.load_weights1 = ''
cfg.model.load_weights2 = ''
cfg.model.resume1 = ''
cfg.model.resume2 = ''
cfg.model.deploy = 'model1'
cfg.data = CN()
cfg.data.type = 'i... |
def send_tokensregex_request(request):
return send_request(request, TokensRegexResponse, 'edu.stanford.nlp.ling.tokensregex.ProcessTokensRegexRequest') |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model_dir', type=str, help='Model directory')
parser.add_argument('--base_analysis_dir', type=str, default='/tmp', help='Analysis directory')
args = parser.parse_args()
assert path.exists(args.model_dir)
return args |
def segment_char_ngrams(args):
vocab = [line.split()[0] for line in args.vocab if (len(line.split()) == 2)]
vocab = dict(((y, x) for (x, y) in enumerate(vocab)))
for line in args.input:
for word in line.split():
if ((word not in vocab) or (vocab[word] > args.shortlist)):
... |
class FakelyQuantONNXPyTorchExporter(BasePyTorchExporter):
def __init__(self, model: torch.nn.Module, is_layer_exportable_fn: Callable, save_model_path: str, repr_dataset: Callable, use_onnx_custom_quantizer_ops: bool=False):
super().__init__(model, is_layer_exportable_fn, save_model_path, repr_dataset)
... |
def text_model_inference(model, input_sentence):
assert isinstance(input_sentence, str)
cfg = model.cfg
if (cfg.data.test.get('pipeline', None) is None):
if is_2dlist(cfg.data.test.datasets):
cfg.data.test.pipeline = cfg.data.test.datasets[0][0].pipeline
else:
cfg.dat... |
class GraphTransformerLayer(nn.Module):
def __init__(self, in_dim, out_dim, num_heads, dropout=0.0, layer_norm=False, batch_norm=True, residual=True, use_bias=False):
super().__init__()
self.in_channels = in_dim
self.out_channels = out_dim
self.num_heads = num_heads
self.drop... |
def get_cache_path(args, out_path):
dir_args = get_name(args)
path = Path(out_path)
path.mkdir(exist_ok=True, parents=True)
dir_name = ''
dir_keys = save_keys
for name in dir_keys:
val = dir_args.pop(name)
name = '{}_{}'.format(name, val)
dir_name = '{}/{}'.format(dir_nam... |
def Dataset_wrap_csv(k_fold='No', use_old_split=True, img_size=384, dataset_name='isic2018', split_ratio=[0.8, 0.2], train_aug=False, data_folder='/bigdata/siyiplace/data/skin_lesion'):
data_dic = {}
data_path = '{}/{}/'.format(data_folder, dataset_name)
if (k_fold != 'No'):
if use_old_split:
... |
class MulCorpusReader():
def __init__(self, *corpuses, control_num=3):
self.corpuses = corpuses
self.epoch = corpuses[0].epoch
self.control_num = control_num
def next_batch(self, size, noop=False):
src = []
rem = (size % self.control_num)
for (idx, corpus) in enum... |
class LaST_Cloth(BaseDataset):
dataset_dir = ''
def __init__(self, root='data', verbose=True, **kwargs):
super(LaST_Cloth, self).__init__()
self.dataset_dir = osp.join(root, self.dataset_dir)
self.train_dir = osp.join(self.dataset_dir, 'train')
self.query_dir = osp.join(self.data... |
def main():
import sys
if (((len(sys.argv) < 4) or (len(sys.argv) > 6)) or (sys.argv[1] not in ['bert', 'gpt', 'transfo_xl', 'gpt2', 'xlnet', 'xlm'])):
print('This command line utility let you convert original (author released) model checkpoint to pytorch.\nIt should be used as one of: \n>> transformers... |
def gen_classifier_loader(name, d):
def classifier_loader():
model = EfficientNet.from_name(d['arch'])
load_model_state_dict(model, name)
return model
return classifier_loader |
def test_check_num_rows_non_reject_sampling_error():
num_rows = 0
expected_num_rows = 5
is_reject_sampling = False
max_tries = 1
error_msg = 'Unable to sample any rows for the given conditions. This may be because the provided values are out-of-bounds in the current model.'
with pytest.raises(Va... |
class Agent():
def __init__(self, module_list: Iterable, config: AttrDict):
self.config = config
parent_folder = config.parent_folder
assert parent_folder, "Setting the agent's parent folder is required!"
self.agent_name = (config.get('agent_name') or ('agent_' + short_timestamp()))
... |
def setup_classifiers():
rng = np.random.RandomState(654321)
(X, y) = make_classification(n_classes=2, n_samples=1000, weights=[0.2, 0.8], random_state=rng)
(X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.33, random_state=rng)
scalar = StandardScaler()
X_train = scalar.fit_tr... |
def force_list(x):
if isinstance(x, tuple):
return list(x)
elif (not isinstance(x, list)):
return [x]
return x |
def load_model_from_config(serialization_directory: str, weight_file: str=None):
serialization_directory = Path(serialization_directory)
metadata_path = (serialization_directory / 'metadata.json')
model_config = json.load(open(metadata_path, 'r'))['model_config']
bert_config = AutoConfig.from_pretrained... |
def monomial_function(n, e):
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.finite_rings.finite_field_constructor import GF
base_ring = GF((2, n), name='x')
R = PolynomialRing(base_ring, name='X')
X = R.gen()
return SBox((X ** e)) |
def argparser():
ap = argparse.ArgumentParser()
ap.add_argument('net', help='network name, should be a .py file under "nns". Choices: {}.'.format(', '.join(all_networks())))
ap.add_argument('--batch', type=int, required=True, help='batch size')
ap.add_argument('--word', type=int, default=16, help='word ... |
def load_dataset():
from keras.datasets import mnist
((x_train, y_train), (x_test, y_test)) = mnist.load_data()
x_train = (x_train.reshape((- 1), 28, 28, 1).astype('float32') / 255.0)
x_test = (x_test.reshape((- 1), 28, 28, 1).astype('float32') / 255.0)
y_train = to_categorical(y_train.astype('float... |
class DicomSeries(object):
def __init__(self, suid, progressIndicator):
self._entries = []
self._suid = suid
self._info = {}
self._progressIndicator = progressIndicator
def __len__(self):
return len(self._entries)
def __iter__(self):
return iter(self._entries)... |
def write_file(file_handle: click.utils.LazyFile, api_name: (str | None), location: str, base_url: (str | None), started_at: str, in_queue: Queue, out_queue: Queue, usage_data: (dict[(str, Any)] | None)) -> None:
with file_handle.open() as fileobj, tarfile.open(mode='w:gz', fileobj=fileobj) as tar:
writer =... |
def np_quantile_version_above_122(a: ArrayLike, q: ArrayLike, method: str='linear', **kwargs: Any) -> NDArray:
return np.quantile(a, q, method=method, **kwargs) |
def return_iterator_by_type(data_type):
if isinstance(data_type, dict):
iterator = data_type.items()
else:
iterator = enumerate(data_type)
return iterator |
class Token(tuple):
__slots__ = ()
(lineno, type, value) = (property(itemgetter(x)) for x in range(3))
def __new__(cls, lineno, type, value):
return tuple.__new__(cls, (lineno, intern(str(type)), value))
def __str__(self):
if (self.type in reverse_operators):
return reverse_o... |
class NodeDispatch(object):
def get_handler_name(node_kind):
if (len(node_kind) <= 4):
return node_kind.lower()
name = re.sub('(.)([A-Z][a-z]+)', '\\1_\\2', node_kind)
return re.sub('([a-z0-9])([A-Z])', '\\1_\\2', name).lower()
def get_handler(self, node_kind, prefix):
... |
class Module(object):
dump_patches = False
_version = 1
def __init__(self):
self._backend = thnn_backend
self._parameters = OrderedDict()
self._buffers = OrderedDict()
self._backward_hooks = OrderedDict()
self._forward_hooks = OrderedDict()
self._forward_pre_h... |
_utils.test(ti.cpu)
def test_static_break():
x = ti.field(ti.i32, 5)
def func():
for i in ti.static(range(5)):
x[i] = 1
if ti.static((i == 2)):
break
func()
assert np.allclose(x.to_numpy(), np.array([1, 1, 1, 0, 0])) |
.skipif((not torch.cuda.is_available()), reason='No CUDA device registered.')
class TestCustomHighwayLSTM(AllenNlpTestCase):
def test_small_model(self):
args = self.get_models_and_inputs(5, 3, 11, 2, 5, 0.0)
self.forward_and_backward_outputs_match(*args)
def test_large_model(self):
args ... |
def compile(name: str, inputs: List[Tensor], outputs: List[Tensor], cmp=True, opt=2, dyn=False, profile=False, has_custom=False, refs=None):
TpuLang.graph.inputs = inputs
TpuLang.graph.outputs = outputs
converter = TpuLangConverter(name=name, graph=TpuLang.graph)
model_transform(name, converter)
mod... |
def _load_model(arch_type, backbone, num_classes, output_stride, pretrained_backbone):
if (backbone == 'mobilenetv2'):
model = _segm_mobilenet(arch_type, backbone, num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone)
elif backbone.startswith('resnet'):
model = _segm... |
class _CudaBase(object):
is_cuda = True
is_sparse = False
def type(self, *args, **kwargs):
with device(self.get_device()):
return super(_CudaBase, self).type(*args, **kwargs)
__new__ = _lazy_new |
class Constraint(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_network(cfg):
arch = cfg.network
get_model = _network_factory[arch]
network = get_model()
return network |
def filter_dataown(qseq, aseq):
filtered_q = []
filtered_p = []
fliter_flag = 0
filtered_a = []
for i in range(len(aseq)):
fliter_flag += 1
(qlen, alen) = (len(qseq[i].split(' ')), len(aseq[i].split(' ')))
filtered_p.append(fliter_flag)
if ((qlen >= limit['minq']) and... |
class OnnxConfigWithPastTestCaseV2(TestCase):
SUPPORTED_WITH_PAST_CONFIGS = {}
(OnnxConfigWithPast, __abstractmethods__=set())
def test_use_past(self):
for (name, config) in OnnxConfigWithPastTestCaseV2.SUPPORTED_WITH_PAST_CONFIGS:
with self.subTest(name):
self.assertFals... |
def analyze(report, templates, accuracy_ks=(1, 2), precision_ks=(1, 2), recall_ks=(1, 2)):
template_match_counts = collections.defaultdict(int)
template_choice_ranks = {'all': collections.defaultdict(list), 'templates only': collections.defaultdict(list)}
template_valid_choice_ranks = {'all': collections.de... |
def env_worker(make_env, make_policy, n_episodes, id_worker):
env = make_env(seed=0)
print('Env created.')
policy = make_policy()
print('Policy created.')
q_env = Queue(f'env_{id_worker}')
q_policy = Queue(f'policy_{id_worker}')
print('Queue created.')
episodes = []
total_env_step = ... |
.only_pytorch
.only_pytorch64
def test_pdf_calculations_pytorch(backend):
tb = pyhf.tensorlib
values = tb.astensor([0, 0, 1, 1])
mus = tb.astensor([0, 1, 0, 1])
sigmas = tb.astensor([0, 0, 0, 0])
for (x, mu, sigma) in zip(values, mus, sigmas):
with pytest.raises(ValueError):
_ = ... |
class GeodesicDistanceComputer(metaclass=Singleton):
def __init__(self):
self._pathfinders = {}
def _get_pathfinder(self, scene_id) -> PathFinder:
scene_name = osp.splitext(osp.basename(scene_id))[0]
if (scene_name not in self._pathfinders):
navmesh = osp.join(osp.dirname(__f... |
.parametrize('test_case, recursive', [(test_bucket_medium_file, True), (test_bucket_large_file, False), (test_bucket_small_file, True)])
def test_azure(azure_bucket, gcp_bucket, test_case, recursive):
client = SkyplaneClient()
src_iface = ObjectStoreInterface.create('gcp:us-west2', test_bucket.split('://')[1])
... |
class BrandtModuleElement(HeckeModuleElement):
def __init__(self, parent, x):
if isinstance(x, HeckeModuleElement):
x = x.element()
HeckeModuleElement.__init__(self, parent, parent.free_module()(x))
def _richcmp_(self, other, op):
return richcmp(self.element(), other.element(... |
def get_aggregate(cl, matrices, domain):
children = [r for r in matrices if ((set(r) < set(cl)) and ((len(r) + 1) == len(cl)))]
ans = [sparse.csr_matrix((0, domain.size(cl)))]
for c in children:
coef = (1.0 / np.sqrt(len(children)))
a = tuple((set(cl) - set(c)))
cl2 = (a + c)
... |
def calc_one(data):
relcnt = 0
score = 0.0
data = sorted(data, key=(lambda d: d[1]), reverse=True)
fout = open('meshres.5.txt', 'a')
for (idx, item) in enumerate(data):
if (idx < 5):
fout.write((((item[0][0] + '\t') + item[0][1]) + '\n')) |
class VideoDiscriminator(nn.Module):
def __init__(self, n_channels, n_output_neurons=1, bn_use_gamma=True, use_noise=False, noise_sigma=None, ndf=64):
super(VideoDiscriminator, self).__init__()
self.n_channels = n_channels
self.n_output_neurons = n_output_neurons
self.use_noise = use... |
def one_hot_encoding(labels, num_classes, scope=None):
with tf.op_scope([labels], scope, 'OneHotEncoding'):
batch_size = labels.get_shape()[0]
indices = tf.expand_dims(tf.range(0, batch_size), 1)
labels = tf.cast(tf.expand_dims(labels, 1), indices.dtype)
concated = tf.concat(1, [indi... |
def get_audio(filename):
if str(filename).endswith('.wav'):
try:
a = wave_get_audio(filename)
if a:
return a
except Exception:
pass
return ffmpeg_get_audio(filename) |
def save_checkpoint(state, checkpoint_path, cfg):
file_path = osp.join(checkpoint_path, 'checkpoint.pth.tar')
torch.save(state, file_path)
if ((cfg.data.train.type in ['synth']) or ((state['iter'] == 0) and ((state['epoch'] % 10) == 0))):
file_name = ('checkpoint_%dep.pth.tar' % state['epoch'])
... |
def test_process_routing_invalid_object():
class InvalidObject():
pass
with pytest.raises(AttributeError, match='either implement the routing method'):
process_routing(InvalidObject(), 'fit', **{}) |
class Token(Structure):
_fields_ = [('int_data', (c_uint * 4)), ('ptr_data', c_void_p)]
def spelling(self):
return conf.lib.clang_getTokenSpelling(self._tu, self)
def kind(self):
return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
def location(self):
return conf.lib.cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.