code
stringlengths
281
23.7M
def do_setup() -> int: root = get_root() try: cfg = get_config_from_root(root) except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (OSError, configparser.NoSectionError)): print('Adding sample versioneer config to setup.cfg', file=sys....
class KinopoiskObject(object): id = None objects = None _urls = {} _sources = [] _source_classes = {} def __init__(self, id=None, **kwargs): if id: self.id = id self.set_defaults() self.__dict__.update(kwargs) def set_defaults(self): pass def p...
def ArtistList(): (artist_to_add, set_artist_to_add) = use_state('') (artists, set_artists) = use_state([]) def handle_change(event): set_artist_to_add(event['target']['value']) def handle_click(event): if (artist_to_add and (artist_to_add not in artists)): set_artists([*arti...
def run_and_save(n: int, depth: int, n_data: int, batch_size: int, n_shots: int, save_dir: str, use_engine: bool) -> None: logging.info('Beginning conventional circuit generation for Weber.') system_pairs = run_config.qubit_pairs() system_pairs = system_pairs[:n] to_run_scramb = [_build_circuit(system_p...
def make_layers(cfg: List[Union[(str, int)]], batch_norm: bool=False) -> nn.Sequential: layers = [] in_channels = 3 for v in cfg: if (v == 'M'): layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: v = cast(int, v) conv2d = MetaConv2d(in_channels, v, ke...
class AdvancedSubtensor1(COp): __props__ = () _f16_ok = True check_input = False def __init__(self, sparse_grad=False): self.sparse_grad = sparse_grad def make_node(self, x, ilist): x_ = as_tensor_variable(x) ilist_ = as_tensor_variable(ilist) if (ilist_.type.dtype no...
class ModelArguments(): model_name_or_path: Optional[str] = field(default=None, metadata={'help': "The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."}) model_type: Optional[str] = field(default=None, metadata={'help': ('If training from scratch, pass a model ty...
.parametrize('orientation', ['vertical', 'horizontal']) def test_clip_to_plot_data_item(orientation): init_vals = ((- 1.5), 1.5) x = np.linspace((- 1), 1, 10) y = np.linspace(1, 1.2, 10) p = pg.PlotWidget() pdi = p.plot(x=x, y=y) lr = pg.LinearRegionItem(init_vals, clipItem=pdi, orientation=orie...
def test_call_on_instance_with_inherited_dunder_call_method() -> None: node = extract_node('\n class Base:\n def __call__(self):\n return self\n\n class Sub(Base):\n pass\n obj = Sub()\n val = obj()\n val #\n ') assert isinstance(node, nodes.NodeNG) [val] = node.in...
class Migration(migrations.Migration): initial = True dependencies = [('auth', '0011_update_proxy_permissions')] operations = [migrations.CreateModel(name='User', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_leng...
class WRNInitBlock(nn.Module): def __init__(self, in_channels, out_channels): super(WRNInitBlock, self).__init__() self.conv = WRNConv(in_channels=in_channels, out_channels=out_channels, kernel_size=7, stride=2, padding=3, activate=True) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padd...
def infer_gsdmm_topics(gsdmm_model, texts): assert (type(texts) == list) assert (type(texts[0]) == list) assert (type(texts[0][0]) == str) dist_over_topic = [gsdmm_model.score(t) for t in texts] global_topics = extract_topic_from_gsdmm_prediction(dist_over_topic) return global_topics
class TagModelQuerySet(models.query.QuerySet): def initial(self): return self.filter(name__in=self.model.tag_options.initial) def filter_or_initial(self, *args, **kwargs): return self.filter((models.Q(*args, **kwargs) | models.Q(name__in=self.model.tag_options.initial))) def weight(self, min...
def chemcore(mol, spinorb=False): core = 0 for a in range(mol.natm): atm_nelec = mol.atom_charge(a) atm_z = charge(mol.atom_symbol(a)) ne_ecp = (atm_z - atm_nelec) ncore_ecp = (ne_ecp // 2) atm_ncore = chemcore_atm[atm_z] if (ncore_ecp > atm_ncore): co...
def assert_plugin_add_result(tester: CommandTester, expected: str, constraint: (str | Mapping[(str, (str | list[str]))])) -> None: assert (tester.io.fetch_output() == expected) dependencies: dict[(str, Any)] = get_self_command_dependencies() assert ('poetry-plugin' in dependencies) assert (dependencies[...
class TCN_GCN_unit_5(nn.Module): def __init__(self, in_channels, out_channels, A, stride=1, residual=True): super(TCN_GCN_unit_5, self).__init__() self.gcn1 = unit_gtcn_5(in_channels, out_channels, A) self.tcn1 = unit_tcn(out_channels, out_channels, stride=stride) self.relu = nn.ReLU...
class BaseLM(LM): def eot_token_id(self): pass def max_length(self): pass def max_gen_toks(self): pass def batch_size(self): pass def device(self): pass def tok_encode(self, string: str): pass def tok_decode(self, tokens: Iterable[int]): ...
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 10) def forward...
def parse_html_form(attr_filter, html, input_names={}): attr_str = ('' if callable(attr_filter) else attr_filter) for form in re.finditer(f'(?P<TAG><form[^>]*{attr_str}.*?>)(?P<CONTENT>.*?)</?(form|body|html).*?>', html, (re.I | re.S)): if (callable(attr_filter) and (not attr_filter(form.group('TAG'))))...
class WarmupCosineWithHardRestartsSchedule(WarmupCosineSchedule): def __init__(self, warmup=0.002, t_total=(- 1), cycles=1.0, **kw): super(WarmupCosineWithHardRestartsSchedule, self).__init__(warmup=warmup, t_total=t_total, cycles=cycles, **kw) assert (cycles >= 1.0) def get_lr_(self, progress):...
class CoCaLoss(ClipLoss): def __init__(self, caption_loss_weight, clip_loss_weight, pad_id=0, local_loss=False, gather_with_grad=False, cache_labels=False, rank=0, world_size=1, use_horovod=False): super().__init__(local_loss=local_loss, gather_with_grad=gather_with_grad, cache_labels=cache_labels, rank=ran...
_task(name='CosRearrangementTask-v0') class CosRearrangementTask(NavigationTask): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.reset_trackers(False) self.load_annotations() self.rec_packers: Dict[(int, ShelfBinPacker)] = {} def get_translation(self, objec...
class EvaluateTool(object): def __init__(self, args): self.args = args def evaluate(self, preds, golds, section): summary = {} all_match = [] simple_match = [] complex_match = [] small_test_match = [] for (pred, gold_item) in zip(preds, golds): ...
class CoreNLPTokenizer(Tokenizer): def __init__(self, **kwargs): self.classpath = (kwargs.get('classpath') or DEFAULTS['corenlp_classpath']) self.annotators = copy.deepcopy(kwargs.get('annotators', set())) self.mem = kwargs.get('mem', '2g') self._launch() def _launch(self): ...
def escape_md_section(text, snob=False): text = md_backslash_matcher.sub('\\\\\\1', text) if snob: text = md_chars_matcher_all.sub('\\\\\\1', text) text = md_dot_matcher.sub('\\1\\\\\\2', text) text = md_plus_matcher.sub('\\1\\\\\\2', text) text = md_dash_matcher.sub('\\1\\\\\\2', text) ...
def run(args): locale.setlocale(locale.LC_ALL, '') QtWidgets.QApplication.setAttribute(QtCore.Qt.ApplicationAttribute.AA_EnableHighDpiScaling, True) is_preview = args.preview start_logger(args.local_data, is_preview) app = QtWidgets.QApplication(sys.argv) app.applicationStateChanged.connect(_on_...
class Test_pep440_post(unittest.TestCase, Testing_renderer_case_mixin): style = 'pep440-post' expected = {'tagged_0_commits_clean': 'v1.2.3', 'tagged_0_commits_dirty': 'v1.2.3.post0.dev0+g', 'tagged_1_commits_clean': 'v1.2.3.post1+gabc', 'tagged_1_commits_dirty': 'v1.2.3.post1.dev0+gabc', 'untagged_0_commits_cl...
class ResizeLongest(nn.Module): def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fill=0): super().__init__() if (not isinstance(max_size, int)): raise TypeError(f'Size should be int. Got {type(max_size)}') self.max_size = max_size self.interpolation =...
.parametrize('suffix', ['inline', 'display']) def test_dark_mode_mathml(webengine_versions, quteproc_new, request, qtbot, suffix): if (not request.config.webengine): pytest.skip('Skipped with QtWebKit') args = (_base_args(request.config) + ['--temp-basedir', '-s', 'colors.webpage.darkmode.enabled', 'tru...
class TestUserDetails(BaseActionTest): def test_user_details(self): self.strategy.set_settings({}) details = {'first_name': 'Test'} user = User(username='foobar') backend = None user_details(self.strategy, details, backend, user) self.assertEqual(user.first_name, 'Tes...
class Hg(Vcs): HEAD = 'tip' _status_translations = (('AR', 'staged'), ('M', 'changed'), ('!', 'deleted'), ('?', 'untracked'), ('I', 'ignored')) def _log(self, refspec=None, maxres=None, filelist=None): args = ['log', '--template', 'json'] if refspec: args += ['--limit', '1', '--r...
class UdemyLectureStream(Downloader): def __init__(self, parent): self._mediatype = None self._quality = None self._resolution = None self._dimension = None self._extension = None self._url = None self._parent = parent self._filename = None sel...
_module() class AudioFeatureDataset(BaseDataset): def __init__(self, ann_file, pipeline, suffix='.npy', **kwargs): self.suffix = suffix super().__init__(ann_file, pipeline, modality='Audio', **kwargs) def load_annotations(self): if self.ann_file.endswith('.json'): return self...
.parametrize('cfg_file', ['configs/ner/bert_softmax/bert_softmax_cluener_18e.py']) def test_bert_softmax(cfg_file): texts = ([''] * 47) img = ([31] * 47) labels = ([31] * 128) input_ids = ([0] * 128) attention_mask = ([0] * 128) token_type_ids = ([0] * 128) img_metas = {'texts': texts, 'labe...
class SharedGDict(GDict): def __init__(self, gdict=None, shape=None, dtype=None, name=None): if (gdict is not None): assert ((shape is None) and (dtype is None) and (name is None)) assert (isinstance(gdict, GDict) and gdict.is_np_all) shape = gdict.shape.memory ...
class ResNetBackbone(Backbone): def __init__(self, backbone): super(ResNetBackbone, self).__init__(backbone) self.custom_objects.update(keras_resnet.custom_objects) def retinanet(self, *args, **kwargs): return resnet_retinanet(*args, backbone=self.backbone, **kwargs) def download_ima...
def test_non_async_context(): () def async_fn_with_yield(should_yield): with Ctx(): if should_yield: ret = (yield ExternalCacheBatchItem(mc._batch, 'get', 'test')) else: ret = 0 return ret () def batch(should_yield=True): (r...
class Networks(nn.Module): def __init__(self, cfgs, num_classes, samples_per_cls=None): super(Networks, self).__init__() self.num_classes = num_classes self.samples_per_cls = samples_per_cls self.backbone_with_fc = (cfgs.classifier is None) self.backbone = self.build_backbone...
class ResidualBaseDecoder(nn.Module): def __init__(self, channel, groups): super().__init__() self._net = nn.Sequential(ResidualBlock(channel, channel, groups=groups), ResidualBlockShuffle(channel, channel, 2, groups=groups), AttentionBlock(channel, groups=groups), ResidualBlock(channel, channel, gr...
_config def test_only_wm_protocols_focus(xmanager, conn): w = None def only_wm_protocols_focus(): nonlocal w w = conn.create_window(5, 5, 10, 10) w.set_attribute(eventmask=xcffib.xproto.EventMask.FocusChange) w.set_property('WM_CLASS', 'float', type='STRING', format=8) hi...
class Solution(object): def minIncrementForUnique(self, A): if ((A is None) or (len(A) == 0)): return 0 res = 0 num_set = set() duplicate = [] A.sort() (left, right) = (A[0], A[(- 1)]) holes = ((right - left) + 1) for v in A: if...
class ExportComplianceException(Exception): def __init__(self, sso_username, email, quay_username): self.sso_username = sso_username self.email = email self.quay_username = quay_username def __str__(self): return f'{self.sso_username}: {self.email} : {self.quay_username}'
class ImmutableStringStrategy(StringStrategy): def as_charlist_ascii(self, w_str): return list(self.as_str_ascii(w_str)) def as_charlist_utf8(self, w_str): return list(self.as_str_utf8(w_str)) def as_unicharlist(self, w_str): return list(self.as_unicode(w_str)) def setitem(self, ...
class ContextMenuUnconditional(ContextMenu, metaclass=ABCMeta): def display(self, callingWindow, context): raise NotImplementedError def getBitmap(self, callingWindow, context): return def getText(self, callingWindow, context): raise NotImplementedError def getSubMenu(self, calli...
def test_log_filter(): rules = {'': 'INFO'} filter_ = LogFilter(rules, default_level='INFO') assert (filter_.should_log('test', 'DEBUG') is False) assert (filter_.should_log('test', 'INFO') is True) assert (filter_.should_log('raiden', 'DEBUG') is False) assert (filter_.should_log('raiden', 'INF...
def _apodize(input, ndim, oversamp, width, beta): output = input for a in range((- ndim), 0): i = output.shape[a] os_i = ceil((oversamp * i)) idx = np.arange(i, dtype=output.dtype) apod = (((beta ** 2) - ((((np.pi * width) * (idx - (i // 2))) / os_i) ** 2)) ** 0.5) apod /...
.parametrize('add_version_condition', [True, False]) def test_delete(add_version_condition: bool) -> None: item = UserModel('foo', 'bar') with patch(PATCH_METHOD) as req: req.return_value = None item.delete(add_version_condition=add_version_condition) expected = {'Key': {'user_id': {'S':...
def Mine_Pattern(FP, ItemS): global CanNum ExpSet = [] temp = FP[:] for pre in temp: for suf in temp: pattern = [pre, suf] CanNum += 1 (count, ItemS[str(pattern)]) = ProMatching(ItemS[str(pre)], suf) if (count >= int(minsup)): FP.ap...
def test_arm(): local = True funcaddr = 0 varaddr = 1048576 stackaddr = 2097152 if local: r2p = r2pipe.open('ipa://test/tests/crackme-level0-symbols.ipa', flags=['-2']) r2p.cmd('s sym._validate; aei; aeim; aer x0 = 0x100000;') funcaddr = int(r2p.cmd('s'), 16) else: ...
.parametrize('report_option', ['term-missing:skip-covered', 'term:skip-covered']) def test_skip_covered_cli(pytester, testdir, report_option): testdir.makefile('', coveragerc=SKIP_COVERED_COVERAGERC) script = testdir.makepyfile(SKIP_COVERED_TEST) result = testdir.runpytest('-v', f'--cov={script.dirpath()}',...
def test_life_list__converters(): life_list = LifeList.from_json(j_life_list_1) assert (life_list.data[0] == life_list[0]) assert (len(life_list) == 10) assert (life_list.count_without_taxon == 4) assert (isinstance(life_list.data[0], TaxonCount) and (life_list.data[0].id == 48460)) life_list = ...
def output_cut(s_partition: List[cirq.Qid]) -> None: coloring = [] for node in working_graph: if (node in s_partition): coloring.append('blue') else: coloring.append('red') edges = working_graph.edges(data=True) weights = [w['weight'] for (u, v, w) in edges] n...
.functions def test_add_column_iterator_repeat(dataframe): df = dataframe.add_column('city_pop', range(3), fill_remaining=True) assert (df.city_pop.iloc[0] == 0) assert (df.city_pop.iloc[1] == 1) assert (df.city_pop.iloc[2] == 2) assert (df.city_pop.iloc[3] == 0) assert (df.city_pop.iloc[4] == 1...
class Register(): def __init__(self) -> None: self._generators = {} self._on_packet = ({}, {}, {}, {}) self._on_server_start = {} self._on_server_stop = {} def add_world_generator(self, name: str): def deco(cls): if (not issubclass(cls, AbstractWorldGenerator)...
def transform_ptt_post_to_spacy(post: ptt.PttPost, nlp: Language, disable: Iterable[str]=['tok2vec']) -> spacy.SpacyPttPost: title_bytes = nlp(post.title, disable=disable).to_bytes() content_bytes = nlp(post.content, disable=disable).to_bytes() comments = [] for comment in post.comments: comment...
def test_thread_cache_basics() -> None: q: Queue[Outcome[object]] = Queue() def fn() -> NoReturn: raise RuntimeError('hi') def deliver(outcome: Outcome[object]) -> None: q.put(outcome) start_thread_soon(fn, deliver) outcome = q.get() with pytest.raises(RuntimeError, match='hi'): ...
def test__vf_ground_sky_2d(test_system_fixed_tilt): (ts, pts, vfs_gnd_sky) = test_system_fixed_tilt vfs = utils.vf_ground_sky_2d(ts['rotation'], ts['gcr'], pts, ts['pitch'], ts['height'], max_rows=1) assert np.allclose(vfs, vfs_gnd_sky, rtol=0.1) vf = utils.vf_ground_sky_2d(ts['rotation'], ts['gcr'], pt...
class VhdlLexer(RegexLexer): name = 'vhdl' aliases = ['vhdl'] filenames = ['*.vhdl', '*.vhd'] mimetypes = ['text/x-vhdl'] url = ' version_added = '1.5' flags = (re.MULTILINE | re.IGNORECASE) tokens = {'root': [('\\s+', Whitespace), ('(\\\\)(\\n)', bygroups(String.Escape, Whitespace)), ('...
def parse_location(file_desc): file_desc = os.fsencode(file_desc) file_parts = [x for x in re.split(b'(?<!\\\\)(\\\\{2})*::', file_desc) if (x is not None)] concat_parts = [] keep = None for part in reversed(file_parts): if re.match(b'^(\\\\{2})+$', part): keep = part els...
def test_internal_error_with_maxfail(pytester: pytest.Pytester) -> None: pytester.makepyfile("\n import pytest\n\n (params=['1', '2'])\n def crasher():\n raise RuntimeError\n\n def test_aaa0(crasher):\n pass\n def test_aaa1(crasher):\n pass\n ")...
def lr_schedule(lrnrate, epoch, warmupperiod=5, schedule=[100, 150, 200], max_epoch=250): if (schedule is None): schedule = [(max_epoch // 2.667), (max_epoch // 1.6), (max_epoch // 1.142)] warmupfactor = min(1, ((epoch + 1) / (1e-06 + warmupperiod))) if (epoch < schedule[0]): return ((1.0 * ...
def time_serie(ts_code: int, start: str, end: str, strict: bool=False) -> pd.Series: if strict: ts_data = api.get_data_with_strict_range(ts_code, start, end) else: ts_data = api.get_data(ts_code, start, end) values = [] index = [] for i in ts_data: values.append(i['valor']) ...
class StatsReporter(threading.Thread): def __init__(self, report_interval: int): super().__init__() self.report_interval = report_interval self.stop = threading.Event() self.stats_queue = SimpleQueue() def run(self): while (not self.stop.wait(self.report_interval)): ...
class ResizeObservation(gym.ObservationWrapper): def __init__(self, env, shape): super().__init__(env) if isinstance(shape, int): self.shape = (shape, shape) else: self.shape = tuple(shape) obs_shape = (self.shape + self.observation_space.shape[2:]) se...
class BaseResourceDetailsPopup(QDialog, Ui_TrickDetailsPopup): def __init__(self, parent: QWidget, window_manager: WindowManager, game_description: GameDescription, areas_to_show: list[tuple[(Region, Area, list[str])]], trick_levels: (TrickLevelConfiguration | None)=None): super().__init__(parent) s...
def _set_adlr_autoresume(args): global _GLOBAL_ADLR_AUTORESUME _ensure_var_is_not_initialized(_GLOBAL_ADLR_AUTORESUME, 'adlr autoresume') if args.adlr_autoresume: if (args.rank == 0): print('enabling autoresume ...', flush=True) sys.path.append(os.environ.get('SUBMIT_SCRIPTS', '....
class TestDataPipeFSSpec(expecttest.TestCase): def setUp(self): self.temp_dir = create_temp_dir() self.temp_files = create_temp_files(self.temp_dir) self.temp_sub_dir = create_temp_dir(self.temp_dir.name) self.temp_sub_files = create_temp_files(self.temp_sub_dir, 4, False) se...
def bbox2d(bboxA, bboxB): minx_overlap = max(bboxA[0], bboxB[0]) miny_overlap = max(bboxA[1], bboxB[1]) maxx_overlap = min(bboxA[2], bboxB[2]) maxy_overlap = min(bboxA[3], bboxB[3]) interArea = (max(0, (maxx_overlap - minx_overlap)) * max(0, (maxy_overlap - miny_overlap))) boxAArea = ((bboxA[2] ...
class StoryCategory(NameSlugModel): class Meta(): ordering = ('name',) verbose_name = 'story category' verbose_name_plural = 'story categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('success_story_list_category', kwargs={'slug'...
class _WrappedModel(): def __init__(self, model, timestep_map, original_num_steps): self.model = model self.timestep_map = timestep_map self.original_num_steps = original_num_steps def __call__(self, x, ts, **kwargs): map_tensor = th.tensor(self.timestep_map, device=ts.device, dt...
def test_multi_mass_spring_damper(): (k0, m0, g, c0) = sm.symbols('k0, m0, g, c0') (x0, v0, f0) = me.dynamicsymbols('x0, v0, f0') sys = multi_mass_spring_damper() assert (sys.constants_symbols == {k0, c0, m0}) assert (sys.specifieds_symbols == set()) assert (sys.coordinates == [x0]) assert (...
class FileUploader(Container): _attribute_decorator('WidgetSpecific', 'If True multiple files can be \n selected at the same time', bool, {}) def multiple_selection_allowed(self): return ('multiple' in self.__dict__.keys()) _selection_allowed.setter def multiple_selection_allowed(self, va...
def _construct_prop_item(key: str, value: ast.expr) -> tuple[(str, ast.expr)]: if ((key == 'style') and isinstance(value, (ast.Dict, ast.Call))): new_value = copy(value) if _rewrite_props(new_value, (lambda k, v: ((k, v) if (k == 'style') else _construct_prop_item(k, v)))): value = new_v...
def add_attribute_to_class(api: SemanticAnalyzerPluginInterface, cls: ClassDef, name: str, typ: Type, final: bool=False, no_serialize: bool=False, override_allow_incompatible: bool=False, fullname: (str | None)=None, is_classvar: bool=False, overwrite_existing: bool=False) -> Var: info = cls.info if ((name in i...
def create_dataloader(dataset_classname, dataset_config, batch_size=1, collate_fn=None, shuffle=False, num_workers=0, drop_last=False) -> DataLoader: dataset = dataset_class_dict[dataset_classname](**dataset_config) dataloader = DataLoader(dataset, batch_size=batch_size, collate_fn=collate_fn, shuffle=shuffle, ...
def configure_converter(converter: BaseConverter): converter.register_structure_hook(bytes, (lambda v, _: b85decode(v))) converter.register_unstructure_hook(bytes, (lambda v: (b85encode(v) if v else b'').decode('utf8'))) def gen_unstructure_mapping(cl: Any, unstructure_to=None): key_handler = str ...
def test_slice_penumbra(): profiler = Profile().from_tuples(PROFILER).resample_x(0.1) (lt_penum, rt_penum) = profiler.slice_penumbra() assert np.all((lt_penum.x < 0)) assert np.all((rt_penum.x > 0)) assert np.all((lt_penum.y < profiler.get_y(0))) assert np.all((rt_penum.y < profiler.get_y(0)))
class XLMTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, merges_fi...
def addScriptCode(hf, testruns): t0 = (testruns[0].start * 1000) tMax = (testruns[(- 1)].end * 1000) detail = '\tvar devtable = [];\n' for data in testruns: topo = data.deviceTopology() detail += ('\tdevtable[%d] = "%s";\n' % (data.testnumber, topo)) detail += ('\tvar bounds = [%f,%f...
class PrepDetails(MWSDataType): AMAZON = 'AMAZON' SELLER = 'SELLER' def __init__(self, prep_instruction: Union[(PrepInstruction, str)], prep_owner: str=SELLER): self.prep_instruction = prep_instruction self.prep_owner = prep_owner def params_dict(self) -> dict: return {'PrepInstr...
class Effect5871(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Operation')), 'shieldBonus', ship.getModifiedItemAttr('shipBonusMI2'), skill='Minmatar Hauler', **kwargs)
class VIIRSSurfaceReflectanceWithVIHandler(VIIRSJRRFileHandler): def __init__(self, *args, filter_veg: bool=True, **kwargs) -> None: super().__init__(*args, **kwargs) self._filter_veg = filter_veg def _mask_invalid(self, data_arr: xr.DataArray, ds_info: dict) -> xr.DataArray: new_data_ar...
class SAFEMSIMDXML(SAFEMSIXMLMetadata): def calibrate_to_reflectances(self, data, band_name): quantification = int(self.root.find('.//QUANTIFICATION_VALUE').text) data = self._sanitize_data(data) return (((data + self.band_offset(band_name)) / quantification) * 100) def _sanitize_data(se...
def _get_expr(s: str) -> Tuple[(str, str)]: level: int = 0 for (i, c) in enumerate(s): if (c in ['(', '{']): level += 1 elif ((level > 0) and (c in [')', '}'])): level -= 1 elif ((level == 0) and (c in [')', '}', ','])): break return (s[0:i], s[i:]...
_destruct_output_when_exp('content') def put_scope(name: str, content: Union[(Output, List[Output])]=[], scope: str=None, position: int=OutputPosition.BOTTOM) -> Output: if (not isinstance(content, list)): content = [content] check_dom_name_value(name, 'scope name') dom_id = scope2dom(name, no_css_s...
class CostRegNet(nn.Module): def __init__(self): super(CostRegNet, self).__init__() self.conv0 = ConvBnReLU3D(32, 8) self.conv1 = ConvBnReLU3D(8, 16, stride=2) self.conv2 = ConvBnReLU3D(16, 16) self.conv3 = ConvBnReLU3D(16, 32, stride=2) self.conv4 = ConvBnReLU3D(32, ...
class Player(): def __init__(self, playerid: int): self.id: int = playerid def set_spawn_info(self, team: int, skin: int, x: float, y: float, z: float, rotation: float, weapon1: int, weapon1_ammo: int, weapon2: int, weapon2_ammo: int, weapon3: int, weapon3_ammo: int) -> bool: return set_spawn_in...
def muti_loss_fusion_kl(preds, target, dfs, fs, mode='MSE'): loss0 = 0.0 loss = 0.0 for i in range(0, len(preds)): if ((preds[i].shape[2] != target.shape[2]) or (preds[i].shape[3] != target.shape[3])): tmp_target = F.interpolate(target, size=preds[i].size()[2:], mode='bilinear', align_co...
class Scenario(ScenarioGenerator): def __init__(self): super().__init__() self.open_scenario_version = 2 def scenario(self, **kwargs): catalog = xosc.Catalog() catalog.add_catalog('VehicleCatalog', '../xosc/Catalogs/Vehicles') road = xosc.RoadNetwork(roadfile='../xodr/str...
class ResourceDatabaseItemModel(ResourceDatabaseGenericModel): def __init__(self, db: ResourceDatabase): super().__init__(db, ResourceType.ITEM) def all_columns(self): return ITEM_FIELDS def _create_item(self, short_name) -> ItemResourceInfo: return ItemResourceInfo(self.db.first_unu...
def _synchronize_async_fixture(fixturedef: FixtureDef, event_loop_fixture_id: str) -> None: if inspect.isasyncgenfunction(fixturedef.func): _wrap_asyncgen_fixture(fixturedef, event_loop_fixture_id) elif inspect.iscoroutinefunction(fixturedef.func): _wrap_async_fixture(fixturedef, event_loop_fixt...
_required _exempt _ def unmark_comment_as_spam(request, conference_slug, proposal_slug, proposal_comment_id): if ((not request.is_ajax()) or (request.user.is_active is False)): return HttpResponseForbidden() conference = get_object_or_404(Conference, slug=conference_slug) proposal = get_object_or_40...
def test_chunk_boundaries() -> None: conn = Connection(our_role=SERVER) request = b'POST / HTTP/1.1\r\nHost: example.com\r\nTransfer-Encoding: chunked\r\n\r\n' conn.receive_data(request) assert (conn.next_event() == Request(method='POST', target='/', headers=[('Host', 'example.com'), ('Transfer-Encoding...
def to_custom_tensor(original: Union[(List, Tuple)], torch_tensors: List[torch.Tensor]) -> List: outputs = [] for (orig, torch_tensor) in zip(original, torch_tensors): tensor = torch_tensor if isinstance(orig, spconv.SparseConvTensor): tensor = orig.replace_feature(torch_tensor) ...
def main(): scene = SceneManager.AddScene('Scene') scene.mainCamera.transform.localPosition = Vector3(0, 0, (- 10)) cube = GameObject('Cube') texture = Texture2D(resolver.getPath('examples/example8/logo.png')) renderer = cube.AddComponent(MeshRenderer) renderer.mesh = Mesh.cube(2) renderer.m...
def resume_from_checkpoint(fdir, model, optimizer=None, scheduler=None): start_epoch = 0 checkpoint_file = osp.join(fdir, 'checkpoint') if (not osp.exists(checkpoint_file)): with open(checkpoint_file, 'w') as f: pass return start_epoch with open(checkpoint_file, 'r') as check...
class RVsAssignmentStepsTester(): def continuous_steps(self, step, step_kwargs): with pm.Model() as m: c1 = pm.HalfNormal('c1') c2 = pm.HalfNormal('c2') with pytensor.config.change_flags(mode=fast_unstable_sampling_mode): assert ([m.rvs_to_values[c1]] == s...
class DictAction(Action): def _parse_int_float_bool(val): try: return int(val) except ValueError: pass try: return float(val) except ValueError: pass if (val.lower() in ['true', 'false']): return (True if (val.lower(...
class SponsorshipBenefitAdminForm(forms.ModelForm): class Meta(): model = SponsorshipBenefit widgets = {'year': SPONSORSHIP_YEAR_SELECT} fields = '__all__' def clean(self): cleaned_data = super().clean() standalone = cleaned_data.get('standalone') packages = clean...
class MultiDatasetSampler(Sampler): def __init__(self, cfg, dataset_dicts, sizes, seed: Optional[int]=None): self.sizes = sizes self.sample_epoch_size = cfg.MULTI_DATASET.SAMPLE_EPOCH_SIZE assert ((self.sample_epoch_size % cfg.SOLVER.IMS_PER_BATCH) == 0) print('self.epoch_size', self...