code
stringlengths
281
23.7M
def test_control_check_get_errors(fake, caplog): def checking(): fake.error = True return [(7, 'some error')] fake.check_get_errors = checking fake.fake_ctrl_errors assert (fake.error is True) assert (caplog.record_tuples[(- 1)] == ('pymeasure.instruments.common_base', logging.ERROR,...
def read_data(train_data_dir, test_data_dir): clients = [] groups = [] train_data = {} test_data = {} train_files = os.listdir(train_data_dir) train_files = [f for f in train_files if f.endswith('.json')] for f in train_files: file_path = os.path.join(train_data_dir, f) with ...
def test_old_style(): assert (get_attrs_shape(OldStyle) == Shape(input=InputShape(constructor=OldStyle, kwargs=None, fields=(InputField(type=Any, id='a', default=NoDefault(), is_required=True, metadata=MappingProxyType({}), original=ANY), InputField(type=int, id='b', default=NoDefault(), is_required=True, metadata=...
def compute_cost(num_spin_orbs: int, lambda_tot: float, thc_dim: int, kmesh: list[int], dE_for_qpe: float=0.0016, chi: int=10, beta: Union[(int, None)]=None) -> ResourceEstimates: thc_costs = _compute_cost(n=num_spin_orbs, lam=lambda_tot, dE=dE_for_qpe, chi=chi, beta=beta, M=thc_dim, Nkx=kmesh[0], Nky=kmesh[1], Nkz...
def test(): input_time = np.linspace(0, 4, 400) input_signal = (np.sin((((input_time * 40) * np.pi) * 2)) + np.sin((((input_time * 20) * np.pi) * 2))) filter1 = LPFilter(100, 40) filter2 = LPFilter(100, 10) y1 = [filter1.next(x) for x in input_signal] y2 = [filter2.next(x) for x in input_signal]...
def open_file(path, sep=' ', mode='train'): src = [] tgt = [] with open(path, 'r', encoding='utf8') as f: content = f.readlines() tmp_src = [] tmp_tgt = [] for (i, line) in enumerate(content): line = line.strip().split(sep) if (len(line) == 2): ...
class ProjectViewSet(ModelViewSet): permission_classes = ((HasModelPermission | HasProjectsPermission),) serializer_class = ProjectSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ('title', 'user', 'user__username', 'catalog', 'catalog__uri') def get_queryset(self): ret...
class CredentialField(CharField): def __init__(self, *args, **kwargs): CharField.__init__(self, *args, **kwargs) assert ('default' not in kwargs) assert (not self.index) def db_value(self, value): if (value is None): return None if isinstance(value, str): ...
def train_lm(args, gpu_id, rank, loader, model, optimizer, scheduler): model.train() start_time = time.time() total_loss = 0.0 (total_correct, total_denominator) = (0.0, 0.0) steps = 1 total_steps = args.total_steps loader_iter = iter(loader) while True: if (steps == (total_steps...
def get_args(): parser = argparse.ArgumentParser(description='This script augments a phones.txt\n file (a phone-level symbol table) by adding certain special symbols\n relating to grammar support. See ../add_nonterminals.sh for context.') parser.add_argument('input_phones_txt', type=str, help='File...
class GPUSchema(Schema): class Meta(): unknown = RAISE gpus = fields.Int(required=True, description='Number of gpus for training. This affects the `world size` of PyTorch DDP.', exclusiveMinimum=0) vRam = fields.Int(required=True, description='Minimum VRam required for each gpu. Set it to `-1` to us...
class GripperController(): def __init__(self, robot_name, create_node=False, upper_limit=0.035, lower_limit=0.01, des_pos_max=1, des_pos_min=0): if create_node: rospy.init_node('gripper_controller') assert (des_pos_max >= des_pos_min), 'gripper des_pos_max has to be >= des_pos_min' ...
.parametrize('package_spec_in,package_or_url_correct,valid_spec', [('pipx', 'pipx', True), ('PiPx_stylized.name', 'pipx-stylized-name', True), ('pipx==0.15.0', 'pipx==0.15.0', True), ('pipx>=0.15.0', 'pipx>=0.15.0', True), ('pipx<=0.15.0', 'pipx<=0.15.0', True), ('pipx;python_version>="3.6"', 'pipx', True), ('pipx==0.1...
def _get_version_tag(tag): version_re = re.compile('\n (?P<package>qt|pyqt|pyqtwebengine|python)\n (?P<operator>==|>=|!=|<)\n (?P<version>\\d+\\.\\d+(\\.\\d+)?)\n ', re.VERBOSE) match = version_re.fullmatch(tag) if (not match): return None package = match.group('package')...
def test_build_schema1(): manifest = DockerSchema2Manifest(Bytes.for_string_or_unicode(MANIFEST_BYTES)) assert (not manifest.has_remote_layer) retriever = ContentRetrieverForTesting({CONFIG_DIGEST: CONFIG_BYTES}) builder = DockerSchema1ManifestBuilder('somenamespace', 'somename', 'sometag') manifest...
class DBAPICursor(): def execute(self, statement, parameters): pass def executemany(self, statement, parameters): pass def description(self): raise NotImplementedError async def prepare(self, context, clause=None): raise NotImplementedError async def async_execute(sel...
class Channel(): BOOLS = {True: 1, False: 0} bwlimit = Instrument.control('BWLimit?', 'BWLimit %d', ' A boolean parameter that toggles 25 MHz internal low-pass filter.', validator=strict_discrete_set, values=BOOLS, map_values=True) coupling = Instrument.control('COUPling?', 'COUPling %s', ' A string paramet...
def test_dsl_async_cmd_run_has_list_input_save_dev_null(): cmd1 = get_cmd('echo one', 'tests\\testfiles\\cmds\\echo.bat one') cmd2 = get_cmd('echo two three', 'tests\\testfiles\\cmds\\echo.bat "two three"') context = Context({'cmds': {'run': [cmd1, cmd2], 'stdout': '/dev/null', 'stderr': '/dev/null'}}) ...
_torch _vision class ViltImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase): image_processing_class = (ViltImageProcessor if is_vision_available() else None) def setUp(self): self.image_processor_tester = ViltImageProcessingTester(self) def image_processor_dict(self): ret...
def test_order_vertex(): dummy_points_x = [20, 20, 120, 120] dummy_points_y = [20, 40, 40, 20] expect_points_x = [20, 120, 120, 20] expect_points_y = [20, 20, 40, 40] with pytest.raises(AssertionError): sort_vertex([], dummy_points_y) with pytest.raises(AssertionError): sort_vert...
def locate_cuda(): if ('CUDAHOME' in os.environ): home = os.environ['CUDAHOME'] nvcc = pjoin(home, 'bin', 'nvcc') else: default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin') nvcc = find_in_path('nvcc', ((os.environ['PATH'] + os.pathsep) + default_path)) if (nvcc is ...
def get_stale_team(stale_timespan): stale_at = (datetime.now() - stale_timespan) try: candidates = TeamSync.select(TeamSync.id).where(((TeamSync.last_updated <= stale_at) | (TeamSync.last_updated >> None))).limit(500).alias('candidates') found = TeamSync.select(candidates.c.id).from_(candidates)...
def get_cadidate_embeddings(json_list, document_embeddings): document_feats = [] for (document, document_emb) in tqdm(zip(json_list, document_embeddings), total=len(json_list)): assert (document['document_id'] == document_emb['document_id']) sentence = flat_list(document['tokens']) sente...
class TrezorClientBase(HardwareClientBase, Logger): def __init__(self, transport, handler, plugin): HardwareClientBase.__init__(self, plugin=plugin) if plugin.is_outdated_fw_ignored(): TrezorClient.is_outdated = (lambda *args, **kwargs: False) self.client = TrezorClient(transport...
class BasicBlock(nn.Module): def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, ker...
def test_upload_mixin_with_filepath(gl): class TestClass(UploadMixin, FakeObject): _upload_path = '/tests/{id}/uploads' url = ' responses.add(method=responses.POST, url=url, json={'id': 42, 'file_name': 'test.txt', 'file_content': 'testing contents'}, status=200, match=[responses.matchers.query_para...
class PresetAM2RHints(PresetTab, Ui_PresetAM2RHints): def __init__(self, editor: PresetEditor, game_description: GameDescription, window_manager: WindowManager): super().__init__(editor, game_description, window_manager) self.setupUi(self) self.hint_layout.setAlignment(QtCore.Qt.AlignmentFla...
class TestRiskParityBoxesFactory(TestCase): def setUpClass(cls): cls.start_date = str_to_date('2022-10-01') cls.end_date = str_to_date('2022-11-01') cls.frequency = Frequency.DAILY datetime_index = pd.DatetimeIndex(['2022-10-02', '2022-10-03', '2022-10-04', '2022-10-05', '2022-10-06'...
(scope='function') def simulation_evaluator() -> ClosedLoopEvaluator: metrics = [DisplacementErrorL2Metric(), DistanceToRefTrajectoryMetric(), CollisionFrontMetric(), CollisionRearMetric(), CollisionSideMetric()] validators = [RangeValidator('displacement_error_l2_validator', DisplacementErrorL2Metric, max_valu...
class TearDownConvenience(object): def __init__(self, setup_stack=None): self._own_setup_stack = (setup_stack is None) if (setup_stack is None): setup_stack = SetupStack() self._setup_stack = setup_stack def tear_down(self): assert self._own_setup_stack self._...
class CAM(Net): def __init__(self): super(CAM, self).__init__() def forward(self, x): x = self.stage1(x) x = self.stage2(x) x = self.stage3(x) x = self.stage4(x) x = F.conv2d(x, self.classifier.weight) x = F.relu(x) x = (x[0] + x[1].flip((- 1))) ...
def _get_in_vals(binst: BloqInstance, reg: Register, soq_assign: Dict[(Soquet, ClassicalValT)]) -> ClassicalValT: if (not reg.shape): return soq_assign[Soquet(binst, reg)] if (reg.bitsize <= 8): dtype = np.uint8 elif (reg.bitsize <= 16): dtype = np.uint16 elif (reg.bitsize <= 32)...
.parametrize('metric', ['euclidean', 'minkowski', 'cityblock', 'chebyshev', 'haversine']) def test_metric(metric): data = (grocs.to_crs(4326) if (metric == 'haversine') else grocs) if ((not HAS_SKLEARN) and (metric in ['chebyshev', 'haversine'])): pytest.skip('metric not supported by scipy') (head, ...
class EmbedSend(discord.ui.Button): view: EmbedBuilder def __init__(self, channel: discord.TextChannel): self.channel = channel super().__init__(label='Send to #{0}'.format(channel.name), style=discord.ButtonStyle.green) async def callback(self, interaction: discord.Interaction) -> T.Any: ...
def initialise_colour_map(book): book.colour_map = {} book.colour_indexes_used = {} if (not book.formatting_info): return for i in xrange(8): book.colour_map[i] = excel_default_palette_b8[i] dpal = default_palette[book.biff_version] ndpal = len(dpal) for i in xrange(ndpal): ...
def test_environment_pass_references(): options = Options(platform='linux', command_line_arguments=CommandLineArguments.defaults(), env={'CIBW_ENVIRONMENT_PASS_LINUX': 'STARTER MAIN_COURSE', 'STARTER': 'green eggs', 'MAIN_COURSE': 'ham', 'CIBW_ENVIRONMENT': 'MEAL="$STARTER and $MAIN_COURSE"'}) parsed_environmen...
class Effect6796(BaseEffect): type = 'passive' def handler(fit, module, context, projectionRange, **kwargs): fit.modules.filteredItemMultiply((lambda mod: mod.item.requiresSkill('Small Hybrid Turret')), 'damageMultiplier', (1 / module.getModifiedItemAttr('modeDamageBonusPostDiv')), stackingPenalties=Tru...
_module() class FooLinearConv1d(BaseModule): def __init__(self, linear=None, conv1d=None, init_cfg=None): super().__init__(init_cfg) if (linear is not None): self.linear = build_from_cfg(linear, COMPONENTS) if (conv1d is not None): self.conv1d = build_from_cfg(conv1d,...
def build_dataset_ccrop(cfg): args = cfg.copy() transform_rcrop = build_transform(args.rcrop_dict) transform_ccrop = build_transform(args.ccrop_dict) ds_dict = args.ds_dict ds_name = ds_dict.pop('type') ds_dict['transform_rcrop'] = transform_rcrop ds_dict['transform_ccrop'] = transform_ccrop...
class Hook(): stages = ('before_run', 'before_train_epoch', 'before_train_iter', 'after_train_iter', 'after_train_epoch', 'before_val_epoch', 'before_val_iter', 'after_val_iter', 'after_val_epoch', 'after_run') def before_run(self, runner): pass def after_run(self, runner): pass def befo...
def wrap_model(opt, modelG, modelD, flowNet): if (opt.n_gpus_gen == len(opt.gpu_ids)): modelG = myModel(opt, modelG) modelD = myModel(opt, modelD) flowNet = myModel(opt, flowNet) else: if (opt.batchSize == 1): gpu_split_id = (opt.n_gpus_gen + 1) modelG = n...
def apply_definition(words, args, raw_expansion, def_name): global valid_prefixes arg_dict = {} num_words_left = len(words) for i in range((len(args) - 1), (- 1), (- 1)): arg_start = (num_words_left - 1) while ((arg_start > 1) and (words[(arg_start - 1)] == ':')): arg_start -...
class MLPNet(nn.Module): def __init__(self): super(MLPNet, self).__init__() self.fc1 = nn.Linear((28 * 28), 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): x = x.view((- 1), (28 * 28)) x = F.relu(self.fc1(x)) x = self.fc2(x) return x
class TotalGraph(TimeGraph): value_params = [(_('year'), _('Distance (km)'), _('Annual Distance'), 'y'), (_('year'), _('Time (hours)'), _('Annual Time'), 'b'), (_('year'), _('Average Heart Rate (bpm)'), _('Annual Average Heart Rate'), 'r'), (_('year'), _('Average Speed (km/h)'), _('Annual Average Speed'), 'g'), (_(...
def test_wrap_long_word_max_data_lines(): column_1 = Column('Col 1', width=10, max_data_lines=2) column_2 = Column('Col 2', width=10, max_data_lines=2) column_3 = Column('Col 3', width=10, max_data_lines=2) column_4 = Column('Col 4', width=10, max_data_lines=1) columns = [column_1, column_2, column_...
.issue(86) .parametrize('today', [False, True]) def test_git_dirty_notag(today: bool, wd: WorkDir, monkeypatch: pytest.MonkeyPatch) -> None: if today: monkeypatch.delenv('SOURCE_DATE_EPOCH', raising=False) wd.commit_testfile() wd.write('test.txt', 'test2') wd('git add test.txt') version = wd...
class NitroMessageLengthTest(TestCase): def setUp(self): self.user = User.objects.create(id=50, name='bill', discriminator=5) self.context = MessageDeletionContext.objects.create(id=50, actor=self.user, creation=dt.now(UTC)) def test_create(self): message = DeletedMessage(id=46, author=s...
class KeynoteSpeaker(TimeStampedModel, OrderedModel): keynote = models.ForeignKey('conferences.Keynote', on_delete=models.CASCADE, verbose_name=_('keynote'), related_name='speakers', null=False) user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=True, blank=True, verbose_name=_('user'), relat...
class ListParameterItem(WidgetParameterItem): def __init__(self, param, depth): self.targetValue = None WidgetParameterItem.__init__(self, param, depth) def makeWidget(self): w = QtWidgets.QComboBox() w.setMaximumHeight(20) w.sigChanged = w.currentIndexChanged w.v...
class read_file(): def GeoTIFF(path_or_dataset, crs_key=None, data_crs=None, sel=None, isel=None, set_data=None, mask_and_scale=False, fill_values='mask'): (xar, rioxarray) = register_modules('xarray', 'rioxarray') if ((isel is None) and (sel is None)): isel = {'band': 0} opened ...
.parametrize('\n start_datetime, end_datetime,\n repository_id, namespace_id,\n max_query_time, scroll_responses, expected_requests, expected_logs, throws\n ', [pytest.param(parse('2018-03-08'), parse('2018-04-02'), 1, 1, timedelta(seconds=10), SCROLL_RESPONSES, SCROLL_REQUESTS, SCROLL_LOGS, False, id='Scroll 3 pag...
class AdaroundAcceptanceTests(unittest.TestCase): .cuda def test_adaround_resnet18_only_weights(self): AimetLogger.set_level_for_all_areas(logging.DEBUG) torch.cuda.empty_cache() seed_all(1000) model = models.resnet18().eval() model = model.to(torch.device('cuda')) ...
class TopicEntryList(EntryCreateMixin, IntegratedFormMixin, ListView): context_object_name = 'entries' template_name = 'dictionary/list/entry_list.html' paginator_class = SafePaginator topic = None entry = None view_mode = None modes = ('regular', 'today', 'popular', 'history', 'nice', 'nice...
def read_regression_classification(db_loc, fs, models_names, datasets, task): fields = (['dataset', 'N', 'D'] + [m[1] for m in models_names]) results = {} for f in fs: results[f] = {'table': {f: [] for f in fields}, 'vals': []} with Database(db_loc) as db: for dataset in datasets: ...
_dtype_float_test(only64=True, onlycpu=True) def test_equil_mem(dtype, device): def _test_equil(): clss = DummyModule torch.manual_seed(100) random.seed(100) nbatch = 2000 fwd_options = {'method': 'broyden1', 'f_tol': 1e-09, 'alpha': (- 0.5)} a = (torch.ones((nbatch,)...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--input_file', default=None, type=str, required=True) parser.add_argument('--vocab_file', default=None, type=str, required=True, help='The vocabulary file that the BERT model was trained on.') parser.add_argument('--output_file', defaul...
class BidirectionalLSTM(nn.Module): def __init__(self, nIn, nHidden, nOut, ngpu): super(BidirectionalLSTM, self).__init__() self.ngpu = ngpu self.rnn = nn.LSTM(nIn, nHidden, bidirectional=True) self.embedding = nn.Linear((nHidden * 2), nOut) def forward(self, input): (rec...
class WebsocketClient(): def __init__(self, symbol, expiry, api_key, acess_token, underlying): self.kws = KiteTicker(api_key, acess_token, debug=True) self.symbol = symbol self.expiry = expiry self.underlying = underlying self.instrumentClass = InstrumentMaster(api_key) ...
def passive_grab_device(self, deviceid, time, detail, grab_type, grab_mode, paired_device_mode, owner_events, event_mask, modifiers): return XIPassiveGrabDevice(display=self.display, opcode=self.display.get_extension_major(extname), deviceid=deviceid, grab_window=self, time=time, cursor=X.NONE, detail=detail, grab_...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a multiple choice task') parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).') parser.add_argument('--dataset_config_name', type=str, de...
class TestAssertLess(TestCase): def test_you(self): self.assertLess(abc, 'xxx') def test_me(self): self.assertLess(123, (xxx + y)) self.assertLess(456, (aaa and bbb)) self.assertLess(789, (ccc or ddd)) self.assertLess(123, (True if You else False)) def test_everybody(...
def train(args, model, device, train_loader, optimizer, scheduler, epoch): model.train() for (batch_idx, (input_ids, attention_mask, token_type_ids, cate)) in enumerate(train_loader): input_ids = input_ids.to(device) attention_mask = attention_mask.to(device) token_type_ids = token_type_...
class ViewProviderAsmRelation(ViewProviderAsmBase): def canDropObjects(self): return False def canDelete(self, _obj): return True def claimChildren(self): return self.ViewObject.Object.Group def getDetailPath(self, subname, path, append): vobj = self.ViewObject id...
def coco_score(refs, pred, scorer): if (scorer.method() == 'Bleu'): scores = np.array([0.0 for n in range(4)]) else: scores = 0 num_cap_per_audio = len(refs[list(refs.keys())[0]]) for i in range(num_cap_per_audio): if (i > 0): for key in refs: refs[key...
class EditableModule(object): def getparams(self, methodname: str) -> Sequence[torch.Tensor]: paramnames = self.cached_getparamnames(methodname) return [get_attr(self, name) for name in paramnames] def setparams(self, methodname: str, *params) -> int: paramnames = self.cached_getparamnam...
class Migration(migrations.Migration): dependencies = [('conferences', '0004_remove_conference_vote_range'), ('submissions', '0002_auto__0954'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('voting', '0004_auto__1733')] operations = [migrations.DeleteModel(name='VoteRange'), migrations.AlterModel...
def _adjoint_final_soqs(cbloq: 'CompositeBloq', new_signature: Signature) -> Dict[(str, 'SoquetT')]: if (LeftDangle not in cbloq._binst_graph): return {} (_, init_succs) = _binst_to_cxns(LeftDangle, binst_graph=cbloq._binst_graph) return _cxn_to_soq_dict(new_signature.rights(), init_succs, get_me=(l...
class webvision_dataloader(): def __init__(self, batch_size, num_batches, num_class, num_workers, root_dir, root_imagenet_dir, log): self.batch_size = batch_size self.num_class = num_class self.num_samples = (None if (num_batches is None) else (self.batch_size * num_batches)) self.nu...
class AccountSupportView(LoginRequiredMixin, FormView): form_class = SupportForm template_name = 'adserver/accounts/support.html' success_url = reverse_lazy('dashboard-home') message_success = _('Thanks, we got your message and we will get back to you as soon as we can.') message_error = _('There wa...
def get_parser(): parser = argparse.ArgumentParser(description='Revise the spk2utt file: it only contans a subset of the utts', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--in-spk2utt', type=str, help='original spk2utt file') parser.add_argument('--out-spk2utt', type=str, h...
class SQL2Text(datasets.GeneratorBasedBuilder): def _info(self): return datasets.DatasetInfo(description=_DESCRIPTION, features=datasets.Features({'question': datasets.Value('string'), 'query': datasets.Value('string')}), supervised_keys=None, homepage=' citation=_CITATION) def _split_generators(self, d...
def main(args): seed_init() if ('base' in args.model_name): model = MANNER_BASE(in_channels=1, out_channels=1, hidden=60, depth=4, kernel_size=8, stride=4, growth=2, head=1, segment_len=64).to(args.device) elif ('large' in args.model_name): model = MANNER_BASE(in_channels=1, out_channels=1, ...
class RegNet(nn.Module): def __init__(self, cfg, in_chans=3, num_classes=1000, output_stride=32, global_pool='avg', drop_rate=0.0, drop_path_rate=0.0, zero_init_last_bn=True): super().__init__() self.num_classes = num_classes self.drop_rate = drop_rate assert (output_stride in (8, 16...
(frozen=True) class GenericParamRC(LocatedRequestChecker): LOCATION = GenericParamLoc pos: int def _check_location(self, mediator: DirectMediator, loc: GenericParamLoc) -> None: if (loc.generic_pos == self.pos): return raise CannotProvide(f'Generic param position {loc.generic_pos...
def test_flops_counter(): with pytest.raises(AssertionError): model = nn.Conv2d(3, 8, 3) input_res = [1, 3, 16, 16] get_model_complexity_info(model, input_res) with pytest.raises(AssertionError): model = nn.Conv2d(3, 8, 3) input_res = tuple() get_model_complexity_...
class NERModel(nn.Module): def __init__(self, args): super().__init__() self.args = args config = AutoConfig.from_pretrained(args.model_name_or_path, num_labels=args.num_class) self.model = AutoModel.from_pretrained(args.model_name_or_path) self.dropout = nn.Dropout(args.drop...
def test_switch_case_all_call_inputs(): with pytest.raises(Call) as err: switch(context=Context({'list': 'sg1', 'def': 'sg3', 'sg2_input': 'sg2', 'case1': False, 'case2': True, 'sg': 'sgv', 'fg': 'fgv', 'switch': [{'case': '{case1}', 'call': '{list}'}, {'case': '{case2}', 'call': {'groups': '{sg2_input}', '...
def find_similar_names(name: str, names: list[str]) -> list[str]: threshold = 1000.0 distance_by_name = {} for actual_name in names: distance = Levenshtein.distance(name, actual_name) is_similar = (distance <= (len(name) / 3)) substring_index = actual_name.find(name) is_subst...
.unit() .parametrize(('path_1', 'path_2', 'expectation', 'expected'), [pytest.param(PurePosixPath('relative_1'), PurePosixPath('/home/relative_2'), pytest.raises(ValueError, match="Can't mix absolute and relative paths"), None, id='test path 1 is relative'), pytest.param(PureWindowsPath('C:/home/relative_1'), PureWindo...
class AudioFile(dict, ImageContainer, HasKey): fill_metadata = False fill_length = False multisong = False streamsong = False can_add = True is_file = True format = 'Unknown Audio File' supports_rating_and_play_count_in_file = False mimes: list[str] = [] _property def _date_f...
def multiple_input_model(): input1 = tf.keras.Input(name='input1', shape=(10, 10, 3)) input2 = tf.keras.Input(name='input2', shape=(12, 12, 3)) x1 = tf.keras.layers.Conv2D(8, (1, 1), name='conv1a')(input1) x2 = tf.keras.layers.Conv2D(8, (3, 3), name='conv1b')(input2) x = tf.keras.layers.add([x1, x2]...
class Migration(migrations.Migration): dependencies = [('projects', '0039_integrationoption_secret')] operations = [migrations.CreateModel(name='IssueResource', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('url', models.URLField(help_text='The URL o...
class CurrentTests(BaseOutputTest): def __init__(self, model, param, disc, solution, operating_condition): super().__init__(model, param, disc, solution, operating_condition) self.a_j_n = solution['Negative electrode volumetric interfacial current density [A.m-3]'] self.a_j_p = solution['Pos...
_dataframe_method def separate_rows(df, column_name: str, sep: str=''): columns_original = list(df.columns) df['id'] = df.index wdf = pd.DataFrame(df[column_name].str.split(sep).tolist()).stack().reset_index() wdf.rename(columns={'level_0': 'id', 0: 'revenue_items'}, inplace=True) wdf.drop(columns=[...
def _transform_electronic_energy(hamiltonian: ElectronicEnergy, density_total: ElectronicIntegrals, density_active: ElectronicIntegrals, active_basis: BasisTransformer, offset_name: str, *, reference_inactive_fock: (ElectronicIntegrals | None)=None, reference_inactive_energy: (float | None)=None) -> ElectronicEnergy: ...
class PointLineDistance(PointOnLine): _id = 8 _props = ['Distance'] _iconName = 'Assembly_ConstraintPointLineDistance.svg' _tooltip = QT_TRANSLATE_NOOP('asm3', 'Add a "{}" to constrain the distance between a point and a linear edge in 2D or 3D') def init(cls, obj): infos = obj.Proxy.getEleme...
class Solution(object): def oddEvenList(self, head): odd = head if (head is None): return None if (head.next is None): return head even_head = even = head.next while ((odd.next is not None) and (even.next is not None)): odd.next = even.next...
def test_execute_should_show_operation_as_cancelled_on_subprocess_keyboard_interrupt(config: Config, pool: RepositoryPool, mocker: MockerFixture, io: BufferedIO, env: MockEnv) -> None: executor = Executor(env, pool, config, io) executor.verbose() mocker.patch.object(executor, '_install', return_value=(- 2))...
class SpconvModel(nn.Module): def __init__(self, in_channels=1, out_channels=10): super().__init__() self.conv = spconv.SparseConv2d(in_channels, out_channels, 1) def forward(self, x): nhwc_x = x.permute(0, *[i for i in range(2, len(x.shape))], 1) spconv_input = spconv.SparseConv...
class ScrimsClaim(discord.ui.Button): view: ScrimsSlotmPublicView def __init__(self, **kwargs): super().__init__(**kwargs) async def callback(self, interaction: discord.Interaction) -> T.Any: if (not self.view.claimable): (await interaction.response.send_message('No slot availabl...
class AttrVI_ATTR_RSRC_SPEC_VERSION(RangeAttribute): resources = AllSessionTypes py_name = 'spec_version' visa_name = 'VI_ATTR_RSRC_SPEC_VERSION' visa_type = 'ViVersion' default = 3145728 (read, write, local) = (True, False, True) (min_value, max_value, values) = (0, , None)
def annotation_string(word_annotation): result = '' for i in range(len(word_annotation.stresses)): result += SYLLABLE_SEPARATOR for j in range(len(word_annotation.syllables)): if (word_annotation.stresses[i][j] == Stress.primary): result += ' ' elif (word_...
class DotOutputFormatter(object): LOAD_IF = staticmethod((lambda config: (config.formatter == 'dots'))) LOAD_PRIORITY = 30 STATE_SYMBOLS = {Step.State.PASSED: '.', Step.State.PENDING: 'P', Step.State.UNTESTED: 'U', Step.State.SKIPPED: 'S', Step.State.FAILED: 'F'} def __init__(self): before.each_...
class AutoPurgeEvents(Cog): def __init__(self, bot: Quotient): self.bot = bot self.bot.loop.create_task(self.delete_older_snipes()) async def delete_older_snipes(self): (await self.bot.wait_until_ready()) (await Snipe.filter(delete_time__lte=(datetime.now(tz=IST) - timedelta(days...
class TestTensorboardPlotHook(HookTestBase): def setUp(self) -> None: self.base_dir = tempfile.mkdtemp() def tearDown(self) -> None: shutil.rmtree(self.base_dir) def test_constructors(self) -> None: config = {'summary_writer': {}, 'log_period': 5} invalid_config = copy.deepco...
class Actor(torch.nn.Module): def __init__(self, device): super().__init__() self.device = device self.mlp_policy = mlp(input_size=128, layer_sizes=[128, 64], output_size=1) def forward(self, x, action): logit = self.mlp_policy(torch.concat([x, action], dim=1).to(self.device)) ...
def test_one_pass(): plugin = ConsoleOutputPlugin() dispatcher = EventDispatcher() plugin.register(dispatcher) graph = bonobo.Graph() context = MagicMock(spec=GraphExecutionContext(graph)) dispatcher.dispatch(events.START, events.ExecutionEvent(context)) dispatcher.dispatch(events.TICK, even...
class Effect2795(BaseEffect): type = 'passive' def handler(fit, module, context, projectionRange, **kwargs): for type in ('kinetic', 'thermal', 'explosive', 'em'): fit.ship.boostItemAttr((('shield' + type.capitalize()) + 'DamageResonance'), (module.getModifiedItemAttr((type + 'DamageResistan...
def load_code_detector(bytecode): if isinstance(bytecode, bytes): bytecode = bytecode.hex() result = list(re.finditer('60.{2}604052', bytecode)) load_bytecode = '' rtcode_auxdata = bytecode if (len(result) > 1): position = result[1].start() load_bytecode = bytecode[:position]...
.parametrize(['width', 'height', 'affine_transform', 'expected_bounds'], [pytest.param(2, 2, Affine.identity(), (0.0, 2.0, 2.0, 0.0), id='Identity transform'), pytest.param(2, 2, Affine.scale(1, (- 1)), (0.0, (- 2.0), 2.0, 0.0), id='North-up transform'), pytest.param(2, 2, (Affine.translation(2, 2) * Affine.scale(1, (-...