code
stringlengths
281
23.7M
def _resolve_looppart(parts, assign_path, context): assign_path = assign_path[:] index = assign_path.pop(0) for part in parts: if isinstance(part, util.UninferableBase): continue if (not hasattr(part, 'itered')): continue try: itered = part.itered(...
def metrics_traversal_order(state_dict: Dict[(str, Dict[(str, TState)])]) -> List[Tuple[(str, str)]]: dict_items = [] for outer_key in sorted(state_dict.keys()): inner_dict = state_dict[outer_key] for inner_key in sorted(inner_dict.keys()): dict_items.append((outer_key, inner_key)) ...
.parametrize('val', [set_test_value(pt.lscalar(), np.array(6, dtype='int64'))]) def test_Bartlett(val): g = extra_ops.bartlett(val) g_fg = FunctionGraph(outputs=[g]) compare_numba_and_py(g_fg, [i.tag.test_value for i in g_fg.inputs if (not isinstance(i, (SharedVariable, Constant)))], assert_fn=(lambda x, y:...
def extract_tarinfo(tarfile, class_to_idx=None, sort=True): extensions = get_img_extensions(as_set=True) files = [] labels = [] for ti in tarfile.getmembers(): if (not ti.isfile()): continue (dirname, basename) = os.path.split(ti.path) label = os.path.basename(dirname...
class TestIsRoot(): .windows .parametrize('directory, is_root', [('C:\\foo\\bar', False), ('C:\\foo\\', False), ('C:\\foo', False), ('C:\\', True)]) def test_windows(self, directory, is_root): assert (filescheme.is_root(directory) == is_root) .posix .parametrize('directory, is_root', [('/foo...
.network def test_prepare_directory_with_extensions(config: Config, config_cache_dir: Path, artifact_cache: ArtifactCache, fixture_dir: FixtureDirGetter) -> None: env = EnvManager.get_system_env() chef = Chef(artifact_cache, env, Factory.create_pool(config)) archive = fixture_dir('extended_with_no_setup').r...
def metrics_df_from_toml_path(toml_path, min_segment_dur, device='cuda', spect_key='s', timebins_key='t'): toml_path = Path(toml_path) cfg = config.parse.from_toml(toml_path) with cfg.eval.labelmap_path.open('r') as f: labelmap = json.load(f) model_config_map = config.models.map_from_path(toml_p...
class TCPCollector(diamond.collector.Collector): PROC = ['/proc/net/netstat', '/proc/net/snmp'] def process_config(self): super(TCPCollector, self).process_config() if (self.config['allowed_names'] is None): self.config['allowed_names'] = [] if (self.config['gauges'] is None)...
def test_repr__undefined(): datum_name = 'unknown' if PROJ_GTE_901: datum_name = f'{datum_name} using nadgrids=' assert (repr(CRS('+proj=merc +a=6378137.0 +b=6378137.0 +nadgrids= +lon_0=0.0 +x_0=0.0 +y_0=0.0 +units=m +no_defs')) == f'''<Bound CRS: +proj=merc +a=6378137.0 +b=6378137.0 +nadgrids= ...>...
class FunnelConverter(Converter): def converted(self) -> Tokenizer: vocab = self.original_tokenizer.vocab tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token))) tokenize_chinese_chars = False strip_accents = False do_lower_case = False ...
def reconstitute_tpm(subsystem): node_tpms = [node.tpm.tpm[(..., 1)] for node in subsystem.nodes] node_tpms = [tpm.squeeze(axis=subsystem.external_indices) for tpm in node_tpms] node_tpms = [np.expand_dims(tpm, (- 1)) for tpm in node_tpms] node_tpms = [(tpm * np.ones((([2] * (tpm.ndim - 1)) + [tpm.shape...
def is_valid_total_withdraw(channel_state: NettingChannelState, our_total_withdraw: WithdrawAmount, allow_zero: bool=False) -> SuccessOrError: balance = get_balance(sender=channel_state.our_state, receiver=channel_state.partner_state) withdraw_overflow = (not is_valid_channel_total_withdraw(TokenAmount((our_tot...
_label def equal_hash_ref_loop(data, idx, key, env, cont): from pycket.interpreter import return_value from pycket.prims.equal import equal_func_unroll_n, EqualInfo if (idx >= len(data)): return return_value(w_missing, env, cont) (k, v) = data[idx] info = EqualInfo.BASIC_SINGLETON cont =...
def _simple_compact(variables): var_array = VarEntities.varToEVarArray[variables[0]] (mins, maxs) = (([float('inf')] * len(var_array.size)), ([float('-inf')] * len(var_array.size))) for x in variables: for (i, v) in enumerate(x.indexes): mins[i] = min(mins[i], v) maxs[i] = ma...
class GraphVAEOptimizer(object): def __init__(self, model, learning_rate=0.001): self.kl_weight = tf.placeholder_with_default(1.0, shape=()) self.la = tf.placeholder_with_default(1.0, shape=()) edges_loss = tf.losses.sparse_softmax_cross_entropy(labels=model.edges_labels, logits=model.edges_...
class DataTrainingArguments(): task_name: Optional[str] = field(default='ner', metadata={'help': 'The name of the task (ner, pos...).'}) dataset_name: Optional[str] = field(default='wikiann', metadata={'help': 'The name of the dataset to use (via the datasets library).'}) dataset_config_name: Optional[str] ...
def drop_block_fast_2d(x: torch.Tensor, drop_prob: float=0.1, block_size: int=7, gamma_scale: float=1.0, with_noise: bool=False, inplace: bool=False, batchwise: bool=False): (B, C, H, W) = x.shape total_size = (W * H) clipped_block_size = min(block_size, min(W, H)) gamma = ((((gamma_scale * drop_prob) *...
class W2lFairseqLMDecoder(W2lDecoder): def __init__(self, args, tgt_dict): super().__init__(args, tgt_dict) self.silence = tgt_dict.bos() self.unit_lm = getattr(args, 'unit_lm', False) self.lexicon = (load_words(args.lexicon) if args.lexicon else None) self.idx_to_wrd = {} ...
def simple_model(simple_model_data): with pm.Model() as model: mu_ = pm.Normal('mu', mu=simple_model_data['mu0'], sigma=simple_model_data['sigma0'], initval=0) pm.Normal('x', mu=mu_, sigma=simple_model_data['sigma'], observed=simple_model_data['data'], total_size=simple_model_data['n']) return m...
class ClassDefinitionTestCase(unittest.TestCase): def runTest(self): errors = 0 commands_dir = os.path.join(os.path.dirname(pykickstart.__file__), 'commands') commands_dir = os.path.abspath(commands_dir) self.assertTrue(os.path.exists(commands_dir)) if (commands_dir not in sy...
class MembershipDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Membership slug_field = 'creator__username' raise_exception = True = ['post', 'delete'] def get_success_url(self): return reverse('users:user_detail', kwargs={'slug': self.request.user.username}) de...
def test_gpu_normalize(): def check_normalize(origin_imgs, result_imgs, norm_cfg): from numpy.testing import assert_array_almost_equal target_imgs = result_imgs.copy() target_imgs *= norm_cfg['std'] target_imgs += norm_cfg['mean'] assert_array_almost_equal(origin_imgs, target...
def test_tdm_fmcw_rx(): print('#### TDM FMCW receiver ####') tdm = tdm_fmcw_rx() print('# TDM FMCW receiver parameters #') assert (tdm.bb_prop['fs'] == 2000000.0) assert (tdm.rf_prop['noise_figure'] == 4) assert (tdm.rf_prop['rf_gain'] == 20) assert (tdm.bb_prop['load_resistor'] == 500) ...
class LambdaWarmUpCosineScheduler2(): def __init__(self, warm_up_steps, f_min, f_max, f_start, cycle_lengths, verbosity_interval=0): assert (len(warm_up_steps) == len(f_min) == len(f_max) == len(f_start) == len(cycle_lengths)) self.lr_warm_up_steps = warm_up_steps self.f_start = f_start ...
def main(): code = '18dczc1337a63427fa' redirect_url = ' app = 0 secret = 'dGbpoJdqNuMlGDECgO9I' vk_session = vk_api.VkApi(app_id=app, client_secret=secret) try: vk_session.code_auth(code, redirect_url) except vk_api.AuthError as error_msg: print(error_msg) return ...
class UperNetFCNHead(nn.Module): def __init__(self, config, in_index: int=2, kernel_size: int=3, dilation: Union[(int, Tuple[(int, int)])]=1) -> None: super().__init__() self.config = config self.in_channels = config.auxiliary_in_channels self.channels = config.auxiliary_channels ...
class TestNonInjectiveLink(unittest.TestCase): (ONE_TEST_TIMEOUT) def test_select_project_forward(self): (rdf_graph, schema) = get_graph_and_schema('dev', 'concert_singer') correct_sparql_query = textwrap.dedent(' SELECT ?singer_name\n WHERE\n {\n ?p...
def test_dual_basis_element(): de = DualBasisElement() de_2 = DualBasisElement() db_0 = (de + de_2) assert isinstance(db_0, DualBasis) db_1 = (db_0 + db_0) assert isinstance(db_1, DualBasis) dim = 2 opdm = np.random.random((dim, dim)) opdm = ((opdm.T + opdm) / 2) opdm = Tensor(te...
def one_hot(indices, depth, no_cuda=False): shape = (list(indices.size()) + [depth]) indices_dim = len(indices.size()) if no_cuda: a = torch.zeros(shape, dtype=torch.float) else: a = torch.zeros(shape, dtype=torch.float).cuda() return a.scatter_(indices_dim, indices.unsqueeze(indices...
def test_hookrelay_registry(pm: PluginManager) -> None: class Api(): def hello(self, arg: object) -> None: pm.add_hookspecs(Api) hook = pm.hook assert hasattr(hook, 'hello') assert (repr(hook.hello).find('hello') != (- 1)) class Plugin(): def hello(self, arg): return ...
_importer.add('(?:decoder|transformer)/logits/kernel(\\w*)') def final_logits(opts, key, val, slot): del opts, key prefix = ('state/param_states' if slot else 'target') suffix = (('/' + SLOT_MAP[slot]) if slot else '') newkey = f'{prefix}/decoder/logits_dense/kernel{suffix}' return (newkey, val)
_task('sentence_prediction') class SentencePredictionTask(FairseqTask): def add_args(parser): parser.add_argument('data', metavar='FILE', help='file prefix for data') parser.add_argument('--num-classes', type=int, default=(- 1), help='number of classes') parser.add_argument('--init-token', t...
class CustomModel(openlm.BaseModel): def create_completion(self, model: Union[(str, List[str])], prompt: Union[(str, List[str])], suffix: Optional[str]=None, max_tokens: Optional[int]=None, temperature: Optional[float]=None, top_p: Optional[float]=None, n: Optional[int]=None, stream: Optional[bool]=None, logprobs: ...
class DownloadStats(base.ScriptBaseWithConfig): ARGS_HELP = '' VERSION = '1.0' FIELDS = ('is_active', 'left_bytes', 'size_bytes', 'down.rate', 'priority') MIN_STALLED_RATE = (5 * 1024) STALLED_PERCENT = 10 def add_options(self): super(DownloadStats, self).add_options() def mainloop(s...
class InfoThread(PluginThread): def __init__(self, manager, data, pid=(- 1), rid=(- 1), add=False): super().__init__(manager) self.data = data self.pid = pid self.rid = rid self.add = add self.cache = [] self.start() def run(self): plugins = {} ...
class FakeIterable(Iterable): def __init__(self, container): self.iterator = container self.size = len(self.iterator) self.step = 0 def __iter__(self) -> Iterator: return self def __next__(self): if (self.step == self.size): raise StopIteration() r...
class Lanes(XodrBase): def __init__(self): super().__init__() self.lanesections = [] self.laneoffsets = [] self.roadmarks_adjusted = False def __eq__(self, other): if (isinstance(other, Lanes) and super().__eq__(other)): if ((self.laneoffsets == other.laneoffs...
def run_gamma(filepath_ref, filepath_eval, random_subset=None, max_gamma=1.1, dose_threshold=1, distance_threshold=1): if (random_subset is not None): np.random.seed(42) ds_ref = pydicom.read_file(filepath_ref) ds_eval = pydicom.read_file(filepath_eval) axes_reference = load_yx_from_dicom(ds_ref...
def write_train_pkl(obj_list_path, meta, output_dir, cate): obj_list = read_obj_list(obj_list_path) model = DeformedImplicitField(**meta) model.load_state_dict(torch.load(meta['checkpoint_path'])) assert (len(obj_list) == model.latent_codes.weight.size()[0]) pkl_info = {} for i in range(len(obj_...
def convert_esm_checkpoint_to_pytorch(model: str, pytorch_dump_folder_path: str, classification_head: bool, push_to_repo: str, auth_token: str): if model.startswith('esmfold'): esm = MODEL_MAPPING[model]() else: (esm, alphabet) = MODEL_MAPPING[model]() esm.eval() if model.startswith('esm...
class ErrorBox(QtWidgets.QWidget): def __init__(self, parent): QtWidgets.QWidget.__init__(self, parent) parent.installEventFilter(self) self.setAttribute(QtCore.Qt.WidgetAttribute.WA_TransparentForMouseEvents) self._resize() self.setVisible(False) def eventFilter(self, ob...
class webvision_dataset(Dataset): def __init__(self, root_dir, transform, mode, num_class, num_samples=None, losses=[]): self.root = root_dir self.transform = transform self.mode = mode if (self.mode == 'test'): with open(os.path.join(self.root, 'info/val_filelist.txt')) ...
def test_dtype_rescaling_uint8_half(tmpdir, runner): outputname = str(tmpdir.join('test.tif')) result = runner.invoke(main_group, ['convert', 'tests/data/RGB.byte.tif', outputname, '--scale-ratio', '0.5']) assert (result.exit_code == 0) with rasterio.open(outputname) as src: for band in src.read...
def test_interactive_with_file_dependency(tester: CommandTester, repo: TestRepository, source_dir: Path, fixture_dir: FixtureDirGetter) -> None: repo.add_package(get_package('pendulum', '2.0.0')) repo.add_package(get_package('pytest', '3.6.0')) demo = (fixture_dir('distributions') / 'demo-0.1.0-py2.py3-none...
def dfs_visit(node: PackageNode, back_edges: dict[(DFSNodeID, list[PackageNode])], visited: set[DFSNodeID], sorted_nodes: list[PackageNode]) -> None: if (node.id in visited): return visited.add(node.id) for neighbor in node.reachable(): back_edges[neighbor.id].append(node) dfs_visit(...
class TestRunner(InferenceRunner): def __init__(self, test_cfg, inference_cfg, base_cfg=None): super().__init__(inference_cfg, base_cfg) self.test_dataloader = self._build_dataloader(test_cfg['data']) extra_data = (len(self.test_dataloader.dataset) % self.world_size) self.test_exclud...
class OptionalActions(): def __init__(self, args, input_images, alignments): logger.debug('Initializing %s', self.__class__.__name__) self.args = args self.input_images = input_images self.alignments = alignments self.remove_skipped_faces() logger.debug('Initialized %...
class ucred_t(ctypes.Structure): class cr_entry(ctypes.Structure): _fields_ = (('tqe_next', POINTER64), ('tqe_prev', POINTER64)) class posix_cred_t(ctypes.Structure): _fields_ = (('cr_uid', ctypes.c_uint32), ('cr_ruid', ctypes.c_uint32), ('cr_svuid', ctypes.c_uint32), ('cr_ngroups', ctypes.c_sho...
class QtileEventLoopPolicy(asyncio.DefaultEventLoopPolicy): def __init__(self, qtile: Qtile) -> None: asyncio.DefaultEventLoopPolicy.__init__(self) self.qtile = qtile def get_event_loop(self) -> asyncio.AbstractEventLoop: if isinstance(self.qtile._eventloop, asyncio.AbstractEventLoop): ...
class YInflictedDamageMixin(): def _getDamagePerKey(self, src, time): if (time is None): raise ValueError return self._getTimeCacheDataPoint(src=src, time=time) def _prepareTimeCache(self, src, maxTime): self.graph._timeCache.prepareDmgData(src=src, maxTime=maxTime) def _...
class nyudepthv2(BaseDataset): def __init__(self, data_path, filenames_path='./dataset/filenames/', is_train=True, crop_size=(448, 576), scale_size=None): super().__init__(crop_size) if (crop_size[0] > 480): scale_size = (int(((crop_size[0] * 640) / 480)), crop_size[0]) self.scal...
.parametrize('version, part, expected', [('1.0.4-rc.1', 'major', '2.0.0'), ('1.1.0-rc.1', 'major', '2.0.0'), ('1.1.4-rc.1', 'major', '2.0.0'), ('1.2.3', 'major', '2.0.0'), ('1.0.0-rc.1', 'major', '1.0.0'), ('0.2.0-rc.1', 'minor', '0.2.0'), ('0.2.5-rc.1', 'minor', '0.3.0'), ('1.3.1', 'minor', '1.4.0'), ('1.3.2', 'patch'...
def get_norm_layer(opt, norm_type='instance'): def get_out_channel(layer): if hasattr(layer, 'out_channels'): return getattr(layer, 'out_channels') return layer.weight.size(0) def add_norm_layer(layer, opt): nonlocal norm_type if norm_type.startswith('spectral'): ...
() def session_api(skip_qtbot): network_client = MagicMock() network_client.server_call = AsyncMock() root = QtWidgets.QWidget() skip_qtbot.addWidget(root) api = MultiplayerSessionApi(network_client, 1234) api.logger.setLevel(logging.DEBUG) api.widget_root = root return api
def get_temporary_copy(path: Union[(str, Path)]) -> Path: path = env.get_path(path) assert ((not path.is_dir()) and (not path.is_symlink())) tmp_path = path.with_name((((path.stem + '___') + str(uuid.uuid4()).replace('-', '')) + path.suffix)) shutil.copyfile(path, tmp_path) atexit.register((lambda :...
def read_and_store_bindings(f: Callable, bindings: Dict[(str, type)]) -> None: function_bindings = (getattr(f, '__bindings__', None) or {}) if (function_bindings == 'deferred'): function_bindings = {} merged_bindings = dict(function_bindings, **bindings) if hasattr(f, '__func__'): f = ca...
def test_handler_bad_request(api_gw_url): body_str = json.dumps({'order_item_count': 5}) response = requests.post(api_gw_url, data=body_str) assert (response.status_code == HTTPStatus.BAD_REQUEST) body_dict = json.loads(response.text) assert (body_dict == {'error': 'invalid input'})
class TestSources(): def test_default(self, isolation): builder = MockBuilder(str(isolation)) assert (builder.config.sources == builder.config.sources == {}) assert (builder.config.get_distribution_path(pjoin('src', 'foo', 'bar.py')) == pjoin('src', 'foo', 'bar.py')) def test_global_inva...
class BinaryBinnedAUROC(Metric[Tuple[(torch.Tensor, torch.Tensor)]]): def __init__(self: TBinaryBinnedAUROC, *, num_tasks: int=1, threshold: Union[(int, List[float], torch.Tensor)]=DEFAULT_NUM_THRESHOLD, device: Optional[torch.device]=None) -> None: super().__init__(device=device) threshold = _creat...
_flags(compute_test_value='raise') def test_mvnormal_ShapeFeature(): M_pt = iscalar('M') M_pt.tag.test_value = 2 d_rv = multivariate_normal(pt.ones((M_pt,)), pt.eye(M_pt), size=2) fg = FunctionGraph([i for i in graph_inputs([d_rv]) if (not isinstance(i, Constant))], [d_rv], clone=False, features=[ShapeF...
def print_args(args): args_verbosity = getattr(args, 'args_verbosity', 1) if (args_verbosity == 2): args_sorted = sorted(vars(args).items()) for (name, value) in args_sorted: print(f'{name}={value}') elif (args_verbosity == 1): print(args) elif (args_verbosity == 0): ...
class TestBotCommandScopeWithoutRequest(): def test_slot_behaviour(self, bot_command_scope): for attr in bot_command_scope.__slots__: assert (getattr(bot_command_scope, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(bot_command_scope)) == len(set(mro_slots(bot_c...
.parametrize('dtype', ['u1', 'int64', 'float32', 'float64']) def test_tofile(tmp_path, xp, dtype): filepath = str((tmp_path / 'test_tofile')) src = xp.arange(100, dtype=dtype) tofile(src, filepath) dst = xp.fromfile(filepath, dtype=dtype) xp.testing.assert_array_equal(src, dst) tofile(src[::2], ...
def reverse_by_epsilon(forward_process, predicted_noise, x, t): fs = forward_process.forward_schedule exs = fs.extract(t, x.shape) betas_t = exs['betas'] sqrt_one_minus_alphas_cumprod_t = exs['sqrt_one_minus_alphas_cumprod'] sqrt_recip_alphas_t = exs['sqrt_recip_alphas'] posterior_variance_t = e...
def anchor(parser, token): bits = [b.strip('"\'') for b in token.split_contents()] if (len(bits) < 2): raise template.TemplateSyntaxError('anchor tag takes at least 1 argument') try: title = bits[2] except IndexError: title = bits[1].capitalize() return SortAnchorNode(bits[1]...
.parametrize('method_name', ['waitExposed', 'waitActive']) def test_wait_window_propagates_other_exception(method_name, qtbot): method = getattr(qtbot, method_name) widget = qt_api.QtWidgets.QWidget() qtbot.add_widget(widget) with pytest.raises(ValueError, match='some other error'): with method(...
def test_delitem() -> None: d: Dict[(str, object)] = {'x': 1} monkeypatch = MonkeyPatch() monkeypatch.delitem(d, 'x') assert ('x' not in d) monkeypatch.delitem(d, 'y', raising=False) pytest.raises(KeyError, monkeypatch.delitem, d, 'y') assert (not d) monkeypatch.setitem(d, 'y', 1700) ...
class LeNet(nn.Module): def __init__(self): super(LeNet, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5, stride=1, padding=2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(400, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) self.T_rev...
def ptb_raw_data(data_path=None): train_path = os.path.join(data_path, 'ptb.train.txt') valid_path = os.path.join(data_path, 'ptb.valid.txt') test_path = os.path.join(data_path, 'ptb.test.txt') (word_to_id, _) = _build_vocab(train_path) train_data = _file_to_word_ids(train_path, word_to_id) vali...
class MockCapsNumLockIndicator(): CalledProcessError = None info: List[List[str]] = [] is_error = False index = 0 def reset(cls): cls.info = [['Keyboard Control:', ' auto repeat: on key click percent: 0 LED mask: ', ' XKB indicators:', ' 00: Caps Lock: off 01: Num Lock: ...
def test_setup_cfg_2line_description(tmpfolder): (_, opts) = actions.get_default_options({}, {'project_path': tmpfolder}) opts['description'] = '2 line\ndescription' text = templates.setup_cfg(opts) setup_cfg = ConfigParser() setup_cfg.read_string(text) assert (setup_cfg['metadata']['description...
def patch(cls): if hasattr(cls, '__orig__init__'): return cls.__orig__init__ = cls.__init__ def patched_init(self, form_, *args, **kwargs): form = kwargs.pop('form', None) cls.__orig__init__(self, form_, *args, **kwargs) if form: self.attrs['form'] = form cls....
class MetaCUB(CUB): def __init__(self, args, partition='base', train_transform=None, test_transform=None, fix_seed=True): super(MetaCUB, self).__init__(args, partition) self.fix_seed = fix_seed self.n_ways = args.n_ways self.n_shots = args.n_shots self.n_queries = args.n_quer...
class TestPrinting(TestCase): def print_to_string(self, formula): return formula.to_smtlib(daggify=False) def test_real(self): f = Plus([Real(1), Symbol('x', REAL), Symbol('y', REAL)]) self.assertEqual(f.to_smtlib(daggify=False), '(+ 1.0 x y)') self.assertEqual(f.to_smtlib(daggif...
def iterate_minibatches_generic(input_lst=None, batchsize=None, shuffle=False): if (batchsize is None): batchsize = len(input_lst[0]) assert all(((len(x) == len(input_lst[0])) for x in input_lst)) if shuffle: indices = np.arange(len(input_lst[0])) np.random.shuffle(indices) for s...
def test_hook_auto_num_workers_arg(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None: from xdist.plugin import pytest_cmdline_main as check_options pytester.makeconftest("\n def pytest_xdist_auto_num_workers(config):\n if config.option.numprocesses == 'auto':\n ...
def parse_bool(arg): if isinstance(arg, bool): return arg if (arg is None): return False if (arg.lower() in ['1', 'true', 't', 'yes', 'y']): return True if (arg.lower() in ['0', 'false', 'f', 'no', 'n', 'none', 'null']): return False raise ValueError(f'`{arg}` cannot ...
def compare_cfg(cfg_main, cfg_secondary, field_name, strict=False): (main_val, secondary_val) = (cfg_main, cfg_secondary) for f in field_name.split('.'): main_val = main_val[f] secondary_val = secondary_val[f] if (main_val != secondary_val): if strict: raise ValueError(f"...
def test_PVSystem_sapm_celltemp_kwargs(mocker): temp_model_params = temperature.TEMPERATURE_MODEL_PARAMETERS['sapm']['open_rack_glass_glass'] system = pvsystem.PVSystem(temperature_model_parameters=temp_model_params) mocker.spy(temperature, 'sapm_cell') temps = 25 irrads = 1000 winds = 1 out...
def masked_cross_entropy(a, b, mask): b_c = torch.nn.functional.one_hot(b, num_classes=a.shape[(- 1)]) a_c = F.log_softmax(a, dim=2) loss = ((- a_c) * b_c).sum(axis=2) non_zero_elements = sum_flat(mask) loss = sum_flat((loss * mask.float())) loss = (loss / (non_zero_elements + 0.0001)) retur...
def true_and_pred(out, label_ids, label_mask): tplist = [] outputs = np.argmax(out, axis=2) for i in range(len(label_ids)): trues = [] preds = [] for (true, pred, mask) in zip(label_ids[i], outputs[i], label_mask[i]): if mask: trues.append(true) ...
def test_load_nist_vectors(): vector_data = textwrap.dedent('\n # CAVS 11.1\n # Config info for aes_values\n # AESVS GFSbox test data for CBC\n # State : Encrypt and Decrypt\n # Key Length : 128\n # Generated on Fri Apr 22 15:11:33 2011\n\n [ENCRYPT]\n\n COUNT = 0\n KEY = \n IV = \n ...
class BNBeforeConvTranspose(torch.nn.Module): def __init__(self, padding=0, stride=1, dilation=1, groups=1, output_padding=0): super(BNBeforeConvTranspose, self).__init__() self.conv1 = torch.nn.Conv2d(10, 10, 3, bias=False) self.relu1 = torch.nn.ReLU() self.bn1 = torch.nn.BatchNorm2...
def test_update_grant(graphql_client, user, conference_factory, grant_factory): graphql_client.force_login(user) conference = conference_factory(active_grants=True) grant = grant_factory(conference=conference, gender='female', user_id=user.id) response = _update_grant(graphql_client, grant, name='Marcot...
def collect_art_info(root_path, split, ratio, print_every=1000): annotation_path = osp.join(root_path, 'annotations/train_labels.json') if (not osp.exists(annotation_path)): raise Exception(f'{annotation_path} not exists, please check and try again.') annotation = mmcv.load(annotation_path) img_...
class Describe_BaseHeaderFooter(): .parametrize(('has_definition', 'expected_value'), [(False, True), (True, False)]) def it_knows_when_its_linked_to_the_previous_header_or_footer(self, has_definition: bool, expected_value: bool, _has_definition_prop_: Mock): _has_definition_prop_.return_value = has_def...
def test_dump_version_doesnt_bail_on_value_error(tmp_path: Path) -> None: write_to = 'VERSION' version = str(VERSIONS['exact'].tag) scm_version = meta(VERSIONS['exact'].tag, config=c) with pytest.raises(ValueError, match='^bad file format:'): dump_version(tmp_path, version, write_to, scm_version...
class Pizza(ABC): name: str dough: str sauce: str toppings: List[str] def getName(self) -> str: return self.name def prepare(self) -> None: print(f'Preparing {self.name}') def bake(self) -> None: print(f'Baking {self.name}') def cut(self) -> None: print(f'...
class ConfigWithFiles(Fixture): def new_config_dir(self): return temp_dir() def new_config_bootstrap_file(self): contents = ("\nreahlsystem.root_egg = '%s'\nreahlsystem.connection_uri = None\nreahlsystem.debug = False\n" % self.root_egg_name) return self.new_config_file(filename='reahl.c...
class FakeCounter(): def __init__(self, batch: FakeBatch, name: str, tags: Dict[(str, Any)]): self.batch = batch self.name = name self.tags = tags def increment(self, delta: float=1.0, sample_rate: float=1.0) -> None: self.send(delta, sample_rate) def decrement(self, delta: f...
class TerminusCopyCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view if (not view.settings().get('terminus_view')): return text = '' for s in view.sel(): if text: text += '\n' text += view.substr(s) t...
def convert_to_distributed_tensor(tensor: torch.Tensor) -> Tuple[(torch.Tensor, str)]: orig_device = ('cpu' if (not tensor.is_cuda) else 'gpu') if (torch.distributed.is_available() and (torch.distributed.get_backend() == torch.distributed.Backend.NCCL) and (not tensor.is_cuda)): tensor = tensor.cuda() ...
def gpg_command(*cmd, with_user_id=False, with_trustdb=False, quiet=True, minimum_version='2.1.15', log=None): global gpg_exe, gpg_exe if (not gpg_mode): raise Exception('Attempt to use GPG before setting mode') if (not gpg_exe): try: output = subprocess.check_output(('gpg2', '--...
def solve_metric_tsptw(distmat, timew, threads=0): n = len(distmat) M = timew[(0, 1)] def subtour(edges): unvisited = list(range(n)) cycle = range((n + 1)) while unvisited: thiscycle = [] neighbors = unvisited while neighbors: curre...
def pool_feature(data, num_proposals=100, num_sample_bins=3, pool_type='mean'): if (len(data) == 1): return np.concatenate(([data] * num_proposals)) x_range = list(range(len(data))) f = scipy.interpolate.interp1d(x_range, data, axis=0) eps = 0.0001 (start, end) = (eps, ((len(data) - 1) - eps...
def test_paint_when_debug_shapes(view): with patch('beeref.selection.commandline_args') as args_mock: with patch('beeref.items.BeePixmapItem.draw_debug_shape') as m: args_mock.debug_shapes = True args_mock.debug_boundingrects = False args_mock.debug_handles = False ...
class SecurityContextTestCase(_GSSAPIKerberosTestCase): def setUp(self): super(SecurityContextTestCase, self).setUp() gssctx.SecurityContext.__DEFER_STEP_ERRORS__ = False self.client_name = gssnames.Name(self.USER_PRINC) self.client_creds = gsscreds.Credentials(name=None, usage='init...
def test_concise_attrib_metadata() -> None: class A(): x: datetime.datetime = desert.ib(marshmallow.fields.NaiveDateTime(), metadata={'foo': 1}) timestring = '2019-10-21T10:25:00' dt = datetime.datetime(year=2019, month=10, day=21, hour=10, minute=25, second=0) schema = desert.schema(A) asse...
class ElementInfo(object): def __repr__(self): return '<{0}, {1}>'.format(self.__str__(), self.handle) def __str__(self): module = self.__class__.__module__ module = module[(module.rfind('.') + 1):] type_name = ((module + '.') + self.__class__.__name__) return "{0} - '{1}...
_REGISTRY.register() def resnet18_ms_l12(pretrained=True, **kwargs): from dassl.modeling.ops import MixStyle model = ResNet(block=BasicBlock, layers=[2, 2, 2, 2], ms_class=MixStyle, ms_layers=['layer1', 'layer2']) if pretrained: init_pretrained_weights(model, model_urls['resnet18']) return model