code
stringlengths
281
23.7M
def get_detached_file_descriptor(filepath): try: import win32file has_win32file = True except ImportError: has_win32file = False if has_win32file: import msvcrt import os handle = win32file.CreateFile(str(filepath), win32file.GENERIC_READ, ((win32file.FILE_SHA...
def load_controller(args, index): if (args.controller[index] == 'none'): return None elif (args.controller[index] == 'fudge_controller'): controller = FudgeController(args, index) if (len(args.controller_load_dir[index]) > 0): controller.load(args.controller_load_dir[index]) ...
class bdist(Command): description = 'create a built (binary) distribution' user_options = [('bdist-base=', 'b', 'temporary directory for creating built distributions'), ('plat-name=', 'p', ('platform name to embed in generated filenames (default: %s)' % get_platform())), ('formats=', None, 'formats for distribu...
class Function(object): def __init__(self, type_name, inputs, params): self.type_name = type_name self.inputs = inputs self.params = params self.ntop = self.params.get('ntop', 1) if ('ntop' in self.params): del self.params['ntop'] self.in_place = self.para...
class BlankCosmeticPatchesDialog(BaseCosmeticPatchesDialog, Ui_BlankCosmeticPatchesDialog): _cosmetic_patches: BlankCosmeticPatches def __init__(self, parent: (QtWidgets.QWidget | None), current: BaseCosmeticPatches): super().__init__(parent) self.setupUi(self) assert isinstance(current,...
def _computations_as_categorical(df: pd.DataFrame, **kwargs) -> pd.DataFrame: categories_dict = _as_categorical_checks(df, **kwargs) categories_dtypes = {} for (column_name, value) in categories_dict.items(): if (value is None): cat_dtype = pd.CategoricalDtype() elif isinstance(v...
class CdPlayer(): description: str currentTrack: int = 0 amplifier: Amplifier title: str def __init__(self, description: str, amplifier: Amplifier): self.description = description self.amplifier = amplifier def on(self) -> None: print(f'{self.description} on') def off...
def test_tested_unlisted(covtest): covtest.makefile('\n def func():\n pass\n ') covtest.run() expected = check_coverage.Message(check_coverage.MsgType.perfect_file, 'module.py', 'module.py has 100% coverage but is not in perfect_files!') assert (covtest.check(perfect_files=[]) == [e...
class StoryFactory(DjangoModelFactory): class Meta(): model = Story django_get_or_create = ('name',) category = factory.SubFactory(StoryCategoryFactory) name = factory.LazyAttribute((lambda o: f'Success Story of {o.company_name}')) company_name = factory.Faker('company') company_url ...
def handle_code(code, vk_packet): code_keys = [] if (code in CODES): code_keys.append(VirtualKeyAction(CODES[code])) elif (len(code) == 1): if ((not vk_packet) and (code in ascii_vk)): code_keys.append(VirtualKeyAction(ascii_vk[code])) else: code_keys.append(K...
class TestFormResourceBaseReviewForm(TestCase): def test_review_form_comment_includes_resource_name(self): form = ResourceBaseReviewForm(resource_name='test resource') self.assertIn('placeholder="Please provide clear feedback if you decided to not approve this test resource." required id="id_comment...
def adapt_network_for_any_size_input(network_definition, multiple): def new_network_definition(*args, **kwargs): pdb.set_trace() if ('image_batch_tensor' in kwargs): image_batch_tensor = kwargs['image_batch_tensor'] else: image_batch_tensor = args[0] args ...
def batch_examples(example, batch_size, max_length, mantissa_bits, shard_multiplier=1, length_multiplier=1, constant=False, num_threads=4, drop_long_sequences=True): with tf.name_scope('batch_examples'): max_length = (max_length or batch_size) min_length = 8 mantissa_bits = mantissa_bits ...
def dump(args, s): s.adapter.set_tclk(0) s.adapter.set_sclk(127) try: code = args.code.decode('hex') except TypeError: logging.fatal('Code must be in hexadecimal format.') return if (len(code) != 7): logging.fatal('Code must be 7 bytes long.') return s.unl...
class RBF(Kernel): def __call__(self, X): XY = X.dot(X.T) x2 = pt.sum((X ** 2), axis=1).dimshuffle(0, 'x') X2e = pt.repeat(x2, X.shape[0], axis=1) H = ((X2e + X2e.T) - (2.0 * XY)) V = pt.sort(H.flatten()) length = V.shape[0] m = pt.switch(pt.eq((length % 2), 0...
_wgpu_render_function(Square, SquareMaterial) class SquareShader(WorldObjectShader): def get_bindings(self, wobject, shared): binding = Binding('u_stdinfo', 'buffer/uniform', shared.uniform_buffer) self.define_binding(0, 0, binding) return {0: {0: binding}} def get_pipeline_info(self, wo...
def kill(pid: int, signal: int, timeout=1000, dword1=wintypes.DWORD(1)): if (pid <= 0): raise OSError(errno.EINVAL, 'process group not supported') if ((signal < 0) or (signal >= PG_SIGNAL_COUNT)): raise OSError(errno.EINVAL, 'unsupported signal number') inbuffer = pointer(wintypes.BYTE(signa...
class _FCNHead(nn.Module): def __init__(self, in_channels, channels, norm_layer=nn.BatchNorm2d): super(_FCNHead, self).__init__() inter_channels = (in_channels // 4) self.block = nn.Sequential(nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False), norm_layer(inter_channels), nn.Re...
class Migration(migrations.Migration): dependencies = [('questions', '0062_meta')] operations = [migrations.AddField(model_name='questionset', name='questionset', field=models.ForeignKey(blank=True, default=None, help_text='The question set this question set belongs to.', null=True, on_delete=django.db.models.d...
class Local(): def get_src_local_rp(extension): return rpath.RPath(Globals.local_connection, os.path.join(old_test_dir, os.fsencode(extension))) def get_tgt_local_rp(extension): return rpath.RPath(Globals.local_connection, os.path.join(abs_test_dir, os.fsencode(extension))) vftrp = get_src_l...
_message(((pyrogram.filters.command(commands='get_last_logs') & pyrogram.filters.private) & tools.is_admin)) def send_last_logs(bot: AutoPoster, message: Message): logs = sorted(list(bot.logs_path.iterdir()))[(- 1)] try: lines = int(message.command[1]) except (ValueError, IndexError): lines ...
def get_invalid_tag_usage(applier_list, include_tags, exclude_tags): if ((len(include_tags.strip()) == 0) or (len(exclude_tags.strip()) == 0)): return [] include_list = include_tags.split(',') include_list = [i.strip() for i in include_list] exclude_list = exclude_tags.split(',') exclude_lis...
def write_job_parameters(params: namedtuple) -> None: dict_path = (params.job_dir + 'params.csv') with open(dict_path, 'w') as csv_file: writer = csv.writer(csv_file, delimiter=';') for (key, value) in enumerate(params._fields): writer.writerow([value, params[key]])
def test_env_all_operations(): os.environ['ARB_GET_ME1'] = 'arb value from $ENV ARB_GET_ME1' os.environ['ARB_GET_ME2'] = 'arb value from $ENV ARB_GET_ME2' os.environ['ARB_DELETE_ME1'] = 'arb value from $ENV ARB_DELETE_ME1' os.environ['ARB_DELETE_ME2'] = 'arb value from $ENV ARB_DELETE_ME2' context =...
class TestMaskedLanguageModel(unittest.TestCase): def test_legacy_masked_lm(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_legacy_mlm') as data_dir: create_dummy_data(data_dir) preprocess_lm_data(data_dir) ...
def parse_having(toks, start_idx, tables_with_alias, schema, default_tables): idx = start_idx len_ = len(toks) if ((idx >= len_) or (toks[idx] != 'having')): return (idx, []) idx += 1 (idx, conds) = parse_condition(toks, idx, tables_with_alias, schema, default_tables) return (idx, conds)
def simulate_trotter(qubits: Sequence[cirq.Qid], hamiltonian: Hamiltonian, time: float, n_steps: int=1, order: int=0, algorithm: Optional[TrotterAlgorithm]=None, control_qubit: Optional[cirq.Qid]=None, omit_final_swaps: bool=False) -> cirq.OP_TREE: if (order < 0): raise ValueError('The order of the Trotter ...
def PolynomialPlot(): (coefficients, set_coefficients) = reactpy.hooks.use_state([0]) x = list(linspace((- 1), 1, 50)) y = [polynomial(value, coefficients) for value in x] return reactpy.html.div(plot(f'{len(coefficients)} Term Polynomial', x, y), ExpandableNumberInputs(coefficients, set_coefficients))
def romfs_validation(line: QtWidgets.QLineEdit): if is_directory_validator(line): return True path = Path(line.text()) return (not all((p.is_file() for p in [path.joinpath('system', 'files.toc'), path.joinpath('packs', 'system', 'system.pkg'), path.joinpath('packs', 'maps', 's010_cave', 's010_cave.p...
class SmartCopyAndPaste(object): def __setCursorPositionAndAnchor(cursor, position, anchor): cursor.setPosition(anchor) cursor.setPosition(position, cursor.KeepAnchor) def __ensureCursorBeforeAnchor(cls, cursor): start = cursor.selectionStart() end = cursor.selectionEnd() ...
def sa_conv_unit(x): with tf.variable_scope(None, 'sa_conv_unit'): shape = x.get_shape().as_list() y = slim.conv2d(x, shape[(- 1)], kernel_size=1, stride=1, biases_initializer=None, activation_fn=None) y = slim.batch_norm(y, activation_fn=None, fused=False) y = tf.nn.sigmoid(y) ...
class TorchProfiler(HookBase): def __init__(self, enable_predicate, output_dir, *, activities=None, save_tensorboard=True): self._enable_predicate = enable_predicate self._activities = activities self._output_dir = output_dir self._save_tensorboard = save_tensorboard def before_s...
class AlexNet(nn.Module): def __init__(self, num_classes=10): super(AlexNet, self).__init__() self.features = nn.Sequential(nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=5), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(inpla...
.parametrize('tp', [ClassVar, InitVar, *cond_list(HAS_TYPE_GUARD, (lambda : [typing.TypeGuard])), *cond_list(HAS_TYPED_DICT_REQUIRED, (lambda : [typing.Required, typing.NotRequired]))]) def test_var_tag(tp): pytest.raises(NotSubscribedError, (lambda : normalize_type(tp))) assert_normalize(tp[int], tp, [nt_zero(...
.slow _figures_equal() def test_DecisionMatrixPlotter_barh(decision_matrix, fig_test, fig_ref): dm = decision_matrix(seed=42, min_alternatives=3, max_alternatives=3, min_criteria=3, max_criteria=3) plotter = plot.DecisionMatrixPlotter(dm=dm) test_ax = fig_test.subplots() plotter.barh(ax=test_ax) df ...
_module() class HandGenerateRelDepthTarget(): def __init__(self): pass def __call__(self, results): rel_root_depth = results['rel_root_depth'] rel_root_valid = results['rel_root_valid'] cfg = results['ann_info'] D = cfg['heatmap_size_root'] root_depth_bound = cfg[...
def prime1_hint_text(): db = default_database.resource_database_for(RandovaniaGame.METROID_PRIME) from randovania.games.prime1.generator.pickup_pool import artifacts artifact = artifacts.create_artifact(0, 0, db) result = [('Artifact', artifact.pickup_category, artifact.broad_category)] return resul...
class RejectSponsorshipApplicationUseCase(BaseUseCaseWithNotifications): notifications = [notifications.RejectedSponsorshipNotificationToPSF(), notifications.RejectedSponsorshipNotificationToSponsors()] def execute(self, sponsorship, request=None): sponsorship.reject() sponsorship.save() ...
class Project(gui.Container): lastUpdateTime = 0 def __init__(self, **kwargs): super(Project, self).__init__(**kwargs) self.variable_name = 'App' self.style.update({'position': 'relative', 'overflow': 'auto', 'background-color': 'rgb(250,248,240)', 'background-image': "url('/editor_resou...
def test_vsite_reg(methanol, vs, tmpdir): with tmpdir.as_cwd(): vs.freeze_site_angles = True vs.regularisation_epsilon = 0.1 vs.run(molecule=methanol) assert (methanol.extra_sites.n_sites == 2) sites = [] center_atom = None with open(os.path.join(methanol.name...
def test_proj_debug_logging(capsys): with proj_logging_env(): with pytest.warns(FutureWarning): transformer = Transformer.from_proj('+init=epsg:4326', '+init=epsg:27700') transformer.transform(100000, 100000) captured = capsys.readouterr() if (os.environ.get('PROJ_DEBUG')...
def test_load_hotp_vectors(): vector_data = textwrap.dedent('\n # HOTP Test Vectors\n # RFC 4226 Appendix D\n\n COUNT = 0\n COUNTER = 0\n INTERMEDIATE = cc93cf18508d94934c64b65d8ba7667fb7cde4b0\n TRUNCATED = 4c93cf18\n HOTP = 755224\n SECRET = \n\n COUNT = 1\n COUNTER = 1\n INTERMED...
def test_fails_rst_no_content(tmp_path, capsys, caplog): sdist = build_sdist(tmp_path, {'setup.cfg': '\n [metadata]\n name = test-package\n version = 0.0.1\n long_description = file:README.rst\n long_description_content_type = text/x-rst\n ...
class RubyRoleTest(ProvyTestCase): def setUp(self): super(RubyRoleTest, self).setUp() self.role = RubyRole(prov=None, context={}) def installs_necessary_packages_to_provision(self): with self.using_stub(AptitudeRole) as aptitude, self.execute_mock() as execute: self.role.prov...
def transforms_imagenet_train(img_size=224, scale=None, ratio=None, hflip=0.5, vflip=0.0, color_jitter=0.4, auto_augment=None, interpolation='random', use_prefetcher=False, mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, re_prob=0.0, re_mode='const', re_count=1, re_num_splits=0, separate=False, force_color_jitter...
def format_for_slack(total_results, results, scheduled: bool, title: str): print(total_results, results) header = {'type': 'header', 'text': {'type': 'plain_text', 'text': title, 'emoji': True}} if (total_results['failed'] > 0): total = {'type': 'section', 'fields': [{'type': 'mrkdwn', 'text': f'''*...
class Importable(t.Trafaret): def check_and_return(self, value): if (not isinstance(value, str)): self._failure('value should be a string', value=value) if (':' not in value): self._failure('import notation must be in format: `package.module:target`', value=value) (mo...
class DatatableDataFactory(factory.Factory): class Meta(): model = dict columns = [{six.u('name'): six.u('per_end_date'), six.u('type'): six.u('Date')}, {six.u('name'): six.u('ticker'), six.u('type'): six.u('String')}, {six.u('name'): six.u('tot_oper_exp'), six.u('type'): six.u('BigDecimal(11,4)')}] ...
def versions_to_display_for_releases(current_version: StrictVersion, last_changelog_version: StrictVersion, releases: list[dict]) -> tuple[(dict[(str, str)], list[str], (VersionDescription | None))]: all_change_logs = {} new_change_logs = [] displayed_new_version = False version_to_display = None fo...
def t2star_circuit_execution() -> Tuple[(qiskit.result.Result, np.array, List[int], float, float)]: num_of_gates = np.append(np.linspace(10, 150, 10).astype(int), np.linspace(160, 450, 5).astype(int)) gate_time = 0.1 qubits = [0] t2_value = 10 error = thermal_relaxation_error(np.inf, t2_value, gate_...
(persist=eval(os.getenv('PERSISTENT'))) def compute_similarity_matrix_keywords(model_path, keywords=[], all_model_vectors=False, return_unk_sim=False): (keywords, word_embs) = get_word_embeddings(model_path, keywords, all_model_vectors=all_model_vectors, return_words=True) word_embs = np.array(word_embs) si...
class Migration(migrations.Migration): dependencies = [('projects', '0050_value_set_prefix')] operations = [migrations.AlterField(model_name='value', name='value_type', field=models.CharField(choices=[('text', 'Text'), ('url', 'URL'), ('integer', 'Integer'), ('float', 'Float'), ('boolean', 'Boolean'), ('datetim...
def project_by_tangent_iteration(space: 'RiemannianSpace', pt_a: 'Point', pt_b: 'Point', pt_c: 'Point', *, tol=1e-06, max_iterations=100) -> Tuple[('Point', OptimResult)]: dist_ab = space.length(pt_a, pt_b) if (dist_ab < tol): return (midpoint(space, pt_a, pt_b), OptimResult.ILL_POSED) projected_len...
def read_sac_zpk(filename=None, file=None, string=None, get_comments=False): if (filename is not None): f = open(filename, 'rb') elif (file is not None): f = file elif (string is not None): f = BytesIO(string) sects = ('ZEROS', 'POLES', 'CONSTANT') sectdata = {'ZEROS': [], 'P...
def ticket_id_to_user_hashid(ticket_id: strawberry.ID, conference_code: str) -> Optional[str]: conference = Conference.objects.filter(code=conference_code).first() decoded_ticket_id = decode_hashid(ticket_id) order_position = pretix.get_order_position(conference, decoded_ticket_id) if (not order_positio...
def help(): print('\nAaia\n\navailable modules:') for (importer, module_name, _) in pkgutil.iter_modules([os.path.dirname(__file__)]): if (module_name != 'main'): library = importlib.import_module(((__package__ + '.') + module_name)) print(((module_name + ' : ') + library.__descr...
def _infer_decorator_callchain(node): if (not isinstance(node, FunctionDef)): return None if (not node.parent): return None try: result = next(node.infer_call_result(node.parent), None) except InferenceError: return None if isinstance(result, bases.Instance): ...
def test_corrected_cphase_ops_throws() -> None: (a, b) = cirq.LineQubit.range(2) with pytest.raises(GateDecompositionError): _corrected_cphase_ops(qubits=(a, b), angle=(np.pi / 13), parameters=ParticleConservingParameters(theta=(np.pi / 4), delta=0, chi=0, gamma=0, phi=(np.pi / 24)))
def test_concordance_cebrian2009localizacion(): matrix = scale_by_sum([[6, 5, 28, 5, 5], [4, 2, 25, 10, 9], [5, 7, 35, 9, 6], [6, 1, 27, 6, 7], [6, 8, 30, 7, 9], [5, 6, 26, 4, 8]], axis=0) objectives = [1, 1, (- 1), 1, 1] weights = [0.25, 0.25, 0.1, 0.2, 0.2] expected = [[np.nan, 0.5, 0.35, 0.5, 0.35, 0...
def copy_tree(src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=1, dry_run=0): from distutils.file_util import copy_file if ((not dry_run) and (not os.path.isdir(src))): raise DistutilsFileError(("cannot copy tree '%s': not a directory" % src)) try: names = ...
class BiDictTests(unittest.TestCase): def setUp(self): self.bidict = BiDict() def testStartEmpty(self): self.assertEqual(len(self.bidict), 0) self.assertEqual(len(self.bidict.forward), 0) self.assertEqual(len(self.bidict.backward), 0) def testLength(self): self.assert...
def get_create_inputs(dataset_name: str, is_train: bool, epochs: int): options = {'mnist': (lambda : create_inputs_mnist(is_train)), 'fashion_mnist': (lambda : create_inputs_mnist(is_train)), 'smallNORB': (lambda : create_inputs_norb(is_train, epochs)), 'cifar10': (lambda : create_inputs_cifar10(is_train)), 'cifa10...
_module() class ViPNAS_ResNet(BaseBackbone): arch_settings = {50: ViPNAS_Bottleneck} def __init__(self, depth, in_channels=3, num_stages=4, strides=(1, 2, 2, 2), dilations=(1, 1, 1, 1), out_indices=(3,), style='pytorch', deep_stem=False, avg_down=False, frozen_stages=(- 1), conv_cfg=None, norm_cfg=dict(type='BN...
class PrepareNuSuperPositionState(Bloq): num_bits_p: int adjoint: bool = False _property def signature(self) -> Signature: return Signature([Register('mu', self.num_bits_p), Register('nu', (self.num_bits_p + 1), shape=(3,))]) def short_name(self) -> str: return 'PREP $2^{-\\mu}|\\mu\...
class ConditionOverSampleDataset(ConditionCaptionDataset): def __init__(self, features: Dict, transforms: Dict, caption: str, vocabulary: str, condition: str, load_into_mem: bool=False, threshold: float=0.9, times: int=4): super().__init__(features, transforms, caption, vocabulary, condition, load_into_mem=...
def add_BAU_constraints(n, config): ext_c = n.generators.query('p_nom_extendable').carrier.unique() mincaps = pd.Series(config['electricity'].get('BAU_mincapacities', {key: 0 for key in ext_c})) lhs = linexpr((1, get_var(n, 'Generator', 'p_nom'))).groupby(n.generators.carrier).apply(join_exprs) define_c...
def add_exec_opts(parser) -> None: parser.add_argument('--timeout', help='maximum number of seconds to allow for all tests to run. This does not include time taken to build the tests.', type=int, default=300, metavar='timeout') parser.add_argument('filter_glob', help='maximum number of seconds to allow for all ...
def test_int_loader_provider(strict_coercion, debug_trail): retort = Retort(strict_coercion=strict_coercion, debug_trail=debug_trail) loader = retort.get_loader(int) assert (loader(100) == 100) if strict_coercion: raises_exc(TypeLoadError(int, None), (lambda : loader(None))) raises_exc(T...
class Tconfig(TestCase): def setUp(self): config.init() def test_init_garbage_file(self): config.quit() garbage = b'\xf1=\xab\xac' (fd, filename) = mkstemp() os.close(fd) with open(filename, 'wb') as f: f.write(garbage) config.init(filename) ...
def test_add_should_not_select_prereleases(app: PoetryTestApplication, repo: TestRepository, tester: CommandTester) -> None: repo.add_package(get_package('pyyaml', '3.13')) repo.add_package(get_package('pyyaml', '4.2b2')) tester.execute('pyyaml') expected = 'Using version ^3.13 for pyyaml\n\nUpdating de...
(Executable) class ExecutableStub(Executable): def __init__(self, name='fake executable', stdout=''): super().__init__(name) self.calls = [] self.stdout = stdout def __repr__(self): return ("StubExecutable('%s')" % self.name) def times_called(self): return len(self.ca...
class Config(object): GPU_USAGE = 1 LOG_DIR = './log/DTN' IMAGE_SIZE = 256 MAP_SIZE = 64 TRU_PARAMETERS = {'alpha': 0.001, 'beta': 0.01, 'mu_update_rate': 0.001} STEPS_PER_EPOCH = 1000 MAX_EPOCH = 40 NUM_EPOCHS_PER_DECAY = 12.0 BATCH_SIZE = 32 LEARNING_RATE = 0.001 LEARNING_M...
def set_object_material_text(object_id: int, text: str, material_index: int=0, material_size: int=OBJECT_MATERIAL_SIZE_256x128, font_face: str='Arial', font_size: int=24, bold: bool=True, font_color: int=, back_color: int=0, text_alignment: int=0) -> bool: return SetObjectMaterialText(object_id, text, material_inde...
def sa_perindopril_rings() -> GoalDirectedBenchmark: specification = uniform_specification(1, 10, 100) benchmark_object = perindopril_rings() sa_biased = ScoringFunctionSAWrapper(benchmark_object.objective, SAScoreModifier()) return GoalDirectedBenchmark(name='SA_perindopril', objective=sa_biased, contr...
class Configs(): def __init__(self): self.config_dir = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'config') self.configs = self.get_configs() def get_configs(self): config_files = [os.path.join(self.config_dir, cfile) for cfile in os.listdir(self.config_dir) if ((os.path...
def test_assign_pickup_to_starting_items(empty_patches, state_game_data, generic_pickup_category, default_generator_params): db = state_game_data.resource_database starting_node = state_game_data.region_list.node_by_identifier(empty_patches.game.starting_location) starting = state.State(ResourceCollection()...
def Euler2Rotation(phi, theta, psi): c_phi = np.cos(phi) s_phi = np.sin(phi) c_theta = np.cos(theta) s_theta = np.sin(theta) c_psi = np.cos(psi) s_psi = np.sin(psi) R_roll = np.array([[1, 0, 0], [0, c_phi, (- s_phi)], [0, s_phi, c_phi]]) R_pitch = np.array([[c_theta, 0, s_theta], [0, 1, ...
class ProgressMeter(object): def __init__(self, num_batches: int, meters: List[AverageMeter], prefix: str=''): self.batch_fmtstr = self._get_batch_fmtstr(num_batches) self.meters = meters self.prefix = prefix def display(self, batch: int) -> None: entries = [(self.prefix + self.b...
('pypyr.moduleloader.get_module') (Step, 'invoke_step') def test_run_pipeline_steps_complex_with_run_str_lower_false(mock_invoke_step, mock_get_module): step = Step({'name': 'step1', 'run': 'false'}) context = get_test_context() original_len = len(context) with patch_logger('pypyr.dsl', logging.INFO) as...
class MissingSpaceInDoctestChecker(BaseChecker): name = 'missing_space_in_doctest' msgs = {'E9973': ('Space missing after >>> in the docstring of "%s."', 'missing-space-in-doctest', 'Used when a doctest is missing a space before the code to be executed')} _required_for_messages('missing-space-in-doctest') ...
def _smoketest(ctx: Context, debug: bool, eth_client: EthClient, report_path: Optional[str]) -> None: from raiden.tests.utils.smoketest import run_smoketest, setup_smoketest, step_printer raiden_stdout = StringIO() assert ctx.parent, MYPY_ANNOTATION environment_type = ctx.parent.params['environment_type...
class Proplist(): def __init__(self, ini_data: Optional[Dict[(str, Union[(bytes, str)])]]=None) -> None: self._pl = pa.pa_proplist_new() if (not self._pl): raise PulseAudioException(0, 'Failed creating proplist.') if (ini_data is not None): for (k, v) in ini_data: ...
.supported(only_if=(lambda backend: backend.hash_supported(hashes.SHA3_224())), skip_message='Does not support SHA3_224') class TestSHA3224(): test_sha3_224 = generate_hash_test(load_hash_vectors, os.path.join('hashes', 'SHA3'), ['SHA3_224LongMsg.rsp', 'SHA3_224ShortMsg.rsp'], hashes.SHA3_224())
class TestHRPTGetCalibratedBT(TestHRPTWithPatchedCalibratorAndFile): def _get_channel_4_bt(self): dataset_id = make_dataid(name='4', calibration='brightness_temperature') return self._get_dataset(dataset_id) def test_calibrated_bt_values(self): result = self._get_channel_4_bt() n...
def get_filenames(): for (dirpath, dirnames, filenames) in os.walk('src'): if dirpath.endswith('__pycache__'): continue for rel_fn in filenames: if (not rel_fn.endswith('.py')): continue fn = os.path.join(dirpath, rel_fn) if (fn in [os....
def get_devices(display=None): _devices = {} base = '/dev' for filename in os.listdir(base): if filename.startswith('hidraw'): path = os.path.join(base, filename) try: _devices[path] = HIDRawDevice(display, path) except OSError: con...
def test_upload_generic_package_file(tmp_path, project, resp_upload_generic_package): path = (tmp_path / file_name) path.write_text(file_content, encoding='utf-8') package = project.generic_packages.upload(package_name=package_name, package_version=package_version, file_name=file_name, data=path.open(mode='...
class RunID(namedtuple('RunID', 'python compat bench timestamp')): def __new__(cls, python, compat, bench, timestamp): self = super().__new__(cls, python, compat, (bench or None), (int(timestamp) if timestamp else None)) return self def __str__(self): if (not self.timestamp): ...
class JsonFormatter(logging.Formatter): def __init__(self, *args, **kwargs): self.json_default = kwargs.pop('json_default', _json_default) self.json_encoder = kwargs.pop('json_encoder', None) self.json_serializer = kwargs.pop('json_serializer', json.dumps) self.default_values = kwarg...
def generate_ann(root_path, split, image_infos, preserve_vertical, format): dst_image_root = osp.join(root_path, 'crops', split) ignore_image_root = osp.join(root_path, 'ignores', split) if (split == 'training'): dst_label_file = osp.join(root_path, f'train_label.{format}') elif (split == 'val')...
def train(ps_device): (train_input_fn, record_info_dict) = data_utils.get_input_fn(tfrecord_dir=FLAGS.record_info_dir, split='train', bsz_per_host=FLAGS.train_batch_size, seq_len=FLAGS.seq_len, reuse_len=FLAGS.reuse_len, bi_data=FLAGS.bi_data, num_hosts=1, num_core_per_host=1, perm_size=FLAGS.perm_size, mask_alpha=...
class BlazeEventsLoader(implements(PipelineLoader)): __doc__ = __doc__.format(SID_FIELD_NAME=SID_FIELD_NAME, TS_FIELD_NAME=TS_FIELD_NAME, EVENT_DATE_FIELD_NAME=EVENT_DATE_FIELD_NAME) def __init__(self, expr, next_value_columns, previous_value_columns, resources=None, odo_kwargs=None): dshape = expr.dsha...
class MatchResult(object): def __init__(self): self._pattern_to_op_tensor = {} self._name_to_pattern = {} def add(self, pattern, op, tensor): self._pattern_to_op_tensor[pattern] = (op, tensor) if (pattern.name is not None): if (pattern.name in self._name_to_pattern): ...
class Arithmetic(Task): VERSION = 0 DATASET_PATH = 'EleutherAI/arithmetic' def has_training_docs(self): return False def has_validation_docs(self): return True def has_test_docs(self): return False def training_docs(self): return NotImplemented def validation_...
def test_get_routed_grid_model_circuit(): problem = _random_grid_model(2, 3, np.random.RandomState(0)) qubits = cirq.GridQubit.rect(2, 3) circuit = get_routed_hardware_grid_circuit(problem_graph=problem.graph, qubits=qubits, coordinates=problem.coordinates, gammas=[(np.pi / 2), (np.pi / 4)], betas=[(np.pi /...
def test_tensordot_of_proxied_cupy_arrays(): cupy = pytest.importorskip('cupy') org = cupy.arange(9).reshape((3, 3)) a = proxy_object.asproxy(org.copy()) b = proxy_object.asproxy(org.copy()) res1 = dask.array.tensordot(a, b).flatten() res2 = dask.array.tensordot(org.copy(), org.copy()).flatten()...
def test_target_task_view(): secret = factories.make_secret() transfer = factories.create(factories.LockedTransferSignedStateProperties(secret=secret)) secrethash = transfer.lock.secrethash mediator = factories.make_address() mediator_channel = factories.create(factories.NettingChannelStatePropertie...
class Fog(VersionBase): def __init__(self, visual_range, bounding_box=None): self.visual_range = visual_range if (bounding_box and (not isinstance(bounding_box, BoundingBox))): raise TypeError('bounding_box not of type BoundingBox') self.bounding_box = bounding_box def __eq__...
def get_val_dataloader(args, val_data, vocab): print('processing val data') (features, vocab) = convert_example_to_feature(args, val_data, vocab, get_vocab=False) val_data = Dataset(features) sampler = data.SequentialSampler(val_data) val_dataloader = data.DataLoader(val_data, sampler=sampler, batch...
def main(): train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True) test_loader = DataLoader(test_data, batch_size=16, shuffle=False, num_workers=4, pin_memory=True) meta_loader = DataLoader(meta_data, batch_size=batch_size, shuffle=True, num_workers=4, pin...