code
stringlengths
101
5.91M
def hed(): img_input = Input(shape=(480, 480, 3), name='input') x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input) x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x) b1 = side_branch(x, 1) x = MaxPooling2D((2, 2), strides=(2, 2), ...
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(((4 * 4) * 50), 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): x = F.relu(self.conv1(x)) ...
class ModelEvaluator(Evaluator): def __init__(self, dataset: Dataset, batch_size: int, num_workers: int, mixed_precision: bool=True): self.dataset = dataset self.mixed_precision = mixed_precision self.loader = DataLoader(dataset, batch_size, shuffle=False, num_workers=num_workers, drop_last=...
def videodata_kwargs(cfg): return {'root': cfg.data.root, 'root_targets': cfg.data.root_targets, 'sources': cfg.data.sources, 'targets': cfg.data.targets, 'height': cfg.data.height, 'width': cfg.data.width, 'transforms': cfg.data.transforms, 'norm_mean': cfg.data.norm_mean, 'norm_std': cfg.data.norm_std, 'use_gpu':...
def make_vector_field(eval_func, x_bounds, y_bounds, *, resolution=10, info=None): if (info is None): info = {} x_values = np.linspace(*x_bounds, num=resolution) y_values = np.linspace(*y_bounds, num=resolution) values = np.zeros((resolution, resolution)) dx_values = np.zeros((resolution, re...
class Attention2d(torch.nn.Module): def __init__(self, in_channels: int, out_channels: int, num_kernels: int, kernel_size: Tuple[(int, int)], padding_size: Tuple[(int, int)]): super(Attention2d, self).__init__() self.conv_depth = torch.nn.Conv2d(in_channels=in_channels, out_channels=(in_channels * n...
class A000255(ExtremesOfPermanentsSequence): def __init__(self): SloaneSequence.__init__(self, offset=0) self._b = [] self._a0a1d = (1, 1, 1) self._precompute(2) def _repr_(self): return 'a(n) = n*a(n-1) + (n-1)*a(n-2), a(0) = 1, a(1) = 1.'
class BasicAggModel(nn.Module): def __init__(self, include_ff=True, include_res_ln=True, dropout=0.0, d_inner=2048, d_model=768, return_att_weights=False, n_head=8, d_k=96, n_rules=63, device='cpu', is_dense_bias=True): super(BasicAggModel, self).__init__() self.include_ff = include_ff self....
.skipif((not limits.can_set_time_limit()), reason='Cannot set time limits on this system') def test_hard_time_limit(): def preexec_fn(): limits.set_time_limit(10) driver = [sys.executable, 'fast-downward.py'] parameters = ['--translate', '--translate-time-limit', '10s', 'misc/tests/benchmarks/grippe...
class KR_type_Dn_twistedElement(KirillovReshetikhinGenericCrystalElement): def e0(self): n = (self.parent().cartan_type().rank() - 1) s = self.parent().s() [b, l] = self.lift().to_highest_weight(index_set=list(range(2, (n + 1)))) pm = self.parent().from_highest_weight_vector_to_pm_di...
.parametrize('dtype', [ti.i32, ti.f32, ti.i64, ti.f64]) .parametrize('shape', [(8,), (6, 12)]) .parametrize('offset', [0, (- 4), 4]) .parametrize('m, n', [(3, 4)]) _utils.test(arch=get_host_arch_list()) def test_matrix_to_numpy_with_offset(dtype, shape, offset, m, n): import numpy as np x = ti.Matrix.field(dtyp...
def feature_column_json_hook(obj): if isinstance(obj, dict): typ = obj.get('type') if (typ in SUPPORTED_CONCRETE_FEATURE_COLUMNS): return FeatureColumn.from_dict_or_feature_column(obj) return obj
class DecoderClassifier(nn.Module): def __init__(self, config, embedding_weights): super(DecoderClassifier, self).__init__() self.cls = BertOnlyMLMHead(config, embedding_weights) def forward(self, hidden_states): cls_scores = self.cls(hidden_states) return cls_scores
_utils.test(require=ti.extension.assertion, debug=True, gdb_trigger=False) def test_not_out_of_bound_with_offset(): x = ti.field(ti.i32, shape=(8, 16), offset=((- 4), (- 8))) def func(): x[((- 4), (- 8))] = 1 x[(3, 7)] = 2 func()
def read_frames_cv2_charades(video_path, num_frames, sample, start_sec=None, end_sec=None): cap = cv2.VideoCapture(video_path) assert cap.isOpened() vlen = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = cap.get(5) if ((not start_sec) and (not end_sec)): frame_idxs = sample_frames(num_frames, v...
class ETagResponseMixin(object): def cache_control(self): def on_update(cache_control): if ((not cache_control) and ('cache-control' in self.headers)): del self.headers['cache-control'] elif cache_control: self.headers['Cache-Control'] = cache_control....
def write_file(file): file.write(TXT) for words in test_words(): record = Record() for word in words: record.add(word) file.write(str(record)) file.write('\n')
class EntropyEstimator(BaseEstimator, ABC, metaclass=EntropyEstimatorType): def __init__(self): self.estimate_ = None self.err_ = None self.input_data_ndim = 1 def __call__(self, nk, k=None, zk=None): return self.fit(nk, k=k, zk=zk).estimate_ def algorithm(self): retu...
def test_vector_draw(verbose=False): np.random.seed(0) ppg = pypolyagamma.PyPolyaGamma(np.random.randint((2 ** 16))) n = 5 v2 = np.zeros(n) a = (14 * np.ones(n, dtype=np.float)) b = (0 * np.ones(n, dtype=np.float)) ppg.pgdrawv(a, b, v2) if verbose: print(v2) return True
class Parser(argparse.ArgumentParser, ABC): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) model_args = self.add_argument_group('model_args') self._add_model_args(model_args) data_args = self.add_argument_group('data_args') self._add_data_args(data_arg...
def add_to_ld_library_path(path): library_path = os.environ.get('LD_LIBRARY_PATH', '') library_paths = (library_path.split(':') if library_path else []) if (path not in library_paths): os.environ['LD_LIBRARY_PATH'] = ':'.join(([path] + library_paths))
def _class_counter(data_dict): counter = Counter() for (data_id, data) in data_dict.items(): counter.update([data['class_name']]) return counter
def inference(data): with tf.variable_scope('inference') as scope: W_1 = utils.weight_variable([((IMAGE_SIZE * IMAGE_SIZE) * 50)], name='W_1') b_1 = utils.bias_variable([50], name='b_1') h_1 = tf.nn.relu((tf.matmul(data, tf.reshape(W_1, [(IMAGE_SIZE * IMAGE_SIZE), 50])) + b_1), name='h_1') ...
class MSELoss(Loss): def __init__(self): super().__init__('MSELoss') def compute_loss(self, y_true, output_model): if (output_model is None): raise TypeError('Argument: output_model must be set.') if (y_true is None): raise TypeError('Argument: y_true must be set....
def make_numpy_ndarray_fromstring(s, dtype, shape): return numpy.fromstring(s, dtype=dtype).reshape(shape)
def plot_recall(measures, eval_dir, plot_file): plt.figure(figsize=(10, 8)) plt.xlabel('cut-off', fontsize=15) plt.ylabel('recall', fontsize=15) for (name, measure) in measures.items(): (xs, ys) = zip(*measure.values()) labels = measure.keys() plt.scatter(xs, ys, marker='o') ...
def check_cuda_kernel_launches(): torch_dir = os.path.dirname(os.path.realpath(__file__)) torch_dir = os.path.dirname(torch_dir) torch_dir = os.path.dirname(torch_dir) kernels_without_checks = 0 files_without_checks = [] for (root, dirnames, filenames) in os.walk(torch_dir): if ((root ==...
class Aggregator(object): def __init__(self, batch_size, dim, dropout, act, name): if (not name): layer = self.__class__.__name__.lower() name = ((layer + '_') + str(get_layer_id(layer))) self.name = name self.dropout = dropout self.act = act self.batc...
((not tf), 'no TF') def test_demo_tf_task12ax_eval(): cfg_filename = 'demos/demo-tf-native-lstm.12ax.config' train_dataset_repr = '{"class": "Task12AXDataset", "num_seqs": 10}' dev_dataset_repr = '{"class": "Task12AXDataset", "num_seqs": 10}' fer1 = run_config_get_fer(cfg_filename, '++num_epochs', '2', ...
def sample_queries(data_dir, db_name, out_dir): in_json = os.path.join(data_dir, '{}.json'.format(db_name)) sqls = load_sqls(in_json, normalize_variables=True) num_samples = 3 count = 0 for idx in np.random.randint(0, len(sqls), num_samples): out_txt = os.path.join(out_dir, '{}-{}.txt'.forma...
class SetupCallback(Callback): def __init__(self, resume, now, logdir, ckptdir, cfgdir, config, lightning_config): super().__init__() self.resume = resume self.now = now self.logdir = logdir self.ckptdir = ckptdir self.cfgdir = cfgdir self.config = config ...
class ManinSymbolList_group(ManinSymbolList): def __init__(self, level, weight, syms): self.__level = level self.__syms = syms L = [(i, u, v) for i in range(((weight - 2) + 1)) for (u, v) in syms.list()] ManinSymbolList.__init__(self, weight, L) def level(self): return se...
def register_Ns3CallbackImplBase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) cls.add_method('IsEqual', 'bool', [param('ns3::Pt...
.parametrize('env_name', ['cartpole-random', 'pendulum-random']) def test_get_dataset(env_name: str) -> None: (_, env) = get_dataset(env_name) if (env_name == 'cartpole-random'): assert (env.unwrapped.spec.id == 'CartPole-v1') elif (env_name == 'pendulum-random'): assert (env.unwrapped.spec....
def check_damping_factor(damping_factor: float): if ((damping_factor < 0) or (damping_factor >= 1)): raise ValueError('A damping factor must have a value in [0, 1[.')
class EmptyRecord(): def __init__(self, is_tuple, parameters): self.length_ = 0 self.is_tuple_ = is_tuple self.parameters_ = parameters self.set_id(Ref(0)) def append(self): self.length_ += 1 def extend(self, size): self.length_ += size def parameters(self...
def convert_to_list(python_input): if isinstance(python_input, torch.Tensor): return [python_input] else: return list(python_input)
def get_eps_scheduler(args, max_eps, train_data): eps_scheduler = eval(args.scheduler_name)(max_eps, args.scheduler_opts) epoch_length = int((((len(train_data.dataset) + train_data.batch_size) - 1) / train_data.batch_size)) eps_scheduler.set_epoch_length(epoch_length) return eps_scheduler
class MonodepthOptions(): def __init__(self): self.parser = argparse.ArgumentParser(description='Monodepthv2 options') self.parser.add_argument('--data_path', type=str, help='path to the training data', default=os.path.join(file_dir, 'kitti')) self.parser.add_argument('--log_dir', type=str, ...
def resolve_ssl_version(candidate): if (candidate is None): return PROTOCOL_SSLv23 if isinstance(candidate, str): res = getattr(ssl, candidate, None) if (res is None): res = getattr(ssl, ('PROTOCOL_' + candidate)) return res return candidate
def get_numeracy_adapter_spec(max_train_instances: int, max_eval_instances: int, dim: int, delimiter: str=', ', **kwargs) -> AdapterSpec: return AdapterSpec(**{**{'method': ADAPT_GENERATION, 'instructions': get_dataset_header(dim, delimiter=delimiter, output_prefix=', '), 'max_train_instances': max_train_instances,...
class FGP_Element(ModuleElement): def __init__(self, parent, x, check=DEBUG): if check: assert (x in parent.V()), (('The argument x=' + str(x)) + ' is not in the covering module!') ModuleElement.__init__(self, parent) self._x = x def lift(self): return self._x def...
def crop_column(crop_colname: str, df: pd.DataFrame, time_start_colname: str='start_secs', time_end_colname: str='end_secs', max_crop_duration: Optional[float]=None) -> pd.DataFrame: for (i, row) in tqdm(df.iterrows(), desc=f'crop {crop_colname}'): (start, end) = (row[time_start_colname], row[time_end_colna...
def test_num_4(): array = ak.Array(ak.contents.numpyarray.NumpyArray(np.array([[0.0, 1.1], [2.2, 3.3], [4.4, 5.5]]))) cuda_array = ak.to_backend(array, 'cuda') assert (ak.num(cuda_array, 0) == ak.num(array, 0)) assert (ak.num(cuda_array, 1).tolist() == ak.num(array, 1).tolist())
class SDDivGradTerm(Term): name = 'ev_sd_div_grad' arg_types = ('opt_material', 'parameter_u', 'parameter_w', 'parameter_mv') arg_shapes = [{'opt_material': '1, 1', 'parameter_u': 'D', 'parameter_w': 'D', 'parameter_mv': 'D'}, {'opt_material': None}] function = staticmethod(terms.d_sd_div_grad) def ...
def _seg_45(): return [(64540, 'M', u''), (64541, 'M', u''), (64542, 'M', u''), (64543, 'M', u''), (64544, 'M', u''), (64545, 'M', u''), (64546, 'M', u''), (64547, 'M', u''), (64548, 'M', u''), (64549, 'M', u''), (64550, 'M', u''), (64551, 'M', u''), (64552, 'M', u''), (64553, 'M', u''), (64554, 'M', u''), (64555, ...
class CommutativeRings(CategoryWithAxiom): class ParentMethods(): def _test_divides(self, **options): tester = self._tester(**options) a = self.an_element() try: a.divides except AttributeError: return z = self.zero(...
class Meteor(): def __init__(self): self.meteor_cmd = ['java', '-jar', '-Xmx2G', METEOR_JAR, '-', '-', '-stdio', '-l', 'en', '-norm'] self.meteor_p = subprocess.Popen(self.meteor_cmd, cwd=os.path.dirname(os.path.abspath(__file__)), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIP...
.parametrize('set_loss', [dict(set_loss_nan=False, set_loss_inf=False), dict(set_loss_nan=True, set_loss_inf=False), dict(set_loss_nan=False, set_loss_inf=True)]) def test_check_invalid_loss_hook(set_loss): class DemoModel(nn.Module): def __init__(self, set_loss_nan=False, set_loss_inf=False): s...
.parametrize('method', ('as_requests_kwargs', 'as_werkzeug_kwargs')) def test_serialize_yaml(open_api_3_schema_with_yaml_payload, method): schema = schemathesis.from_dict(open_api_3_schema_with_yaml_payload) (case=schema['/yaml']['POST'].as_strategy()) (max_examples=1) def test(case): kwargs = g...
def _apply_split(dataset: ImageFolder, split: List[str]): img_paths = [] for (path, label) in dataset.samples: root_with_slash = os.path.join(dataset.root, '') img_paths.append(path.replace(root_with_slash, '')) split_set = set(split) samples = [] for (path, sample) in zip(img_paths,...
def get_combination_wise_output_matrix(y, order): return np.array([set((tuple(combination) for combination in it.combinations_with_replacement(get_indicator_representation(row), order))) for row in y])
def compute_score_with_logits(logits, labels): if (labels.shape[0] == 0): scores = torch.zeros(*labels.size()).to(logits.device) return scores logits = torch.max(logits, 1)[1].data one_hots = torch.zeros(*labels.size()).to(logits.device) one_hots.scatter_(1, logits.view((- 1), 1), 1) ...
def run_cases(cases, run_lambda, set_key): job_arg = [(case, run_lambda, set_key, index, len(cases)) for (index, case) in enumerate(cases) if (not result_exists(set_key, case))] print(f"{(len(cases) - len(job_arg))}/{len(cases)} cases won't be calculated because their results already exist.") jobs = [] ...
class EisensteinExtensionRingCappedRelative(EisensteinExtensionGeneric, pAdicCappedRelativeRingGeneric): def __init__(self, exact_modulus, poly, prec, print_mode, shift_seed, names, implementation='NTL'): unram_prec = (((prec + poly.degree()) - 1) // poly.degree()) ntl_poly = ntl_ZZ_pX([a.lift() for...
class PreNormResidual(nn.Module): def __init__(self, dim, fn): super().__init__() self.fn = fn self.norm = nn.LayerNorm(dim) def forward(self, x): return (self.fn(self.norm(x)) + x)
class TrackedLayers(): def __init__(self, *layers_modules): self._layers_dict = {} self._layers_modules = list(layers_modules) self._namespaces = defaultdict(list) self._current_namespace = '/' def track_module(self, layers_module): self._layers_modules.append(layers_modu...
def calculate_inception_stats(image_path, num_expected=None, seed=0, max_batch_size=64, num_workers=3, prefetch_factor=2, device=torch.device('cuda')): if (dist.get_rank() != 0): torch.distributed.barrier() dist.print0('Loading Inception-v3 model...') detector_url = ' detector_kwargs = dict(retu...
def create_splits_logs(split: str, nusc: 'NuScenes') -> List[str]: scene_splits = create_splits_scenes(verbose=False) assert (split in scene_splits.keys()), 'Requested split {} which is not a known nuScenes split.'.format(split) version = nusc.version if (split in {'train', 'val', 'train_detect', 'train...
class CohereTokenCounter(TokenCounter): def count_tokens(self, request: Request, completions: List[Sequence]) -> int: return sum((len(sequence.tokens) for sequence in completions))
def test_validation_sha_without_split(tmp_path): tmp_no_split_output_dir = (tmp_path / 'pretraining_sha256_no_split') logging.info(f'temporary no split output directory is in {tmp_no_split_output_dir}') input_file = os.path.join(Path.cwd(), 'tests', 'examples', 'pretraining', 'example_pretraining_data.jsonl...
class ModelInfo(): def __init__(self, factory: nn.Module, args: dict, batch_size: int, dataset_args: dict, use_sgd: bool=False, img_size: int=IMG_SIZE): self.factory = factory self.args = args self.batch_size = batch_size self.dataset_args = dataset_args self.img_size = img_s...
def test_likelihood_executable_realign(msa_sampler): input_aln = ['AKDKG-LDINSAEKFFEALHSESIKHQINVMEK-', 'N--EGPLDKESVRTIYELLMSSSHDIQAEQRQRE', 'GQEQN-LDSNYISQVYHTIIEQSVLSQQEFNNRF', 'N--PGPLDDSAIISMFNLIMDGSRILEKKQTNQH', 'GKEKQ-LDPQYVSQIFHTIIEDSVLYQRS-----'] query_name = 'xyz' reference_sequence = f'''>{query_...
def get_decode_dir_name(ckpt_name): if ('train' in FLAGS.data_path): dataset = 'train' elif ('val' in FLAGS.data_path): dataset = 'val' elif ('test' in FLAGS.data_path): dataset = 'test' else: raise ValueError(('FLAGS.data_path %s should contain one of train, val or test'...
(numba_geometry_spec) class NumbaRadial1DGeometry(object): def __init__(self, r_inner, r_outer, v_inner, v_outer): self.r_inner = r_inner self.r_outer = r_outer self.v_inner = v_inner self.v_outer = v_outer
def get_third_party(): txt_files = list(Path('./requirements').rglob('*.txt')) package_list = [] for file in txt_files: with open(file, 'r') as fp: for line in fp: line = line.strip() if (line == ''): continue package_li...
.overload_method(UnionType, 'append_content') def Union_append_content(builder, tag): if (isinstance(builder, UnionType) and isinstance(tag, numba.types.Integer)): def append_content(builder, tag): content = builder._contents[numba.literally(tag)] builder._tags.append(tag) ...
class TriggerPool(): def __init__(self): self.triggers = [] self.results = [] def add(self, trigger): self.triggers.append(trigger) def test(self, model, data): untested_triggers = range(len(self.results), len(self.triggers)) for i in untested_triggers: se...
def transform_proposals_seg(dataset_dict, image_shape, transforms, *, proposal_topk, min_box_size=0): boxes = dataset_dict['proposals'].proposal_boxes.tensor.cpu().numpy() boxes = transforms.apply_box(boxes) boxes = Boxes(boxes) objectness_logits = dataset_dict['proposals'].objectness_logits oh_labe...
class Fpr(Critic): def __init__(self, recall_level=0.95): super().__init__() self.recall_level = recall_level def get_name(self): return (('FPR(' + str((self.recall_level * 100))) + ')') def stable_cumsum(self, arr, rtol=1e-05, atol=1e-08): out = np.cumsum(arr, dtype=np.float...
class cuFFTPlanCache(object): def __init__(self, device_index): self.device_index = device_index size = cuFFTPlanCacheAttrContextProp(torch._cufft_get_plan_cache_size, '.size is a read-only property showing the number of plans currently in the cache. To change the cache capacity, set cufft_plan_cache.ma...
def convert_fsmt_checkpoint_to_pytorch(fsmt_checkpoint_path, pytorch_dump_folder_path): assert os.path.exists(fsmt_checkpoint_path) os.makedirs(pytorch_dump_folder_path, exist_ok=True) print(f'Writing results to {pytorch_dump_folder_path}') checkpoint_file = basename(fsmt_checkpoint_path) fsmt_folde...
class MMFDatasetBuilder(BaseDatasetBuilder): ZOO_CONFIG_PATH = None ZOO_VARIATION = None def __init__(self, dataset_name, dataset_class=None, zoo_variation='defaults', *args, **kwargs): super().__init__(dataset_name) self.dataset_class = dataset_class self.zoo_type = 'datasets' ...
class MPNetTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES slow_tokenizer_class = MPNetTo...
def main(): args = get_args() for class_no in os.listdir(args.feature_dir): print('Class index ', class_no) compute_mean_vector(class_no, args.save_path, args.feature_dir)
class AlignTextConfig(PretrainedConfig): model_type = 'align_text_model' def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_voc...
def strip_artist(s): s = s.lower() s = s.replace('the ', '') keys = [' - ', '/', ' ft', 'feat', 'featuring', ' and ', ' with ', '_', ' vs', '&', ';', '+'] for key in keys: loc = s.find(key) if (loc != (- 1)): s = s[:loc] return s
class HessianProblem(): def __init__(self, db: database.Database, form_handler: _forms.ControlFormHandler, adjoint_form_handler: _forms.AdjointFormHandler, gradient_problem: control_gradient_problem.ControlGradientProblem, box_constraints: boxc.BoxConstraints) -> None: self.db = db self.form_handler...
def count_letter_ngram(sentence, n=3): if (len(sentence) < n): return set(sentence) local_counts = set() for k in range(((len(sentence.strip()) - n) + 1)): local_counts.add(sentence[k:(k + n)]) return local_counts
class network_29layers_Custom(network_29layers): def forward(self, x, nrm=True): x = self.conv1(x) x = self.pool1(x) x = self.block1(x) x = self.group1(x) x = self.pool2(x) x = self.block2(x) x = self.group2(x) x = self.pool3(x) x = self.block3...
def length(node, indices): return expr.Expr(impl.get_runtime().compiling_callable.ast_builder().expr_snode_length(node._snode.ptr, expr.make_expr_group(indices)), dbg_info=_ti_core.DebugInfo(impl.get_runtime().get_current_src_info()))
def GenerateSM90_TensorOp_1684_complex_gaussian(manifest, cuda_version): if (not CudaToolkitVersionSatisfies(cuda_version, 11, 8)): return layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.ColumnMajor), (LayoutTy...
class AssistQVideoPath(Dataset): def __init__(self, root, split, save_dir, num_gpus): super().__init__() (videos, save_dirs) = get_assistq_videos(root, split, save_dir) (self.videos, self.save_dirs) = ([], []) for (video, save_dir) in zip(videos, save_dirs): self.videos.a...
def save(papers, authors, edges): biadjacency = sparse.coo_matrix((np.ones(len(edges), dtype=np.bool), (edges['paper_node_id'], edges['author_node_id']))) papers.drop('paper_node_id', axis=1, inplace=True) authors.drop('author_node_id', axis=1, inplace=True) edges.drop('paper_node_id', axis=1, inplace=T...
class FullTokenizer(object): def __init__(self, vocab_file, do_lower_case=True): self.vocab = load_vocab(vocab_file) self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) def tokenize(self, text): split_...
class Parse_Vuln(): json_data = dict() filename = 'vulnerabilities.json' tools_info_obj = tools_info.Tools_Info() def ParseArgs(self): Args = argparse.ArgumentParser(description='Parser to parse vulnerability result file into JSON') Args.add_argument('--src', required=True, help='result ...
class JointPPO(): def __init__(self, actor_critic, clip_param, ppo_epoch, num_mini_batch, value_loss_coef, entropy_coef, lr=None, eps=None, max_grad_norm=None, use_clipped_value_loss=False): self.actor_critic = actor_critic self.clip_param = clip_param self.ppo_epoch = ppo_epoch self...
def markinnerspaces(line): l = '' f = 0 cc = "'" cb = '' for c in line: if ((cb == '\\') and (c in ['\\', "'", '"'])): l = (l + c) cb = c continue if ((f == 0) and (c in ["'", '"'])): cc = c if (c == cc): f = (f + 1)...
class MixSpec(ComplexitySpec): environment = {'asr_acc': 0.7, 'asr_std': 0.15} proposition = {'yn_question': 0.4, 'reject_style': {'reject': 0.5, 'reject+inform': 0.5}, 'multi_slots': {1: 0.7, 2: 0.3}, 'dont_care': 0.1, 'multi_goals': {1: 0.6, 2: 0.4}} interaction = {'hesitation': 0.4, 'self_restart': 0.1, ...
class IBMVPCInstance(): def __init__(self, name, ibm_vpc_config, ibm_vpc_client=None, public=False): self.name = name.lower() self.config = ibm_vpc_config self.delete_on_dismantle = self.config['delete_on_dismantle'] self.profile_name = self.config['worker_profile_name'] self...
class PinyinTestCase(unittest.TestCase): def test_single_pinyin(self): sents = ['zhuan', 'zuo'] res = [] for name in sents: (s, r) = m.correct(name) print(s, r) res.append(r) self.assertEqual(res[0], []) self.assertEqual(res[1], []) def...
class IntFormat(object): def from_number(cls, n, min=None): width = (number_digits(n) + 1) if (n < 0): width += 1 repeat = (80 // width) return cls(width, min, repeat=repeat) def __init__(self, width, min=None, repeat=None): self.width = width self.rep...
class Vocab(object): __slots__ = ('_word_dict', '_entity_dict') def __init__(self, word_dict, entity_dict): self._word_dict = word_dict self._entity_dict = entity_dict def word_size(self): return len(self._word_dict) def entity_size(self): return len(self._entity_dict) ...
def click_play_button_off(): pyautogui.doubleClick('screenshots/play_button_off.PNG') pyautogui.moveTo(1000, 1000, duration=0)
def compute_metrics_for_regression(y_test, y_test_pred): metrics = {} for task in DIMENSIONS: targets_task = [t[DIMENSIONS.index(task)] for t in y_test] pred_task = [l[DIMENSIONS.index(task)] for l in y_test_pred] rmse = mean_squared_error(targets_task, pred_task, squared=False) ...
class DatasetSampler(Dataset): def __init__(self, x): self.x = x def __len__(self): return len(self.x) def __getitem__(self, idx): return self.x[idx].astype('float32')
def check_build_sdist(hooks, build_sys_requires): with BuildEnvironment() as env: try: env.pip_install(build_sys_requires) log.info('Installed static build dependencies') except CalledProcessError: log.error('Failed to install static build dependencies') ...
.parametrize('task_name', [tn for tn in (all_tasks - julia_tasks)]) def test_obtain_prior_from_task(task_name): task = get_task(task_name) prior = task.get_prior() assert (prior is not None)
def standard_confusion_matrix(y_test, y_test_pred): [[tn, fp], [fn, tp]] = confusion_matrix(y_test, y_test_pred) return np.array([[tp, fp], [fn, tn]])
class ASPP_Efficientnetv2(nn.Module): def __init__(self, num_classes, concat=True, output_kernel_size=1): super(ASPP_Efficientnetv2, self).__init__() self.concat = concat self.conv_1x1_1 = nn.Conv2d(512, 256, kernel_size=1) self.bn_conv_1x1_1 = nn.BatchNorm2d(256) self.conv_3...