code
stringlengths
281
23.7M
def _row_column_layout(content, flow, size, scope=None, position=OutputPosition.BOTTOM) -> Output: if (not isinstance(content, (list, tuple, OutputList))): content = [content] if (not size): size = ' '.join((('1fr' if (c is not None) else '10px') for c in content)) content = [(c if (c is not...
class Vector(QtWidgets.QGraphicsItem): arrow_color = QtGui.QColor(*getConfig().vector_color) arrow_brush = QtGui.QBrush(arrow_color, QtCore.Qt.SolidPattern) arrow_pen = QtGui.QPen(arrow_brush, 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin) relative_length = getConfig().vector_relative_...
def pytest_runtest_setup(item): sanity = item.config.getoption('--sanity', False) non_interactive = item.config.getoption('--non-interactive', False) interactive = ((not sanity) and (not non_interactive)) if interactive: _show_test_header(item) _try_set_class_attribute(item, 'interactive', i...
def test_monkeypatch_ini(testdir: Any, mocker: MockerFixture) -> None: stub = mocker.stub() assert (stub.assert_called_with.__module__ != stub.__module__) testdir.makepyfile('\n def test_foo(mocker):\n stub = mocker.stub()\n assert stub.assert_called_with.__module__ == stub.__mo...
def test_initialization(): x = np.random.normal(size=(13, 5)) y = np.random.randint(2, size=(13, 3)) model = MultiLabelClf() model.initialize(x, y) assert_equal(model.n_states, 2) assert_equal(model.n_labels, 3) assert_equal(model.n_features, 5) assert_equal(model.size_joint_feature, (5 ...
class Blip2Config(PretrainedConfig): model_type = 'blip-2' is_composition = True def __init__(self, vision_config=None, qformer_config=None, text_config=None, num_query_tokens=32, **kwargs): super().__init__(**kwargs) if (vision_config is None): vision_config = {} log...
def test_save_unequal_chunks_error(): ds = simulate_genotype_call_dataset(n_variant=10, n_sample=10, n_ploidy=10, n_allele=10, n_contig=10) with pytest.raises(ValueError, match="path '' contains an array"): save_dataset(ds, {'.zarray': ''}) ds = ds.chunk({dim: (1, 3, 5, 1) for dim in ds.sizes}) ...
def test_links_1(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: print('\n\n\nLINKS\n') c1c2 = Links(sim)['C1:C2'] assert (c1c2.linkid == 'C1:C2') assert (c1c2.is_conduit() == True) assert (c1c2.is_pump() == False) assert (c1c2.is_orifice() == False) asser...
class AppDefStatusTest(unittest.TestCase): def test_is_terminal(self) -> None: for s in AppState: is_terminal = AppStatus(state=s).is_terminal() if (s in _TERMINAL_STATES): self.assertTrue(is_terminal) else: self.assertFalse(is_terminal) ...
.skipif(IS_PYPY, reason='Test run with coverage on PyPy sometimes raises a RecursionError') def test_recursion_on_inference_tip() -> None: code = '\n class MyInnerClass:\n ...\n\n\n class MySubClass:\n inner_class = MyInnerClass\n\n\n class MyClass:\n sub_class = MySubClass()\n\n\n ...
class DistributedGroupSampler(Sampler): def __init__(self, dataset, samples_per_gpu=1, num_replicas=None, rank=None): (_rank, _num_replicas) = get_dist_info() if (num_replicas is None): num_replicas = _num_replicas if (rank is None): rank = _rank self.dataset ...
_LOSSES.register_module() class SmoothFocalLoss(nn.Module): def __init__(self, gamma=2.0, alpha=0.25, reduction='mean', loss_weight=1.0): super(SmoothFocalLoss, self).__init__() self.gamma = gamma self.alpha = alpha self.reduction = reduction self.loss_weight = loss_weight ...
class Transparent(BaseProtocol): async def guess(self, reader, sock, **kw): remote = self.query_remote(sock) return ((remote is not None) and ((sock is None) or (sock.getsockname() != remote))) async def accept(self, reader, user, sock, **kw): remote = self.query_remote(sock) ret...
def print_loaded_dict_info(model_state_dict: Dict[(str, Any)], state_dict: Dict[(str, Any)], skip_layers: List[str], model_config: AttrDict): extra_layers = [] max_len_model = max((len(key) for key in model_state_dict.keys())) for layername in model_state_dict.keys(): if ((len(skip_layers) > 0) and ...
def get_value_counts(values: List[Any]) -> List[int]: counts = [] if all(((value is None) for value in values)): counts.append(0) else: for value in values: if (value is None): counts.append(0) elif (hasattr(value, '__len__') and (not isinstance(value,...
class NIREmissivePartFromReflectance(NIRReflectance): def __init__(self, sunz_threshold=None, **kwargs): self.sunz_threshold = sunz_threshold super(NIREmissivePartFromReflectance, self).__init__(sunz_threshold=sunz_threshold, **kwargs) def __call__(self, projectables, optional_datasets=None, **i...
def ssl_server(request, qapp): server = WebserverProcess(request, 'webserver_sub_ssl') if (not hasattr(request.node, '_server_logs')): request.node._server_logs = [] request.node._server_logs.append(('SSL server', server.captured_log)) server.start() (yield server) server.after_test() ...
class main(list): def __init__(self, campaign, domains, mod, project_id): global campaign_list campaign_list = campaign global domain_list domain_list = domains if (mod is not None): global module module = mod i = cmd_main() i.prompt = ...
class Effect6404(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Structure Energy Neutralizer')), 'maxRange', src.getModifiedItemAttr('structureRigEwarOptimalBonus'), stackingPenalties=True, **kw...
def test_find_files_to_add() -> None: poetry = Factory().create_poetry(project('complete')) builder = SdistBuilder(poetry) result = {f.relative_to_source_root() for f in builder.find_files_to_add()} assert (result == {Path('AUTHORS'), Path('COPYING'), Path('LICENCE'), Path('LICENSE'), Path('README.rst')...
def _fallback_property(func): name = func.__name__ (func) def new_func(self): out = getattr(self._param_td, name) if (out is self._param_td): return self return out def setter(self, value): return getattr(type(self._param_td), name).fset(self._param_td, value)...
class TestTotalVariationLoss(): def test_call(self): torch.manual_seed(0) image = torch.rand(1, 3, 128, 128) exponent = 3.0 op = loss.TotalVariationLoss(exponent=exponent) actual = op(image) desired = F.total_variation_loss(image, exponent=exponent) ptu.assert...
def get_optim_and_schedulers(model, args): if (args.base_opt == 'SGD'): base_optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) elif (args.base_opt == 'Adam'): base_optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args...
_response(prefix='') def request_word(word): url = URL_FORM.format(word=word) try: response = requests.get(url, timeout=DEFAULT_TIMEOUT) except requests.exceptions.ConnectionError as exc: raise Exception(_('Connection could not be established. Check your internet connection.')) from exc ...
def main(opts): (default_gpu, n_gpu, device) = set_cuda(opts) if default_gpu: LOGGER.info('device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}'.format(device, n_gpu, bool((opts.local_rank != (- 1))), opts.fp16)) seed = opts.seed if (opts.local_rank != (- 1)): seed += opt...
def test_generate_system_pyproject_carriage_returns(example_system_pyproject: str) -> None: cmd = SelfCommand() cmd.system_pyproject.write_text((example_system_pyproject + '\n')) cmd.generate_system_pyproject() with open(cmd.system_pyproject, newline='') as f: generated = f.read() assert ('\...
class ResultsTable(QtCore.QObject): data_changed = QtCore.Signal(int, int, int, int) def __init__(self, results, color, column_index=None, force_reload=False, wdg=None, **kwargs): super().__init__() self.results = results self.color = color self.force_reload = force_reload ...
class SourceGenerator(LocationGenerator): nevents = Int.T(default=2) avoid_water = Bool.T(default=False, help='Avoid sources offshore under the ocean / lakes.') time_min = Timestamp.T(default=Timestamp.D('2017-01-01 00:00:00')) time_max = Timestamp.T(default=Timestamp.D('2017-01-03 00:00:00')) magni...
class Meteor(object): def __init__(self): assert (_METEOR_PATH is not None) cmd = 'java -Xmx2G -jar {} - - -l en -norm -stdio'.format(_METEOR_PATH) self._meteor_proc = sp.Popen(cmd.split(), stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True, encoding='utf-8', bufsize=1) ...
class BertPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.tran...
class Effect6559(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.fighters.filteredItemBoost((lambda mod: mod.item.requiresSkill('Fighters')), 'fighterAbilityAttackMissileExplosionRadius', src.getModifiedItemAttr('aoeCloudSizeBonus'), stackingPenalties=True, *...
class WordInformationPreserved(Metric[torch.Tensor]): def __init__(self: TWordInformationPreserved, *, device: Optional[torch.device]=None) -> None: super().__init__(device=device) self._add_state('correct_total', torch.tensor(0, dtype=torch.float64, device=self.device)) self._add_state('inp...
(python=PYTHON_ALL_VERSIONS) def tests(session: nox.Session) -> None: posargs = session.posargs extras = ('coverage' if RUNNING_CI else 'test') session.install('-e', f'.[{extras}]') if RUNNING_CI: posargs.extend(['--cov', 'auditwheel', '--cov-branch']) for image in _docker_images(session...
class TestAppConfig(AppConfig): name = 'test_app' def ready(self): register_iframe('test_app.views.view_to_component_sync_func_compatibility') register_iframe(views.view_to_component_async_func_compatibility) register_iframe(views.ViewToComponentSyncClassCompatibility) register_i...
def generate_meas_calibration(results_file_path: str, runs: int): results = [] for run in range(runs): (cal_results, state_labels, circuit_results) = meas_calibration_circ_execution(1000, (SEED + run)) meas_cal = CompleteMeasFitter(cal_results, state_labels) meas_filter = MeasurementFilt...
class ViewProviderAsmElementGroup(ViewProviderAsmGroup): _iconName = 'Assembly_Assembly_Element_Tree.svg' def setupContextMenu(self, vobj, menu): setupSortMenu(menu, self.sort, self.sortReverse) ViewProviderAsmElement.setupSyncNameMenu('Sync elements names', menu, vobj) def syncElementName(s...
class Disc_feat(nn.Module): def __init__(self): super(Disc_feat, self).__init__() self.fc11 = nn.Linear(10240, 4096) self.fc12 = nn.Linear(4096, 4096) self.fc13 = nn.Linear(4096, 1) self.d = nn.Dropout(0.5) def forward(self, x_feat): x = self.fc13(self.d(F.relu(se...
def create_sweeptx_for_their_revoked_htlc(chan: 'Channel', ctx: Transaction, htlc_tx: Transaction, sweep_address: str) -> Optional[SweepInfo]: x = analyze_ctx(chan, ctx) if (not x): return (ctn, their_pcp, is_revocation, per_commitment_secret) = x if (not is_revocation): return pcp =...
class ParentProperty(): def __get__(self, inst, owner): return getattr(inst, '_parent', None) def __set__(self, inst, value): if ((getattr(inst, '_parent', None) is not None) and (value is not None)): raise ValueError("Cannot set parent property without first setting it to 'None'.") ...
def clean_value(val: Any) -> str: if isinstance(val, (Mapping, list, set, tuple)): raise ValueError(('Cannot clean parameter value of type %s' % str(type(val)))) if isinstance(val, (datetime.datetime, datetime.date)): return clean_date(val) if isinstance(val, bool): return clean_bool...
def _add_encryption(field_class, requires_length_check=True): class indexed_class(field_class): def __init__(self, default_token_length=None, *args, **kwargs): def _generate_default(): return DecryptedValue(random_string(default_token_length)) if (default_token_length...
def _generate_WS_to_parallel(i, num_nodes, num_signals, graph_hyper, weighted, weight_scale=False): G = nx.watts_strogatz_graph(num_nodes, k=graph_hyper['k'], p=graph_hyper['p']) W_GT = nx.adjacency_matrix(G).A if (weighted == 'uniform'): weights = np.random.uniform(0, 2, (num_nodes, num_nodes)) ...
def annotate_pymodbus_logs(file: (str | os.PathLike)) -> None: with open(file, encoding='utf-8') as in_file, tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', delete=False) as out_file: for (i, line) in enumerate(in_file): if (('Running transaction' in line) and (i > 0)): o...
.parametrize('environment', [{}, {'something': 'value'}, {'something': 'value', 'something_else': 'other_value'}]) .parametrize('platform_specific', [False, True]) def test_environment(environment, platform_specific, platform, intercepted_build_args, monkeypatch): env_string = ' '.join((f'{k}={v}' for (k, v) in env...
def test_pass_through_equal_m_constraint(): class Top(Component): def construct(s): s.push = CalleeIfcCL() s.pull = CalleeIfcCL() s.pass1 = PassThroughPlus100() s.pass1.push //= s.push s.inner = TestModuleNonBlockingIfc() s.inner.push /...
class ParallelLinearQubitOperatorTest(unittest.TestCase): def setUp(self): self.qubit_operator = ((QubitOperator('Z3') + QubitOperator('Y0')) + QubitOperator('X1')) self.n_qubits = 4 self.linear_operator = ParallelLinearQubitOperator(self.qubit_operator) self.vec = numpy.array(range(...
def test_is_generator_for_yield_in_while() -> None: code = '\n def paused_iter(iterable):\n while True:\n # Continue to yield the same item until `next(i)` or `i.send(False)`\n while (yield value):\n pass\n ' node = astroid.extract_node(code) assert bool(nod...
class LazyFrames(object): def __init__(self, frames): self._frames = frames self._out = None def _force(self): if (self._out is None): self._out = np.concatenate(self._frames, axis=0) self._frames = None return self._out def __array__(self, dtype=None)...
def _create_or_update_runtime(task_signature: str, start: float, end: float) -> None: with DatabaseSession() as session: runtime = session.get(Runtime, task_signature) if (not runtime): session.add(Runtime(task=task_signature, date=start, duration=(end - start))) else: ...
class RoIAlignFunction(Function): def forward(ctx, features, rois, out_size, spatial_scale, sample_num=0): (out_h, out_w) = _pair(out_size) assert (isinstance(out_h, int) and isinstance(out_w, int)) ctx.spatial_scale = spatial_scale ctx.sample_num = sample_num ctx.save_for_ba...
def create_line_trotter_step_circuit(parameters: FermiHubbardParameters) -> cirq.Circuit: layout = parameters.layout hamiltonian = parameters.hamiltonian dt = parameters.dt j_theta = (dt * hamiltonian.j_array) (j_theta_even, j_theta_odd) = (j_theta[0::2], j_theta[1::2]) u_phi = ((- dt) * hamilto...
class SerializerTests(AuthenticatedAPITestCase): def setUpTestData(cls): cls.user = User.objects.create(id=5, name='james', discriminator=1) def create_infraction(self, _type: str, active: bool): return Infraction.objects.create(user_id=self.user.id, actor_id=self.user.id, type=_type, reason='A ...
class PickupObjectAction(BaseAction): valid_actions = {'PickupObject', 'OpenObject', 'CloseObject'} def get_reward(self, state, prev_state, expert_plan, goal_idx, low_idx=None): if (low_idx is None): subgoal = expert_plan[goal_idx]['planner_action'] else: subgoal = expert...
class BareReport(FormatterAPI): def render_vulnerabilities(self, announcements, vulnerabilities, remediations, full, packages, fixes=()): parsed_announcements = [] Announcement = namedtuple('Announcement', ['name']) for announcement in get_basic_announcements(announcements, include_local=Fal...
class KnownValues(unittest.TestCase): def test_nosymm_sa4_newton(self): mc = mcscf.CASSCF(m, 4, 4).state_average_(([0.25] * 4)).newton() mo = mc.sort_mo([4, 5, 6, 10], base=1) mc.kernel(mo) self.assertAlmostEqual(mc.e_tot, mc_ref.e_tot, 8) for (e1, e0) in zip(mc.e_states, mc_...
class ins(object): def localin(self): Mylogo() print('\n\x1b[01;32mInstalling Localtunnel .......\x1b[00m\n') if (system == 'termux'): lt().notinl() elif (system == 'ubuntu'): os.system((pac + ' update')) os.system((pac + ' upgrade -y')) ...
class ImageNetConverter(DatasetConverter): def _create_data_spec(self): self.files_to_skip = set() for other_dataset in ('Caltech101', 'Caltech256', 'CUBirds'): duplicates_file = os.path.join(AUX_DATA_PATH, 'ImageNet_{}_duplicates.txt'.format(other_dataset)) with tf.io.gfile....
(kw_only=True) class Session(): config: dict[(str, Any)] = field(factory=dict) collection_reports: list[CollectionReport] = field(factory=list) dag: nx.DiGraph = field(factory=nx.DiGraph) hook: HookRelay = field(factory=HookRelay) tasks: list[PTask] = field(factory=list) dag_report: (DagReport |...
class TestUserAgent(BaseTestCase): async def test_user_agent(self): self.assertIn('Mozilla', (await self.page.evaluate('() => navigator.userAgent'))) (await self.page.setUserAgent('foobar')) (await self.page.goto(self.url)) self.assertEqual('foobar', (await self.page.evaluate('() => ...
def sort_by_keywords(keywords, args): flat = [] res = {} cur_key = None limit = (- 1) for arg in args: if (arg in keywords): limit = keywords[arg] if (limit == 0): res[arg] = True cur_key = None limit = (- 1) ...
class CLIPFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin): model_input_names = ['pixel_values'] def __init__(self, do_resize=True, size=224, resample=Image.BICUBIC, do_center_crop=True, crop_size=224, do_normalize=True, image_mean=None, image_std=None, do_convert_rgb=True, **kwargs): ...
class EntryChangeNotificationControl(ResponseControl): controlType = '2.16.840.1.113730.3.4.7' def decodeControlValue(self, encodedControlValue): (ecncValue, _) = decoder.decode(encodedControlValue, asn1Spec=EntryChangeNotificationValue()) self.changeType = int(ecncValue.getComponentByName('chan...
def test_index_report(api, initialized_db): with fake_security_scanner() as security_scanner: manifest = manifest_for('devtable', 'simple', 'latest') layers = registry_model.list_manifest_layers(manifest, storage, True) assert (manifest.digest not in security_scanner.index_reports.keys()) ...
def test_TrioToken_run_sync_soon_idempotent_requeue() -> None: record: list[None] = [] def redo(token: _core.TrioToken) -> None: record.append(None) with suppress(_core.RunFinishedError): token.run_sync_soon(redo, token, idempotent=True) async def main() -> None: token = ...
class XDistanceMixin(SmoothPointGetter): _baseResolution = 50 _extraDepth = 2 def _getCommonData(self, miscParams, src, tgt): self._prepareTimeCache(src=src, ancReload=miscParams['ancReload'], maxTime=miscParams['time']) return {'rrMap': self._getRepsPerKey(src=src, ancReload=miscParams['anc...
class SpatialDropout2D(Dropout): _spatialdropoutNd_support def __init__(self, rate, data_format=None, **kwargs): super(SpatialDropout2D, self).__init__(rate, **kwargs) if (data_format is None): data_format = K.image_data_format() if (data_format not in {'channels_last', 'chan...
class ConvNextOnnxConfig(OnnxConfig): torch_onnx_minimum_version = version.parse('1.11') def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: return OrderedDict([('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'})]) def atol_for_validation(self) -> float: return 1e...
def require_digest_auth(resource): p = portal.Portal(TestAuthRealm(DIGEST_AUTH_PAGE)) c = checkers.InMemoryUsernamePasswordDatabaseDontUse(digestuser=b'digestuser') p.registerChecker(c) cred_factory = DigestCredentialFactory('md5', b'Digest Auth protected area') return HTTPAuthSessionWrapper(p, [cre...
class Bottleneck(nn.Module): expansion = 2 def __init__(self, inplanes, planes, stride=1, dilation=1): super(Bottleneck, self).__init__() expansion = Bottleneck.expansion bottle_planes = (planes // expansion) self.conv1 = nn.Conv2d(inplanes, bottle_planes, kernel_size=1, bias=Fal...
def test_jsonparse_scalar_with_key_empty(): context = Context({'ok1': 'ov1', 'jsonParse': {'json': '', 'key': 'out'}}) with pytest.raises(KeyInContextHasNoValueError) as err_info: jsonparse.run_step(context) assert (str(err_info.value) == 'jsonParse.json exists but is empty. It should be a valid jso...
class RegNetCfg(): depth: int = 21 w0: int = 80 wa: float = 42.63 wm: float = 2.66 group_size: int = 24 bottle_ratio: float = 1.0 se_ratio: float = 0.0 stem_width: int = 32 downsample: Optional[str] = 'conv1x1' linear_out: bool = False preact: bool = False num_features: i...
def _test(): import torch pretrained = False models = [sharesnet18, sharesnet34, sharesnet50, sharesnet50b, sharesnet101, sharesnet101b, sharesnet152, sharesnet152b] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('...
class LinearAttention(nn.Module): def __init__(self, dim, heads=4, dim_head=32): super().__init__() self.heads = heads hidden_dim = (dim_head * heads) self.to_qkv = nn.Conv2d(dim, (hidden_dim * 3), 1, bias=False) self.to_out = nn.Conv2d(hidden_dim, dim, 1) def forward(sel...
class BoundMethod(UnboundMethod): special_attributes = objectmodel.BoundMethodModel() def __init__(self, proxy: ((nodes.FunctionDef | nodes.Lambda) | UnboundMethod), bound: SuccessfulInferenceResult) -> None: super().__init__(proxy) self.bound = bound def implicit_parameters(self) -> Literal...
class LoopNonlocalControl(NonlocalControl): def __init__(self, outer: NonlocalControl, continue_block: BasicBlock, break_block: BasicBlock) -> None: self.outer = outer self.continue_block = continue_block self.break_block = break_block def gen_break(self, builder: IRBuilder, line: int) -...
def test_verbose_output(testdir): testdir.makepyfile('\n def describe_something():\n def describe_nested_ok():\n def passes():\n assert True\n def describe_nested_bad():\n def fails():\n assert False\n ') res...
class TestDicke(): def test_num_dicke_states(self): N_list = [1, 2, 3, 4, 5, 6, 9, 10, 20, 100, 123] dicke_states = [num_dicke_states(i) for i in N_list] assert_array_equal(dicke_states, [2, 4, 6, 9, 12, 16, 30, 36, 121, 2601, 3906]) N = (- 1) assert_raises(ValueError, num_di...
def get_train_features(cfg, temp_dir, train_dataset_name, resize_img, spatial_levels, image_helper, train_dataset, model): train_features = [] def process_train_image(i, out_dir): if ((i % LOG_FREQUENCY) == 0): (logging.info(f'Train Image: {i}'),) fname_out = f'{out_dir}/{i}.npy' ...
class MemcacheContextFactory(ContextFactory): PROM_PREFIX = 'memcached_client_pool' PROM_LABELS = ['memcached_pool'] pool_size_gauge = Gauge(f'{PROM_PREFIX}_max_size', 'Maximum number of connections allowed in this pool', PROM_LABELS) used_connections_gauge = Gauge(f'{PROM_PREFIX}_active_connections', '...
class STFTLoss(torch.nn.Module): def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'): super(STFTLoss, self).__init__() self.fft_size = fft_size self.shift_size = shift_size self.win_length = win_length window = getattr(torch, window)(win_le...
class SentimentTriple(BaseModel): aspect: List opinion: List sentiment: Text def from_sentiment_triple(cls, labels: Tuple[(List, List, Text)]): relation = {'': 'POS', '': 'NEG', '': 'NEU'} assert (len(labels) == 3) return cls(aspect=labels[0], opinion=labels[1], sentiment=(relati...
class LilyPondStyle(Style): name = 'lilypond' web_style_gallery_exclude = True styles = {Token.Text: '', Token.Keyword: 'bold', Token.Comment: 'italic #A3AAB2', Token.String: '#AB0909', Token.String.Escape: '#C46C6C', Token.String.Symbol: 'noinherit', Token.Pitch: '', Token.Number: '#976806', Token.ChordMod...
class ResourceRequirementEditor(): def __init__(self, parent: QWidget, layout: QHBoxLayout, resource_database: ResourceDatabase, item: ResourceRequirement): self.parent = parent self.layout = layout self.resource_database = resource_database self.resource_type_combo = _create_resourc...
class Decoderv2(nn.Module): def __init__(self, up_in, x_in, n_out): super(Decoderv2, self).__init__() up_out = x_out = (n_out // 2) self.x_conv = nn.Conv2d(x_in, x_out, 1, bias=False) self.tr_conv = nn.ConvTranspose2d(up_in, up_out, 2, stride=2) self.bn = nn.BatchNorm2d(n_out...
_fixtures(SqlAlchemyFixture, DeferredActionFixture) def test_deferred_action_times_out_with_shared_requirements(sql_alchemy_fixture, deferred_action_fixture): fixture = deferred_action_fixture with sql_alchemy_fixture.persistent_test_classes(fixture.MyDeferredAction, fixture.SomeObject): requirements1 =...
def get_datasets(data_cfg: DataConfig) -> Tuple[(Subset[CharDataset], Subset[CharDataset], CharDataset)]: dataset = CharDataset(data_cfg) train_len = int((len(dataset) * data_cfg.train_split)) (train_set, eval_set) = random_split(dataset, [train_len, (len(dataset) - train_len)]) return (train_set, eval_...
class ApacheRole(Role): def __available_site_for(self, name): return ('/etc/apache2/sites-available/%s' % name) def __enabled_site_for(self, name): return ('/etc/apache2/sites-enabled/%s' % name) def __init__(self, prov, context): super(ApacheRole, self).__init__(prov, context) ...
class HeaderChecker(): def __init__(self, caplog, stubs): self.caplog = caplog self.stubs = stubs def check_filename(self, header, filename, expected_inline=False): reply = self.stubs.FakeNetworkReply(headers={'Content-Disposition': header}) (cd_inline, cd_filename) = as...
class PosTransformerEncoderLayerNoFFN(TransformerEncoderLayerNoFFN): def __init__(self, d_model, nhead, dropout): super().__init__(d_model, nhead, dropout) def forward(self, src, pos, src_mask=None, src_key_padding_mask=None): src2 = self.self_attn((src + pos), (src + pos), src, attn_mask=src_ma...
def test_basename_natural2(): fsos = [create_filesystem_object(path) for path in ('hello', 'hello.txt', 'hello0.txt', 'hello1.txt', 'hello2.txt', 'hello3.txthello10.txt', 'hello11.txt', 'hello12.txt', 'hello13.txthello100.txt', 'hello101.txt', 'hello102.txt', 'hello103.txthello110.txt', 'hello111.txt', 'hello112.tx...
class BeachballView(qw.QWidget): def __init__(self, *args): qw.QWidget.__init__(self, *args) mt = mtm.MomentTensor(m=mtm.symmat6(1.0, (- 1.0), 2.0, 0.0, (- 2.0), 1.0)) self._mt = mt self.set_moment_tensor(mt) def set_moment_tensor(self, mt): self._mt = mt self.upd...
class Xception65(nn.Module): def __init__(self, norm_layer=nn.BatchNorm2d): super().__init__() output_stride = cfg.MODEL.OUTPUT_STRIDE if (output_stride == 32): entry_block3_stride = 2 middle_block_dilation = 1 exit_block_dilations = (1, 1) exi...
class WBLogger(): def __init__(self, opts): wandb_run_name = os.path.basename(opts.exp_dir) wandb.init(project='pixel2style2pixel', config=vars(opts), name=wandb_run_name) def log_best_model(): wandb.run.summary['best-model-save-time'] = datetime.datetime.now() def log(prefix, metric...
class DevhostSt(SimpleDownloader): __name__ = 'DevhostSt' __type__ = 'downloader' __version__ = '0.11' __status__ = 'testing' __pattern__ = ' __config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback to...
_config def test_fullscreen_on_top(xmanager): conn = xcbq.Connection(xmanager.display) def _wnd(name): return xmanager.c.window[{w['name']: w['id'] for w in xmanager.c.windows()}[name]] def _clients(): root = conn.default_screen.root.wid q = conn.conn.core.QueryTree(root).reply() ...
class KTZ1(DataElementGroup): is_sepa = DataElementField(type='jn', _d='Kontoverwendung SEPA') iban = DataElementField(type='an', max_length=34, _d='IBAN') bic = DataElementField(type='an', max_length=11, _d='BIC') account_number = DataElementField(type='id', _d='Konto-/Depotnummer') subaccount_numb...
class random_crystal(): def __init__(self, dim=3, group=227, species=['C'], numIons=8, factor=1.1, thickness=None, area=None, lattice=None, sites=None, conventional=True, tm=Tol_matrix(prototype='atomic'), use_hall=False): self.source = 'Random' self.valid = False self.factor = factor ...
def system_details_to_str(d: Dict[(str, Union[(str, Dict[(str, DebugInfo)])])], indent: str='') -> str: details = ['Machine Details:', (' Platform ID: %s' % d.get('platform', 'n/a')), (' Processor: %s' % d.get('processor', 'n/a')), '', 'Python:', (' Implementation: %s' % d.get('implementation', 'n/a')...
def test_notify_exception(pytester: Pytester, capfd) -> None: config = pytester.parseconfig() with pytest.raises(ValueError) as excinfo: raise ValueError(1) config.notify_exception(excinfo, config.option) (_, err) = capfd.readouterr() assert ('ValueError' in err) class A(): def p...
class ShardedIterator(CountingIterator): def __init__(self, iterable, num_shards, shard_id, fill_value=None): if ((shard_id < 0) or (shard_id >= num_shards)): raise ValueError('shard_id must be between 0 and num_shards') sharded_len = int(math.ceil((len(iterable) / float(num_shards)))) ...