code
stringlengths
281
23.7M
def git_upstream(destination): git_url = '/'.join((cli.args.baseurl, default_fork)) git_cmd = ['git', '-C', destination, 'remote', 'add', 'upstream', git_url] with subprocess.Popen(git_cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True, encoding='utf-8') as p: ...
class RandomizedSearchTest(unittest.TestCase): def test_clone_estimator(self): params = dict(lr=tune.loguniform(0.1, 1)) random_search = TuneSearchCV(SGDClassifier(), param_distributions=params, return_train_score=True, n_jobs=2) clone(random_search) random_search = TuneSearchCV(SGDC...
class TestInstagramPortraitPost(unittest.TestCase): ('nider.models.Image._set_fullpath') def setUp(self, *mocks): self.post = InstagramPortraitPost(content=mock.Mock(), fullpath=mock.Mock()) def test_size(self): self.assertEqual(self.post.width, 1080) self.assertEqual(self.post.heigh...
class UT_HAR_GRU(nn.Module): def __init__(self, hidden_dim=64): super(UT_HAR_GRU, self).__init__() self.gru = nn.GRU(90, hidden_dim, num_layers=1) self.fc = nn.Linear(hidden_dim, 7) def forward(self, x): x = x.view((- 1), 250, 90) x = x.permute(1, 0, 2) (_, ht) = ...
class RequestScope(Scope): def configure(self): self.context = None def __call__(self, request): assert (self.context is None) self.context = {} binder = self.injector.get(Binder) binder.bind(Request, to=request, scope=RequestScope) (yield) self.context = ...
def test_remove(brew_info): brew_info.brew_input.extend(['aaa', 'bbb', 'ccc']) brew_info.remove('brew_input', 'bbb') assert (brew_info.brew_input == ['aaa', 'ccc']) brew_info.brew_input_opt.update({'aaa': 'aaa', 'bbb': 'bbb', 'ccc': 'ccc'}) brew_info.remove('brew_input_opt', 'bbb') assert (brew_...
class F13_TestCase(F12_TestCase): def __init__(self, *kargs, **kwargs): F12_TestCase.__init__(self, *kargs, **kwargs) self.validLevels.append('RAID4') def runTest(self): F12_TestCase.runTest(self) self.assert_parse(('raid / --device=md0 --level=4%s raid.01 raid.02' % (self.bytesP...
def get_modname_from_path(modpath: pathlib.Path, package_path: pathlib.Path, add_package_name: bool=True) -> str: package_name: str = package_path.stem rel_path_parts = modpath.relative_to(package_path).parts modname = '' if (len(rel_path_parts) > 0): for part in rel_path_parts[:(- 1)]: ...
.parametrize('log_prob_key', [None, 'sample_log_prob', ('nested', 'sample_log_prob'), ('data', 'sample_log_prob')]) def test_nested_keys_probabilistic_delta(log_prob_key): policy_module = TensorDictModule(nn.Linear(1, 1), in_keys=[('data', 'states')], out_keys=[('data', 'param')]) td = TensorDict({'data': Tenso...
class GrabPointer(rq.ReplyRequest): _request = rq.Struct(rq.Opcode(26), rq.Bool('owner_events'), rq.RequestLength(), rq.Window('grab_window'), rq.Card16('event_mask'), rq.Set('pointer_mode', 1, (X.GrabModeSync, X.GrabModeAsync)), rq.Set('keyboard_mode', 1, (X.GrabModeSync, X.GrabModeAsync)), rq.Window('confine_to',...
class AssignmentStmt(Statement): __slots__ = ('lvalues', 'rvalue', 'type', 'unanalyzed_type', 'new_syntax', 'is_alias_def', 'is_final_def', 'invalid_recursive_alias') __match_args__ = ('lvalues', 'rvalues', 'type') lvalues: list[Lvalue] rvalue: Expression type: (mypy.types.Type | None) unanalyze...
def test_dealloc_mix1_2_order(): allocs = ([1, 2] * 5) capacity = sum(allocs) allocator = RegionAllocator(capacity) regions = [] for alloc in allocs: regions.append(allocator.alloc(alloc)) for region in regions: allocator.dealloc(region) assert (allocator.get_free_size() == a...
_exporter class SceneToPixmapExporter(ExporterBase): TYPE = ExporterRegistry.DEFAULT_TYPE def get_user_input(self, parent): dialog = widgets.SceneToPixmapExporterDialog(parent=parent, default_size=self.default_size) if dialog.exec(): size = dialog.value() logger.debug(f'G...
class FakePathlibPathModule(): fake_pathlib = None def __init__(self, filesystem=None): if (self.fake_pathlib is None): self.__class__.fake_pathlib = FakePathlibModule(filesystem) def __call__(self, *args, **kwargs): return self.fake_pathlib.Path(*args, **kwargs) def __getatt...
def main(): parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--seed', type=int, default=1, help='random seed') args = parser.parse_args() pp.connect() _utils.init_simulation(camera_distance=1) unique_ids = _utils.create_pile(class_ids=...
def eval_model(model, filepaths, entropy_estimation=False, half=False, savedir=''): device = next(model.parameters()).device metrics = defaultdict(float) for (idx, f) in enumerate(sorted(filepaths)): x = read_image(f).to(device) if (not entropy_estimation): print('evaluating inde...
def apply_rc(mediator: Mediator, request: BaseNameLayoutRequest, request_checker: RequestChecker, field: BaseField) -> bool: owner_type = request.loc_map[TypeHintLoc].type filter_request = NameMappingFilterRequest(loc_map=field_to_loc_map(owner_type, field)) try: request_checker.check_request(ExtraS...
def add_data_args(parser): parser.add_argument('--dataset', type=str, choices=DATASET_CHOICES, help='dataset format') parser.add_argument('--data-dir', type=str, help='data directory') parser.add_argument('--split-sizes', type=float, nargs=3, default=[0.8, 0.1, 0.1], help='train/val/test proportions for dat...
def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, return_dataset=False, threads=1): features = [] threads = min(threads, cpu_count()) with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p: ...
class MaxOrderSize(TradingControl): def __init__(self, on_error, asset=None, max_shares=None, max_notional=None): super(MaxOrderSize, self).__init__(on_error, asset=asset, max_shares=max_shares, max_notional=max_notional) self.asset = asset self.max_shares = max_shares self.max_notio...
class MaximumEntropyInverseRL(): def __init__(self, agent): self.agent = agent def train(self, sess): start = time.time() max_epoch = AbstractLearning.max_epochs dataset_size = AbstractLearning.dataset_size tuning_size = AbstractLearning.validation_datasize train_...
class Document(ElementProxy): def __init__(self, element: CT_Document, part: DocumentPart): super(Document, self).__init__(element) self._element = element self._part = part self.__body = None def add_heading(self, text: str='', level: int=1): if (not (0 <= level <= 9)): ...
class CifarNet(nn.Module): def __init__(self): super(CifarNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=3) self.conv2 = nn.Conv2d(64, 64, kernel_size=3) self.conv3 = nn.Conv2d(64, 128, kernel_size=3) self.conv4 = nn.Conv2d(128, 128, kernel_size=3) se...
def test_trafficstopaction(): tsa = OSC.TrafficStopAction('hej') tsa2 = OSC.TrafficStopAction('hej') tsa3 = OSC.TrafficStopAction('hey') prettyprint(tsa) assert (tsa == tsa2) assert (tsa != tsa3) tsa4 = OSC.TrafficStopAction.parse(tsa.get_element()) prettyprint(tsa4.get_element()) as...
class TestTopPSamplingSearch(TestSequenceGeneratorBase): def setUp(self): d = test_utils.dummy_dictionary(vocab_size=2) self.assertEqual(d.pad(), 1) self.assertEqual(d.eos(), 2) self.assertEqual(d.unk(), 3) self.eos = d.eos() self.w1 = 4 self.w2 = 5 se...
class DocumentationLink(ModelReprMixin, models.Model): package = models.CharField(primary_key=True, max_length=50, validators=(package_name_validator,), help_text='The Python package name that this documentation link belongs to.') base_url = models.URLField(help_text='The base URL from which documentation will ...
class TestTupleNames(unittest.TestCase): def setUp(self) -> None: self.inst_a = RInstance(ClassIR('A', '__main__')) self.inst_b = RInstance(ClassIR('B', '__main__')) def test_names(self) -> None: assert (RTuple([int_rprimitive, int_rprimitive]).unique_id == 'T2II') assert (RTuple...
class FC3_RaidData(BaseData): removedKeywords = BaseData.removedKeywords removedAttrs = BaseData.removedAttrs def __init__(self, *args, **kwargs): BaseData.__init__(self, *args, **kwargs) self.device = kwargs.get('device', None) self.fstype = kwargs.get('fstype', '') self.lev...
class GaussNewtonCG(ConjugateGradientBase): def __init__(self, problem: L2Problem, variable: TensorList, cg_eps=0.0, fletcher_reeves=True, standard_alpha=True, direction_forget_factor=0, debug=False, analyze=False, plotting=False, visdom=None): super().__init__(fletcher_reeves, standard_alpha, direction_for...
def is_same_side(p1: ColorXY, p2: ColorXY, a: ColorXY, b: ColorXY) -> bool: vector_ab = [(y - x) for (x, y) in zip(a, b)] vector_ap1 = [(y - x) for (x, y) in zip(a, p1)] vector_ap2 = [(y - x) for (x, y) in zip(a, p2)] cross_vab_ap1 = ((vector_ab[0] * vector_ap1[1]) - (vector_ab[1] * vector_ap1[0])) ...
def plot_segments(onsets, offsets, labels, palette, y=0.5, seg_height=0.1, ax=None, patch_kwargs=None): if (patch_kwargs is None): patch_kwargs = {} if (ax is None): (fig, ax) = plt.subplots segments = [Rectangle(xy=(on, y), height=seg_height, width=(off - on)) for (on, off) in zip(onsets, o...
def platipy_cli(): if ((len(sys.argv) == 1) or (not (sys.argv[1] in tools))): print('') print(' PlatiPy CLI (Command Line Interface)') print(' ') print('') print(' Usage: platipy [tool]') print('') print(' Supply the name of the desired tool:') for...
_fixtures(WebFixture, AccessDomainFixture, AccessUIFixture) def test_edit_and_add_own(web_fixture, access_domain_fixture, access_ui_fixture): browser = access_ui_fixture.browser fixture = access_domain_fixture account = fixture.account address_book = fixture.address_book web_fixture.log_in(browser=b...
def format_to_lines_new(args): json_dir_init = os.path.abspath(args.raw_path) dataset_split = ['test', 'valid', 'train'] lang_split = ['eng', 'chn'] (train_files, valid_files, test_files) = ({}, {}, {}) for data_sp in dataset_split: for lan_sp in lang_split: if (data_sp == 'train...
def test_model_gradient_descent_limited_evaluations(): x0 = np.random.randn(10) sample_radius = 0.1 rate = 0.1 result = model_gradient_descent(sum_of_squares, x0, sample_radius=sample_radius, n_sample_points=10, rate=rate, tol=1e-08, known_values=None, max_evaluations=15) assert isinstance(result.x,...
class SeviriL2AMVBufrData(): (sys.platform.startswith('win'), "'eccodes' not supported on Windows") def __init__(self, filename): from satpy.readers.seviri_l2_bufr import SeviriL2BufrFileHandler with mock.patch('satpy.readers.seviri_l2_bufr.np.fromfile'): self.fh = SeviriL2BufrFileHa...
class DirectoryFormat(FormatBase, metaclass=_DirectoryMeta): def validate(self, level='max'): _check_validation_level(level) if (not self.path.is_dir()): raise ValidationError(('%s is not a directory.' % self.path)) collected_paths = {p: None for p in self.path.glob('**/*') if ((...
def train(epoch, model, model_ema, vnet, optimizer_model, optimizer_vnet, train_loader, train_meta_loader, meta_lr): print(('\nEpoch: %d' % epoch)) train_loss = 0 meta_loss = 0 train_meta_loader_iter = iter(train_meta_loader) for (batch_idx, (inputs, targets, _, index)) in enumerate(train_loader): ...
def get_worker_config(dask_worker): from .proxify_host_file import ProxifyHostFile plugin_vals = dask_worker.plugins.values() ret = {} for p in plugin_vals: config = {v: getattr(p, v) for v in dir(p) if (not (v.startswith('_') or (v in {'setup', 'cores'})))} try: pickle.dumps...
class FConvEncoder(FairseqEncoder): def __init__(self, dictionary, embed_dim=512, max_positions=1024, convolutions=(((512, 3),) * 20), dropout=0.1, attention=False, attention_nheads=1): super().__init__(dictionary) self.dropout = dropout self.num_attention_layers = None num_embedding...
def draw_experiment(env_axes, experiment_statistics, algo): for (ax, metric_name, label) in zip(env_axes, ['objectives', 'mean_sum_costs', 'average_costs'], ['Average reward return', 'Average cost return', 'Cost regret']): draw(ax, experiment_statistics['timesteps'], experiment_statistics[(metric_name + '_m...
class SNResNetDiscriminator(chainer.Chain): def __init__(self, ch=64, activation=F.relu): super(SNResNetDiscriminator, self).__init__() self.activation = activation initializer = chainer.initializers.GlorotUniform() with self.init_scope(): self.block1 = OptimizedBlock(3, ...
def test_move_to_device_trivial() -> None: in_dict = {'k1': torch.zeros(10), 'k2': torch.ones(4)} for k in in_dict: assert isinstance(in_dict[k], torch.Tensor) assert (in_dict[k].device == torch.device('cpu')) out_dict = move_to_device(in_dict, torch.device('cpu')) assert np.alltrue((lis...
class Effect11392(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Hybrid Turret')), 'maxRange', ship.getModifiedItemAttr('shipBonusNavyDestroyerCaldari2'), skill='Caldari Destroyer', **kwar...
class TestFork(TestCase): def test_fork(self): f1 = jsons.fork() f2 = jsons.fork() f3 = jsons.fork(fork_inst=f1) jsons.set_serializer((lambda *_, **__: 'f1'), str, fork_inst=f1) jsons.set_serializer((lambda *_, **__: 'f2'), str, fork_inst=f2) jsons.set_serializer((lam...
def test_patched_errwindow(capfd, mocker, monkeypatch): monkeypatch.setattr(checkpyver.sys, 'hexversion', ) monkeypatch.setattr(checkpyver.sys, 'exit', (lambda status: None)) try: import tkinter except ImportError: tk_mock = mocker.patch('qutebrowser.misc.checkpyver.Tk', spec=['withdraw'...
def test_get_secret(): secret1 = factories.make_secret() secret2 = factories.make_secret() secrethash3 = factories.make_secret_hash() secrethash4 = factories.make_secret_hash() lock_state = HashTimeLockState(amount=10, expiration=10, secrethash=factories.UNIT_SECRETHASH) end_state = factories.cr...
class History(): def __init__(self, project, maxundos=None): self.project = project self._undo_list = [] self._redo_list = [] self._maxundos = maxundos self._load_history() self.project.data_files.add_write_hook(self.write) self.current_change = None def _...
def test_perform_indexing_needs_reindexing(initialized_db, set_secscan_config): secscan = V4SecurityScanner(application, instance_keys, storage) secscan._secscan_api = mock.Mock() secscan._secscan_api.state.return_value = {'state': 'xyz'} secscan._secscan_api.index.return_value = ({'err': None, 'state':...
class TestEvMenu(TestCase): menutree = {} startnode = 'start' cmdset_mergetype = 'Replace' cmdset_priority = 1 auto_quit = True auto_look = True auto_help = True cmd_on_exit = 'look' persistent = False startnode_input = '' kwargs = {} expect_all_nodes = False expected...
def main(): parser = build_parser() args = parser.parse_args() (_, input_ext) = os.path.splitext(args.input) if (input_ext == '.h5ad'): x = ad.read_h5ad(args.input) elif (input_ext == '.h5'): x = sc.read_10x_h5(args.input) else: raise ValueError(f'Unrecognized file extens...
def main(): args = parse_args() max_length = 5 num_beams = 4 logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger.setLevel(logging.INFO) transformers.utils.logging.set_verbosity_error() device = torch.devic...
def load_xml(p): tree = ET.parse(p) root = tree.getroot() (title, byline, abs, paras) = ([], [], [], []) title_node = list(root.iter('hedline')) if (len(title_node) > 0): try: title = [p.text.lower().split() for p in list(title_node[0].iter('hl1'))][0] except: ...
def get_thumbnail_from_file(fileobj, boundary) -> (GdkPixbuf.Pixbuf | None): assert fileobj try: path = fileobj.name assert isinstance(path, fsnative), path return get_thumbnail(path, boundary) except GLib.GError: try: loader = GdkPixbuf.PixbufLoader() ...
class Subtensor(COp): check_input = False view_map = {0: [0]} _f16_ok = True __props__ = ('idx_list',) def __init__(self, idx_list): self.idx_list = tuple(map(index_vars_to_types, idx_list)) def make_node(self, x, *inputs): x = as_tensor_variable(x) inputs = tuple((as_non...
def _group_ptr_queries_with_known_answers(now_millis: float_, multicast: bool_, question_with_known_answers: _QuestionWithKnownAnswers) -> List[DNSOutgoing]: query_by_size: Dict[(DNSQuestion, int)] = {question: (question.max_size + sum((answer.max_size_compressed for answer in known_answers))) for (question, known_...
class TestForbiddenIOFunctionNoAllowedChecker(pylint.testutils.CheckerTestCase): CHECKER_CLASS = IOFunctionChecker CONFIG = {} def setup(self): self.setup_method() def test_message_function_no_allowed(self): src = '\n def my_function(string: str):\n string = "hello"\n ...
def parse_source_file(mod: StubSource, mypy_options: MypyOptions) -> None: assert (mod.path is not None), 'Not found module was not skipped' with open(mod.path, 'rb') as f: data = f.read() source = mypy.util.decode_python_encoding(data) errors = Errors(mypy_options) mod.ast = mypy.parse.pars...
def test_build_wheel_extended() -> None: with temporary_directory() as tmp_dir, cwd(os.path.join(fixtures, 'extended')): filename = api.build_wheel(tmp_dir) whl = (Path(tmp_dir) / filename) assert whl.exists() validate_wheel_contents(name='extended', version='0.1', path=whl.as_posix(...
def run(train_batch_size, epochs, lr, weight_decay, config, exp_id, log_dir, disable_gpu=False): if (config['test_ratio'] is not None): (train_loader, val_loader, test_loader) = get_data_loaders(config, train_batch_size, exp_id) else: (train_loader, val_loader) = get_data_loaders(config, train_b...
class OpenFF(Parametrisation): type: Literal['OpenFF'] = 'OpenFF' force_field: str = 'openff_unconstrained-2.0.0.offxml' def start_message(self, **kwargs) -> str: return f'Parametrising molecule and fragments with {self.force_field}.' def is_available(cls) -> bool: off = which_import('op...
def test_context_formatting(hatch, helpers, temp_dir, config_file): config_file.model.template.plugins['default']['tests'] = False config_file.save() project_name = 'My.App' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), result.output project_...
class BoolAsk(Bool): def __init__(self, *, none_ok: bool=False, completions: _Completions=None) -> None: super().__init__(none_ok=none_ok, completions=completions) self.valid_values = ValidValues('true', 'false', 'ask') def to_py(self, value: Union[(bool, str)]) -> Union[(bool, str, None)]: ...
class TestTextInput(unittest.TestCase): def test_init(self): widget = gui.TextInput(single_line=True, hint='test text input') self.assertIn('test text input', widget.repr()) assertValidHTML(widget.repr()) widget = gui.TextInput(single_line=False, hint='test text input') self....
class TrainWithLogger(): def reset_log(self): self.log_components = OrderedDict() def log_append(self, log_key, length, loss_components): for (key, value) in loss_components.items(): key_name = f'{log_key}/{key}' (count, sum) = self.log_components.get(key_name, (0, 0.0)) ...
class HeightCompression(nn.Module): def __init__(self, model_cfg, **kwargs): super().__init__() self.model_cfg = model_cfg self.num_bev_features = self.model_cfg.NUM_BEV_FEATURES def forward(self, batch_dict): encoded_spconv_tensor = batch_dict['encoded_spconv_tensor'] sp...
class _ExtractMethodParts(ast.RopeNodeVisitor): def __init__(self, info): self.info = info self.info_collector = self._create_info_collector() self.info.kind = self._get_kind_by_scope() self._check_constraints() def _get_kind_by_scope(self): if self._extacting_from_static...
def create_ctth_alti_pal_variable_with_fill_value_color(nc_file, var_name): var = nc_file.create_variable(var_name, ('pal_colors_250', 'pal_rgb'), np.uint8) var[:] = PAL_ARRAY var.attrs['palette_meanings'] = CTTH_PALETTE_MEANINGS var.attrs['fill_value_color'] = [0, 0, 0] var.attrs['scale_factor'] = ...
def test_Anything(): assert_eq(Anything, None) assert_eq(Anything, []) assert_eq(None, Anything) assert_eq([], Anything) assert (not (Anything != None)) assert (not (Anything != [])) assert (not (None != Anything)) assert (not ([] != Anything)) assert_eq('<Anything>', repr(Anything))
class AllDatasetBatchesIterator(MultiIterator): def __init__(self, individual_dataloaders: Mapping[(str, Union[(DataLoader, Iterable)])], iteration_strategy: AllDatasetBatches) -> None: super().__init__(individual_dataloaders, iteration_strategy) self.iteration_strategy = iteration_strategy ...
class Gmetric(): type = ('', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp') protocol = ('udp', 'multicast') def __init__(self, host, port, protocol): if (protocol not in self.protocol): raise ValueError(('Protocol must be one of: ' + str(self.protocol))) ...
class FormTagFieldTest(TagTestManager, TestCase): def test_required(self): self.assertTrue(tag_forms.TagField(required=True).required) self.assertTrue(tag_forms.TagField(required=True).widget.is_required) self.assertFalse(tag_forms.TagField(required=False).required) self.assertFalse(...
class Migration(migrations.Migration): dependencies = [('adserver_auth', '0003_allow-blank')] operations = [migrations.CreateModel(name='HistoricalUser', fields=[('id', models.IntegerField(auto_created=True, blank=True, db_index=True, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_na...
def test_pipeline_runner_main_all(pipeline_cache_reset): expected_notify_output = ['sg1', 'sg1.2', 'success_handler'] with patch_logger('pypyr.steps.echo', logging.NOTIFY) as mock_log: pipelinerunner.run(pipeline_name='pipelines/api/main-all', args_in=['A', 'B', 'C'], groups=['sg1'], success_group='sh',...
def run(scenarios_list, config, wait_duration, kubecli: KrknKubernetes, telemetry: KrknTelemetryKubernetes) -> (list[str], list[ScenarioTelemetry]): failed_post_scenarios = '' logging.info('Runing the Network Chaos tests') failed_post_scenarios = '' scenario_telemetries: list[ScenarioTelemetry] = [] ...
class Effect7013(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'kineticDamage', src.getModifiedItemAttr('eliteBonusGunship1'), skill='Assault Frigates', **kwar...
class FGM(): def __init__(self, model): self.model = model self.backup = {} def attack(self, epsilon=1.0, emb_name='word_embeddings'): for (name, param) in self.model.named_parameters(): if (param.requires_grad and (emb_name in name)): self.backup[name] = para...
class S3Path(_S3Path): keep_file = '.s3keep' def mkdir(self, mode: int=511, parents: bool=False, exist_ok: bool=False) -> None: self.joinpath(self.keep_file).touch() def glob(self, pattern: str) -> Iterator[S3Path]: bucket_name = self.bucket (resource, _) = self._accessor.configurati...
class Solution(): def twoSum(self, nums, target): for i in nums: a = (target - i) m = nums.index(i) if (a in nums): try: n = nums.index(a, (m + 1), len(nums)) return (m, n) except: ...
def test_annotation_long(testdir): testdir.makepyfile("\n import pytest\n pytest_plugins = 'pytest_github_actions_annotate_failures'\n\n def f(x):\n return x\n\n def test_fail():\n x = 1\n x += 1\n x += 1\n x += 1\n x += 1...
class TestRegisteringSubclass(BaseTestCase): def test_handling_duplicate(self): with pytest.raises(ValueError) as e: rname.register_subclass(rname.GPIBInstr) assert ('Class already registered for' in e.exconly()) def test_handling_duplicate_default(self) -> None: with pytest....
def _standardize_weights(y, sample_weight=None, class_weight=None, sample_weight_mode=None): if (sample_weight_mode is not None): if (sample_weight_mode != 'temporal'): raise ValueError(('"sample_weight_mode should be None or "temporal". Found: ' + str(sample_weight_mode))) if (len(y.sha...
def _expval_with_stddev(coeffs: np.ndarray, probs: np.ndarray, shots: int) -> Tuple[(float, float)]: expval = coeffs.dot(probs) sq_expval = (coeffs ** 2).dot(probs) variance = ((sq_expval - (expval ** 2)) / shots) if ((variance < 0) and (not np.isclose(variance, 0))): logger.warning('Encountered...
def test_infer_generated_setter() -> None: code = '\n class A:\n \n def test(self):\n pass\n A.test.setter\n ' node = extract_node(code) inferred = next(node.infer()) assert isinstance(inferred, nodes.FunctionDef) assert isinstance(inferred.args, nodes.Arguments) ...
class AccreditationFitter(): def __init__(self): self._counts_all = {} self._counts_accepted = {} self._Ntraps = None self._Nrejects = [] self._Nruns = 0 self._Nacc = 0 self._g = 1.0 self.flag = None self.outputs = None self.num_runs = ...
def test_cc_head(): head = CCHead(in_channels=32, channels=16, num_classes=19) assert (len(head.convs) == 2) assert hasattr(head, 'cca') if (not torch.cuda.is_available()): pytest.skip('CCHead requires CUDA') inputs = [torch.randn(1, 32, 45, 45)] (head, inputs) = to_cuda(head, inputs) ...
class Imagefolder_modified(DatasetFolder): def __init__(self, root, transform=None, target_transform=None, loader=default_loader, is_valid_file=None, cached=False, number=None): super(Imagefolder_modified, self).__init__(root, loader, (IMG_EXTENSIONS if (is_valid_file is None) else None), transform=transfor...
def _on_raw(func_name): def wrapped(self, *args, **kwargs): args = list(args) try: string = args.pop(0) if hasattr(string, '_raw_string'): args.insert(0, string.raw()) else: args.insert(0, string) except IndexError: ...
class TestNormalDistribution(QiskitTestCase): def assertDistributionIsCorrect(self, circuit, num_qubits, mu, sigma, bounds, upto_diag): if (not isinstance(num_qubits, (list, np.ndarray))): num_qubits = [num_qubits] if (not isinstance(mu, (list, np.ndarray))): mu = [mu] ...
class PizzaTestDrive(): def main(*args) -> None: nyStore: PizzaStore = NYPizzaStore() chicagoStore: PizzaStore = ChicagoPizzaStore() pizza: Pizza = nyStore.orderPizza('cheese') print(f'''Ethan ordered a {pizza.getName()} ''') pizza = chicagoStore.orderPizza('cheese') ...
def test_logins_fails_with_invalid_email(graphql_client): UserFactory(email='', password='test') response = graphql_client.query('mutation($input: LoginInput!) {\n login(input: $input) {\n __typename\n ... on LoginErrors {\n errors {\n ...
class JavaLexer(RegexLexer): name = 'Java' url = ' aliases = ['java'] filenames = ['*.java'] mimetypes = ['text/x-java'] version_added = '' flags = (re.MULTILINE | re.DOTALL) tokens = {'root': [('(^\\s*)((?:(?:public|private|protected|static|strictfp)(?:\\s+))*)(record)\\b', bygroups(Whi...
def find_paths(path_patterns: Sequence[str], exclude_name_patterns: Sequence[str]=[], cwd: Optional[Union[(Path, str)]]=None) -> Generator[(Path, None, None)]: if (cwd is None): cwd = Path.cwd() elif isinstance(cwd, str): cwd = Path(cwd) for pattern in path_patterns: for path in cwd....
class GANLoss(nn.Module): def __init__(self, use_lsgan=True, gan_mode='lsgan', target_real_label=1.0, target_fake_label=0.0): super(GANLoss, self).__init__() self.register_buffer('real_label', torch.tensor(target_real_label)) self.register_buffer('fake_label', torch.tensor(target_fake_label)...
class FunctionTest(unittest.TestCase): def test_asized(self): self.assertEqual(list(asizeof.asized(detail=2)), []) self.assertRaises(KeyError, asizeof.asized, **{'all': True}) sized = asizeof.asized(Foo(42), detail=2) self.assertEqual(sized.name, 'Foo') refs = [ref for ref in...
class AttentionBlock(nn.Module): def __init__(self, channels, num_heads=1, use_checkpoint=False): super().__init__() self.channels = channels self.num_heads = num_heads self.use_checkpoint = use_checkpoint self.norm = normalization(channels) self.qkv = conv_nd(1, chan...
def should_stop_early(cfg: DictConfig, valid_loss: float) -> bool: if (valid_loss is None): return False if (cfg.checkpoint.patience <= 0): return False def is_better(a, b): return ((a > b) if cfg.checkpoint.maximize_best_checkpoint_metric else (a < b)) prev_best = getattr(should...
def module_name_from_dir(dirname, err=True, files=None): if (files is None): try: files = os.listdir(dirname) except OSError as e: if ((e.errno == 2) and (not err)): return None names = [file for file in files if (file.endswith('.so') or file.endswith('.py...
def get_gml_graph(location): try: g = nx_pydot.read_dot(location).to_undirected() temp = sorted(g) mapping = {} for node in temp: node_name = node if (',' in node_name): node_name = (('"' + node_name) + '"') if (node_name[(- 1)] == ...
def run_data_migration(apps, schema_editor): QuestionSet = apps.get_model('questions', 'QuestionSet') Question = apps.get_model('questions', 'Question') VerboseName = apps.get_model('domain', 'VerboseName') Range = apps.get_model('domain', 'Range') for questionset in QuestionSet.objects.exclude(attr...