code stringlengths 101 5.91M |
|---|
class TestMotionBindings(unittest.TestCase):
def test_zero_getters(self):
v = pin.Motion.Zero()
self.assertTrue(np.allclose(zero(3), v.linear))
self.assertTrue(np.allclose(zero(3), v.angular))
self.assertTrue(np.allclose(zero(6), v.vector))
def test_setRandom(self):
v = p... |
def _skip_slow():
if (os.environ.get('ASV_SKIP_SLOW', '0') == '1'):
raise NotImplementedError('Skipping this test...') |
class SpatialSoftmax3D(torch.nn.Module):
def __init__(self, depth, height, width, channel):
super(SpatialSoftmax3D, self).__init__()
self.depth = depth
self.height = height
self.width = width
self.channel = channel
self.temperature = 0.01
(pos_x, pos_y, pos_z)... |
class CoolObjectAction(BaseAction):
valid_actions = {'OpenObject', 'CloseObject', 'PickupObject', 'PutObject'}
def get_reward(self, state, prev_state, expert_plan, goal_idx):
if (state.metadata['lastAction'] not in self.valid_actions):
(reward, done) = (self.rewards['invalid_action'], False)... |
class DoubleMNIST(CombinationMetaDataset):
def __init__(self, root, num_classes_per_task=None, meta_train=False, meta_val=False, meta_test=False, meta_split=None, transform=None, target_transform=None, dataset_transform=None, class_augmentations=None, download=False):
dataset = DoubleMNISTClassDataset(root,... |
def main(args):
fpaths = glob.glob(f'{args.dpath}/*mesh00.obj')
for fpath in fpaths:
print(f'Processing {fpath}...')
mesh = o3d.io.read_triangle_mesh(fpath)
if (args.filter_iters > 0):
mesh = mesh.filter_smooth_simple(number_of_iterations=args.filter_iters)
(fpath, ex... |
def test_simplify_mixed_ws():
helpers.disbale_tqdm()
helpers.setup(with_data=True)
test_lines = ['a b c\n', 'test\tdata stuff\n', 'to test\tstuff\n']
out_file = os.path.join(helpers.DATA_DIR, 'test.cat')
with open(out_file, 'w') as f:
f.writelines(test_lines)
convert._simplify_mixe... |
def select_examples_NQ(data, index, passages, passages_index):
selected_data = []
for (i, k) in enumerate(index):
ctxs = [{'id': idx, 'title': passages[idx][1], 'text': passages[idx][0]} for idx in passages_index[str(i)]]
dico = {'question': data[k]['question'], 'answers': data[k]['answer'], 'ct... |
class SBCSGroupProber(CharSetGroupProber):
def __init__(self):
super(SBCSGroupProber, self).__init__()
self.probers = [SingleByteCharSetProber(Win1251CyrillicModel), SingleByteCharSetProber(Koi8rModel), SingleByteCharSetProber(Latin5CyrillicModel), SingleByteCharSetProber(MacCyrillicModel), SingleBy... |
def replace_EO(sentence, EO, ent_type_labels, cur_type, entities):
s = ' '.join(sentence)
e = ' '.join(entities)
s = s.replace(e, ' '.join((['XXX'] * len(entities))))
s = s.split()
assert (len(s) == len(EO))
flag = True
cont = 0
indices_list = []
for i in range(len(s)):
if (s... |
def alpha_calc(RACC, ACC, POP):
try:
epsi = (1 / (2 * POP))
p_a = (((1 - epsi) * ACC) + epsi)
p_e = RACC
return reliability_calc(p_e, p_a)
except Exception:
return 'None' |
def command_generator():
args_msgs = []
for (token, item) in setting.items():
arg = setting[token]['arg']
val = np.random.choice(setting[token]['value'])
args_msgs.append(f'{arg} {val}')
args_msg = ' '.join(args_msgs)
command = ('python train.py ' + args_msg)
return (command,... |
def solve(proto, snapshot, gpus, timing, uid, rank):
caffe.set_mode_gpu()
caffe.set_device(gpus[rank])
caffe.set_solver_count(len(gpus))
caffe.set_solver_rank(rank)
caffe.set_multiprocess(True)
solver = caffe.SGDSolver(proto)
if (snapshot and (len(snapshot) != 0)):
solver.restore(sna... |
def load_usps0_noisy():
(X_train, y_train, X_test, y_test) = load_usps0()
n_samples = X_train.shape[0]
indices = np.arange(n_samples)
random_state = check_random_state(0)
random_state.shuffle(indices)
n = (n_samples / 10)
indices = indices[:n]
y_train[indices] = np.logical_not(y_train[in... |
def result_message(finding, info_finding):
message = (finding.get('message') or info_finding.get('descr_short') or finding['name'])
severity = finding.get('severity')
return (f'''{message}
Severity: {severity}''' if (message and severity) else (message if message else (f'Severity: {severity}' if severity el... |
def strainxx(xx):
(x, y) = (xx[0], xx[1])
Q = qload
return ((((- 2) * pi) * np.sin(((2 * pi) * x))) * np.sin((pi * y))) |
def flatten_dict(d, parent_key='', sep='_'):
items = []
for (k, v) in d.items():
new_key = (((parent_key + sep) + k) if parent_key else k)
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return d... |
class EffHead(nn.Module):
def __init__(self, w_in, w_out, bn_norm):
super(EffHead, self).__init__()
self.conv = nn.Conv2d(w_in, w_out, 1, stride=1, padding=0, bias=False)
self.conv_bn = get_norm(bn_norm, w_out)
self.conv_swish = Swish()
def forward(self, x):
x = self.conv... |
class T5Corrector():
def __init__(self, model_name_or_path: str='shibing624/mengzi-t5-base-chinese-correction'):
t1 = time.time()
self.tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
self.model = T5ForConditionalGeneration.from_pretrained(model_name_or_path)
self.model.... |
def broadcast_to_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, axis=None):
dy = grad_inputs[0]
x0 = inputs[0]
raise NotImplementedError('broadcast_to_backward is not implemented.') |
class TextClassificationPipeline(Pipeline):
def __call__(self, *args, **kwargs):
outputs = super().__call__(*args, **kwargs)
scores = (np.exp(outputs) / np.exp(outputs).sum((- 1)))
return [{'label': self.model.config.id2label[item.argmax()], 'score': item.max()} for item in scores] |
def barrier(group: Optional[ProcessGroup]=None) -> None:
if is_distributed():
if (group is None):
group = get_default_group()
torch_dist.barrier(group) |
def build_dataset(is_train, args):
transform = build_transform(is_train, args)
root = os.path.join(args.data_path, ('train' if is_train else 'val'))
dataset = datasets.ImageFolder(root, transform=transform)
print(dataset)
return dataset |
class TFAlbertForTokenClassification(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
.torch
def test_item_ids_are_grouped_to_sequences_with_subset(small_dataset: Dataset, item_id_and_item_feature_schema: TensorSchema):
tokenizer = SequenceTokenizer(item_id_and_item_feature_schema).fit(small_dataset)
sequential_dataset = tokenizer.transform(small_dataset, tensor_features_to_keep=['item_id'])
... |
(frozen=True)
class DiscreteSACModules(Modules):
policy: CategoricalPolicy
q_funcs: nn.ModuleList
targ_q_funcs: nn.ModuleList
log_temp: Optional[Parameter]
actor_optim: Optimizer
critic_optim: Optimizer
temp_optim: Optional[Optimizer] |
def make_model(config):
model_type = config['aspect_term_model']['type']
if (model_type == 'recurrent_capsnet'):
return make_recurrent_capsule_network(config)
elif (model_type == 'bert_capsnet'):
return make_bert_capsule_network(config)
else:
raise ValueError('No Supporting.') |
class SASRecDataset(Dataset):
def __init__(self, args, user_seq, test_neg_items=None, data_type='train'):
self.args = args
self.user_seq = user_seq
self.test_neg_items = test_neg_items
self.data_type = data_type
self.max_len = args.max_seq_length
def _data_sample_rec_task... |
def GetPseudoAAC2(ProteinSequence, lamda=30, weight=0.05, AAP=[_Hydrophobicity, _hydrophilicity]):
rightpart = []
for i in range(lamda):
rightpart.append(GetSequenceOrderCorrelationFactor(ProteinSequence, (i + 1), AAP))
result = {}
temp = (1 + (weight * sum(rightpart)))
for index in range(20... |
class MLP(nn.Module):
def __init__(self, n_in, n_out, dropout=0, activation=True):
super().__init__()
self.n_in = n_in
self.n_out = n_out
self.linear = nn.Linear(n_in, n_out)
self.activation = (nn.LeakyReLU(negative_slope=0.1) if activation else nn.Identity())
self.dr... |
class SetPartitionsPk_k(SetPartitionsAk_k):
def _repr_(self):
return (SetPartitionsAk_k._repr_(self) + ' that are planar')
def __contains__(self, x):
if (not SetPartitionsAk_k.__contains__(self, x)):
return False
if (not is_planar(x)):
return False
return ... |
def pose_to_siren_to_pose(p: Pose, fps=None) -> Pose:
p.body.zero_filled()
(mu, std) = p.normalize_distribution()
net = siren.get_pose_siren(p, total_steps=3000, steps_til_summary=100, learning_rate=0.0001, cuda=True)
new_fps = (fps if (fps is not None) else p.body.fps)
coords = siren.PoseDataset.ge... |
.parametrize('module_creator', [ModuleCreator(TSTNetNormal(), [(4, 3, 32, 32), (4, 3, 32, 32)]), ModuleCreator(ResUnit(16), [(4, 3, 32, 32)]), ModuleCreator(NestedTestNet(), [(4, 3, 32, 32), (4, 3, 32, 32)])])
def test_with_statement_graph_def(module_creator):
module = module_creator.module
proto_variable_input... |
class ExceptionWrapper(object):
def __init__(self, exc_info=None, where='in background'):
if (exc_info is None):
exc_info = sys.exc_info()
self.exc_type = exc_info[0]
self.exc_msg = ''.join(traceback.format_exception(*exc_info))
self.where = where
def reraise(self):
... |
def load_data(path, alphabet):
with open(path, 'rb') as f:
(names, structs, sequences) = scop.parse_astral(f, encoder=alphabet)
x = [torch.from_numpy(x).long() for x in sequences]
s = torch.from_numpy(structs)
c = []
for name in names:
name = name.decode('utf-8')
if (name not... |
def run_partition(args, data, metas):
(assignments, shard_names, filenames, clustering_types) = preprocess(data, args.computation.num_workers, args.log_every, verbose=args.verbose)
samples_list = run_greedy(args, assignments, shard_names, filenames, clustering_types, args.subset.size, args.subset.ratio, measure... |
class Encode2DVAE_nb(nn.Module):
def __init__(self, opt, out_dim=None, num_blocks=2):
super(Encode2DVAE_nb, self).__init__()
if (out_dim is None):
output_dim = opt.nfc
else:
assert (type(out_dim) is int)
output_dim = out_dim
self.features = Feature... |
class DarknetBasicBlockV3(gluon.HybridBlock):
def __init__(self, channel, num_sync_bn_devices=(- 1), **kwargs):
super(DarknetBasicBlockV3, self).__init__(**kwargs)
self.body = nn.HybridSequential(prefix='')
self.body.add(_conv2d(channel, 1, 0, 1, num_sync_bn_devices))
self.body.add(_... |
def get_args():
parser = argparse.ArgumentParser()
arg = parser.add_argument
arg('-c', '--config_path', type=Path, help='Path to the config.', required=True)
return parser.parse_args() |
def test_evaluate_classification_coverage(tmpdir):
stream = RandomTreeGenerator(tree_random_state=23, sample_random_state=12, n_classes=2, n_cat_features=2, n_num_features=5, n_categories_per_cat_feature=5, max_tree_depth=6, min_leaf_depth=3, fraction_leaves_per_level=0.15)
nominal_attr_idx = [x for x in range(... |
class SeparatorStyle(Enum):
SINGLE = auto()
TWO = auto()
MPT = auto()
PLAIN = auto()
LLAMA_2 = auto() |
def subprocess_fn(rank, args):
if (not args.debug):
dnnlib.util.Logger(file_name=os.path.join(args.run_dir, 'log.txt'), file_mode='a', should_flush=True)
distributed_utils.init_distributed_mode(rank, args)
if (args.rank != 0):
custom_ops.verbosity = 'none'
training_loop.training_loop(**a... |
def tokenize(tokenizer, tokens: List[str], splits: List[int]):
tok_to_orig_index = []
orig_to_tok_index = []
all_doc_tokens = []
tok_to_orig_span_index = defaultdict(list)
for (i, s) in enumerate(splits):
tok_to_orig_span_index[s].append(i)
span_to_orig_index = dict()
for (i, token) ... |
def make_data_formatter(exp_name):
data_formatter_class = {'volatility': data_formatters.volatility.VolatilityFormatter, 'electricity': data_formatters.electricity.ElectricityFormatter, 'traffic': data_formatters.traffic.TrafficFormatter, 'favorita': data_formatters.favorita.FavoritaFormatter}
return data_forma... |
def train(predictor, x, split_edge, optimizer, batch_size):
predictor.train()
pos_train_edge = split_edge['train']['edge'].to(x.device)
total_loss = total_examples = 0
for perm in DataLoader(range(pos_train_edge.size(0)), batch_size, shuffle=True):
optimizer.zero_grad()
edge = pos_train_... |
class ME(nn.Module):
def __init__(self, cin, cout):
super().__init__()
self.maxpool = nn.MaxPool2d(2, ceil_mode=True)
self.pw = nn.Conv2d(cin, cout, 1, 1, bias=False)
self.bn = nn.BatchNorm2d(cout)
def forward(self, x):
x = self.maxpool(x)
x = self.pw(x)
x... |
def dump_tower(sess, net, from_layer, tower_name, tower_layers, operation='create'):
for tower_layer in tower_layers:
tower_layer = '{}/{}'.format(tower_name, tower_layer)
if ('pool' in tower_layer):
dump_pool(sess, net, from_layer, tower_layer, operation)
else:
dump_... |
class AlbertOnnxConfig(OnnxConfig):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
if (self.task == 'multiple-choice'):
dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
dynamic_axis = {0: 'batch', 1: 'sequence'}
return OrderedDict([('input_ids',... |
def syscall_get_stdout(cmd):
try:
out = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE).communicate()[0].decode('utf-8').rstrip()
return out.split('\n')
except:
raise Error(('Error in system call. I tried to run:\n' + str(cmd))) |
def append_data(save_folder, data, corpus):
logger.info((('Preparing ' + corpus) + '.csv'))
to_append = []
for line in tqdm(data):
(channel, filename, speaker_name, sentences) = line
out = subprocess.Popen(['soxi', '-D', ((((save_folder + '/wav/') + channel) + filename) + '.wav')], stdout=su... |
def make_roi_mask_loss_evaluator():
matcher = Matcher(cfg.MODEL.ROI_HEADS.FG_IOU_THRESHOLD, cfg.MODEL.ROI_HEADS.BG_IOU_THRESHOLD, allow_low_quality_matches=False)
loss_evaluator = MaskRCNNLossComputation(matcher, cfg.MODEL.ROI_MASK_HEAD.RESOLUTION)
return loss_evaluator |
def killProcess(processID):
if (processID is None):
return
if (platform.system() == 'Windows'):
import ctypes
handle = ctypes.windll.kernel32.OpenProcess(2, False, processID)
ctypes.windll.kernel32.TerminateProcess(handle, (- 1))
ctypes.windll.kernel32.CloseHandle(handle)... |
def get_parameter_groups(model, stage_cfg, print_log=False):
weight_decay = stage_cfg.weight_decay
embed_weight_decay = stage_cfg.embed_weight_decay
backbone_lr_ratio = stage_cfg.backbone_lr_ratio
base_lr = stage_cfg.learning_rate
backbone_params = []
embed_params = []
other_params = []
... |
def _determine_child_storage(parent_schedules: List[dtypes.ScheduleType]) -> Optional[dtypes.StorageType]:
for sched in reversed(parent_schedules):
if ((sched is not None) and (sched in dtypes.SCOPEDEFAULT_STORAGE) and (sched != dtypes.ScheduleType.Sequential)):
child_sched = dtypes.SCOPEDEFAULT... |
def in_notebook():
try:
shell = get_ipython().__class__.__name__
if (shell == 'ZMQInteractiveShell'):
return True
elif (shell == 'TerminalInteractiveShell'):
return False
else:
return False
except NameError:
return False |
def calcul_value(annotation_list):
all_vlaue = {}
for i in annotation_list:
k = i['image_id']
v = i['caption']
if (v in all_vlaue):
all_vlaue[v] = (all_vlaue.get(v) + 1)
else:
all_vlaue[v] = 1
return all_vlaue |
def _get_extension():
if (TORCH_VERSION == 'parrots'):
from parrots.utils.build_extension import BuildExtension, Extension
CppExtension = partial(Extension, cuda=False)
CUDAExtension = partial(Extension, cuda=True)
else:
from torch.utils.cpp_extension import BuildExtension, CppEx... |
class BaseDataset(Dataset, ABC):
def __init__(self, datadir: str, scene_bbox: torch.Tensor, split: str, is_ndc: bool, is_contracted: bool, rays_o: Optional[torch.Tensor], rays_d: Optional[torch.Tensor], intrinsics: Union[(Intrinsics, List[Intrinsics])], batch_size: Optional[int]=None, imgs: Optional[Union[(torch.Te... |
.parametrize('metric', METRICS)
def test_kernel_density_numerical_consistency(global_random_seed, metric):
(X_64, X_32, Y_64, Y_32) = get_dataset_for_binary_tree(random_seed=global_random_seed)
metric_params = METRICS.get(metric, {})
kd_64 = KDTree64(X_64, leaf_size=2, metric=metric, **metric_params)
kd... |
def test_ufunc_add_where_list():
A = np.random.randint(1, 10, size=(2,), dtype=np.int32)
B = np.random.randint(1, 10, size=(2,), dtype=np.int32)
try:
C = ufunc_add_where_list(A, B)
except:
assert True
return
assert False |
def pytest_addoption(parser):
parser.addoption('--fuser', default='old', help='fuser to use for benchmarks')
parser.addoption('--executor', default='legacy', help='executor to use for benchmarks') |
def LR_CI_calc(mean, SE, CV=1.96):
try:
CI_down = math.exp((math.log(mean) - (CV * SE)))
CI_up = math.exp((math.log(mean) + (CV * SE)))
return (CI_down, CI_up)
except Exception:
return ('None', 'None') |
class Precision(BaseMetric):
def __init__(self, recommendations, config, params, eval_objects):
super().__init__(recommendations, config, params, eval_objects)
self._cutoff = self._evaluation_objects.cutoff
self._relevance = self._evaluation_objects.relevance.binary_relevance
def name():... |
def load_model(app):
(Output('cytoscape-responsive-layout', 'elements'), Output('top-label', 'children'), Output('top-label', 'style'), Output('forward', 'n_clicks'), Input('auto_load', 'interval'))
def callback(interval):
import os
path = os.getcwd()
errmsg_style = component.top_lable_s... |
def format_ov_stats(stats: Dict[(str, List[Any])]) -> Tuple[(Dict[(str, str)], List[Dict[(str, str)]])]:
(nrows, ncols, npresent_cells, nrows_wo_dups, mem_use, dtypes_cnt) = stats.values()
ncells = np.multiply(nrows, ncols).tolist()
data = {'Number of Variables': ncols, 'Number of Rows': nrows, 'Missing Cel... |
class StarDistBase(BaseModel):
def __init__(self, config, name=None, basedir='.'):
super().__init__(config=config, name=name, basedir=basedir)
threshs = dict(prob=None, nms=None)
if (basedir is not None):
try:
threshs = load_json(str((self.logdir / 'thresholds.jso... |
class TAscFlt(TFlt):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TAscFlt_swiginit(self, _snap.new_TAscFlt(*args))
def Save(self, SOut):
return _snap.TAscFlt_Save(self, S... |
def load_model(name, model_type, is_eval=False, device='cpu', checkpoint=None):
model = registry.get_model_class(name).from_pretrained(model_type=model_type)
if (checkpoint is not None):
model.load_checkpoint(checkpoint)
if is_eval:
model.eval()
if (device == 'cpu'):
model = mode... |
def test_psp_head():
with pytest.raises(AssertionError):
PSPHead(in_channels=32, channels=16, num_classes=19, pool_scales=1)
head = PSPHead(in_channels=32, channels=16, num_classes=19)
assert (not _conv_has_norm(head, sync_bn=False))
head = PSPHead(in_channels=32, channels=16, num_classes=19, no... |
def convert_cmake_value_to_python_value(cmake_value, cmake_type):
cmake_type = cmake_type.upper()
up_val = cmake_value.upper()
if (cmake_type == 'BOOL'):
return (not ((up_val in ('FALSE', 'OFF', 'N', 'NO', '0', '', 'NOTFOUND')) or up_val.endswith('-NOTFOUND')))
elif (cmake_type == 'FILEPATH'):
... |
_utils.test(arch=[ti.cuda, ti.cpu], real_matrix_scalarize=False)
def test_local_matrix_indexing_in_loop():
s = ti.field(ti.i32, shape=(3, 3))
def test():
mat = ti.Matrix([[((x * 3) + y) for y in range(3)] for x in range(3)])
for i in range(3):
for j in range(3):
s[(i,... |
class CheckPointState(object):
def __init__(self):
self.root_problem = None
self.temp_root = None
self.cumulative_time = 0 |
def do_analyse_sick(file_path, dev=True, delta=1, stop=None):
results = []
with open(file_path, 'r', encoding='utf-8') as file:
find_entry = False
output = [0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
for line in file:
if (not find_entry):
if line.startswith('d... |
class LogAnomaly(ParamInfoMixin):
algorithms = {'one_class_svm': ('logai.algorithms.anomaly_detection_algo.one_class_svm', 'OneClassSVMDetector', 'OneClassSVMParams'), 'isolation_forest': ('logai.algorithms.anomaly_detection_algo.isolation_forest', 'IsolationForestDetector', 'IsolationForestParams'), 'lof': ('logai... |
def load_valid_paths():
with open('./valid_paths.txt', 'r') as fp:
paths = [line.strip() for line in fp if (line.strip() != '')]
return paths |
class CartanType(cartan_type.CartanType_decorator):
def __classcall__(cls, ct, marked_nodes):
ct = cartan_type.CartanType(ct)
if (not marked_nodes):
return ct
if any(((node not in ct.index_set()) for node in marked_nodes)):
raise ValueError('invalid marked node')
... |
class CarSprite(pyglet.shapes.Rectangle):
def __init__(self, actor_id, traffic_manager, color, batch=None, group=None):
super().__init__(0, 0, 1, 1, batch=batch, group=group)
self.traffic_manager = traffic_manager
self._actor_id = actor_id
self._color = color
def update(self):
... |
def create_librispeech_txt(dataset_dir):
output_dir = dataset_dir
with pushd(output_dir):
for part in Parts:
dest_meta_filename_gz = ('%s.txt.gz' % part)
if os.path.exists(dest_meta_filename_gz):
print('File exists:', dest_meta_filename_gz)
continu... |
def initialize_from_weights_file(model, weights_file, broadcast=True):
initialize_gpu_0_from_weights_file(model, weights_file)
if broadcast:
broadcast_parameters(model) |
class EmptyRandomEnv6x6(EmptyEnv):
def __init__(self):
super().__init__(size=6, agent_start_pos=None) |
def _jit_build_partition_tree(xmin, xmax, ymin, ymax, zmin, zmax, total_ywidth, total_zwidth, M, clustering, q):
ind = (len(clustering) - 1)
while (len(q) > 0):
(_, xmin, xmax, ymin, ymax, zmin, zmax, parent_ind, is_left) = heapq.heappop(q)
if (parent_ind >= 0):
clustering[(parent_in... |
class RankSelection(SelectionFunction[T]):
def get_index(self, population: list[T]) -> int:
random_value = randomness.next_float()
bias = config.configuration.search_algorithm.rank_bias
return int((len(population) * (((bias - sqrt(((bias ** 2) - ((4.0 * (bias - 1.0)) * random_value)))) / 2.0... |
_ASSIGNERS.register_module()
class HungarianAssigner(BaseAssigner):
def __init__(self, cls_cost=dict(type='ClassificationCost', weight=1.0), reg_cost=dict(type='BBoxL1Cost', weight=1.0), iou_cost=dict(type='IoUCost', iou_mode='giou', weight=1.0)):
self.cls_cost = build_match_cost(cls_cost)
self.reg_... |
class Evaluator():
def __init__(self, cfg_=None, timer_=None):
self.timer = timer_
self.cfg = cfg_
self.ref_coordinate = cfg_.DATA_CONFIG.REF_COOR
self.batch_time = AverageMeter()
self.data_time = AverageMeter()
self.Success_main = Success()
self.Precision_mai... |
def corpus_dataflow_match(references, candidates, lang):
LANGUAGE = Language((root_dir + '/parser/languages.so'), lang)
parser = Parser()
parser.set_language(LANGUAGE)
parser = [parser, dfg_function[lang]]
match_count = 0
total_count = 0
scores = []
for i in range(len(candidates)):
... |
def register_Ns3Ipv4Header_methods(root_module, cls):
cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True)
cls.add_method('DscpTypeToString', 'std::string', [param('ns... |
.parametrize('observation_shape', [(100,), (4, 84, 84), ((100,), (200,))])
.parametrize('q_func_factory', [MeanQFunctionFactory(), QRQFunctionFactory()])
.parametrize('scalers', [None, 'min_max'])
def test_fqe(observation_shape: Shape, q_func_factory: QFunctionFactory, scalers: Optional[str]) -> None:
(observation_... |
def test_union_numpy_empty_1():
text = 'union[float64[parameters={"wonky": "boop"}], unknown]'
parsedtype = deduce_type(text)
assert isinstance(parsedtype, ak.types.UnionType)
assert (str(parsedtype) == text) |
class Compositional_dot_Transformer(nn.Module):
def __init__(self, dim, search_dim, value_dim, search, retrieval, nonlinear, gumbel, concat, separate, bias):
super(Compositional_dot_Transformer, self).__init__()
self.dim = dim
self.search_dim = search_dim
self.value_dim = value_dim
... |
def write_continents_top(continents):
top_continents_list = ''
for continent in continents.keys():
top_continents_list += 'Continent: {continent}, found - {count}\n'.format(continent=continent, count=continents[continent])
try:
with open('{dest}/{txt}/{result_file}'.format(dest=RESUL... |
def copy_flax_attn_params(hf_backbone, flax_attn_params):
for (k, v) in flax_attn_params.items():
if k.startswith('transformer'):
torch_key = k.replace('transformer.resblocks', 'text_model.encoder.layers')
else:
torch_key = k.replace('visual.transformer.resblocks', 'vision_mo... |
class VoxelResBackBone8x(nn.Module):
def __init__(self, model_cfg, input_channels, grid_size, **kwargs):
super().__init__()
self.model_cfg = model_cfg
norm_fn = partial(nn.BatchNorm1d, eps=0.001, momentum=0.01)
self.sparse_shape = (grid_size[::(- 1)] + [1, 0, 0])
self.conv_in... |
class MeanLastFractionalSuccess(BaseMetric):
def __init__(self):
super(MeanLastFractionalSuccess, self).__init__(name='last_fractional_success')
self.per_episode_scores = []
self.total_number_of_episodes = 0
return
def process_episode(self, episode_obj):
self.total_number... |
class distill():
def __init__(self, args, model, teacher):
self.args = args
self.student = model
self.teacher = teacher
self.student_layers = self.sampled_layer(args.arch, self.student)
self.teacher_layers = self.sampled_layer(args.teacher_arch, self.teacher)
def kwar... |
class PygGraphPropPredDataset(InMemoryDataset):
def __init__(self, name, root='dataset', transform=None, pre_transform=None, meta_dict=None):
self.name = name
if (meta_dict is None):
self.dir_name = '_'.join(name.split('-'))
if osp.exists(osp.join(root, (self.dir_name + '_pyg... |
.filterwarnings('ignore::pytest.PytestUnhandledThreadExceptionWarning')
def test_killing_endless_loop():
config.configuration.module_name = 'tests.fixtures.examples.loop'
module_name = config.configuration.module_name
tracer = ExecutionTracer()
tracer.current_thread_identifier = threading.current_thread... |
def build_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, drop_last=False, pin_memory=True, persistent_workers=True, **kwargs):
(rank, world_size) = get_dist_info()
if dist:
sampler = DistributedSampler(dataset, world_size, rank, shuffle=shuffle, see... |
class Simulator():
def __init__(self, level_filename: Optional[str]=None, level: Optional[List[str]]=None, interactive_jar_path: Optional[str]=None, astar_jar_path: Optional[str]=None):
if ((level_filename is None) and (level is None)):
raise ValueError('level_filename OR level_txt must be provi... |
class SerializedInteraction():
request: Request
response: Response
checks: list[SerializedCheck]
status: Status
recorded_at: str
def from_interaction(cls, interaction: Interaction) -> SerializedInteraction:
return cls(request=interaction.request, response=interaction.response, checks=[Se... |
class GraphConvolution(layers.Layer):
def __init__(self, input_dim: int, output_dim: int, num_features_nonzero: int, dropout: float=0.0, is_sparse_inputs: bool=False, activation: Callable[([tf.Tensor], tf.Tensor)]=tf.nn.relu, norm: bool=False, bias: bool=False, featureless: bool=False, **kwargs: Optional) -> None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.