code
stringlengths
281
23.7M
def main(): parser = argparse.ArgumentParser() parser.add_argument('--model_type', default=None, type=str, required=True, help=('Model type selected in the list: ' + ', '.join(MODEL_CLASSES.keys()))) parser.add_argument('--model_name_or_path', default=None, type=str, required=True, help='Path to pretrained ...
class ConvKXBNRELU(nn.Module): def __init__(self, in_c, out_c, kernel_size, stride, act='silu'): super(ConvKXBNRELU, self).__init__() self.conv = ConvKXBN(in_c, out_c, kernel_size, stride) if (act is None): self.activation_function = torch.relu else: self.acti...
class _SQLLineageConfigLoader(): config = {'DIRECTORY': (str, os.path.join(os.path.dirname(__file__), 'data')), 'TSQL_NO_SEMICOLON': (bool, False)} def __getattr__(self, item): if (item in self.config): (type_, default) = self.config[item] return type_(os.environ.get(('SQLLINEAGE...
def name_to_array(name: str) -> t.Tuple[(str, ...)]: tags: t.Dict[(str, t.Callable[([str], bool)])] = {'unstable': (lambda i: (i == 'master')), 'latest': (lambda i: (RELEASE_RE.fullmatch(i) is not None)), name: (lambda i: ((RELEASE_RE.fullmatch(i) is not None) or (PRE_RELEASE_RE.fullmatch(i) is not None)))} ret...
def load_pickle(pickle_file): try: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f) except UnicodeDecodeError as e: with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f, encoding='latin1') except Exception as e: print('Unable to load d...
def get_valid_stats(cfg: DictConfig, trainer: Trainer, stats: Dict[(str, Any)]) -> Dict[(str, Any)]: stats['num_updates'] = trainer.get_num_updates() if hasattr(checkpoint_utils.save_checkpoint, 'best'): key = 'best_{0}'.format(cfg.checkpoint.best_checkpoint_metric) best_function = (max if cfg.c...
class ConvModule(enn.EquivariantModule): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias='auto', conv_cfg=None, norm_cfg=None, activation='relu', inplace=False, order=('conv', 'norm', 'act')): super(ConvModule, self).__init__() assert ((conv...
def get_bool_opt(options, optname, default=None): string = options.get(optname, default) if isinstance(string, bool): return string elif isinstance(string, int): return bool(string) elif (not isinstance(string, str)): raise OptionError(('Invalid type %r for option %s; use 1/0, ye...
def useCycleGetPrefixData(e, prefixE, data): copyData = list(copy.deepcopy(data)) flage = 0 for i in copyData[:]: for j in i[:]: if set('_').issubset(e): if set([prefixE, e[1]]).issubset(set(j)): for l in j[:]: if ((l == prefixE...
def get_augmentations(): sometimes = (lambda aug: iaa.Sometimes(0.5, aug)) seq = iaa.Sequential([iaa.SomeOf((0, 5), [iaa.OneOf([iaa.GaussianBlur((0, 3.0)), iaa.AverageBlur(k=(2, 7)), iaa.MedianBlur(k=(3, 11))]), iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)), iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), i...
def test_get_next_page_de_should_return_3_on_page_2(tmp_path): htmlString = '\n <div class="next-previous-links">\n <div class="previous dl-rounded-borders dl-white-bg">\n <a href="/impfung-covid-19-corona/berlin?ref_visit_motive_ids%5B%5D=6769">\n <svg xmlns=" wi...
def getAWSGroups(data_path, account_name): logger.debug("[*] Getting AWS Group data for AWS Account '%s'", account_name) jqQuery = '.GroupDetailList[]' data = getAWSIamAccountAuthorizationDetailsInfo(data_path, account_name, jqQuery) logger.debug("[*] Completed getting AWS Group data for AWS Account '%s...
class ResBlock_myDFNM(nn.Module): def __init__(self, dim, norm='in', activation='relu', pad_type='zero'): super(ResBlock_myDFNM, self).__init__() model1 = [] model2 = [] model1 += [Conv2dBlock_my(dim, dim, 3, 1, 1, norm=norm, activation=activation, pad_type=pad_type)] model2 ...
def test_project_location_complex_set_first_project(hatch, config_file, helpers, temp_dir): with temp_dir.as_cwd(): result = hatch('config', 'set', 'projects.foo.location', '.') path = str(temp_dir).replace('\\', '\\\\') assert (result.exit_code == 0), result.output assert (result.output == help...
def total_loss(net, t_inst_dict, params=dict()): loss_dict_Disc = dict() loss_dict_Gene = dict() metrics = dict() replay_worst = params.get('replay_worst', 0) t_inst_real = t_inst_dict['instr_real'] t_inst_synt = t_inst_dict['instr_synt'] if replay_worst: t_inst_wors = t_inst_dict['w...
def test_shell_sequence_with_ampersands_save_output(): context = Context({'one': 1, 'two': 2, 'three': 3, 'cmd': {'run': 'echo {one} && echo {two} && echo {three}', 'save': True}}) pypyr.steps.shell.run_step(context) assert (context['cmdOut'].returncode == 0) assert (context['cmdOut'].stdout == ('1 \n2 ...
class TestSysModulesSnapshot(): key = 'my-test-module' def test_remove_added(self) -> None: original = dict(sys.modules) assert (self.key not in sys.modules) snapshot = SysModulesSnapshot() sys.modules[self.key] = ModuleType('something') assert (self.key in sys.modules) ...
def test_merge_pass_nested_with_substitutions(): context = Context({'key1': 'value1', 'key2': 'value2', 'key3': {'k31': 'value31', 'k32': 'value32'}, 'key5': False, 15: 16}) add_me = {'key2': 'value4', 'key3': {'k33': 'value33'}, 'key4': '444_{key1}_444', 'key5': {'k51': PyString('key1')}, 13: 14, 15: 17} c...
class GlmMultiResp(Glm): def get_z(self, x): return safe_data_mat_coef_mat_dot(X=self.X, coef=x.reshape(self.var_shape_), fit_intercept=self.fit_intercept) def cat_intercept_coef(self, intercept, coef): if (intercept.ndim == 1): intercept = intercept.reshape(1, (- 1)) return ...
def test_env_only_calls_set(): context = Context({'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'env': {'set': {'ARB_SET_ME1': 'key2', 'ARB_SET_ME2': 'key1'}}}) with patch.multiple('pypyr.steps.env', env_get=DEFAULT, env_set=DEFAULT, env_unset=DEFAULT) as mock_env: pypyr.steps.env.run_step(conte...
def confirm_booleanbased_sqli(base, parameter, payload_detected, url='', data='', headers='', injection_type='', proxy='', is_multipart=False, timeout=30, delay=0, timesec=5, response_time=8, code=None, match_string=None, not_match_string=None, text_only=False, confirmation=False): _temp = [] Response = collect...
class TestAccount(potr.context.Account): contextclass = TestContext def __init__(self, name, post_office): self.post_office = post_office super(TestAccount, self).__init__(name, 'test_protocol', 415) def loadPrivkey(self): pass def savePrivkey(self): pass
class MultilabelAccuracy(MulticlassAccuracy): def __init__(self: TMultilabelAccuracy, *, threshold: float=0.5, criteria: str='exact_match', device: Optional[torch.device]=None) -> None: super().__init__(device=device) _multilabel_accuracy_param_check(criteria) self.threshold = threshold ...
def get_auth_header(protocol, timestamp, client, api_key, api_secret=None, **kwargs): header = [('sentry_timestamp', timestamp), ('sentry_client', client), ('sentry_version', protocol), ('sentry_key', api_key)] if api_secret: header.append(('sentry_secret', api_secret)) return ('Sentry %s' % ', '.jo...
def _bfs_for_latest_version_in_history(merge_base: (((Commit | TagObject) | Blob) | Tree), full_release_tags_and_versions: list[tuple[(Tag, Version)]]) -> (Version | None): def bfs(visited: set[Commit], q: Queue[Commit]) -> (Version | None): if q.empty(): log.debug('queue is empty, returning non...
class FakeKeyparser(QObject): keystring_updated = pyqtSignal(str) request_leave = pyqtSignal(usertypes.KeyMode, str, bool) def __init__(self): super().__init__() self.passthrough = False def handle(self, evt: QKeyEvent, *, dry_run: bool=False) -> QKeySequence.SequenceMatch: retur...
class TPreferencesWindow(TestCase): def setUp(self): config.init() init_fake_app() set_columns(['artist', 'title']) self.win = PreferencesWindow(None) def test_ctr(self): pass def tearDown(self): destroy_fake_app() self.win.destroy() config.qui...
def test_valid_manifestlist(): manifestlist = DockerSchema2ManifestList(Bytes.for_string_or_unicode(MANIFESTLIST_BYTES)) assert (len(manifestlist.manifests(retriever)) == 2) assert (manifestlist.media_type == 'application/vnd.docker.distribution.manifest.list.v2+json') assert (manifestlist.bytes.as_enco...
def load_module_from_name(dotted_name: str) -> types.ModuleType: try: return sys.modules[dotted_name] except KeyError: pass with redirect_stderr(io.StringIO()) as stderr, redirect_stdout(io.StringIO()) as stdout: module = importlib.import_module(dotted_name) stderr_value = stderr...
class LinearQubitOperatorOptions(object): def __init__(self, processes=10, pool=None): if (processes <= 0): raise ValueError('Invalid number of processors specified {} <= 0'.format(processes)) self.processes = min(processes, multiprocessing.cpu_count()) self.pool = pool def g...
def get_logger(args): logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)s: - %(message)s', datefmt='%m-%d %H:%M:%S') fh = logging.FileHandler('./logs/{}.txt'.format(args.model_id), mode='w+') fh.setLevel(logging.INFO) fh.setFormatte...
def ld2table(header, ld, html_id=None, html_class=None, widths={}): table = '<table' if html_id: table += (' id="%s"' % html_id) if html_class: table += (' class="%s"' % html_class) table += '>\n\t<thead>\n\t\t<tr>' for h in header: if (not (h in widths)): table +...
def load_properties_data(file_name='../../resources/properties_data.json'): abs_dir_path = os.path.dirname(os.path.abspath(__file__)) file_name_all = os.path.join(abs_dir_path, file_name) with open(file_name_all, 'r') as f: pd_dict = json.load(f) return {key: [Property[p] for p in props] for...
def test_set_current(): with expected_protocol(AdvantestR6246, [('di 1,0,2.1100e-04,2.1300e-04', None), ('spot 1,2.3120e-03', None), (None, 'ABCD 7.311e-4')]) as inst: inst.ch_A.current_source(0, 0.000211, 0.000213) inst.ch_A.change_source_current = 0.002312 assert (inst.read_measurement() =...
def _build_message(*args, **kwargs): string = kwargs.get('string', None) t = _escape(kwargs.get('t', '')) expected = _escape(kwargs.get('expected', '')) result = _escape(kwargs.get('result', '')) if (string is None): string = "The expected output of '{t}'\n\t\tShould be '{expected}'\n\t\tAct...
class _XXZZLattice(_RotatedLattice): stabilizer_shortnames = {'mx': _XXXX, 'mz': _ZZZZ} def reset_x(self) -> None: self.circ.reset(self.qregisters['data']) self.circ.h(self.qregisters['data']) self.circ.barrier() def reset_z(self) -> None: self.circ.reset(self.qregisters['dat...
class Evaluator(object): def eval_annotation(self, annotation, output): captions = json.load(open(annotation, 'r'))['audios'] key2refs = {} for audio_idx in range(len(captions)): audio_id = captions[audio_idx]['audio_id'] key2refs[audio_id] = [] for captio...
def make_save_dirs(args, prefix, suffix=None, with_time=False): time_str = (datetime.now().strftime('%Y-%m-%dT%H-%M-%S') if with_time else '') suffix = (suffix if (suffix is not None) else '') result_path = make_dir(os.path.join(args.result_path, prefix, suffix, time_str)) image_path = make_dir(os.path....
class Qtile(CommandObject): current_screen: Screen dgroups: DGroups _eventloop: asyncio.AbstractEventLoop def __init__(self, kore: base.Core, config: Config, no_spawn: bool=False, state: (str | None)=None, socket_path: (str | None)=None) -> None: self.core = kore self.config = config ...
class Time2BumpDistanceGetter(Time2BumpSpeedGetter): def _calculatePoint(self, x, miscParams, src, tgt, commonData): tgtMass = (miscParams['tgtMass'] / (10 ** 6)) tgtInertia = miscParams['tgtInertia'] tgtSpeed = Time2BumpSpeedGetter._calculatePoint(self, x=x, miscParams=miscParams, src=src, ...
class DistributedTrainingConfig(FairseqDataclass): distributed_world_size: int = field(default=max(1, torch.cuda.device_count()), metadata={'help': 'total number of GPUs across all nodes (default: all visible GPUs)'}) distributed_rank: Optional[int] = field(default=0, metadata={'help': 'rank of the current work...
def allocator_hparams(): return PlacerParams(hidden_size=512, forget_bias_init=1.0, grad_bound=1.0, lr=0.01, lr_dec=1.0, decay_steps=50, start_decay_step=400, optimizer_type='adam', name='hierarchical_controller', keep_prob=1.0, seed=1, model_size='small', random_prob=1.0, max_degree=100, epoches=10000, dropout=0.0...
def gather_tensors_fake(tensor): tensors_gather = [torch.ones_like(tensor) for _ in range(comm.world_size)] dist.all_gather(tensors_gather, tensor, async_op=False) tensors_gather[comm.rank] = tensor output = torch.cat(tensors_gather, dim=0) output = torch.cat([output, output.detach()], 0) return...
class BaseClientFactoriesTests(unittest.TestCase): def setUp(self): transport = mock.Mock(spec=metrics.NullTransport) self.client = metrics.BaseClient(transport, 'namespace') def test_make_timer(self): timer = self.client.timer('some_timer') self.assertIsInstance(timer, metrics.T...
class TestWaitForNavigation(BaseTestCase): async def test_wait_for_navigatoin(self): (await self.page.goto((self.url + 'empty'))) results = (await asyncio.gather(self.page.waitForNavigation(), self.page.evaluate('(url) => window.location.href = url', self.url))) response = results[0] ...
.parametrize('username,password', users) .parametrize('value_id', values) def test_file(db, client, files, username, password, value_id): client.login(username=username, password=password) value = Value.objects.get(pk=value_id) url = reverse(urlnames['file'], args=[value_id]) response = client.get(url) ...
class SchemasTest(): def test_lazyness(self): schema = schemas.LazySchema('oas-2.0.json') assert (schema._schema is None) ('' in schema) assert (schema._schema is not None) assert isinstance(schema._schema, dict) def test_oas2_schema_is_present(self): assert hasat...
class TestWalletHistory_DoubleSpend(TestCaseForTestnet): transactions = {'a3849040fba12a4389310b58a17b78025d81116a3338595bdefa1625': 'b7ebb40209c234344f57a3365669c8883a3d511fbde5155f11f64dfdffffff024c400fb50d21483fb5e088db90bf766ea79219fb377fef40420faaf5fc4a6297375c32403a9c2768e7029c8dbdefd510954b289829f8f778163b98...
.skipif((sys.platform != 'win32'), reason='no Windows registry') .usefixtures('_mock_registry') def test_pep514(): from virtualenv.discovery.windows.pep514 import discover_pythons interpreters = list(discover_pythons()) assert (interpreters == [('ContinuumAnalytics', 3, 10, 32, 'C:\\Users\\user\\Miniconda3\...
class InvalidOpcode(Opcode): mnemonic = 'INVALID' gas_cost = 0 def __init__(self, value: int) -> None: self.value = value super().__init__() def __call__(self, computation: ComputationAPI) -> None: raise InvalidInstruction(f'Invalid opcode 0x{self.value:x} {(computation.code.pro...
def pytest_unconfigure(config: Config) -> None: import faulthandler faulthandler.disable() if (fault_handler_stderr_fd_key in config.stash): os.close(config.stash[fault_handler_stderr_fd_key]) del config.stash[fault_handler_stderr_fd_key] if (fault_handler_original_stderr_fd_key in confi...
def _get_frame_recognized_actions_view_from_video(frame_time: float, video_recognized_actions: VideoSoccerRecognizedActions, label_map: LabelMap) -> Optional[FrameRecognizedActionsView]: action_times = video_recognized_actions.keys() (time_diff, best_time) = min(((abs((action_time - frame_time)), action_time) f...
def test_do_not_mistake_JSDoc_for_django_comment(lexer): text = '/**\n * {*} cool\n */\n func = function(cool) {\n };\n\n /**\n * {*} stuff\n */\n fun = function(stuff) {\n };' tokens = lex...
def count_conseq_double(mol): bonds = mol.GetBonds() previous_BType = None count_conseq_doub = 0 for b in bonds: curr_BType = b.GetBondType() if ((previous_BType == curr_BType) and (curr_BType == rdkit.Chem.rdchem.BondType.DOUBLE)): count_conseq_doub += 1 previous_BTy...
def integral_interval_probaCDF_recall(I, J, E): def f(J_cut): if (J_cut is None): return 0 else: return integral_mini_interval_Precall_CDFmethod(I, J_cut, E) def f0(J_middle): if (J_middle is None): return 0 else: return (max(J_midd...
def _generate_filler(key_type: bytes, hops_data: Sequence[OnionHopsDataSingle], shared_secrets: Sequence[bytes]) -> bytes: num_hops = len(hops_data) filler_size = 0 for hop_data in hops_data[:(- 1)]: filler_size += len(hop_data.to_bytes()) filler = bytearray(filler_size) for i in range(0, (n...
class ConvLayer(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride): super(ConvLayer, self).__init__() reflection_padding = (kernel_size // 2) self.reflection_pad = torch.nn.ReflectionPad2d(reflection_padding) self.conv2d = torch.nn.Conv2d(in_channels...
(id='vmware-node-terminate', name='Reboot VMware VM', description='Wait for the node to be terminated', outputs={'success': NodeScenarioSuccessOutput, 'error': NodeScenarioErrorOutput}) def node_terminate(cfg: NodeScenarioConfig) -> typing.Tuple[(str, typing.Union[(NodeScenarioSuccessOutput, NodeScenarioErrorOutput)])]...
class MiniImagenet(CombinationMetaDataset): def __init__(self, root, num_classes_per_task=None, meta_train=False, meta_val=False, meta_test=False, meta_split=None, transform=None, target_transform=None, dataset_transform=None, class_augmentations=None, download=False): dataset = MiniImagenetClassDataset(roo...
def model_with_compat_bn_layers(training_as_placeholder, is_fused): training = True if training_as_placeholder: training = tf.compat.v1.placeholder_with_default(True, shape=()) inputs = tf.keras.Input(shape=(32, 32, 3)) x = tf.keras.layers.Conv2D(32, (3, 3))(inputs) x = tf.compat.v1.layers.b...
def load(model, dataset_name, uid, root='models_checkpoints', optimizer=None): checkpoint_path = os.path.join(root, dataset_name, model.name) save_path = os.path.join(checkpoint_path, ('%s_%s_%s.pth.tar' % (dataset_name, model.name, uid))) checkpoint = torch.load(save_path) model.load_state_dict(checkpo...
def run_train(): parser = argparse.ArgumentParser() parser.add_argument('--model_dir', '-md', default=None, required=True, type=str) parser.add_argument('--resume_weights', '-r', default=None, type=int) os.environ['MASTER_ADDR'] = '127.0.0.1' os.environ['MASTER_PORT'] = '8888' os.environ['NCCL_I...
class OptionViewSet(ModelViewSet): permission_classes = ((HasModelPermission | HasObjectPermission),) serializer_class = OptionSerializer queryset = Option.objects.annotate(values_count=models.Count('values')).annotate(projects_count=models.Count('values__project', distinct=True)).prefetch_related('optionse...
class Product(Bloq): a_bitsize: int b_bitsize: int def signature(self): return Signature([Register('a', self.a_bitsize), Register('b', self.b_bitsize), Register('result', (2 * max(self.a_bitsize, self.b_bitsize)), side=Side.RIGHT)]) def short_name(self) -> str: return 'a*b' def t_com...
class DEVISR(IntEnum): SUSP = (1 << 0) MSOF = (1 << 1) SOF = (1 << 2) EORST = (1 << 3) WAKEUP = (1 << 4) EORSM = (1 << 5) UPRSM = (1 << 6) PEP_0 = (1 << 12) PEP_1 = (1 << 13) PEP_2 = (1 << 14) PEP_3 = (1 << 15) PEP_4 = (1 << 16) PEP_5 = (1 << 17) PEP_6 = (1 << 18)...
class Generator_Prune(nn.Module): def __init__(self, cfg_mask, n_residual_blocks=9): super(Generator_Prune, self).__init__() first_conv_out = int(sum(cfg_mask[0])) model = [nn.ReflectionPad2d(3), nn.Conv2d(3, first_conv_out, 7), nn.InstanceNorm2d(first_conv_out), nn.ReLU(inplace=True)] ...
def main(): args = parse_args() net = caffe_pb2.NetParameter() text_format.Merge(open(args.input_net_proto_file).read(), net) print(('Drawing net to %s' % args.output_image_file)) phase = None if (args.phase == 'TRAIN'): phase = caffe.TRAIN elif (args.phase == 'TEST'): phase ...
class SDFNetwork(nn.Module): def __init__(self, encoding='hashgrid', num_layers=3, skips=[], hidden_dim=64, clip_sdf=None): super().__init__() self.num_layers = num_layers self.skips = skips self.hidden_dim = hidden_dim self.clip_sdf = clip_sdf (self.encoder, self.in_...
class DataTrainingArguments(): source_lang: str = field(default=None, metadata={'help': 'Source language id for translation.'}) target_lang: str = field(default=None, metadata={'help': 'Target language id for translation.'}) dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of th...
class IDR(IntEnum): EOC0 = (1 << 0) EOC1 = (1 << 1) EOC2 = (1 << 2) EOC3 = (1 << 3) EOC4 = (1 << 4) EOC5 = (1 << 5) EOC6 = (1 << 6) EOC7 = (1 << 7) EOC8 = (1 << 8) EOC9 = (1 << 9) EOC10 = (1 << 10) EOC11 = (1 << 11) EOC12 = (1 << 12) EOC13 = (1 << 13) EOC14 = ...
.requires_user_action class EVENT_MOVE(InteractiveTestCase): def on_move(self, x, y): print(('Window moved to %dx%d.' % (x, y))) def test_move(self): w = Window(200, 200) try: w.push_handlers(self) while (not w.has_exit): w.dispatch_events() ...
class F13_TestCase(CommandTest): command = 'sshpw' def runTest(self): self.assert_parse('sshpw --username=someguy --iscrypted secrethandshake', 'sshpw --username=someguy --iscrypted secrethandshake\n') self.assertFalse((self.assert_parse('sshpw --username=A --iscrypted secrethandshake') is None)...
def test_add_mod_n_protocols(): with pytest.raises(ValueError, match='must be between'): _ = AddConstantMod(3, 10) add_one = AddConstantMod(3, 5, 1) add_two = AddConstantMod(3, 5, 2, cvs=[1, 0]) assert (add_one == AddConstantMod(3, 5, 1)) assert (add_one != add_two) assert (hash(add_one)...
def parse_args(): parser = argparse.ArgumentParser(description='Train Meta R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset:coco2017,coco,pascal_07_12', default='pascal_voc_0712', type=str) parser.add_argument('--net', dest='net', help='metarcnn', default='metarcnn', t...
class TestPostgresqlCollector(CollectorTestCase): def setUp(self, allowed_names=None): if (not allowed_names): allowed_names = [] config = get_collector_config('PostgresqlCollector', {}) self.collector = PostgresqlCollector(config, None) def test_import(self): self.as...
class DocDB(object): def __init__(self, db_path=None, full_docs=False): self.path = (db_path or config.DOC_DB) self.full_docs = full_docs self.connection = sqlite3.connect(self.path, check_same_thread=False) def __enter__(self): return self def __exit__(self, *args): ...
def test_serializer_create(db): class MockedView(): project = Project.objects.get(id=project_id) value = Value.objects.get(project_id=project_id, snapshot=None, attribute__path=attribute_path) validator = ValueConflictValidator() serializer = ValueSerializer() serializer.context['view'] = Mo...
class MultisourceLanguagePairDataset(data.LanguagePairDataset): def __getitem__(self, i): source = [src_sent.long() for src_sent in self.src[i]] res = {'id': i, 'source': source} if self.tgt: res['target'] = self.tgt[i].long() return res def collater(self, samples): ...
class Rouge(): def __init__(self): self.beta = 1.2 def calc_score(self, candidate, refs): assert (len(candidate) == 1) assert (len(refs) > 0) prec = [] rec = [] token_c = candidate[0].split(' ') for reference in refs: token_r = reference.split(...
def render_missing_space_in_doctest(msg, _node, source_lines=None): line = msg.line (yield from render_context((line - 2), line, source_lines)) (yield (line, slice(None, None), LineType.ERROR, source_lines[(line - 1)])) (yield from render_context((line + 1), (line + 3), source_lines))
.skipif((sys.platform == 'win32'), reason='symlinks to files not supported on windows') def test_symlink_file(inwd: WorkDir) -> None: ((inwd.cwd / 'adir') / 'file1link').symlink_to('../file1') inwd.add_and_commit() assert (set(find_files('adir')) == _sep({'adir/filea', 'adir/file1link'}))
(config_path='config', config_name='config') def main(opt): print(opt.pretty()) pl.seed_everything(42, workers=True) torch.set_num_threads(10) datamodule = hydra.utils.instantiate(opt.datamodule, opt.datamodule) datamodule.setup(stage='fit') np.savez('meta_info.npz', **datamodule.meta_info) ...
class abstractmethod(IncludeMixin): def __init__(self, func): if (not callable(func)): raise ABCException(f'Function is not callable: {func}') self.func = func self.args = self.getargs(func) def __eq__(self, other): if isinstance(other, abstractmethod): re...
class CecaModule(nn.Module): def __init__(self, channels=None, kernel_size=3, gamma=2, beta=1, act_layer=None, gate_layer='sigmoid'): super(CecaModule, self).__init__() if (channels is not None): t = int((abs((math.log(channels, 2) + beta)) / gamma)) kernel_size = max((t if (...
class TestUpdateLon(object): def setup_method(self): self.py_inst = None self.inst_time = pysat.instruments.pysat_testing._test_dates[''][''] return def teardown_method(self): del self.py_inst, self.inst_time return .parametrize('name', ['testing', 'testing_xarray', '...
def test_conc_str() -> None: assert (str(Conc(Mult(Charclass('a'), ONE), Mult(Charclass('b'), ONE), Mult(Charclass('c'), ONE), Mult(Charclass('d'), ONE), Mult(Charclass('e'), ONE), Mult((~ Charclass('fg')), STAR), Mult(Charclass('h'), Multiplier(Bound(5), Bound(5))), Mult(Charclass('abcdefghijklmnopqrstuvwxyz'), PL...
def temp_link_blob(repository_id, blob_digest, link_expiration_s): assert blob_digest with db_transaction(): try: storage = ImageStorage.get(content_checksum=blob_digest) except ImageStorage.DoesNotExist: return None _temp_link_blob(repository_id, storage, link_ex...
class PPLScorer(Scorer): def __init__(self): super(PPLScorer, self).__init__(float('inf'), 'ppl') def is_improving(self, stats): return (stats.ppl() < self.best_score) def is_decreasing(self, stats): return (stats.ppl() > self.best_score) def _caller(self, stats): return ...
('I can iterate over the inline shape collection') def then_can_iterate_over_inline_shape_collection(context): inline_shapes = context.inline_shapes shape_count = 0 for inline_shape in inline_shapes: shape_count += 1 assert isinstance(inline_shape, InlineShape) expected_count = 5 ass...
class EqualPointLineDistance(BaseSketch): _id = 13 _entityDef = (_p, _l, _p, _l) _workplane = True _iconName = 'Assembly_ConstraintEqualPointLineDistance.svg' _tooltip = QT_TRANSLATE_NOOP('asm3', 'Add a "{}" to constrain the distance between a point and a\nline to be the same as the distance between...
class ProjectMetadata(): def __str__(self): return 'Default project metadata provider' def __init__(self, project): self.project = project def project_name(self): return os.path.basename(self.directory) def directory(self): return self.project.directory def version(se...
_end_docstrings(PIPELINE_INIT_ARGS) class ImageClassificationPipeline(Pipeline): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) requires_backends(self, 'vision') self.check_model_type((TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if (self.framework == 'tf') else MODEL_FO...
class DNSRecord(DNSEntry): __slots__ = ('ttl', 'created') def __init__(self, name: str, type_: int, class_: int, ttl: Union[(float, int)], created: Optional[float]=None) -> None: super().__init__(name, type_, class_) self.ttl = ttl self.created = (created or current_time_millis()) de...
def draw_meter(x, y, dx, dy, style=None, fill='bgcolor'): global bgcolor if (fill == 'bgcolor'): fill = bgcolor draw_rectangle(x, y, dx, dy, None, style=style, fill=fill) radius = min((0.5 * dx), (0.5 * dy)) if style: style_str = (',' + style) else: style_str = '' pri...
def get_default_config(): config = {'logdir': 'ppo_torch', 'idx': 0, 'seed': 0, 'num_timesteps': int(.0), 'episode_length': 1000, 'discounting': 0.97, 'learning_rate': 0.0003, 'entropy_cost': 0.01, 'unroll_length': 5, 'batch_size': 1024, 'num_minibatches': 32, 'num_update_epochs': 4, 'reward_scaling': 10, 'lambda_'...
class TestProtLib(EvenniaTest): def setUp(self): super(TestProtLib, self).setUp() self.obj1.attributes.add('testattr', 'testval') self.prot = spawner.prototype_from_object(self.obj1) def test_prototype_to_str(self): prstr = protlib.prototype_to_str(self.prot) self.assertT...
def parse_kinetics_splits(level, dataset): def convert_label(s, keep_whitespaces=False): if (not keep_whitespaces): return s.replace('"', '').replace(' ', '_') return s.replace('"', '') def line_to_map(x, test=False): if test: video = f'{x[1]}_{int(float(x[2])):06...
def import_optionset(element, save=False, user=None): try: optionset = OptionSet.objects.get(uri=element.get('uri')) except OptionSet.DoesNotExist: optionset = OptionSet() set_common_fields(optionset, element) optionset.order = (element.get('order') or 0) optionset.provider_key = (el...
class TestOOVQE(QiskitChemistryTestCase): def setUp(self): super().setUp() self.driver1 = HDF5Driver(hdf5_input=self.get_resource_path('test_oovqe_h4.hdf5')) self.driver2 = HDF5Driver(hdf5_input=self.get_resource_path('test_oovqe_lih.hdf5')) self.driver3 = HDF5Driver(hdf5_input=self....
class Record(object): def __init__(self, mod, mde, dat, sum, values): self._mod = mod self._mde = mde self._dat = dat self._sum = sum self._values = values self._approx_system_time = None self._approx_gps_time = None self._gps = None def set_approx...