code stringlengths 101 5.91M |
|---|
def test_olsq_depth_normal_circstr_devtmp():
lsqc_solver = OLSQ('depth', 'normal')
lsqc_solver.setdevice(device_tmp)
lsqc_solver.setprogram(circuit_str)
assert (lsqc_solver.solve()[2] == 14) |
def splev(x, tck, der=0, ext=0):
(t, c, k) = tck
try:
c[0][0]
parametric = True
except Exception:
parametric = False
if parametric:
return list(map((lambda c, x=x, t=t, k=k, der=der: splev(x, [t, c, k], der, ext)), c))
else:
if (not (0 <= der <= k)):
... |
def _prepare_gradient_if_op(fwd_op, input_names, output_names, then_grad_net, else_grad_net):
gradient_if_def = caffe2_pb2.OperatorDef()
gradient_if_def.CopyFrom(fwd_op)
del gradient_if_def.input[:]
gradient_if_def.input.extend(input_names)
del gradient_if_def.output[:]
gradient_if_def.output.ex... |
def Cifar100(home_path, model_name):
from tensorflow.keras.datasets.cifar100 import load_data
((train_images, train_labels), (val_images, val_labels)) = load_data()
teacher = sio.loadmat((home_path + ('/pre_trained/%s.mat' % model_name)))
def pre_processing(image, is_training):
with tf.variable_... |
_module()
class BasePartSeg(BaseSeg):
def __init__(self, encoder_args=None, decoder_args=None, cls_args=None, **kwargs):
super().__init__(encoder_args, decoder_args, cls_args, **kwargs)
def forward(self, p0, f0=None, cls0=None):
if hasattr(p0, 'keys'):
(p0, f0, cls0) = (p0['pos'], p0... |
def str2bool(v):
if isinstance(v, bool):
return v
if (v.lower() in ('yes', 'true', 't', 'y', '1')):
return True
elif (v.lower() in ('no', 'false', 'f', 'n', '0')):
return False
else:
raise argparse.ArgumentTypeError('boolean value expected') |
def test_get_init_msa(msa_sampler):
seed = ['AAA', 'ACC', 'ACDE']
batch_size = 2
max_len = 5
result = msa_sampler.get_init_msa(seed, 5, 2)
assert (result.shape[0] == batch_size)
assert (result.shape[1] == len(seed))
assert (result.shape[2] == (max_len + 1))
assert (result[0][0].tolist() ... |
def clear_parameters():
global current_scope
for key in list(current_scope.keys()):
del current_scope[key] |
def process_base_case(header_contents):
retval = list()
if (len(header_contents) == 0):
return retval
if (len(header_contents) == 1):
headers = header_contents[0].header
header_text = ''.join([h for h in headers])
contents = header_contents[0].content
content_text = '... |
def load_checkpoint(train_config, path, map_location='cuda', strict=True):
model: torch.nn.Module = make_training_model(train_config)
state = torch.load(path, map_location=map_location)
model.load_state_dict(state['state_dict'], strict=strict)
model.on_load_checkpoint(state)
return model |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = FixedBatchNorm(planes)
self.conv2 = nn.Conv2d(... |
def test_get_nrows():
assert (1000 == get_nrows('1000'))
assert (1 == get_nrows('1'))
assert (get_nrows('None') is None)
assert (get_nrows('asdf') is None) |
def pre_user_cohort_demo(indir, patient_list):
cad_user_cohort_demo = {}
file = '{}/demo.csv'.format(indir)
with open(file, 'r') as f:
next(f)
for row in f:
row = row.split(',')
(id, db, sex) = (row[0], row[1], row[2])
if (id in patient_list):
... |
_properties
class StreamingMemory(xf.SingleStateTransformation):
access = xf.PatternNode(nodes.AccessNode)
entry = xf.PatternNode(nodes.EntryNode)
exit = xf.PatternNode(nodes.ExitNode)
buffer_size = properties.Property(dtype=int, default=1, desc='Set buffer size for the newly-created stream')
storag... |
def process_root_test():
root = '~/test'
module_dir = utils.process_root(root, module_name='test_module')
print(module_dir) |
class TestBidafPredictor(TestCase):
def test_uses_named_inputs(self):
inputs = {'question': 'What kind of test succeeded on its first attempt?', 'passage': 'One time I was writing a unit test, and it succeeded on the first attempt.'}
archive = load_archive('tests/fixtures/bidaf/serialization/model.t... |
def _copyto(a, val, mask):
if isinstance(a, np.ndarray):
np.copyto(a, val, where=mask, casting='unsafe')
else:
a = a.dtype.type(val)
return a |
class BatchPermutationOpTest(unittest.TestCase):
def _run_op_test(self, X, I, check_grad=False):
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CUDA, 0)):
op = core.CreateOperator('BatchPermutation', ['X', 'I'], ['Y'])
workspace.FeedBlob('X', X)
workspace.FeedBlob('I'... |
def solc_wrapper(solc_binary: Union[(Path, str)]=None, stdin: str=None, source_files: Union[(List, Path, str)]=None, import_remappings: Union[(Dict, List, str)]=None, success_return_code: int=None, **kwargs: Any) -> Tuple[(str, str, List, subprocess.Popen)]:
if solc_binary:
solc_binary = Path(solc_binary)
... |
class HyperParam():
def __init__(self, dtype=None, bounds=None, classes=None, log=False, default=None):
if isinstance(dtype, (list, tuple)):
assert (classes is None)
assert (bounds is None)
classes = dtype
dtype = None
if (dtype is None):
a... |
class B(FairseqDataclass):
bar: A = field(default=A())
foo: int = field(default=0, metadata={'help': 'not a bar'}) |
def main():
args = parse_args()
assert (args.out or args.eval or args.format_only or args.show or args.show_dir), 'Please specify at least one operation (save/eval/format/show the results / save the results) with the argument "--out", "--eval", "--format-only", "--show" or "--show-dir"'
if (args.eval and ar... |
class C(nn.Module):
def __init__(self, nIn, nOut, kSize, stride=1, groups=1):
super().__init__()
padding = int(((kSize - 1) / 2))
self.conv = nn.Conv2d(nIn, nOut, kSize, stride=stride, padding=padding, bias=False, groups=groups)
def forward(self, input):
output = self.conv(input)... |
def isotopism(p):
if isinstance(p, (Integer, int)):
return Permutation(range(1, (p + 1)))
if isinstance(p, PermutationGroupElement):
return Permutation(list(p.tuple()))
if isinstance(p, list):
return Permutation([(x + 1) for x in p])
if isinstance(p, tuple):
if isinstance... |
class EarlyStopping():
def __init__(self, name, patience=8):
self.patience = patience
self.best_model = None
self.best_score = None
self.best_epoch = 0
self.epoch = 0
self.name = name
self.logger = LogHelper.get_logger(EarlyStopping.__name__)
def __call__(... |
def flatten_and_concat(Xs: List[torch.Tensor]) -> torch.Tensor:
return torch.cat([X.flatten() for X in Xs], dim=0) |
def upsample2(input, data_format):
assert (data_format == 'NHWC')
output = tf.transpose(input, [0, 3, 1, 2])
output = tf.concat([output, output, output, output], axis=1)
output = tf.transpose(output, [0, 2, 3, 1])
output = tf.depth_to_space(output, 2)
return output |
def WDLEstimator(linear_feature_columns, dnn_feature_columns, dnn_hidden_units=(256, 128, 64), l2_reg_linear=1e-05, l2_reg_embedding=1e-05, l2_reg_dnn=0, seed=1024, dnn_dropout=0, dnn_activation='relu', task='binary', model_dir=None, config=None, linear_optimizer='Ftrl', dnn_optimizer='Adagrad', training_chief_hooks=No... |
def _write_signal(sim, signal_name, signal_value):
signal_name = _find_signal(sim, signal_name)
sim.io[signal_name] = signal_value |
def parse_args():
parser = argparse.ArgumentParser(description='Re-evaluate results')
parser.add_argument('output_dir', nargs=1, help='results directory', type=str)
parser.add_argument('--dataset', dest='dataset_name', help='dataset to re-evaluate', default='voc_2007_test', type=str)
parser.add_argument... |
def handleEntity(ctxObj, publish):
print('Implement losic')
print(ctxObj)
publish(ctxObj) |
class EntangleNode(Node):
def __init__(self, name: str, timeline: 'Timeline', src_list: List[str]):
super().__init__(name, timeline)
self.bsm_name = (name + '.bsm')
bsm = QSDetectorFockInterference(self.bsm_name, timeline, src_list)
self.add_component(bsm)
bsm.attach(self)
... |
def read_cifar10(filename_queue):
class CIFAR10Record(object):
pass
result = CIFAR10Record()
label_bytes = 1
result.height = 32
result.width = 32
result.depth = 3
image_bytes = ((result.height * result.width) * result.depth)
record_bytes = (label_bytes + image_bytes)
reader =... |
def mobilenet_v2(pretrained=False, progress=True, device='cpu', **kwargs):
model = MobileNetV2(**kwargs)
if pretrained:
script_dir = os.path.dirname(__file__)
state_dict = torch.load((script_dir + '/state_dicts/mobilenet_v2.pt'), map_location=device)
model.load_state_dict(state_dict)
... |
def pytorch_func(a, b, c, d, e, f, tensor_kwargs=None):
if (tensor_kwargs is None):
tensor_kwargs = {'device': a.device, 'dtype': a.dtype}
_a_out = a
_b_out = b
_c_out = _broadcast_and_stack([c[(..., 0)], c[(..., 1)], c[(..., 2)]], dim=(- 1))
_d_out = _broadcast_and_stack([_broadcast_and_sta... |
def read_json(filename, encoding='utf-8'):
contents = get_file_contents(filename, encoding=encoding)
return json.loads(contents) |
class EventString():
def __init__(self, at=0, value=''):
self.at = at
self.value = value |
def decapitalize(tok):
if (len(tok) == 0):
return tok
(pre, tok) = ((HALF, tok[1:]) if (tok[0] == HALF) else ('', tok))
if (tok[0] == tok[0].lower()):
return (pre + tok)
if ((tok[0] == tok[0].upper()) and ((len(tok) == 1) or (tok[1] != tok[1].upper()))):
return (((CAP + pre) + to... |
def test_precision_macro_3d_np_array():
y_true = np.array([[['human', 'mermaid'], ['', '']], [['human', 'minotaur'], ['bull', 'minotaur']]])
y_pred = np.array([[['human', 'mermaid'], ['fish', 'mermaid']], [['human', 'minotaur'], ['bull', 'minotaur']]])
assert (0.8333 == approx(precision(y_true, y_pred, 'mac... |
def batchnorm_args_preprocessor(args, kwargs):
converted = []
if (len(args) > 1):
raise TypeError('The `BatchNormalization` layer does not accept positional arguments. Use keyword arguments instead.')
return (args, kwargs, converted) |
(message='scipy.misc.replace_notes_in_docstring is deprecated in Scipy 1.3.0')
def replace_notes_in_docstring(cls, notes):
return _ld.replace_notes_in_docstring(cls, notes) |
def upload_file_to_s3_with_backoff(local_filename, key, *, bucket, num_tries=5, initial_delay=1.0, delay_factor=math.sqrt(2.0), thread_local=None):
assert pathlib.Path(local_filename).is_file()
if (thread_local is None):
client = get_s3_client()
else:
if (not hasattr(thread_local, 's3_client... |
def get_marg_probs(filename='BSSG_input.txt'):
subprocess.call(['/opt/gurobi701/linux64/bin/gurobi.sh', 'BSG_multi_milp.py', filename]) |
def test_BBPSSW_phi_minus_psi_minus():
counter = 0
for i in range(100):
(tl, kept1, kept2, meas1, meas2, ep1, ep2) = create_scenario(phi_minus, psi_minus, i)
assert (kept1.entangled_memory == kept2.entangled_memory == {'node_id': None, 'memo_id': None})
assert (ep1.meas_res != ep2.meas_r... |
def valid_string_length(label, trailing_dot):
if (len(label) > (254 if trailing_dot else 253)):
return False
return True |
.gpu
def test_gpu_access_on_device_interstate_edge_default():
sdfg = dace.SDFG('tester')
sdfg.add_array('A', [20], dace.float64, storage=dace.StorageType.GPU_Global)
state = sdfg.add_state()
(me, mx) = state.add_map('test', dict(i='0:20'))
nsdfg = dace.SDFG('nester')
nsdfg.add_array('A', [20], d... |
def fuse_four_images(img_paths, image_size):
fuse_img_1 = fuse_two_images(img_paths[0:2], image_size)
fuse_img_2 = fuse_two_images(img_paths[2:4], image_size)
fuse_img = np.concatenate([fuse_img_1, fuse_img_2], axis=1)
return fuse_img |
class LifelongAntEnv(mujoco_env.MujocoEnv, utils.EzPickle):
def __init__(self, xml_file='ant.xml', gear_ratio=30, ctrl_cost_weight=0.01, contact_cost_weight=0.0005, healthy_reward=1.0, terminate_when_unhealthy=True, healthy_z_range=(0.2, 1.2), contact_force_range=((- 1.0), 1.0), reset_noise_scale=0.1, exclude_curre... |
def DFG_python(root_node, index_to_code, states):
assignment = ['assignment', 'augmented_assignment', 'for_in_clause']
if_statement = ['if_statement']
for_statement = ['for_statement']
while_statement = ['while_statement']
do_first_statement = ['for_in_clause']
def_statement = ['default_paramete... |
def to_video(ema_model, arg):
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.animation as animation
import matplotlib.image as mpimg
ema_model.eval()
num = 100
if (arg.dataset != 'cifar10'):
num = 25
save_sample_q(ema_model, 0, arg, num=num, video=Tr... |
def ComputeRHS(rhs, w_hat, solver, work, Tp, VT, VTp, K, K2, K_over_K2, Source, u_dealias, mask, **context):
rhs = solver.conv(rhs, w_hat, work, Tp, VTp, K, K_over_K2, u_dealias)
if (mask is not None):
rhs.mask_nyquist(mask)
rhs = solver.add_linear(rhs, w_hat, params.nu, K2, Source)
return rhs |
def test_pooling1d(device):
from speechbrain.nnet.pooling import Pooling1d
input = torch.tensor([1, 3, 2], device=device).unsqueeze(0).unsqueeze((- 1)).float()
pool = Pooling1d('max', 3).to(device)
output = pool(input)
assert (output == 3)
pool = Pooling1d('avg', 3).to(device)
output = pool(... |
def supported_graphbuilder_generator():
for weighted in [True, False]:
for include_self_edges in [True, False]:
normalize_cases = [False]
if (weighted and include_self_edges):
normalize_cases.append(True)
for normalize_self_edges in normalize_cases:
... |
class Helper(HelperBase):
def increment_average(self, model, model_next, n):
return np.add(model, ((model_next - model) / n))
def save(self, model, path=None):
if (not path):
(_, path) = tempfile.mkstemp()
np.savetxt(path, model)
return path
def load(self, path):
... |
def test_register_cached(auth_storage, auth_provider_class):
auth_storage.register()(auth_provider_class)
assert auth_storage.providers
assert isinstance(auth_storage.providers[0], CachingAuthProvider)
assert isinstance(auth_storage.providers[0].provider, auth_provider_class) |
def test_two_tag_training_backprop(pretrain_file, tmp_path):
trainer = run_two_tag_training(pretrain_file, tmp_path)
trainer.save(os.path.join(trainer.args['save_dir'], trainer.args['save_name']))
new_trainer = run_two_tag_training(pretrain_file, tmp_path, '--finetune')
assert (len(trainer.model.tag_clf... |
class TestNagFCompilerVersions(object):
def test_version_match(self):
for (comp, vs, version) in nag_version_strings:
fc = numpy.distutils.fcompiler.new_fcompiler(compiler=comp)
v = fc.version_match(vs)
assert_((v == version)) |
def rotate_pose_msg_by_euler_angles(pose, r, p, y):
initial = matrix_from_pose_msg(pose)
transform = quaternion_matrix(quaternion_from_euler(r, p, y))
return pose_msg_from_matrix(concatenate_matrices(initial, transform)) |
def dict_to_json(dict, fname):
with open(fname, 'a') as f:
json.dump(dict, f)
f.write('\n') |
class Code(io.StringIO):
def start(self, indent, fmt, *args):
self.write((u' ' * indent))
self.add(fmt, *args)
def add(self, fmt, *args):
self.write(self._format(fmt, args))
def end(self, fmt, *args):
self.add(fmt, *args)
self.write(u'\n')
def _format(self, fmt... |
def readJSONLine(path, verbose=False):
input = readTXTFile(path)
data = []
for each_line in input:
each_line = each_line.strip()
each_line = json.loads(each_line)
data.append(each_line)
if verbose:
print('[I] file read complete')
return data |
def test_BinIOUSegmLoss():
reset_seed(0, check_cudnn=False)
instance = BinIOUSegmLoss(smooth=1.0)
announce_msg('Testing {}'.format(instance))
cuda = 0
DEVICE = torch.device(('cuda:{}'.format(cuda) if torch.cuda.is_available() else 'cpu'))
if torch.cuda.is_available():
torch.cuda.set_devi... |
def ideal_to_gfan_format(input_ring, polys):
ideal_gen_str = (('{' + ','.join((str(poly).replace(' ', '').replace("'", '') for poly in polys))) + '}')
ring_str = ring_to_gfan_format(input_ring)
output = (ring_str + ideal_gen_str)
return output |
.parametrize('key, mat, quad', some_mats_and_quads)
def test_isub(key, mat, quad):
test = key[0]
trial = key[1]
measure = 1
if (len(key) == 3):
measure = key[2]
if (quad == 'GL'):
return
t0 = test[0]
t1 = trial[0]
if (trial[0] in bcbases):
t1 = functools.p... |
def dctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
shape = _good_shape(x, shape, axes)
return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x) |
class SchurTensorModule(CombinatorialFreeModule_Tensor):
def __init__(self, R, n, r):
C = CombinatorialFreeModule(R, list(range(1, (n + 1))))
self._n = n
self._r = r
self._sga = SymmetricGroupAlgebra(R, r)
self._schur = SchurAlgebra(R, n, r)
cat = ModulesWithBasis(R).... |
class GroupedEpochBatchIterator(EpochBatchIterator):
def __init__(self, dataset, collate_fn, batch_samplers, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=0, mult_rate=1, buffer_size=0):
super().__init__(dataset, collate_fn, batch_samplers, seed, num_shards, shard_id, num_workers, epoch, buffer_siz... |
def update_shard_values_for_worker(num_workers, worker_id):
num_shards_per_worker = 1
for num_shards in tf.get_collection(shard.NUM_SHARDS):
num_shards_tensor = num_shards.op.node_def.attr['value'].tensor
num_shards_per_worker = num_shards_tensor.int64_val[0]
num_shards_tensor.int64_val[... |
(frozen=True)
class DecodeRequest():
tokens: List[int]
tokenizer: str = 'huggingface/gpt2'
clean_up_tokenization_spaces: bool = False
def tokenizer_organization(self):
return self.tokenizer.split('/')[0]
def tokenizer_name(self):
return self.tokenizer.split('/')[1] |
def find_matching_trees(docs, num_sentences, accepted_trees, tag_pipe, parser_pipes, shuffle=True, chunk_size=10, max_len=140, min_len=10, output_ptb=False):
if (num_sentences < 0):
tqdm_total = len(docs)
else:
tqdm_total = num_sentences
if output_ptb:
output_format = '{}'
else:
... |
def test_BitMaskedArray_NumpyArray():
v2a = ak.contents.bitmaskedarray.BitMaskedArray(ak.index.Index(np.packbits(np.array([1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1], np.uint8))), ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6])), valid_when=True, length... |
def v2w(signal, n):
s = ''
for i in range((n - 1), 0, (- 1)):
s = (((s + signal) + str(i)) + ', ')
s = ((s + signal) + '0')
return s |
def test_observers(short_test_case):
tracer = ExecutionTracer()
tracer.current_thread_identifier = threading.current_thread().ident
executor = TestCaseExecutor(tracer)
observer = MagicMock()
observer.before_statement_execution.side_effect = (lambda x, y, z: y)
executor.add_observer(observer)
... |
def QuaternionMatrixGroupGF3():
from sage.rings.finite_rings.finite_field_constructor import FiniteField
from sage.matrix.matrix_space import MatrixSpace
MS = MatrixSpace(FiniteField(3), 2)
aye = MS([1, 1, 1, 2])
jay = MS([2, 1, 1, 1])
return MatrixGroup([aye, jay]) |
def to_mkldnn(module):
def m_fn(m):
if isinstance(m, torch.nn.Linear):
return MkldnnLinear(m)
elif isinstance(m, torch.nn.Conv1d):
return MkldnnConv1d(m)
elif isinstance(m, torch.nn.Conv2d):
return MkldnnConv2d(m)
elif isinstance(m, torch.nn.Conv3d... |
def read_directory(dirname, broken_ok=False, tree_callback=None):
trees = []
for filename in sorted(os.listdir(dirname)):
full_name = os.path.join(dirname, filename)
trees.extend(read_tree_file(full_name, broken_ok, tree_callback))
return trees |
def selectTrainData(tweets, targets):
inv_topics = {v: k for (k, v) in preprocess.TOPICS_LONG.items()}
inlist = []
outcnt = 0
for (i, tweet) in enumerate(tweets):
target_keywords = preprocess.KEYWORDS.get(inv_topics.get(targets[i]))
target_in_tweet = 0
for key in target_keywords:... |
.parametrize('channel_axis', [0, 1, 2, (- 1), (- 2), (- 3)])
def test_build_laplacian_pyramid_rgb(channel_axis):
image = data.astronaut()
(rows, cols, dim) = image.shape
image = np.moveaxis(image, source=(- 1), destination=channel_axis)
pyramid = pyramids.pyramid_laplacian(image, downscale=2, channel_ax... |
class Attention(nn.Module):
def __init__(self, style_dim=64):
super().__init__()
self.layers = nn.Sequential(nn.Linear(style_dim, style_dim), nn.ReLU(), nn.Linear(style_dim, style_dim))
def forward(self, s):
return self.layers(s) |
class SawyerPlateSlideSideEnv(SawyerXYZEnv):
def __init__(self):
goal_low = ((- 0.3), 0.6, 0.02)
goal_high = ((- 0.25), 0.7, 0.02)
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = (0.0, 0.6, 0.015)
obj_high = (0.0, 0.6, 0.015)
super().__init... |
()
('dump_db_file', type=click.Path(exists=True))
('tokenizer_name')
('entity_vocab_file', type=click.Path(exists=True))
('output_dir', type=click.Path(file_okay=False))
('--language', type=str)
('--sentence-splitter', default='en')
('--max-seq-length', default=512)
('--max-entity-length', default=128)
('--max-mention-... |
def rot6d_to_quat(rotation_6d: Union[(torch.Tensor, numpy.ndarray)]) -> Union[(torch.Tensor, numpy.ndarray)]:
if (rotation_6d.shape[(- 1)] != 6):
raise ValueError(f'Invalid input rotation_6d shape f{rotation_6d.shape}.')
t = Compose([rotation_6d_to_matrix, matrix_to_quaternion])
return t(rotation_6d... |
class hypsecant_gen(rv_continuous):
def _shape_info(self):
return []
def _pdf(self, x):
return (1.0 / (np.pi * np.cosh(x)))
def _cdf(self, x):
return ((2.0 / np.pi) * np.arctan(np.exp(x)))
def _ppf(self, q):
return np.log(np.tan(((np.pi * q) / 2.0)))
def _sf(self, x):... |
def register_Ns3UanMacAloha_methods(root_module, cls):
cls.add_constructor([param('ns3::UanMacAloha const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True)
cls.add_method('AttachPhy', 'void', [param('ns3::Ptr< ns3::UanPhy >', ... |
def get_root_logger(log_file=None, log_level=logging.INFO):
logger = get_logger(name='mmseg', log_file=log_file, log_level=log_level)
return logger |
def G_adv_loss(pred_fake, w=None):
w = match_size(w, pred_fake)
return (w * (- pred_fake)).mean() |
class SAM(torch.optim.Optimizer):
def __init__(self, params, base_optimizer, rho=0.05, adaptive=False, **kwargs):
assert (rho >= 0.0), f'Invalid rho, should be non-negative: {rho}'
defaults = dict(rho=rho, adaptive=adaptive, **kwargs)
super(SAM, self).__init__(params, defaults)
self.... |
def ref_linear_interpolate_2d(x, output_size, align_corners, half_pixel):
oshape = output_size
ishape = x.shape[(- 2):]
xx = x.reshape((- 1), *ishape)
ib = np.arange(xx.shape[0])
scale = (compute_scale(ishape[0], oshape[0], align_corners), compute_scale(ishape[1], oshape[1], align_corners))
inde... |
class StripTokenDataset(BaseWrapperDataset):
def __init__(self, dataset, id_to_strip):
super().__init__(dataset)
self.id_to_strip = id_to_strip
def __getitem__(self, index):
item = self.dataset[index]
return item[item.ne(self.id_to_strip)] |
class ViewNet(nn.Module):
def __init__(self):
super(ViewNet, self).__init__()
print('ViewNet...')
self.net = encoder3D2D.Net3D2D(hyp.feat3D_dim, 64, 32, hyp.view_depth, depth_pool=8).cuda()
self.rgb_layer = nn.Sequential(nn.LeakyReLU(), nn.Conv2d(32, 32, kernel_size=3, stride=1, padd... |
def check_or_download_inception(inception_path):
INCEPTION_URL = '
if (inception_path is None):
inception_path = '/tmp'
inception_path = pathlib.Path(inception_path)
model_file = (inception_path / 'classify_image_graph_def.pb')
if (not model_file.exists()):
print('Downloading Incepti... |
.parametrize('in_shape', [(1, 2, 3)])
def test_swish(in_shape: Sequence[int]) -> None:
x = torch.rand(in_shape)
swish = Swish()
y = swish(x)
assert (y.shape == in_shape)
assert torch.allclose(y, (x * torch.sigmoid(x))) |
class SpatialReflectionPadding(Module):
def __init__(self, pad_l, pad_r=None, pad_t=None, pad_b=None):
super(SpatialReflectionPadding, self).__init__()
self.pad_l = pad_l
self.pad_r = (pad_r if (pad_r is not None) else pad_l)
self.pad_t = (pad_t if (pad_t is not None) else pad_l)
... |
class UnionType(LayoutBuilderType):
def __init__(self, tags_dtype, index_dtype, contents, parameters):
super().__init__(name=f'ak.lb.Union({tags_dtype}, {index_dtype}, {contents}, parameters={parameters!r})')
self._tags_dtype = tags_dtype
self._index_dtype = index_dtype
self._conten... |
def _build_vocabulary(input_files):
if FLAGS.vocab_file:
tf.logging.info('Loading existing vocab file.')
vocab = collections.OrderedDict()
with tf.gfile.GFile(FLAGS.vocab_file, mode='r') as f:
for (i, line) in enumerate(f):
word = line.decode('utf-8').strip()
... |
class ModuleDict(Module):
_modules: Dict[(str, Module)]
def __init__(self, modules: Optional[Mapping[(str, Module)]]=None) -> None:
super(ModuleDict, self).__init__()
if (modules is not None):
self.update(modules)
_copy_to_script_wrapper
def __getitem__(self, key: str) -> Mod... |
class FlaxResNetPreTrainedModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class Normalize():
def __init__(self, mean, std, device='cpu'):
self.mean = torch.tensor(mean, device=device).reshape(1, len(mean), 1, 1)
self.std = torch.tensor(std, device=device).reshape(1, len(mean), 1, 1)
def __call__(self, x, seed=(- 1)):
return ((x - self.mean) / self.std) |
def J_adjoint_checkpointing(model, src_coords, wavelet, rec_coords, recin, space_order=8, is_residual=False, n_checkpoints=None, born_fwd=False, return_obj=False, ic='as', ws=None, nlind=False, f0=0.015, misfit=None, illum=False, fw=True):
ffunc = op_fwd_J[born_fwd]
(op_f, u, rec_g, kwu) = ffunc(model, src_coor... |
class SawyerHandlePressEnvV2(SawyerXYZEnv):
def __init__(self):
hand_low = ((- 0.5), 0.4, 0.05)
hand_high = (0.5, 1, 0.5)
obj_low = ((- 0.1), 0.8, (- 0.001))
obj_high = (0.1, 0.9, (+ 0.001))
goal_low = ((- 0.1), 0.55, 0.04)
goal_high = (0.1, 0.7, 0.08)
super()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.