code
stringlengths
281
23.7M
def define_G(model_opt): from .sr3_modules import unet if (('norm_groups' not in model_opt) or (model_opt['norm_groups'] is None)): model_opt['norm_groups'] = 32 model = unet.UNet(in_channel=model_opt['in_channel'], out_channel=model_opt['out_channel'], norm_groups=model_opt['norm_groups'], inner_ch...
class TPaneEntry(TestCase): def test_all_have(self): sel = SongsEntry('foo', 'foo', SONGS) self.assertFalse(sel.all_have('artist', 'one')) self.assertFalse(sel.all_have('~#mtime', 4)) self.assertTrue(sel.all_have('foo', 'bar')) def test_all(self): entry = AllEntry() ...
class FeatureExtractionPipeline(Pipeline): def _sanitize_parameters(self, truncation=None, **kwargs): preprocess_params = {} if (truncation is not None): preprocess_params['truncation'] = truncation return (preprocess_params, {}, {}) def preprocess(self, inputs, truncation=No...
def get_template_files(template_name, project_name, **kwargs): kwargs['project_name'] = project_name kwargs['project_name_normalized'] = project_name.lower().replace('.', '-') kwargs['package_name'] = kwargs['project_name_normalized'].replace('-', '_') config = RootConfig({}) kwargs.setdefault('auth...
class Solution(object): def isIsomorphic(self, s, t): if (len(s) != len(t)): return False ls = len(s) mapStoT = ([0] * 127) mapTtoS = ([0] * 127) for i in range(ls): (s_num, t_num) = (ord(s[i]), ord(t[i])) if ((mapStoT[s_num] == 0) and (map...
def test_conftest_symlink(pytester: Pytester) -> None: real = pytester.mkdir('real') realtests = real.joinpath('app/tests') realtests.mkdir(parents=True) symlink_or_skip(realtests, pytester.path.joinpath('symlinktests')) symlink_or_skip(real, pytester.path.joinpath('symlink')) pytester.makepyfil...
def test_multitensor_offsetmap(): a = np.random.random((5, 5, 5, 5)) b = np.random.random((4, 4, 4)) c = np.random.random((3, 3)) at = Tensor(tensor=a, name='a') bt = Tensor(tensor=b, name='b') ct = Tensor(tensor=c, name='c') mt = MultiTensor([at, bt, ct]) assert (mt.off_set_map == {'a':...
class MultiloadCz(BaseDecrypter): __name__ = 'MultiloadCz' __type__ = 'decrypter' __version__ = '0.46' __status__ = 'testing' __pattern__ = ' __config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('use_subfolder', 'bool', 'Save p...
class ViewProviderAsmConstraint(ViewProviderAsmGroup): def setupContextMenu(self, vobj, menu): obj = vobj.Object action = QtGui.QAction(QtGui.QIcon(), ('Enable constraint' if obj.Disabled else 'Disable constraint'), menu) QtCore.QObject.connect(action, QtCore.SIGNAL('triggered()'), self.togg...
class AttrVI_ATTR_4882_COMPLIANT(BooleanAttribute): resources = [(constants.InterfaceType.usb, 'INSTR'), (constants.InterfaceType.vxi, 'INSTR')] py_name = 'is_4882_compliant' visa_name = 'VI_ATTR_4882_COMPLIANT' visa_type = 'ViBoolean' default = NotAvailable (read, write, local) = (True, False, ...
class PluginEnabledFilterCombo(Gtk.ComboBox): def __init__(self): combo_store = Gtk.ListStore(str, int) super().__init__(model=combo_store) cell = Gtk.CellRendererText() cell.props.ellipsize = Pango.EllipsizeMode.END self.pack_start(cell, True) self.add_attribute(cell...
class CTOCFlagsSpec(ByteSpec): def read(self, header, frame, data): (value, data) = ByteSpec.read(self, header, frame, data) return (CTOCFlags(value), data) def validate(self, frame, value): value = ByteSpec.validate(self, frame, value) if (value is not None): return ...
def test_transform_bounds_densify_out_of_bounds(): transformer = Transformer.from_crs('EPSG:4326', '+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs', always_xy=True) with pytest.raises(ProjError): transformer.transform_bounds((- 120), 40, (- 80), 64, densify_pts=(-...
class LRSchedulerStep(object): def __init__(self, fai_optimizer: OptimWrapper, total_step, lr_phases, mom_phases): self.optimizer = fai_optimizer self.total_step = total_step self.lr_phases = [] for (i, (start, lambda_func)) in enumerate(lr_phases): if (len(self.lr_phases...
class Condition(models.Model): RELATION_EQUAL = 'eq' RELATION_NOT_EQUAL = 'neq' RELATION_CONTAINS = 'contains' RELATION_GREATER_THAN = 'gt' RELATION_GREATER_THAN_EQUAL = 'gte' RELATION_LESSER_THAN = 'lt' RELATION_LESSER_THAN_EQUAL = 'lte' RELATION_EMPTY = 'empty' RELATION_NOT_EMPTY =...
class GroupPushRulesManager(GetWithoutIdMixin, CreateMixin, UpdateMixin, DeleteMixin, RESTManager): _path = '/groups/{group_id}/push_rule' _obj_cls = GroupPushRules _from_parent_attrs = {'group_id': 'id'} _create_attrs = RequiredOptional(optional=('deny_delete_tag', 'member_check', 'prevent_secrets', 'c...
class OpVisitor(Generic[T]): def visit_goto(self, op: Goto) -> T: raise NotImplementedError def visit_branch(self, op: Branch) -> T: raise NotImplementedError def visit_return(self, op: Return) -> T: raise NotImplementedError def visit_unreachable(self, op: Unreachable) -> T: ...
class Block(nn.Module): def __init__(self, channels): super(Block, self).__init__() self.conv1 = nn.Conv2d(channels, channels, 3, 1, 1, bias=False) self.bn1 = nn.BatchNorm2d(channels) self.prelu1 = nn.PReLU(channels) self.conv2 = nn.Conv2d(channels, channels, 3, 1, 1, bias=Fa...
def test_bng_printer(): assert (_bng_print(sympy.pi) == '_pi') assert (_bng_print(sympy.E) == '_e') (x, y) = sympy.symbols('x y') assert (_bng_print(sympy.sympify('x & y')) == 'x && y') assert (_bng_print(sympy.sympify('x | y')) == 'x || y') assert (_bng_print(sympy.sin(x)) == 'sin(x)') asse...
(params=[_PROJECT_TASK, _PROJECT_TASK_NEW_INTERFACE]) def project(request, tmp_path): tmp_path.joinpath('task_module.py').write_text(textwrap.dedent(request.param)) tmp_path.joinpath('in.txt').touch() tmp_path.joinpath('to_be_deleted_file_1.txt').touch() tmp_path.joinpath('to_be_deleted_folder_1').mkdir...
class UploaderBase(object): __metaclass__ = abc.ABCMeta def __init__(self, bucket_name, **kwargs): self.bucket_name = bucket_name self.auth = kwargs.get('auth', None) regions = kwargs.get('regions', []) self.regions = regions hosts_cache_dir = kwargs.get('hosts_cache_dir'...
def get_train_dataloader(data_pth, max_seq_length, train_batch_size): print('processing training data') data = get_data(data_pth) (features, vocab) = convert_example_to_feature(data, max_seq_length, None, sum_mode=args.sum_mode, context_mode=args.context_mode, get_vocab=True) train_data = PGNDataset(fea...
def process_squad_data(data, morphological_analyzer): for article in data: tokenized_title = morphological_analyzer.get_tokenized_string(article['title']) for paragraph in article['paragraphs']: title_context = paragraph['context'] (_, context) = title_context.split(' [SEP] '...
class FakeTestCase(unittest.TestCase): def runTest(self): pass def subTest(self, *args, **kwargs): try: self._subtest = unittest.case._SubTest(self, object(), {}) (yield) finally: self._subtest = None def __call__(self, result): pass
def load_parent(**kwargs: Any) -> CompletedProcess: frame = inspect.currentframe() if (not frame): raise Exception('workflow: load_parent() called from unknown frame') caller_frame = frame.f_back if (not caller_frame): raise Exception('workflow: load_parent() called from unknown caller')...
def generate_class_type_decl(cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter) -> None: context = c_emitter.context name = emitter.type_struct_name(cl) context.declarations[name] = HeaderDeclaration(f'PyTypeObject *{emitter.type_struct_name(cl)};', needs_export=True) if (not ...
class TestLoadNetCDF2DPandas(TestLoadNetCDF): def setup_method(self): self.tempdir = tempfile.TemporaryDirectory() self.saved_path = pysat.params['data_dirs'] pysat.params['data_dirs'] = self.tempdir.name self.testInst = pysat.Instrument(platform='pysat', name='testing2d', update_fil...
def check_other_isdataclass_overloads(x: type, y: object) -> None: dc.fields(y) dc.asdict(x) dc.asdict(y) dc.astuple(x) dc.astuple(y) dc.replace(x) dc.replace(y) if dc.is_dataclass(x): assert_type(x, Type['DataclassInstance']) assert_type(dc.fields(x), Tuple[(dc.Field[Any...
def get_args_tuple(args, kwargs, arg_names, kwargs_defaults): args_list = list(args) args_len = len(args) all_args_len = len(arg_names) try: while (args_len < all_args_len): arg_name = arg_names[args_len] if (arg_name in kwargs_defaults): args_list.append(...
def test_mlpg_gradcheck(): static_dim = 2 T = 10 for windows in _get_windows_set(): torch.manual_seed(1234) means = torch.rand(T, (static_dim * len(windows)), requires_grad=True) variances = torch.ones((static_dim * len(windows))).expand(T, (static_dim * len(windows))) inputs...
def handle_long_project_survey_participants_request(**kwargs) -> Any: data = kwargs['data'] headers = kwargs['headers'] resp = None if (('test' in data.get('instrument')) and ('raw' in data.get('event'))): resp = [{'email': '', 'email_occurrence': 1, 'identifier': '', 'record': '', 'invitation_s...
def test_class_interact(): parent = Parameter.create(name='parent', type='group') interactor = Interactor(parent=parent, nest=False) def outside_class_deco(func): (func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper class A(): def a...
_optionals.HAS_PYSCF.require_in_instance class PySCFDriver(ElectronicStructureDriver): def __init__(self, atom: (str | list[str])='H 0.0 0.0 0.0; H 0.0 0.0 0.735', *, unit: DistanceUnit=DistanceUnit.ANGSTROM, charge: int=0, spin: int=0, basis: str='sto3g', method: MethodType=MethodType.RHF, xc_functional: str='lda,...
class TestParameterValuesWithModel(TestCase): def test_parameter_values_with_model(self): param_to_model = {'Ai2020': pybamm.lithium_ion.DFN({'particle mechanics': 'swelling and cracking'}), 'Chen2020': pybamm.lithium_ion.DFN(), 'Chen2020_composite': pybamm.lithium_ion.DFN({'particle phases': ('2', '1'), 'o...
def properties_of_geometric_objects(): Print_Function() global n, nbar g = (((('# # # 0 0,' + '# # # 0 0,') + '# # # 0 0,') + '0 0 0 0 2,') + '0 0 0 2 0') c3d = Ga('p1 p2 p3 n nbar', g=g) (p1, p2, p3, n, nbar) = c3d.mv() print('g_{ij} =\n', c3d.g) P1 = F(p1) P2 = F(p2) P3 = F(p3) ...
def add_default_codecs(): try: from pyglet.image.codecs import dds registry.add_encoders(dds) registry.add_decoders(dds) except ImportError: pass if (compat_platform == 'darwin'): try: from pyglet.image.codecs import quartz registry.add_encoder...
def test_many2one_match_ic13(): det_id = 0 recall_mat = np.array([[1, 0], [0, 0]]) precision_mat = np.array([[1, 0], [0, 0]]) recall_thr = 0.5 precision_thr = 0.5 gt_match_flag = [0, 0] det_match_flag = [0, 0] gt_dont_care_index = [] with pytest.raises(AssertionError): det_id...
def get_resnext_cifar(num_classes, blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): assert (((blocks - 2) % 9) == 0) layers = ([((blocks - 2) // 9)] * 3) channels_per_layers = [256, 512, 1024] init_block_channels = 64 ch...
.parametrize('marker1, marker2, expected', [('python_version >= "3" and sys_platform == "win32"', 'python_version >= "3" and sys_platform != "win32" and sys_platform != "linux"', 'python_version >= "3" and sys_platform != "linux"'), ('python_version >= "3.8" and python_version < "4.0" and sys_platform == "win32"', 'pyt...
def test_spa_python_numpy_physical_dst(expected_solpos, golden): times = pd.date_range(datetime.datetime(2003, 10, 17, 13, 30, 30), periods=1, freq='D', tz=golden.tz) ephem_data = solarposition.spa_python(times, golden.latitude, golden.longitude, pressure=82000, temperature=11, delta_t=67, atmos_refract=0.5667,...
class DeepMimicEnv(Env): def __init__(self, args, enable_draw): super().__init__(args, enable_draw) self._core = DeepMimicCore.cDeepMimicCore(enable_draw) rand_seed = np.random.randint(np.iinfo(np.int32).max) self._core.SeedRand(rand_seed) self._core.ParseArgs(args) s...
class TDBase(rhf.TDBase): _keys = {'cell'} def __init__(self, mf): rhf.TDBase.__init__(self, mf) self.cell = mf.cell def get_ab(self, mf=None): raise NotImplementedError def nuc_grad_method(self): raise NotImplementedError get_nto = rhf.TDBase.get_nto analyze = li...
def plot(t_plot, z_plot, t_slices, var_name, units, comsol_var_fun, dfn_var_fun, dfncc_var_fun, param, cmap='viridis'): (fig, ax) = plt.subplots(2, 2, figsize=(13, 7)) fig.subplots_adjust(left=0.15, bottom=0.1, right=0.95, top=0.95, wspace=0.4, hspace=0.8) comsol_var = comsol_var_fun(t=t_plot, z=z_plot) ...
class TestLDIFParser(unittest.TestCase): def _parse_records(self, ldif_string, ignored_attr_types=None, max_entries=0): ldif_file = StringIO(ldif_string) ldif_parser = ldif.LDIFRecordList(ldif_file, ignored_attr_types=ignored_attr_types, max_entries=max_entries) parser_method = getattr(ldif_...
def evaluation(myNet, test_loader, args): myNet.eval() num_correct = 0 num_total = 0 with torch.no_grad(): for (xs, ys) in test_loader: if torch.cuda.is_available(): (xs, ys) = (xs.cuda(), ys.cuda()) ypreds = myNet(xs) (_, preds) = torch.max(yp...
def create_motion_model_widgets() -> dict[(str, tuple[(str, QtWidgets.QWidget)])]: widgets = _create_sigma_widgets() accuracy = QtWidgets.QDoubleSpinBox() accuracy.setRange(0.1, 10) accuracy.setStepType(QtWidgets.QAbstractSpinBox.AdaptiveDecimalStepType) accuracy.setToolTip('Integration limits for c...
class Ensemble(nn.Module): def __init__(self, models, name=None): super(Ensemble, self).__init__() if (name is not None): self.name = name else: self.name = ('%s_ensemble' % models[0].name) self.models = nn.ModuleList(models) def forward(self, x): ...
def makeMetaChild(name, cfgDict): children = [] for (chName, chOpts) in cfgDict.items(): if (not isinstance(chOpts, dict)): ch = Parameter.create(name=chName, type=chName, value=chOpts) else: ch = Parameter.create(name=chName, **chOpts) _encounteredTypes.add(ch.ty...
class _march_rays(Function): _fwd(cast_inputs=torch.float32) def forward(ctx, n_alive, n_step, rays_alive, rays_t, rays_o, rays_d, bound, density_bitfield, C, H, near, far, align=(- 1), perturb=False, dt_gamma=0, max_steps=1024): if (not rays_o.is_cuda): rays_o = rays_o.cuda() if (no...
def _migrate_v17(preset: dict) -> dict: if (preset['game'] == 'prime1'): preset['configuration']['elevators']['excluded_teleporters'].append({'world_name': 'Impact Crater', 'area_name': 'Metroid Prime Lair', 'node_name': 'Teleporter to Credits'}) preset['configuration']['elevators']['excluded_telepo...
class Keynote(): id: ID title: str = strawberry.field(resolver=make_localized_resolver('title')) description: str = strawberry.field(resolver=make_localized_resolver('description')) slug: str = strawberry.field(resolver=make_localized_resolver('slug')) topic: Optional[Topic] speakers: List[Sched...
def test_multiple_constraints_on_root(package: ProjectPackage, solver: Solver, repo: Repository) -> None: package.add_dependency(Factory.create_dependency('foo', {'version': '^1.0', 'python': '^2.7'})) package.add_dependency(Factory.create_dependency('foo', {'version': '^2.0', 'python': '^3.7'})) foo15 = ge...
class TestPyfakefsTestCase(unittest.TestCase): def setUp(self): class TestTestCase(fake_filesystem_unittest.TestCase): def runTest(self): pass self.test_case = TestTestCase('runTest') def test_test_case_type(self): self.assertIsInstance(self.test_case, unittes...
class Parameterized(object): def __init__(self): self._cached_params = {} self._cached_param_dtypes = {} self._cached_param_shapes = {} self._cached_assign_ops = {} self._cached_assign_placeholders = {} def get_params_internal(self, **tags): raise NotImplementedEr...
class TestVersionSourceName(): def test_empty(self, isolation): with pytest.raises(ValueError, match='The `source` option under the `tool.hatch.version` table must not be empty if defined'): _ = HatchMetadata(isolation, {'version': {'source': ''}}, None).version.source_name def test_not_tabl...
class TrezorKeyStore(Hardware_KeyStore): hw_type = 'trezor' device = TREZOR_PRODUCT_KEY plugin: 'TrezorPlugin' def get_client(self, force_pair=True): return self.plugin.get_client(self, force_pair) def decrypt_message(self, sequence, message, password): raise UserFacingException(_('E...
_collator('multicrop_collator') def multicrop_collator(batch): assert ('data' in batch[0]), 'data not found in sample' assert ('label' in batch[0]), 'label not found in sample' data = [x['data'] for x in batch] labels = [torch.tensor(x['label']) for x in batch] data_valid = [torch.tensor(x['data_val...
def test_convert_variable_mixed_specificity(): type1 = TensorType(config.floatX, shape=(1, None, 3)) type2 = TensorType(config.floatX, shape=(None, 5, 3)) type3 = TensorType(config.floatX, shape=(1, 5, 3)) test_var1 = type1() test_var2 = type2() assert (type1.convert_variable(test_var2).type == ...
def all_gather(data): world_size = get_world_size() if (world_size == 1): return [data] buffer = pickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to('cuda') local_size = torch.tensor([tensor.numel()], device='cuda') size_list = [to...
class TestNodePosition(): def test_position_class() -> None: code = textwrap.dedent("\n class A: #\n ...\n\n class B(A): #\n pass\n\n class C: #\n '''Docstring'''\n\n class D: #\n ...\n\n class E: #\n def ...
() def mocked_stream_df() -> Mock: mock = Mock() mock.isStreaming = True mock.writeStream = mock mock.trigger.return_value = mock mock.outputMode.return_value = mock mock.option.return_value = mock mock.foreachBatch.return_value = mock mock.start.return_value = Mock(spec=StreamingQuery) ...
class CrossEntropyLIDLoss(_Loss): def __init__(self, output_size, label_smoothing): super().__init__() self.output_size = output_size self.padding_idx = (- 1) self.smoothing_value = label_smoothing self.confidence = (1.0 - label_smoothing) self.label_smoothing = label...
class ChamferLossMetric(TensorMetric): def __init__(self, chamfer_loss_params, name: str, reduce_op: Optional[Any]=None): super(ChamferLossMetric, self).__init__(name=name, reduce_op=reduce_op) self.loss = ChamferLoss(**chamfer_loss_params) def forward(self, pc_source: torch.Tensor, pc_target: t...
def get_leaf_jaw_positions_for_type(beam_limiting_device_position_sequences, rt_beam_limiting_device_type): leaf_jaw_positions = [] for sequence in beam_limiting_device_position_sequences: matching_type = [item for item in sequence if (item.RTBeamLimitingDeviceType == rt_beam_limiting_device_type)] ...
def test_show_nested_fixtures(pytester: Pytester, mode) -> None: pytester.makeconftest('\n import pytest\n (scope=\'session\')\n def arg_same():\n """session scoped fixture"""\n ') p = pytester.makepyfile('\n import pytest\n (scope=\'function\')\n def ...
def main(args): modelpath = (args.loadDir + args.loadModel) weightspath = (args.loadDir + args.loadWeights) print(('Loading model: ' + modelpath)) print(('Loading weights: ' + weightspath)) model = Net(NUM_CLASSES) model = torch.nn.DataParallel(model) if (not args.cpu): model = model...
class COCOClsDatasetMS(Dataset): def __init__(self, img_name_list_path, coco_root, label_file_path, scales, train=True, transform=None, gen_attn=False, unit=1): img_name_list_path = os.path.join(img_name_list_path, f"{('train' if (train or gen_attn) else 'val')}_id.txt") self.img_name_list = load_im...
class PartialFC(torch.nn.Module): _version = 1 def __init__(self, margin_loss: Callable, embedding_size: int, num_classes: int, sample_rate: float=1.0, fp16: bool=False): super(PartialFC, self).__init__() assert distributed.is_initialized(), 'must initialize distributed before create this' ...
class MetaRLScreener_pro(torch.nn.Module): def __init__(self, model, epochs=100, lr=0.01, log=True): super(MetaRLScreener_pro, self).__init__() self.model = model self.model.to(device) self.epochs = epochs self.lr = lr self.log = log self.temperature = 0.5 ...
class ZoneUpdateHandler(threading.Thread): def __init__(self, queue, handler): super(ZoneUpdateHandler, self).__init__() self.event = threading.Event() self.lock = threading.Lock() self.zones_to_update = set() self.zones_queues = Queue() self.queue_name = queue ...
def test_losses_models_ext_def(pvwatts_dc_pvwatts_ac_system, location, weather, mocker): m = mocker.spy(sys.modules[__name__], 'constant_losses') mc = ModelChain(pvwatts_dc_pvwatts_ac_system, location, dc_model='pvwatts', aoi_model='no_loss', spectral_model='no_loss', losses_model=constant_losses) mc.run_mo...
def test_mismatch_private_key(): (public_key_data, _) = generate_test_cert() (_, private_key_data) = generate_test_cert() private_key = NamedTemporaryFile(delete=True) private_key.write(private_key_data) private_key.seek(0) cert = load_certificate(public_key_data) with pytest.raises(KeyInval...
def retrieve_cdn_ip_networks(retrieve_new_data=False): cdn_ip_networks = [] cloudfront_dict = retrieve_amazon_cloudfront_ip_ranges(retrieve_new_data) cdn_ip_networks += cloudfront_dict['list_of_ipaddress_objects'] cloudflare_dict = retrieve_cloudflare_ip_networks(retrieve_new_data) cdn_ip_networks +...
class DKKKU2(FinTS3Segment): account = DataElementGroupField(type=Account2, _d='Kontoverbindung Auftraggeber') credit_card_number = DataElementField(type='an', _d='Kreditkartennummer') subaccount = DataElementField(type='an', required=False, _d='Subaccount?') date_start = DataElementField(type='dat', re...
def test_format_variety(): def _(fmt, matches): d = parse.extract_format(fmt, {'spam': 'spam'}) for k in matches: assert (d.get(k) == matches[k]) for t in '%obxegfdDwWsS': _(t, {'type': t}) _(('10' + t), {'type': t, 'width': '10'}) _('05d', {'type': 'd', 'width': ...
def project_onto_sector(operator, qubits, sectors): if (not isinstance(operator, QubitOperator)): raise TypeError('Input operator must be a QubitOperator.') if (not isinstance(qubits, (list, numpy.ndarray))): raise TypeError('Qubit input must be an array-like.') if (not isinstance(sectors, (...
def test_get_observation_histogram(requests_mock): requests_mock.get(f'{API_V1}/observations/histogram', json=SAMPLE_DATA['get_observation_histogram_month'], status_code=200) histogram = get_observation_histogram(interval='month', place_id=24, d1='2020-01-01', d2='2020-12-31') assert (len(histogram) == 12) ...
class TestOptimizerStateShardingIntegration(unittest.TestCase, TestOptimizer): def _maybe_destro_dist(): if dist.is_initialized(): logging.debug('Destroy previous torch dist process group') dist.destroy_process_group() def setUp(self): self._maybe_destro_dist() di...
def test_colorinterp_like_all(runner, path_4band_no_colorinterp, path_rgba_byte_tif, tmpdir): noci = str(tmpdir.join('test_colorinterp_like_all.tif')) rasterio.shutil.copy(path_4band_no_colorinterp, noci) result = runner.invoke(main_group, ['edit-info', noci, '--like', path_rgba_byte_tif, '--all']) asse...
class Train_config(): world_size = 0 mini_batch_size = 0 iter_per_epoch = 0 total_epoch = 0 warm_iter = 0 learning_rate = 0 momentum = 0 weight_decay = 0 lr_decay = [] log_dump_interval = 0 resume_weights = None init_weights = None model_dir = '' log_path = ''
def _populate(): for name in ('allowed_functions', 'bytecode_analysis', 'bytecode_transformation', 'codegen', 'config', 'convert_frame', 'debug_utils', 'eval_frame', 'exc', 'guards', 'logging', 'mutation_guard', 'optimizations', 'output_graph', 'profiler', 'replay_record', 'resume_execution', 'side_effects', 'skipf...
class Snapshot(Model): objects = SnapshotManager() project = models.ForeignKey('Project', related_name='snapshots', on_delete=models.CASCADE, null=True, verbose_name=_('Project'), help_text=_('The project this snapshot belongs to.')) title = models.CharField(max_length=256, verbose_name=_('Title'), help_tex...
def loadUtilitySpectra(): global am_zero_wavelength, am_zero_irradiance, waterspectra, ozonespectra, uniformgasspectra spctra = numpy.loadtxt(os.path.join(this_dir, 'SPCTRAL_si_units.txt'), unpack=True) (am_zero_wavelength, am_zero_irradiance, waterspectra, ozonespectra, uniformgasspectra) = spctra wate...
class LoginForm(Form): def __init__(self, view): super().__init__(view, 'login') self.use_layout(FormLayout()) accounts = AccountManagementInterface.for_current_session() if self.exception: self.layout.add_alert_for_domain_exception(self.exception) self.layout.add...
def main(): opts = parse_args() if ((not opts.overwrite) and isfile(opts.out_path)): return mkdir2(dirname(opts.out_path)) time_info = pickle.load(open(opts.time_info, 'rb')) if (opts.method_type == 'det'): rt_samples = time_info['runtime_all'] rt_dist = {'type': 'empirical',...
class Element(BaseElement): def children(self): return [self.__class__(el) for el in self._js.children] def append(self, child): if isinstance(child, JsProxy): return self.append(Element(child)) elif isinstance(child, Element): self._js.appendChild(child._js) ...
class FusedAdamV1(torch.optim.Optimizer): def __init__(self, params, lr=0.001, bias_correction=True, betas=(0.9, 0.999), eps=1e-08, eps_inside_sqrt=False, weight_decay=0.0, max_grad_norm=0.0, amsgrad=False): global fused_adam_cuda import importlib fused_adam_cuda = importlib.import_module('f...
def convert(comp_type: str, src_file: Path, dest_dir: Path): dest_dir = Path(dest_dir) dest_dir.mkdir(exist_ok=True) dpr_state = DPRState.from_type(comp_type, src_file=src_file) model = dpr_state.load_dpr_model() model.save_pretrained(dest_dir) model.from_pretrained(dest_dir)
class TestExitCode(unittest.TestCase): def setUp(self): sys.path.append('.') from mprof import run_action self.run_action = run_action def test_exit_code_success(self): s = '1+1' tmpfile = tempfile.NamedTemporaryFile('w', suffix='.py') with tmpfile as ofile: ...
def decode_onion_error(error_packet: bytes, payment_path_pubkeys: Sequence[bytes], session_key: bytes) -> (OnionRoutingFailureMessage, int): (decrypted_error, sender_index) = _decode_onion_error(error_packet, payment_path_pubkeys, session_key) failure_msg = get_failure_msg_from_onion_error(decrypted_error) ...
def handle_style(book, data): if (not book.formatting_info): return blah = (DEBUG or (book.verbosity >= 2)) bv = book.biff_version (flag_and_xfx, built_in_id, level) = unpack('<HBB', data[:4]) xf_index = (flag_and_xfx & 4095) if ((data == b'\x00\x00\x00\x00') and ('Normal' not in book.st...
class TestCDPSession(BaseTestCase): async def test_create_session(self): client = (await self.page.target.createCDPSession()) (await client.send('Runtime.enable')) (await client.send('Runtime.evaluate', {'expression': 'window.foo = "bar"'})) foo = (await self.page.evaluate('window.fo...
(st.sets(text)) def test_map(tmpdir_factory, keys): trie = marisa_trie.Trie(keys) dirname = f'{str(uuid4())}_' path = str(tmpdir_factory.mktemp(dirname).join('trie.bin')) trie.save(path) data = open(path, 'rb').read() trie2 = marisa_trie.Trie() trie2.map(data) for key in keys: as...
class MedrxivClusteringP2P(AbsTaskClustering): def description(self): return {'name': 'MedrxivClusteringP2P', 'hf_hub_name': 'mteb/medrxiv-clustering-p2p', 'description': 'Clustering of titles+abstract from medrxiv. Clustering of 10 sets, based on the main category.', 'reference': ' 'type': 'Clustering', 'c...
def test_in_solver(): opt = {'method': 'adams', 'store_states': True, 'atol': 1} solver = qutip.SESolver(qutip.qeye(1), options=opt) adams = qutip.integrator.IntegratorScipyAdams lsoda = qutip.integrator.IntegratorScipylsoda bdf = qutip.integrator.IntegratorScipyBDF assert (solver.options['store...
def test_rebuild_system_tpm(s): node0_tpm = ExplicitTPM(np.array([[0, 1], [0, 0]])) node1_tpm = ExplicitTPM(np.array([[0, 1]])) node_tpms = [node0_tpm, node1_tpm] answer = ExplicitTPM(np.array([[[0, 0], [1, 1]], [[0, 0], [0, 1]]])) assert macro.rebuild_system_tpm(node_tpms).array_equal(answer) n...
class Optimizer(object): def __init__(self, optimizer, learning_rate, learning_rate_decay_fn=None, max_grad_norm=None): self._optimizer = optimizer self._learning_rate = learning_rate self._learning_rate_decay_fn = learning_rate_decay_fn self._max_grad_norm = (max_grad_norm or 0) ...
def get_valid_dataloader(musdb_root, is_wav, filed_mode, n_fft, hop_length, num_frame, batch_size=4, num_workers=1, pin_memory=True, target_names=None, cache_mode=True, dev_mode=False) -> DataLoader: if filed_mode: musdb_valid = FiledMusdbValidSet(musdb_root, is_wav, n_fft=n_fft, hop_length=hop_length, num_...
class MockReadline(): def __init__(self): self.l_buffer = lineobj.ReadLineTextBuffer('') self._history = history.LineHistory() def add_history(self, line): self._history.add_history(lineobj.TextLine(line)) def _print_prompt(self): pass def _bell(self): pass de...
class TestGenericReporting(): def test_collect_fail(self, pytester: Pytester, option) -> None: pytester.makepyfile('import xyz\n') result = pytester.runpytest(*option.args) result.stdout.fnmatch_lines(['ImportError while importing*', '*No module named *xyz*', '*1 error*']) def test_maxfa...