code
stringlengths
281
23.7M
def test_read_classifiers_cached(monkeypatch, tmp_path): def mock_get_cache_dir(): tmp_file = (tmp_path / 'classifiers.lst') with tmp_file.open('w') as fh: fh.write('A\nB\nC') return tmp_path monkeypatch.setattr(fv, 'get_cache_dir', mock_get_cache_dir) classifiers = fv._r...
def test_suppress_error_removing_lock(tmp_path: Path) -> None: path = (tmp_path / 'dir') path.mkdir() lock = get_lock_path(path) lock.touch() mtime = lock.stat().st_mtime with unittest.mock.patch.object(Path, 'unlink', side_effect=OSError) as m: assert (not ensure_deletable(path, conside...
def split_header_words(header_values): assert (type(header_values) not in STRING_TYPES) result = [] for text in header_values: orig_text = text pairs = [] while text: m = token_re.search(text) if m: text = unmatched(m) name = m....
class EventLoop(QEventLoop): def __init__(self, parent: QObject=None) -> None: super().__init__(parent) self._executing = False def exec(self, flags: _ProcessEventFlagType=QEventLoop.ProcessEventsFlag.AllEvents) -> int: if self._executing: raise AssertionError('Eventloop is a...
class AZPReactiveTabu(AZPTabu): def __init__(self, max_iterations, k1, k2, random_state=None): self.tabu = deque([], maxlen=1) super().__init__(random_state=random_state) self.avg_it_until_rep = 1 self.rep_counter = 1 if (max_iterations <= 0): raise ValueError('Th...
def get_all_datasets(args: argparse.Namespace, tokenizer: object) -> List[Generator[(Dict, None, None)]]: train_gen_list = [] if (args.mode in ['train']): for train_data_path in args.train_data.split(','): train_gen_list.append(get_data_gen(train_data_path, 'train', args, tokenizer)) ret...
def test_jump_control_of_flow_instruction_raises(): try: raise Jump(['one', 'two'], 'sg', 'fg', 'og') except Jump as err_info: assert isinstance(err_info, ControlOfFlowInstruction) assert (err_info.groups == ['one', 'two']) assert (err_info.success_group == 'sg') assert (...
class SquareBoxCoderTest(tf.test.TestCase): def test_correct_relative_codes_with_default_scale(self): boxes = [[10.0, 10.0, 20.0, 15.0], [0.2, 0.1, 0.5, 0.4]] anchors = [[15.0, 12.0, 30.0, 18.0], [0.1, 0.0, 0.7, 0.9]] scale_factors = None expected_rel_codes = [[(- 0.790569), (- 0.263...
class Effect6641(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Hull Upgrades')), 'armorHPBonusAdd', src.getModifiedItemAttr('shipBonusRole2'), **kwargs) fit.modules.filteredItemBoost((la...
def test_time_adapt(model, criterion, args=None, logger=None, writer=None): from utils.norm_stats_utils import CombineNormStatsRegHook_onereg from utils.relation_map_utils import CombineCossimRegHook candidate_bn_layers = [nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d] if args.update_only_bn_affine: ...
def rfc2047(value): def decode_chunk(m): (data, encoding) = decode_rfc2047_header(m.group(0))[0] try: res = data.decode(encoding) except (LookupError, UnicodeEncodeError): res = m.group(0) return res return _RE_RFC2047.sub(decode_chunk, value, re.I)
.parametrize('flag, expected', [('--blink-settings=key=value', [('key', 'value')]), ('--blink-settings=key=equal=rights', [('key', 'equal=rights')]), ('--blink-settings=one=1,two=2', [('one', '1'), ('two', '2')]), ('--enable-features=feat', [])]) def test_pass_through_existing_settings(config_stub, flag, expected): ...
class DiagonalLineDecorator(ChartDecorator, SimpleLegendItem): def __init__(self, key: str=None, **plot_settings: Any): ChartDecorator.__init__(self, key) SimpleLegendItem.__init__(self) self.plot_settings = plot_settings def decorate(self, chart: 'Chart') -> None: self.legend_ar...
_model class Sound(BaseMedia): file_content_type: str = field(default=None) file_url: str = field(default=None) native_sound_id: str = field(default=None) secret_token: str = field(default=None) subtype: str = field(default=None) def from_json(cls, value: JsonResponse, **kwargs) -> 'Sound': ...
def get_model(data, weights='imagenet'): base_model = InceptionV3(weights=weights, include_top=False) x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(len(data.classes), activation='softmax')(x) model = Model(inputs=base_model.input,...
class KLRegSteepestDescent(nn.Module): def __init__(self, score_predictor, num_iter=1, compute_losses=True, detach_length=float('Inf'), parameter_batch_dim=0, steplength_reg=0.0, hessian_reg=0, init_step_length=1.0, softmax_reg=None): super().__init__() self.score_predictor = score_predictor ...
class EfficientNet(tf.keras.Model): def __init__(self, blocks_args=None, global_params=None): super(EfficientNet, self).__init__() if (not isinstance(blocks_args, list)): raise ValueError('blocks_args should be a list.') self._global_params = global_params self._blocks_ar...
def venv(tmp_path_factory, session_app_data): if CURRENT.is_venv: return sys.executable root_python = root(tmp_path_factory, session_app_data) dest = tmp_path_factory.mktemp('venv') process = Popen([str(root_python), '-m', 'venv', '--without-pip', str(dest)]) process.communicate() return...
class NormFreeNet(nn.Module): def __init__(self, cfg: NfCfg, num_classes=1000, in_chans=3, global_pool='avg', output_stride=32, drop_rate=0.0, drop_path_rate=0.0): super().__init__() self.num_classes = num_classes self.drop_rate = drop_rate self.grad_checkpointing = False ass...
def upgrade(saveddata_engine): saveddata_engine.execute(tmpTable) saveddata_engine.execute('INSERT INTO boostersTemp (ID, itemID, fitID, active) SELECT ID, itemID, fitID, active FROM boosters') saveddata_engine.execute('DROP TABLE boosters') saveddata_engine.execute('ALTER TABLE boostersTemp RENAME TO b...
class InequalityToEquality(QuadraticProgramConverter): _delimiter = '' def __init__(self, mode: str='auto') -> None: self._src: Optional[QuadraticProgram] = None self._dst: Optional[QuadraticProgram] = None self._mode = mode def convert(self, problem: QuadraticProgram) -> QuadraticPr...
def main(args): cfg = setup(args) model = build_model(cfg) logger.info('Model:\n{}'.format(model)) if args.eval_only: DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume) if cfg.TEST.AUG.ENABLED: logger.info('Running infe...
def test_flake8_per_file_ignores(workspace): config_str = '[flake8]\nignores = F403\nper-file-ignores =\n **/__init__.py:F401,E402\n test_something.py:E402,\nexclude =\n file_1.py\n file_2.py\n ' doc_str = "print('hi')\nimport os\n" doc_uri = uris.from_fs_path(os.path.join(workspace.root_path...
def MCLDNN(weights=None, input_shape1=[2, 128], input_shape2=[128, 1], classes=11, **kwargs): if ((weights is not None) and (not os.path.exists(weights))): raise ValueError('The `weights` argument should be either `None` (random initialization), or the path to the weights file to be loaded.') dr = 0.5 ...
class ImplementationWrapper(object): def __init__(self, instance, field_name, transition, workflow, implementation, hooks=None): self.instance = instance self.field_name = field_name self.transition = transition self.workflow = workflow self.hooks = (hooks or {}) self...
def test_upload_pypirc_file(copy_sample): with temp_pypirc(pypirc3) as pypirc, patch('flit.upload.upload_file') as upload_file: td = copy_sample('module1_toml') formats = list(ALL_FORMATS)[:1] upload.main((td / 'pyproject.toml'), formats=set(formats), repo_name='test123', pypirc_path=pypirc)...
def ssim(img1, img2, window_size=11, mask=None, size_average=True): (_, channel, _, _) = img1.size() window = create_window(window_size, channel) if img1.is_cuda: window = window.cuda(img1.get_device()) window = window.type_as(img1) return _ssim(img1, img2, window, window_size, channel, mask...
class LLL_Net(nn.Module): def __init__(self, model, remove_existing_head=False): head_var = model.head_var assert (type(head_var) == str) assert ((not remove_existing_head) or hasattr(model, head_var)), 'Given model does not have a variable called {}'.format(head_var) assert ((not re...
def uninstall_variables(name=JTOP_VARIABLE_FILE): if os.path.isfile('/etc/profile.d/{name}'.format(name=name)): logger.info('Found {name}'.format(name=name)) os.remove('/etc/profile.d/{name}'.format(name=name)) logger.info(' - Remove {name} from /etc/profile.d/'.format(name=name))
(description='Upload videos to YouTube') def upload_videos_to_youtube(modeladmin, request, queryset): videos = queryset.filter(youtube_video_id__exact='').exclude(video_uploaded_path__exact='') conference_id = queryset.first().conference_id start_workflow(workflow=BatchMultipleScheduleItemsVideoUpload.run, ...
def is_proper_subtype(left: Type, right: Type, *, subtype_context: (SubtypeContext | None)=None, ignore_promotions: bool=False, ignore_uninhabited: bool=False, erase_instances: bool=False, keep_erased_types: bool=False) -> bool: if (subtype_context is None): subtype_context = SubtypeContext(ignore_promotion...
def test_strict_option_is_deprecated(pytester: Pytester) -> None: pytester.makepyfile('\n import pytest\n\n .unknown\n def test_foo(): pass\n ') result = pytester.runpytest('--strict', '-Wdefault::pytest.PytestRemovedIn8Warning') result.stdout.fnmatch_lines(["'unknown' not found ...
(frozen=True) class MultiplayerSessionEntry(JsonDataclass): id: int name: str worlds: list[MultiplayerWorld] users_list: list[MultiplayerUser] game_details: (GameDetails | None) visibility: MultiplayerSessionVisibility generation_in_progress: (int | None) allowed_games: list[RandovaniaGa...
def msrvtt_zh(msrvtt_train_captions): print(('-' * 20)) print('Prepare msrvtt_zh') msrvtt_cn_path = 'data/MSRVTT-CN/msrvtt10kcntrain_google_enc2zh.caption.txt' assert os.path.exists(msrvtt_cn_path), msrvtt_cn_path data = open(msrvtt_cn_path, 'r').read().strip().split('\n') vid2Chinese_captions =...
class FC3_Duplicate_TestCase(CommandSequenceTest): def __init__(self, *args, **kwargs): CommandSequenceTest.__init__(self, *args, **kwargs) self.version = FC3 def runTest(self): self.assert_parse('\nlogvol / --size=1024 --name=nameA --vgname=vgA\nlogvol /home --size=1024 --name=nameB --v...
class cLSTM(nn.Module): def __init__(self, emodict, worddict, embedding, args): super(cLSTM, self).__init__() self.num_classes = emodict.n_words self.embeddings = embedding self.utt_cnn = CNNencoder(args.d_word_vec, 64, 100, [3, 4, 5]) self.dropout_in = nn.Dropout(0.3) ...
class AttrVI_ATTR_TRIG_ID(EnumAttribute): resources = [(constants.InterfaceType.gpib, 'INSTR'), (constants.InterfaceType.gpib, 'INTFC'), (constants.InterfaceType.pxi, 'INSTR'), (constants.InterfaceType.pxi, 'BACKPLANE'), (constants.InterfaceType.asrl, 'INSTR'), (constants.InterfaceType.tcpip, 'INSTR'), (constants.I...
def annotate_streets(df, img, text_col): if (not os.path.exists(FONT_PATH)): print('Error loading default font. Check your FONT_PATH') return None unique_sts = df[text_col].unique() for street in unique_sts: draw_coords = df.loc[((df.ST_NAME == street), 'draw_coords')].tolist()[0] ...
class BalanceProofData(): def __init__(self, canonical_identifier): self._canonical_identifier = canonical_identifier self._pending_locks = make_empty_pending_locks_state() self.properties = None def update(self, amount, lock): self._pending_locks = channel.compute_locks_with(sel...
def _iter_num_atoms_for_radii(mol, min_radius, max_radius, start_atoms): unique_atoms = set(start_atoms) assert (len(start_atoms) == len(unique_atoms)), 'duplicate start atom' ignore_atoms = set((a for a in start_atoms if (not is_heavy_atom(mol.GetAtomWithIdx(a))))) (yield (len(unique_atoms) - len(ignor...
def train(model, dataloader, optimizer, criterion, epoch_number, max_gradient_norm): model.train() device = model.device epoch_start = time.time() batch_time_avg = 0.0 running_loss = 0.0 preds = [] golds = [] for (batch_index, batch) in enumerate(dataloader): batch_start = time.t...
def test_sub(): x = Bits(4, 5) y = Bits(4, 4) assert ((x - y) == 1) assert ((x - Bits(4, 4)) == 1) assert ((x - 4) == 1) y = Bits(4, 5) assert ((x - y) == 0) assert ((x - 5) == 0) y = Bits(4, 7) assert ((x - y) == 14) assert ((x - 7) == 14) assert ((9 - x) == 4) with ...
def verify_module(fscache: FileSystemCache, id: str, path: str, prefix: str) -> bool: if is_init_file(path): path = os.path.dirname(path) for i in range(id.count('.')): path = os.path.dirname(path) if (not any((fscache.isfile_case(os.path.join(path, f'__init__{extension}'), prefix) for e...
.parametrize('qubitop, state_binary', [((QubitOperator('Z0 Z1 Z2 Z3', (- 1.0)) + QubitOperator('X0 Y1 Y2 X3', 1.0)), '1100'), ((QubitOperator('X0 X3', (- 1.0)) + QubitOperator('Y1 Y2', 1.0)), '0000')]) def test_expectation_values_paulisum(qubitop, state_binary): n_qubits = openfermion.count_qubits(qubitop) stat...
class AdminRecord(models.Model): record_modes = (('ssh', 'ssh'), ('guacamole', 'guacamole')) admin_login_user = models.ForeignKey('users.UserProfile', verbose_name='', on_delete=models.CASCADE) admin_server = models.CharField(max_length=32, verbose_name='') admin_remote_ip = models.GenericIPAddressField...
class Event(): def __init__(self, should_lock: bool=False) -> None: self._items: list[Callable[(..., Any)]] = [] self._should_lock = should_lock self._event = threading.Event() def set(self, *args: Any, **kwargs: Any) -> bool: def execute(): for func in self._items: ...
.parametrize(('locations_to_collect', 'exists'), [((0,), ()), ((0,), (0,)), ((0, 1), ()), ((0, 1), (0,)), ((0, 1), (0, 1))]) def test_collect_locations_other(flask_app, two_player_session, echoes_resource_database, locations_to_collect: tuple[(int, ...)], exists: tuple[(int, ...)], mocker: pytest_mock.MockerFixture): ...
def compute_predictions_logits(all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file, verbose_logging, version_2_with_negative, null_score_diff_threshold, tokenizer): if output_prediction_file: logger.info...
def test_read_write_mem(cmdline_opts): rgen = random.Random() rgen.seed() data = [rgen.randrange((- (2 ** 31)), (2 ** 31)) for _ in range(20)] data_bytes = struct.pack('<{}i'.format(len(data)), *data) msgs = [] for (i, item) in enumerate(data): msgs.extend([req('rd', 1, (4096 + (4 * i)),...
def get_parser(): parser = argparse.ArgumentParser('Prints a table from metrics files\n') parser.add_argument('--config', '-c', type=str, default='config.csv', help='Path to the config csv with `name` and `path` columns. `name` is a model name, and `path` is a path to metrics file`') parser.add_argument('--...
class ConvNeXtBlock(nn.Module): def __init__(self, in_chs, out_chs=None, kernel_size=7, stride=1, dilation=1, mlp_ratio=4, conv_mlp=False, conv_bias=True, ls_init_value=1e-06, act_layer='gelu', norm_layer=None, drop_path=0.0): super().__init__() out_chs = (out_chs or in_chs) act_layer = get_...
def parse_wheel_filename(filename: str) -> Tuple[(NormalizedName, Version, BuildTag, FrozenSet[Tag])]: if (not filename.endswith('.whl')): raise InvalidWheelFilename(f"Invalid wheel filename (extension must be '.whl'): {filename}") filename = filename[:(- 4)] dashes = filename.count('-') if (das...
def test_invert_error_at(): phys_err = 0.001 budgets = np.logspace((- 1), (- 18)) for budget in budgets: d = qecs.FowlerSuperconductingQubits.code_distance_from_budget(physical_error_rate=phys_err, budget=budget) assert ((d % 2) == 1) assert (qecs.FowlerSuperconductingQubits.logical_...
def main(args): assert ((len(args) == 3) and isinstance(args[1], str) and isinstance(args[2], str)) dataset_name = args[1] model_name = args[2] tf.set_random_seed(1234) coord_add = get_coord_add(dataset_name) dataset_size_train = get_dataset_size_train(dataset_name) dataset_size_test = get_d...
class ZGate(Bloq): _property def signature(self) -> 'Signature': return Signature.build(q=1) def short_name(self) -> 'str': return 'Z' def decompose_bloq(self) -> CompositeBloq: raise DecomposeTypeError(f'{self} is atomic') def add_my_tensors(self, tn: qtn.TensorNetwork, tag:...
class Logger(object): def __init__(self, args): self.args = args self.save_dir = args.log_dir self.is_primary = is_primary() if self.is_primary: os.makedirs(self.save_dir, exist_ok=True) self.config_dir = os.path.join(self.save_dir, 'configs') os.m...
class ArcCos(UnaryScalarOp): nfunc_spec = ('arccos', 1, 1) def impl(self, x): x_dtype = str(getattr(x, 'dtype', '')) if (x_dtype in ('int8', 'uint8')): return np.arccos(x, dtype=np.float32) return np.arccos(x) def L_op(self, inputs, outputs, gout): (x,) = inputs ...
def calculate_sentence_transformer_embedding(examples, embedding_model, mean_normal=False): if (not args.add_prompt): text_to_encode = [raw_item['text'] for raw_item in examples] else: text_to_encode = [['Represent the civil comment; Input: ', raw_item['text'], 0] for raw_item in examples] n...
class webvision_dataloader(): def __init__(self, batch_size, num_class, num_workers, root_dir, log): self.batch_size = batch_size self.num_class = num_class self.num_workers = num_workers self.root_dir = root_dir self.log = log self.transform_train = transforms.Compos...
class _NodeTest(unittest.TestCase): CODE = '' def astroid(self) -> Module: try: return self.__class__.__dict__['CODE_Astroid'] except KeyError: module = builder.parse(self.CODE) self.__class__.CODE_Astroid = module return module
def _parseASN1PrivateKey(s): s = ASN1_Node(s) root = s.root() version_node = s.first_child(root) version = bytestr_to_int(s.get_value_of_type(version_node, 'INTEGER')) if (version != 0): raise SyntaxError('Unrecognized RSAPrivateKey version') n = s.next_node(version_node) e = s.next_...
def test_basic_push_by_manifest_digest(manifest_protocol, basic_images, liveserver_session, app_reloader): credentials = ('devtable', 'password') options = ProtocolOptions() options.push_by_manifest_digest = True result = manifest_protocol.push(liveserver_session, 'devtable', 'newrepo', 'latest', basic_...
class ValidatorTestMixin(MetaSchemaTestsMixin): def test_it_implements_the_validator_protocol(self): self.assertIsInstance(self.Validator({}), protocols.Validator) def test_valid_instances_are_valid(self): (schema, instance) = self.valid self.assertTrue(self.Validator(schema).is_valid(in...
class Dataset(torch.utils.data.Dataset): def __init__(self, args, datas, images, split): self.split = split self.dataset = args.dataset self.data_path = args.data_path self.datas = datas self.images = images print(' {} set has {} datas'.format(split, len(self.datas)))...
def blackbox(blackbox): if (tuple(sorted(blackbox.output_indices)) != blackbox.output_indices): raise ValueError('Output indices {} must be ordered'.format(blackbox.output_indices)) partition(blackbox.partition) for part in blackbox.partition: if (not (set(part) & set(blackbox.output_indices...
class Discard(ScrimsButton): def __init__(self, ctx: Context, label='Back', row: int=None): super().__init__(style=discord.ButtonStyle.red, label=label, row=row) self.ctx = ctx async def callback(self, interaction: Interaction): (await interaction.response.defer()) from .main imp...
def test_load_successful_with_invalid_distribution(caplog: LogCaptureFixture, mocker: MockerFixture, env: MockEnv, tmp_path: Path) -> None: invalid_dist_info = ((tmp_path / 'site-packages') / 'invalid-0.1.0.dist-info') invalid_dist_info.mkdir(parents=True) mocker.patch('poetry.utils._compat.metadata.Distrib...
class ImageData(AbstractImage): _swap1_pattern = re.compile(asbytes('(.)'), re.DOTALL) _swap2_pattern = re.compile(asbytes('(.)(.)'), re.DOTALL) _swap3_pattern = re.compile(asbytes('(.)(.)(.)'), re.DOTALL) _swap4_pattern = re.compile(asbytes('(.)(.)(.)(.)'), re.DOTALL) _current_texture = None _c...
def build_loader(data_path, autoaug, batch_size, workers): rank = dist.get_rank() world_size = dist.get_world_size() assert ((batch_size % world_size) == 0), f'The batch size is indivisible by world size {batch_size} // {world_size}' train_transform = create_transform(input_size=224, is_training=True, a...
def run_evolution_search(max_time_budget=5000000.0, population_size=50, tournament_size=10, mutation_rate=1.0): nasbench.reset_budget_counters() (times, best_valids, best_tests) = ([0.0], [0.0], [0.0]) population = [] for _ in range(population_size): spec = random_spec() data = nasbench....
def main(): api_key = os.environ.get('QUANDL_API_KEY') start_date = '2014-1-1' end_date = '2015-1-1' symbols = ('AAPL', 'BRK_A', 'MSFT', 'ZEN') url = format_table_query(api_key=api_key, start_date=start_date, end_date=end_date, symbols=symbols) print(('Fetching equity data from %s' % url)) r...
def build_usage_examples(dag: ProvDAG, cfg: ReplayConfig, ns: NamespaceCollections): sorted_nodes = nx.topological_sort(dag.collapsed_view) actions = group_by_action(dag, sorted_nodes, ns) for node_id in actions.no_provenance_nodes: node = dag.get_node_data(node_id) build_no_provenance_node_...
def test_interface_array(do_test): class Ifc(Interface): def construct(s): s.msg = InPort(Bits32) s.val = InPort(Bits1) s.rdy = OutPort(Bits1) class A(Component): def construct(s): s.ifc = [Ifc() for _ in range(2)] a = A() a._ref_ports = [(...
def auto_augment_transform(config_str, hparams): config = config_str.split('-') policy_name = config[0] config = config[1:] for c in config: cs = re.split('(\\d.*)', c) if (len(cs) < 2): continue (key, val) = cs[:2] if (key == 'mstd'): hparams.setd...
class CheckpointFunction(torch.autograd.Function): def forward(ctx, run_function, preserve_rng_state, *args): check_backward_validity(args) ctx.run_function = run_function ctx.preserve_rng_state = preserve_rng_state ctx.had_autocast_in_fwd = torch.is_autocast_enabled() ctx.in...
def test_load_config(track_widget): original_config_name = track_widget.config_name.currentText() with patch('btrack.napari.widgets.load_path_dialogue_box') as load_path_dialogue_box: load_path_dialogue_box.return_value = btrack.datasets.cell_config() track_widget.load_config_button.click() ...
class AugmentationCfg(): scale: Tuple[(float, float)] = (0.9, 1.0) ratio: Optional[Tuple[(float, float)]] = None color_jitter: Optional[Union[(float, Tuple[(float, float, float)])]] = None interpolation: Optional[str] = None re_prob: Optional[float] = None re_count: Optional[int] = None use_...
def test_foo_field_as_writer(): class FooStruct_wrap(Component): def construct(s): s.in_ = InPort(Bits16) s.out = OutPort(Bits32) s.inner = FooStruct(16) s.inner.in_ //= s.in_ connect(s.inner.out.b, s.out) def line_trace(s): ret...
class HandshakeType(enum.IntEnum): hello_request = 0 client_hello = 1 server_hello = 2 hello_verify_request = 3 new_session_ticket = 4 end_of_early_data = 4 encrypted_extensions = 8 certificate = 11 server_key_exchange = 12 certificate_request = 13 server_hello_done = 14 ...
def get_random_cached_bottlenecks(sess, image_lists, how_many, category, bottleneck_dir, image_dir, jpeg_data_tensor, bottleneck_tensor): class_count = len(image_lists.keys()) bottlenecks = [] ground_truths = [] filenames = [] if (how_many >= 0): for unused_i in range(how_many): ...
class PoolFormer(nn.Module): def __init__(self, layers, embed_dims=(64, 128, 320, 512), mlp_ratios=(4, 4, 4, 4), downsamples=(True, True, True, True), pool_size=3, in_chans=3, num_classes=1000, global_pool='avg', norm_layer=GroupNorm1, act_layer=nn.GELU, in_patch_size=7, in_stride=4, in_pad=2, down_patch_size=3, do...
def find_mutated(form): if isinstance(form, W_Correlated): return find_mutated(form.get_obj()) elif isinstance(form, values.W_Cons): if (not form.is_proper_list()): (elements, _) = to_rpython_list(form, unwrap_correlated=True, improper=True) return extend_dicts([find_muta...
def target_directory(output_path: Optional[str]=None) -> str: if output_path: if (not os.path.isabs(output_path)): output_path = os.path.join(os.getcwd(), output_path) else: output_path = os.getcwd() os.makedirs(output_path, exist_ok=True) return output_path
def _word_forms_from_xml_elem(elem): lexeme = [] lex_id = elem.get('id') if (len(elem) == 0): return (lex_id, lexeme) base_info = list(elem.iter('l')) assert (len(base_info) == 1) base_grammemes = _grammemes_from_elem(base_info[0]) for form_elem in elem.iter('f'): grammemes =...
def translate_to_vocab(tokens, vocab, vocab_translate, skip_new_tokens=False): if vocab_translate.contains_same_content(vocab): return tokens lang_orig = tokens_to_lang(tokens, vocab, join=False) tokens_new = [] for word in lang_orig: if (skip_new_tokens and (word not in vocab_translate....
def enable_oeenclave_debug(oe_enclave_addr): enclave = oe_debug_enclave_t(oe_enclave_addr) if (not enclave.is_valid()): return False if (enclave.debug == 0): print(('oegdb: Debugging not enabled for enclave %s' % enclave.path)) return False if (enclave.simulate != 0): pri...
def get_acceleration_bw_models(year1, year2, model_path, selected_ngrams, all_model_vectors, top_k_acc): model_path1 = os.path.join(model_path, (year1 + '.model')) model_path2 = os.path.join(model_path, (year2 + '.model')) (word_pairs, em1, em2) = compute_acc_between_years(selected_ngrams, model_path1, mode...
def format_skeleton(skeleton: str, datetime: _Instant=None, tzinfo: (datetime.tzinfo | None)=None, fuzzy: bool=True, locale: ((Locale | str) | None)=LC_TIME) -> str: locale = Locale.parse(locale) if (fuzzy and (skeleton not in locale.datetime_skeletons)): skeleton = match_skeleton(skeleton, locale.datet...
def run_query(config, client, query_func, write_func=write_result, sql_context=None): QUERY_NUM = get_query_number() if config.get('dask_profile'): with performance_report(filename=f'q{QUERY_NUM}_profile.html'): if sql_context: run_sql_query(config=config, client=client, quer...
class CollectSessionComparisonData(): def __init__(self, pathserv, pathserv_other, fn_count_bads): self.pathserv = pathserv self.pathserv_other = pathserv_other samples = {e for e in fs.load_session_playlist(pathserv)} other_samples = {e for e in fs.load_session_playlist(pathserv_oth...
class ProcessStatCollector(diamond.collector.Collector): PROC = '/proc/stat' def get_default_config_help(self): config_help = super(ProcessStatCollector, self).get_default_config_help() config_help.update({}) return config_help def get_default_config(self): config = super(Pro...
def test_nested_process_search(cbc_product: CbEnterpriseEdr, mocker): with open(os.path.join(os.getcwd(), 'tests', 'data', 'cbc_surveyor_testing.json')) as f: programs = json.load(f) cbc_product.log = logging.getLogger('pytest_surveyor') cbc_product._sensor_group = None cbc_product._results = {}...
class TWaveformSeekBar(PluginTestCase): def setUp(self): self.mod = self.modules['WaveformSeekBar'] def tearDown(self): del self.mod def test_main(self): WaveformScale = self.mod.WaveformScale player = NullPlayer() player.info = AudioFile({'~#length': 10}) sca...
.django_db def test_scope_multisite(site1, site2, comment1, comment2): with scope(site=[site1]): assert (list(Comment.objects.all()) == [comment1]) with scope(site=[site1, site2]): assert (list(Comment.objects.all()) == [comment1, comment2]) assert (get_scope() == {'site': [site1, site2]...
def test_fbo_head(): lfb_prefix_path = osp.normpath(osp.join(osp.dirname(__file__), '../data/lfb')) st_feat_shape = (1, 16, 1, 8, 8) st_feat = generate_backbone_demo_inputs(st_feat_shape) rois = torch.randn(1, 5) rois[0][0] = 0 img_metas = [dict(img_key='video_1, 930')] fbo_head = FBOHead(lf...
class WideResNet(nn.Module): def __init__(self, depth=28, widen_factor=10, num_classes=None, dropout_rate=0.3): super().__init__() assert (((depth - 4) % 6) == 0), 'Wide-resnet depth should be 6n+4' self.dropout_rate = dropout_rate n = ((depth - 4) // 6) k = widen_factor ...
def _get_backend_kernel(dtype, grid, block, k_type): kernel = _cupy_kernel_cache[(dtype, k_type)] if kernel: return _cupy_channelizer_wrapper(grid, block, kernel) else: raise ValueError('Kernel {} not found in _cupy_kernel_cache'.format(k_type)) raise NotImplementedError('No kernel found...
class TestSuite(object): _KNOWN_CACHES = {'species_pattern_matcher': SpeciesPatternMatcher, 'rule_pattern_matcher': RulePatternMatcher, 'reaction_pattern_matcher': ReactionPatternMatcher} _COL = {'OK': '\x1b[92m', 'FAIL': '\x1b[91m', 'END': '\x1b[0m'} def __init__(self, model=None): self._caches = {...
def terraform_remote_state_s3(name: str, **body: Any) -> Block: body['backend'] = 's3' config = body.get('config', {}) if config.get('profile'): session = get_session(profile_name=config['profile']) creds = session.get_credentials() if (not _profile_creds_definitely_supported_by_terr...
def pseudonymise_buffer_list(file_buffer_list: list): if ((file_buffer_list is not None) and (len(file_buffer_list) > 0)): my_date_time = datetime.datetime.now() str_now_datetime = my_date_time.strftime('%Y%m%d_%H%M%S') zipfile_basename = f'Pseudonymised_{str_now_datetime}' bad_data ...