code
stringlengths
101
5.91M
def aa_to_quat(axis_angle: Union[(torch.Tensor, numpy.ndarray)]) -> Union[(torch.Tensor, numpy.ndarray)]: if (axis_angle.shape[(- 1)] != 3): raise ValueError(f'Invalid input axis angles f{axis_angle.shape}.') t = Compose([axis_angle_to_quaternion]) return t(axis_angle)
def withClass(classname, namespace=''): classattr = (('%s:class' % namespace) if namespace else 'class') return withAttribute(**{classattr: classname})
def register_Ns3DesMetrics_methods(root_module, cls): cls.add_method('Initialize', 'void', [param('int', 'argc'), param('char * *', 'argv'), param('std::string', 'outDir', default_value='""')]) cls.add_method('Trace', 'void', [param('ns3::Time const &', 'now'), param('ns3::Time const &', 'delay')]) cls.add_...
def symbolic_override(symbolic_fn): return functools.partial(_symbolic_override_wrapper_maker, symbolic_fn, (lambda x: True))
def register_Ns3ArfWifiManager_methods(root_module, cls): cls.add_constructor([param('ns3::ArfWifiManager const &', 'arg0')]) cls.add_constructor([]) cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_method('SetHeSupported', 'void', [param('bool', 'enable')], is_virtual=True) cl...
def process_str_value(v: str) -> str: if ((len(v) > 0) and (v[0] in QUOTE_CHARS)): v = v[1:] if ((len(v) > 0) and (v[(- 1)] in QUOTE_CHARS)): v = v[:(- 1)] for c in QUOTE_CHARS: v = v.replace((c + c), c) return v
def get_circle_coordinates(r: float, degree: float): if ((degree < 0) or (degree > 360)): raise ValueError radian = (((degree / 360) * 2) * np.pi) x = (r * np.sin(radian)) y = (r * np.cos(radian)) return (x, y)
def getContent(request): if (request.method == 'GET'): if request.user.is_authenticated: ACCESS_DENIED = False else: ACCESS_DENIED = True if ACCESS_DENIED: return redirect('/login') else: return render(request, 'content.html') else:...
_model def metaformer_ppff_s12_224(pretrained=False, **kwargs): layers = [2, 2, 6, 2] embed_dims = [64, 128, 320, 512] token_mixers = [Pooling, Pooling, partial(SpatialFc, spatial_shape=[14, 14]), partial(SpatialFc, spatial_shape=[7, 7])] mlp_ratios = [4, 4, 4, 4] downsamples = [True, True, True, Tr...
def run_test(test, args=(), test_atol=1e-05, n=100, iters=None, callback=None, minimizer_kwargs=None, options=None, sampling_method='sobol'): res = shgo(test.f, test.bounds, args=args, constraints=test.cons, n=n, iters=iters, callback=callback, minimizer_kwargs=minimizer_kwargs, options=options, sampling_method=sam...
def prepare_config(exp_config: Union[(List[str], str)], run_type: str, ckpt_path='', opts=None, suffix=None) -> None: config = get_config(exp_config, opts) if isinstance(exp_config, str): variant_config = exp_config else: variant_config = exp_config[(- 1)] variant_name = osp.split(varian...
def hans_convert_examples_to_features(examples, tokenizer, max_length=512, task=None, label_list=None, output_mode=None, pad_on_left=False, pad_token=0, pad_token_segment_id=0, mask_padding_with_zero=True): is_tf_dataset = False if (is_tf_available() and isinstance(examples, tf.data.Dataset)): is_tf_dat...
def dilated_basic_1d(filters, suffix, stage=0, block=0, kernel_size=3, numerical_name=False, stride=None, dilations=(1, 1)): if (stride is None): if ((block != 0) or (stage == 0)): stride = 1 else: stride = 2 if ((block > 0) and numerical_name): block_char = 'b{}'...
def new_empty(g, self, sizes, dtype, layout, device, pin_memory=False): if ((dtype is None) and self.isCompleteTensor()): dtype = self.type().scalarType() dtype = sym_help.scalar_type_to_onnx.index(sym_help.cast_pytorch_to_onnx[dtype]) return empty(g, sizes, dtype, layout, device, pin_memory)
def launch_experiment(variant, get_config=None, get_offline_algorithm=None, exp_postfix='', use_gpu=True, log_to_tensorboard=False, data_args=None): experiment_config = dict() if (get_config is not None): experiment_config['get_config'] = get_config if (get_offline_algorithm is not None): ex...
def nano_sleep(time_ns): wait_until = (time.time_ns() + time_ns) while (time.time_ns() < wait_until): pass
def count_string_tokens(string: str, model_name: str) -> int: try: encoding = tiktoken.encoding_for_model(model_name) except KeyError: logger.warn('Warning: model not found. Using cl100k_base encoding.') encoding = tiktoken.get_encoding('cl100k_base') return len(encoding.encode(strin...
def test_gather(): time_dim = Dim(Tensor('time', [batch_dim], dtype='int32')) in_dim = Dim(7, name='in') extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')}) class _Net(rf.Module): def __call__(self, x: Tensor) -> Tensor: return rf.gather...
class BaseDetNeck(nn.Module, metaclass=ABCMeta): def __init__(self, subtype=None, cfg=None, in_channels=None, mid_channels=None, out_channels=None, num_blocks=None, aux_out_channels=None, depthwise=False, conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), act_cfg=dict(type='ReLU')): super(BaseDetN...
def isnan(x): ftype = impl.get_runtime().default_fp fx = ops.cast(x, ftype) if static((ftype == f64)): y = ops.bit_cast(fx, u64) return (((ops.cast((y >> 32), u32) & ) + (ops.cast(y, u32) != 0)) > ) y = ops.bit_cast(fx, u32) return ((y & ) > )
def _impl(array, value_set, skip_nones, highlevel, behavior, attrs): from awkward._connect.pyarrow import import_pyarrow_compute from awkward.operations.str import _apply_through_arrow pc = import_pyarrow_compute('ak.str.index_in') with HighLevelContext(behavior=behavior, attrs=attrs) as ctx: (l...
class BloomInt8(CausalInt8Model): config_name: str = 'bloom_int8' def __init__(self, weights_path: Optional[str]=None): super().__init__(BloomInt8Engine.config_name, weights_path)
_module() class VCRDataset(MInstrDataset): def __init__(self, *args, version, **kwargs): super().__init__(*args, **kwargs, placeholders=(IMAGE_PLACEHOLDER, QUESTION_PLACEHOLDER)) self.version = version assert (version in ['q-a', 'q-ra', 'qc-a', 'qc-ra', 'qc-rac', 'qa-r', 'q-a-q-r', 'qac-r', ...
def disambiguate_grad_if_op_output(grad_op, idx, new_grad_output): then_net = _get_net_argument(grad_op, 'then_net') old_grad_out_match = grad_op.output[idx] for op in then_net.op: for (i, out) in enumerate(op.output): if (out == old_grad_out_match): op.output[i] = new_gr...
_test() def test_ddr_reduce_red_1x40_8b_decouple_array_interfaces(): with set_temporary('compiler', 'xilinx', 'decouple_array_interfaces', value=True): return exec_test(1, 40, 8, 'ddr', 'red_1x40_8b_decoupled')
def train(args, train_loader, model, criterion, optimizer, epoch): model.train() iouEvalTrain = iouEval(args.classes) epoch_loss = [] total_batches = len(train_loader) for (i, (input, target)) in enumerate(train_loader): start_time = time.time() if (args.onGPU == True): i...
class FormattedTimesMixin(object): cpu_time_str = attr_formatter('cpu_time') cuda_time_str = attr_formatter('cuda_time') cpu_time_total_str = attr_formatter('cpu_time_total') cuda_time_total_str = attr_formatter('cuda_time_total') self_cpu_time_total_str = attr_formatter('self_cpu_time_total') s...
def make_regex(obj): if (not can_be_regex(obj)): raise ValueError('Expected a string or a regex, got: {}'.format(type(obj))) if isinstance(obj, string_types): return re.compile(obj) else: return obj
def register_Ns3Ipv6AddressGenerator_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::Ipv6AddressGenerator const &', 'arg0')]) cls.add_method('AddAllocated', 'bool', [param('ns3::Ipv6Address const', 'addr')], is_static=True) cls.add_method('GetAddress', 'ns3::Ipv6Addre...
('colorbar', orientation='vertical', format=None, spacing='uniform') ('label', fontsize=9, colors='blue', inline=None, inline_spacing=3, fmt='%1.2f') (plot_points=100, fill=True, contours=None, linewidths=None, linestyles=None, labels=False, frame=True, axes=False, colorbar=False, legend_label=None, aspect_ratio=1, reg...
class KGDataset(): def __init__(self, entity_path, relation_path, train_path, valid_path=None, test_path=None, format=[0, 1, 2], delimiter='\t', skip_first_line=False): self.delimiter = delimiter (self.entity2id, self.n_entities) = self.read_entity(entity_path) (self.relation2id, self.n_rela...
def main(): with _utils.tqdm_stdout() as orig_stdout: parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, required=True) parser.add_argument('-H', '--visdom-host', type=str, required=False) parser.add_argument('-P', '--visdom-port', type=int, required=F...
.parametrize('observation_shape', [(100,)]) .parametrize('action_size', [2]) .parametrize('n_episodes', [100]) .parametrize('episode_length', [10]) def test_initial_state_value_estimation_scorer(observation_shape: Sequence[int], action_size: int, n_episodes: int, episode_length: int) -> None: A = np.random.random((...
def left(): PressKey(Z) PressKey(Q) ReleaseKey(D) time.sleep(t_time) ReleaseKey(Q)
class CopyCheckTester(unittest.TestCase): def setUp(self): self.transformer_dir = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir, 'models/bert/')) check_copies.TRANSFORMER_PATH = self.transformer_dir shutil.copy(os.path.join(git_repo_path, 'src/transformers/models/b...
def test_nest_cf_simple_if_elif(): def simple_if_elif(i: dace.int64): if (i < 2): return 0 elif (i < 4): return 1 elif (i < 6): return 2 elif (i < 8): return 3 else: return 4 sdfg = simple_if_elif.to_sdfg() n...
.parametrize('synthesizer', SYNTHESIZERS) def test_sampling_reset_sampling(synthesizer): metadata = SingleTableMetadata.load_from_dict({'METADATA_SPEC_VERSION': 'SINGLE_TABLE_V1', 'columns': {'column1': {'sdtype': 'numerical'}, 'column2': {'sdtype': 'address'}, 'column3': {'sdtype': 'email'}, 'column4': {'sdtype': ...
def _inception_v3(*args, **kwargs): try: version = tuple(map(int, torchvision.__version__.split('.')[:2])) except ValueError: version = (0,) if (version >= (0, 6)): kwargs['init_weights'] = False return torchvision.models.inception_v3(*args, **kwargs)
class Request(RequestHooksMixin): def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): data = ([] if (data is None) else data) files = ([] if (files is None) else files) headers = ({} if (headers is None)...
class SpeakerVerifi_train(Dataset): def __init__(self, vad_config, key_list, file_path, meta_data, max_timestep=None, n_jobs=12): self.roots = file_path self.root_key = key_list self.max_timestep = max_timestep self.vad_c = vad_config self.dataset = [] self.all_speake...
def def_API(name, result, params): global API2Id, next_id global log_h, log_c mk_py_binding(name, result, params) reg_dotnet(name, result, params) API2Id[next_id] = name mk_log_header(log_h, name, params) log_h.write(';\n') mk_log_header(log_c, name, params) log_c.write(' {\n R();\n...
def test_olsq_swap_transition(): lsqc_solver = OLSQ_cirq('swap', 'transition') lsqc_solver.setdevicegraph(device_graph) lsqc_solver.setprogram(circuit) assert (lsqc_solver.solve()[2] == 1)
class JukeboxPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class WEBVIDDataModule(BaseDataModule): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def dataset_cls(self): return WEBVIDDataset def dataset_cls_no_false(self): return WEBVIDDataset def dataset_name(self): return 'webvid'
.parametrize('synthesizer', SYNTHESIZERS) def test_sampling(synthesizer): sample_1 = synthesizer.sample(10) sample_2 = synthesizer.sample(10) with pytest.raises(AssertionError): pd.testing.assert_frame_equal(sample_1, sample_2)
def which(thefile): path = os.environ.get('PATH', os.defpath).split(os.pathsep) for d in path: fname = os.path.join(d, thefile) fnames = [fname] if (sys.platform == 'win32'): exts = os.environ.get('PATHEXT', '').split(os.pathsep) fnames += [(fname + ext) for ext i...
def merge(src, tgt, hypos, log_probs, path): with open(path, 'w') as f: for (s, t, hs, lps) in zip(src, tgt, hypos, log_probs): f.write((s + '\n')) f.write((t + '\n')) f.write('\n') for (h, lp) in zip(hs, lps): f.write(('\t%f\t%s\n' % (lp, h.st...
class LstmFlatteningResult(nn.LSTM): def forward(self, input, *fargs, **fkwargs): (output, (hidden, cell)) = nn.LSTM.forward(self, input, *fargs, **fkwargs) return (output, hidden, cell)
def debug_logger(log_dir): logger = getLogger('train') logger.setLevel(DEBUG) fmt = Formatter('%(asctime)s %(name)s %(lineno)d [%(levelname)s][%(funcName)s] %(message)s') sh = StreamHandler() sh.setLevel(INFO) sh.setFormatter(fmt) logger.addHandler(sh) fh = FileHandler(filename=log_dir.j...
def progress_bar(iterator, log_format: Optional[str]=None, log_interval: int=100, log_file: Optional[str]=None, epoch: Optional[int]=None, prefix: Optional[str]=None, tensorboard_logdir: Optional[str]=None, default_log_format: str='tqdm', wandb_project: Optional[str]=None, wandb_run_name: Optional[str]=None, azureml_lo...
def return_html(story_file): story_name = path.basename(story_file) html_string = (HTML_START + '<div style="line-height: 3">') (all_tokens, cluster_id_to_spans) = story_to_info[story_file] ment_start_dict = defaultdict(list) ment_end_dict = defaultdict(list) for (cluster_idx, ment_list) in clus...
class DDIMSampler(object): def __init__(self, diffusion, model, schedule='linear', alpha_generator_func=None, set_alpha_scale=None): super().__init__() self.diffusion = diffusion self.model = model self.device = diffusion.betas.device self.ddpm_num_timesteps = diffusion.num_t...
class MLPReadout(nn.Module): def __init__(self, in_dim, out_dim, act): super(MLPReadout, self).__init__() self.layer1 = nn.Linear(in_dim, out_dim) self.act = nn.ReLU() self.out_act = act def forward(self, x): ret = self.layer1(x) return self.out_act(ret)
def parse_args(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--dataset_file', '-d', required=True, help='dataset file with protein names') parser.add_argument('--protein_path', '-pp', required=True, help='directory of protein files') par...
def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3SpectrumValue__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::SpectrumValue const >, ns3::empty, ns3::empty...
def test_meta_post_init(synthetic_slate_bandit_feedback: BanditFeedback) -> None: ope_ = SlateOffPolicyEvaluation(bandit_feedback=synthetic_slate_bandit_feedback, ope_estimators=[sips, sips2]) assert (ope_.ope_estimators_ == {'sips': sips2}), '__post_init__ returns a wrong value' ope_ = SlateOffPolicyEvalua...
class DropPath(nn.Module): def __init__(self, drop_prob=None): super(DropPath, self).__init__() self.drop_prob = drop_prob def forward(self, x): return drop_path(x, self.drop_prob, self.training)
def get_absolute_path(p): if p.startswith('~'): p = os.path.expanduser(p) return os.path.abspath(p)
((not have_sympy), 'SymPy not installed') def test_unevaluated_expr(): x = Symbol('x') e1 = sympy.UnevaluatedExpr(sympy.Symbol('x')) e2 = UnevaluatedExpr(x) assert (sympify(e1) == e2) assert (e2._sympy_() == e1)
def block_reduction_b(inputs, scope=None, reuse=None): with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'): with tf.variable_scope(scope, 'BlockReductionB', [inputs], reuse=reuse): with tf.variable_scope('Branch_0'): branch_0 = slim.conv...
def plot_topk_histogram(tag, array, k=10, class_names=None, figsize=None): (val, ind) = torch.topk(array, k) fig = plt.Figure(figsize=figsize, facecolor='w', edgecolor='k') ax = fig.add_subplot(1, 1, 1) if (class_names is None): class_names = [str(i) for i in ind] else: class_names =...
class MethodsDict(CaseInsensitiveDict): def __getitem__(self, item: Any) -> Any: try: return super().__getitem__(item) except KeyError as exc: available_methods = ', '.join(map(str.upper, self)) message = f'Method `{item}` not found. Available methods: {available_...
def _place_post_grad_agg_ops_hybrid(ps_device, var_op_to_agg_grad, var_op_to_apply_grad_op): def _find_agg_grad_descendant_ops(agg_grad_ops, apply_grad_ops): agg_grad_descendant_ops = set() queue = [] queue.extend(agg_grad_ops) while (len(queue) > 0): curr_op = queue.pop(...
_utils.test(exclude=[ti.metal, ti.opengl, ti.gles, ti.cuda, ti.vulkan, ti.amdgpu]) def test_node_manager(): def test(): impl.call_internal('test_node_allocator') test() test()
def get_ckpt_epochs() -> List[int]: paths = glob.glob(get_ckpt_path('*')) return sorted([int(osp.basename(path).split('.')[0]) for path in paths])
def register_Ns3GenericMacHeader_methods(root_module, cls): cls.add_constructor([param('ns3::GenericMacHeader const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) cls.add_method('GetCi', 'uint8_t', [], is_const=...
def test_invalid(): layout = ak.contents.RecordArray([ak.contents.NumpyArray([1, 2, 3]), ak.contents.NumpyArray([1, 2, 3])], ['x', 'x']) assert (re.match(".*duplicate field 'x'.*", ak.validity_error(layout)) is not None)
class QuantumManagerDensityFock(QuantumManager): def __init__(self, truncation: int=1): super().__init__(DENSITY_MATRIX_FORMALISM, truncation=truncation) def new(self, state=None) -> int: key = self._least_available self._least_available += 1 if (state is None): gnd =...
.parametrize('mask_distance,expected', [(1, ((- 2.), (- 2.))), (2, ((- 0.), (- 0.))), (5, ((- 0.), (- 0.))), (10, ((- 0.), (- 0.))), (28, ((- 0.), (- 0.))), (50, ((- 0.), (- 0.)))]) def test_likelihood_batch_with_individual_masking_distance(msa_sampler, msa_batch_example, mask_distance, expected): result = list(msa...
def _impl(array): if isinstance(array, (ak.highlevel.Array, ak.highlevel.Record, ak.highlevel.ArrayBuilder)): return array.to_list() elif isinstance(array, (ak.contents.Content, ak.record.Record)): return array.to_list(None) elif isinstance(array, _ext.ArrayBuilder): (formstr, length...
class CheckOnlineDocs(Step): def action(self, context): self.instruct('Check online docs') open_website(URLs.DOCS_ONLINE)
class Queue(): def __init__(self, size_max: int) -> None: assert (size_max > 0) self.max = size_max self.head = 0 self.tail = 0 self.size = 0 self.data = array.array('i', range(size_max)) def empty(self) -> bool: return (self.size != 0) def full(self) ...
def profileToProfile(im, inputProfile, outputProfile, renderingIntent=INTENT_PERCEPTUAL, outputMode=None, inPlace=False, flags=0): if (outputMode is None): outputMode = im.mode if ((not isinstance(renderingIntent, int)) or (not (0 <= renderingIntent <= 3))): raise PyCMSError('renderingIntent mus...
class TestTranslation(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) def test_fconv(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fconv') as data_dir: ...
def make_batch_roberta_bert(sessions): (batch_input, batch_labels, batch_speaker_tokens) = ([], [], []) for session in sessions: data = session[0] label_list = session[1] (context_speaker, context, emotion, sentiment) = data now_speaker = context_speaker[(- 1)] speaker_ut...
def _log_obj(name, obj, prefix): if (name in ['wandb', 'dset', 'model']): try: obj = vars(obj)['_content'] except Exception: return if isinstance(obj, dict): logger.info(f'{prefix}{name}:') for (k, v) in obj.items(): _log_obj(k, v, (prefix + ' ...
def halo3d(x, a, sigma, array_size): ar = np.zeros(array_size, dtype=float) for i in range(array_size[0]): for j in range(array_size[1]): for k in range(array_size[2]): dx = float(reduce((lambda foo, y: (foo + (y ** 2))), [0, (i - x[0]), (j - x[1]), (k - x[2])])) ...
def d_logistic_loss(real_pred, fake_pred): real_loss = F.softplus((- real_pred)) fake_loss = F.softplus(fake_pred) return (real_loss.mean() + fake_loss.mean())
def sunrgbd_data_prep(root_path, info_prefix, out_dir, workers): indoor.create_indoor_info_file(root_path, info_prefix, out_dir, workers=workers)
def type_check(param, value): if isinstance(value, bool): if (param in DEFAULTS[MAIN]['boolean']): return True elif isinstance(value, list): if (param in DEFAULTS[MAIN]['list']): list_type = type(DEFAULTS[MAIN]['list'][param][0]) if all((isinstance(elem, list_...
def main(): parser = argparse.ArgumentParser() parser.add_argument('dataset', type=str, help='Dataset (or a single file) to process') parser.add_argument('--output', type=str, help='Write the processed data here instead of clobbering') parser.add_argument('--constituency_package', type=str, default=None...
class RSCrop(object): def __init__(self, size): self.size = size def __call__(self, img, mask): assert (img.size == mask.size) crop_size = self.size short_size = random.randint(int((self.size * 0.5)), int((self.size * 2.0))) (w, h) = img.size if (h > w): ...
class KMaxPool1d(nn.Module): def __init__(self, k): super().__init__() self.k = k def forward(self, inputs): return kmax_pooling(inputs, 2, self.k) def __repr__(self): fmt_str = self.__class__.__name__ fmt_str += '(k={0})'.format(self.k) return fmt_str
def train_model(): args = get_args() kwargs = args.__dict__ save_dir = kwargs['save_dir'] common.setup_logger(save_dir, log_name='autoregr_train.log', debug=kwargs['debug']) pl.utilities.seed.seed_everything(kwargs.get('seed')) yaml_args = yaml.dump(kwargs) logging.info(f''' {yaml_args}''') ...
def find_d_likelihood(ln, lk, n, k, ww): return SMin(_compute_binomial_logl, args=(lk, k, ln, n, ww), bounds=((D_MIN + np.finfo(np.float16).eps), D_MAX), method='bounded').x
def get_next_nonempty_states(sdfg: SDFG, state: SDFGState) -> Set[SDFGState]: result: Set[SDFGState] = set() for succ in sdfg.successors(state): result |= set(dfs_conditional(sdfg, sources=[succ], condition=(lambda parent, _: parent.is_empty()))) result = {s for s in result if (not s.is_empty())} ...
class CustomDataset(BaseDataset): def __init__(self, csv_name, is_training, study_level, transform_args, toy, return_info_dict, logger=None, data_args=None, stability_training=False): super().__init__(csv_name, is_training, transform_args) self.study_level = study_level self.toy = toy ...
_params({'X': ['array-like', 'sparse matrix'], 'y': ['array-like']}, prefer_skip_nested_validation=True) def chi2(X, y): X = check_array(X, accept_sparse='csr', dtype=(np.float64, np.float32)) if np.any(((X.data if issparse(X) else X) < 0)): raise ValueError('Input X must be non-negative.') Y = Labe...
def visits_per_time_unit(traj, time_unit='1h'): return pd.DataFrame(traj[constants.DATETIME]).set_index(traj[constants.DATETIME]).groupby(pd.Grouper(freq=time_unit)).count().rename(columns={constants.DATETIME: 'n_visits'})
def length_to_string(len, bin_bound): flag = False for (i, bucket) in enumerate(bin_bound): if ((len >= bucket[0]) and (len < bucket[1])): id_ = i flag = True break if (not flag): raise ValueError("didn't find a bucket for length {}".format(len)) retur...
def load_data(input_dir, bert_name, batch_size): cache_fn = os.path.join(input_dir, 'processed.pt') if os.path.exists(cache_fn): print('Read from cache file: {} (NOTE: delete it if you modified data loading process)'.format(cache_fn)) with open(cache_fn, 'rb') as fp: (ent2id, rel2id,...
.datainstrument def test_dinstr_strided(): def dinstr(A: dace.float64[(20, 20)]): tmp = (A + 1) return (tmp + 5) sdfg = dinstr.to_sdfg(simplify=True) sdfg.arrays['tmp'].total_size = (32 * 32) sdfg.arrays['tmp'].strides = (32, 1) _instrument(sdfg, dace.DataInstrumentationType.Save, ig...
class Caffe2CompatibleConverter(object): def __init__(self, replaceCls): self.replaceCls = replaceCls def create_from(self, module): assert isinstance(module, torch.nn.Module) if issubclass(self.replaceCls, GenericMixin): new_class = type('{}MixedWith{}'.format(self.replaceCl...
def DF_calc(classes): try: return ((len(classes) - 1) ** 2) except Exception: return 'None'
def ask_questions_in_text(sample, bridge_entity, num_sent=2, replace_with_ENT=True): bridge_entity_name_in_table = bridge_entity['name'] bridge_entity_text_url = bridge_entity['url'] bridge_entity_text = get_passage(sample, bridge_entity_text_url, num_sent) if (bridge_entity_text is None): retur...
def subsample_dataset(dataset, idxs): mask = np.zeros(len(dataset)).astype('bool') mask[idxs] = True dataset.data = dataset.data[mask] dataset.uq_idxs = dataset.uq_idxs[mask] return dataset
def main(): parser = argparse.ArgumentParser() parser.add_argument('-g', '--use-ggui', action='store_true', help='Display with GGUI') parser.add_argument('-a', '--arch', required=False, default='cpu', dest='arch', type=str, help='The arch (backend) to run this example on') (args, unknowns) = parser.pars...
def stream_audio(filename): is_tmp = False if filename.startswith('s3://'): tmpname = simpleutils.download_tmp_from_s3(filename) is_tmp = True filename = tmpname try: return WaveStream(filename, is_tmp=is_tmp) except: pass try: return ffmpeg_stream_aud...
class IndexStore(ABC): def __init__(self, cleanup: bool=True): self._index = None self.cleanup = cleanup def save_to_store(self, save_index: Callable[([str], None)]): def load_index(self, init_index: Callable[([], None)], load_index: Callable[([Any, str], None)], configure_index: Callable[([...
def _program_name(function) -> str: result = '' if ((function.__module__ is not None) and (function.__module__ != '__main__')): result += (function.__module__.replace('.', '_') + '_') return (result + function.__name__)