code
stringlengths
101
5.91M
def subgraphs_to_query(subgraphs, db): q = GraphQuery(graph_db=db, induced_subgraphs=subgraphs[1]) if (subgraphs[0] == 'all_of'): for i in range(2, len(subgraphs)): q.intersect(GraphQuery(graph_db=db, induced_subgraphs=subgraphs[i]), in_place=True) elif (subgraphs[0] == 'one_of'): ...
def test_2d_2d_stride_trick(): data = np.array([101], dtype=np.int32) array = np.lib.stride_tricks.as_strided(data, (40, 3), strides=(0, 0)) container = {'node0-data': array} form = '\n {\n "class": "NumpyArray",\n "primitive": "int32",\n "form_key": "node0",\n ...
_model('convtransformer') class ConvTransformerModel(FairseqEncoderDecoderModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) def add_args(parser): parser.add_argument('--input-feat-per-channel', type=int, metavar='N', help='encoder input dimension per input channel'...
.parametrize('sampling_strategy', ['auto', 'majority', 'not minority', 'not majority', 'all']) def test_random_under_sampler_strings(sampling_strategy): (X, y) = make_classification(n_samples=100, n_clusters_per_class=1, n_classes=3, weights=[0.1, 0.3, 0.6], random_state=0) RandomUnderSampler(sampling_strategy=...
def register_function(lib, item, ignore_errors): try: func = getattr(lib, item[0]) except AttributeError as e: msg = (str(e) + '. Please ensure that your python bindings are compatible with your libclang.so version.') if ignore_errors: return raise LibclangError(msg) ...
def soft_update_from_to(source, target, tau): for (target_param, param) in zip(target.parameters(), source.parameters()): target_param.data.copy_(((target_param.data * (1.0 - tau)) + (param.data * tau)))
class ParallelAvoidance(): def __init__(self, ped_ped=None, *, b_center=0.0, **kwargs): self.ped_ped = (ped_ped or potentials.PedPedPotential(2.1)) self.b_center = b_center self.simulator = Simulator(ped_ped=self.ped_ped, **kwargs) def generate(self, n): speed0 = (0.7 + (0.4 * to...
('data.resisc45', 'class') class Resisc45Data(base.ImageTfdsData): def __init__(self, data_dir=None): dataset_builder = tfds.builder('resisc45:3.*.*', data_dir=data_dir) dataset_builder.download_and_prepare() num_examples = dataset_builder.info.splits['train'].num_examples train_coun...
def test_rag_generator(): generator = RagGenerator(client_name='openai', model_name='text-curie-001', context_dir='data/home_search/v0', max_output_token=256, top_k_api=10, top_k_example=3, query_template='{api_docs}\n{examples}\nTask: {query}\nActions:\n') query = 'Find a home with 12 bed above $961000 in Birm...
def separate_and_evaluate(track, args, ext): estimates = test.separate(track.audio, args) if args.out_dir: mus.save_estimates(estimates, track, args.out_dir) scores = museval.eval_mus_track(track, estimates, output_dir=args.out_dir) ext.clear_memory_cache() return scores
def get_args(): parser = argparse.ArgumentParser() parser = add_ffn_train_args(parser) return parser.parse_args()
def check_dist_restriction(options, check_target=False): dist_restriction_set = any([options.python_version, options.platform, options.abi, options.implementation]) binary_only = FormatControl(set(), {':all:'}) sdist_dependencies_allowed = ((options.format_control != binary_only) and (not options.ignore_dep...
def processFiles(fname, prefix, dset, trunc): dataset = [] codeVocab = collections.Counter() nlVocab = collections.Counter() i = 0 didnt_parse = 0 for line in open(fname, 'r'): i += 1 if ((i % 10000) == 0): print(i) js = json.loads(line) code = js['ren...
class class_cls(nn.Module): def __init__(self, input_dim, nclass): super(class_cls, self).__init__() self.fc = nn.Linear(input_dim, nclass) self.logic = nn.LogSoftmax(dim=1) self.fc1 = nn.Linear(input_dim, 512) self.bn1_fc = nn.BatchNorm1d(512) self.fc2 = nn.Linear(51...
def is_PowerSeriesRing(R): if isinstance(R, PowerSeriesRing_generic): return (R.ngens() == 1) else: return False
def get_public_fields(obj): return [attr for attr in dir(obj) if (not (attr.startswith('_') or inspect.isbuiltin(attr) or inspect.isfunction(attr) or inspect.ismethod(attr)))]
def single_or_rankzero(): return ((not _current_communicator) or (_current_communicator.rank == 0))
class UniformPolicy(Policy, Serializable): def __init__(self, env_spec): Serializable.quick_init(self, locals()) self._Da = env_spec.action_space.flat_dim super(UniformPolicy, self).__init__(env_spec) def get_action(self, observation): return (np.random.uniform((- 1.0), 1.0, self...
.skipif((not has_pytorch()), reason='Pytorch not installed.') _utils.test() def test_torch_zero(): def test_torch(arr: ti.types.ndarray()): pass test_torch(torch.zeros(0, dtype=torch.int32)) test_torch(torch.zeros((0, 5), dtype=torch.int32)) test_torch(torch.zeros((5, 0, 5), dtype=torch.int32))
class TestAAPhi(unittest.TestCase): def test_aa_phi(self): ms = range(1, 5) ns = range(1, 5) for m in ms: U = b.util.haar_rand(m) for n in ns: phiU = b.aa_phi(U, n) phiUCorrect = aa_phi_slow(U, n) self.assertTrue(np.allc...
class Siren(nn.Module): def __init__(self, in_features, hidden_features, hidden_layers, out_features, outermost_linear=False, first_omega_0=30, hidden_omega_0=30.0): super().__init__() self.net = [] self.net.append(SineLayer(in_features, hidden_features, is_first=True, omega_0=first_omega_0)...
def _try_numeric(val: str) -> ((float | str) | None): if (val == ''): return None try: return float(val) except ValueError: return val
def _get_line_to_branch_coverage(subject_properties, trace): line_to_branch_coverage = {} for predicate in subject_properties.existing_predicates: lineno = subject_properties.existing_predicates[predicate].line_no if (lineno not in line_to_branch_coverage): line_to_branch_coverage[li...
def load_checkpoints(model, path, device): checkpoint = torch.load(path, map_location=device) model_state = checkpoint.get('model_state', None) model.load_state_dict(model_state)
def make_builder(out_file, impl, vocab_size=None): if (impl == 'mmap'): return MMapIndexedDatasetBuilder(out_file, dtype=__best_fitting_dtype(vocab_size)) elif (impl == 'fasta'): raise NotImplementedError else: return IndexedDatasetBuilder(out_file)
def test_tf_grad_log_sm(): import tensorflow as tf print('TF version:', tf.__version__) with tf.Session() as session: x = tf.constant([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) y = tf.nn.log_softmax(x) scores = [0.0, float('-inf'), float('-inf')] def combine(s_, y_): ret...
_utils.test(require=ti.extension.bls) def test_scattering(): bls_particle_grid(N=128, ppc=10, block_size=8, scatter=True, use_offset=False)
class BiSeNet(nn.Module): def __init__(self, num_class): super(BiSeNet, self).__init__() self.cp = ContextPath() self.ffm = FeatureFusionModule(256, 256) self.conv_out = BiSeNetOutput(256, 256, num_class) self.conv_out16 = BiSeNetOutput(128, 64, num_class) self.conv_o...
def test_multiclip_mono(): class TestClip(core.Clip): def __init__(self, key, data_home='foo', dataset_name='foo', index=None, metadata=None): self.key = key def f(self): return (np.random.uniform((- 1), 1, 100), 1000) class TestClipGroup1(core.ClipGroup): def __i...
def step(epoch): if (epoch < (EP / 4)): return 0 if (epoch < (EP / 2)): return (1 / 3) if (epoch < ((EP * 3) / 4)): return (2 / 3) else: return 1
def generate_seq_indexes(indexes): if (not indexes): (yield []) return for ind in indexes[0]: for seq in generate_seq_indexes(indexes[1:]): (yield ([ind] + seq))
def load_existing_model(args, cfg, cfg_train, reload_ckpt_path, device): FourierGrid_datasets = ['waymo', 'mega', 'nerfpp'] if ((cfg.data.dataset_type in FourierGrid_datasets) or (cfg.model == 'FourierGrid')): model_class = FourierGridModel elif cfg.data.ndc: model_class = dmpigo.DirectMPIGO...
def update_average(model_tgt, model_src, beta): param_dict_src = dict(model_src.named_parameters()) for (p_name, p_tgt) in model_tgt.named_parameters(): p_src = param_dict_src[p_name] assert (p_src is not p_tgt) p_tgt.copy_(((beta * p_tgt) + ((1.0 - beta) * p_src)))
class AlgebraicNumber_base(sage.structure.element.FieldElement): def __init__(self, parent, x): sage.structure.element.FieldElement.__init__(self, parent) if isinstance(x, (int, sage.rings.integer.Integer, sage.rings.rational.Rational)): self._descr = ANRational(x) elif isinstanc...
def save_rates(ckpt_path, handle): (runner, spikes, rates) = init_by_ckpt(ckpt_path, mode=DATASET_MODES.val) if (('maze' in variant) or ('m700' in variant)): runner.config.defrost() runner.config.DATA.DATAPATH = '/snel/share/data/ndt_paper/m1_maze/heldout_trial/2296_trials/0_seed' runner...
def test_box(): def f3(x): return x builder = lb.Numpy(np.int32) out1 = f3(builder) assert (ak.to_list(out1.snapshot()) == []) for x in range(15): out1.append(x) out2 = f3(out1) assert (ak.to_list(out2.snapshot()) == list(range(15))) builder = lb.Empty() out3 = f3(bui...
def value_func(obs, critic_policy=None, qf1=None, qf2=None): (actions, *_) = critic_policy(obs) sa = torch.cat([obs, actions], dim=(- 1)) (q1, q2) = (qf1(sa), qf2(sa)) min_q = torch.min(q1, q2) return min_q
def test_semisupervisedtrainingplan_metrics(): adata = scvi.data.synthetic_iid(n_labels=3) scvi.model.SCANVI.setup_anndata(adata, labels_key='labels', unlabeled_category='label_0', batch_key='batch') model = scvi.model.SCANVI(adata) model.train(max_epochs=1, check_val_every_n_epoch=1) for mode in ['...
def get_rnn_cell(cell_class, num_units, num_layers=1, keep_prob=1.0, dropout_input_keep_prob=None, dropout_output_keep_prob=None, reuse=None): if (dropout_input_keep_prob is None): dropout_input_keep_prob = keep_prob if (dropout_output_keep_prob is None): dropout_output_keep_prob = keep_prob ...
def ignore_exceptions(func): def inner(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter('ignore') try: return func(*args, **kwargs) except Exception: return None return inner
_torch _sentencepiece _tokenizers class LlamaIntegrationTest(unittest.TestCase): def setUpClass(cls): checkpoint_name = 'hf-internal-testing/llama-tokenizer' cls.tokenizer: LlamaTokenizer = LlamaTokenizer.from_pretrained(checkpoint_name) cls.rust_tokenizer = LlamaTokenizerFast.from_pretraine...
def make_target_python(options): target_python = TargetPython(platform=options.platform, py_version_info=options.python_version, abi=options.abi, implementation=options.implementation) return target_python
def predict(): args = get_args() kwargs = args.__dict__ save_dir = kwargs['save_dir'] common.setup_logger(save_dir, log_name='scarf_pred_binned.log', debug=kwargs['debug']) pl.utilities.seed.seed_everything(kwargs.get('seed')) yaml_args = yaml.dump(kwargs) logging.info(f''' {yaml_args}''') ...
class TD2020LearnAPI(TFPluginAPI): def __init__(self): self.owning_player = None self.initial_board_config = None self.setup = False self.g = None self.graph_var = None self.session_var = None self.mcts = None def onSetup(self): graph = tf.Graph() ...
def test_raises_on_non_square_input(): with pytest.raises(ValueError): graph = csr_matrix([[0, 1, 2], [2, 1, 0]]) maximum_flow(graph, 0, 1)
class UpsamplingBilinear2d(Upsample): def __init__(self, size=None, scale_factor=None): super(UpsamplingBilinear2d, self).__init__(size, scale_factor, mode='bilinear', align_corners=True) def forward(self, input): warnings.warn('nn.UpsamplingBilinear2d is deprecated. Use nn.functional.interpolat...
class KR_type_C(KirillovReshetikhinGenericCrystal): def classical_decomposition(self): return CrystalOfTableaux(self.cartan_type().classical(), shapes=horizontal_dominoes_removed(self.r(), self.s())) def ambient_crystal(self): return KashiwaraNakashimaTableaux(['A', ((2 * self.cartan_type().clas...
class InceptionC(nn.Module): def __init__(self, in_channels, channels_7x7, conv_block=None): super(InceptionC, self).__init__() if (conv_block is None): conv_block = BasicConv2d self.branch1x1 = conv_block(in_channels, 192, kernel_size=1) c7 = channels_7x7 self.br...
class ActivationHessianTraceBasicModelTest(BaseHessianTraceBasicModelTest): def __init__(self, unit_test): super().__init__(unit_test) self.val_batch_size = 1 def run_test(self, seed=0): (graph, pytorch_impl) = self._setup() hessian_service = hessian_common.HessianInfoService(gra...
def load_config(config_file=None): config = base_config if (config_file is not None): config_file_path = os.path.join('lib', 'configs', f'{config_file}.yaml') if os.path.isfile(config_file_path): config.merge_from_file(config_file_path) msg = f"Merged config from '{config...
def last_k(tokens, k): if (not (0 <= k <= len(tokens))): raise ValueError('k must be between 0 and len(tokens) = {}, got: {}'.format(len(tokens), k)) return tuple(tokens[(len(tokens) - k):])
class TestCatalogue_Star(TestCase): def test_magV(self): x = [star.magV for star in exocat.stars] def test_T(self): x = [star.T for star in exocat.stars] def test_calcTemperature(self): x = [star.calcTemperature() for star in exocat.stars]
def isProjective(heads): pairs = [(h, d) for (d, h) in enumerate(heads, 1) if (h >= 0)] for (i, (hi, di)) in enumerate(pairs): for (hj, dj) in pairs[(i + 1):]: ((li, ri), (lj, rj)) = (sorted([hi, di]), sorted([hj, dj])) if ((li <= hj <= ri) and (hi == dj)): return...
.parametrize('digits_bits', [23, 24]) _utils.test(require=ti.extension.quant) def test_quant_float_precision(digits_bits): qflt = ti.types.quant.float(exp=8, frac=digits_bits) x = ti.field(dtype=qflt) bitpack = ti.BitpackedFields(max_num_bits=32) bitpack.place(x) ti.root.place(bitpack) tests = [...
def get_midi_info(pm): if pm.time_signature_changes: pm.time_signature_changes.sort(key=(lambda x: x.time)) first_beat_time = pm.time_signature_changes[0].time else: first_beat_time = pm.estimate_beat_start() (tc_times, tempi) = pm.get_tempo_changes() if (len(pm.time_signature_ch...
def parse_nested_args(d_cmd_cfg): d_new_cfg = {} for (key, val) in d_cmd_cfg.items(): l_key = key.split('.') d = d_new_cfg for (i_key, each_key) in enumerate(l_key): if (i_key == (len(l_key) - 1)): d[each_key] = val else: if (each_k...
class PythonCapiFunctionNode(ExprNode): subexprs = [] def __init__(self, pos, py_name, cname, func_type, utility_code=None): ExprNode.__init__(self, pos, name=py_name, cname=cname, type=func_type, utility_code=utility_code) def analyse_types(self, env): return self def generate_result_co...
class Runner(object): def __init__(self, config): self.all_args = config['all_args'] self.envs = config['envs'] self.eval_envs = config['eval_envs'] self.device = config['device'] self.num_agents = config['num_agents'] if config.__contains__('render_envs'): ...
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_dk_cvr(val)): if (errors == 'raise'): raise ValueError(f'Unable to parse value {val}') error_re...
def setup_buckets(src_region, dest_region, n_files=1, file_size_mb=1): (src_provider, src_zone) = src_region.split(':') (dest_provider, dest_zone) = dest_region.split(':') if (src_provider == 'azure'): src_bucket_name = f"skyplanetest{src_zone}/{str(uuid.uuid4()).replace('-', '')}" else: ...
def test_offline_dataset(): if (not ray.is_initialized()): ray.init() server = OfflineDataset(table_capacity=10000) server.start() (pname, pqueue) = server.start_producer_pipe(name='test_offline_dataset') (cname, cqueue) = server.start_consumer_pipe(name='test_offline_dataset', batch_size=64...
def dla60x(cfg, pretrained=None, **kwargs): BottleneckX.expansion = 2 model = DLA(cfg, [1, 1, 1, 2, 3, 1], [16, 32, 128, 256, 512, 1024], block=BottleneckX, **kwargs) if (pretrained is not None): model.load_pretrained_model(pretrained, 'dla60x') return model
class ExperimentBaseRunner(ABC): def __init__(self, exp: Experiment, env: ExpEnv, verbose: bool) -> None: self.exp = exp self.env = env self.verbose = verbose self.out = ExpOutput(exp) self.running: tp.List[tp.Tuple[(Simulator, SimpleComponent)]] = [] self.sockets: tp...
class CheckpointManager(object): BLOB_NAMES = 'blob_names' def __init__(self, db_prefix, node_name, db_type, metadata_handler=None): self._db_prefix = db_prefix self._node_name = node_name self._db_type = db_type self._metadata_handler = metadata_handler self._net = core....
def save_model(state, checkpoint, filename='checkpoint.pth.tar'): filename = (('epoch' + str(state['epoch'])) + filename) filepath = os.path.join(checkpoint, filename) torch.save(state, filepath)
def register_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter< ns3::WifiInformationElement ...
def argparser(is_train=True): def str2bool(v): return (v.lower() == 'true') parser = argparse.ArgumentParser() parser.add_argument('--debug', type=str2bool, default=False) parser.add_argument('--batch_size', type=int, default=8, help='the mini-batch size') parser.add_argument('--prefix', typ...
def is_package_installed_and_updated(package: str) -> bool: try: all_packages = list_packages(local=True) pkginfo = all_packages[package] return (pkginfo.installed_version == pkginfo.remote_version) except KeyError: return is_package_installed(package)
class Sequencer(object): def __init__(self): self._preds = {} self._succs = {} self._nodes = set() def add_node(self, node): self._nodes.add(node) def remove_node(self, node, edges=False): if (node in self._nodes): self._nodes.remove(node) if edges...
def main(): logging.info(f'Reading annotations from {args.data_file} file...') dataset = read_jsonl_datafile(args.data_file) logging.info(f'Total annotations:{len(dataset)}') logging.info(f'Creating labeled data instances from annotations...') print(dataset[0].keys()) (task_instances_dict, tag_s...
def transpose_network(nn): incoming = {} outgoing = defaultdict((lambda : [])) dfg = nn.dataFlow orig_nodes = [x for x in nn.nodes] for node in orig_nodes: if (node.isOperator() and (node.name == 'Conv')): arg_dict = utils.ArgsToDict(node.annotation.operator_def.arg) ...
class StandardPermutations_descents(StandardPermutations_n_abstract): def __classcall_private__(cls, d, n): return super().__classcall__(cls, tuple(sorted(d)), n) def __init__(self, d, n): StandardPermutations_n_abstract.__init__(self, n) self._d = d def _repr_(self): return ...
def download_language_builtin_entities(language, *pip_args): from builtins import str from snips_nlu_parsers import get_supported_gazetteer_entities from snips_nlu import __about__ from snips_nlu.cli.download import download_from_resource_name from snips_nlu.cli.utils import check_resources_alias, g...
.parametrize('result', [True, False]) def test_mutation_change_call_success(constructor_mock, result, default_test_case): factory = MagicMock(tf.TestFactory) factory.change_random_call.return_value = result chromosome = tcc.TestCaseChromosome(default_test_case, test_factory=factory) const0 = Constructor...
class LocalsDictItemNode(DictItemNode): def analyse_types(self, env): self.key = self.key.analyse_types(env) self.value = self.value.analyse_types(env) self.key = self.key.coerce_to_pyobject(env) if self.value.type.can_coerce_to_pyobject(env): self.value = self.value.coer...
def build_norm_layer(cfg, num_features, postfix=''): if (not isinstance(cfg, dict)): raise TypeError('cfg must be a dict') if ('type' not in cfg): raise KeyError('the cfg dict must contain the key "type"') cfg_ = cfg.copy() layer_type = cfg_.pop('type') if (layer_type not in NORM_LAY...
def load_url(url, model_dir='./pretrained', map_location=torch.device('cpu')): if (not os.path.exists(model_dir)): os.makedirs(model_dir) filename = url.split('/')[(- 1)] cached_file = os.path.join(model_dir, filename) if (not os.path.exists(cached_file)): sys.stderr.write('Downloading: ...
def _expm_multiply_interval_core_0(A, X, h, mu, q, norm_info, tol, ell, n0): if (norm_info.onenorm() == 0): (m_star, s) = (0, 1) else: norm_info.set_scale((1.0 / q)) (m_star, s) = _fragment_3_1(norm_info, n0, tol, ell=ell) norm_info.set_scale(1) for k in range(q): X[(...
_decorator(0) def get_status(html): cont = public.get_left(html) if (cont == ''): return 0 soup = BeautifulSoup(cont, 'lxml') try: return int(soup.find_all('strong')[2].get_text()) except Exception: return 0
def camera_ray_from_pixel_with_jacobians(self: sf.CameraCal, pixel: sf.V2, epsilon: sf.Scalar) -> T.Tuple[(sf.V3, sf.Scalar, sf.M, sf.M)]: (point, is_valid) = self.camera_ray_from_pixel(pixel, epsilon) point_D_cal = point.jacobian(self.parameters()) point_D_pixel = point.jacobian(pixel) return (point, i...
def generate_bsb(dims, reduce_dim, warp_reduce_dim, libname, reps=1): if os.path.exists(libname): return size = reduce((lambda x, y: (x * y)), dims.values()) for d in dims: if ((d != reduce_dim) and (d != warp_reduce_dim)): non_reduce_dim = d non_reduce_size = dims[non_reduce...
def sense(phase, pos, ang): p = (pos + (ti.Vector([ti.cos(ang), ti.sin(ang)]) * SENSE_DIST)) return grid[(phase, (p.cast(int) % GRID_SIZE))]
def test_clip_action(as_default, as_jt_full, as_jt_norm, as_jp_full, as_jp_norm): assert (as_default.clip_action(upper_99_normalized_action) == upper_99_normalized_action).all() assert (as_default.clip_action(lower_99_normalized_action) == lower_99_normalized_action).all() assert (as_default.clip_action(upp...
(config_path='./conf', config_name='config') def main(config: DictConfig) -> None: set_seed(config.train.state.seed) logger.info(OmegaConf.to_yaml(config, resolve=True)) logger.info(f'Using the model: {config.model.name}') (train_data, val_data) = get_data(config) config.data.num_class = len(set([x[...
class ProperlyShapedPointEstimateModelMixin(PointEstimateActorModelMixin): def forward_pass_actor(self): with tf.variable_scope('NormalizeNetworkInput'): self._create_normalized_network_input() with tf.variable_scope('ForwardGraph'): h = self.normalized_network_input ...
def protoge_config(): config = default_ddpg_config() config.gamma = 0.98 config.actor_lr = 0.001 config.critic_lr = 0.001 config.actor_weight_decay = 0.0 config.action_l2_regularization = 0.1 config.target_network_update_freq = 40 config.target_network_update_frac = 0.05 config.optim...
class Shift(nn.Module): def __init__(self, kernel_size, dim): super(Shift, self).__init__() self.kernel_size = kernel_size self.dim = dim assert ((dim == 2) or (dim == 3)) assert ((kernel_size % 2) == 1) def forward(self, x): if (self.kernel_size == 1): ...
def register_Ns3BasicEnergySourceHelper_methods(root_module, cls): cls.add_constructor([param('ns3::BasicEnergySourceHelper const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_virtual=True) cls.add_method...
def _expm(A, use_exact_onenorm): if isinstance(A, (list, tuple, np.matrix)): A = np.asarray(A) if ((len(A.shape) != 2) or (A.shape[0] != A.shape[1])): raise ValueError('expected a square matrix') if (A.shape == (0, 0)): out = np.zeros([0, 0], dtype=A.dtype) if (issparse(A) or...
class AdditiveSemigroups(CategoryWithAxiom_singleton): _base_category_class_and_axiom = (AdditiveMagmas, 'AdditiveAssociative') AdditiveCommutative = LazyImport('sage.categories.commutative_additive_semigroups', 'CommutativeAdditiveSemigroups', at_startup=True) AdditiveUnital = LazyImport('sage.categories.a...
def main(args): args.device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) train_path_sp = (args.data_path + 'cnsd-sts-train.txt') train_path_unsp = (args.data_path + 'cnsd-sts-train_unsup.txt') dev_path_sp = (args.data_path + 'cnsd-sts-dev.txt') test_path_sp = (args.data_path + ...
def select_free_cuda(): tmp_name = str(uuid.uuid1()).replace('-', '') os.system(('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >' + tmp_name)) memory_gpu = [int(x.split()[2]) for x in open(tmp_name, 'r').readlines()] os.system(('rm ' + tmp_name)) return np.argmax(memory_gpu)
class ConvBnReLU2d(ConvBn2d): _FLOAT_MODULE = nni.ConvBnReLU2d _FLOAT_CONV_MODULE = nn.Conv2d _FLOAT_BN_MODULE = nn.BatchNorm2d _FLOAT_RELU_MODULE = nn.ReLU def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=None, padding_mode='zeros', eps=1e-0...
def load_spm(path: str) -> sentencepiece.SentencePieceProcessor: spm = sentencepiece.SentencePieceProcessor() spm.Load(str(path)) return spm
def unpublishMySelf(): global profile, brokerURL deviceCtxObj = {} deviceCtxObj['entityId'] = {} deviceCtxObj['entityId']['id'] = ((('Device.' + profile['type']) + '.') + profile['id']) deviceCtxObj['entityId']['type'] = profile['type'] deviceCtxObj['entityId']['isPattern'] = False deleteCon...
def test_analyze_with_all_actions_as_list(): img = 'dataset/img4.jpg' demography_objs = DeepFace.analyze(img, actions=['age', 'gender', 'race', 'emotion'], silent=True) for demography in demography_objs: logger.debug(f'Demography: {demography}') age = demography['age'] gender = demog...
def getter_setter_test(): cluster = generate_test_cluster('tests.fixtures.linecoverage.setter_getter') transformer = AstToTestCaseTransformer(cluster, False, EmptyConstantProvider()) transformer.visit(ast.parse('def test_case_0():\n setter_getter_0 = module_0.SetterGetter()\n int_0 = 3360\n int_1 =...
def main(env_name='Acrobot-v1', n_episodes=1000, actor_lr=0.001, critic_lr=0.01, gamma=0.98, gae_lambda=0.95, epsilon=0.2, jax_seed=42): env = gym.make(env_name) assert (len(env.observation_space.shape) == 1) agent = PPOAgent(state_dim=env.observation_space.shape[0], action_dim=env.action_space.n, actor_lr=...
def get_sequence_check_dna(f): sequence_list = [] for e in read_fasta_yield(f): res = is_under_alphabet(e.seq, ALPHABET) if (res is not True): raise ValueError(' '.join(['Sorry, sequence', str(e.no), 'has character', str(res), '(The character must be A, C, G or T)'])) else: ...
def generator_loss(disc_outputs): loss = 0 gen_losses = [] for dg in disc_outputs: l = torch.mean(((1 - dg) ** 2)) gen_losses.append(l) loss += l return (loss, gen_losses)