code
stringlengths
101
5.91M
def get_defense_summary(defense, trace_ids, traces): summary = pd.DataFrame(columns=summary_columns) for (trace_id, trace) in tqdm.tqdm_notebook(list(zip(trace_ids, traces))): x = extract(trace) orig_trace = traces_by_trace_id[trace_id] orig_x = featurevecs_by_trace_id[trace_id] ...
def zip_item_is_executable(info): mode = (info.external_attr >> 16) return bool((mode and stat.S_ISREG(mode) and (mode & 73)))
def summarize(writer, global_step, scalars={}, histograms={}, images={}, audios={}, audio_sampling_rate=22050): for (k, v) in scalars.items(): writer.add_scalar(k, v, global_step) for (k, v) in histograms.items(): writer.add_histogram(k, v, global_step) for (k, v) in images.items(): ...
def convert_rembert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_path): config = RemBertConfig.from_json_file(bert_config_file) print('Building PyTorch model from configuration: {}'.format(str(config))) model = RemBertModel(config) load_tf_weights_in_rembert(model, config,...
class Seq(RE): def __init__(self, *re_list): nullable = 1 for (i, re) in enumerate(re_list): self.check_re(i, re) nullable = (nullable and re.nullable) self.re_list = re_list self.nullable = nullable i = len(re_list) match_nl = 0 while ...
class FastBatchNorm1d(nn.Module): def __init__(self, num_features, **kwargs): super().__init__() self.bn = nn.BatchNorm1d(num_features, **kwargs) def _forward_dense(self, x): return self.bn(x.transpose(1, 2)).transpose(2, 1) def _forward_sparse(self, x): return self.bn(x) ...
def _format(val: Any, output_format: str='standard', errors: str='coarse') -> Any: val = str(val) result: Any = [] if (val in NULL_VALUES): return [np.nan] if (not validate_no_mva(val)): if (errors == 'raise'): raise ValueError(f'Unable to parse value {val}') error_re...
class StandardTableaux_residue_shape(StandardTableaux_residue): def __init__(self, residue, shape): if (residue.size() != shape.size()): raise ValueError('the size of the shape and the length of the residue defence must coincide') StandardTableauTuples.__init__(self, category=FiniteEnume...
.parametrize('sparse_feature_num,dense_feature_num', [(2, 0)]) def test_CCPM_without_seq(sparse_feature_num, dense_feature_num): model_name = 'CCPM' sample_size = SAMPLE_SIZE (x, y, feature_columns) = get_test_data(sample_size, sparse_feature_num=sparse_feature_num, dense_feature_num=dense_feature_num, sequ...
def skip_backend(backend): backend = _backend_from_arg(backend) return ua.skip_backend(backend)
def train(epoch, model, dataloader, optimizer, training): (utils.fix_randseed(None) if training else utils.fix_randseed(0)) (model.module.train_mode() if training else model.module.eval()) average_meter = AverageMeter(dataloader.dataset) for (idx, batch) in enumerate(dataloader): batch = utils.t...
class AttributeExpandSuggestion(object): def __init__(self, att_idx, att_val, operator, resulting_class_distributions, merit): self.resulting_class_distributions = resulting_class_distributions self.merit = merit self.att_idx = att_idx self.att_val = att_val self.operator = o...
class StraightLinePolicy(): def __init__(self, env): self.action_space = env.action_space self.env = env def reset(self): pass def get_action(self, obs): current = self.env.state.q goal = self.env.goal_state.q action = (goal - current)[:self.action_space.low.s...
def from_args(func, ns, *args, **kwargs): return func(*args, **strip_unexpected_kwargs(func, vars(ns)), **kwargs)
def mediainfo_json(filepath, read_ahead_limit=(- 1)): prober = get_prober_name() command_args = ['-v', 'info', '-show_format', '-show_streams'] try: command_args += [fsdecode(filepath)] stdin_parameter = None stdin_data = None except TypeError: if (prober == 'ffprobe'): ...
class PegasusTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES 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 ...
def dataset_10x(dataset_name: (str | None)=None, filename: (str | None)=None, save_path: str='data/10X', url: str=None, return_filtered: bool=True, remove_extracted_data: bool=False, **scanpy_read_10x_kwargs) -> anndata.AnnData: return _load_dataset_10x(dataset_name=dataset_name, filename=filename, save_path=save_p...
class DocSettings(): dim: int = DefaultVal(128) doc_maxlen: int = DefaultVal(220) mask_punctuation: bool = DefaultVal(True)
def rbf_kernel(X: torch.Tensor, Y: torch.Tensor, h_dim: int): batch_size = X.size(0) norms_x = X.pow(2).sum(1, keepdim=True) prods_x = torch.mm(X, X.t()) dists_x = ((norms_x + norms_x.t()) - (2 * prods_x)) norms_y = Y.pow(2).sum(1, keepdim=True) prods_y = torch.mm(Y, Y.t()) dists_y = ((norms...
class Perceptron(BaseSGDClassifier): _parameter_constraints: dict = {**BaseSGDClassifier._parameter_constraints} _parameter_constraints.pop('loss') _parameter_constraints.pop('average') _parameter_constraints.update({'penalty': [StrOptions({'l2', 'l1', 'elasticnet'}), None], 'alpha': [Interval(Real, 0, ...
def build(net, netName='net.net.xml'): connections = [] nodesFile = tempfile.NamedTemporaryFile(mode='w', delete=False) print('<nodes>', file=nodesFile) for nid in net._nodes: n = net._nodes[nid] print((' <node id="%s" x="%s" y="%s" type="%s"/>' % (n.nid, n._x, n._y, n.nodeType)), fil...
class ActivationTraceHessianCalculatorKeras(TraceHessianCalculatorKeras): def __init__(self, graph: Graph, input_images: List[tf.Tensor], fw_impl, trace_hessian_request: TraceHessianRequest, num_iterations_for_approximation: int=HESSIAN_NUM_ITERATIONS): super(ActivationTraceHessianCalculatorKeras, self).__i...
def test_isotonic_regression_pickle(): y = np.array([3, 7, 5, 9, 8, 7, 10]) x = np.arange(len(y)) ir = IsotonicRegression(increasing='auto', out_of_bounds='clip') ir.fit(x, y) ir_ser = pickle.dumps(ir, pickle.HIGHEST_PROTOCOL) ir2 = pickle.loads(ir_ser) np.testing.assert_array_equal(ir.predi...
def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper']) register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice']) regis...
def model_config(input_file_pattern=None, input_queue_capacity=640000, num_input_reader_threads=1, shuffle_input_data=True, uniform_init_scale=0.1, vocab_size=20000, batch_size=128, word_embedding_dim=620, bidirectional_encoder=False, encoder_dim=2400): config = _HParams() config.input_file_pattern = input_file...
class _DeprecatedBool(object): def __init__(self, name, version, value): self.message = "'{}' is deprecated and will be removed in version {}.".format(name, version) self.value = value def _warn(self): import warnings warnings.warn(self.message, DeprecationWarning, stacklevel=2) ...
def randint_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, low=0, high=1, shape=[], seed=(- 1)): return ([None] * (len(grad_inputs) + len(inputs)))
def helio_jd(date, ra, dec, b1950=False, time_diff=False): if (not b1950): (ra1, dec1) = bprecess(ra, dec) else: ra1 = ra dec1 = dec delta_t = ((array(date).astype(float) - 33282.) / 36525.0) epsilon_sec = poly1d([44.836, (- 46.8495), (- 0.00429), 0.00181][::(- 1)])(delta_t) ...
def _main(config, num_trials): load_metadata(config) if config.train: comb_train_ds = read_data(config, 'train', config.task) comb_dev_ds = read_data(config, 'dev', config.task) comb_test_ds = read_data(config, 'test', config.task) if config.draft: config.train_num_batches = 1 ...
def train_model(model, train_dl, val_dl, epochs: int=10, lr: float=0.0003, name: str='no_name', mcat_ratio: float=0.1, ema: float=0.99, pbar_width: int=None, use_wandb: bool=True, overwrite_model: bool=True): from sklearn.metrics import f1_score import warnings from pathlib import Path print(f'Training ...
class MLP_2HL(nn.Module): def __init__(self, dim_in, dim_hidden1, dim_hidden2, sparse=False, bn=True): super(MLP_2HL, self).__init__() self.in_layer = (SpLinear(dim_in, dim_hidden1) if sparse else nn.Linear(dim_in, dim_hidden1)) self.dropout_layer = nn.Dropout(0.0) self.lrelu = nn.Le...
.parametrize('task_name', [tn for tn in get_available_tasks() if (not re.search('lotka|sir', tn))]) def test_benchmark_metrics_selfobserved(task_name): task = get_task(task_name) nobs = 1 theta_o = task.get_prior()(num_samples=nobs) sim = task.get_simulator() x_o = sim(theta_o) (outputs, nsim, l...
class AsyncRenderer(): def __init__(self): self._closed = False self._is_async = False self._cur_args = None self._cur_result = None self._cur_stamp = 0 self._renderer_obj = None self._args_queue = None self._result_queue = None self._process =...
def test_byte(): t = NumpyType('uint8', {'__array__': 'byte'}) assert (str(parser.parse(str(t))) == str(t))
def train_G_D1(fake, D1, optimizer, **kwargs): y = D1(fake) err = loss._loss(y=y, target=True) err.backward() optimizer.step() return (0.0, y.detach().mean().item(), 0.0, 0.0, err.item(), 0.0)
class Subwords_w(Parent): def __init__(self, w, element_constructor): Parent.__init__(self, category=FiniteEnumeratedSets()) self._w = w self._build = element_constructor def __eq__(self, other) -> bool: return ((self.__class__ == other.__class__) and (self._w == other._w) and (s...
def main(argv): arg_parser = argparse.ArgumentParser(description='Dump search scores and other info to HDF file.') arg_parser.add_argument('config', help='filename to config-file') arg_parser.add_argument('--dataset', default='config:train') arg_parser.add_argument('--epoch', type=int, default=(- 1), he...
class CamEncode(nn.Module): def __init__(self, C): super(CamEncode, self).__init__() self.C = C self.trunk = EfficientNet.from_pretrained('efficientnet-b0') self.up1 = Up((320 + 112), self.C) def get_eff_depth(self, x): endpoints = dict() x = self.trunk._swish(sel...
def scrape_index_pages(seed_page): scraped_links = [] try: soup = BeautifulSoup(urllib.request.urlopen(seed_page), 'html.parser') except Exception as e: print('Skipping: ', seed_page) errors_file.write((((seed_page + '\t') + str(e)) + '\n')) return [] items = soup.findAll...
class AffordanceCVAE(nn.Module): def __init__(self, in_dim, hidden_dim, latent_dim, condition_dim, coord_dim=None, pred_len=4, condition_traj=True, z_scale=2.0): super().__init__() self.latent_dim = latent_dim self.condition_traj = condition_traj self.z_scale = z_scale if sel...
class LogisticMatrixFactorization(RecMixin, BaseRecommenderModel): _charger def __init__(self, data, config, params, *args, **kwargs): self._params_list = [('_learning_rate', 'lr', 'lr', 0.001, None, None), ('_factors', 'factors', 'factors', 10, None, None), ('_l_w', 'reg', 'reg', 0.1, None, None), ('_a...
def array2csv(array, filename, **kwargs): df = pd.DataFrame(array) return df.to_csv(filename, index=False, **kwargs)
class DecreasingHeckeFactorization(Element, metaclass=InheritComparisonClasscallMetaclass): def __classcall_private__(self, t, max_value=None, parent=None): _check_decreasing_hecke_factorization(t) if isinstance(t, DecreasingHeckeFactorization): u = t.value if (parent is None...
def list_files(files, recursive=False, extensions=None, exclude=None): if (extensions is None): extensions = [] if (exclude is None): exclude = [] out = [] for file in files: if (recursive and os.path.isdir(file)): for (dirpath, dnames, fnames) in os.walk(file): ...
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True): if (target.dim() == (lprobs.dim() - 1)): target = target.unsqueeze((- 1)) nll_loss = (- lprobs.gather(dim=(- 1), index=target)) smooth_loss = (- lprobs.sum(dim=(- 1), keepdim=True)) if (ignore_index is not None...
def merge_datasets(datasets): if isinstance(datasets, dict): keys = sorted(list(datasets.keys())) datasets = [datasets[key] for key in keys] res = datasets[0] if torch.is_tensor(datasets[0].data): res.data = torch.cat([dataset.data for dataset in datasets], dim=0) else: r...
def calculate_diff_w_significance(A_scores, B_scores, alpha=1e-05): A_scores = np.array(A_scores) B_scores = np.array(B_scores) mu = (np.mean(A_scores) - np.mean(B_scores)) p_value = stats.ttest_ind(A_scores, B_scores, alternative='greater')[1] mu_variance = ((np.var(A_scores) / len(A_scores)) + (np...
class CPM(object): def __init__(self, crop_size=256, out_chan=21, withPAF=False, PAFdim=2, numPAF=19, numStage=5, input_chan=3, withDirVec=False, withConf=False, withSeg=False): self.name = 'CPM' self.out_chan = out_chan self.crop_size = crop_size self.withPAF = withPAF self....
class TestGF2Ops(unittest.TestCase): def field_size_test(self, field_size): gf = GF2Ops(field_size) for i in range(100): x = random.randrange((1 << field_size)) y = random.randrange((1 << field_size)) x2 = gf.mul2(x) xy = gf.mul(x, y) self....
def inference(args, model, test_save_path=None): db_test = args.Dataset(base_dir=args.volume_path, split='test', list_dir=args.list_dir) testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=1) logging.info('{} test iterations per epoch'.format(len(testloader))) model.eval() metr...
def _cvt_variable(v): if isinstance(v, variable.Variable): v = v.data if hasattr(v, 'get'): v = v.get() return v
def register_Ns3SchedulerEvent_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_constructor([]) cls.add_constructor([param('ns3::Scheduler::Event const &', 'arg0')]) cls.add_instance_attribute('impl', 'ns3::EventImpl *', is_const=False) cls.add_instance_attribute('key', 'ns...
def _merge_entity_utterances(raw_utterances, stemmed_utterances): for (raw_stemmed_value, resolved_value) in sorted(iteritems(stemmed_utterances), key=operator.itemgetter(1)): if (raw_stemmed_value not in raw_utterances): raw_utterances[raw_stemmed_value] = resolved_value return raw_utteranc...
def get_optimizer(name, model, **kwargs): name = name.lower().strip() parameters = get_trainable_params(model) if (name == 'adam'): lr = (kwargs['lr'] if ('lr' in kwargs) else 0.001) wd = (kwargs['weight_decay'] if ('weight_decay' in kwargs) else 0) print('Using Adam optimizer: Lr=',...
class SerializationInterop(FileSetup): path = 'ivalue.pt' def setup(self): ones = torch.ones(2, 2) twos = (torch.ones(3, 5) * 2) value = (ones, twos) torch.save(value, self.path, _use_new_zipfile_serialization=True)
def SamplePairing(imgs): def f(img1, v): i = np.random.choice(len(imgs)) img2 = PIL.Image.fromarray(imgs[i]) return PIL.Image.blend(img1, img2, v) return f
def yuv2rgb(Y, U, V, height, width): U = imresize(U, [height, width], 'bilinear', mode='F') V = imresize(V, [height, width], 'bilinear', mode='F') Y = Y rf = (Y + (1.4075 * (V - 128.0))) gf = ((Y - (0.3455 * (U - 128.0))) - (0.7169 * (V - 128.0))) bf = (Y + (1.779 * (U - 128.0))) for m in ra...
_module() class DilatedEncoder(nn.Module): def __init__(self, in_channels, out_channels, block_mid_channels, num_residual_blocks, block_dilations): super(DilatedEncoder, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.block_mid_channels = block_m...
class Test_init_nd_shape_and_axes(object): def test_py_0d_defaults(self): x = np.array(4) shape = None axes = None shape_expected = np.array([]) axes_expected = np.array([]) (shape_res, axes_res) = _init_nd_shape_and_axes(x, shape, axes) assert_equal(shape_res...
def LF_travel(s): rgx = '\\b(travel(s|ed|ing)*|vacation|trip)\\b' trigger = match_regex(rgx, s) if (not trigger): return ABSTAIN return (TRAVEL if (not is_negated(trigger)) else NO_TRAVEL)
def _pairwise_emd_cd_(sample_pcs, ref_pcs, batch_size): print('computing Earth Mover and Chamfer distances') n_sample = sample_pcs.shape[0] n_ref = ref_pcs.shape[0] all_cd = [] all_emd = [] iterator = range(n_sample) for sample_b_start in tqdm.tqdm(iterator): sample_batch = sample_pc...
def get(tag_like: (str | Tag)) -> Model: model = bentoml.models.get(tag_like) if (model.info.module not in (MODULE_NAME, __name__)): raise NotFound(f'Model {model.tag} was saved with module {model.info.module}, not loading with {MODULE_NAME}.') return model
class BasicBlock(nn.Module): def __init__(self, inplanes, planes, stride=1, dilation=1, kernel=3, norm='bn', use_se=False, activation=nn.ReLU): super(BasicBlock, self).__init__() padding = (((dilation * kernel) - dilation) // 2) (self.inplanes, self.planes) = (int(inplanes), int(planes)) ...
class TestOpenAIWindowService(): def setup_method(self): self.path: str = tempfile.mkdtemp() service: TokenizerService = get_tokenizer_service(self.path) self.window_service = WindowServiceFactory.get_window_service('openai/gpt-3.5-turbo-0301', service) def teardown_method(self, method):...
class Encoder(nn.Module): def __init__(self, z_dim, c_dim, img_size): super(Encoder, self).__init__() self.model_enc = nn.Sequential(nn.Conv2d(int(c_dim), 64, 4, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 64, 4, stride=2, padding=1), nn.ReLU(), nn.ZeroPad2d((1, 2, 1, 2)), nn.Conv2d(64, 64, 4, st...
def make_buff(comm_handler: BufferSimpleCommBase, is_bwd, shapes, dtypes=None, max_buffers=1, create=False, prev_stream_to_use=None): comm_handler.set_tensor_shapes(shapes) comm_handler.set_tensor_dtypes(dtypes) if is_bwd: b = Buffers(max_buffers, comm_handler.create_gradients_rcv_buffers, comm_hand...
def box_voting(top_boxes, top_scores, all_boxes, all_scores, overlap_thresh, method='ID', beta=1.0): assert (method in BOX_VOTING_METHODS), 'Unknown box_voting method: {}'.format(method) return _C.box_voting(top_boxes, top_scores, all_boxes, all_scores, BOX_VOTING_METHODS[method], beta, overlap_thresh)
class JsonConfig(dict): Indent = 2 def __init__(self, *argv, **kwargs): super().__init__() super().__setitem__('__name', 'default') assert ((len(argv) == 0) or (len(kwargs) == 0)), '[JsonConfig]: Cannot initialize with position parameters (json file or a dict) and named parameters (key a...
def test_standard_represent(): img_path = 'dataset/img1.jpg' embedding_objs = DeepFace.represent(img_path) for embedding_obj in embedding_objs: embedding = embedding_obj['embedding'] logger.debug(f'Function returned {len(embedding)} dimensional vector') assert (len(embedding) == 2622...
_module() class ABIFuser(BaseModule): def __init__(self, d_model=512, max_seq_len=40, num_chars=90, init_cfg=None, **kwargs): super().__init__(init_cfg=init_cfg) self.max_seq_len = (max_seq_len + 1) self.w_att = nn.Linear((2 * d_model), d_model) self.cls = nn.Linear(d_model, num_char...
def read_all_throughputs_json(throughputs_file): with open(throughputs_file, 'r') as f: throughputs = json.load(f) return throughputs
def traindata_to_tfrecord(): filename = '../deepsea_filtered.npz' with np.load(filename) as file: x = file['x_train'] y = file['y_train'] for file_num in range(1): with tf.io.TFRecordWriter(('./data/traindata-%.2d.tfrecord' % file_num)) as writer: for i in tqdm(range((fil...
def test_round_trip_placeholder(): layout = ak.contents.RecordArray([ak.contents.NumpyArray(PlaceholderArray(nplike, (4,), np.dtype(np.float64))), ak.contents.NumpyArray([1, 2, 3, 4])], ['x', 'y']) (form, length, container) = ak.to_buffers(layout) result = ak.from_buffers(form, length, container, highlevel=...
def make_scorecard(scores): scorecard = [] display_names = [(None, 'Overall'), (Gender.MASCULINE, 'Masculine'), (Gender.FEMININE, 'Feminine')] bias_terms = {} for (gender, display_name) in display_names: gender_scores = scores.get(gender, Scores()) recall = gender_scores.recall() ...
def compute_metrics(seg_pred, seg_gt, n_cls, ignore_index=None, ret_cat_iou=False, tmp_dir=None, distributed=False): ret_metrics_mean = torch.zeros(3, dtype=float, device=ptu.device) if (ptu.dist_rank == 0): list_seg_pred = [] list_seg_gt = [] keys = sorted(seg_pred.keys()) for k...
def insert_indent(s: str, indent: str='\t', insert_first=True) -> str: prefix = (indent if insert_first else '') return ((prefix + s.rstrip('\n ').replace('\n', ('\n' + indent))) + '\n')
class GlobalNode(StatNode): child_attrs = [] def analyse_declarations(self, env): for name in self.names: env.declare_global(name, self.pos) def analyse_expressions(self, env): return self def generate_execution_code(self, code): pass
def sliced_fun(f, n_slices): def sliced_f(sliced_inputs, non_sliced_inputs=None): if (non_sliced_inputs is None): non_sliced_inputs = [] if isinstance(non_sliced_inputs, tuple): non_sliced_inputs = list(non_sliced_inputs) n_paths = len(sliced_inputs[0]) slice_...
class InputFeatures(object): def __init__(self, input_ids, input_mask, col_label_ids, lm_label_ids): self.input_ids = input_ids self.input_mask = input_mask self.col_label_ids = col_label_ids self.lm_label_ids = lm_label_ids
def load_refcoco_json(json_file, image_root, dataset_name=None, extra_annotation_keys=None): from pycocotools.coco import COCO timer = Timer() json_file = PathManager.get_local_path(json_file) with contextlib.redirect_stdout(io.StringIO()): coco_api = COCO(json_file) if (timer.seconds() > 1)...
class ReconNetWrapper(nn.Module): fc_dim = 257 def __init__(self, net_recon, use_last_fc=False, init_path=None): super(ReconNetWrapper, self).__init__() self.use_last_fc = use_last_fc if (net_recon not in func_dict): return NotImplementedError('network [%s] is not implemented...
_level_function() def argmax(array, axis=None, *, keepdims=False, mask_identity=True, highlevel=True, behavior=None, attrs=None): (yield (array,)) return _impl(array, axis, keepdims, mask_identity, highlevel, behavior, attrs)
def set_framework_dependencies(x): if (type(x) is numpy.ndarray): to_dtype = (lambda a: a) fw = numpy else: to_dtype = (lambda a: a.to(x.dtype)) fw = torch eps = fw.finfo(fw.float32).eps return (fw, to_dtype, eps)
class storage(): instance = None client = None def __init__(self): if ('MINIO_ADDRESS' in os.environ): address = os.environ['MINIO_ADDRESS'] access_key = os.environ['MINIO_ACCESS_KEY'] secret_key = os.environ['MINIO_SECRET_KEY'] self.client = minio.Min...
def hashing_trick(text, n, hash_function=None, filters='!"#$%&()*+,-./:;<=>?[\\]^_`{|}~\t\n', lower=True, split=' '): if (hash_function is None): hash_function = hash elif (hash_function == 'md5'): hash_function = (lambda w: int(md5(w.encode()).hexdigest(), 16)) seq = text_to_word_sequence(t...
def read_element_wav(elem: Dict[(str, Any)], audio_dir, dataset_info: DatasetInfo, target_sr=44100, duration: Optional[float]=None) -> Dict[(str, Any)]: track_id = elem[dataset_info.id_col] filepath = dataset_info.id_to_filename(track_id, audio_dir) (samples, sr) = read_wav(filepath=filepath, target_sr=targ...
class CenterPivotConv4d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True): super(CenterPivotConv4d, self).__init__() self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size[:2], stride=stride[:2], bias=bias, padding=padding[:2]) self.con...
class DependencyGraph(object): def __init__(self): self.adjacency_list = {} self.reverse_list = {} self.missing = {} def add_distribution(self, distribution): self.adjacency_list[distribution] = [] self.reverse_list[distribution] = [] def add_edge(self, x, y, label=No...
def _cfg(url='', **kwargs): return {'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.875, 'interpolation': 'bilinear', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'layer0.conv1', 'classifier': 'last_linear', **kwargs}
def initialize_cuda_kernels(cupy): if (cupy is not None): global kernel if (kernel is None): import awkward._connect.cuda._kernel_signatures cuda_src = f'''#define ERROR_BITS {ERROR_BITS} #define NO_ERROR {NO_ERROR}''' cuda_kernels_path = os.path.join(os.path.dirn...
def test(file): h2t = Horn2Transitions() h2t.parse(file) mp = MiniIC3(h2t.init, h2t.trans, h2t.goal, h2t.xs, h2t.inputs, h2t.xns) result = mp.run() if isinstance(result, Goal): g = result print('Trace') while g: print(g.level, g.cube) g = g.parent ...
class FSD50k(HearScene): _cfg(**HearScene.setup.default_except(corpus=dict(CLS=field(hear_scene_trainvaltest, '\nThe corpus class. You can add the **kwargs right below this CLS key', str), dataset_root=field('???', 'The root path of the corpus', str)), train_sampler=newdict(CLS=FixedBatchSizeBatchSampler, batch_siz...
class TestClearInput(): def check_input_data_clear_called_flags(self, answer): result = clear_called_flag_recorder.get_input_clear_called_flags() assert (len(result) == len(answer)) for (i, flags) in enumerate(answer): assert (len(result[i]) == len(flags)) for (j, fla...
class LinearModel(): def __init__(self, coefficient, bias): self.coefficient = coefficient self.bias = bias def __repr__(self): return 'LinearModel(coefficient={:.4f}, bias={:.4f})'.format(self.coefficient, self.bias) def evaluate(self, x): return ((self.coefficient * x) + se...
class SqueezeNetV11(SqueezeNet): def __init__(self): super(SqueezeNetV11, self).__init__('v1.1')
class SimpleShot(FewShotClassifier): def forward(self, query_images: Tensor) -> Tensor: query_features = self.compute_features(query_images) self._raise_error_if_features_are_multi_dimensional(query_features) scores = self.cosine_distance_to_prototypes(query_features) return self.sof...
def build_transforms_swap(cfg, is_train=True, PIXEL_MEAN=[0.485, 0.456, 0.406], PIXEL_STD=[0.229, 0.224, 0.225]): normalize_transform = T.Normalize(mean=PIXEL_MEAN, std=PIXEL_STD) if is_train: transform = T.Compose([T.Resize([cfg.height, cfg.width]), T.RandomHorizontalFlip(p=0.5), T.Pad(10), T.RandomCro...
def _get_codegen_targets(sdfg: SDFG, frame: framecode.DaCeCodeGenerator): disp = frame._dispatcher provider_mapping = InstrumentationProvider.get_provider_mapping() disp.instrumentation[dtypes.InstrumentationType.No_Instrumentation] = None disp.instrumentation[dtypes.DataInstrumentationType.No_Instrumen...
def test_gammaincc_edge_cases(): assert (gammaincc(1.2, np.inf) == 0) assert (gammaincc((- 1.2), np.inf) == 0) assert (gammaincc(0, np.inf) == 0) npt.assert_equal(gammaincc([1.2, 2.2], np.inf), [0, 0]) npt.assert_equal(gammaincc([(- 1.2), (- 2.2)], np.inf), [0, 0]) npt.assert_equal(gammaincc([0....
class Tanh_DenseNet(nn.Module): def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=100): super(Tanh_DenseNet, self).__init__() self.growth_rate = growth_rate num_planes = (2 * growth_rate) self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, padding=1, bias...