code
stringlengths
281
23.7M
def test_base_recognizer(): cls_score = torch.rand(5, 400) with pytest.raises(KeyError): wrong_test_cfg = dict(clip='score') recognizer = ExampleRecognizer(None, wrong_test_cfg) recognizer.average_clip(cls_score) with pytest.raises(ValueError): wrong_test_cfg = dict(average_c...
class Locker(BaseLocker): def __init__(self, lock_path: Path) -> None: self._lock = (lock_path / 'poetry.lock') self._written_data = None self._locked = False self._lock_data = None self._content_hash = self._get_content_hash() def written_data(self) -> dict[(str, Any)]: ...
def test_points_from_angles(): distance = [1] elevation = [30] azimuth = [45] point1 = points_from_angles(distance=distance, elevation=elevation, azimuth=azimuth, is_degree=True) assert (point1.shape == (1, 3)) assert (point1.dtype == np.float64) point2 = points_from_angles(distance=distance...
class FilePathValidator(Validator): def validate(self, value): if len(value.text): if os.path.isfile(value.text): return True else: raise ValidationError(message='File not found', cursor_position=len(value.text)) else: return True
class SimpleLayer(caffe.Layer): def setup(self, bottom, top): pass def reshape(self, bottom, top): top[0].reshape(*bottom[0].data.shape) def forward(self, bottom, top): top[0].data[...] = (10 * bottom[0].data) def backward(self, top, propagate_down, bottom): bottom[0].dif...
def test_preserve_keys_order(pytester: Pytester) -> None: from _pytest.cacheprovider import Cache config = pytester.parseconfig() cache = Cache.for_config(config, _ispytest=True) cache.set('foo', {'z': 1, 'b': 2, 'a': 3, 'd': 10}) read_back = cache.get('foo', None) assert (list(read_back.items()...
def testPropEvo(): a = destroy(5) H = (a.dag() * a) U = Propagator([H, [(a + a.dag()), 'w*t']], args={'w': 1}) psi = (QobjEvo(U) basis(5, 4)) tlist = np.linspace(0, 1, 6) psi_expected = sesolve([H, [(a + a.dag()), 'w*t']], basis(5, 4), tlist=tlist, args={'w': 1}).states for (t, psi_t) in zi...
def main(client, config): wcs_df = benchmark(read_tables, config=config, compute_result=config['get_read_time']) f_wcs_df = wcs_df.map_partitions(pre_repartition_task) f_wcs_df = f_wcs_df.shuffle(on=['wcs_user_sk']) grouped_df = f_wcs_df.map_partitions(reduction_function, q02_session_timeout_inSec) ...
def test_lint(): assert_lints('%s', []) assert_lints('%.1%', ['using % combined with optional specifiers does not make sense']) assert_lints('%(a)s%s', ['cannot combine specifiers that require a mapping with those that do not']) assert_lints('%(a)*d', ['cannot combine specifiers that require a mapping w...
def evaluate(args, model, tokenizer, prefix=''): (dataset, examples, features) = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True) if ((not os.path.exists(args.output_dir)) and (args.local_rank in [(- 1), 0])): os.makedirs(args.output_dir) args.eval_batch_size = (args.per...
class Processor(): def __init__(self, arg): self.arg = arg self.save_arg() if self.arg.random_fix: self.rng = RandomState(seed=self.arg.random_seed) self.device = GpuDataParallel() self.recoder = Recorder(self.arg.work_dir, self.arg.print_log) self.data_lo...
def main(source, output, java, prefix_filter, exclude_filter, jars_list): reports_dir = 'jacoco_reports_dir' mkdir_p(reports_dir) with tarfile.open(source) as tf: def is_within_directory(directory, target): abs_directory = os.path.abspath(directory) abs_target = os.path.abspa...
class NullSection(Section): allLines = True def __init__(self, *args, **kwargs): Section.__init__(self, *args, **kwargs) self.sectionOpen = kwargs.get('sectionOpen') self._args = [] self._body = [] def handleHeader(self, lineno, args): self._args = args def handle...
.parametrize('run_at, start, end, idle, with_warning', [('document-start', True, False, False, False), ('document-end', False, True, False, False), ('document-idle', False, False, True, False), ('', False, True, False, False), ('bla', False, True, False, True)]) def test_run_at(gm_manager, run_at, start, end, idle, wit...
class ComPort(object): def __init__(self, usb_device, start=True): self.device = usb_device self._isFTDI = False self._rxinterval = 0.005 self._rxqueue = queue.Queue() self._rxthread = None self._rxactive = False self.baudrate = 9600 self.parity = 0 ...
def set_initial_resolution(request: WSGIRequest) -> HttpResponse: (value, response) = extract_value(request.POST) resolution = tuple(map(int, value.split('x'))) resolution = cast(Tuple[(int, int)], resolution) storage.put('initial_resolution', resolution) _notify_settings_changed('adjust_screen') ...
def test_multidim_register(): r = Register('my_reg', bitsize=1, shape=(2, 3), side=Side.RIGHT) idxs = list(r.all_idxs()) assert (len(idxs) == (2 * 3)) assert (not (r.side & Side.LEFT)) assert (r.side & Side.THRU) assert (r.total_bits() == (2 * 3)) assert (r.adjoint() == Register('my_reg', bi...
class InteractionTask(AbstractData): __slots__ = ['iid', 'input', 'structure', 'preset', 'output', 'data', 'title', 'description', 'plugin'] def __init__(self, iid=None, input=None, structure=None, preset=None, output=None, data=None, title=None, description=None, plugin=None): self.iid = iid se...
class CSVDIRBundle(): def __init__(self, tframes=None, csvdir=None): self.tframes = tframes self.csvdir = csvdir def ingest(self, environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress, output_dir): csv...
_register class MBIDMassager(Massager): tags = ['musicbrainz_trackid', 'musicbrainz_albumid', 'musicbrainz_artistid', 'musicbrainz_albumartistid', 'musicbrainz_trmid', 'musicip_puid'] error = _('MusicBrainz IDs must be in UUID format.') def validate(self, value): value = value.encode('ascii', 'repla...
def test_wr_As_wr_At_disjoint(): class Top(ComponentLevel3): def construct(s): s.A = Wire(Bits32) def up_wr_As(): s.A[1:3] = Bits2(2) def up_wr_At(): s.A[5:7] = Bits2(2) def up_rd_A(): z = s.A _test_model(Top...
class LLTM(nn.Module): def __init__(self, input_features, state_size): super(LLTM, self).__init__() self.input_features = input_features self.state_size = state_size self.weights = nn.Parameter(torch.Tensor((3 * state_size), (input_features + state_size))) self.bias = nn.Para...
class resnet_v1_101_fpn_dcn_rcnn_rep_noemb(Symbol): def __init__(self): self.shared_param_list = ['offset_p2', 'offset_p3', 'offset_p4', 'offset_p5', 'rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred'] self.shared_param_dict = {} for name in self.shared_param_list: self.shared_param_di...
def test_setting_list_option_completion(qtmodeltester, config_stub, configdata_stub, info): model = configmodel.list_option(info=info) model.set_pattern('') qtmodeltester.check(model) _check_completions(model, {'List options': [('completion.open_categories', 'Which categories to show (in which order) in...
class FC4_TestCase(CommandTest): command = 'mediacheck' def runTest(self): self.assert_parse('mediacheck', 'mediacheck\n') self.assert_parse_error('mediacheck --cheese') self.assert_parse_error('mediacheck --crackers=CRUNCHY') self.assert_parse_error('mediacheck cheese crackers')
class CometCallback(TrainerCallback): def __init__(self): if (not _has_comet): raise RuntimeError('CometCallback requires comet-ml to be installed. Run `pip install comet-ml`.') self._initialized = False self._log_assets = False def setup(self, args, state, model): se...
class AdvertisingIntegrationTests(BaseApiTest): def setUp(self): super().setUp() self.user.publishers.add(self.publisher2) self.publisher_group.publishers.add(self.publisher2) self.page_url = ' def test_ad_view_and_tracking(self): data = {'placements': self.placements, 'p...
class TestDocumentDataRetrivalMethods(unittest.TestCase): def test_get_method(self): document = parse(USER_ONLY) user = document.get('user') expected_body = ['id = 1', "name = 'alex'"] self.assertEqual(expected_body, user.body) user = document.get('user', 1) expected_...
def parse_args(): special_args = [{'name': ['-b', '--backend'], 'choices': ['dask', 'explicit-comms', 'dask-noop'], 'default': 'dask', 'type': str, 'help': 'The backend to use.'}, {'name': ['-t', '--type'], 'choices': ['cpu', 'gpu'], 'default': 'gpu', 'type': str, 'help': 'Do merge with GPU or CPU dataframes'}, {'n...
def crosses(shape, other): if (not hasattr(shape, GEO_INTERFACE_ATTR)): raise TypeError((SHAPE_TYPE_ERR % shape)) if (not hasattr(other, GEO_INTERFACE_ATTR)): raise TypeError((SHAPE_TYPE_ERR % shape)) o = geom.shape(shape) o2 = geom.shape(other) return o.crosses(o2)
class EvolutionSampler(BaseSampler): def __init__(self, **kwargs): super().__init__(**kwargs) if (not hasattr(self, 'heads_share')): self.heads_share = False assert (self.heads_share == True), f'We need share heads for Block opeartion' if (not hasattr(self, 'GPU_search'))...
class GPT2TokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] slow_tokenizer_class = GPT2Tokenizer ...
class TenluaVn(SimpleDownloader): __name__ = 'TenluaVn' __type__ = 'downloader' __version__ = '0.04' __status__ = 'testing' __pattern__ = ' __config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback to f...
_REGISTRY.register() class REDSRecurrentDataset(data.Dataset): def __init__(self, opt): super(REDSRecurrentDataset, self).__init__() self.opt = opt (self.gt_root, self.lq_root) = (Path(opt['dataroot_gt']), Path(opt['dataroot_lq'])) self.num_frame = opt['num_frame'] self.keys ...
def conduit_draw_color(conduit): if ('draw_color' in conduit.axes[0]): return conduit.draw_color fill = '#787882' if (('MaxQPerc' in conduit) and (conduit.MaxQPerc >= 1)): capacity = (conduit.MaxQ / conduit.MaxQPerc) stress = (conduit.MaxQ / capacity) fill = gradient_grey_red...
.parametrize('basedirs, expected_basedirs, os_name', [(['foo', 'bar'], ['foo', 'bar'], 'posix'), (['foo:bar', 'foobar'], ['foo', 'bar', 'foobar'], 'posix'), (['foo:bar', 'foobar', 'one:two:three'], ['foo', 'bar', 'foobar', 'one', 'two', 'three'], 'posix'), (['foo:', ':bar'], ['foo', 'bar'], 'posix'), (['C:\\windows\\ra...
def test_function_overloading(): assert (m.test_function() == 'test_function()') assert (m.test_function(7) == 'test_function(7)') assert (m.test_function(m.MyEnum.EFirstEntry) == 'test_function(enum=1)') assert (m.test_function(m.MyEnum.ESecondEntry) == 'test_function(enum=2)') assert (m.test_funct...
.parametrize('tp', [str, *cond_list(HAS_PY_311, (lambda : [typing.LiteralString]))]) def test_str_loader_provider(strict_coercion, debug_trail, tp): retort = Retort(strict_coercion=strict_coercion, debug_trail=debug_trail) loader = retort.get_loader(tp) assert (loader('foo') == 'foo') if strict_coercion...
def date2juldate(val: date) -> float: f = (((12 * val.year) + val.month) - 22803) fq = (f // 12) fr = (f % 12) dt = (((((fr * 153) + 302) // 5) + val.day) + ((fq * 1461) // 4)) if isinstance(val, datetime): return (dt + ((val.hour + ((val.minute + ((val.second + (1e-06 * val.microsecond)) / ...
class ApplyClassicalTest(Bloq): def signature(self) -> 'Signature': return Signature([Register('x', 1, shape=(5,)), Register('z', 1, shape=(5,), side=Side.RIGHT)]) def on_classical_vals(self, *, x: NDArray[np.uint8]) -> Dict[(str, NDArray[np.uint8])]: const = np.array([1, 0, 1, 0, 1], dtype=np.u...
class Uniform(BoundedContinuous): rv_op = uniform bound_args_indices = (3, 4) def dist(cls, lower=0, upper=1, **kwargs): lower = pt.as_tensor_variable(floatX(lower)) upper = pt.as_tensor_variable(floatX(upper)) return super().dist([lower, upper], **kwargs) def moment(rv, size, lo...
def caffenet(lmdb, batch_size=256, include_acc=False): (data, label) = L.Data(source=lmdb, backend=P.Data.LMDB, batch_size=batch_size, ntop=2, transform_param=dict(crop_size=227, mean_value=[104, 117, 123], mirror=True)) (conv1, relu1) = conv_relu(data, 11, 96, stride=4) pool1 = max_pool(relu1, 3, stride=2)...
class GroupAll(nn.Module): def __init__(self, use_xyz=True): super(GroupAll, self).__init__() self.use_xyz = use_xyz def forward(self, xyz, new_xyz, features=None): grouped_xyz = xyz.transpose(1, 2).unsqueeze(2) if (features is not None): grouped_features = features.u...
def main(args): meta_path = os.path.abspath(args[0]) timeout_code = int(args[1]) subprocess.check_call(args[2:]) with open(meta_path) as f: meta_info = json.loads(f.read()) if (meta_info['exit_code'] == timeout_code): ((print >> sys.stderr), meta_info['project'], 'crashed by ...
class StereoDataset(BaseDataset): def __init__(self, data_path, filenames_file, args, dataset, mode, ret_meta_info=False): super(StereoDataset, self).__init__(data_path, filenames_file, dataset, mode, args.height, args.width) assert (self.dataset in ['sceneflow', 'kitti', 'cityscapes']) self...
def test_check_python_script(capsys): mmcv.utils.check_python_script('./tests/data/scripts/hello.py zz') captured = capsys.readouterr().out assert (captured == 'hello zz!\n') mmcv.utils.check_python_script('./tests/data/scripts/hello.py agent') captured = capsys.readouterr().out assert (captured...
.isolated def test_build_raises_build_backend_exception(mocker, package_test_flit): mocker.patch('build.ProjectBuilder.get_requires_for_build', side_effect=build.BuildBackendException(Exception('a'))) mocker.patch('build.env.DefaultIsolatedEnv.install') msg = f"Backend operation failed: Exception('a'{(',' i...
class Trainer(): def __init__(self, model: torch.nn.Module, train_data: DataLoader, optimizer: torch.optim.Optimizer, save_every: int, snapshot_path: str) -> None: self.gpu_id = int(os.environ['LOCAL_RANK']) self.model = model.to(self.gpu_id) self.train_data = train_data self.optimiz...
class TestTrialUnittest(): def setup_class(cls): cls.ut = pytest.importorskip('twisted.trial.unittest') cls.ignore_unclosed_socket_warning = ('-W', 'always') def test_trial_testcase_runtest_not_collected(self, pytester: Pytester) -> None: pytester.makepyfile('\n from twisted.t...
class DetectionModel(object): __metaclass__ = ABCMeta def __init__(self, num_classes): self._num_classes = num_classes self._groundtruth_lists = {} def num_classes(self): return self._num_classes def groundtruth_lists(self, field): if (field not in self._groundtruth_lists...
def overlap_detection(radius_list, x, y, z, show_info=0): overlapOrNot = 0 for ii in range(0, len(radius_list)): for jj in range((ii + 1), len(radius_list)): tempR1 = radius_list[ii][0] tempR2 = radius_list[jj][0] tempDis = ((((x[ii] - x[jj]) ** 2) + ((y[ii] - y[jj]) ...
def test_progress_with_exception(workspace, consumer): workspace._config.capabilities['window'] = {'workDoneProgress': True} class DummyError(Exception): pass try: with workspace.report_progress('some_title'): raise DummyError('something') except DummyError: pass ...
def test_read_only(tmpdir_cwd): dist = Distribution(dict(script_name='setup.py', script_args=['build_py'], packages=['pkg'], package_data={'pkg': ['data.dat']})) os.makedirs('pkg') open('pkg/__init__.py', 'w').close() open('pkg/data.dat', 'w').close() os.chmod('pkg/__init__.py', stat.S_IREAD) os...
class BILSTMCRF(object): def __init__(self, params: dict): self.char_embedding = tf.Variable(np.load(params['embedding_path']), dtype=tf.float32, name='input_char_embedding') self.word_embedding = tf.Variable(np.load(params['word_embedding_path']), dtype=tf.float32, name='input_word_embedding') ...
class ForbiddenExtraKeysError(Exception): def __init__(self, message: Optional[str], cl: Type, extra_fields: Set[str]) -> None: self.cl = cl self.extra_fields = extra_fields cln = cl.__name__ super().__init__((message or f"Extra fields in constructor for {cln}: {', '.join(extra_field...
def default_errformat(val): it = val._e_metas() if (val.creator is not None): try: after = (os.linesep + format_element(val.creator)) except Exception: after = ('Element Traceback of %r caused exception:%s' % (type(val.creator).__name__, os.linesep)) after += ...
class Dequantization(nn.Module): filters: int = 96 components: int = 4 blocks: int = 5 attn_heads: int = 4 dropout_p: float = 0.0 use_nin: bool = True use_ln: bool = True def __call__(self, eps, x, inverse=False, train=False): logp_eps = jnp.sum((((- (eps ** 2)) / 2.0) - (0.5 * n...
def get_versioned_symbols(libs): result = {} for (path, elf) in elf_file_filter(libs.keys()): elf_versioned_symbols = defaultdict(set) for (key, value) in elf_find_versioned_symbols(elf): log.debug('path %s, key %s, value %s', path, key, value) elf_versioned_symbols[key]....
def test_configure_multiple_modules(): def configure_a(binder): binder.bind(DependsOnEmptyClass) def configure_b(binder): binder.bind(EmptyClass) injector = Injector([configure_a, configure_b]) a = injector.get(DependsOnEmptyClass) assert isinstance(a, DependsOnEmptyClass) assert...
class CLIPTextCfg(): context_length: int = 77 vocab_size: int = 49408 width: int = 512 heads: int = 8 layers: int = 12 ls_init_value: Optional[float] = None hf_model_name: str = None hf_tokenizer_name: str = None hf_model_pretrained: bool = True proj: str = 'mlp' pooler_type:...
class INR(nn.Module): def __init__(self, in_features, hidden_features, hidden_layers, out_features, outermost_linear=True, sigma=10.0, pos_encode_configs={'type': None, 'use_nyquist': None, 'scale_B': None, 'mapping_input': None}): super().__init__() self.pos_encode = pos_encode_configs['type'] ...
def meta_next_trading_day(is_trading_day): def next_trading_day(dt): if (type(dt) is datetime.datetime): dt = dt.date() while True: dt = (dt + datetime.timedelta(days=1)) if is_trading_day(dt): return dt return next_trading_day
class GdbExit(sublime_plugin.WindowCommand): def run(self): global gdb_shutting_down gdb_shutting_down = True wait_until_stopped() run_cmd('-gdb-exit', True) if gdb_server_process: gdb_server_process.terminate() def is_enabled(self): return is_running(...
def _test(): import torch pretrained = False models = [fbnet_cb] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) assert ((model != fbnet_cb) or (weight_count ...
class StochasticEncoderLayer(EncoderLayer): def __init__(self, h, d_model, p, d_ff, attn_p=0.1, version=1.0, death_rate=0.0): super().__init__(h, d_model, p, d_ff, attn_p, version) self.death_rate = death_rate def forward(self, input, attn_mask): coin = True if self.training: ...
class SemsegMeter(object): def __init__(self, num_classes, class_names, has_bg=True, ignore_index=255): self.num_classes = (num_classes + int(has_bg)) self.class_names = class_names self.tp = ([0] * self.num_classes) self.fp = ([0] * self.num_classes) self.fn = ([0] * self.nu...
def parse_args(): parser = argparse.ArgumentParser(description='Train keypoints network') parser.add_argument('--cfg', help='experiment configure file name', required=True, type=str) (args, rest) = parser.parse_known_args() update_config(args.cfg) parser.add_argument('--frequent', help='frequency of...
def test_resnext_backbone(): with pytest.raises(KeyError): ResNeXt(depth=18) model = ResNeXt(depth=50, groups=32, base_width=4) print(model) for m in model.modules(): if is_block(m): assert (m.conv2.groups == 32) model.init_weights() model.train() imgs = torch.ran...
def ComboBoxDroppedHeightTest(windows): bugs = [] for win in windows: if (not win.ref): continue if ((win.class_name() != 'ComboBox') or (win.ref.class_name() != 'ComboBox')): continue if (win.dropped_rect().height() != win.ref.dropped_rect().height()): ...
def main(): parser = HfArgumentParser((ModelArguments,)) (model_args,) = parser.parse_args_into_dataclasses() if model_args.encoder_config_name: encoder_config = AutoConfig.from_pretrained(model_args.encoder_config_name) else: encoder_config = AutoConfig.from_pretrained(model_args.encode...
('pypyr.moduleloader.get_module') ('unittest.mock.MagicMock', new=DeepCopyMagicMock) def test_run_pipeline_steps_complex_swallow_true_error(mock_get_module): step = Step({'name': 'step1', 'swallow': 1}) context = get_test_context() original_len = len(context) arb_error = ValueError('arb error here') ...
class HotelRoomReservationFactory(DjangoModelFactory): order_code = 'AAAABB' room = factory.SubFactory(HotelRoomFactory) checkin = factory.Faker('past_date') checkout = factory.Faker('future_date') user = factory.SubFactory(UserFactory) class Meta(): model = HotelRoomReservation
class TimeLabel(Gtk.Label): def __init__(self, time_=0): Gtk.Label.__init__(self) self.__widths = {} self._disabled = False self.set_time(time_) def do_get_preferred_width(self): widths = Gtk.Label.do_get_preferred_width(self) num_chars = len(self.get_text()) ...
class Test_avl_iter(unittest.TestCase): def setUp(self): self.n = 1000 self.t = range_tree(0, self.n) self.orig = list(range(self.n)) def testiter_forloop(self): list = self.orig[:] for i in range(5): random.shuffle(list) for k in avl.new(list): ...
def main(client, config): (ws_df, item_df, imp_df, ss_df) = benchmark(read_tables, config=config, compute_result=config['get_read_time']) item_imp_join_df = get_helper_query_table(imp_df, item_df) r_ss = get_ss(ss_df, item_imp_join_df) r_ws = get_ws(ws_df, item_imp_join_df) result_df = r_ws.merge(r_...
_pipeline_test _vision class ZeroShotImageClassificationPipelineTests(unittest.TestCase): _torch def test_small_model_pt(self): image_classifier = pipeline(model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification') image = Image.open('./tests/fixtures/tests_samples/COCO/.png') ...
class TestAssertionWarnings(): def assert_result_warns(result, msg) -> None: result.stdout.fnmatch_lines([('*PytestAssertRewriteWarning: %s*' % msg)]) def test_tuple_warning(self, pytester: Pytester) -> None: pytester.makepyfile(' def test_foo():\n assert (1,2)\n ...
def test_search_for_directory_setup_read_setup_with_extras(provider: Provider, mocker: MockerFixture, fixture_dir: FixtureDirGetter) -> None: mocker.patch('poetry.utils.env.EnvManager.get', return_value=MockEnv()) dependency = DirectoryDependency('demo', (((fixture_dir('git') / 'github.com') / 'demo') / 'demo')...
class DescribeImagePart(): def it_is_used_by_PartFactory_to_construct_image_part(self, image_part_load_, partname_, blob_, package_, image_part_): content_type = CT.JPEG reltype = RT.IMAGE image_part_load_.return_value = image_part_ part = PartFactory(partname_, content_type, reltype...
class Migration(migrations.Migration): dependencies = [('comms', '0008_auto__0902')] operations = [migrations.AlterField(model_name='msg', name='db_hide_from_channels', field=models.ManyToManyField(blank=True, null=True, related_name='hide_from_channels_set', to='comms.ChannelDB')), migrations.AlterField(model_...
def test_param_name_duplicates(): with pytest.raises(ValueError, match=full_match_regex_str("Parameter names {'a'} are duplicated")): InputShape(constructor=stub_constructor, kwargs=None, fields=(InputField(id='a1', type=int, default=NoDefault(), is_required=True, metadata={}, original=None), InputField(id=...
def logged_in_admin_user(e2e_tests_django_db_setup, page: Page) -> Page: page.goto('/account/login') page.get_by_label('Username').fill('admin', timeout=5000) page.get_by_label('Password').fill('admin') page.get_by_role('button', name='Login').click() page.goto('/management') (yield page)
class TestArtifactVersion(unittest.TestCase, ArchiveTestingMixin): def setUp(self): prefix = 'qiime2-test-temp-' self.temp_dir = tempfile.TemporaryDirectory(prefix=prefix) self.provenance_capture = archive.ImportProvenanceCapture() def tearDown(self): self.temp_dir.cleanup() ...
def main(id: int, skip_crawling: bool, with_quote: bool): parsed_json = Crawler.crawl(id) cache_dir = os.sep.join([os.curdir, 'cache', str(id), 'data.json']) with open(cache_dir, 'r', encoding='utf-8') as file: radio = Radio.load_from_json(parsed_json) if (not skip_crawling): Cra...
(epilog=rgroup2smarts_epilog) ('--cut-rgroup', metavar='SMILES', multiple=True, help='R-group SMILES to use') ('--single', '-s', default=False, is_flag=True, help='Generate a SMARTS for each R-group SMILES (default: generate a single recursive SMARTS)') ('--check', '-c', default=False, is_flag=True, help='Check that th...
def test_get_pipeline_path_raises_no_parent(): with pytest.raises(PipelineNotFoundError) as err: fileloader.get_pipeline_path('unlikelypipeherexyz', None) cwd_pipes_path = cwd.joinpath('pipelines') expected_msg = f'''unlikelypipeherexyz.yaml not found in any of the following: {cwd} {cwd_pipes_path} ...
def _create_s3_backend(session: Session, bucket: str, table: str, region_name: str) -> None: account_id = get_account_id(session) bucket_arn = _get_s3_bucket_arn(region_name, account_id, bucket) table_arn = _get_dynamodb_table_arn(region_name, account_id, table) log.ok(f'backend: {bucket_arn}') log....
class MSVCCompiler(CCompiler): compiler_type = 'msvc' executables = {} _c_extensions = ['.c'] _cpp_extensions = ['.cc', '.cpp', '.cxx'] _rc_extensions = ['.rc'] _mc_extensions = ['.mc'] src_extensions = (((_c_extensions + _cpp_extensions) + _rc_extensions) + _mc_extensions) res_extension...
def test_correctness_vertex_set_contiguity_distinct(): data = geopandas.GeoSeries((shapely.box(0, 0, 1, 1), shapely.box(0.5, 1, 1.5, 2))) vs_rook = _vertex_set_intersection(data, rook=True) rook = _rook(data) assert (set(zip(*vs_rook, strict=True)) != set(zip(*rook, strict=True))) vs_queen = _vertex...
def get_interp_fun(variable_name, domain): variable = comsol_variables[variable_name] if (domain == ['negative electrode']): comsol_x = comsol_variables['x_n'] elif (domain == ['positive electrode']): comsol_x = comsol_variables['x_p'] elif (domain == whole_cell): comsol_x = coms...
(device=True) def imt_func_o25(value, other_value): return ((((((0 + ((1.0 * value[2]) * other_value[30])) + ((1.0 * value[1]) * other_value[29])) + (((- 1.0) * value[30]) * other_value[2])) + (((- 1.0) * value[6]) * other_value[31])) + (((- 1.0) * value[29]) * other_value[1])) + (((- 1.0) * value[31]) * other_valu...
def load_data_for_worker(base_samples, batch_size, class_cond): with bf.BlobFile(base_samples, 'rb') as f: obj = np.load(f) image_arr = obj['arr_0'] if class_cond: label_arr = obj['arr_1'] rank = dist.get_rank() num_ranks = dist.get_world_size() buffer = [] label_...
_funcify.register(Solve) def numba_funcify_Solve(op, node, **kwargs): assume_a = op.assume_a if (assume_a != 'gen'): lower = op.lower warnings.warn('Numba will use object mode to allow the `compute_uv` argument to `numpy.linalg.svd`.', UserWarning) ret_sig = get_numba_type(node.outputs[0...
('/v1/organization/<orgname>/quota/<quota_id>/limit/<limit_id>') _if(features.SUPER_USERS) _if(features.QUOTA_MANAGEMENT) class OrganizationQuotaLimit(ApiResource): schemas = {'UpdateOrgQuotaLimit': {'type': 'object', 'description': 'Description of changing organization quota limit', 'properties': {'type': {'type':...
class GroupElasticNet(ElasticNetConfig): def __init__(self, groups=None, pen_val=1, mix_val=0.5, lasso_weights=None, lasso_flavor=None, ridge_weights=None): pass def _get_sum_configs(self): lasso_config = GroupLasso(groups=self.groups, pen_val=(self.pen_val * self.mix_val), weights=self.lasso_we...
def obtain_confused_result(out: defaultdict, threshole=0.6, confuse_value=0.15, num_template=2): hard_answer = dict() for (k, v) in out.items(): if ('ner' in k.lower()): continue is_filter = False (best_result, best_prob) = (v.most_common()[0][0], v.most_common()[0][1]) ...
class CheckInService(): _EARLY_CHECK_IN_OFFSET: int = 3 _LATE_CHECK_IN_OFFSET: int = 6 def _is_valid_date(reservation: Reservation) -> bool: return ((reservation.date_in - timedelta(hours=CheckInService._EARLY_CHECK_IN_OFFSET)) <= datetime.utcnow() <= (reservation.date_out - timedelta(hours=CheckInS...
class InteriorSquirmer(DynSys): def _rhs_static(r, th, t, a, g, n): nvals = np.arange(1, (n + 1)) (sinvals, cosvals) = (np.sin((th * nvals)), np.cos((th * nvals))) rnvals = (r ** nvals) vrn = ((g * cosvals) + (a * sinvals)) vrn *= (((nvals * rnvals) * ((r ** 2) - 1)) / r) ...
def clean_folder(folder): for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if (os.path.isfile(file_path) or os.path.islink(file_path)): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_pa...
def batchify_data(batch): enc_input_ids = [f['enc_input'] for f in batch] (enc_input_ids, enc_lens) = padded_sequence(enc_input_ids, batch[0]['pad']) enc_input_ids = torch.tensor(enc_input_ids, dtype=torch.long) enc_lens = torch.tensor(enc_lens, dtype=torch.long) enc_batch_extend_vocab = [f['enc_inp...