code
stringlengths
281
23.7M
.testinfra_hosts('ansible://debian_bookworm', 'ansible://_bookworm') def test_ansible_module_become(host): user_name = host.user().name assert (host.ansible('shell', 'echo $USER', check=False)['stdout'] == user_name) assert (host.ansible('shell', 'echo $USER', check=False, become=True)['stdout'] == 'root') ...
class IgnoreControl(ScalarControl): def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) self._value = None def is_of_kind(self, kind): return False def __setattr__(self, name, value): if (name == 'value'): rais...
class TestSyntheticLocate(): def setup_method(self) -> None: self.dirpath = os.path.join(os.path.dirname(__file__), './data/') lattice = spaghetti.regular_lattice((0, 0, 10, 10), 9, exterior=True) ntw = spaghetti.Network(in_data=lattice) gdf = spaghetti.element_as_gdf(ntw, arcs=True)...
def download_pretrained_models(method, file_ids): save_path_root = f'./experiments/pretrained_models/{method}' os.makedirs(save_path_root, exist_ok=True) for (file_name, file_id) in file_ids.items(): save_path = osp.abspath(osp.join(save_path_root, file_name)) if osp.exists(save_path): ...
class global_sttr(nn.Module): def __init__(self, config): super(global_sttr, self).__init__() self.embed_channel = config.embed_channel self.tokenizer = tokenizer(config) encoder_layer_actor = TransformerEncoderLayer(self.embed_channel, config.Nhead, dropout=config.dropout_porb, norm...
class CommandDispatcher(): _commands: list[Command] = field(default_factory=list) _commands_by_trigger: dict[(str, Command)] = field(default_factory=dict) def _register(self, command: Command) -> None: self._commands.append(command) self._commands_by_trigger.update({trigger: command for trig...
def pack_rows(rows, bitdepth): assert (bitdepth < 8) assert ((8 % bitdepth) == 0) spb = int((8 / bitdepth)) def make_byte(block): res = 0 for v in block: res = ((res << bitdepth) + v) return res for row in rows: a = bytearray(row) n = float(len(a))...
def build_voc_dirs(outdir): mkdir = (lambda dir: (os.makedirs(dir) if (not os.path.exists(dir)) else None)) mkdir(outdir) mkdir(os.path.join(outdir, 'Annotations')) mkdir(os.path.join(outdir, 'ImageSets')) mkdir(os.path.join(outdir, 'ImageSets', 'Layout')) mkdir(os.path.join(outdir, 'ImageSets',...
def separate_attributes_and_event_handlers(attributes: Mapping[(str, Any)]) -> tuple[(dict[(str, Any)], EventHandlerDict)]: separated_attributes = {} separated_event_handlers: dict[(str, EventHandlerType)] = {} for (k, v) in attributes.items(): handler: EventHandlerType if callable(v): ...
def merge_annotations(annotations, comment_annotations): for (ann, comment_ann) in itertools.zip_longest(annotations, comment_annotations): if (ann and (not _is_ellipsis(ann))): (yield ann) elif (comment_ann and (not _is_ellipsis(comment_ann))): (yield comment_ann) el...
def test_partial(): C = Bobby with inspect_node(C) as ci: assert (ci.type == Bobby) assert (not ci.instance) assert (len(ci.options) == 4) assert (len(ci.processors) == 1) assert (not ci.partial) f1 = MagicMock() C = C(f1) with inspect_node(C) as ci: a...
class SemisuperDecayEnv(SemisuperEnv): DECAY_RATE = 0.999 def __init__(self): super(SemisuperDecayEnv, self).__init__() self.prob_get_reward = 1.0 def _distort_reward(self, true_reward): self.prob_get_reward *= SemisuperDecayEnv.DECAY_RATE if (self.np_random.uniform() < self....
def get_supported_kernel_in_dict_format(act_constraint: Dict, weight_constraint: Dict) -> Dict: supported_kernel_in_dict_format = {'activation': {'bitwidth': act_constraint['bitwidth'], 'dtype': act_constraint['dtype']}, 'param': {'bitwidth': weight_constraint['bitwidth'], 'dtype': weight_constraint['dtype']}} ...
class CalendarParameter(Parameter): itemClass = CalendarParameterItem def __init__(self, **opts): opts.setdefault('format', 'TextDate') super().__init__(**opts) def _interpretFormat(self, fmt=None): fmt = (fmt or self.opts.get('format')) if hasattr(QtCore.Qt.DateFormat, fmt):...
class deprecated(): def __init__(self, new_name=None, removed_after='next major patch'): self.new_name = new_name self.removed_after = removed_after def __call__(self, func): def newFunc(*args, **kwargs): warning = ('%s is deprecated and will be removed in %s. ' % (func.__nam...
def render_pcl_front_view(vis, cam_params=None, fn=None, img_save_fn=None, pt_size=3): mesh = o3d.io.read_point_cloud(fn) vis.add_geometry(mesh) opt = vis.get_render_option() opt.point_size = pt_size ctr = vis.get_view_control() ctr.convert_from_pinhole_camera_parameters(cam_params) vis.poll...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_channels, channels, stride=1, groups=1, width_per_group=64, sd=0.0, **block_kwargs): super(BasicBlock, self).__init__() if ((groups != 1) or (width_per_group != 64)): raise ValueError('BasicBlock only supports groups=1 ...
def check_file(filename: str) -> List[LintMessage]: try: top_of_file_cat = usort_config.Category('top_of_file') known = usort_config.known_factory() known['__strict__'] = top_of_file_cat known['__static__'] = top_of_file_cat config = usort_config.Config(categories=(usort_conf...
def test_logins_fails_with_wrong_password(graphql_client): user = UserFactory(email='', password='test') response = graphql_client.query('mutation($input: LoginInput!) {\n login(input: $input) {\n __typename\n }\n }', variables={'input': {'email': user.email, 'passwor...
def get_icns(svg_path): ICONS = [(b'is32', 16, 'icon'), (b's8mk', 16, 'mask'), (b'il32', 32, 'icon'), (b'l8mk', 32, 'mask'), (b'ic08', 256, 'png'), (b'ic09', 512, 'png'), (b'icp6', 64, 'png'), (b'ic07', 128, 'png'), (b'ic11', 32, 'png'), (b'ic12', 64, 'png'), (b'ic13', 256, 'png'), (b'ic14', 512, 'png')] funcs ...
class TestNcNWCSAFFileKeyPrefix(): def test_get_dataset_uses_file_key_prefix(self, nwcsaf_pps_cmic_filehandler): dsid_cpp = {'name': 'cpp_cot'} dsid_cmic = {'name': 'cmic_cot'} file_key = 'cot' info_cpp = dict(name='cpp_cot', file_key=file_key, file_type='nc_nwcsaf_cpp') res_...
def functionParams(args, vars): params = {} index = 1 for var in vars: value = args.get(var) if (value is None): value = args.get(str(index)) if (value is None): value = '' else: index += 1 params[var] = value re...
def collapse_lora(model, alpha=1.0): for (_module, name, _child_module) in _find_modules(model, (UNET_EXTENDED_TARGET_REPLACE | TEXT_ENCODER_EXTENDED_TARGET_REPLACE), search_class=[LoraInjectedLinear, LoraInjectedConv2d]): if isinstance(_child_module, LoraInjectedLinear): print('Collapsing Lin L...
def get_datasets(): configurations_all = {'Task01_BrainTumour': ('3d_fullres', '2d'), 'Task02_Heart': ('3d_fullres', '2d'), 'Task03_Liver': ('3d_cascade_fullres', '3d_fullres', '3d_lowres', '2d'), 'Task04_Hippocampus': ('3d_fullres', '2d'), 'Task05_Prostate': ('3d_fullres', '2d'), 'Task06_Lung': ('3d_cascade_fullre...
class Cauchy(Continuous): rv_op = cauchy def dist(cls, alpha, beta, *args, **kwargs): alpha = pt.as_tensor_variable(floatX(alpha)) beta = pt.as_tensor_variable(floatX(beta)) return super().dist([alpha, beta], **kwargs) def moment(rv, size, alpha, beta): (alpha, _) = pt.broadc...
.parametrize('function_', ['DCV', 'ACV', 'DCI', 'R2W']) def test_resolution(resetted_hp34401a, function_): resetted_hp34401a.function_ = function_ resetted_hp34401a.range_ = 1 resetted_hp34401a.resolution = 0.0001 assert (len(resetted_hp34401a.check_errors()) == 0) assert (resetted_hp34401a.resoluti...
class ClientInput(): content: bytes log_time: str recv_time: str elapsed: str hash: str path: str seed_status: SeedType fuzzer_id: bytes fuzzer_name: str broker_status: str replay_status: str replay_time: float new_coverage: list[tuple[(int, int)]]
def create_unique_list(apps: Apps, _): filter_list: pydis_site.apps.api.models.FilterList = apps.get_model('api', 'FilterList') filter_: pydis_site.apps.api.models.Filter = apps.get_model('api', 'Filter') list_ = filter_list.objects.create(name='unique', list_type=0, guild_pings=[], filter_dm=True, dm_pings...
def dir(root, type='f', addroot=True): dirList = [] fileList = [] root = (root + '/') files = os.listdir(root) for f in files: if os.path.isdir((root + f)): if (addroot == True): dirList.append((root + f)) else: dirList.append(f) ...
def _get_lines_for_constructing_an_object(func: Callable): (def_line, *pre, ret_line) = inspect.getsource(func).splitlines() assert def_line.startswith('def '), def_line trimmed_lines = [] for line in pre: assert ((line == '') or line.startswith((' ' * 4))), line trimmed_lines.append(lin...
.parametrize('helper', model_helpers) def test_management_navigation(logged_in_admin_user: Page, helper: ModelHelper) -> None: page = logged_in_admin_user expect(page.get_by_role('heading', name='Management')).to_be_visible() name = helper.verbose_name_plural page.get_by_role('link', name=name, exact=Tr...
class InstructionMRCForFewCLUEProcessor(CLSProcessor): def __init__(self, data_args, training_args, model_args, tokenizer=None, post_tokenizer=False, keep_raw_data=True): super().__init__(data_args, training_args, model_args, tokenizer, post_tokenizer=post_tokenizer, keep_raw_data=keep_raw_data) par...
def random_sources_in_disk(size, power, wavelength_mean, bandwidth, r): source_list = ([None] * size) (x0, y0) = random_in_unit_disk(size) (x0, y0) = ((r * x0), (r * y0)) phase = ((np.random.rand(size) * 2) * np.pi) wavelength = (wavelength_mean + (bandwidth * (np.random.rand(size) - 0.5))) for ...
def LoadAbsorption(layer, T, wavelengths, use_Adachi=False): if use_Adachi: try: absorption = adachi_alpha.create_adachi_alpha(InLineComposition(layer), T=T, wl=wavelengths)[3] except: print('Warning: Using experimental data to estimate the absorption coefficient of material:...
def test_set_parent_for_preset(tmp_path): opt = Options(tmp_path) u1 = uuid.UUID('b41fde84-1f57-4b79-8cd6-3e5a78077fa6') u2 = uuid.UUID('b51fdeaa-1fff-4b79-8cd6-3e5a78077fa6') assert (opt.get_parent_for_preset(u1) is None) opt.set_parent_for_preset(u1, u2) assert (opt.get_parent_for_preset(u1) =...
class ModelUtils(): convert: dict = {'gpt-3.5-turbo': Model.gpt_35_turbo, 'gpt-3.5-turbo-0613': Model.gpt_35_turbo_0613, 'gpt-3.5-turbo-0301': Model.gpt_35_turbo_0301, 'gpt-4': Model.gpt_4, 'gpt-4-0613': Model.gpt_4_0613, 'gpt-4-for-dev': Model.gpt_4_dev, 'gpt-3.5-turbo-16k': Model.gpt_35_turbo_16k, 'gpt-3.5-turbo-...
class Effect11999(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Hybrid Turret')), 'trackingSpeed', src.getModifiedItemAttr('eliteBonusGunship2'), skill='Assault Frigates', **kwargs)
class BattleCmdSet(default_cmds.CharacterCmdSet): key = 'DefaultCharacter' def at_cmdset_creation(self): self.add(CmdFight()) self.add(CmdAttack()) self.add(CmdRest()) self.add(CmdPass()) self.add(CmdDisengage()) self.add(CmdCombatHelp()) self.add(CmdLearn...
class TestNoOperation(EndianTest): def setUp(self): self.req_args_0 = {} self.req_bin_0 = b'\x7f\x00\x00\x01' def testPackRequest0(self): bin = request.NoOperation._request.to_binary(*(), **self.req_args_0) self.assertBinaryEqual(bin, self.req_bin_0) def testUnpackRequest0(se...
def add_index(shard_dir, index_path): data_shard_list = [] for shard_address in glob((str(shard_dir) + '/*/')): data_shard_list.append(load_from_disk(shard_address)) concat = concatenate_datasets(data_shard_list) faiss.omp_set_num_threads(96) index = faiss.IndexHNSWFlat(768, 128, faiss.METRI...
def test_gen_poll_url_xml_has_xmltodict(monkeypatch): monkeypatch.setitem(sys.modules, 'xmltodict', Mockxml('xmltodict')) reload(generic_poll_text) gpurl = generic_poll_text.GenPollUrl(json=False, xml=True, parse=(lambda x: x), url='testing') monkeypatch.setattr(generic_poll_text, 'Request', MockRequest...
class _ConfigSettingsTranslator(): def _get_config(self, key: str, config_settings: _ConfigSettings) -> List[str]: cfg = (config_settings or {}) opts = (cfg.get(key) or []) return (shlex.split(opts) if isinstance(opts, str) else opts) def _global_args(self, config_settings: _ConfigSettin...
def collect_rst_dps(rst_file_location): rst_dps = set() with open(rst_file_location) as rst_file: while ((line := rst_file.readline()) != ''): if ((line.count('class_template.rst') > 0) or (line.count('function.rst') > 0)): rst_file.readline() while (((line :=...
def slice_aspect_ratio(pixel_dim, axis): if (pixel_dim.size != 3): raise ValueError('pixel_dim must be an array of 3 elements for 3D images') if (axis == 0): aspect_ratio = (pixel_dim[2] / pixel_dim[1]) elif (axis == 1): aspect_ratio = (pixel_dim[2] / pixel_dim[0]) elif (axis == ...
class Container(): def __init__(self, r: Union[(Variable, Type)], storage: list[Any], *, readonly: bool=False, strict: bool=False, allow_downcast: Optional[bool]=None, name: Optional[str]=None) -> None: if ((not isinstance(storage, list)) or (not (len(storage) >= 1))): raise TypeError('storage m...
def CalcuPSNR_int(img1, img2, max_val=255.0): float_type = 'float64' img1 = np.round((torch.clamp(img1, 0, 1).detach().cpu().numpy() * 255)) img2 = np.round((torch.clamp(img2, 0, 1).detach().cpu().numpy() * 255)) img1 = img1.astype(float_type) img2 = img2.astype(float_type) mse = np.mean(np.squa...
def max_pool2d(data, l=(2, 2)): if ((type(data) is tuple) and (len(data) == 3)): out = (F.max_pool2d(data[0], l), F.max_pool2d(data[1], l), F.max_pool2d(data[2], l)) return out elif ((type(data) is tuple) and (len(data) == 2)): if (data[0] is None): out = (F.max_pool2d(data[1...
def main() -> None: version = get_version() url = f' with urlopen(url) as response: if (response.status >= 400): print(f'Failed to retrieve config.proto: status {response.status}', file=sys.stderr) sys.exit(1) with TemporaryDirectory() as dir_name: file_pa...
def init_actor(actor, pool, dict_ph, env, num_q, value_fn_params, noise_params): M1 = value_fn_params['layer_size1'] M2 = value_fn_params['layer_size2'] with tf.variable_scope(actor.name): policy = DeterministicPolicy(env_spec=env.spec, hidden_layer_sizes=(M1, M2), reg=0.001, observation_ph=dict_ph[...
def test_safe_getattr() -> None: helper = ErrorsHelper() assert (safe_getattr(helper, 'raise_exception', 'default') == 'default') assert (safe_getattr(helper, 'raise_fail_outcome', 'default') == 'default') with pytest.raises(BaseException): assert safe_getattr(helper, 'raise_baseexception', 'def...
class Test_git_describe(unittest.TestCase, Testing_renderer_case_mixin): style = 'git-describe' expected = {'tagged_0_commits_clean': 'v1.2.3', 'tagged_0_commits_dirty': 'v1.2.3-dirty', 'tagged_1_commits_clean': 'v1.2.3-1-gabc', 'tagged_1_commits_dirty': 'v1.2.3-1-gabc-dirty', 'untagged_0_commits_clean': '', 'u...
def usage(msg=None): if msg: print(msg) print(sys.argv[0], '[-p port] [-l logfile] [-dh] [allowed_client_name ...]]') print() print(' -p - Port to bind to') print(' -l - Path to logfile. If not specified, STDOUT is used') print(' -d - Run in the background') p...
def accumulate_results(game_modifications: dict, items: dict[(str, dict[(str, int)])], locations: dict[(str, dict[(str, int)])], major_progression_items_only: bool): for (world_name, world_data) in game_modifications['locations'].items(): for (area_name, item_name) in world_data.items(): area_na...
class CfcCell(tf.keras.layers.Layer): def __init__(self, units, hparams, **kwargs): super(CfcCell, self).__init__(**kwargs) self.units = units self.state_size = units self.hparams = hparams self._no_gate = False def build(self, input_shape): if isinstance(input_sh...
def eval_expression(node: str, rng: np.random.RandomState, scope: dict): true = True false = False def Uniform(low, high): return rng.uniform(low, high) def RandomAngleAxis(angle_low, angle_high, axis): return random_angle_axis(angle_low, angle_high, axis, rng) if (('$' in node) and ...
def when(event_type=None, selector=None): def decorator(func): if isinstance(selector, str): elements = document.querySelectorAll(selector) else: from pyweb import pydom if isinstance(selector, pydom.Element): elements = [selector._js] ...
class NTU_Fi_ResNet(nn.Module): def __init__(self, ResBlock, layer_list, num_classes): super(NTU_Fi_ResNet, self).__init__() self.reshape = nn.Sequential(nn.Conv2d(3, 3, (15, 23), stride=(3, 9)), nn.ReLU(), nn.Conv2d(3, 3, kernel_size=(3, 23), stride=1), nn.ReLU()) self.in_channels = 64 ...
.parametrize('enabled', [True, False]) def test_trigger_auto_delay_enabled(enabled): with expected_protocol(HP34401A, [('TRIG:DEL:AUTO?', ('1' if enabled else '0')), (f'TRIG:DEL:AUTO {(1 if enabled else 0)}', None)]) as inst: assert (enabled == inst.trigger_auto_delay_enabled) inst.trigger_auto_dela...
def fix_missing_data(contour_data_list): contour_data = np.array(contour_data_list) if (contour_data.any() == ''): logger.warning(' Missing values detected.') missing_values = np.where((contour_data == ''))[0] if (missing_values.shape[0] > 1): logger.warning(" More than...
class MSRA10k(BaseImageDataset): def __init__(self, root=None, image_loader=jpeg4py_loader, data_fraction=None, min_area=None): root = (env_settings().msra10k_dir if (root is None) else root) super().__init__('MSRA10k', root, image_loader) self.image_list = self._load_dataset(min_area=min_ar...
class CharbonnierLoss(nn.Module): def __init__(self, loss_weight=1.0, reduction='mean', eps=0.001): super(CharbonnierLoss, self).__init__() self.eps = eps def forward(self, x, y): diff = (x - y) loss = torch.mean(torch.sqrt(((diff * diff) + (self.eps * self.eps)))) return...
class GetTypeHintTests(BaseTestCase): def setUpClass(cls): with tempfile.TemporaryDirectory() as tempdir: sys.path.append(tempdir) Path(tempdir, 'ann_module.py').write_text(ANN_MODULE_SOURCE) Path(tempdir, 'ann_module2.py').write_text(ANN_MODULE_2_SOURCE) Path...
.parametrize('tensor_shape', [FC_SHAPE, CONV_SHAPE], ids=['FC', 'CONV']) def test_he_uniform(tensor_shape): (fan_in, _) = initializers._compute_fans(tensor_shape) scale = np.sqrt((6.0 / fan_in)) _runner(initializers.he_uniform(), tensor_shape, target_mean=0.0, target_max=scale, target_min=(- scale))
def mutable_seq_typed_attrs(draw, defaults=None, allow_mutable_defaults=True, legacy_types_only=False, kw_only=None): default_val = NOTHING val_strat = lists(floats(allow_infinity=False, allow_nan=False)) if ((defaults is True) or ((defaults is None) and draw(booleans()))): default_val = draw(val_st...
def _parse_specifier(package_spec: str) -> ParsedPackage: valid_pep508 = None valid_url = None valid_local_path = None try: package_req = Requirement(package_spec) except InvalidRequirement: pass else: valid_pep508 = package_req if (valid_pep508 and package_req.name.e...
def _create_recorded_proxy_method(proxy: HFProxy, method_name: str, cache_name: str, return_proxy: bool): original_method = getattr(torch.Tensor, method_name) (original_method) def method(*args, **kwargs): cache = getattr(args[0].tracer.root, cache_name) res = cache.pop(0) if return_...
def parse_by_phrase(path_to_txt_or_xml_file, meter='default_english', minword=5): txt = read_file(path_to_txt_or_xml_file) import re phrases = re.split('[?.,;:\n]', txt) if minword: phrases2 = [] phrase = [] for px in phrases: phrase += px.split() if (len(...
def handle_receive_delivered(chain_state: ChainState, state_change: ReceiveDelivered) -> TransitionResult[ChainState]: queueid = QueueIdentifier(state_change.sender, CANONICAL_IDENTIFIER_UNORDERED_QUEUE) inplace_delete_message_queue(chain_state, state_change, queueid) return TransitionResult(chain_state, []...
class SelfShowCommand(SelfCommand, ShowCommand): name = 'self show' options = [option('addons', None, 'List only add-on packages installed.'), *[o for o in ShowCommand.options if (o.name in {'tree', 'latest', 'outdated'})]] description = "Show packages from Poetry's runtime environment." help = f'''The ...
class Job(pydantic.BaseModel): job_type: JobType payload: Optional[Dict] ('payload') def crawler_payload(cls, v, values, **kwargs): if (not v): raise Exception('payload is required') if (values['job_type'] == JobType.CRAWL_PTT_LATEST_POSTS): for key in ['board']: ...
class Inception_C(nn.Module): def __init__(self): super(Inception_C, self).__init__() self.branch0 = BasicConv2d(1536, 256, kernel_size=1, stride=1) self.branch1_0 = BasicConv2d(1536, 384, kernel_size=1, stride=1) self.branch1_1a = BasicConv2d(384, 256, kernel_size=(1, 3), stride=1, ...
def relations(distinctions, relation_computation=None, **kwargs): if (not distinctions.resolved_congruence): warnings.warn(_CONGRUENCE_WARNING_MSG, PyPhiWarning, stacklevel=2) return relation_computations[fallback(relation_computation, config.RELATION_COMPUTATION)](distinctions, **kwargs)
class Thermotron3800(Instrument): def __init__(self, adapter, name='Thermotron 3800', **kwargs): super().__init__(adapter, name, includeSCPI=False, **kwargs) def write(self, command): super().write(command) sleep(1) id = Instrument.measurement('IDEN?', ' Reads the instrument identifi...
class BackgroundTaskMixin(): progress_update_signal = Signal(str, int) background_tasks_button_lock_signal = Signal(bool) abort_background_task_requested: bool = False _background_thread: (threading.Thread | None) = None def _start_thread_for(self, target): randovania.games.prime2.patcher.cs...
def could_use_op(input): if ((not enabled) or (not torch.backends.cudnn.enabled)): return False if (input.device.type != 'cuda'): return False if any((torch.__version__.startswith(x) for x in ['1.7.', '1.8.'])): return True warnings.warn(f'conv2d_gradfix not supported on PyTorch ...
class Textual_Encoder(nn.Module): def __init__(self, cfg, classnames, clip_model): super().__init__() self.cfg = cfg self.classnames = classnames self.clip_model = clip_model self.dtype = clip_model.dtype def forward(self): prompts = best_prompt_weight['{}_{}_test...
class SyncMiddleware(LogMiddleware): def __init__(self): self.request_parent = dict() self.sync_items = dict() self._lock = asyncio.Lock() async def process_spider_output(self, response, result, spider): key = getattr(spider, 'sync_item_key') if (key is None): ...
def apply_to_ndarray(f, sample): if (len(sample) == 0): return {} def _apply(x): if isinstance(x, np.ndarray): return f(x) elif isinstance(x, dict): return {key: _apply(value) for (key, value) in x.items()} elif isinstance(x, list): return [_ap...
class UserDeleteView(DeleteView): model = User template_name = 'django_scantron/user_delete.html' slug_field = 'slug' slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' context_object_name = 'user' def __init__(self, **kwargs): return super(UserDeleteView, self).__init__(**kwargs) def d...
class GetRootUUIDTests(unittest.TestCase): def setUpClass(cls): cls.das = DummyArtifacts() cls.tempdir = cls.das.tempdir def tearDownClass(cls): cls.das.free() def test_get_root_uuid(self): exp_root_uuids = {'0': '89af91c0-033d-4e30-8ac4-f29a3b407dc1', '1': '5b929500-e4d6-4d3...
class Swinv2Config(PretrainedConfig): model_type = 'swinv2' attribute_map = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__(self, image_size=224, patch_size=4, num_channels=3, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4.0, qkv_...
def main(config, args): if (args.module and (args.module != 'main')): if (args.module == 'help'): help() return try: library = importlib.import_module(((__package__ + '.') + args.module)) if args.name: if (args.name == 'all'): ...
class FrNet(nn.Module): def __init__(self, input_nc, output_nc, nf): super(FrNet, self).__init__() self.conv1_d_stage1 = nn.Conv2d(input_nc, 8, 3, 1, 1) self.relu1_d_stage1 = nn.LeakyReLU() self.conv1_c_stage1 = nn.Conv2d((input_nc * 3), 8, 3, 1, 1) self.relu1_c_stage1 = nn.L...
def train(opt): print('Training Information') print('start from {}'.format(opt.start_from)) print('box from {}'.format(opt.input_box_dir)) print('attributes from {}'.format(opt.input_att_dir)) print('features from {}'.format(opt.input_fc_dir)) print('batch size ={}'.format(opt.batch_size)) p...
class BosonicTransformation(Transformation): def __init__(self, qubit_mapping: BosonicQubitMappingType=BosonicQubitMappingType.DIRECT, transformation_type: BosonicTransformationType=BosonicTransformationType.HARMONIC, basis_size: Union[(int, List[int])]=2, truncation: int=3): self._qubit_mapping = qubit_map...
def dicom_input_method(config, key_namespace='', patient_id='', site=None, **_): monaco_site = site FILE_UPLOAD = 'File upload' MONACO_SEARCH = 'Search Monaco file export location' import_method = st.radio('DICOM import method', [FILE_UPLOAD, MONACO_SEARCH], key=f'{key_namespace}_dicom_file_import_metho...
class Window(OperatorMixin): def __init__(self, sdf, n=None, value=None, with_state=False, start=None): if ((value is None) and isinstance(n, (str, pd.Timedelta))): value = n n = None self.n = n self.root = sdf if (isinstance(value, str) and isinstance(self.ro...
class ModelBuilder(): default_tri_ke = 100.0 default_tri_ka = 100.0 default_tri_kd = 10.0 default_tri_drag = 0.0 default_tri_lift = 0.0 default_edge_ke = 100.0 default_edge_kd = 0.0 def __init__(self): self.particle_q = [] self.particle_qd = [] self.particle_mass ...
def verify_online_player(caller, value): session_list = SESSIONS.get_sessions() char_list = [] matched_character = None for session in session_list: if (not session.logged_in): continue char_list.append(session.get_puppet()) for character in char_list: if (value.l...
def main(): if (not TOKEN): print('No token is set, skipping') return python = shutil.which('python') dependency = f'mkdocs-material[imaging] {DEP_REF}{GIT_REF}' try: process = subprocess.Popen([python, '-m', 'pip', 'install', '--disable-pip-version-check', dependency], stdout=s...
def test_from_string__wkt_with_proj(): wkt = 'PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298., AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0., ...
class ProviderValidator(): def __call__(self, data): provider_key = data.get('provider_key') provider = get_plugin('PROJECT_ISSUE_PROVIDERS', provider_key) if (provider is None): raise ValidationError({'provider_key': 'Please provide a valid provider.'}) try: ...
.parametrize('option_api, backend', [('pyqt5', 'PyQt5'), ('pyqt6', 'PyQt6'), ('pyside2', 'PySide2'), ('pyside6', 'PySide6')]) def test_already_loaded_backend(monkeypatch, option_api, backend): import builtins class Mock(): pass qtcore = Mock() for method_name in ('qInstallMessageHandler', 'qDebu...
def parse_davis2017_splits(): with open('data/davis/DAVIS/ImageSets/2017/train.txt') as f: train_list = [(vid.rstrip(), idx) for (idx, vid) in enumerate(f.readlines())] with open('data/davis/DAVIS/ImageSets/2017/val.txt') as f: val_list = [(vid.rstrip(), idx) for (idx, vid) in enumerate(f.readli...
class MobileViTDeepLabV3(nn.Module): def __init__(self, config: MobileViTConfig) -> None: super().__init__() self.aspp = MobileViTASPP(config) self.dropout = nn.Dropout2d(config.classifier_dropout_prob) self.classifier = MobileViTConvLayer(config, in_channels=config.aspp_out_channels...
class ACLExtractor(meta.FlatExtractor): def _record_to_object(record): newline_pos = record.find(b'\n') first_line = record[:newline_pos] if (not first_line.startswith(b'# file: ')): raise meta.ParsingError(('Bad record beginning: %r' % first_line)) filename = first_line[...
def test_redirect_both(capfd): msg = 'StdOut' msg2 = 'StdErr' stream = StringIO() stream2 = StringIO() with redirect_stdout(stream): with redirect_stderr(stream2): with m.ostream_redirect(): m.raw_output(msg) m.raw_err(msg2) (stdout, stderr) = ...
class Graph(pg.GraphItem): def __init__(self): self.dragPoint = None self.dragOffset = None self.textItems = [] pg.GraphItem.__init__(self) self.scatter.sigClicked.connect(self.clicked) def setData(self, **kwds): self.text = kwds.pop('text', []) self.data ...
class FusedLeakyReLUFunction(Function): def forward(ctx, input, bias, negative_slope, scale): empty = input.new_empty(0) out = fused_act_ext.fused_bias_act(input, bias, empty, 3, 0, negative_slope, scale) ctx.save_for_backward(out) ctx.negative_slope = negative_slope ctx.scal...
_arg_scope def split_separable_conv2d(input_tensor, num_outputs, scope=None, normalizer_fn=None, stride=1, rate=1, endpoints=None, use_explicit_padding=False): with _v1_compatible_scope_naming(scope) as scope: dw_scope = (scope + 'depthwise') endpoints = (endpoints if (endpoints is not None) else {}...