code
stringlengths
281
23.7M
def to_py_obj(obj): if isinstance(obj, (dict, UserDict)): return {k: to_py_obj(v) for (k, v) in obj.items()} elif isinstance(obj, (list, tuple)): return [to_py_obj(o) for o in obj] elif (is_tf_available() and _is_tensorflow(obj)): return obj.numpy().tolist() elif (is_torch_availa...
_criterion('label_smoothed_cross_entropy') class LabelSmoothedCrossEntropyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) self.eps = args.label_smoothing def add_args(parser): parser.add_argument('--label-smoothing', default=0.0, type=float, meta...
def test_matchnodes_two_collections_same_file(pytester: Pytester) -> None: pytester.makeconftest('\n import pytest\n def pytest_configure(config):\n config.pluginmanager.register(Plugin2())\n\n class Plugin2(object):\n def pytest_collect_file(self, file_path, parent):\n ...
class _ROIAlignRotated(Function): def forward(ctx, input, roi, output_size, spatial_scale, sampling_ratio): ctx.save_for_backward(roi) ctx.output_size = _pair(output_size) ctx.spatial_scale = spatial_scale ctx.sampling_ratio = sampling_ratio ctx.input_shape = input.size() ...
class DecisionTransformerModelTester(): def __init__(self, parent, batch_size=13, seq_length=7, act_dim=6, state_dim=17, hidden_size=23, max_length=11, is_training=True): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.act_dim = act_dim sel...
def get_zip_manifest(zip_root, zip_filename): zip_path = op.join(zip_root, zip_filename) with zipfile.ZipFile(zip_path, mode='r') as f: info = f.infolist() manifest = {} for i in tqdm(info): utt_id = op.splitext(i.filename)[0] (offset, file_size) = (((i.header_offset + 30) + len(...
def test(args, device_id, pt, step): device = ('cpu' if (args.visible_gpus == '-1') else 'cuda') if (pt != ''): test_from = pt else: test_from = args.test_from logger.info(('Loading checkpoint from %s' % test_from)) checkpoint = torch.load(test_from, map_location=(lambda storage, loc...
def test_get_pipeline_path_absolute_path_ignore_parent(): abs_path = Path('tests/testpipelinewd.yaml').resolve() str_abs_sans_yaml = str(abs_path.with_suffix('')) path_found = fileloader.get_pipeline_path(str_abs_sans_yaml, 'parent') expected_path = cwd_tests.joinpath('testpipelinewd.yaml') assert (...
def parse_search_arg(search): groups = search.split() entries = dict((g.split('=') for g in groups)) entry_names = list(entries.keys()) sets = [[f'--{k} {v}' for v in vs.split(':')] for (k, vs) in entries.items()] matrix = [list(x) for x in itertools.product(*sets)] return (matrix, entry_names)
def test_change_mychar(skip_qtbot: pytestqt.qtbot.QtBot) -> None: cosmetic_patches = CSCosmeticPatches() dialog = CSCosmeticPatchesDialog(None, cosmetic_patches) skip_qtbot.addWidget(dialog) skip_qtbot.mouseClick(dialog.mychar_left_button, QtCore.Qt.MouseButton.LeftButton) assert (dialog.cosmetic_pa...
def _partial_compare_list(val1, val2, *, indent): if (len(val1) < len(val2)): outcome = PartialCompareOutcome('Second list is longer than first list') print_i(outcome.error, indent, error=True) return outcome for (item1, item2) in zip(val1, val2): outcome = partial_compare(item1,...
class GreedyPerfPartitioner(Partitioner): def __init__(self, sort_by: SortBy=SortBy.STORAGE, balance_modules: bool=False) -> None: self._sort_by = sort_by self._balance_modules = balance_modules def partition(self, proposal: List[ShardingOption], storage_constraint: Topology) -> List[ShardingOpt...
def test_single_output(mode): n_steps = int64('n_steps') x0 = float64('x0') const = float64('const') x = (x0 + const) op = ScalarLoop(init=[x0], constant=[const], update=[x]) x = op(n_steps, x0, const) fn = function([n_steps, x0, const], x, mode=mode) np.testing.assert_allclose(fn(5, 0, ...
def test_mice_ordering(): phi1 = mice() phi2 = mice(phi=(1.0 + (EPSILON * 2)), partition=()) assert (phi1 < phi2) assert (phi2 > phi1) assert (phi1 <= phi2) assert (phi2 >= phi1) different_direction = mice(direction='different') assert (phi2 > different_direction) assert (different_d...
def closeness_centrality(graph, name='closeness', weight='mm_len', radius=None, distance=None, verbose=True, **kwargs): netx = graph.copy() if radius: lengraph = len(netx) for n in tqdm(netx, total=len(netx), disable=(not verbose)): sub = nx.ego_graph(netx, n, radius=radius, distance...
class FCTDecoderLayer(nn.Module): def __init__(self, h, d_model, p, d_ff, attn_p=0.1): super(FCTDecoderLayer, self).__init__() self.preprocess_attn = PrePostProcessing(d_model, p, sequence='n') self.postprocess_attn = PrePostProcessing(d_model, p, sequence='da', static=True) self.pre...
class PageSerializer(ThroughModelSerializerMixin, TranslationSerializerMixin, ElementModelSerializerMixin, ElementWarningSerializerMixin, ReadOnlyObjectPermissionSerializerMixin, serializers.ModelSerializer): model = serializers.SerializerMethodField() uri_path = serializers.CharField(required=True) section...
class TestKernprof(unittest.TestCase): def test_enable_disable(self): profile = ContextualProfile() self.assertEqual(profile.enable_count, 0) profile.enable_by_count() self.assertEqual(profile.enable_count, 1) profile.enable_by_count() self.assertEqual(profile.enable_...
def write_tokenizer(tokenizer_path, input_tokenizer_path): print(f'Fetching the tokenizer from {input_tokenizer_path}.') os.makedirs(tokenizer_path, exist_ok=True) write_json({}, os.path.join(tokenizer_path, 'special_tokens_map.json')) write_json({'bos_token': '', 'eos_token': '', 'model_max_length': in...
def test_logxml_changingdir(pytester: Pytester) -> None: pytester.makepyfile('\n def test_func():\n import os\n os.chdir("a")\n ') pytester.mkdir('a') result = pytester.runpytest('--junitxml=a/x.xml') assert (result.ret == 0) assert pytester.path.joinpath('a/x.xml').e...
def resp_create_group_access_token(): content = {'user_id': 141, 'scopes': ['api'], 'name': 'token', 'expires_at': '2021-01-31', 'id': 42, 'active': True, 'created_at': '2021-01-20T22:11:48.151Z', 'revoked': False} with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps: rsps.add(method...
def print_scatter(model, p=0.0, interface=None): if (interface is not None): discontinuities = [model.discontinuity(interface)] else: discontinuities = model.discontinuities() for discontinuity in discontinuities: print(('%s (%g km)' % (discontinuity, (discontinuity.z / cake.km)))) ...
class NotRequiredTests(BaseTestCase): def test_basics(self): if (not TYPING_3_11_0): with self.assertRaises(TypeError): NotRequired[1] with self.assertRaises(TypeError): NotRequired[(int, str)] with self.assertRaises(TypeError): NotRequired...
class ConfigDict(Dict): def __missing__(self, name): raise KeyError(name) def __getattr__(self, name): try: value = super(ConfigDict, self).__getattr__(name) except KeyError: ex = AttributeError("'{}' object has no attribute '{}'".format(self.__class__.__name__, n...
def test_any_value() -> None: any = AnyValue(AnySource.unannotated) assert (not any.is_type(int)) assert_can_assign(any, KnownValue(1)) assert_can_assign(any, TypedValue(int)) assert_can_assign(any, MultiValuedValue([KnownValue(1), TypedValue(int)])) assert (str(any) == 'Any[unannotated]') a...
def prune_model(args): device = torch.device(('cuda:{}'.format(args.gpu) if ((args.gpu >= 0) and torch.cuda.is_available()) else 'cpu')) if ((args.gpu >= 0) and torch.cuda.is_available()): cudnn.benchmark = True if (args.type == 'float64'): dtype = torch.float64 elif (args.type == 'float...
class BaseObject(nn.Module): def __init__(self, name=None): super().__init__() self._name = name def __name__(self): if (self._name is None): name = self.__class__.__name__ s1 = re.sub('(.)([A-Z][a-z]+)', '\\1_\\2', name) return re.sub('([a-z0-9])([A-Z...
_module class WIDERFaceDataset(XMLDataset): CLASSES = ('face',) def __init__(self, **kwargs): super(WIDERFaceDataset, self).__init__(**kwargs) def load_annotations(self, ann_file): img_infos = [] img_ids = mmcv.list_from_file(ann_file) for img_id in img_ids: filen...
def createRelationalTables(): query = QSqlQuery() query.exec_('create table employee(id int, name varchar(20), city int, country int)') query.exec_("insert into employee values(1, 'Espen', 5000, 47)") query.exec_("insert into employee values(2, 'Harald', 80000, 49)") query.exec_("insert into employe...
def create_inline(project, resource, offset): pyname = _get_pyname(project, resource, offset) message = 'Inline refactoring should be performed on a method, local variable or parameter.' if (pyname is None): raise exceptions.RefactoringError(message) if isinstance(pyname, pynames.ImportedName): ...
class PrettifyBaseEntryTestCase(unittest.TestCase): def setUp(self): self.element = dict(name='soccer shoes', value=(- 123.45), date='04-01', category='sport equipment') def test_prettify(self): self.assertEqual(prettify_entry(self.element, default_category=CategoryEntry.DEFAULT_NAME), 'Name ...
def bench_pickle_list(loops, pickle, options): range_it = range(loops) dumps = pickle.dumps obj = LIST protocol = options.protocol t0 = pyperf.perf_counter() for _ in range_it: dumps(obj, protocol) dumps(obj, protocol) dumps(obj, protocol) dumps(obj, protocol) ...
def sample_initial_conditions(model, points_to_sample, traj_length=1000, pts_per_period=30): initial_sol = model.make_trajectory(traj_length, resample=True, pts_per_period=pts_per_period, postprocess=False) sample_inds = np.random.choice(np.arange(initial_sol.shape[0]), points_to_sample, replace=False) samp...
def pairwise(accuracy_balanced, method_names, out_results_dir, num_repetitions): bal_acc_transposed = accuracy_balanced.T num_datasets = len(method_names) median_bal_acc = np.nanmedian(accuracy_balanced, axis=0) ranks = np.rank(median_bal_acc) critical_dist = compute_critical_dist(ranks) signif_...
def test_translate(): mt = dlt.TranslationModel() msg_en = 'Hello everyone, how are you?' assert (mt.translate(msg_en, source='English', target='Spanish') == 'Hola a todos, como estas?') fr_1 = mt.translate(msg_en, source='English', target='French') ch = mt.translate(msg_en, source='English', target...
class DialogueManager(): def __init__(self, rec, agent, user, bftracker): self.tracker_idx_list = [0, 1, 2, 3, 4] self.facet_action_dict = {'categories': 0, 'state': 1, 'city': 2, 'price': 3, 'stars': 4, 'recommend': 5} self.rec = rec self.agent = agent self.user = user ...
.parametrize('molecule, atom_index, expected', [pytest.param('water', 0, 'O', id='O'), pytest.param('water', 1, 'X', id='Polar H'), pytest.param('acetone', 4, 'H', id='Normal H')]) def test_get_param_code(molecule, atom_index, expected, request): molecule = request.getfixturevalue(molecule) rfree_code = _get_pa...
class Effect5793(BaseEffect): type = 'passive' def handler(fit, container, context, projectionRange, **kwargs): level = (container.level if ('skill' in context) else 1) for attr in ('maxRangeBonus', 'falloffBonus'): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('W...
class RandomValuePicker(): def __init__(self, pools): self._pools = [] for pool in pools: self._pools.append(pool) def _cell_size(self): return self._pools[0]['cell_size'] def _get_static_size(self, th): return ((th * 8000) * self._cell_size()) def _get_size(s...
def apply_along_last_axis(func, *args, **kwargs): first_arg_name = getfullargspec(func)[0][0] has_positional_arg = (len(args) > 0) input_arg = (args[0] if has_positional_arg else kwargs[first_arg_name]) if (input_arg.ndim == 1): ret = func(*args, **kwargs) else: if (len(args) == 0): ...
def test_region_locked_error(): with pytest.raises(exceptions.VideoUnavailable): raise exceptions.VideoRegionBlocked('hZpzr8TbF08') try: raise exceptions.VideoRegionBlocked('hZpzr8TbF08') except exceptions.VideoRegionBlocked as e: assert (e.video_id == 'hZpzr8TbF08') assert (...
def dropout(x, drop_prob, shared_axes=[], training=False): if ((drop_prob == 0) or (drop_prob == None) or (not training)): return x sz = list(x.size()) for i in shared_axes: sz[i] = 1 mask = x.new(*sz).bernoulli_((1.0 - drop_prob)).div_((1.0 - drop_prob)) mask = mask.expand_as(x) ...
def _identify_slide(group): def _possible_offset(all_args): for arg1 in all_args[1]: for (i, arg0) in enumerate(all_args[0]): if (arg0 == arg1): return i return None if (isinstance(group.abstraction, dict) and (len([v for v in group.abstraction.val...
class RepoMirrorAPI(object): def __init__(self, config, server_hostname=None, skip_validation=False, instance_keys=None): feature_enabled = config.get('FEATURE_REPO_MIRROR', False) has_valid_config = skip_validation if ((not skip_validation) and feature_enabled): config_validator...
def test_error_stream(testcase: DataDrivenTestCase) -> None: options = Options() options.show_traceback = True options.hide_error_codes = True logged_messages: list[str] = [] def flush_errors(filename: (str | None), msgs: list[str], serious: bool) -> None: if msgs: logged_message...
class SeedScheduler(): def has_seed_remaining(self) -> bool: raise NotImplementedError() def add(self, seed: Seed) -> None: raise NotImplementedError() def update_worklist(self, coverage: GlobalCoverage) -> None: raise NotImplementedError() def can_solve_models(self) -> bool: ...
def main(gpu, ngpus_per_node, cfg, args): args.local_rank = gpu if (args.local_rank <= 0): os.makedirs(args.save_path, exist_ok=True) logger = init_log_save(args.save_path, 'global', logging.INFO) logger.propagate = 0 if (args.local_rank <= 0): tb_dir = args.save_path tb = Su...
def set_partitions(in_dict): rules = _get_partition_rules() replace = _replacement_rules(rules) initd = {k: _unmatched for k in flatten_dict(in_dict)} result = {k: replace(k, v) for (k, v) in initd.items()} assert (_unmatched not in result.values()), 'Incomplete partition spec.' return freeze(un...
def generate_pairs_reverse(numCat, numRep, pre_graph): result = [] for i in range(numCat): cat_result = [] for j in range(len(pre_graph)): if (i in pre_graph[j]): cat_result.append(j) for _ in range(numRep): result.append(torch.tensor(cat_result)) ...
class MemoryFileObject(): def __init__(self, file): self.file = file if ((not getattr(self.file, 'seek', None)) or (not getattr(self.file, 'tell', None))): raise Exception('File object does not support seeking.') self.file.seek(0, 2) self.file_size = self.file.tell() ...
class LowLevelIRBuilder(): def __init__(self, current_module: str, errors: Errors, mapper: Mapper, options: CompilerOptions) -> None: self.current_module = current_module self.errors = errors self.mapper = mapper self.options = options self.args: list[Register] = [] s...
def calculate_SNR(pxx_pred, f_pred, currHR, signal): currHR = (currHR / 60) f = f_pred pxx = pxx_pred gtmask1 = ((f >= (currHR - 0.1)) & (f <= (currHR + 0.1))) gtmask2 = ((f >= ((currHR * 2) - 0.1)) & (f <= ((currHR * 2) + 0.1))) sPower = np.sum(np.take(pxx, np.where((gtmask1 | gtmask2)))) i...
class HFProxy(Proxy): def __init__(self, node: Node, tracer: Optional[Tracer]=None): super().__init__(node, tracer=tracer) if (hasattr(self, 'tracer') and (self.tracer is not None)): self.device = self.tracer.root.device self.dtype = next(self.tracer.root.parameters()).dtype ...
class AbbeMaterial(Material): def __init__(self, n=1.0, v=np.inf, lambda_ref=lambda_d, lambda_long=lambda_C, lambda_short=lambda_F, **kwargs): super().__init__(**kwargs) self.n = n self.v = v self.lambda_ref = lambda_ref self.lambda_short = lambda_short self.lambda_lo...
class AverageLearner(BaseLearner): def __init__(self, function: Callable[([int], Real)], atol: (float | None)=None, rtol: (float | None)=None, min_npoints: int=2) -> None: if ((atol is None) and (rtol is None)): raise Exception('At least one of `atol` and `rtol` should be set.') if (atol...
def test_driven_control_default_values(): _rabi_rates = np.array([np.pi, np.pi, 0]) _azimuthal_angles = np.array([(np.pi / 2), 0, (- np.pi)]) _detunings = np.array([0, 0, 0]) _durations = np.array([1, 2, 3]) _name = 'driven_control' driven_control = DrivenControl(rabi_rates=None, azimuthal_angle...
class Module(): def __init__(self, name, title=None, *, automodule_options=None, append=None): self.append = append self.name = name self.title = (title or ' '.join(map(str.title, self.name.split('.')[1:]))) self.automodule_options = (automodule_options or list()) def __repr__(se...
def random_date(begin: datetime.datetime, end: datetime.datetime): epoch = datetime.datetime(1970, 1, 1) begin_seconds = int((begin - epoch).total_seconds()) end_seconds = int((end - epoch).total_seconds()) dt_seconds = random.randint(begin_seconds, end_seconds) return datetime.datetime.fromtimestam...
def test_aws_session_class_endpoint(): pytest.importorskip('boto3') sesh = AWSSession(endpoint_url='example.com') assert (sesh.get_credential_options()['AWS_S3_ENDPOINT'] == 'example.com') sesh = AWSSession(endpoint_url='example.com', aws_unsigned=True) assert (sesh.get_credential_options()['AWS_S3_...
def _multiprocessing_managers_transform(): return parse("\n import array\n import threading\n import multiprocessing.pool as pool\n import queue\n\n class Namespace(object):\n pass\n\n class Value(object):\n def __init__(self, typecode, value, lock=True):\n self._typecode ...
class _StreamCloser(_Closer): def __init__(self, write, close_on_exit): self.write = write self.close_on_exit = close_on_exit def close(self, parent_close): super().close(parent_close) if self.close_on_exit: closer = getattr(self.write, 'close', None) if c...
def test_multi_addr(): r2p = r2pipe.open('-', flags=['-2']) r2p.cmd('wa mov [rax], rbx') esilsolver = ESILSolver(r2p, debug=True, trace=False) state = esilsolver.init_state() state.set_symbolic_register('rax') rax = state.registers['rax'] state.solver.add((rax > 7)) state.solver.add((rax...
class TestPolyFillArc(EndianTest): def setUp(self): self.req_args_0 = {'arcs': [{'x': (- 3276), 'y': (- 22928), 'width': 33490, 'height': 20525, 'angle1': (- 10916), 'angle2': (- 19386)}], 'drawable': , 'gc': } self.req_bin_0 = b'G\x00\x06\x00\x82\\\xc1)\x1b\xdb\x8234\xf3p\xa6\xd2\x82-P\\\xd5F\xb4' ...
class BaseLastTransitionLog(BaseTransitionLog): class Meta(): verbose_name = _('XWorkflow last transition log') verbose_name_plural = _('XWorkflow last transition logs') abstract = True def _update_or_create(cls, unique_fields, **kwargs): (last_transition, created) = cls.objects....
def get_hiformer_b_configs(): cfg = ml_collections.ConfigDict() cfg.swin_pyramid_fm = [96, 192, 384] cfg.image_size = 224 cfg.patch_size = 4 cfg.num_classes = 9 if (not os.path.isfile('./weights/swin_tiny_patch4_window7_224.pth')): print('Downloading Swin-transformer model ...') ...
class RandomMaskingGenerator(): def __init__(self, input_size, mask_ratio): self.num_patches = int(input_size) self.num_mask = int((mask_ratio * self.num_patches)) def __repr__(self): repr_str = 'Maks: total patches {}, mask patches {}'.format(self.num_patches, self.num_mask) ret...
def seek_backward(_request: WSGIRequest) -> None: player.seek_backward(SEEK_DISTANCE) try: current_song = models.CurrentSong.objects.get() now = timezone.now() current_song.created += datetime.timedelta(seconds=SEEK_DISTANCE) current_song.created = min(current_song.created, now) ...
def create_data_files(input_path: str, output_path: str, download: bool): input_path = os.path.expanduser(input_path) output_path = os.path.expanduser(output_path) if download: os.makedirs(input_path, exist_ok=True) output_train_folder = os.path.join(output_path, 'train') train_set = PatchCa...
def main(args): assert (args.dataset in ['mnist', 'cifar', 'svhn']), "Dataset parameter must be either 'mnist', 'cifar' or 'svhn'" assert (args.attack in ['fgsm', 'bim-a', 'bim-b', 'jsma', 'cw-l2', 'all']), "Attack parameter must be either 'fgsm', 'bim-a', 'bim-b', 'jsma' or 'cw-l2'" assert (args.characteri...
class RandomUsernameTest(BaseActionTest): user_data_body = json.dumps({'id': 1, 'avatar_url': ' 'gravatar_id': 'somehexcode', 'url': ' 'name': 'monalisa foobar', 'company': 'GitHub', 'blog': ' 'location': 'San Francisco', 'email': '', 'hireable': False, 'bio': 'There once was...', 'public_repos': 2, 'public_gists':...
class RayExecutor(): def set_env_var(self, key: str, value: str): if (value is not None): value = str(value) os.environ[key] = value def set_env_vars(self, keys: List[str], values: List[str]): assert (len(keys) == len(values)) for (key, value) in zip(keys, values)...
class PushTImageEnv(PushTEnv): metadata = {'render.modes': ['rgb_array'], 'video.frames_per_second': 10} def __init__(self, legacy=False, block_cog=None, damping=None, render_size=96): super().__init__(legacy=legacy, block_cog=block_cog, damping=damping, render_size=render_size, render_action=False) ...
def update_maxmind_dbs(outdir): print('Updating the GeoIP databases from MaxMind...') if (not MAXMIND_LICENSE_KEY): raise RuntimeError('No envvar MAXMIND_LICENSE_KEY. Cannot download the databases without this. Create a MaxMind account.') for url in (MAXMIND_COUNTRY_DATABASE, MAXMIND_CITY_DATABASE):...
class DirectSDBWriter(): def __init__(self, sdb_filename, buffering=BUFFER_SIZE, audio_type=AUDIO_TYPE_OPUS, bitrate=None, id_prefix=None, labeled=True): self.sdb_filename = sdb_filename self.id_prefix = (sdb_filename if (id_prefix is None) else id_prefix) self.labeled = labeled if (...
class LineSegmentROI(ROI): def __init__(self, positions=(None, None), pos=None, handles=(None, None), **args): if (pos is None): pos = [0, 0] ROI.__init__(self, pos, [1, 1], **args) if (len(positions) > 2): raise Exception('LineSegmentROI must be defined by exactly 2 ...
(params=[{}, {'teleporters': TeleporterShuffleMode.ONE_WAY_ANYTHING, 'translator_configuration': True}]) def layout_config(request, default_echoes_configuration): if ('translator_configuration' in request.param): translator_requirement = copy.copy(default_echoes_configuration.translator_configuration.transl...
.end_to_end() def test_parametrization_in_for_loop_with_ids(tmp_path, runner): source = '\n import pytask\n\n for i in range(2):\n\n .task(\n "deco_task", id=str(i), kwargs={"i": i, "produces": f"out_{i}.txt"}\n )\n def example(produces, i):\n produces.write_text(str...
def test_order_with_dependency(item_names_for): tests_content = '\n import pytest\n\n .dependency(depends=["test_b"])\n .order("second")\n def test_a():\n pass\n\n .dependency()\n def test_b():\n pass\n ' assert (item_names_for(tests_content...
.utils .parametrize('arguments, func_args, expected', [(['a'], [0, 0], 0), (['b'], [1, 1], 2), (['a', 'b'], [0, 1], 1), (['b', 'a'], [0, 1], 1)]) def test_without_error(arguments, func_args, expected): _kwargs(*arguments) def simple_sum(alpha, beta, a=0, b=0): return (alpha + beta) assert (simple_su...
def main(mode='folder'): opt = {} opt['dist'] = False opt['phase'] = 'train' opt['name'] = 'DIV2K' opt['type'] = 'PairedImageDataset' if (mode == 'folder'): opt['dataroot_gt'] = 'datasets/DIV2K/DIV2K_train_HR_sub' opt['dataroot_lq'] = 'datasets/DIV2K/DIV2K_train_LR_bicubic/X4_sub...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, gen_attention=None): super(BasicBlock, self).__init__() assert (dcn is None), 'Not i...
() def _django_db_helper(request: pytest.FixtureRequest, django_db_setup: None, django_db_blocker: DjangoDbBlocker) -> Generator[(None, None, None)]: from django import VERSION if is_django_unittest(request): (yield) return marker = request.node.get_closest_marker('django_db') if marker:...
def modality_fcn(net_spec, data, modality): n = net_spec (n[('conv1_1' + modality)], n[('relu1_1' + modality)]) = conv_relu(n[data], 64, pad=100) (n[('conv1_2' + modality)], n[('relu1_2' + modality)]) = conv_relu(n[('relu1_1' + modality)], 64) n[('pool1' + modality)] = max_pool(n[('relu1_2' + modality)]...
class ObjectEditForm(ObjectCreateForm): class Meta(object): fields = '__all__' db_lock_storage = forms.CharField(label='Locks', required=False, widget=forms.Textarea(attrs={'cols': '100', 'rows': '2'}), help_text='In-game lock definition string. If not given, defaults will be used. This string should be...
def test_equation_of_time(): times = pd.date_range(start='1/1/2015 0:00', end='12/31/2015 23:00', freq='H') output = solarposition.spa_python(times, 37.8, (- 122.25), 100) eot = output['equation_of_time'] eot_rng = (eot.max() - eot.min()) eot_1 = solarposition.equation_of_time_spencer71(times.dayofy...
_time('14-06-15 15:44:25') class TestListAPIView(CassandraTestCase): def test_get(self): thing = create_thing() response = self.client.get(reverse('thing_listview_api')) self.assertEqual(response.status_code, client.OK) expected_response = [{'created_on': '2015-06-14T15:44:25Z', 'dat...
class SlugModelTest(TestCase): def setUp(self): User = get_user_model() u = User.objects.create_user('julia', password='julia') def test_autocreateSlug(self): pu = PytitionUser.objects.get(user__username='julia') self.assertEqual(SlugModel.objects.count(), 0) p = Petition...
def test_parameterset_for_fail_at_collect(pytester: Pytester) -> None: pytester.makeini('\n [pytest]\n {}=fail_at_collect\n '.format(EMPTY_PARAMETERSET_OPTION)) config = pytester.parseconfig() from _pytest.mark import pytest_configure, get_empty_parameterset_mark pytest_configure(config) wi...
class EnclaveCreationBreakpoint(): def __init__(self, target): breakpoint = target.BreakpointCreateByName('oe_debug_enclave_created_hook') breakpoint.SetScriptCallbackFunction('lldb_sgx_plugin.EnclaveCreationBreakpoint.onHit') def onHit(frame, bp_loc, dict): enclave_addr = frame.FindValu...
class ANETclassification(object): GROUND_TRUTH_FIELDS = ['database', 'taxonomy', 'version'] PREDICTION_FIELDS = ['results', 'version', 'external_data'] def __init__(self, ground_truth_filename=None, prediction_filename=None, ground_truth_fields=GROUND_TRUTH_FIELDS, prediction_fields=PREDICTION_FIELDS, subse...
class QuantizableInception(Inception): def __init__(self, *args, **kwargs): super(QuantizableInception, self).__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) self.cat = nn.quantized.FloatFunctional() def forward(self, x): outputs = self._forward(x) return self.cat.ca...
class Migration(migrations.Migration): dependencies = [('devices', '0001_initial')] operations = [migrations.AlterField(model_name='device', name='verification_code_expires_at', field=models.DateTimeField(default=junction.devices.models.expiry_time, verbose_name='Verification Code Expires At'), preserve_default...
def append_call_sample_docstring(model_class, tokenizer_class, checkpoint, output_type, config_class, mask=None): model_class.__call__ = copy_func(model_class.__call__) model_class.__call__ = add_code_sample_docstrings(processor_class=tokenizer_class, checkpoint=checkpoint, output_type=output_type, config_class...
def nca(similarities, targets, class_weights=None, focal_gamma=None, scale=1.0, margin=0.6, exclude_pos_denominator=True, hinge_proxynca=False, memory_flags=None): margins = torch.zeros_like(similarities) margins[(torch.arange(margins.shape[0]), targets)] = margin similarities = (scale * (similarities - mar...
class P3S_TD3(MARLAlgorithm, Serializable): def __init__(self, base_kwargs, env, arr_actor, best_actor, dict_ph, arr_initial_exploration_policy, with_best=False, initial_beta_t=1, plotter=None, specific_type=0, target_noise_scale=0.2, target_noise_clip=0.5, target_ratio=2, target_range=0.04, lr=0.003, discount=0.99...
class UniformPolicy(Policy, Serializable): def __init__(self, env_spec): Serializable.quick_init(self, locals()) self._Da = env_spec.action_space.flat_dim super(UniformPolicy, self).__init__(env_spec) def get_action(self, observation): return (np.random.uniform((- 1.0), 1.0, self...
class Git(): def __init__(self, directory): self.directory = directory def last_commit_time(self): with TemporaryFile(mode='w+') as out: with open(os.devnull, 'w') as DEVNULL: Executable('git').check_call('log -r -1 --pretty="%ci"'.split(), cwd=self.directory, stdout=...
def command_server(conn): while True: (cmd, cwd, verbose) = conn.recv() res: subprocess.CompletedProcess = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd) if verbose: print((f'{cwd}$ ' + ' '.join(res.args))) print(res.stdout.decode(), en...
def parse_replay(replay_player_path, sampled_action_path, reward): if os.path.isfile(os.path.join(FLAGS.parsed_replay_path, 'GlobalFeatures', replay_player_path)): return with open(os.path.join(FLAGS.parsed_replay_path, 'GlobalInfos', replay_player_path)) as f: global_info = json.load(f) uni...
_LAYERS.register_module('DCNv2') class ModulatedDeformConv2dPack(ModulatedDeformConv2d): _version = 2 def __init__(self, *args, **kwargs): super(ModulatedDeformConv2dPack, self).__init__(*args, **kwargs) self.conv_offset = nn.Conv2d(self.in_channels, (((self.deform_groups * 3) * self.kernel_size...