code
stringlengths
281
23.7M
_model def resmlp_big_24_distilled_224(pretrained=False, **kwargs): model_args = dict(patch_size=8, num_blocks=24, embed_dim=768, mlp_ratio=4, block_layer=partial(ResBlock, init_values=1e-06), norm_layer=Affine, **kwargs) model = _create_mixer('resmlp_big_24_distilled_224', pretrained=pretrained, **model_args) ...
def read_crn(filename, map_variables=True): data = pd.read_fwf(filename, header=None, names=HEADERS, widths=WIDTHS, dtype=str) data = data.dropna(axis=0, how='all') data = data.astype(dict(zip(HEADERS, DTYPES))) data = data.replace(NAN_DICT, value=np.nan) dts = data[['UTC_DATE', 'UTC_TIME']].astype(...
.parametrize('frac_dummies', [0.1, 0.5, 0.9]) def test_hdf5_write_dummies(hdf5_file_path, test_objects, frac_dummies): num_dummies = int((len(test_objects) * frac_dummies)) for obj in test_objects[:num_dummies]: obj.dummy = True obj.ID = (- (obj.ID + 1)) track_id = 1 track_with_dummies =...
def load(fnames, tag='', inst_id='', malformed_index=False, start_time=None, num_samples=864, test_load_kwarg=None, max_latitude=90.0): pysat.logger.info(''.join(('test_load_kwarg = ', str(test_load_kwarg)))) iperiod = mm_test.define_period() drange = mm_test.define_range() (uts, index, dates) = mm_test...
def main() -> None: application = Application.builder().token('TOKEN').build() conv_handler = ConversationHandler(entry_points=[CommandHandler('start', start)], states={START_ROUTES: [CallbackQueryHandler(one, pattern=(('^' + str(ONE)) + '$')), CallbackQueryHandler(two, pattern=(('^' + str(TWO)) + '$')), Callba...
def configure_converter(converter: BaseConverter): converter.register_unstructure_hook(bytes, (lambda v: (b85encode(v) if v else b'').decode('utf8'))) converter.register_structure_hook(bytes, (lambda v, _: b85decode(v))) converter.register_structure_hook(datetime, (lambda v, _: datetime.fromisoformat(v))) ...
class ScrimSetup(ScrimsView): def __init__(self, ctx: Context): super().__init__(ctx, timeout=60) self.ctx = ctx self.record: Scrim = None self.add_item(RegChannel(ctx, 'a')) self.add_item(SlotChannel(ctx, 'b')) self.add_item(SetRole(ctx, 'c')) self.add_item(S...
def dicom_dataset_from_dict(input_dict: dict, template_ds=None): if (template_ds is None): dataset = pydicom.Dataset() else: dataset = deepcopy(template_ds) for (key, value) in input_dict.items(): if (key not in get_dicom_names()): raise ValueError('{} is not within the D...
def test_list_from_entry_points(): ext_list = extensions.list_from_entry_points() orig_len = len(ext_list) assert all((isinstance(e, extensions.Extension) for e in ext_list)) name_list = [e.name for e in ext_list] for ext in ('cirrus', 'pre_commit', 'no_skeleton', 'namespace', 'venv'): asser...
(short_help='Display project metadata') ('field', required=False) _obj def metadata(app, field): import json from hatchling.dep.core import dependencies_in_sync if dependencies_in_sync(app.project.metadata.build.requires_complex): from hatchling.metadata.utils import resolve_metadata_fields ...
def missing_info(modules: dict[(str, MypyFile)]) -> TypeInfo: suggestion = _SUGGESTION.format('info') dummy_def = ClassDef(suggestion, Block([])) dummy_def.fullname = suggestion info = TypeInfo(SymbolTable(), dummy_def, '<missing>') obj_type = lookup_fully_qualified_typeinfo(modules, 'builtins.objec...
def depthwise_conv_bn(x, kernel_size, strides=1, dilation=1): with tf.variable_scope(None, 'depthwise_conv_bn'): x = slim.separable_conv2d(x, None, kernel_size, depth_multiplier=1, stride=strides, rate=dilation, activation_fn=None, biases_initializer=None) x = slim.batch_norm(x, activation_fn=None, ...
class _ConfigExpander(): def __init__(self, config: dict, root_dir: Optional[_Path]=None, ignore_option_errors: bool=False, dist: Optional['Distribution']=None): self.config = config self.root_dir = (root_dir or os.getcwd()) self.project_cfg = config.get('project', {}) self.dynamic =...
class LogicalLineFinder(): def __init__(self, lines): self.lines = lines def logical_line_in(self, line_number): indents = count_line_indents(self.lines.get_line(line_number)) tries = 0 while True: block_start = get_block_start(self.lines, line_number, indents) ...
class RepoMirrorConfig(BaseModel): repository = ForeignKeyField(Repository, index=True, unique=True, backref='mirror') creation_date = DateTimeField(default=datetime.utcnow) is_enabled = BooleanField(default=True) mirror_type = ClientEnumField(RepoMirrorType, default=RepoMirrorType.PULL) internal_ro...
class FakeHDF5FileHandler2(FakeHDF5FileHandler): def _get_geo_data(self, num_rows, num_cols): geo = {'Grid/lon': xr.DataArray(DEFAULT_LON_DATA, attrs={'units': 'degrees_east'}, dims='lon'), 'Grid/lat': xr.DataArray(DEFAULT_LAT_DATA, attrs={'units': 'degrees_north'}, dims='lat')} return geo def _...
class CudnnGruEncoder(CudnnRnnEncoder, SequenceEncoder): def __init__(self, n_units, n_layers=1, keep_recurrent=1, w_init=TruncatedNormal(stddev=0.05), recurrent_init=None, bidirectional=True, learn_initial_states=False): super().__init__('GRU', n_units, n_layers, w_init, recurrent_init, bidirectional, lear...
def run_cmd(*cmd: Optional[str], out: Optional[Union[(TeeCapture, IO[str])]]=sys.stdout, err: Optional[Union[(TeeCapture, IO[str])]]=sys.stderr, raise_on_fail: bool=True, log_run_to_stderr: bool=True, abbreviate_non_option_arguments: bool=False, **kwargs) -> CommandOutput: kept_cmd = tuple((cast(str, e) for e in cm...
.parametrize('py_info_name', ['cpython3_win_embed']) def test_no_python_zip_if_exists_and_not_set_in_path(py_info, mock_files): python_zip_name = f'python{py_info.version_nodot}.zip' python_zip = path(py_info.prefix, python_zip_name) py_info.path.remove(python_zip) mock_files(CPYTHON3_PATH, [python_zip]...
def code_to_bitstream(code): code = parse(code).render() data = swap_bytes(code) stream = ['10000', '00000', '11111', '01111', '11111', '01111', '11111'] for c in data: v = int(c, 16) stream.append((((('1' + str((v & 1))) + str(((v & 2) >> 1))) + str(((v & 4) >> 2))) + str(((v & 8) >> 3)...
def update_config(config, args): _update_config_from_file(config, args.cfg) config.defrost() if args.opts: config.merge_from_list(args.opts) if args.batch_size: config.DATA.BATCH_SIZE = args.batch_size if args.zip: config.DATA.ZIP_MODE = True if args.cache_mode: c...
def _encode_path_parts(text_parts, rooted=False, has_scheme=True, has_authority=True, maximal=True): if (not text_parts): return () if rooted: text_parts = ((u'',) + tuple(text_parts)) encoded_parts = [] if has_scheme: encoded_parts = [(_encode_path_part(part, maximal=maximal) if...
class MusicProvider(): def __init__(self, query: Optional[str], key: Optional[int]) -> None: self.query = query self.key = key if (not hasattr(self, 'type')): self.type = 'unknown' assert False self.id: Optional[str] = None self.ok_message = 'ok' ...
def sum_fst(rp_pairs): global quiet n = len(rp_pairs) if (not quiet): print(('Processing statistics from session 1 of %d' % (n,))) total_fst = make_fst(*rp_pairs[0]) for i in range(1, n): if (not quiet): print(('Processing statistics from session %d of %d' % ((i + 1), n))...
def test_entity_search(auth_engine, requires_email, client): with auth_engine(requires_email=requires_email) as auth: with patch('endpoints.api.search.authentication', auth): response = conduct_api_call(client, EntitySearch, 'GET', params=dict(prefix='unknown')) results = response.js...
def test_non_total(): assert (get_typed_dict_shape(Bar) == Shape(input=InputShape(constructor=Bar, kwargs=None, fields=(InputField(type=int, id='a', default=NoDefault(), is_required=False, metadata=MappingProxyType({}), original=None), InputField(type=str, id='b', default=NoDefault(), is_required=False, metadata=Ma...
def test_num_complex_while_else_labels() -> None: src = "\n i = 0\n while i < 10:\n j = 0\n while j < 5:\n j += 1\n i += 1\n\n if i > 4:\n print('hi')\n else:\n print('is else')\n\n print('not else')\n " expected_num_labels = 6 assert (...
class ThreadForReqChannel(threading.Thread): def __init__(self, channel): threading.Thread.__init__(self) if (not isinstance(channel, RepChannel)): raise ValueError('The given channel must be a REP channel.') self._channel = channel if (sys.version_info < (2, 6)): ...
.parametrize(('project_directory', 'required_fixtures'), [('project_with_local_dependencies', ['distributions/demo-0.1.0-py2.py3-none-any.whl', 'project_with_setup'])]) def test_show_outdated_local_dependencies(tester: CommandTester, poetry: Poetry, installed: Repository, repo: TestRepository) -> None: cachy_010 = ...
def _make_along_axis_idx(arr_shape, indices, axis): if (str(indices.dtype) not in int_types): raise IndexError('`indices` must be an integer array') shape_ones = ((1,) * indices.ndim) dest_dims = ((list(range(axis)) + [None]) + list(range((axis + 1), indices.ndim))) fancy_index = [] for (dim...
def main(_): train_dir = os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name, 'train') utils.force_mkdir(os.path.join(FLAGS.checkpoint_dir, FLAGS.model_name)) utils.force_mkdir(train_dir) g = tf.Graph() with g.as_default(): with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks)): ...
class DNSOutgoing(): __slots__ = ('flags', 'finished', 'id', 'multicast', 'packets_data', 'names', 'data', 'size', 'allow_long', 'state', 'questions', 'answers', 'authorities', 'additionals') def __init__(self, flags: int, multicast: bool=True, id_: int=0) -> None: self.flags = flags self.finish...
class BaseOAuth2(OAuthAuth): REFRESH_TOKEN_URL = None REFRESH_TOKEN_METHOD = 'POST' RESPONSE_TYPE = 'code' REDIRECT_STATE = True STATE_PARAMETER = True USE_BASIC_AUTH = False def use_basic_auth(self): return self.USE_BASIC_AUTH def auth_params(self, state=None): (client_i...
class Effect5754(BaseEffect): type = 'overheat' def handler(fit, module, context, projectionRange, **kwargs): module.boostItemAttr('maxRangeBonus', module.getModifiedItemAttr('overloadTrackingModuleStrengthBonus'), **kwargs) module.boostItemAttr('falloffBonus', module.getModifiedItemAttr('overlo...
class TouchDelete(RPathTest): def testTouch(self): t = rpath.RPath(self.lc, self.write_dir, ('testtouch',)) self.assertFalse(t.lstat()) t.touch() self.assertTrue(t.lstat()) t.delete() def testDelete(self): d = rpath.RPath(self.lc, self.write_dir, ('testdelete',)) ...
class DeleteRemovedAttrs_TestCase(unittest.TestCase): def runTest(self): errors = [] commands_dir = os.path.join(os.path.dirname(pykickstart.__file__), 'commands') commands_dir = os.path.abspath(commands_dir) self.assertTrue(os.path.exists(commands_dir)) if (commands_dir not ...
class ClassifierModule(nn.Module): def __init__(self, m, channel, num_classes): super(ClassifierModule, self).__init__() self.m = m self.linear = nn.Linear(channel, num_classes) def forward(self, x): res = self.m(x) res = res.view(res.size(0), (- 1)) return self.l...
def collate_function(batch): graphs_as_adjlist = [elem[0] for elem in batch] targets = [elem[1] for elem in batch] graphs_as_adjlist_catted = graphs_as_adjlist[0].concatenate(graphs_as_adjlist) graphs_as_adjlist_catted.inplace_from_np_to_torch() targets = torch.from_numpy(np.array(targets)) retu...
def msid_descriptor(x, ts=np.logspace((- 1), 1, 256), k=5, m=10, niters=100, rademacher=False, graph_builder='sparse', normalized_laplacian=True, normalize='empty'): Lx = _build_graph(x, k, graph_builder, normalized_laplacian) nx = Lx.shape[0] msidx = slq_red_var(Lx, m, niters, ts, rademacher) normed_ms...
class ApproveSponsorshipAdminViewTests(TestCase): def setUp(self): self.user = baker.make(settings.AUTH_USER_MODEL, is_staff=True, is_superuser=True) self.client.force_login(self.user) self.sponsorship = baker.make(Sponsorship, status=Sponsorship.APPLIED, _fill_optional=True) self.ur...
def client_with_identity(auth_username, app): if (auth_username and (auth_username is not None)): loaded = model.user.get_user(auth_username) else: loaded = None with app.test_client(user=loaded) as cl: (yield cl) with cl.session_transaction() as sess: sess['_user...
('pytube.request.get') ('pytube.cli.YouTube.__init__', return_value=None) def test_load_more(youtube, request_get, playlist_html): url = ' request_get.side_effect = [playlist_html, '{"content_html":"", "load_more_widget_html":""}'] playlist = Playlist(url) assert (len(list(playlist.videos)) == 12) r...
class PhysicalParameter(VectorParameter): def __init__(self, name, uncertaintyType='absolute', **kwargs): super().__init__(name, length=2, **kwargs) self._utype = ListParameter('uncertainty type', choices=['absolute', 'relative', 'percentage'], default=None) self._utype.value = uncertaintyTy...
def pretty_print_requirement_array(requirement: RequirementArrayBase, level: int) -> Iterator[tuple[(int, str)]]: if ((len(requirement.items) == 1) and (requirement.comment is None)): (yield from pretty_print_requirement(requirement.items[0], level)) return resource_requirements = [item for item...
def check_encoded_labels(sentences, labels, itow): for sent in sentences: print(('gd-truth: %s' % ' '.join(sent['tokens']))) h5_id = sent['h5_id'] label = labels[h5_id].tolist() decoded = ' '.join([itow[i] for i in label if (i != 0)]) print(('decoded : %s' % decoded)) ...
def dL_dMu(mu, C_hat, m, r): global dLdMu_numers if (len(dLdMu_numers) == 0): dLdMu_numers = [(r[i] * (C_hat[i][0] - C_hat[i][1])) for i in range(m)] total_sum = 0 mu1 = (1 - mu) for i in range(m): total_sum += (dLdMu_numers[i] / ((C_hat[i][0] * mu) + (C_hat[i][1] * mu1))) return...
class BaseDataLoader(object): def __init__(self, dataset, batch_size, repeat=1, shuffle=True, seed=0, drop_last_sample=False, drop_last_batch=True, num_workers=0, prefetch_factor=2): self._dataset = dataset self._batch_size = batch_size self.repeat = repeat self.shuffle = shuffle ...
class AttentionLayer(nn.Module): def __init__(self, channel): super().__init__() self.convs = nn.ModuleList([nn.Conv2d(channel, channel, kernel_size=3, stride=1, padding=1) for _ in range(4)]) def forward(self, xs, anchor): ans = torch.ones_like(anchor) target_size = anchor.shape...
def get_all_objects(start_obj: QObject=None) -> str: output = [''] widget_lines = _get_widgets() widget_lines = [(' ' + e) for e in widget_lines] widget_lines.insert(0, 'Qt widgets - {} objects:'.format(len(widget_lines))) output += widget_lines if (start_obj is None): start_obj = obj...
class ImageNetSubset(data.Dataset): def __init__(self, subset_file, root=MyPath.db_root_dir('imagenet'), split='train', transform=None): super(ImageNetSubset, self).__init__() self.root = os.path.join(root, ('ILSVRC2012_img_%s' % split)) self.transform = transform self.split = split ...
def gaussian_1u1d_instance(layout: QubitsLayout, u: float, dt: float=0.3) -> FermiHubbardParameters: hamiltonian = Hamiltonian(sites_count=layout.size, j=1.0, u=u) initial_state = IndependentChainsInitialState(up=PhasedGaussianSingleParticle(k=(1.2 * 7), sigma=(1.2 / 7), position=(1.5 / 7)), down=PhasedGaussian...
class FileReader(): def __init__(self, binary): self.binary = binary self.offset = 0 def read(self, size): data = self.binary[self.offset:(self.offset + size)] self.offset += size return data def setOffset(self, offset): self.offset = offset def readString...
def python_to_json(o, version=1): if (version not in (1, 2)): raise ValueError(f'Unexpected version {version}') references = [] result = {'v': version, 'data': _py2js(o, references, version=version), 'references': references} if (not result['references']): del result['references'] re...
class Effect6188(BaseEffect): runTime = 'late' type = ('projected', 'active') def handler(fit, container, context, projectionRange, **kwargs): if ('projected' not in context): return if fit.ship.getModifiedItemAttr('disallowAssistance'): return bonus = contain...
def main_worker(gpu, ngpus_per_node, args, loader_args): if (gpu == 0): save_dir = ((args.save_dir + args.name) + '/') if (not os.path.exists(save_dir)): os.makedirs(save_dir) if (not os.path.exists((save_dir + 'results/'))): os.makedirs((save_dir + 'results/')) ...
def random_input_forward_pass(sess, args): np.random.seed(0) model_output = sess.graph.get_tensor_by_name(args['output_tensor']) data = (np.random.randint(16384, size=args['input_shape']) if args['int'] else np.random.rand(*args['input_shape'])) model_inputs = {sess.graph.get_tensor_by_name(args['input_...
class MultiXactStream(Chunks): chunksize = (1024 * 4) _process_chunk = Output._process_tuple_chunk def _e_metas(self): (yield ('chunksize', self.chunksize)) (yield ('type', self.__class__.__name__)) def __init__(self, statement, parameters, cursor_id): self.statement = statement ...
class FakeFCIFileHandlerWithBadIDPFData(FakeFCIFileHandlerFDHSI): def _get_test_content_all_channels(self): data = super()._get_test_content_all_channels() data['data/vis_06/measured/x'].attrs['scale_factor'] *= (- 1) data['data/vis_06/measured/x'].attrs['scale_factor'] = np.float32(data['da...
class PredictUnit(AppStateMixin, _OnExceptionMixin, Generic[TPredictData], ABC): def __init__(self) -> None: super().__init__() self.predict_progress = Progress() def on_predict_start(self, state: State) -> None: pass def on_predict_epoch_start(self, state: State) -> None: pa...
class BertDecoder(nn.Module): def __init__(self, config, embedding=None): super(BertDecoder, self).__init__() if isinstance(config, dict): config = dict2obj(config) self.embedding = (BertEmbeddings(config, return_pos=(True if config.pos_attention else False)) if (embedding is Non...
class SubmissionAdminForm(forms.ModelForm): class Meta(): model = Submission fields = ['title', 'slug', 'speaker', 'status', 'type', 'duration', 'topic', 'conference', 'audience_level', 'languages', 'elevator_pitch', 'abstract', 'notes', 'tags', 'speaker_level', 'previous_talk_video', 'short_social_...
class GAT(nn.Module): def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads, layer): super(GAT, self).__init__() self.dropout = dropout self.layer = layer if (self.layer == 1): self.attentions = [GraphAttentionLayer(nfeat, nclass, dropout=dropout, alpha=alpha, co...
class IssuingDistributionPoint(ExtensionType): oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT def __init__(self, full_name: (typing.Iterable[GeneralName] | None), relative_name: (RelativeDistinguishedName | None), only_contains_user_certs: bool, only_contains_ca_certs: bool, only_some_reasons: (frozenset[ReasonF...
def upgrade(op, tables, tester): op.bulk_insert(tables.logentrykind, [{'name': 'org_create'}, {'name': 'org_delete'}, {'name': 'org_change_email'}, {'name': 'org_change_invoicing'}, {'name': 'org_change_tag_expiration'}, {'name': 'org_change_name'}, {'name': 'user_create'}, {'name': 'user_delete'}, {'name': 'user_d...
_optimizer('adam', dataclass=FairseqAdamConfig) class FairseqAdam(FairseqOptimizer): def __init__(self, cfg: DictConfig, params): super().__init__(cfg) fused_adam_cls = get_fused_adam_class() use_fused_adam = ((not getattr(cfg, 'use_old_adam', False)) and (fused_adam_cls is not None) and tor...
def test(): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for (data, target) in test_loader: (data, target) = (data.to(device), target.to(device)) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() p...
class Rect(object): def __init__(self, id: int, rect_range: mn.Range2D, is_rotated=False): self.id = id self.range = rect_range self.is_rotated = is_rotated def copy(self): return Rect(self.id, mn.Range2D(self.range.bottom_left, self.range.top_right), self.is_rotated) def rot...
_staging_test class ProcessorPushToHubTester(unittest.TestCase): vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] def setUpClass(cls): cls._token = TOKEN HfFolder.save_token(TOKEN) def tearDownClass(cls): try: delete_repo(token=cls._token, repo...
class PreviewTrain(DisplayOptionalPage): def __init__(self, *args, **kwargs): self.update_preview = get_config().tk_vars['updatepreview'] super().__init__(*args, **kwargs) def display_item_set(self): logger.trace('Loading latest preview') if (not self.update_preview.get()): ...
def normalize_size_param(size: Optional[Union[(int, np.ndarray, Variable, Sequence)]]) -> Variable: if (size is None): size = constant([], dtype='int64') elif isinstance(size, int): size = as_tensor_variable([size], ndim=1) elif (not isinstance(size, (np.ndarray, Variable, Sequence))): ...
_shuffle _external_ids _inputs _idtypes _input_type def test_validate_input_geoms(geoms, ids, shuffle, external_ids, input_type): if (ids is not None): geoms = geoms.set_index(ids) input_ids = (geoms.index if external_ids else None) if shuffle: geoms = geoms.sample(frac=1, replace=False) ...
def scenarios(*feature_paths: str, **kwargs: Any) -> None: caller_locals = get_caller_module_locals() caller_path = get_caller_module_path() features_base_dir = kwargs.get('features_base_dir') if (features_base_dir is None): features_base_dir = get_features_base_dir(caller_path) abs_feature_...
def get_pascal_selected_image_annotation_filenames_pairs(pascal_root, selected_names): pascal_relative_images_folder = 'JPEGImages' pascal_relative_class_annotations_folder = 'SegmentationClass' images_extention = 'jpg' annotations_extention = 'png' pascal_images_folder = os.path.join(pascal_root, p...
.parametrize(['solver', 'state'], [pytest.param('me', _equivalence_fock, id='me-ket'), pytest.param('me', _equivalence_coherent, id='me-dm'), pytest.param('me', None, id='me-steady'), pytest.param('es', _equivalence_fock, id='es-ket'), pytest.param('es', _equivalence_coherent, id='es-dm'), pytest.param('es', None, id='...
def test_get_next_page_fr_should_return_2_on_page_1(tmp_path): htmlString = '\n <div class="next-previous-links">\n <div class="previous dl-rounded-borders dl-white-bg">\n <span class="disabled">\n <svg xmlns=" width="16" height="16" fill="currentColor" viewBox="0...
def clustering_perm_acc(pred_labels, true_labels): true_label_set = list(set(true_labels)) logger.info(f'# of unique true labels {len(true_label_set)}') mapping = {label: i for (i, label) in enumerate(true_label_set)} true_labels = [mapping[l] for l in true_labels] best_acc = 0 all_labels = list...
def prep_param_lists(model, flat_master=False): model_params = [param for param in model.parameters() if param.requires_grad] if flat_master: try: master_params = _flatten_dense_tensors([param.data for param in model_params]).float() except: print('Error in prep_param_lis...
class RedisRateLimitBackendContextFactory(ContextFactory): def __init__(self, redis_pool: ConnectionPool, prefix: str='rl:'): self.redis_context_factory = RedisContextFactory(redis_pool) self.prefix = prefix def make_object_for_context(self, name: str, span: Span) -> 'RedisRateLimitBackend': ...
_model() _legacy_interface(weights=('pretrained', ResNeXt101_64X4D_Weights.IMAGENET1K_V1)) def resnext101_64x4d(*, weights: Optional[ResNeXt101_64X4D_Weights]=None, progress: bool=True, **kwargs: Any) -> ResNet: weights = ResNeXt101_64X4D_Weights.verify(weights) _ovewrite_named_param(kwargs, 'groups', 64) _...
_fixtures(WebFixture, PagingFixture) def test_paging(web_fixture, paging_fixture): web_fixture.reahl_server.set_app(paging_fixture.wsgi_app) browser = paging_fixture.browser browser.open('/') assert paging_fixture.is_email_listed('') assert (not paging_fixture.is_email_listed('')) with browser.n...
class CHBlock(dict): def __init__(self, fid, pointer): self.update(_load_header(fid, pointer)) (self['ch_ch_next'], self['ch_ch_first'], self['ch_tx_name'], self['ch_md_comment']) = unpack('<4Q', fid.read(32)) n_links = (self['link_count'] - 4) self['ch_element'] = unpack('<{}Q'.form...
def _read_midi_length(fileobj): (TEMPO, MIDI) = range(2) def read_chunk(fileobj): info = fileobj.read(8) if (len(info) != 8): raise SMFError('truncated') chunklen = struct.unpack('>I', info[4:])[0] data = fileobj.read(chunklen) if (len(data) != chunklen): ...
class IssueViewSet(ReadOnlyModelViewSet): permission_classes = ((HasModelPermission | HasProjectsPermission),) serializer_class = IssueSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ('task', 'task__uri', 'status') def get_queryset(self): return Issue.objects.filter_us...
class ConversionSpecifier(): def __init__(self, match: Match[str], start_pos: int=(- 1), non_standard_format_spec: bool=False) -> None: self.whole_seq = match.group() self.start_pos = start_pos m_dict = match.groupdict() self.key = m_dict.get('key') self.conv_type = m_dict.ge...
def todate(val: Any) -> date: if (not val): raise ValueError('Value not provided') if isinstance(val, datetime): return val.date() elif isinstance(val, date): return val else: try: ival = int(val) sval = str(ival) if (len(sval) == 8): ...
def gen_tutorials(repo_dir: str) -> None: with open(os.path.join(repo_dir, 'website', 'tutorials.json'), 'r') as infile: tutorial_config = json.loads(infile.read()) tutorial_ids = {x['id'] for v in tutorial_config.values() for x in v} for tid in tutorial_ids: print('Generating {} tutorial'.f...
class MemMasterAdapter(Component): def read(s, addr, nbytes): while (s.req_entry is not None): greenlet.getcurrent().parent.switch(0) s.req_entry = s.create_req(MemMsgType.READ, 0, addr, nbytes) while (s.resp_entry is None): greenlet.getcurrent().parent.switch(0) ...
def iou_box(b1, b2): if isinstance(b1, list): b1 = torch.tensor(b1, dtype=torch.float32) if isinstance(b2, list): b2 = torch.tensor(b2, dtype=torch.float32) if isinstance(b1, np.ndarray): b1 = torch.from_numpy(b1.astype(np.float32)) if isinstance(b2, np.ndarray): b2 = tor...
class Camera(): def __init__(self): self.target_points = self._getPoints() self.pixels = MsgCamera() self.projected_points = [] def updateProjectedPoints(self, state, target_position): mav_position = np.array([[state.north], [state.east], [(- state.altitude)]]) R = Euler2...
class LSFJobService(cpi.Service): def __init__(self, api, adaptor): self._mt = None _cpi_base = super(LSFJobService, self) _cpi_base.__init__(api, adaptor) self._adaptor = adaptor def __del__(self): self.close() def close(self): if self.mt: self._l...
def plot(func, filename, **kwargs): (nlats, nlons) = (91, 181) lats = num.linspace((- 90.0), 90.0, nlats) lons = num.linspace((- 180.0), 180.0, nlons) vecfunc = num.vectorize(func, [float]) (latss, lonss) = num.meshgrid(lats, lons) thickness = vecfunc(latss, lonss) from pyrocko.plot import g...
def get_rpc_credentials(config: SimpleConfig) -> Tuple[(str, str)]: rpc_user = config.get('rpcuser', None) rpc_password = config.get('rpcpassword', None) if (rpc_user == ''): rpc_user = None if (rpc_password == ''): rpc_password = None if ((rpc_user is None) or (rpc_password is None)...
def weights_init(m): if isinstance(m, nn.Conv2d): m.weight.data.normal_(0.0, 0.001) elif isinstance(m, nn.Linear): m.weight.data.normal_(0.0, 0.001) elif isinstance(m, nn.LSTMCell): for param in m.parameters(): if (len(param.shape) >= 2): nn.init.orthogona...
def process_one_image(image, resize_height, resize_width, if_zero_one=False): image = tf.image.convert_image_dtype(image, dtype=tf.float32) if if_zero_one: return image image = tf.image.resize_images(image, size=[resize_height, resize_width], method=tf.image.ResizeMethod.BILINEAR) return ((image...
def intersperse(e, iterable, n=1): if (n == 0): raise ValueError('n must be > 0') elif (n == 1): return islice(interleave(repeat(e), iterable), 1, None) else: filler = repeat([e]) chunks = chunked(iterable, n) return flatten(islice(interleave(filler, chunks), 1, None)...
.ddblocal def test_transact_write__error__transaction_cancelled__partial_failure(connection): User(2).delete() BankStatement(2).save() with pytest.raises(TransactWriteError) as exc_info: with TransactWrite(connection=connection) as transaction: transaction.save(User(2), condition=User.us...
def main(config, args): neo4j_uri = config['neo4j_conf']['neo4j_uri'] neo4j_user = config['neo4j_conf']['neo4j_user'] neo4j_password = config['neo4j_conf']['neo4j_password'] data_path = os.path.join(config['offline_datapath']['data_path'], 'aws') if args.name: account_name = args.name ...
class Issue(): id: int node_id: str url: str repository_url: str labels_url: str comments_url: str events_url: str html_url: str number: int state: IssueState state_reason: Optional[StateReason] title: str user: Optional[SimpleUser] labels: List[Label] assigne...
def compute_K_z(x_minimum, sigma, l_vec, noise, d): min_min = cov_max_max(x_minimum, sigma, noise, l_vec) dia_min = cov_diaHess_max(x_minimum, sigma, l_vec) dia_dia = cov_diaHess_diaHess(x_minimum, sigma, l_vec) first_row = np.concatenate((dia_dia, dia_min), axis=1) second_row = np.concatenate((dia_...
def test_test_bloq_with_call_graph(): bwcg = TestBloqWithCallGraph() def all_atoms_the_same(b: Bloq) -> Optional[Bloq]: if isinstance(b, TestAtom): return attrs.evolve(b, tag=None) return b (g, sigma) = bwcg.call_graph(generalizer=all_atoms_the_same) assert (len(sigma) == 3) ...