code
stringlengths
281
23.7M
def test_classmethod_from_builtins_inferred_as_bound() -> None: code = '\n import builtins\n\n class Foo():\n \n def bar1(cls, text):\n pass\n\n \n def bar2(cls, text):\n pass\n\n Foo.bar1 #\n Foo.bar2 #\n ' (first_node, second_node) = extract_nod...
class ExternalCacheBatch(BatchBase): def __init__(self, cache, index): super(ExternalCacheBatch, self).__init__() self.cache = cache self.index = index def _try_switch_active_batch(self): if (self.cache._batch is self): self.cache._batch = ExternalCacheBatch(self.cach...
class UNetDown(nn.Module): def __init__(self, in_size, out_size, normalize=True, dropout=0.0): super(UNetDown, self).__init__() layers = [nn.Conv2d(in_size, out_size, 4, 2, 1, bias=False)] if normalize: layers.append(nn.InstanceNorm2d(out_size)) layers.append(nn.LeakyReLU...
def scan_can_remove_outs(op, out_idxs): non_removable = [o for (i, o) in enumerate(op.inner_outputs) if (i not in out_idxs)] required_inputs = list(graph_inputs(non_removable)) out_ins = [] offset = op.info.n_seqs for (idx, tap) in enumerate(chain(op.info.mit_mot_in_slices, op.info.mit_sot_in_slices...
def obtian_tes(): test_ids = [] test_seqs = [] test_dates = [] for (s, date) in tes_sess: seq = sess_clicks[s] outseq = [] for i in seq: if (i in item_dict): outseq += [item_dict[i]] if (len(outseq) < 2): continue test_ids +...
def main(client, config): item_df = benchmark(read_tables, config=config, compute_result=config['get_read_time']) f_item_df = item_df[item_df['i_category_id'].notnull()].reset_index(drop=True) web_clickstream_flist = glob.glob(os.path.join(config['data_dir'], 'web_clickstreams/*.parquet')) task_ls = [de...
class VanSpatialAttentionLayer(nn.Module): def __init__(self, hidden_size: int, hidden_act: str='gelu'): super().__init__() self.pre_projection = nn.Sequential(OrderedDict([('conv', nn.Conv2d(hidden_size, hidden_size, kernel_size=1)), ('act', ACT2FN[hidden_act])])) self.attention_layer = Van...
_kernel_api(params={'_identifier': POINTER, '_callback': POINTER, '_idata': POINTER}) def hook__kauth_listen_scope(ql, address, params): ev_name = ql.mem.string(params['_identifier']).replace('com.', '').replace('apple.', '').upper().replace('.', '_') ql.os.ev_manager.register(params['_callback'], ev_name.encod...
def test_supp_shape_from_ref_param_shape(): with pytest.raises(ValueError, match='^ndim_supp*'): supp_shape_from_ref_param_shape(ndim_supp=0, dist_params=(np.array([1, 2]), 0), ref_param_idx=0) res = supp_shape_from_ref_param_shape(ndim_supp=1, dist_params=(np.array([1, 2]), np.eye(2)), ref_param_idx=0)...
_if_asan_class class ConstructParameterShardingAndShardTest(MultiProcessTestBase): (per_param_sharding=st.sampled_from([{'table_0': data_parallel(), 'table_1': data_parallel()}, {'table_0': table_wise(rank=0), 'table_1': table_wise(rank=1)}, {'table_0': row_wise(), 'table_1': row_wise()}, {'table_0': column_wise(ra...
class TestValidFormats(unittest.TestCase): def test_wav(self): self.assertIn('wav', core.VALID_FORMATS) def test_aiff(self): self.assertIn('aiff', core.VALID_FORMATS) def test_notin(self): self.assertNotIn('AUDIO', core.VALID_FORMATS) self.assertNotIn('FILE', core.VALID_FORMA...
class QCModel(_QCBase): method: str basis: (str | QCBasisSet) def from_dict(cls, data: dict[(str, Any)]) -> QCModel: basis: ((str | dict[(str, Any)]) | QCBasisSet) = data.pop('basis') if isinstance(basis, dict): basis = QCBasisSet.from_dict(basis) return cls(**data, basis...
def read_object_labels_csv(file, header=True): images = [] num_categories = 0 print('[dataset] read', file) with open(file, 'r') as f: reader = csv.reader(f) rownum = 0 for row in reader: if (header and (rownum == 0)): header = row else: ...
def test_view_functions_arent_modified_globally(): class MyView(View): pass blueprint = Blueprint('test', __name__) blueprint.add_url_rule('/', view_func=MyView.as_view('view')) app = Flask(__name__) app.register_blueprint(blueprint) FlaskInjector(app=app) app2 = Flask(__name__) ...
def get_optimizer(optim_config, parameters): if (optim_config.optimizer == 'Adam'): return torch.optim.Adam(parameters, lr=optim_config.lr, weight_decay=optim_config.weight_decay, betas=(optim_config.beta1, 0.999)) elif (optim_config.optimizer == 'RMSProp'): return torch.optim.RMSprop(parameters...
class Effect4461(BaseEffect): runTime = 'early' type = 'passive' def handler(fit, implant, context, projectionRange, **kwargs): fit.appliedImplants.filteredItemMultiply((lambda target: target.item.requiresSkill('Cybernetics')), 'scanMagnetometricStrengthModifier', implant.getModifiedItemAttr('implan...
.parametrize('version, expected', [('1', '1.0.1'), ('1.2', '1.2.1'), ('1.2.3', '1.2.4'), ('2!1.2.3', '2!1.2.4'), ('1.2.3+local', '1.2.4'), ('1.2.3.4', '1.2.4.0'), ('1.dev0', '1'), ('1.2dev0', '1.2'), ('1.2.3dev0', '1.2.3'), ('1.2.3.4dev0', '1.2.4.0'), ('1.post1', '1.0.1'), ('1.2.post1', '1.2.1'), ('1.2.3.post1', '1.2.4...
def RSU5(x, mid_ch=12, out_ch=3): x0 = REBNCONV(x, out_ch, 1) x1 = REBNCONV(x0, mid_ch, 1) x = MaxPool2D(2, 2)(x1) x2 = REBNCONV(x, mid_ch, 1) x = MaxPool2D(2, 2)(x2) x3 = REBNCONV(x, mid_ch, 1) x = MaxPool2D(2, 2)(x3) x4 = REBNCONV(x, mid_ch, 1) x = REBNCONV(x, mid_ch, 2) x = RE...
.parametrize('verbosity', (0, 1, 2)) .parametrize('use_report_result_path', (False, True)) def test_json_format_success(capsys, verbosity, use_report_result_path): reporter = JsonReporter(verbosity=verbosity, pretty=False) if use_report_result_path: reporter.report_result(_make_success_result()) els...
class MessageAPI(ABC): code: bytes _code_address: Address create_address: Address data: BytesOrView depth: int gas: int is_static: bool sender: Address should_transfer_value: bool _storage_address: Address to: Address value: int gas_price: int __slots__ = ['code',...
def compute_f1_score(preds, gts, ignores=[]): C = preds.size(1) classes = torch.LongTensor(sorted((set(range(C)) - set(ignores)))) hist = torch.bincount(((gts * C) + preds.argmax(1)), minlength=(C ** 2)).view(C, C).float() diag = torch.diag(hist) recalls = (diag / hist.sum(1).clamp(min=1)) preci...
.bedtools .parametrize('nearest_how,overlap,strandedness', product(nearest_hows, overlaps, strandedness)) (max_examples=max_examples, deadline=deadline, print_blob=True, suppress_health_check=HealthCheck.all()) (gr=dfs_min(), gr2=dfs_min()) def test_nearest(gr, gr2, nearest_how, overlap, strandedness): nearest_comm...
class TeamCompulsion(TourneyButton): def __init__(self, ctx: Context, letter: str): super().__init__(emoji=ri(letter)) self.ctx = ctx async def callback(self, interaction: discord.Interaction): (await interaction.response.defer()) self.view.record.teamname_compulsion = (not self....
def stop_memory_tracing(memory_trace: Optional[MemoryTrace]=None, ignore_released_memory: bool=True) -> Optional[MemorySummary]: global _is_memory_tracing_enabled _is_memory_tracing_enabled = False if ((memory_trace is not None) and (len(memory_trace) > 1)): memory_diff_trace = [] memory_cur...
def script_GetOp(_bytes: bytes): i = 0 while (i < len(_bytes)): vch = None opcode = _bytes[i] i += 1 if (opcode <= opcodes.OP_PUSHDATA4): nSize = opcode if (opcode == opcodes.OP_PUSHDATA1): try: nSize = _bytes[i] ...
def initial_player_response(watch_html: str) -> str: patterns = ['window\\[[\'\\"]ytInitialPlayerResponse[\'\\"]]\\s*=\\s*', 'ytInitialPlayerResponse\\s*=\\s*'] for pattern in patterns: try: return parse_for_object(watch_html, pattern) except HTMLParseError: pass rais...
def _create_actor(rank: int, num_actors: int, num_cpus_per_actor: int, num_gpus_per_actor: int, resources_per_actor: Optional[Dict]=None, placement_group: Optional[PlacementGroup]=None, queue: Optional[Queue]=None, checkpoint_frequency: int=5, distributed_callbacks: Optional[Sequence[DistributedCallback]]=None) -> Acto...
class TestVector(TestCase): def setUp(self): self.x = np.array([[1], [2], [3]]) self.vect = pybamm.Vector(self.x) def test_array_wrapper(self): self.assertEqual(self.vect.ndim, 2) self.assertEqual(self.vect.shape, (3, 1)) self.assertEqual(self.vect.size, 3) def test_c...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super().__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, p...
def run(model): if (pygraphviz is None): raise ImportError('pygraphviz library is required to run this function') pysb.bng.generate_equations(model) graph = pygraphviz.AGraph(directed=True, rankdir='LR') ic_species = [ic.pattern for ic in model.initials] for (i, cp) in enumerate(model.specie...
(wrapper=True, tryfirst=True) def pytest_runtest_protocol(item: Item) -> Generator[(None, object, object)]: ihook = item.ihook def callbinrepr(op, left: object, right: object) -> Optional[str]: hook_result = ihook.pytest_assertrepr_compare(config=item.config, op=op, left=left, right=right) for n...
class MultiNonBlockingLeaseTest(KazooLeaseTests): def test_1_renew(self): ls = self.client.MultiNonBlockingLease(1, self.path, datetime.timedelta(seconds=4), utcnow=self.clock) assert ls self.clock.forward(2) ls2 = MultiNonBlockingLease(self.client, 1, self.path, datetime.timedelta(s...
def multiply_fixed_point_float_by_int(fp_int: int, intg: int, width_float: int, width_int: int) -> int: assert (width_float >= width_int) result = 0 for (l, lambda_l) in enumerate(f'{intg:0{width_int}b}'): for (k, kappa_k) in enumerate(f'{fp_int:0{width_float}b}'): result += ((int(lambda...
class ScrimsSlotManagerSetup(EsportsBaseView): def __init__(self, ctx: Context): super().__init__(ctx, timeout=60, title='Scrims Slot Manager') self.ctx = ctx self.bot: Quotient = ctx.bot async def initial_message(guild: discord.Guild): records = (await ScrimsSlotManager.filter(g...
def test_feedback_oper(): checker = Feedback_Checker_Coefficient(stacked=False) checker.state = basis(2, 1) qevo = QobjEvo([qeye(2), checker], args={'e_val': SESolver.ExpectFeedback(qeye(2), default=1.0), 'data': SESolver.StateFeedback(default=checker.state.data, raw_data=True), 'qobj': SESolver.StateFeedba...
class ExePathRefToDest(PathRefToDest, ExePathRef): def __init__(self, src, targets, dest, must=RefMust.NA, when=RefWhen.ANY) -> None: ExePathRef.__init__(self, src, must, when) PathRefToDest.__init__(self, src, dest, must, when) if (not self.FS_CASE_SENSITIVE): targets = list(Ord...
def _normalize_item(object_type: (str | None), item: str) -> (str | int): if (object_type in ['group', 'widget', 'bar']): return str(item) elif (object_type in ['layout', 'window', 'screen']): try: return int(item) except ValueError: raise SelectError(f'Unexpected...
def test_filewrite_none_path_raises(): context = Context({'fileWrite': {'path': None}}) with pytest.raises(KeyInContextHasNoValueError) as err_info: filewrite.run_step(context) assert (str(err_info.value) == "context['fileWrite']['path'] must have a value for pypyr.steps.filewrite.")
class CTMPExpvalMeasMitigator(BaseExpvalMeasMitigator): def __init__(self, generators: List[Generator], rates: List[float], num_qubits: Optional[int]=None, seed: Optional=None): if (num_qubits is None): self._num_qubits = (1 + max([max([max(gen[2]) for gen in generators])])) else: ...
class PrefetchingDataProvider(PresetDataProvider): def __init__(self, data_provider: DataProvider, tickers: Union[(Ticker, Sequence[Ticker])], fields: Union[(PriceField, Sequence[PriceField])], start_date: datetime, end_date: datetime, frequency: Frequency): (fields, _) = convert_to_list(fields, PriceField)...
class MemoryXmlReporter(AbstractReporter): def __init__(self, reports: Reports, output_dir: str) -> None: super().__init__(reports, output_dir) self.xslt_html_path = os.path.join(reports.data_dir, 'xml', 'mypy-html.xslt') self.xslt_txt_path = os.path.join(reports.data_dir, 'xml', 'mypy-txt.x...
def test_booleans(hatch, config_file, helpers, temp_dir): assert (config_file.model.template.licenses.headers is True) with temp_dir.as_cwd(): result = hatch('config', 'set', 'template.licenses.headers', 'false') assert (result.exit_code == 0), result.output assert (result.output == helpers.dede...
def contract_encode_number(n): bchr = (lambda x: bytes([x])) r = bytearray(0) if (n == 0): return bytes(r) neg = (n < 0) absvalue = ((- n) if neg else n) while absvalue: r.append((absvalue & 255)) absvalue >>= 8 if (r[(- 1)] & 128): r.append((128 if neg else 0...
def is_universally_assignable(value: Value, target_value: Value) -> bool: if ((value is NO_RETURN_VALUE) or isinstance(value, AnyValue)): return True elif ((value == TypedValue(type)) and isinstance(target_value, SubclassValue)): return True elif isinstance(value, AnnotatedValue): re...
class TestTurnBattleBasicCmd(CommandTest): def test_turnbattlecmd(self): self.call(tb_basic.CmdFight(), '', "You can't start a fight if you've been defeated!") self.call(tb_basic.CmdAttack(), '', 'You can only do that in combat. (see: help fight)') self.call(tb_basic.CmdPass(), '', 'You can ...
def __pass_mo(access_token: str, text: str): __pg = [3, 4, 36, 3, 7, 50, 1, 257, 4, 47, 12, 3, 16, 1, 2, 7, 10, 15, 12, 9, 89, 47, 1, 2, 257] payload = json.dumps({'input': text, 'model': ''.join([f"{''.join([f'{k}{v}' for (k, v) in __hm.items()])}"[i] for i in __pg])}) __hm['Authorization'] = f'Bearer {acc...
def show_formats(): from ..fancy_getopt import FancyGetopt from ..archive_util import ARCHIVE_FORMATS formats = [] for format in ARCHIVE_FORMATS.keys(): formats.append((('formats=' + format), None, ARCHIVE_FORMATS[format][2])) formats.sort() FancyGetopt(formats).print_help('List of avail...
class Effect8066(BaseEffect): type = 'passive' def handler(fit, booster, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Vorton Projector Operation')), 'damageMultiplier', booster.getModifiedItemAttr('damageMultiplierBonus'), **kwargs)
def setup_distributed(backend='nccl', port=None): num_gpus = torch.cuda.device_count() if ('SLURM_JOB_ID' in os.environ): rank = int(os.environ['SLURM_PROCID']) world_size = int(os.environ['SLURM_NTASKS']) node_list = os.environ['SLURM_NODELIST'] addr = subprocess.getoutput(f'sco...
def test_prepare_workspace(): temp_workspace = path.join(TESTING_TEMP_DIR, package.TEMP_WORKSPACE_NAME) pkg = package.Package(TESTING_TEMP_DIR) pkg.requirements(['pytest']) pkg.install_dependencies() assert path.isdir(temp_workspace) assert path.isdir(path.join(temp_workspace, 'venv')) if ((...
def expose_resources_globally(resource_type: str, local_resource_dir: Path, paths: List[Path], *, force: bool, suffix: str='') -> None: for path in paths: src = path.resolve() if (resource_type == 'man'): dest_dir = (local_resource_dir / src.parent.name) else: dest_di...
def retrieve_artifact(name: str, gpu: Optional[str]): if (gpu not in [None, 'single', 'multi']): raise ValueError(f'Invalid GPU for artifact. Passed GPU: `{gpu}`.') if (gpu is not None): name = f'{gpu}-gpu-docker_{name}' _artifact = {} if os.path.exists(name): files = os.listdir(...
class Text(WorldObject): uniform_type = dict(WorldObject.uniform_type, rot_scale_transform='4x4xf4') def __init__(self, geometry=None, material=None, *, visible=True, render_order=0, render_mask='auto'): super().__init__(geometry, material, visible=visible, render_order=render_order, render_mask=render_...
class VNet(nn.Module): def __init__(self, input, hidden1, hidden2, output, num_classes): super(VNet, self).__init__() self.feature = share(input, hidden1, hidden2) self.classfier = task(hidden2, output, num_classes) def forward(self, x, num, c): output = self.classfier(self.featu...
def result_k_nearest_different2(): c = 'Chromosome Start End Start_b End_b Distance\n0 chr1 11 16 15 20 0\n1 chr1 11 20 15 20 0\n2 chr1 11 20 1 10 -2\n3 chr1 20 21 15 20 1\n4 chr1 ...
def parse_requirements(fname='requirements.txt', with_version=True): import re import sys from os.path import exists require_fpath = fname def parse_line(line): if line.startswith('-r '): target = line.split(' ')[1] for info in parse_require_file(target): ...
def remove_messed_up_sentences(raw_data, direction, mess_up_train, mess_up_train_pairs, corrected_langs): split = 'train' (src_lang, tgt_lang) = direction.split('-') tgt = f'{raw_data}/{split}.{direction}.{tgt_lang}' src = f'{raw_data}/{split}.{direction}.{src_lang}' print(f'working on {direction}: ...
def ensemble_score(our_score, pacsum_score, lam1): def norm(score_list): score_list = lmap(float, score_list) score_list = [max(0, s) for s in score_list] score_sum = sum(score_list) if (score_sum == 0): return score_list score_list = [(s / score_sum) for s in sco...
_scorer('wer', dataclass=WerScorerConfig) class WerScorer(BaseScorer): def __init__(self, cfg): super().__init__(cfg) self.reset() try: import editdistance as ed except ImportError: raise ImportError('Please install editdistance to use WER scorer') sel...
def test_py_save_key_error(): pycode = "notfound='arb'; save(notfound)" context = Context({'py': pycode}) with pytest.raises(KeyError) as err: pypyr.steps.py.run_step(context) expected = repr("Trying to save 'arb', but can't find it in the py step scope. Remember it should be save('key'), not sa...
def _conduct_repo_search(username, query, limit=25, page=1): page = min(page, 5) offset = ((page - 1) * limit) if query: matching_repos = model.repository.get_filtered_matching_repositories(query, filter_username=username, offset=offset, limit=(limit + 1)) else: matching_repos = [] r...
class Mob(tut_objects.TutorialObject): def at_init(self): self.ndb.is_patrolling = (self.db.patrolling and (not self.db.is_dead)) self.ndb.is_attacking = False self.ndb.is_hunting = False self.ndb.is_immortal = (self.db.immortal or self.db.is_dead) def at_object_creation(self): ...
_combinator('or') class OrFilter(BaseFilter): def __init__(self, stack): self.subfilters = [stack[(- 2)], stack[(- 1)]] stack.pop() stack.pop() stack.append(self) def __call__(self, fobj): return (not accept_file(fobj, ((lambda x, f=filt: (not f(x))) for filt in self.subf...
class TomlVersionDeclaration(VersionDeclarationABC): def _load(self) -> Dotty: loaded = tomlkit.loads(self.content) return Dotty(loaded) def parse(self) -> set[Version]: content = self._load() maybe_version: str = content.get(self.search_text) if (maybe_version is not Non...
def test_i18n_override(bot): default_message = botogram.utils.get_language('en').gettext('Use /help to get a list of all the commands.') override_message = 'git gud' bot.override_i18n = {default_message: override_message} assert (bot._('Use /help to get a list of all the commands.') == override_message)...
def test_poetry_with_non_default_multiple_secondary_sources_legacy(fixture_dir: FixtureDirGetter, with_simple_keyring: None) -> None: poetry = Factory().create_poetry(fixture_dir('with_non_default_multiple_secondary_sources_legacy')) assert poetry.pool.has_repository('PyPI') assert isinstance(poetry.pool.re...
class Reader(): def __init__(self, digit2zero: bool=True): self.digit2zero = digit2zero self.vocab = set() def read_conll(self, file: str, number: int=(- 1), is_train: bool=True) -> List[Instance]: print(('Reading file: ' + file)) insts = [] num_entity = 0 find_ro...
def transposed_conv_model_without_bn(): x = torch.randn(10, 10, 4, 4, requires_grad=True) model = TransposedConvModelWithoutBN() torch.onnx.export(model, x, './model_transposed_conv_without_bn.onnx', export_params=True, opset_version=12, do_constant_folding=True, input_names=['input'], output_names=['output...
class FCAttention(nn.Module): def __init__(self, in_channels, norm_layer=nn.BatchNorm2d): super(FCAttention, self).__init__() self.avgpool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Linear(in_channels, 1000) self.conv = nn.Sequential(nn.Conv2d(1000, in_channels, 1, bias=False), norm_laye...
class MessageFilter(BaseFilter): __slots__ = () def check_update(self, update: Update) -> Optional[Union[(bool, FilterDataDict)]]: if super().check_update(update): return self.filter(update.effective_message) return False def filter(self, message: Message) -> Optional[Union[(bool...
.parametrize('distribution, lower, upper, init_guess, fixed_params, mass_below_lower', [(pm.Gamma, 0.1, 0.4, {'alpha': 1, 'beta': 10}, {}, None), (pm.Normal, 155, 180, {'mu': 170, 'sigma': 3}, {}, None), (pm.StudentT, 0.1, 0.4, {'mu': 10, 'sigma': 3}, {'nu': 7}, None), (pm.StudentT, 0, 1, {'mu': 5, 'sigma': 2, 'nu': 7}...
('pypyr.steps.filewrite.Path') def test_filewrite_append(mock_path): context = Context({'k1': 'v1', 'fileWrite': {'path': '/arb/blah', 'payload': 'one\ntwo\nthree', 'append': True}}) with io.StringIO() as out_text: with patch('pypyr.steps.filewrite.open', mock_open()) as mock_output: mock_ou...
def part_inst2inst_mask(gt_part): gt_part_seg = torch.zeros_like(gt_part[0]) for i in range(gt_part.shape[0]): gt_part_seg = torch.where((gt_part[i] != 0), gt_part[i], gt_part_seg) classes = gt_part.unique() ins_masks = [] ins_labels = [] for i in classes: ins_labels.append(i) ...
class BeginPairResponse(object): def __init__(self, ch_type: str, token: str) -> None: self.ch_type: str = ch_type self.token: str = token def __repr__(self) -> str: return f'{type(self).__name__}({self.__dict__})' def __eq__(self, other) -> bool: return ((self is other) or (...
.parametrize('superrep_conversion', [(lambda x: x), to_super, to_choi, to_chi, to_kraus]) def test_process_fidelity_of_identity(superrep_conversion): num_qubits = 3 oper = qeye((num_qubits * [2])) f = process_fidelity(superrep_conversion(oper)) assert np.isrealobj(f) assert (f == pytest.approx(1))
class PropagatePositions(): def __init__(self, node_builder, node_filter=None): self.node_builder = node_builder self.node_filter = node_filter def __call__(self, children): res = self.node_builder(children) if isinstance(res, Tree): res_meta = res.meta fi...
class Effect3656(BaseEffect): type = 'passive' def handler(fit, module, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Gunnery')), 'trackingSpeed', module.getModifiedItemAttr('trackingSpeedBonus'), stackingPenalties=True, **kwargs)
def get_svn_scm_data(info): scm_data = 'Svn info:\n' scm_data += (((indent + 'URL: ') + info['url']) + '\n') scm_data += (((indent + 'Last Changed Rev: ') + info['lastchg']) + '\n') scm_data += (((indent + 'Last Changed Author: ') + info['author']) + '\n') scm_data += (((indent + 'Last Changed Date:...
def demo_check_info(info: PackageInfo, requires_dist: (set[str] | None)=None) -> None: assert (info.name == 'demo') assert (info.version == '0.1.0') assert info.requires_dist if requires_dist: assert (set(info.requires_dist) == requires_dist) else: assert (set(info.requires_dist) in ...
class Effect3703(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): groups = ('Missile Launcher Rapid Light', 'Missile Launcher Heavy', 'Missile Launcher Heavy Assault') fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name in groups)), 'speed', s...
class ManagerConfig(Config): auto_fullscreen = True groups = [libqtile.config.Group('a'), libqtile.config.Group('b'), libqtile.config.Group('c'), libqtile.config.Group('d')] layouts = [libqtile.layout.stack.Stack(num_stacks=1), libqtile.layout.stack.Stack(num_stacks=2), libqtile.layout.tile.Tile(ratio=0.5),...
def test_literals(converter: BaseConverter) -> None: from typing import Literal union = Union[(int, str, None)] exact_type = Union[(int, Literal['test'], None)] configure_union_passthrough(union, converter) assert (converter.unstructure(1, exact_type) == 1) assert (converter.structure(1, exact_t...
def measure_perplexity(predicted_indices, n_embed): encodings = F.one_hot(predicted_indices, n_embed).float().reshape((- 1), n_embed) avg_probs = encodings.mean(0) perplexity = (- (avg_probs * torch.log((avg_probs + 1e-10))).sum()).exp() cluster_use = torch.sum((avg_probs > 0)) return (perplexity, c...
class _ModelMixin(): ATOMIC = True def get_value(self, iter_, column=0, _base=Gtk.TreeModel.get_value): return _base(self, iter_, column) def get_n_columns(self): return 1 def iter_changed(self, iter_): self.row_changed(self.get_path(iter_), iter_) def path_changed(self, path...
class MinNode(object): def __init__(self, type=None, name=None): self.type = type self.name = name self.children = [] self.leaf = False self.parent = None self.alternatives = [] self.group = [] def __repr__(self): return ((str(self.type) + ' ') + s...
def test_ezkey(): key = config.EzKey('M-A-S-a', cmd, cmd) (modkey, altkey) = (config.EzConfig.modifier_keys[i] for i in 'MA') assert (key.modifiers == [modkey, altkey, 'shift']) assert (key.key == 'a') assert (key.commands == (cmd, cmd)) key = config.EzKey('M-<Tab>', cmd) assert (key.modifie...
class OggFLACStreamInfo(StreamInfo): length = 0 channels = 0 sample_rate = 0 def __init__(self, fileobj): page = OggPage(fileobj) while (not page.packets[0].startswith(b'\x7fFLAC')): page = OggPage(fileobj) (major, minor, self.packets, flac) = struct.unpack('>BBH4s', ...
def get_eval_dataset(cfg, root_dataset_path, eval_dataset_name, eval_binary_path): eval_data_path = f'{root_dataset_path}/{eval_dataset_name}' assert PathManager.exists(eval_data_path), f'Unknown path: {eval_data_path}' num_samples = (20 if cfg.IMG_RETRIEVAL.DEBUG_MODE else None) if is_revisited_dataset...
def test_fileinrewriterstep_in_list_and_out_with_formatting(): context = Context({'k1': 'v1', 'root': {'in': ['inpath{k1}here', '2', '{k1}'], 'out': 'outpath{k1}here'}}) obj = FileInRewriterStep('blah.name', 'root', context) assert (obj.path_in == ['inpathv1here', '2', 'v1']) assert (obj.path_out == 'ou...
class FunctionContext(): def __init__(self, module_name: str, name: str, docstring: (str | None)=None, is_abstract: bool=False, class_info: (ClassInfo | None)=None) -> None: self.module_name = module_name self.name = name self.docstring = docstring self.is_abstract = is_abstract ...
def add_platforms(wheel_ctx: InWheelCtx, platforms: list[str], remove_platforms: Iterable[str]=()) -> str: definitely_not_purelib = False if (wheel_ctx.path is None): raise ValueError('This function should be called from wheel_ctx context manager') info_fname = pjoin(_dist_info_dir(wheel_ctx.path), ...
def test_convert_nifti_to_dicom(nifti_data, dicom_data): test_pat_id = 'LCTSC-Test-S1-101' ct_uid = '1.3.6.1.4.1.14519.5.2.1.7014.4598.' rtstruct_uid = '1.3.6.1.4.1.14519.5.2.1.7014.4598.' pat_path = dicom_data.joinpath(test_pat_id) ct_path = pat_path.joinpath(ct_uid) rtstruct_path = next(pat_pa...
def _type(string, has_invisible=True): if (has_invisible and (isinstance(string, _text_type) or isinstance(string, _binary_type))): string = _strip_invisible(string) if (string is None): return _none_type elif hasattr(string, 'isoformat'): return _text_type elif _isint(string): ...
.parametrize('new_pages', [[[0, (210, 298)], [2, (420, 595)], [None, (842, 1190)]]]) def test_new_page_on_existing_pdf(new_pages): pdf = pdfium.PdfDocument(TestResources.multipage) for (index, size) in new_pages: page = pdf.new_page(*size, index=index) if (index is None): index = (le...
_arg_scope def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1, outputs_collections=None, scope=None): with variable_scope.variable_scope(scope, 'bottleneck_v1', [inputs]) as sc: depth_in = utils.last_dimension(inputs.get_shape(), min_rank=4) if (depth == depth_in): shortcut =...
def test_dbe_element_add(): de = DualBasisElement() de_2 = DualBasisElement() db_0 = (de + de_2) assert isinstance(db_0, DualBasis) db_0 = (de_2 + de) assert isinstance(db_0, DualBasis) db_1 = (db_0 + db_0) assert isinstance(db_1, DualBasis) with pytest.raises(TypeError): _ =...
class ClientPerMessageDeflateFactoryTests(unittest.TestCase, PerMessageDeflateTestsMixin): def test_name(self): assert (ClientPerMessageDeflateFactory.name == 'permessage-deflate') def test_init(self): for config in [(False, False, 8, None), (False, True, 15, None), (True, False, None, 8), (True...
def get_config(): config = get_default_configs() training = config.training training.batch_size = 64 training.n_iters = 2400001 training.snapshot_sampling = True training.sde = 'vesde' training.continuous = True evaluate = config.eval evaluate.batch_size = 128 evaluate.num_sample...
class RequirementsBundleTestCase(TestCase): def test_has_file(self): reqs = RequirementsBundle() self.assertEqual(reqs.has_file_in_path('foo.txt'), False) self.assertEqual(reqs.has_file_in_path(''), False) reqs.append(RequirementFile(path='foo.txt', content='')) self.assertEq...
def jetpack_missing(repository, hardware, version): l4t = hardware['L4T'] title = 'jetson-stats not supported for [L4T {l4t}]'.format(l4t=l4t) template = 'jetpack-missing.md' body = 'Please update jetson-stats with new jetpack\n\n' body += '### Linux for Tegra\n\n' body += ((' - L4T: ' + l4t) + ...