code
stringlengths
281
23.7M
.mosaiqdb def test_session_offsets_for_site(connection): mock_patient_ident_df = mocks.create_mock_patients() mock_site_df = mocks.create_mock_treatment_sites(mock_patient_ident_df) mock_txfield_df = mocks.create_mock_treatment_fields(mock_site_df) mocks.create_mock_treatment_sessions(mock_site_df, mock...
class EmptyCudaCache(Callback): def __init__(self, step_interval: int) -> None: self._step_interval = step_interval def on_train_step_end(self, state: State, unit: TTrainUnit) -> None: total_num_steps_completed = unit.train_progress.num_steps_completed if (state.entry_point == EntryPoint...
class TestOverrideIniArgs(): .parametrize('name', 'setup.cfg tox.ini pytest.ini'.split()) def test_override_ini_names(self, pytester: Pytester, name: str) -> None: section = ('[pytest]' if (name != 'setup.cfg') else '[tool:pytest]') pytester.path.joinpath(name).write_text(textwrap.dedent('\n ...
class InferenceContext(): __slots__ = ('path', 'lookupname', 'callcontext', 'boundnode', 'extra_context', 'constraints', '_nodes_inferred') max_inferred = 100 def __init__(self, path: (set[tuple[(nodes.NodeNG, (str | None))]] | None)=None, nodes_inferred: (list[int] | None)=None) -> None: if (nodes_...
(optionalhook=True) def pytest_selenium_runtest_makereport(item, report, summary, extra): provider = BrowserStack() if (not provider.uses_driver(item.config.getoption('driver'))): return passed = (report.passed or (report.failed and hasattr(report, 'wasxfail'))) session_id = item._driver.session...
class ResNet(nn.Module): def __init__(self, block, layers, n_channels=3, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None, drop_rate=0.0): super(ResNet, self).__init__() self.drop_rate = drop_rate if (norm_layer is N...
class PoseEstimationEvaluator(chainer.training.extensions.Evaluator): def comm(self): if (not hasattr(self, '_comm')): self._comm = None return self._comm def comm(self, value): self._comm = value def evaluate(self): iterator = self._iterators['main'] eval...
def get_args(driver=None, download_dir=None, download_ftypes=None, firefox_pref=None, firefox_prof_dir=None, remote_url=None, executable=None, headless=False, driver_kwargs=None): kwargs = {} firefox_profile_preferences = dict({'browser.download.folderList': 2, 'browser.download.manager.showWhenStarting': False...
def get_parameter_groups(model): no_weight_decay_names = ['bias', 'normalization', 'label_embeddings'] parameter_groups = [{'params': [param for (name, param) in model.named_parameters() if (not any(((no_weight_decay_name in name) for no_weight_decay_name in no_weight_decay_names)))]}, {'params': [param for (na...
def get_baseline_dict_entry(tag): if (not isinstance(tag, pydicom.tag.BaseTag)): tag = pydicom.tag.Tag(tag) try: return get_baseline_dicom_dict()[tag] except KeyError: if (not tag.is_private): mask_x = pydicom.datadict.mask_match(tag) if mask_x: ...
class SwaggerMaskHeaderTest(object): def test_marshal_with_expose_mask_header(self, app, client): api = Api(app) model = api.model('Test', {'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean}) ('/test/') class TestResource(Resource): _with(model) ...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._norm...
def _install_one(requirement, cmd, pkgname, modulename): cmd.args = [requirement] cmd.ensure_finalized() cmd.run() target = cmd.install_dir dest_path = glob.glob(os.path.join(target, (pkgname + '*.egg'))) assert dest_path assert os.path.exists(os.path.join(dest_path[0], pkgname, modulename))
def grid_partition(x, grid_size: List[int]): (B, H, W, C) = x.shape _assert(((H % grid_size[0]) == 0), f'height {H} must be divisible by grid {grid_size[0]}') _assert(((W % grid_size[1]) == 0), '') x = x.view(B, grid_size[0], (H // grid_size[0]), grid_size[1], (W // grid_size[1]), C) windows = x.per...
def fetch_data_table(api_key, show_progress, retries): for _ in range(retries): try: if show_progress: log.info('Downloading WIKI metadata.') metadata = pd.read_csv(format_metadata_url(api_key)) table_url = metadata.loc[(0, 'file.link')] if sho...
def replacePassword(actionData, password): if (actionData['TYPE'] == 'COMMANDS'): for i in range(len(actionData['COMMANDS'])): for j in range(len(actionData['COMMANDS'][i])): while ('VM_PASSWORD' in actionData['COMMANDS'][i][j]): actionData['COMMANDS'][i][j] =...
class FortuneThread(QThread): newFortune = pyqtSignal(str) error = pyqtSignal(int, str) def __init__(self, parent=None): super(FortuneThread, self).__init__(parent) self.quit = False self.hostName = '' self.cond = QWaitCondition() self.mutex = QMutex() self.po...
class FakeResponse(web.Response): headers = CIMultiDict({'content-type': 'application/json; charset=utf-8', 'x-ratelimit-limit': '10', 'x-ratelimit-remaining': '5', 'x-ratelimit-reset': '1'}) url = 'test URL' def __init__(self, data=None, **kwargs): super().__init__(**kwargs) self._data = da...
def test_colorscheme_gentoo_workaround(config_stub, gentoo_versions): config_stub.val.colors.webpage.preferred_color_scheme = 'dark' darkmode_settings = darkmode.settings(versions=gentoo_versions, special_flags=[]) assert (darkmode_settings['blink-settings'] == [('preferredColorScheme', '0')])
class ExampleDataset(Dataset): def __init__(self): self.index = 0 self.eval_result = [1, 4, 3, 7, 2, (- 3), 4, 6] def __getitem__(self, idx): results = dict(x=torch.tensor([1])) return results def __len__(self): return 1 _autospec def evaluate(self, results, l...
(hookwrapper=True) def pytest_fixture_setup(fixturedef: FixtureDef, request: SubRequest) -> Optional[object]: if (fixturedef.argname == 'event_loop'): _add_finalizers(fixturedef, _close_event_loop, _restore_event_loop_policy(asyncio.get_event_loop_policy()), _provide_clean_event_loop) outcome = (yie...
_REGISTRY.register() class CIFAR10C(DatasetBase): dataset_dir = '' domains = ['cifar10', 'cifar10_c'] def __init__(self, cfg): root = osp.abspath(osp.expanduser(cfg.DATASET.ROOT)) self.dataset_dir = root self.check_input_domains(cfg.DATASET.SOURCE_DOMAINS, cfg.DATASET.TARGET_DOMAINS)...
_deepspeed _torch_gpu class TestDeepSpeedModelZoo(TestCasePlus): def get_task_cmd(self, task, stage): if (task not in task_cmds): raise ValueError(f"don't know of task {task}, have {task_cmds.keys()}") cmd = task_cmds[task] args_ds = f'--deepspeed {self.test_file_dir_str}/ds_conf...
def test_set_inf_nodata(tmpdir): dst_path = str(tmpdir.join('lol.tif')) with rasterio.open('tests/data/RGB.byte.tif') as src: meta = src.meta meta['dtype'] = 'float32' meta['nodata'] = float('inf') with rasterio.open(dst_path, 'w', **meta) as dst: assert numpy.isinf(d...
class TestPruningLRUProxiedImagesToAllowBlobUpload(): upstream_registry = 'docker.io' upstream_repository = 'library/busybox' orgname = 'proxy-cache' repository = f'{orgname}/{upstream_repository}' tag = '1.35.0' (autouse=True) def setup(self, app): self.user = get_user('devtable') ...
def test_mouse_press_event_small_item_inside_handle_free_center(view, item): view.scene.addItem(item) item.setSelected(True) event = MagicMock() event.pos.return_value = QtCore.QPointF(10, 10) event.button.return_value = Qt.MouseButton.LeftButton with patch('PyQt6.QtWidgets.QGraphicsPixmapItem.m...
def accuracy(output, target, topk=(1,)): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape((- 1)).float().sum(0, ke...
.parametrize('repeat', [1, 2]) .parametrize('preset_name', [None, 'Starter Preset']) .parametrize('no_retry', [False, True]) def test_generate_logic(no_retry: bool, preset_name: (str | None), repeat: int, mocker: pytest_mock.MockerFixture, preset_manager): layout_description = MagicMock() mock_run = mocker.patc...
def test_mlp_grad(test, device): results = load_golden() torch_weights = results['weights'] torch_weights_grad = results['weights_grad'] torch_bias = results['bias'] torch_bias_grad = results['bias_grad'] torch_x = results['x'].T torch_x_grad = results['x_grad'].T torch_y = results['y']....
def test_models(): for _ in range(3): clf = CacheClassifier('clf', SGDClassifier(loss='log')) check_classifier(clf, has_staged_pp=False, has_importances=False) reg = CacheRegressor('reg', SGDRegressor()) check_regression(reg, has_staged_predictions=False, has_importances=False) c...
def _lru_cache_with_config_path(func: Callable): _cache() def _call_without_config_path_wrapper(sensor_name, _): return func(sensor_name) def _add_config_path_wrapper(sensor_name: str): config_path = satpy.config.get('config_path') config_path = tuple(config_path) return _cal...
def update_best_score(new_score, old_score, is_higher_better): if (not old_score): (score, updated) = (new_score, True) elif is_higher_better: score = max(new_score, old_score) updated = (new_score > old_score) else: score = min(new_score, old_score) updated = (new_sc...
class SponsorshipPackageTests(TestCase): def setUp(self): self.package = baker.make('sponsors.SponsorshipPackage') self.package_benefits = baker.make(SponsorshipBenefit, _quantity=3) self.package.benefits.add(*self.package_benefits) def test_has_user_customization_if_benefit_from_other_p...
class ImageNet100(data.Dataset): def __init__(self, data_dir, dataidxs=None, train=True, transform=None, target_transform=None, download=False, client_num=100, alpha=None): self.dataidxs = dataidxs self.client_num = client_num self.train = train self.transform = transform sel...
class WideResNet1(nn.Module): def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0): super(WideResNet1, self).__init__() nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)] assert (((depth - 4) % 6) == 0) n = ((depth - 4) / 6) block ...
class FastAIMixedOptim(OptimWrapper): def create(cls, opt_func, lr, layer_groups, model, flat_master=False, loss_scale=512.0, **kwargs): opt = OptimWrapper.create(opt_func, lr, layer_groups, **kwargs) (opt.model_params, opt.master_params) = get_master(layer_groups, flat_master) opt.flat_mast...
def majority_vote(nsqls: List, pred_answer_list: List, allow_none_and_empty_answer: bool=False, allow_error_answer: bool=False, answer_placeholder: Union[(str, int)]='<error|empty>', vote_method: str='prob', answer_biased: Union[(str, int)]=None, answer_biased_weight: float=None): def _compare_answer_vote_simple(a,...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1, drop=False, block_size=4): super(Bottleneck, self).__init__() self.drop = drop self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) ...
def test_new_project_does_not_fail_pre_commit(cwd, pre_commit, putup): name = 'my_project' run(f'{putup} --pre-commit --dsproject -p my_package --namespace my.ns {name}') with cwd.join(name).as_cwd(): try: run(f'{pre_commit} install') run(f'{pre_commit} run --all') ex...
_infer_shape _useless _canonicalize _specialize _rewriter([Subtensor]) def local_subtensor_of_alloc(fgraph, node): if (not isinstance(node.op, Subtensor)): return False u = node.inputs[0] if (u.owner is None): return False if (not isinstance(u.owner.op, Alloc)): return False ...
def load_model(model_version=None): currentDirectory = os.getcwd() if (model_version == 'chembl'): model_name = 'chembl_pretrained' elif (model_version == 'moses'): model_name = 'moses_pretrained' elif (model_version == 'new'): model_name = 'new_model' else: print('No...
class MDConfig(dict): def __init__(self, config_name='default'): self.update(DEFAULT_CONFIG) self.set_configs(config_name) def set_configs(self, config_name='default'): configs = getattr(settings, 'MDEDITOR_CONFIGS', None) if configs: if isinstance(configs, dict): ...
def add_instructions(opts: ScaffoldOpts, content: AbstractContent, file_op: FileOp) -> ResolvedLeaf: text = structure.reify_content(content, opts) if (text is not None): i = text.find(INSERT_AFTER) assert (i > 0), f'''{INSERT_AFTER!r} not found in README template: {text}''' j = (i + len(...
class SsoCharacterMgmt(AuxiliaryFrame): def __init__(self, parent): super().__init__(parent, id=wx.ID_ANY, title=_t('SSO Character Management'), pos=wx.DefaultPosition, size=wx.Size(550, 250), resizeable=True) self.mainFrame = parent mainSizer = wx.BoxSizer(wx.HORIZONTAL) self.lcChar...
class SCPIndexDataset(torch.utils.data.Dataset): def __init__(self, scp_path_list, concat=4, shared_object=None): self.scp_path_list = scp_path_list self._sizes = len(self.scp_path_list) self._dtype = torch.float32 self.concat = concat if (shared_object is not None): ...
def test_keep_alive_return_value(capture): n_inst = ConstructorStats.detail_reg_inst() with capture: p = m.Parent() assert (capture == 'Allocating parent.') with capture: p.returnChild() assert (ConstructorStats.detail_reg_inst() == (n_inst + 1)) assert (capture == '\n ...
def test_fermi_hubbard_2x2_spinful_phs(): hubbard_model = fermi_hubbard(2, 2, 1.0, 4.0, chemical_potential=0.5, magnetic_field=0.3, spinless=False, particle_hole_symmetry=True) assert (str(hubbard_model).strip() == '\n4.0 [] +\n-2.8 [0^ 0] +\n4.0 [0^ 0 1^ 1] +\n-1.0 [0^ 2] +\n-1.0 [0^ 4] +\n-2.2 [1^ 1] +\n-1.0 ...
def training_loop(run_dir='.', dataset_kwargs={}, data_loader_kwargs={}, network_kwargs={}, loss_kwargs={}, optimizer_kwargs={}, augment_kwargs=None, seed=0, batch_size=512, batch_gpu=None, total_kimg=200000, ema_halflife_kimg=500, ema_rampup_ratio=0.05, lr_rampup_kimg=10000, loss_scaling=1, kimg_per_tick=50, snapshot_...
def test_alternation_ab(a: FixtureA, b: FixtureB) -> None: altAB = (a | b) assert (not altAB.accepts('')) assert altAB.accepts('a') assert altAB.accepts('b') assert (not altAB.accepts('aa')) assert (not altAB.accepts('ab')) assert (not altAB.accepts('ba')) assert (not altAB.accepts('bb')...
class KnownValues(unittest.TestCase): def test_h2_gamma(self): mf = pscf.KRHF(cell).rs_density_fit() mf.kernel() self.assertAlmostEqual(mf.e_tot, (- 1.), 7) def test_h2_kpt1_shiftedcenter(self): kpts = cell.make_kpts([1, 1, 1], scaled_center=scaled_center) mf = pscf.KRHF(...
def Increment(new, mirror, incpref, inc_time=None): log.Log('Incrementing mirror file {mf}'.format(mf=mirror), log.INFO) if (((new and new.isdir()) or mirror.isdir()) and (not incpref.lstat())): incpref.mkdir() if (not mirror.lstat()): incrp = _make_missing_increment(incpref, inc_time) e...
class EvoNorm2dS1(nn.Module): def __init__(self, num_features, groups=32, group_size=None, apply_act=True, act_layer=None, eps=1e-05, **_): super().__init__() act_layer = (act_layer or nn.SiLU) self.apply_act = apply_act if ((act_layer is not None) and apply_act): self.ac...
def _get_weight_tensor_transpose_reshape(conv_linear: LayerType) -> libpymo.TensorParams(): weight_tensor = libpymo.TensorParams() weight = conv_linear.get_weights()[0] shape = weight.shape if isinstance(conv_linear, tf.keras.layers.DepthwiseConv2D): weight = np.transpose(weight, (2, 3, 0, 1)) ...
class SPSA(Optimizer): _C0 = ((2 * np.pi) * 0.1) _OPTIONS = ['save_steps', 'last_avg'] def __init__(self, maxiter: int=1000, save_steps: int=1, last_avg: int=1, c0: float=_C0, c1: float=0.1, c2: float=0.602, c3: float=0.101, c4: float=0, skip_calibration: bool=False, max_trials: Optional[int]=None) -> None:...
def log_events(klass: Type[QObject]) -> Type[QObject]: old_event = klass.event (old_event) def new_event(self: Any, e: QEvent) -> bool: log.misc.debug('Event in {}: {}'.format(utils.qualname(klass), qenum_key(QEvent, e.type(), klass=QEvent.Type))) return old_event(self, e) klass.event = ...
class Project(MPTTModel, Model): objects = ProjectManager() parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.DO_NOTHING, related_name='children', db_index=True, verbose_name=_('Parent project'), help_text=_('The parent project of this project.')) user = models.ManyToManyField(settings...
def collate_fn_all_des(batch): (obj_point_list, obj_label_list) = ([], []) rel_label_list = [] (edge_indices, descriptor) = ([], []) count = 0 for i in batch: obj_point_list.append(i[0]) obj_label_list.append(i[2]) rel_label_list.append(i[3]) edge_indices.append((i[4]...
class TestGaussianProcess(GaussianProcessTestCase): precompute_gaussian_process_data = True (autouse=True, scope='class') def base_setup(cls): numpy.random.seed(8794) super(TestGaussianProcess, cls).base_setup() def test_sample_point_from_gp(self): point_one = SamplePoint([0.0, 1...
def test_interactive_with_dependencies_and_no_selection(tester: CommandTester, repo: TestRepository) -> None: repo.add_package(get_package('django-pendulum', '0.1.6-pre4')) repo.add_package(get_package('pendulum', '2.0.0')) repo.add_package(get_package('pytest', '3.6.0')) inputs = ['my-package', '1.2.3'...
def _label_nodes_by_identity(intralayer_graphs, interlayer_edges, layer_vec): namedict = {} backedges = {} for e in interlayer_edges: (ei, ej) = (e[0], e[1]) if (ei < ej): backedges[ej] = (backedges.get(ej, []) + [ei]) else: backedges[ei] = (backedges.get(ei, ...
class ControlTabs(QtWidgets.QTabWidget): def __init__(self, *args, m=None, **kwargs): super().__init__(*args, **kwargs) self.m = m self.tab_compare = CompareTab(m=self.m) self.tab_open = OpenFileTabs(m=self.m) self.tab_edit = ArtistEditor(m=self.m) self.addTab(self.ta...
class TestHuffman(): def test_request_huffman_decoder(self): assert (decode_huffman(b'\xf1\xe3\xc2\xe5\xf2:k\xa0\xab\x90\xf4\xff') == b'www.example.com') assert (decode_huffman(b'\xa8\xeb\x10d\x9c\xbf') == b'no-cache') assert (decode_huffman(b'%\xa8I\xe9[\xa9}\x7f') == b'custom-key') ...
def _parse_path(path): if isinstance(path, _Path): return path elif (pathlib and isinstance(path, pathlib.PurePath)): return _ParsedPath(path.as_posix(), None, None) elif isinstance(path, str): if ((sys.platform == 'win32') and re.match('^[a-zA-Z]\\:', path)): if pathlib:...
def hydra_init(cfg_name='config') -> None: cs = ConfigStore.instance() cs.store(name=cfg_name, node=FairseqConfig) for k in FairseqConfig.__dataclass_fields__: v = FairseqConfig.__dataclass_fields__[k].default try: cs.store(name=k, node=v) except BaseException: ...
def init_eigenstate_visualization(eigenstates): if (eigenstates.type == 'SingleParticle1D'): return VisualizationSingleParticle1D(eigenstates) elif (eigenstates.type == 'SingleParticle2D'): return VisualizationSingleParticle2D(eigenstates) elif (eigenstates.type == 'SingleParticle3D'): ...
class JobList(ListView): template_name = 'jobs_list.html' context_object_name = 'jobs' paginate_by = 20 paginator_class = DiggPaginator model = JobItem def get_queryset(self): jobs = super().get_queryset() search = self.request.GET.get('q') if search: filters ...
class FragDB(): def __init__(self, metadata, options, db, c): self.metadata = metadata self.db = db self.c = c self.options = options def get(self, id): obj = select_fragment_record_by_title(self.c, id) if (obj is not None): return obj return s...
def multiplicative_rlattention(queries, keys, values, bias, sample, keep_prob=None, name=None, epsilon=1e-06): with tf.name_scope(name, default_name='multiplicative_rlattention', values=[queries, keys, values, bias]): logits = tf.matmul(queries, keys, transpose_b=True) if (bias is not None): ...
class SmartBulb(SmartDevice): LIGHT_SERVICE = 'smartlife.iot.smartbulb.lightingservice' SET_LIGHT_METHOD = 'transition_light_state' emeter_type = 'smartlife.iot.common.emeter' def __init__(self, host: str, *, config: Optional[DeviceConfig]=None, protocol: Optional[TPLinkProtocol]=None) -> None: ...
def load_and_covnert_case(input_image: str, input_seg: str, output_image: str, output_seg: str, min_component_size: int=50): seg = io.imread(input_seg) assert ((np.unique(seg)[0] == 0) and ((np.unique(seg)[1] == 255) or (np.unique(seg)[1] == 1))) seg[(seg == 255)] = 1 image = io.imread(input_image) ...
def transform_import(builder: IRBuilder, node: Import) -> None: if node.is_mypy_only: return if (not node.is_top_level): globals = builder.load_globals_dict() for (mod_id, as_name) in node.ids: builder.gen_import(mod_id, node.line) (globals_id, globals_name) = imp...
class NLLModel(nn.Module): def __init__(self, args, config): super().__init__() self.args = args self.models = nn.ModuleList() self.device = [(i % args.n_gpu) for i in range(args.n_model)] self.loss_fnt = nn.CrossEntropyLoss() for i in range(args.n_model): ...
def total_ordering(cls): assert ('__eq__' in cls.__dict__) assert ('__lt__' in cls.__dict__) cls.__le__ = (lambda self, other: ((self == other) or (self < other))) cls.__gt__ = (lambda self, other: (not ((self == other) or (self < other)))) cls.__ge__ = (lambda self, other: (not (self < other))) ...
class IndentLoggerAdapter(logging.LoggerAdapter): def process(self, msg, kwargs): if get_yf_logger().isEnabledFor(logging.DEBUG): i = (' ' * self.extra['indent']) if (not isinstance(msg, str)): msg = str(msg) msg = '\n'.join([(i + m) for m in msg.split('\n...
def is_protocol_implementation(left: Instance, right: Instance, proper_subtype: bool=False, class_obj: bool=False, skip: (list[str] | None)=None, options: (Options | None)=None) -> bool: assert right.type.is_protocol if (skip is None): skip = [] type_state.record_protocol_subtype_check(left.type, ri...
def parse_args(): parser = argparse.ArgumentParser(description='Calculate the prototype for trained model') parser.add_argument('config', help='trained model config file path') parser.add_argument('checkpoint', help='checkpoint file path') parser.add_argument('--round', type=int, default=1, help='save d...
class TestPDFJSVersion(): def test_not_found(self, mocker): mocker.patch('qutebrowser.utils.version.pdfjs.get_pdfjs_res_and_path', side_effect=pdfjs.PDFJSNotFound('/build/pdf.js')) assert (version._pdfjs_version() == 'no') def test_unknown(self, monkeypatch): monkeypatch.setattr('qutebro...
def _serialize(value: Any, memo: Optional[SerializeMemoizer]) -> Any: if isinstance(value, Serialize): return value.serialize(memo) elif isinstance(value, list): return [_serialize(elem, memo) for elem in value] elif isinstance(value, frozenset): return list(value) elif isinstanc...
def test_unmeargeable_dimshuffles(): x = pt.random.dirichlet(np.ones((3,)), size=(4, 2)) y = x.dimshuffle((0, 2, 1)) z = pt.cumsum(y, axis=(- 2)) w = z.dimshuffle((1, 0, 2)) w_vv = w.clone() with pytest.raises(RuntimeError, match='could not be derived'): conditional_logp({w: w_vv})
_tag() def render_lang_template(template_name, escape_html=False): loc = to_locale(get_language()) lst = [(((template_name + '_') + loc) + '.html'), (((template_name + '_') + settings.LANGUAGES[0][0]) + '.html'), (template_name + '_en.html'), (template_name + '.html')] for el in lst: try: ...
def run_cmd(cmd): dsz.ui.Echo('Searching for files') dsz.control.echo.Off() dsz.cmd.Run(cmd, dsz.RUN_FLAG_RECORD) dsz.control.echo.On() try: dir_path = dsz.cmd.data.Get('DirItem::path', dsz.TYPE_STRING) dsz.ui.Echo('Found {0} archive(s)'.format(str(len(dir_path)))) return dir...
def _parse_pvgis_hourly_csv(src, map_variables): inputs = {} inputs['latitude'] = float(src.readline().split(':')[1]) inputs['longitude'] = float(src.readline().split(':')[1]) inputs['elevation'] = float(src.readline().split(':')[1]) inputs['radiation_database'] = src.readline().split(':')[1].strip(...
class RNNAgent(nn.Module): def __init__(self, input_shape, args): super(RNNAgent, self).__init__() self.args = args self.fc1 = nn.Linear(input_shape, args.hidden_dim) if self.args.use_rnn: self.rnn = nn.GRUCell(args.hidden_dim, args.hidden_dim) else: s...
def test(val_loader, criterion, val_text_features, clip_model, clip_preprocess, clip_device): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() end = time.time() bar = Bar('Processing', max=len(val_loader)) avg_accuracy_per_class = None ...
class _PtqSession(_EvalSession): def __init__(self, *args, **kwargs): super(_PtqSession, self).__init__(*args, **kwargs) self._ptq_result = None def ptq_result(self) -> PtqResult: if (self._ptq_result is None): raise RuntimeError return self._ptq_result def set_pt...
class Tformat_locale(TestCase): def test_format_int_locale(self): assert isinstance(util.format_int_locale(1024), str) def test_format_float_locale(self): assert isinstance(util.format_float_locale(1024.1024), str) def test_format_time_seconds(self): assert isinstance(util.format_tim...
def compile_rule(filename): if (filename.startswith('{') and filename.endswith('}')): return re.compile(filename[1:(- 1)]).match with open(filename) as f: return re.compile((('(:?' + ''.join('|'.join((i.strip() for i in f if (i.strip() and (not i.startswith('#'))))))) + ')$')).match
class GDN(nn.Module): def __init__(self, in_channels, inverse=False, beta_min=1e-06, gamma_init=0.1): super().__init__() beta_min = float(beta_min) gamma_init = float(gamma_init) self.inverse = bool(inverse) self.beta_reparam = NonNegativeParametrizer(minimum=beta_min) ...
class Callback(object): def __init__(self): self.validation_data = None def set_params(self, params): self.params = params def set_model(self, model): self.model = model def on_epoch_begin(self, epoch, logs=None): pass def on_epoch_end(self, epoch, logs=None): ...
class SyntaxHighlighting(object): _styleElements = Manager.getStyleElementDescriptionsForAllParsers() def parser(self): try: return self.__parser except AttributeError: return None _option(None) def setParser(self, parserName=''): self.__parser = Manager.g...
class AdditionsExportAll(ContextMenuUnconditional): visibilitySetting = 'additionsCopyPaste' def __init__(self): self.mainFrame = gui.mainFrame.MainFrame.getInstance() self.viewSpecMap = {'droneItemMisc': (_t('Drones'), (lambda cw: cw.drones), exportDrones), 'fighterItemMisc': (_t('Fighters'), (...
def test_manual_response_limits(): out = manual_response.plot() axs = ct.get_plot_axes(out) for i in range(manual_response.noutputs): for j in range(1, manual_response.ninputs): assert (axs[((i * 2), 0)].get_ylim() == axs[((i * 2), j)].get_ylim()) assert (axs[(((i * 2) + 1), ...
def LoadObjectInfos(file): with open(file) as f: contents = f.read().rstrip().splitlines() data = [] attrs = {} struct = {} (name, uuid) = contents.pop(0).split(' : ') for line in contents: if ('#' in line): quotes = 0 for (i, char) in enumerate(line): ...
class ManagedCollisionModule(nn.Module): def __init__(self, device: torch.device) -> None: super().__init__() self._device = device def preprocess(self, features: Dict[(str, JaggedTensor)]) -> Dict[(str, JaggedTensor)]: pass def device(self) -> torch.device: return self._devi...
class ElasticConditionParser(BaseConditionParser): def build_condition(self, and_subfilters: Optional[List[Any]], or_subfilters: Optional[List[Any]]) -> Optional[Any]: return {'bool': {'must': and_subfilters, 'should': or_subfilters}} def build_exact_match_filter(self, field_name: str, value: FieldValue...
class AbstractBasicLexer(Lexer): terminals_by_name: Dict[(str, TerminalDef)] def __init__(self, conf: 'LexerConf', comparator=None) -> None: ... def next_token(self, lex_state: LexerState, parser_state: Any=None) -> Token: ... def lex(self, state: LexerState, parser_state: Any) -> Iterat...
def mod_import(module): if (not module): return None if isinstance(module, types.ModuleType): return module if (module.endswith('.py') and os.path.exists(module)): return mod_import_from_path(module) try: return importlib.import_module(module) except ImportError: ...
class TerminalIniter(IniterBase): def prompt_text(self, prompt, default, validator, retry_msg='Try again.'): if (default is not None): p = '{} [{}]: '.format(prompt, default) else: p = (prompt + ': ') while True: response = input(p) if ((respon...
def get_filter_args_for_specific_event_from_channel(token_network_address: TokenNetworkAddress, channel_identifier: ChannelID, event_name: str, contract_manager: ContractManager, from_block: BlockIdentifier=GENESIS_BLOCK_NUMBER, to_block: BlockIdentifier=BLOCK_ID_LATEST) -> FilterParams: event_abi = contract_manage...
def edit_rest(file_, key): key = ('description' if key.strip().startswith('d') else 'summary') if file_.startswith(URL_REPO): file_ = file_.replace(URL_REPO, '') with open(file_) as fp: data = json.load(fp) data[key] = get_edited_text(data[key]) with open(file_, 'w') as fp: j...