code
stringlengths
281
23.7M
class Trio_Asyncio_Wrapper(): def __init__(self, proc, loop=None): self.proc = proc self._loop = loop def loop(self): loop = self._loop if (loop is None): loop = current_loop.get() return loop def __get__(self, obj, cls): if (obj is None): ...
def test_transaction_rollback(tmp_path): filename = f'v{RAIDEN_DB_VERSION}_log.db' db_path = Path((tmp_path / filename)) storage = SQLiteStorage(db_path) storage.update_version() assert (storage.get_version() == RAIDEN_DB_VERSION) with pytest.raises(RuntimeError): with storage.transactio...
class EpochBatchIterating(object): def __len__(self) -> int: raise NotImplementedError def next_epoch_idx(self): raise NotImplementedError def next_epoch_itr(self, shuffle=True, pin_memory=False): raise NotImplementedError def end_of_epoch(self) -> bool: raise NotImplemen...
def find_speaker_f0_median_std(speaker_utt_path, fs, window, hop, voiced_prob_cutoff): frame_len_samples = int((fs * window)) hop_len_samples = int((fs * hop)) utterance_files = get_speaker_utterance_paths(speaker_utt_path) k = min(50, len(utterance_files)) utterance_files = random.sample(utterance_...
def load_matrix(embedding_file_path, word_dict, word_embedding_dim): embedding_matrix = np.random.uniform(size=((len(word_dict) + 1), word_embedding_dim)) have_word = [] if (embedding_file_path is not None): with open(embedding_file_path, 'rb') as f: while True: line = f....
_cache(maxsize=512) def parse_git_url(url: str) -> ParsedGitUrl: log.debug('Parsing git url %r', url) normalizers = [('^(\\w+)', 'ssh://\\1'), ('^git\\+ssh://', 'ssh://'), ('(ssh://(?:\\w+)?[\\w.]+):(?!\\d{1,5}/\\w+/)(.*)$', '\\1/\\2'), ('^([C-Z]:/)|^/(\\w)', 'file:///\\1\\2')] for (pattern, replacement) in...
def gen_random_test(): data = [] for i in range(128): data.append(random.randint(0, )) asm_code = [] for i in range(50): a = random.randint(0, 127) b = random.randint(0, 127) base = Bits32((8192 + (4 * b))) offset = Bits16((4 * (a - b))) result = data[a] ...
def test_load_rsa_nist_vectors(): vector_data = textwrap.dedent('\n # CAVS 11.4\n # "SigGen PKCS#1 RSASSA-PSS" information\n # Mod sizes selected: 1024 1536 2048 3072 4096\n # SHA Algorithm selected:SHA1 SHA224 SHA256 SHA384 SHA512\n # Salt len: 20\n\n [mod = 1024]\n\n n = bcb47b2e0dafcba81ff2a...
class SpreadSheetDelegate(QItemDelegate): def __init__(self, parent=None): super(SpreadSheetDelegate, self).__init__(parent) def createEditor(self, parent, styleOption, index): if (index.column() == 1): editor = QDateTimeEdit(parent) editor.setDisplayFormat(self.parent()....
def evaluate(args): model.eval() losses = [] for (step, batch) in enumerate(eval_dataloader): with torch.no_grad(): outputs = model(batch, labels=batch) loss = outputs.loss.repeat(args.valid_batch_size) losses.append(accelerator.gather(loss)) if ((args.max_eval_st...
def get_alt_az(utc_time, lon, lat): lon = np.deg2rad(lon) lat = np.deg2rad(lat) (ra_, dec) = sun_ra_dec(utc_time) h__ = _local_hour_angle(utc_time, lon, ra_) return (np.arcsin(((np.sin(lat) * np.sin(dec)) + ((np.cos(lat) * np.cos(dec)) * np.cos(h__)))), np.arctan2((- np.sin(h__)), ((np.cos(lat) * np...
class Fates(enum.Enum): FALSE_POSITIVE = 0 INITIALIZE = 1 TERMINATE = 2 LINK = 3 DIVIDE = 4 APOPTOSIS = 5 MERGE = 6 EXTRUDE = 7 INITIALIZE_BORDER = 10 INITIALIZE_FRONT = 11 INITIALIZE_LAZY = 12 TERMINATE_BORDER = 20 TERMINATE_BACK = 21 TERMINATE_LAZY = 22 DEAD...
def get_nonlinearity_layer(activation_type='PReLU'): if (activation_type == 'ReLU'): nonlinearity_layer = nn.ReLU() elif (activation_type == 'SELU'): nonlinearity_layer = nn.SELU() elif (activation_type == 'LeakyReLU'): nonlinearity_layer = nn.LeakyReLU(0.1) elif (activation_type...
def plot_fig(args, test_img, recon_imgs, scores, gts, threshold, save_dir): num = len(scores) vmax = (scores.max() * 255.0) vmin = (scores.min() * 255.0) for i in range(num): img = test_img[i] img = denormalization(img) recon_img = recon_imgs[i] recon_img = denormalizatio...
def set_random_seed(seed, deterministic=False, use_rank_shift=False): if use_rank_shift: (rank, _) = mmcv.runner.get_dist_info() seed += rank random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) os.enviro...
def get_num_bond_types(mol): bonds = mol.GetBonds() num_bonds = 0 num_double = 0 num_triple = 0 num_single = 0 num_aromatic = 0 for b in bonds: num_bonds += 1 if (b.GetBondType() == rdkit.Chem.rdchem.BondType.SINGLE): num_single += 1 if (b.GetBondType() ==...
def test_update_catalog_error(db): catalog = Catalog.objects.first() catalog.locked = True catalog.save() section = Section.objects.exclude(catalogs=catalog).first() with pytest.raises(ValidationError): SectionLockedValidator(section)({'catalogs': [catalog], 'locked': False})
class IpAddressMiddleware(): PROVIDER_NAME = 'REMOTE_ADDR header' def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.ip_address = self.get_ip_address(request) response = self.get_response(request) if (settings.DEBUG or requ...
def test_mix_resize(): allocator = RegionAllocator(1) regions = [] for i in range(10): regions.append(allocator.force_alloc(3)) for region in regions[:5]: allocator.force_realloc(region, 8) for i in range(10): regions.append(allocator.force_alloc((i + 1))) for region in r...
class TestCallableGuards(TestNameCheckVisitorBase): _passes() def test_callable(self): from pyanalyze.signature import ANY_SIGNATURE def capybara(o: object) -> None: assert_is_value(o, TypedValue(object)) if callable(o): assert_is_value(o, CallableValue(AN...
class ImageFilelist(data.Dataset): def __init__(self, root, flist, transform=None, target_transform=None, flist_reader=default_flist_reader, loader=default_loader): self.root = root self.imlist = flist_reader(flist) self.transform = transform self.target_transform = target_transform ...
def test_quantizable_mha_with_mask(): B = 5 T = 8 S = 4 q_inputs = keras.Input(shape=(T, 16)) v_inputs = keras.Input(shape=(S, 16)) k_inputs = keras.Input(shape=(S, 16)) m_inputs = keras.Input(shape=(T, S)) model_output = keras.layers.MultiHeadAttention(key_dim=2, num_heads=2)(q_inputs, ...
class TestValidationCountingAggregator(unittest.TestCase): def test_aggregate_scenes(self) -> None: agg = validators.ValidationCountingAggregator() mock_validator_output = mock.Mock() is_valid_scene = mock.PropertyMock(return_value=False) type(mock_validator_output).is_valid_scene = ...
class DisabledQuerySet(models.QuerySet): def __init__(self, *args, **kwargs): self.missing_scopes = kwargs.pop('missing_scopes', None) super().__init__(*args, **kwargs) def error(self, *args, **kwargs): raise ScopeError('A scope on dimension(s) {} needs to be active for this query.'.form...
class TestMonteCarloGFormula(): def test_error_continuous_treatment(self, sim_t_fixed_data): with pytest.raises(ValueError): MonteCarloGFormula(sim_t_fixed_data, idvar='id', exposure='W1', outcome='Y', time_out='t', time_in='t0') def test_error_continuous_outcome(self, sim_t_fixed_data): ...
(scope='session') def special_char_name(): base = 'e-$ e-j' encoding = ('ascii' if IS_WIN else sys.getfilesystemencoding()) result = '' for char in base: try: trip = char.encode(encoding, errors='strict').decode(encoding) if (char == trip): result += char ...
def rolling_volatility(qf_series: QFSeries, frequency: Frequency=None, annualise: bool=True, window_size: int=None) -> QFSeries: returns_tms = qf_series.to_log_returns() if annualise: assert (frequency is not None) volatility_values = [] for i in range((window_size - 1), len(returns_tms)): ...
class CausalLMOutputWithCrossAttentions(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = ...
def init_network_weights(model, init_type='normal', gain=0.02): def _init_func(m): classname = m.__class__.__name__ if (hasattr(m, 'weight') and ((classname.find('Conv') != (- 1)) or (classname.find('Linear') != (- 1)))): if (init_type == 'normal'): nn.init.normal_(m.weig...
class OP_RunSynthesis(bpy.types.Operator): bl_idname = 'genmm.run_synthesis' bl_label = 'Run synthesis' bl_description = '' bl_options = {'REGISTER', 'UNDO'} def __init__(self) -> None: super().__init__() def execute(self, context: bpy.types.Context): setting = context.scene.sett...
def patch_plots(function): from functools import wraps (function) def decorated(*args, **kwargs): with patch('matplotlib.pyplot.show', (lambda *x, **y: None)): import matplotlib matplotlib.use('Agg') return function(*args, **kwargs) return decorated
class DistributedTrainingParams(FairseqDataclass): distributed_world_size: int = field(default=max(1, torch.cuda.device_count()), metadata={'help': 'total number of GPUs across all nodes (default: all visible GPUs)'}) distributed_rank: Optional[int] = field(default=0, metadata={'help': 'rank of the current work...
def test_substrate_presence_profile(): wavelength = (np.linspace(300, 800, 3) * 1e-09) GaAs = material('GaAs')(T=300) my_structure = SolarCell([Layer(si(700, 'nm'), material=GaAs)], substrate=GaAs) solar_cell_solver(my_structure, 'optics', user_options={'wavelength': wavelength, 'optics_method': 'TMM', ...
def test_xdg_vars_set_single(freebsd, xdg_env_single): pp = platform.get_platform_paths('pypyr', 'config.yaml') assert (pp == platform.PlatformPaths(config_user=Path('/ch//pypyr/config.yaml'), config_common=[Path('/cc/pypyr/config.yaml')], data_dir_user=Path('/dh/pypyr'), data_dir_common=[Path('/dc/pypyr')]))
def write_results(filename: str, insts): f = open(filename, 'w', encoding='utf-8') for inst in insts: for i in range(len(inst.input)): words = inst.input.words tags = inst.input.pos_tags heads = inst.input.heads dep_labels = inst.input.dep_labels ...
class TestWeightFi(): def setup_class(self): torch.manual_seed(0) batch_size = 1 workers = 1 channels = 3 img_size = 32 use_gpu = False (self.model, self.dataset) = CIFAR10_set_up_custom(batch_size, workers) dataiter = iter(self.dataset) (self....
class TPUDistributedDataParallel(nn.Module): def __init__(self, module, process_group): super().__init__() self.module = module self.process_group = process_group self.world_size = distributed_utils.get_world_size(self.process_group) def forward(self, *inputs, **kwargs): ...
class Effect5132(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Medium Projectile Turret')), 'falloff', ship.getModifiedItemAttr('shipBonusMC2'), skill='Minmatar Cruiser', **kwargs)
class TestURIReferenceComparesToURIReferences(): def test_same_basic_uri(self, basic_uri): uri = URIReference.from_string(basic_uri) assert (uri == uri) def test_different_basic_uris(self, basic_uri, basic_uri_with_port): uri = URIReference.from_string(basic_uri) assert ((uri == ...
class BirthdayParty(QObject): def __init__(self, parent=None): super(BirthdayParty, self).__init__(parent) self._host = None self._guests = [] (Person) def host(self): return self._host def host(self, host): self._host = host (QQmlListProperty) def guests(...
def test_direct_junction_offsets_pre_suc_3_left(direct_junction_left_lane_fixture): (main_road, small_road, junction_creator) = direct_junction_left_lane_fixture main_road.add_predecessor(xodr.ElementType.junction, junction_creator.id) small_road.add_successor(xodr.ElementType.junction, junction_creator.id)...
class ProjectUpdateViewsView(ObjectPermissionMixin, RedirectViewMixin, UpdateView): model = Project queryset = Project.objects.all() form_class = ProjectUpdateViewsForm permission_required = 'projects.change_project_object' def get_form_kwargs(self): views = View.objects.filter_current_site(...
def init_client(client: QdrantBase, records: List[models.Record], collection_name: str=COLLECTION_NAME, vectors_config: Optional[Union[(Dict[(str, models.VectorParams)], models.VectorParams)]]=None, sparse_vectors_config: Optional[Dict[(str, models.SparseVectorParams)]]=None) -> None: initialize_fixture_collection(...
class StoreKeyValuePairAction(argparse.Action): def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None): if (type not in (None, str)): raise ValueError('type for StoreKeyValuePairAction must be str') ...
class Zoom(object): def __init__(self, value, interp='bilinear', lazy=False): if (not isinstance(value, (tuple, list))): value = (value, value) self.value = value self.interp = interp self.lazy = lazy def __call__(self, *inputs): if (not isinstance(self.interp...
def init_QKV_forward_buffer(): args = get_args() batch_pp = (args.batch_size // args.summa_dim) seq_length = args.seq_length hidden_pp = (args.hidden_size // args.summa_dim) global _QKV_FORWARD_BUFFER assert (_QKV_FORWARD_BUFFER is None), '_QKV_FORWARD_BUFFER is already initialized' space = ...
def _search_noise_pauses(levels, tsc): pauses = list() possible_start = None for i in range(2, (len(levels) - 2)): if (((levels[i] - levels[(i - 1)]) >= tsc) and ((levels[(i - 1)] - levels[(i - 2)]) < tsc)): possible_start = i if (((levels[i] - levels[(i + 1)]) >= tsc) and ((leve...
class SetComprehension(Expression): __slots__ = ('generator',) __match_args__ = ('generator',) generator: GeneratorExpr def __init__(self, generator: GeneratorExpr) -> None: super().__init__() self.generator = generator def accept(self, visitor: ExpressionVisitor[T]) -> T: re...
_module() class GCHead(FCNHead): def __init__(self, ratio=(1 / 4.0), pooling_type='att', fusion_types=('channel_add',), **kwargs): super(GCHead, self).__init__(num_convs=2, **kwargs) self.ratio = ratio self.pooling_type = pooling_type self.fusion_types = fusion_types self.gc_...
class Effect4809(BaseEffect): type = 'passive' def handler(fit, module, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'ECM')), 'scanGravimetricStrengthBonus', module.getModifiedItemAttr('ecmStrengthBonusPercent'), stackingPenalties=True, **kwargs...
class FeatureGraphNet(nn.Module): def __init__(self, model, out_indices, out_map=None): super().__init__() assert has_fx_feature_extraction, 'Please update to PyTorch 1.10+, torchvision 0.11+ for FX feature extraction' self.feature_info = _get_feature_info(model, out_indices) if (out...
def nice_value(x): if (x == 0.0): return 0.0 exp = 1.0 sign = 1 if (x < 0.0): x = (- x) sign = (- 1) while (x >= 1.0): x /= 10.0 exp *= 10.0 while (x < 0.1): x *= 10.0 exp /= 10.0 if (x >= 0.75): return ((sign * 1.0) * exp) ...
def make_tcl_script_vis_annot(subject_id, hemi, out_vis_dir, annot_file='aparc.annot'): script_file = (out_vis_dir / f'vis_annot_{hemi}.tcl') vis = dict() for view in cfg.tksurfer_surface_vis_angles: vis[view] = (out_vis_dir / f'{subject_id}_{hemi}_{view}.tif') img_format = 'tiff' cmds = lis...
def residual_bottleneck(feature_dim=256, num_blocks=1, l2norm=True, final_conv=False, norm_scale=1.0, out_dim=None, interp_cat=False, final_relu=False, final_pool=False): if (out_dim is None): out_dim = feature_dim feat_layers = [] if interp_cat: feat_layers.append(InterpCat()) for i in ...
class RegexLexerMeta(LexerMeta): def _process_regex(cls, regex, rflags, state): if isinstance(regex, Future): regex = regex.get() return re.compile(regex, rflags).match def _process_token(cls, token): assert ((type(token) is _TokenType) or callable(token)), ('token type must ...
def get_protocol_member(left: Instance, member: str, class_obj: bool) -> (ProperType | None): if ((member == '__call__') and class_obj): from mypy.checkmember import type_object_type def named_type(fullname: str) -> Instance: return Instance(left.type.mro[(- 1)], []) return type_...
def load_lvis_v1_json(json_file, image_root, dataset_name=None): from lvis import LVIS json_file = PathManager.get_local_path(json_file) timer = Timer() lvis_api = LVIS(json_file) if (timer.seconds() > 1): logger.info('Loading {} takes {:.2f} seconds.'.format(json_file, timer.seconds())) ...
class TwoStepParameters6(TwoStepParametersCommon): zka_id = DataElementField(type='an', max_length=32, _d='ZKA TAN-Verfahren') zka_version = DataElementField(type='an', max_length=10, _d='Version ZKA TAN-Verfahren') name = DataElementField(type='an', max_length=30, _d='Name des Zwei-Schritt-Verfahrens') ...
def create_pytensor_params(dist_params, obs, size): dist_params_at = [] for p in dist_params: p_aet = pt.as_tensor(p).type() p_aet.tag.test_value = p dist_params_at.append(p_aet) size_at = [] for s in size: s_aet = pt.iscalar() s_aet.tag.test_value = s siz...
class SplAtConv2d(Module): def __init__(self, in_channels, channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=True, radix=2, reduction_factor=4, rectify=False, rectify_avg=False, norm_layer=None, dropblock_prob=0.0, **kwargs): super(SplAtConv2d, self).__init__() pa...
class TestTupleEqual(TestCase): def test_simple(self): assert (100 == klm) assert (456 == (aaa and bbb)) assert (789 == (ccc or ddd)) assert (123 == (True if You else False)) def test_simple_msg(self): assert (klm == 100), 'This is wrong!' def test_simple_msg2(self): ...
def inception_v1(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.8, prediction_fn=slim.softmax, spatial_squeeze=True, reuse=None, scope='InceptionV1'): with tf.variable_scope(scope, 'InceptionV1', [inputs, num_classes], reuse=reuse) as scope: with slim.arg_scope([slim.batch_norm, slim.dropou...
class BackgroundDataset(Dataset): def __getitem__(self, index): texture_img_path = self.data[index] texture_img = cv2.imread(texture_img_path) texture_img = cv2.cvtColor(texture_img, cv2.COLOR_BGR2RGB) texture_img = self.resize(texture_img) if self.random: texture...
class Migration(migrations.Migration): dependencies = [('typeclasses', '0010_delete_old_player_tables')] operations = [migrations.DeleteModel(name='DefaultAccount'), migrations.DeleteModel(name='DefaultCharacter'), migrations.DeleteModel(name='DefaultExit'), migrations.DeleteModel(name='DefaultGuest'), migratio...
def generate_and_save(env_name, traj_len, cache_size=100000, qpos_only=False, qpos_qvel=False, delta=True, whiten=True, pixels=False, source_img_width=64): dataset = GymData(env_name, traj_len, cache_size, qpos_only, qpos_qvel, delta, whiten, pixels, source_img_width) print('Generating dataset to save.') fo...
class LinePrecisionReporter(AbstractReporter): def __init__(self, reports: Reports, output_dir: str) -> None: super().__init__(reports, output_dir) self.files: list[FileInfo] = [] def on_file(self, tree: MypyFile, modules: dict[(str, MypyFile)], type_map: dict[(Expression, Type)], options: Optio...
class PersianSecondDirective(PersianNumberDirective): def format(self, d): return super(PersianSecondDirective, self).format(d.second) def post_parser(self, ctx, formatter): super(PersianSecondDirective, self).post_parser(ctx, formatter) if ((self.name in ctx) and ctx[self.name]): ...
def parse_unit_patterns(data, tree): unit_patterns = data.setdefault('unit_patterns', {}) compound_patterns = data.setdefault('compound_unit_patterns', {}) unit_display_names = data.setdefault('unit_display_names', {}) for elem in tree.findall('.//units/unitLength'): unit_length_type = elem.attr...
def main(options, arguments): devices = ['/gpu:0', '/gpu:1'] if (options.device == None): device = devices[0] else: device = devices[int(options.device)] if (options.distance == None): distance = 8 else: distance = int(options.distance) global DISTANCE_THRESHOLD ...
class BaseResampler(): def __init__(self, source_geo_def: Union[(SwathDefinition, AreaDefinition)], target_geo_def: Union[(CoordinateDefinition, AreaDefinition)]): self.source_geo_def = source_geo_def self.target_geo_def = target_geo_def def get_hash(self, source_geo_def=None, target_geo_def=Non...
class RedisOrchestrator(Orchestrator): def __init__(self, host='127.0.0.1', port=6379, password=None, db=0, cert_and_key=None, ca_cert=None, ssl=False, skip_keyspace_event_setup=False, canceller_only=False, **kwargs): self.is_canceller_only = canceller_only (cert, key) = (tuple(cert_and_key) if (cer...
class PerfTimer(): def __init__(self, timer_name: str, perf_stats: Optional['PerfStats']): self.skip: bool = False if (perf_stats is None): self.skip = True return self.name: str = timer_name self.elapsed: float = 0.0 self._last_interval: float = 0.0 ...
class RTLIRGetter(): ifc_primitive_types = (dsl.InPort, dsl.OutPort, dsl.Interface) def __init__(self, cache=True): if cache: self._rtlir_cache = {} self.get_rtlir = self._get_rtlir_cached else: self.get_rtlir = self._get_rtlir_uncached self._RTLIR_ifc...
class ExecAccuracyEvaluationResult(evaluate.EvaluationResult): def __init__(self, prompts, scores): self.prompts = prompts self.scores = scores def _agg_scores(self, method): if (method == 'mean'): return [np.mean(s) for s in self.scores] elif (method == 'median'): ...
class GaussianDiffusion(): def __init__(self, *, betas, model_mean_type, model_var_type, loss_type, rescale_timesteps=False): self.model_mean_type = model_mean_type self.model_var_type = model_var_type self.loss_type = loss_type self.rescale_timesteps = rescale_timesteps beta...
class RepeatListForever(Repeat): name = 'repeat_all' display_name = _('Repeat all') accelerated_name = _('Repeat _all') def next(self, playlist, iter): next = self.wrapped.next(playlist, iter) if next: return next self.wrapped.reset(playlist) print_d('Restarti...
class SyncPerformerTests(TestCase): def test_success(self): _performer def succeed(dispatcher, intent): return intent dispatcher = (lambda _: succeed) result = sync_perform(dispatcher, Effect('foo')) self.assertEqual(result, 'foo') def test_failure(self): ...
_REGISTRY.register() def build_mit_backbone(cfg, input_shape): if (cfg.MODEL.MIT_BACKBONE.NAME == 'b0'): return mit_b0() elif (cfg.MODEL.MIT_BACKBONE.NAME == 'b1'): return mit_b1() elif (cfg.MODEL.MIT_BACKBONE.NAME == 'b2'): return mit_b2() elif (cfg.MODEL.MIT_BACKBONE.NAME == 'b...
def test_no_linecache(): class A(): a: int c = Converter() before = len(linecache.cache) c.structure(c.unstructure(A(1)), A) after = len(linecache.cache) assert (after == (before + 2)) class B(): a: int before = len(linecache.cache) c.register_structure_hook(B, make_d...
def test_delete_cur_item_no_func(): callback = mock.Mock(spec=[]) model = completionmodel.CompletionModel() cat = listcategory.ListCategory('', [('foo', 'bar')], delete_func=None) model.rowsAboutToBeRemoved.connect(callback) model.rowsRemoved.connect(callback) model.add_category(cat) parent ...
class dense121(torch.nn.Module): def __init__(self, requires_grad=False): super(dense121, self).__init__() dense_pretrained_features = light_estimation.module.dense self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() ...
.skipif(utils.is_windows, reason="current CPython/win can't recover from SIGSEGV") def test_debug_crash_segfault(): caught = False def _handler(num, frame): nonlocal caught caught = (num == signal.SIGSEGV) with _trapped_segv(_handler): with pytest.raises(Exception, match='Segfault fa...
def get_arch(filename: Union[(str, Path)]) -> List[ArchitectureType]: this_platform = sys.platform if this_platform.startswith('win'): machine_type = get_shared_library_arch(filename) if (machine_type == PEMachineType.I386): return [ArchitectureType.I386] elif (machine_type =...
def plot(*args, **kargs): mkQApp() pwArgList = ['title', 'labels', 'name', 'left', 'right', 'top', 'bottom', 'background'] pwArgs = {} dataArgs = {} for k in kargs: if (k in pwArgList): pwArgs[k] = kargs[k] else: dataArgs[k] = kargs[k] windowTitle = pwArgs...
def main(data_dir, client, bc, config): benchmark(read_tables, data_dir, bc, dask_profile=config['dask_profile']) query_date = f''' select min(d_date_sk) as min_d_date_sk, max(d_date_sk) as max_d_date_sk from date_dim where d_year = {q17_year} and d_moy = {q17_month} ...
def InceptionV3Body(net, from_layer, output_pred=False): use_scale = False out_layer = 'conv' ConvBNLayer(net, from_layer, out_layer, use_bn=True, use_relu=True, num_output=32, kernel_size=3, pad=0, stride=2, use_scale=use_scale) from_layer = out_layer out_layer = 'conv_1' ConvBNLayer(net, from_...
def EnsureNonBlockingDataPipe(validated_datapipe): if (not isinstance(validated_datapipe, IterDataPipe)): raise Exception(('Not Iterable DataPipe ' + str(validated_datapipe.__class__))) if isinstance(validated_datapipe, NonBlocking): return validated_datapipe if (not hasattr(validated_datapi...
_kernel_api(params={'handle': UINT}) def hook__sflt_unregister(ql, address, params): handle = str(params['handle']).encode() evs = ql.os.ev_manager.get_events_by_name(b'', keyword=handle) for found in evs: ql.os.ev_manager.emit(found.name, MacOSEventType.EV_SFLT_UNREGISTERED, [params['handle']]) ...
def test_run_all(mock_pipe): out = run(pipeline_name='arb pipe', args_in='arb context input', parse_args=True, dict_in={'a': 'b'}, groups=['g'], success_group='sg', failure_group='fg', loader='arb loader', py_dir='arb/dir') assert (type(out) is Context) assert (out == Context({'a': 'b'})) assert (not ou...
def configure_stabilization_augs(img, init_image_pil, params, loss_augs): stabilization_augs = ['direct_stabilization_weight', 'depth_stabilization_weight', 'edge_stabilization_weight'] stabilization_augs = [build_loss(x, params[x], 'stabilization', img, init_image_pil) for x in stabilization_augs if (params[x]...
class StopOrder(ExecutionStyle): def __init__(self, stop_price, asset=None, exchange=None): check_stoplimit_prices(stop_price, 'stop') self.stop_price = stop_price self._exchange = exchange self.asset = asset def get_limit_price(self, _is_buy): return None def get_sto...
def tw_mock(): class TWMock(): WRITE = object() def __init__(self): self.lines = [] self.is_writing = False def sep(self, sep, line=None): self.lines.append((sep, line)) def write(self, msg, **kw): self.lines.append((TWMock.WRITE, msg))...
(scope='module') def inline_query_result_contact(): return InlineQueryResultContact(TestInlineQueryResultContactBase.id_, TestInlineQueryResultContactBase.phone_number, TestInlineQueryResultContactBase.first_name, last_name=TestInlineQueryResultContactBase.last_name, thumbnail_url=TestInlineQueryResultContactBase.t...
_arg_scope def batch_norm(inputs, decay=0.999, center=True, scale=False, epsilon=0.001, activation_fn=None, param_initializers=None, param_regularizers=None, updates_collections=ops.GraphKeys.UPDATE_OPS, is_training=True, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, batch_weights=No...
def get_example_spectral_response(wavelength=None): SR_DATA = np.array([[290, 0.0], [350, 0.27], [400, 0.37], [500, 0.52], [650, 0.71], [800, 0.88], [900, 0.97], [950, 1.0], [1000, 0.93], [1050, 0.58], [1100, 0.21], [1150, 0.05], [1190, 0.0]]).transpose() if (wavelength is None): resolution = 5.0 ...
class ResNet3dPathway(ResNet3d): def __init__(self, *args, lateral=False, speed_ratio=8, channel_ratio=8, fusion_kernel=5, **kwargs): self.lateral = lateral self.speed_ratio = speed_ratio self.channel_ratio = channel_ratio self.fusion_kernel = fusion_kernel super().__init__(*...
class SCMIFileHandler(BaseFileHandler): def __init__(self, filename, filename_info, filetype_info): super(SCMIFileHandler, self).__init__(filename, filename_info, filetype_info) self.nc = xr.open_dataset(self.filename, decode_cf=True, mask_and_scale=False, chunks={'x': LOAD_CHUNK_SIZE, 'y': LOAD_CHU...
class MathSATOptions(SolverOptions): def __init__(self, **base_options): SolverOptions.__init__(self, **base_options) def _set_option(msat_config, name, value): check = mathsat.msat_set_option(msat_config, name, value) if (check != 0): raise PysmtValueError(("Error setting th...
_module() class CosineAnnealingLrUpdaterHook(LrUpdaterHook): def __init__(self, min_lr=None, min_lr_ratio=None, **kwargs): assert ((min_lr is None) ^ (min_lr_ratio is None)) self.min_lr = min_lr self.min_lr_ratio = min_lr_ratio super(CosineAnnealingLrUpdaterHook, self).__init__(**kwa...
def test_change_rv_size_default_update(): rng = pytensor.shared(np.random.default_rng(0)) x = normal(rng=rng) rng.default_update = x.owner.outputs[0] new_x = change_dist_size(x, new_size=(2,)) new_rng = new_x.owner.inputs[0] assert (rng.default_update is x.owner.outputs[0]) assert (new_rng.d...