code stringlengths 101 5.91M |
|---|
('/slot-details/<slotNumber>', methods=('GET',))
def getSlotDetails(slotNumber):
return render_template('beacon-frontend/one-slot.html', slotNumber=slotNumber) |
def and_pred(*preds):
def new_pred(*args):
for pred in preds:
if (not pred(*args)):
return False
return True
return new_pred |
def tokenize(sql, value_tokenize, parsed=False, **kwargs):
ast = (sql if parsed else parse(sql))
tokenizer = Tokenizer(value_tokenize, **kwargs)
(tokens, token_types) = tokenizer.tokenize(ast)
if tokenizer.atomic_value:
return (tokens, token_types, tokenizer.constants)
else:
return (... |
def test_kernel_and_bias_defaults():
(graph, _) = create_graph_features()
generator = ClusterNodeGenerator(graph)
cluster_gcn = ClusterGCN(layer_sizes=[2, 2], activations=['relu', 'relu'], generator=generator)
for layer in cluster_gcn._layers:
if isinstance(layer, GraphConvolution):
... |
def _persist_stop_words(stop_words, path):
stop_words = sorted(stop_words)
with path.open(encoding='utf8', mode='w') as f:
for stop_word in stop_words:
f.write(('%s\n' % stop_word)) |
def run_benchmark(benchmark, ranks, opts):
group = dist.new_group(ranks=ranks, backend=benchmark.distributed_backend)
measurements = []
if (dist.get_rank() in set(ranks)):
if (not opts):
opts = dict()
measurements = benchmark_process_group(group, benchmark, **opts)
dist.destr... |
class ReLU6(Hardtanh):
def __init__(self, inplace=False):
super(ReLU6, self).__init__(0, 6, inplace)
def extra_repr(self):
inplace_str = ('inplace' if self.inplace else '')
return inplace_str |
def get_random_pairs(size):
pairs = []
while (len(pairs) < size):
must_same = choice([True, False])
if must_same:
class_ = images_above1.sample().iloc[0]['class']
same_pairs = images_above1[(images_above1['class'] == class_)].sample(2)
pairs.append((same_pairs... |
class TStrHashF_Md5(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def GetPrimHashCd(*args):
return _snap.TStrHashF_Md5_GetPrimHashCd(*args)
GetPrimHashCd = staticmethod(GetPrimHashCd)
def GetSecHashC... |
class InstallPlatlib(install):
'Fix auditwheel error,
def finalize_options(self) -> None:
install.finalize_options(self)
if self.distribution.has_ext_modules():
self.install_lib = self.install_platlib |
.parametrize('shuffle', [False, True])
def test_kg_triple_sequence_shuffle(shuffle):
seq = KGTripleSequence(max_node_iloc=10, source_ilocs=[0, 1, 2, 3, 4], rel_ilocs=[0, 1, 0, 1, 0], target_ilocs=[4, 3, 2, 1, 0], batch_size=5, shuffle=shuffle, negative_samples=None, sample_strategy='uniform', seed=None)
assert ... |
class SawyerButtonPressWallEnv(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.05), 0.85, 0.05)
obj_high = (0.05, 0.9, 0.05)
super().__init__(self.model_name, hand_low=hand_low, hand_high=hand_high)
self.ini... |
def calc_boomerang_cod(location, orientation):
r_vectors = bm.get_boomerang_r_vectors_15(location, orientation)
dist = 0.96087
coh = ((location + ((np.cos((np.pi / 4.0)) * (dist / 2.1)) * (r_vectors[0] - location))) + ((np.cos((np.pi / 4.0)) * (dist / 2.1)) * (r_vectors[14] - location)))
return coh |
class CSBuFLO():
def __init__(self, initial_rho=INIT_RHO):
self.initial_rho = initial_rho
def reset(self):
self.defended_trace = Queue()
self.client = CSBuFLOEndpoint(self.defended_trace, OUT, self.initial_rho)
self.server = CSBuFLOEndpoint(self.defended_trace, IN, self.initial_r... |
('shorter_resize_for_crop')
def shorter_resize_for_crop(cfg, **kwargs):
size = (kwargs['input_size'] if (kwargs['input_size'] != None) else cfg.INPUT_SIZE)
assert (size[0] == size[1]), 'this img-process only process square-image'
return transforms.Resize(int((size[0] / 0.875))) |
_model('lightconv_lm')
class LightConvLanguageModel(FairseqLanguageModel):
def __init__(self, decoder):
super().__init__(decoder)
def add_args(parser):
parser.add_argument('--dropout', default=0.1, type=float, metavar='D', help='dropout probability')
parser.add_argument('--attention-drop... |
def evaluate_box_proposals(dataset, roidb):
res = _empty_box_proposal_results()
areas = {'all': '', 'small': 's', 'medium': 'm', 'large': 'l'}
for limit in [100, 1000, 5000, 10000, 50000, 100000]:
for (area, suffix) in areas.items():
stats = json_dataset_evaluator.evaluate_box_proposals(... |
class BengaliDoc2vec():
def __init__(self, model_path: str='', tokenizer: Callable=None):
if ((model_path == '') or (model_path == ModelTypeEnum.NEWS_DOC2VEC)):
model_path = download_model(ModelTypeEnum.NEWS_DOC2VEC)
if (model_path == ModelTypeEnum.WIKI_DOC2VEC):
model_path =... |
class ElectraForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def main():
print('*** Negative Sample Generation ***')
num_neg_e_per_pos = 20
neg_sample_strategy = 'hist_rnd'
rnd_seed = 42
name = 'tgbl-comment'
dataset = PyGLinkPropPredDataset(name=name, root='datasets')
train_mask = dataset.train_mask
val_mask = dataset.val_mask
test_mask = dat... |
class Partition1(nn.Module):
LAYER_SCOPES = ['WideResNet/NetworkBlock[block1]/Sequential[layer]/BasicBlock[2]/Conv2d[conv2]', 'WideResNet/NetworkBlock[block1]/Sequential[layer]/BasicBlock[3]/GroupNorm[bn1]', 'WideResNet/NetworkBlock[block1]/Sequential[layer]/BasicBlock[3]/ReLU[relu1]', 'WideResNet/NetworkBlock[bloc... |
def dump_mixed_4a_7a(name='Mixed_4a'):
dump_conv2d(name=(name + '/Branch_0/Conv2d_0a_1x1'))
dump_conv2d(name=(name + '/Branch_0/Conv2d_1a_3x3'))
dump_conv2d(name=(name + '/Branch_1/Conv2d_0a_1x1'))
dump_conv2d(name=(name + '/Branch_1/Conv2d_0b_1x7'))
dump_conv2d(name=(name + '/Branch_1/Conv2d_0c_7x1... |
def get_rank(group):
if use_xla():
assert (group[0] == 'tpu')
my_group = _find_my_group(group[1])
return my_group.index(get_global_rank())
else:
return dist.get_rank(group=group) |
def append_atom():
choices = [['single', ['C', 'N', 'O', 'F', 'S', 'Cl', 'Br'], (7 * [(1.0 / 7.0)])], ['double', ['C', 'N', 'O'], (3 * [(1.0 / 3.0)])], ['triple', ['C', 'N'], (2 * [(1.0 / 2.0)])]]
p_BO = [0.6, 0.35, 0.05]
index = np.random.choice(list(range(3)), p=p_BO)
(BO, atom_list, p) = choices[inde... |
def to_diff_file(old_str, new_str):
diff = difflib.ndiff(old_str.splitlines(1), new_str.splitlines(1))
result = '\n'.join(diff)
return result |
def test_release():
parser = _get_command_line_parser(['valid-detector'], [], [])
result = parser.parse_args(['run', 'ex1', 'valid-detector', '--tag', 'FSE17'])
assert_equals('fse17', result.requested_release) |
def reset_handler(handler):
for _logger in all_loggers:
del _logger.handlers[:]
_logger.addHandler(handler)
if (file_handler is not None):
_logger.addHandler(file_handler) |
def model_fn_builder(bert_config, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings):
def model_fn(features, labels, mode, params):
tf.logging.info('*** Features ***')
for name in sorted(features.keys()):
tf.logging.info((' name = %s, sha... |
def setup_snapshot_image_grid(training_set, random_seed=0):
rnd = np.random.RandomState(random_seed)
gw = np.clip((7680 // training_set.image_shape[2]), 15, 32)
gh = np.clip((4320 // training_set.image_shape[1]), 8, 32)
if (not training_set.has_labels):
all_indices = list(range(len(training_set)... |
class SubsampleDataset(BaseWrapperDataset):
def __init__(self, dataset, size_ratio):
super().__init__(dataset)
assert (size_ratio < 1)
self.actual_size = np.ceil((len(dataset) * size_ratio)).astype(int)
self.indices = np.random.choice(list(range(len(self.dataset))), self.actual_size,... |
def simulate(N=100, k=10000):
truth = gen_prob_dist(N)
area_ratio = truth
(accept, alias) = create_alias_table(area_ratio)
ans = np.zeros(N)
for _ in range(k):
i = alias_sample(accept, alias)
ans[i] += 1
return ((ans / np.sum(ans)), truth) |
class CommandCollection(MultiCommand):
def __init__(self, name=None, sources=None, **attrs):
MultiCommand.__init__(self, name, **attrs)
self.sources = (sources or [])
def add_source(self, multi_cmd):
self.sources.append(multi_cmd)
def get_command(self, ctx, cmd_name):
for sou... |
def polevl(x, coefs, n):
ans = 0
power = (len(coefs) - 1)
for coef in coefs:
ans += (coef * (x ** power))
power -= 1
return ans |
class TestCOCOeval(unittest.TestCase):
def test_fast_eval(self):
detections = [{'image_id': 139, 'category_id': 1, 'bbox': [417., 159., 47., 143.], 'score': 0., 'segmentation': {'size': [426, 640], 'counts': 'Tc`52W=3N0N4aNN^E7]:4XE1g:8kDMT;UO1gE[Nk8h1dFiNY9Z1aFkN]9g2J3NdN`FlN`9S1cFRN07]9g1bFoM6;X9c1cFoM=8R... |
class Node2Vec():
def __init__(self, emb_size, generator=None, node_num=None, multiplicity=None):
self.generator = generator
if (generator is not None):
self._get_sizes_from_generator(generator)
else:
self.input_node_num = _require_without_generator(node_num, 'node_nu... |
class Wide_ResNet(nn.Module):
def __init__(self, depth, widen_factor, num_classes, stride=1, parallel=False):
super(Wide_ResNet, self).__init__()
self.num_classes = num_classes
self.in_planes = 16
assert (((depth - 4) % 6) == 0), 'Wide-resnet_v2 depth should be 6n+4'
n = int(... |
class DummyCriticNet():
def __init__(self):
pass
def parameters(self):
return torch.zeros(5)
def __call__(self, observation, actions):
value = torch.max(observation, dim=(- 1)).values
q_value = torch.max(actions, axis=(- 1)).values
ret = (value + q_value)
retu... |
def get_chunks(seq, tags, message=None):
default = tags[NONE]
idx_to_tag = {idx: tag for (tag, idx) in tags.items()}
chunks = []
(chunk_type, chunk_start) = (None, None)
for (i, tok) in enumerate(seq):
if ((tok == default) and (chunk_type is not None)):
chunk = (chunk_type, chunk... |
def masked_select(tensor: Tensor, *, mask: Tensor, dims: Sequence[Dim], out_dim: Optional[Dim]=None) -> Tuple[(Tensor, Dim)]:
return tensor._raw_backend.masked_select(tensor, mask=mask, dims=dims, out_dim=out_dim) |
('(float32[:], float32[:], int32, int32, float32[:])', device=True, inline=True)
def line_segment_intersection(pts1, pts2, i, j, temp_pts):
A = cuda.local.array((2,), dtype=numba.float32)
B = cuda.local.array((2,), dtype=numba.float32)
C = cuda.local.array((2,), dtype=numba.float32)
D = cuda.local.array... |
class TestMultipleInputsMultipleOutputsKerasFQExporter(KerasFakeQuantExporterBaseTest):
def get_input_shape(self):
return [(30, 30, 3), (28, 28, 3)]
def get_tpc(self):
tp = generate_test_tp_model({'weights_n_bits': 2})
return generate_keras_tpc(name='test_conv2d_2bit_fq_weight', tp_model... |
class DebertaV2ForMaskedLM():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def check_and_reduce_pair(x1, x2=None):
y1 = [Integer(x) for x in x1]
if ((x2 is None) or (not x2) or (x2[0] is Infinity)):
y2 = [Infinity]
if (not y1):
raise ValueError('continued fraction can not represent infinity')
elif ((len(y1) > 1) and (y1[(- 1)] == 1)):
y1... |
.gpu
.parametrize('img', (real_image3d()[1], random_image((33, 44, 55))))
.parametrize('n_rays', (4, 16, 32))
.parametrize('grid', ((1, 1, 1), (1, 2, 4)))
def test_types_gpu(img, n_rays, grid):
mode = 'opencl'
rays = Rays_GoldenSpiral(n_rays)
gt = star_dist3D(img, rays=rays, grid=grid, mode=mode)
for dt... |
def get_training_parser(default_task='translation'):
parser = get_parser('Trainer', default_task)
add_dataset_args(parser, train=True)
add_distributed_training_args(parser)
add_model_args(parser)
add_optimization_args(parser)
add_checkpoint_args(parser)
return parser |
def _run_operation(n: BaseNode, input_tensors: List, op_func: Any, quantize_node_activation_fn, use_activation_quantization: bool) -> Tuple[(Union[(List, torch.Tensor)], Union[(List, torch.Tensor)])]:
op_call_args = (n.op_call_args if isinstance(n, FunctionalNode) else [])
functional_kwargs = (n.op_call_kwargs ... |
class DistOptimizerHook(OptimizerHook):
def __init__(self, grad_clip=None, coalesce=True, bucket_size_mb=(- 1)):
self.grad_clip = grad_clip
self.coalesce = coalesce
self.bucket_size_mb = bucket_size_mb
def after_train_iter(self, runner):
runner.optimizer.zero_grad()
runne... |
def print_header():
header = ' _____ _ ____ _______ _ ___ _ _ _____ \n/ ___| | / /\\ \\ / / ___ \\ | / _ \\ | \\ | || ___|\n\\ `--.| |/ / \\ V /| |_/ / | / /_\\ \\| \\| || |__ \n `--. \\ \\ \\ / | __/| | | _ || . ` || __| \n/\\__/ / |\\ \\ | | | | | |____| | | || |\\ || |... |
def build_joint_config(args: argparse.Namespace):
drop_rates = ((0.0, 0.05, args.drop_rate) if args.use_locked_drop else (args.drop_rate, 0.0, 0.0))
if (args.ck_decoder == 'sequence_tagging'):
ck_decoder_config = SequenceTaggingDecoderConfig(scheme=args.scheme, use_crf=args.use_crf, fl_gamma=args.fl_gam... |
class RestrictedImageNet(DataSet):
def __init__(self, data_path, **kwargs):
ds_name = 'restricted_imagenet'
ds_kwargs = {'num_classes': len(constants.RESTRICTED_IMAGNET_RANGES), 'mean': ch.tensor([0.4717, 0.4499, 0.3837]), 'std': ch.tensor([0.26, 0.2516, 0.2575]), 'custom_class': None, 'label_mappin... |
def register_Ns3DefaultDeleter__Ns3SpectrumSignalParameters_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::DefaultDeleter< ns3::SpectrumSignalParameters > const &', 'arg0')])
cls.add_method('Delete', 'void', [param('ns3::SpectrumSignalParameters *', 'object')], is_static... |
def _create_fake_setuptools_pkg_info(placeholder):
if ((not placeholder) or (not os.path.exists(placeholder))):
log.warn('Could not find the install location')
return
pyver = ('%s.%s' % (sys.version_info[0], sys.version_info[1]))
setuptools_file = ('setuptools-%s-py%s.egg-info' % (SETUPTOOLS... |
class EuclideanLoss(BaseLossWithValidity):
def calculate_loss(self, a, b):
assert (a.ndim == b.ndim)
assert (a.ndim > 1)
squared_difference = torch.pow((a - b), 2)
ssd = torch.sum(squared_difference, axis=tuple(range(1, a.ndim)))
return torch.sqrt(ssd) |
_function_dispatch(_fftn_dispatcher)
def ifftn(a, s=None, axes=None, norm=None):
return _raw_fftnd(a, s, axes, ifft, norm) |
def test_compare_gt():
a_raw = torch.tensor([2.0, 2.0, 2.0])
b_raw = torch.tensor([1.0, 2.0, 3.0])
feature_dim = Dim(3)
a = Tensor(name='a', raw_tensor=a_raw, dims=[feature_dim], dtype='float32')
b = Tensor(name='b', raw_tensor=b_raw, dims=[feature_dim], dtype='float32')
result = (a > b)
res... |
def imnormalize_(img, mean, std, to_rgb=True):
assert (img.dtype != np.uint8)
mean = np.float64(mean.reshape(1, (- 1)))
stdinv = (1 / np.float64(std.reshape(1, (- 1))))
if to_rgb:
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
cv2.subtract(img, mean, img)
cv2.multiply(img, stdinv, img)
re... |
class LongformerTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
def __init__(self, vocab_file, merges_file,... |
class CCInterpreter(StackInterpreter):
name = 'cc'
def __init__(self):
mc_retval = MemoryChunkCCRetval('retval', ty_mpc)
super(CCInterpreter, self).__init__(ty_mpc, mc_retval=mc_retval)
self.err_return = '0'
self.mc_py_constants = MemoryChunkConstants('py_constants', ty_python)
... |
def conv_block(input_mat, num_filters, kernel_size, batch_norm):
X = Conv3D(num_filters, kernel_size=(kernel_size, kernel_size, kernel_size), strides=(1, 1, 1), padding='same')(input_mat)
if batch_norm:
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(num_filters, kernel_size=(ke... |
def is_file(path, filename, restore=False):
if os.path.isdir(path):
if os.path.isfile((path + filename)):
if (restore == False):
open((path + filename), 'w').close()
else:
pass
else:
open((path + filename), 'w').close()
else:
... |
class Environment(object):
sandboxed = False
overlayed = False
linked_to = None
shared = False
code_generator_class = CodeGenerator
context_class = Context
def __init__(self, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING... |
def check_error(res: int) -> None:
if (res != _cudart.cudaError.success):
raise CudaError(res) |
def add_python_install(libz3Component):
name = 'python_install'
reg_component(name, PythonInstallComponent(name, libz3Component)) |
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding... |
def find_extension(codec):
if (codec in extensions_dict):
return codec
for (ext, infos) in extensions_dict.items():
if (codec in infos.get('codec', [])):
return ext
raise ValueError('The audio_codec you chose is unknown by MoviePy. You should report this. In the meantime, you can... |
class TransformedDataset(Dataset):
def __init__(self, dataset, transform=None, target_transform=None, as_rgb=False):
self.dataset = dataset
self.transform = transform
self.target_transform = target_transform
self.as_rgb = as_rgb
def __len__(self):
return len(self.dataset)... |
class Model(torch.nn.Module):
def __init__(self, args, concat=False):
super(Model, self).__init__()
self.args = args
self.num_features = args.num_features
self.nhid = args.nhid
self.num_classes = args.num_classes
self.dropout_ratio = args.dropout_ratio
self.mo... |
def tensorflow2pytorch():
lookup_inception_resnet_v1 = {'conv2d_1a': ['InceptionResnetV1/Conv2d_1a_3x3', load_tf_basicConv2d], 'conv2d_2a': ['InceptionResnetV1/Conv2d_2a_3x3', load_tf_basicConv2d], 'conv2d_2b': ['InceptionResnetV1/Conv2d_2b_3x3', load_tf_basicConv2d], 'conv2d_3b': ['InceptionResnetV1/Conv2d_3b_1x1'... |
def main():
config_path = './config.json'
with open(config_path) as f:
args = json.load(f)
args = AttrDict(args)
device = torch.device(args.device)
args.model = nn.chimera(**args['model_options'])
args.model.to(device)
args.train_loader = data.wsj0_2mix_dataloader(args.model_name... |
def constant(fill_value: RawTensorTypes, *, dims: Sequence[Dim], dtype: Optional[str]=None, device: Optional[str]=None, sparse_dim: Optional[Dim]=None, feature_dim: Optional[Dim]=None) -> Tensor:
return full(dims=dims, fill_value=fill_value, dtype=dtype, device=device, sparse_dim=sparse_dim, feature_dim=feature_dim... |
def _calculate_dynamic_per_channel_qparams(X, dtype):
if isinstance(X, torch.Tensor):
X = X.numpy()
(qmin, qmax) = (torch.iinfo(dtype).min, torch.iinfo(dtype).max)
n_levels = (qmax - qmin)
scale = np.zeros(X.shape[0], dtype=np.float64)
zero_point = np.zeros(X.shape[0], dtype=np.int64)
fo... |
def test_linalg_cholesky():
A = generate_positive_semidefinite_matrix(100, np.float64)
ref = np.linalg.cholesky(A)
val = linalg_cholesky(A)
assert (relative_error(val, ref) < 1e-10) |
def validate_nl_postcode(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(postcode.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != '... |
def register_Ns3LteRrcSapRrcConnectionReestablishmentReject_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteRrcSap::RrcConnectionReestablishmentReject const &', 'arg0')])
return |
class Gatv2CifarNet(CifarNet):
def make_graph_layer(self, hidden_dim, layer_idx):
heads = (8 if (layer_idx != (self.num_graph_layers - 1)) else 1)
return GATv2Conv(hidden_dim, (hidden_dim // heads), heads=heads) |
class GroupedBatchSampler(BatchSampler):
def __init__(self, sampler, group_ids, batch_size):
if (not isinstance(sampler, Sampler)):
raise ValueError('sampler should be an instance of torch.utils.data.Sampler, but got sampler={}'.format(sampler))
self.sampler = sampler
self.group_... |
class AttentionBlock(nn.Module):
def __init__(self, F_g, F_l, n_coefficients):
super(AttentionBlock, self).__init__()
self.W_gate = nn.Sequential(nn.Conv2d(F_g, n_coefficients, kernel_size=1, stride=1, padding=0, bias=True), nn.BatchNorm2d(n_coefficients))
self.W_x = nn.Sequential(nn.Conv2d(... |
class TrivialMapEliminationTest(unittest.TestCase):
def test_can_be_applied(self):
graph = trivial_map_sdfg()
count = graph.apply_transformations(TrivialMapElimination)
self.assertGreater(count, 0)
def test_removes_map(self):
graph = trivial_map_sdfg()
graph.apply_transfo... |
def check_gcc_variable_attribute(cmd, attribute):
cmd._check_compiler()
body = (textwrap.dedent('\n #pragma GCC diagnostic error "-Wattributes"\n #pragma clang diagnostic error "-Wattributes"\n\n int %s foo;\n\n int\n main()\n {\n return 0;\n }\n ... |
def build_optimizer(cfg: CfgNode, model: torch.nn.Module) -> torch.optim.Optimizer:
norm_module_types = (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.SyncBatchNorm, torch.nn.GroupNorm, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.LayerNorm, torch.... |
def logistic_loss_cond(scores, labels):
cond = tf.select(tf.equal(labels, tf.zeros(tf.shape(labels))), tf.zeros(tf.shape(labels)), tf.nn.sigmoid_cross_entropy_with_logits(logits=scores, labels=labels))
cls_loss = tf.reduce_mean(tf.reduce_sum(cond, [1, 2, 3]))
return cls_loss |
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert (inputs.shape[0] == targets.shape[0])
if shuffle:
indices = np.arange(inputs.shape[0])
np.random.shuffle(indices)
for start_idx in tqdm(range(0, inputs.shape[0], batchsize)):
if shuffle:
excerpt = ... |
def get_score(model, device, train_loader, test_loader):
train_feature_space = []
with torch.no_grad():
for (imgs, _) in tqdm(train_loader, desc='Train set feature extracting'):
imgs = imgs.to(device)
(_, features) = model(imgs)
train_feature_space.append(features)
... |
.parametrize('join', ['left outer', 'right outer'])
def test_combine_workspace_same_channels_outer_join_unsafe(workspace_factory, join, caplog):
ws = workspace_factory()
new_ws = ws.rename(channels={ws.channels[(- 1)]: 'new_channel'})
pyhf.Workspace.combine(ws, new_ws, join=join)
assert ('using an unsaf... |
def dates_checker(feature: pd.Series) -> bool:
try:
feature = pd.to_datetime(feature)
if ((feature.min().year <= 1975) or (feature.min().year is np.nan)):
return False
else:
return True
except ValueError:
return False
except Exception:
raise Va... |
('/upload')
def upload():
username = request.args.get('username')
filename = request.files.get('attachment').filename
re.search(username, filename) |
def process_en_conll03(paths, short_name):
ner_input_path = paths['NERBASE']
conll_path = os.path.join(ner_input_path, 'english', 'en_conll03')
ner_output_path = paths['NER_DATA_DIR']
convert_en_conll03.process_dataset('en_conll03', conll_path, ner_output_path) |
def cvt_ECSSD():
img_list = sorted(glob(os.path.join(args.src, 'images', '*.jpg')), key=(lambda x: (len(x), x)))
mask_list = sorted(glob(os.path.join(args.src, 'ground_truth_mask', '*.png')), key=(lambda x: (len(x), x)))
dst_img_dir = os.path.join(args.dst, 'JPEGImages', args.name)
dst_mask_dir = os.pat... |
def merge_output(res, total_pixels, batch_size):
model_outputs = {}
for entry in res[0]:
if (res[0][entry] is None):
continue
if (len(res[0][entry].shape) == 1):
model_outputs[entry] = torch.cat([r[entry].reshape(batch_size, (- 1), 1) for r in res], 1).reshape((batch_size... |
class PredictDiff(nn.Module):
def __init__(self, config, cln=21, in_channel=256, in_channel2=128, dr_rate_d=0.5):
super(PredictDiff, self).__init__()
self.config = config
chn = 256
self.conv1c = Conv2dbnPR(cln, chn, kernel_size=1, stride=1, padding=0)
self.conv1abc = Bottlene... |
def main():
set_seeds(2020)
args = vars(parser.parse_args())
alphabet = Protein()
cfgs = []
data_cfg = config.DataConfig(args['data_config'])
cfgs.append(data_cfg)
if (args['lm_model_config'] is None):
model_cfg = config.ModelConfig(args['model_config'], input_dim=len(alphabet), num_... |
def vgg_a(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_a'):
with tf.variable_scope(scope, 'vgg_a', [inputs]) as sc:
end_points_collection = (sc.name + '_end_points')
with slim.arg_scope([slim.conv2d, slim.max_pool2d], outputs_collections=end_poi... |
_utils.test()
def test_matrix_field_non_constant_index():
m = ti.Matrix.field(2, 2, ti.i32, 5)
v = ti.Vector.field(10, ti.i32, 5)
def func1():
for i in range(5):
for (j, k) in ti.ndrange(2, 2):
m[i][(j, k)] = ((j * j) + (k * k))
func1()
assert (m[1][(0, 1)] == 1)
... |
def register_functions(root_module):
module = root_module
module.add_function('Integral', 'double', [param('ns3::SpectrumValue const &', 'arg')])
module.add_function('Log', 'ns3::SpectrumValue', [param('ns3::SpectrumValue const &', 'arg')])
module.add_function('Log10', 'ns3::SpectrumValue', [param('ns3:... |
_numpy_output(non_zero=True, check_dtype=True)
def test_square_as_multiply(A: dace.complex64[10], I: dace.bool_[10]):
np.multiply(A, A, where=I) |
def fusion_re(**kwargs):
sq = squeezenet1_1(pretrained=True)
model = CreateNetFusion_re(sq, stack=True)
return model |
class JBluesDetailed(ProcessingPlasmaProperty):
outputs = ('j_blues',)
latex_name = 'J_{\\textrm{blue}}'
def __init__(self, plasma_parent, w_epsilon):
super(JBluesDetailed, self).__init__(plasma_parent)
self.w_epsilon = w_epsilon
def calculate(self, lines, nu, t_rad, w, j_blues_norm_fact... |
class PaviClient(object):
def __init__(self, url, username=None, password=None, instance_id=None):
self.url = url
self.username = self._get_env_var(username, 'PAVI_USERNAME')
self.password = self._get_env_var(password, 'PAVI_PASSWORD')
self.instance_id = instance_id
self.log_... |
class AutoModelForAudioFrameClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class DecoderEmbedding(nn.Module):
def __init__(self, n_responses, n_dims, seq_len):
super(DecoderEmbedding, self).__init__()
self.n_dims = n_dims
self.seq_len = seq_len
self.response_embed = nn.Embedding(n_responses, n_dims)
self.time_embed = nn.Linear(1, n_dims, bias=False)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.