code stringlengths 101 5.91M |
|---|
class KRTToRCBijectionTypeA2Odd(KRTToRCBijectionTypeA):
def next_state(self, val):
n = self.n
tableau_height = (len(self.cur_path[0]) - 1)
if (val > 0):
KRTToRCBijectionTypeA.next_state(self, val)
return
pos_val = (- val)
if (len(self.ret_rig_con[(pos_... |
def GenerateSM75_TensorOp_1688(manifest, cuda_version):
if (not CudaToolkitVersionSatisfies(cuda_version, 10, 2)):
return
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, Layo... |
def shapley_coefficients(n):
out = np.zeros(n)
for i in range(n):
out[i] = (1 / (n * scipy.special.comb((n - 1), i)))
return out |
def soft_threshold(x, gamma):
x_abs = np.abs(x)
return (np.maximum(0, (1 - (gamma / x_abs))) * x) |
def _transform_day(result_str: str, day_token: str, day: int) -> str:
result = deepcopy(result_str)
if (day_token != ''):
if (day == (- 1)):
if (len(day_token) == 2):
result = result.replace(day_token, '--')
elif (len(day_token) == 1):
result = res... |
def create_instances_from_document(all_documents, document_index, max_seq_length, short_seq_prob=0.1):
document = all_documents[document_index]
max_num_tokens = (max_seq_length - 3)
target_seq_length = max_num_tokens
if (random.random() < short_seq_prob):
target_seq_length = random.randint(2, ma... |
def softmax(x):
x = (x - np.max(x))
exp_x = np.exp(x)
softmax_x = (exp_x / np.sum(exp_x))
return softmax_x |
def _prepare_caffe2(x):
from caffe2.python import workspace
x = workspace.FetchBlob(x)
return x |
class AttentionLayer(nn.Module):
def __init__(self, image_dim, question_dim, **kwargs):
super().__init__()
combine_type = kwargs['modal_combine']['type']
combine_params = kwargs['modal_combine']['params']
modal_combine_layer = ModalCombineLayer(combine_type, image_dim, question_dim, ... |
('mmseg.apis.multi_gpu_test', multi_gpu_test)
def test_dist_eval_hook():
with pytest.raises(TypeError):
test_dataset = ExampleModel()
data_loader = [DataLoader(test_dataset, batch_size=1, sampler=None, num_worker=0, shuffle=False)]
DistEvalHook(data_loader)
test_dataset = ExampleDataset(... |
def train(loss_val, var_list):
optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)
grads = optimizer.compute_gradients(loss_val, var_list=var_list)
if FLAGS.debug:
for (grad, var) in grads:
utils.add_gradient_summary(grad, var)
return optimizer.apply_gradients(grads) |
class CategoricalEncodingAlgo(abc.ABC):
def fit_transform(self, log_attributes: pd.DataFrame) -> pd.DataFrame:
pass |
def load_models(config, mode):
gen_conf = deepcopy(config.models['generator'])
dis_conf = deepcopy(config.models['discriminator'])
if (mode == 'source'):
gen_conf['args']['n_classes'] = gen_conf['args']['n_classes_src']
dis_conf['args']['n_classes'] = dis_conf['args']['n_classes_src']
el... |
_node_type()
class GaussianSource(optplan.EmSource):
type = schema_utils.polymorphic_model_type('source.gaussian_beam')
w0 = types.FloatType()
center = optplan.vec3d()
beam_center = optplan.vec3d()
extents = optplan.vec3d()
normal = optplan.vec3d()
theta = types.FloatType()
psi = types.F... |
class XGLMTokenizer(metaclass=DummyObject):
_backends = ['sentencepiece']
def __init__(self, *args, **kwargs):
requires_backends(self, ['sentencepiece']) |
def affiliation_precision_distance(Is=[(1, 2), (3, 4), (5, 6)], J=(2, 5.5)):
if all([(I is None) for I in Is]):
return math.nan
return (sum([integral_interval_distance(I, J) for I in Is]) / sum_interval_lengths(Is)) |
class TFRegNetModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class FurthestPointSampling(Function):
def forward(ctx, xyz, npoint):
return pl.furthest_point_sampling(xyz.contiguous(), npoint)
def backward(xyz, a=None):
return (None, None) |
def test_cross_entropy_no_batch_dim_dense_target():
logits_raw = torch.tensor([0.0, 0.0, math.log(10.0), 0.0, 0.0, 0.0])
target_raw = torch.tensor([0.0, 0.0, 0.5, 0.0, 0.0, 0.5])
classes_dim = Dim(dimension=6)
logits = Tensor(name='logits', dims=[classes_dim], dtype='float32', raw_tensor=logits_raw)
... |
class BaseOfflinePolicyLearner(metaclass=ABCMeta):
n_actions: int
len_list: int = 1
def __post_init__(self) -> None:
check_scalar(self.n_actions, 'n_actions', int, min_val=2)
check_scalar(self.len_list, 'len_list', int, min_val=1, max_val=self.n_actions)
def policy_type(self) -> PolicyTy... |
def label2id(image):
array = np.array(image)
out_array = np.empty(array.shape, dtype=array.dtype)
for l in labels:
if (0 <= l.trainId < 255):
out_array[(array == l.trainId)] = l.id
return Image.fromarray(out_array) |
def WriteStatus(num_steps, eval_metric, best_eval_metric):
status = os.path.join((os.getenv('GOOGLE_STATUS_DIR') or '/tmp'), 'STATUS')
message = ('Parameters: %s | Steps: %d | Tuning score: %.2f%% | Best tuning score: %.2f%%' % (FLAGS.params, num_steps, eval_metric, best_eval_metric))
with gfile.FastGFile(s... |
class AnnotatedConvBnModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.qconfig = default_qconfig
self.conv = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float)
self.bn = torch.nn.BatchNorm2d(5).to(dtype=torch.float)
self.quant = QuantStub()
s... |
def parse(exit_code, log, output):
(findings, infos) = ([], set())
(errors, fails) = sb.parse_utils.errors_fails(exit_code, log)
for line in log:
i = line.find(': ')
if (i >= 0):
k = line[0:i].strip()
v = line[(i + 2):].strip()
if v.isdigit():
... |
def is_OctalStringMonoidElement(x):
from .string_monoid import OctalStringMonoid
return (isinstance(x, StringMonoidElement) and isinstance(x.parent(), OctalStringMonoid)) |
class RandomActiveLearningNodeMean(LearningNodeMean, RandomActiveLeafRegressor):
def __init__(self, initial_stats=None, max_features=2, random_state=None):
super().__init__(initial_stats)
self.max_features = max_features
self.feature_indices = np.array([])
self.random_state = random_... |
def get_alignment_angle_arctan2(left_eye: Union[(list, tuple)], right_eye: Union[(list, tuple)]) -> float:
return float(np.degrees(np.arctan2((right_eye[1] - left_eye[1]), (right_eye[0] - left_eye[0])))) |
class A064553(SloaneSequence):
def __init__(self):
SloaneSequence.__init__(self, offset=1)
def _repr_(self):
return 'a(1) = 1, a(prime(i)) = i+1 for i > 0 and a(u*v) = a(u)*a(v) for u,v > 0'
def _eval(self, n):
return prod([((prime_pi(p) + 1) ** e) for (p, e) in arith.factor(n)]) |
def get_trainer_params():
return d(cls=LatentTrainer, params=d(dynamics_learning_rate=0.0001, latent_learning_rate=0.0005, latent_train_every_n_steps=LATENT_TRAIN_EVERY_N, sample_every_n_steps=0, train_every_n_steps=1, holdout_every_n_steps=500, max_steps=100000.0, max_train_data_steps=0, max_holdout_data_steps=0, ... |
()
def ssh():
instances = query_instances()
if (len(instances) == 0):
typer.secho(f'No instances found', fg='red', err=True)
raise typer.Abort()
instance_map = {f'{i.region_tag}, {i.public_ip()} ({i.instance_state()})': i for i in instances}
choices = list(sorted(instance_map.keys()))
... |
.parametrize('csr_container', CSR_CONTAINERS)
def test_load_offset_exhaustive_splits(csr_container):
rng = np.random.RandomState(0)
X = np.array([[0, 0, 0, 0, 0, 0], [1, 2, 3, 4, 0, 6], [1, 2, 3, 4, 0, 6], [0, 0, 0, 0, 0, 0], [1, 0, 3, 0, 0, 0], [0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0]])
X = csr_container(X)
... |
def worker(gpu, ngpus_per_node, args):
if args.adv:
model = AdvTrainer(args)
else:
model = BaseTrainer(args)
model.make_model_env(gpu, ngpus_per_node)
model.make_run_env()
model.train() |
def get_criterion():
criterion_dict = {}
from ctrl.utils.loss_functions import CrossEntropy2D
criterion_dict['semseg'] = CrossEntropy2D()
from ctrl.utils.loss_functions import BerHuLossDepth
criterion_dict['depth'] = BerHuLossDepth()
from ctrl.utils.loss_functions import BCELossSS
criterion_... |
def get_checkpoint_callback(fix_config, save_path) -> ModelCheckpoint:
prefix = save_path
suffix = 'Best-{epoch:02d}-{val_loss:.4f}-{val_acc:.4f}'
checkpoint_callback = ModelCheckpoint(dirpath=prefix, filename=suffix, save_top_k=1, save_last=True, monitor=fix_config.monitor.metric, mode=fix_config.monitor.m... |
def get_index_mask(data, index, flattened_too=False, is_data_flattened=False):
(lats, lons) = get_region_bounds(index)
return cord_mask(data, lat=lats, lon=lons, flattened_too=flattened_too, is_flattened=is_data_flattened) |
def type_to_python(typename, size=None):
typename = typename.replace(' ', '')
if ((typename in {'IntArrayRef', 'TensorList'}) and (size is not None)):
typename += '[]'
typename = {'Device': 'Device', 'Generator': 'Generator', 'IntegerTensor': 'Tensor', 'Scalar': 'Number', 'ScalarType': '_dtype', 'St... |
def parse_args():
parser = argparse.ArgumentParser(description='Train a change detector')
parser.add_argument('config', help='train config file path')
parser.add_argument('--work-dir', help='the dir to save logs and models')
parser.add_argument('--load-from', help='the checkpoint file to load weights fr... |
def as_markdown(value: Union[(List[str], Dict[(str, str)], str)]) -> Union[(str, Number)]:
if isinstance(value, list):
return __as_markdown_list(value)
elif isinstance(value, dict):
return __as_markdown_dict(value)
elif isinstance(value, str):
return value
elif (isinstance(value,... |
class GBlock(ControlFlowScope):
def as_string(self, indent: int=0):
result = ((indent * INDENTATION) + 'gblock:\n')
return (result + super().as_string(indent)) |
class Updater(object):
def _force_to_list(self, x):
if (type(x) is list):
return x
else:
return [x]
def __init__(self, solver=None, loss=None, data_feeder=(lambda : True), forward_callback_on_start=(lambda i: True), forward_callback_on_finish=(lambda i: True), backward_ca... |
def expected_version(done_fwds, done_bwds, se) -> Tuple[(int, int)]:
return (my_version(done_bwds, se), expected_staleness(done_fwds, done_bwds, se)) |
def LF_definite_left_7_10(span, negex):
left = get_left_span(span, span.sentence)
trigger = match_regex(negex.rgxs['definite']['left'], left)
if (not trigger):
return ABSTAIN
dist = token_distance(trigger, span)
right = get_right_span(trigger, window=2)
if pseudo_negation.search(right.te... |
class SubwordSlotTokenizer(Tokenizer):
def __init__(self, spm, slots):
super().__init__()
if ((spm.pad_id() != 0) or (spm.eos_id() != 1) or (spm.unk_id() != 2)):
raise ValueError('Please train sentencepiece model with following argument:\n--pad_id=0 --eos_id=1 --unk_id=2 --bos_id=-1 --mo... |
class Resnet_Imb_CB_beta099999_ep100_cifar100_2():
def __init__(self):
self.set_config()
def set_config(self):
self.filename_head = (self.__class__.__name__ + '_')
self.checkpoint_path = None
def get_model(self):
model = resnet.ResNet18(num_classes=100)
return model
... |
def get_numpy_iterator(train: NumpyOrSparse, valid: Optional[NumpyOrSparse]=None, n_folds: Optional[int]=None, iterator: Optional[CustomIdxs]=None) -> Union[(FoldsIterator, HoldoutIterator, CustomIterator, DummyIterator)]:
if (valid is not None):
train_valid = HoldoutIterator(train, valid)
elif (iterato... |
class TargetPlatformModel(ImmutableClass):
def __init__(self, default_qco: QuantizationConfigOptions, name='default_tp_model'):
super().__init__()
self.name = name
self.operator_set = []
assert isinstance(default_qco, QuantizationConfigOptions)
assert (len(default_qco.quantiz... |
def check_output_dir(training_args):
if (os.path.isdir(training_args.output_dir) and training_args.do_train and (not training_args.overwrite_output_dir)):
last_checkpoint = get_last_checkpoint(training_args.output_dir)
if ((last_checkpoint is None) and (len(os.listdir(training_args.output_dir)) > 0)... |
.parametrize('observation_shape', [((100,), (200,))])
.parametrize('batch_size', [32])
def test_tuple_observation_scaler_with_transition_picker(observation_shape: Shape, batch_size: int) -> None:
observations = create_observations(observation_shape, batch_size)
actions = np.random.random((batch_size, 1))
re... |
def main():
graph = as_733()
sis_params = {'model': 'SIS', 'b': 0.001, 'd': 0.01, 'c': 1, 'runs': 1, 'steps': 5000, 'seed': 1, 'diffusion': 'min', 'method': 'ns_node', 'k': 5, 'plot_transition': True, 'gif_animation': True, 'edge_style': 'bundled', 'node_style': 'force_atlas', 'fa_iter': 20}
ds = Diffusion(... |
class MomentumUpdaterHook(Hook):
def __init__(self, by_epoch=True, warmup=None, warmup_iters=0, warmup_ratio=0.9):
if (warmup is not None):
if (warmup not in ['constant', 'linear', 'exp']):
raise ValueError(f'"{warmup}" is not a supported type for warming up, valid types are "con... |
def _tensorviewer_from_parmap(par_map, batch_size):
(names, slices, _) = list(zip(*sorted(((paramset_name, paramset_spec['slice'], paramset_spec['slice'].start) for (paramset_name, paramset_spec) in par_map.items()), key=(lambda x: x[2]))))
return _tensorviewer_from_slices(slices, names, batch_size) |
class Matcher(object):
version_class = None
_operators = {'<': (lambda v, c, p: (v < c)), '>': (lambda v, c, p: (v > c)), '<=': (lambda v, c, p: ((v == c) or (v < c))), '>=': (lambda v, c, p: ((v == c) or (v > c))), '==': (lambda v, c, p: (v == c)), '===': (lambda v, c, p: (v == c)), '~=': (lambda v, c, p: ((v ... |
class global_state():
def __init__(self):
self.graph = None
self.analysis_data = None
self.figure_cache = None
self.dist_cache = None
self.weight_cache = None
self.draggable = None
self.zIndex = 50
self.f32_mlir = ''
self.quant_mlir = ''
... |
def load_cython(name):
from sage.misc.cython import cython
(mod, dir) = cython(name, compile_message=True, use_cache=True)
import sys
sys.path.append(dir)
return 'from {} import *'.format(mod) |
def create_distiller(opt, verbose=True):
distiller = find_distiller_using_name(opt.distiller)
instance = distiller(opt)
if verbose:
print(('distiller [%s] was created' % type(instance).__name__))
return instance |
def train(args, model, train_loader, eval_loader, num_epochs, output, opt=None, s_epoch=0):
device = args.device
lr_default = args.lr
lr_decay_step = 2
lr_decay_rate = 0.75
best_model = ''
lr_decay_epochs = (range(10, 20, lr_decay_step) if (eval_loader is not None) else range(10, 20, lr_decay_st... |
class ModuleList(BaseModule, nn.ModuleList):
def __init__(self, modules: Optional[Iterable]=None, init_cfg: Optional[dict]=None):
BaseModule.__init__(self, init_cfg)
nn.ModuleList.__init__(self, modules) |
_args('v', 'i', 'i', 'none')
def sort(g, self, dim, decending, out=None):
if (out is not None):
_unimplemented('Sort', 'Out parameter is not supported for sort')
if (not self.isCompleteTensor()):
return _unimplemented('Sort', 'input size not accessible')
return g.op('TopK', self, k_i=self.ty... |
_module()
class NASFCOS(SingleStageDetector):
def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None, init_cfg=None):
super(NASFCOS, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained, init_cfg) |
def create_crefs(refs):
crefs = []
for ref in refs:
crefs.append(cook_refs(ref))
return crefs |
def repro_fig_4(gpu=None, interp='bicubic'):
net = caffe.Net('/home/ruthfong/packages/caffe/models/bvlc_googlenet/deploy_force_backward.prototxt', '/home/ruthfong/packages/caffe/models/bvlc_googlenet/bvlc_googlenet.caffemodel', caffe.TEST)
topName = 'loss3/classifier'
bottomName = 'pool2/3x3_s2'
zebra_i... |
class TestCost(unittest.TestCase):
def test_valid_args(self):
cost = Cost(mac_op=1, mem_hier=(200, 6, 2, 1), noc_hop=10, idl_unit=0)
self.assertEqual(cost.mac_op, 1, 'mac_op')
self.assertEqual(cost.mem_hier, (200, 6, 2, 1), 'mem_hier')
self.assertEqual(cost.noc_hop, 10, 'noc_hop')
... |
class HParams(tf_contrib.training.HParams):
def del_hparam(self, name):
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name]
def pop_hparam(self, name):
value = getattr(self, name)
self.del_hparam(name)
return value
def get_hparam(s... |
class TextCNN(nn.Module):
def __init__(self, vocab_dict, glove_file=None, emb_dim=104, dropout_p=0.1, word_embed_dim=50):
super(TextCNN, self).__init__()
Ks = [3, 4, 5]
Ci = 1
Co = 1000
self.embed = nn.Embedding(len(vocab_dict), word_embed_dim)
if glove_file:
... |
def test_parser():
parser = parse_args(['--predictions', 'predictions.tsv', '--ground-truth', 'ground_truth.tsv', '--metrics', 'metrics.tsv'])
assert (parser.predictions is not None)
assert ('predictions.tsv' == parser.predictions)
assert (parser.ground_truth is not None)
assert ('ground_truth.tsv' ... |
def _make_unique_name(seen: Set[str], name: str, min_version: int=0):
assert (name is not None)
i = min_version
x = (('%s_%d' % (name, i)) if i else name)
while (x in seen):
i += 1
x = ('%s_%d' % (name, i))
seen.add(x)
return x |
def test_inclusive_policy_positive_examples_3(digraph, features_1d, labels):
policy = InclusivePolicy(digraph, features_1d, labels)
ground_truth = [False, False, True, False, True, True, False, False]
result = policy.positive_examples('2.1')
assert_array_equal(ground_truth, result) |
def create_pipeline_configuration(DEBUG=False, batch_size=32):
config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (CrossEntropyLoss, T5LayerNorm, Linear, StatelessEmbedding, Dropout, T5Block), 'model_inputs': {'attention_mask': {'shape': torch.Size([32, 1, 1, 64]), 'dtype': torch.float32, 'is_batched': True,... |
class AutoProcessor():
def __init__(self):
raise EnvironmentError('AutoProcessor is designed to be instantiated using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method.')
_list_option_in_docstrings(PROCESSOR_MAPPING_NAMES)
def from_pretrained(cls, pretrained_model_name_or_pat... |
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps, scale_betas=1.0):
if (schedule_name == 'linear'):
scale = ((scale_betas * 1000) / num_diffusion_timesteps)
beta_start = (scale * 0.0001)
beta_end = (scale * 0.02)
return np.linspace(beta_start, beta_end, num_diffusio... |
class FiniteField_pari_ffelt(FiniteField):
def __init__(self, p, modulus, name=None):
n = modulus.degree()
if (n < 2):
raise ValueError('the degree must be at least 2')
FiniteField.__init__(self, base=GF(p), names=name, normalize=True)
self._modulus = modulus
self... |
def corpus_bleu(sys_stream, ref_streams):
bleu = _corpus_bleu(sys_stream, ref_streams, tokenize='none')
return bleu.score |
def mk_zimpl_input(dialog):
data_dir = './tmp'
edus = dialog['edus']
turn_len = []
turn_off = []
edu_ind = []
c_off = 0
for (i, edu) in enumerate(dialog['edus']):
edu_ind.append((edu['turn'] + 1))
i = 0
while (i < len(edus)):
j = i
while ((j < len(edus)) and (... |
class CNN3(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)):
super().__init__()
self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
self.con... |
def test_unknowntype():
t = UnknownType()
assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t)) |
class Function_zeta(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'zeta', conversions={'giac': 'Zeta', 'maple': 'Zeta', 'sympy': 'zeta', 'mathematica': 'Zeta'}) |
def vocab_token_counts(text_filepattern, max_lines):
ret = {}
for (i, line) in enumerate(_read_filepattern(text_filepattern, max_lines=max_lines)):
if (',' not in line):
tf.logging.warning("Malformed vocab line #%d '%s'", i, line)
continue
(token, count) = line.rsplit(','... |
def _expand_vocabulary(skip_thoughts_emb, skip_thoughts_vocab, word2vec):
tf.logging.info('Finding shared words')
shared_words = [w for w in word2vec.vocab if (w in skip_thoughts_vocab)]
tf.logging.info('Selecting embeddings for %d shared words', len(shared_words))
shared_st_emb = skip_thoughts_emb[[ski... |
class TSInt(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
Val = _swig_property(_snap.TSInt_Val_get, _snap.TSInt_Val_set)
def __init__(self, *args):
_snap.TSInt_swiginit(self, _snap.new_TSInt(*args))
... |
def import_statements(*objects, **kwds):
import itertools
import inspect
from sage.misc.lazy_import import LazyImport
answer = defaultdict(list)
module_name = None
lazy = kwds.pop('lazy', False)
verbose = kwds.pop('verbose', True)
answer_as_str = kwds.pop('answer_as_str', False)
if k... |
def get_net_qc_graph(config_file: str):
with open(config_file, 'r') as fh:
config = load(fh)
graph = {}
for node in config[ParallelRouterNetTopo.ALL_NODE]:
if (node[ParallelRouterNetTopo.TYPE] == ParallelRouterNetTopo.QUANTUM_ROUTER):
graph[node[ParallelRouterNetTopo.NAME]] = []
... |
def generate_compl_labels(labels):
K = (torch.max(labels) + 1)
candidates = np.arange(K)
candidates = np.repeat(candidates.reshape(1, K), len(labels), 0)
mask = np.ones((len(labels), K), dtype=bool)
mask[(range(len(labels)), labels.numpy())] = False
candidates_ = candidates[mask].reshape(len(lab... |
class FakeConstantModel(flexs.Model):
def __init__(self, constant):
super().__init__(name='ConstantModel')
self.constant = constant
def _fitness_function(self, sequences):
return (np.ones(len(sequences)) * self.constant)
def train(self, *args, **kwargs):
pass |
def eval_model(args):
model = torch.load(args.save)
model.eval()
evaluateL2 = nn.MSELoss().to(args.device)
evaluateL1 = nn.L1Loss().to(args.device)
Data = DataLoaderS(args, train_dates=train_dates, val_dates=val_dates, test_dates=test_dates)
(test_acc, test_rae, test_corr, oni_test_stats, preds,... |
def register_Ns3UanChannel_methods(root_module, cls):
cls.add_constructor([param('ns3::UanChannel const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AddDevice', 'void', [param('ns3::Ptr< ns3::UanNetDevice >', 'dev'), param('ns3::Ptr< ns3::UanTransducer >', 'trans')])
cls.add_method('Clear', 'vo... |
class PyGNodePropPredDataset(InMemoryDataset):
def __init__(self, name: str, root: str, transform: Optional[Callable]=None, pre_transform: Optional[Callable]=None):
self.name = name
self.root = root
self.dataset = NodePropPredDataset(name=name, root=root)
self._train_mask = torch.fro... |
class PretrainedBartModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class LieGroupOps(GroupOps):
def tangent_dim(a: T.ElementOrType) -> int:
return LieGroupOps.implementation(get_type(a)).tangent_dim(a)
def from_tangent(a: T.ElementOrType, vec: T.Sequence[T.Scalar], epsilon: T.Scalar=sf.epsilon()) -> T.Element:
return LieGroupOps.implementation(get_type(a)).from... |
class DWConv2d_BN_M(nn.Module):
def __init__(self, in_ch, out_ch, kernel_size=1, stride=1, norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, bn_weight_init=1, num_domains=1):
super().__init__()
self.dwconv = nn.Conv2d(in_ch, in_ch, kernel_size, stride, ((kernel_size - 1) // 2), groups=in_ch, bias=F... |
class _CrossEntropy(nn.Module):
def __init__(self, sumit=True):
super(_CrossEntropy, self).__init__()
self.sumit = sumit
def forward(self, p, q):
if self.sumit:
return ((- p) * torch.log(q)).sum(dim=1)
else:
return ((- p) * torch.log(q))
def __str__(se... |
def test_main_wrapper_loads_from_fsspec():
with fsspec.open('memory://test.yaml', 'w') as f:
f.write('\n project: test\n ')
args = ['--config_path', 'memory://test.yaml', '--x', '2']
class Config():
project: str
x: int = 1
.main(args=args)
def main(config: Confi... |
class MINRES(CPAlgorithm):
def __init__(self, num_runs=10):
self.num_runs = num_runs
self.n_jobs = 1
def detect(self, G):
(A, nodelabel) = utils.to_adjacency_matrix(G)
def _detect(A, maxIt=10000):
w = np.random.rand(A.shape[0])
adam = ADAM()
fo... |
def get_frames(video_name):
if (not video_name):
cap = cv2.VideoCapture(0)
for i in range(5):
cap.read()
while True:
(ret, frame) = cap.read()
if ret:
(yield frame)
else:
break
elif (video_name.endswith('avi'... |
def numpy_to_cutlass(inp):
if numpy_available:
if (inp == np.float16):
return cutlass.float16
elif (inp == np.float32):
return cutlass.float32
elif (inp == np.float64):
return cutlass.float64
elif (inp == np.int8):
return cutlass.int8
... |
class ScriptMaker(object):
script_template = SCRIPT_TEMPLATE
executable = None
def __init__(self, source_dir, target_dir, add_launchers=True, dry_run=False, fileop=None):
self.source_dir = source_dir
self.target_dir = target_dir
self.add_launchers = add_launchers
self.force =... |
def validate_fr_tva(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(tva.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
_tf
class TFCLIPVisionModelTest(TFModelTesterMixin, unittest.TestCase):
all_model_classes = ((TFCLIPVisionModel,) if is_tf_available() else ())
test_pruning = False
test_resize_embeddings = False
test_head_masking = False
test_onnx = False
def setUp(self):
self.model_tester = TFCLIPVisio... |
class Wallet():
_accounts: list
_imported_accounts: list
_web3: Web3
_default_account: Account
_chain_id: int
_url: str
_max_fee: float
_max_priority_fee: float
_KEY_DERIVATION_PATH = "m/44'/60'/0'/0/{}"
_DEFAULT_MNEMONIC = 'great amazing fun seed lab protect network system secur... |
class PlaceSet(UniqueRepresentation, Parent):
Element = FunctionFieldPlace
def __init__(self, field):
self.Element = field._place_class
Parent.__init__(self, category=Sets().Infinite())
self._field = field
def _repr_(self):
return 'Set of places of {}'.format(self._field)
... |
class FPN(nn.Module):
def __init__(self, in_channels_list, out_channels, conv_block, top_blocks=None):
super(FPN, self).__init__()
self.inner_blocks = []
self.layer_blocks = []
for (idx, in_channels) in enumerate(in_channels_list, 1):
inner_block = 'fpn_inner{}'.format(id... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.