code
stringlengths
281
23.7M
def cleanup_numbered_dir(root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float) -> None: if (not root.exists()): return for path in cleanup_candidates(root, prefix, keep): try_cleanup(path, consider_lock_dead_if_created_before) for path in root.glob('garbage-*'): ...
def test_mouse_press_event_topleft_scale(view, item): view.scene.addItem(item) item.setSelected(True) event = MagicMock() event.pos.return_value = QtCore.QPointF(2, 2) event.scenePos.return_value = QtCore.QPointF((- 1), (- 1)) event.button.return_value = Qt.MouseButton.LeftButton with patch....
def check_not_deprecated(file, metadata_is={}, metadata_keys_contain=[], compare_as_close=[], current_version=None, last_compatible_version=radis.config['OLDEST_COMPATIBLE_VERSION'], engine='guess'): if (engine == 'guess'): engine = DataFileManager.guess_engine(file) manager = DataFileManager(engine) ...
def make_trident_res_layer(block, inplanes, planes, num_blocks, stride=1, trident_dilations=(1, 2, 3), style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, plugins=None, test_branch_idx=(- 1)): downsample = None if ((stride != 1) or (inplanes != (planes * block.expansion))): ...
class CiderD(): def __init__(self, n=4, sigma=6.0, df='corpus'): self._n = n self._sigma = sigma self._df = df self.cider_scorer = CiderScorer(n=self._n, df_mode=self._df) def compute_score(self, gts, res): self.cider_scorer.clear() for res_id in res: ...
class G_D(nn.Module): def __init__(self, G, D): super(G_D, self).__init__() self.G = G self.D = D def forward(self, z, gy, x=None, dy=None, train_G=False, return_G_z=False, split_D=False, return_bn=False): with torch.set_grad_enabled(train_G): G_z = self.G(z, self.G.s...
.parametrize(('use_comm', 'use_framer'), [('tcp', 'socket'), ('tcp', 'rtu'), ('tls', 'tls'), ('udp', 'socket'), ('udp', 'rtu'), ('serial', 'rtu')]) class TestClientServerAsyncExamples(): (name='use_port') def get_port_in_class(base_ports): base_ports[__class__.__name__] += 1 return base_ports[__...
def phrase_event(callbacks, parameters): phrase = parameters.strip().lower() punctuations = ',.";?!' for p in punctuations: phrase = phrase.replace(p, ' ') words = phrase.split() words = [w.strip("' ") for w in words if w.strip("' ")] to_call = [] for callback in callbacks: k...
def get_nuc_g_factor(symb_or_charge, mass=None): if isinstance(symb_or_charge, str): Z = mole.charge(symb_or_charge) else: Z = symb_or_charge if (mass is None): (nuc_spin, g_nuc) = ISOTOPE_GYRO[Z][0][1:3] else: for (isotop_mass, nuc_spin, g_nuc) in ISOTOPE_GYRO[Z]: ...
def duplicate_states_loss(player): episode_loss = torch.tensor(0) with torch.cuda.device(player.gpu_id): episode_loss = episode_loss.cuda() for i in player.duplicate_states_actions: step_optimal_action = torch.tensor(player.duplicate_states_actions[i]).reshape([1]).long() with torch....
class Decoder(nn.Module): def __init__(self, in_channels, out_channels, conv_kernel_size=3, scale_factor=2, basic_module=DoubleConv, conv_layer_order='gcr', num_groups=8, padding=1, upsample='default', dropout_prob=0.1, is3d=True): super(Decoder, self).__init__() concat = True adapt_channels...
def test_get_transparent_pixel(ntg1, ntg2, ntg3, ntg_no_fill_value): tp = ntg1.get_transparent_pixel() assert isinstance(tp, int) assert (tp == 255) assert (ntg2.get_transparent_pixel() == 0) assert (ntg3.get_transparent_pixel() == 255) assert (ntg_no_fill_value.get_transparent_pixel() == (- 1))
.parametrize('main_schema, other_schema_data, instance, expect_err', [(CASE1_MAIN_SCHEMA, {'title_schema.json': CASE1_TITLE_SCHEMA}, CASE1_FAILING_DOCUMENT, None), (CASE2_MAIN_SCHEMA, {'values.json': CASE2_VALUES_SCHEMA}, CASE2_FAILING_DOCUMENT, "{'foo': 'bar'} is not of type 'string'")]) .parametrize('with_file_scheme...
class SmallEncoder(nn.Module): def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0): super(SmallEncoder, self).__init__() self.norm_fn = norm_fn if (self.norm_fn == 'group'): self.norm1 = nn.GroupNorm(num_groups=8, num_channels=32) elif (self.norm_fn == 'batch...
def evaluate_js(window): result = window.evaluate_js("\n var h1 = document.createElement('h1')\n var text = document.createTextNode('Hello pywebview')\n h1.appendChild(text)\n document.body.appendChild(h1)\n\n document.body.style.backgroundColor = '#212121'\n document.body....
class Effect508(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Small Projectile Turret')), 'damageMultiplier', ship.getModifiedItemAttr('shipBonusMF'), skill='Minmatar Frigate', **kwargs)
def is_trivial_bound(tp: ProperType, allow_tuple: bool=False) -> bool: if (isinstance(tp, Instance) and (tp.type.fullname == 'builtins.tuple')): return (allow_tuple and is_trivial_bound(get_proper_type(tp.args[0]))) return (isinstance(tp, Instance) and (tp.type.fullname == 'builtins.object'))
class GlobalContextVitBlock(nn.Module): def __init__(self, dim: int, feat_size: Tuple[(int, int)], num_heads: int, window_size: int=7, mlp_ratio: float=4.0, use_global: bool=True, qkv_bias: bool=True, layer_scale: Optional[float]=None, proj_drop: float=0.0, attn_drop: float=0.0, drop_path: float=0.0, attn_layer: Ca...
class ObjectsBoundingBoxConditionalBuilder(ObjectsCenterPointsConditionalBuilder): def object_descriptor_length(self) -> int: return 3 def _make_object_descriptors(self, annotations: List[Annotation]) -> List[Tuple[(int, ...)]]: object_triples = [(self.object_representation(ann), *self.token_pai...
class EntropyStatCollector(diamond.collector.Collector): PROC = '/proc/sys/kernel/random/entropy_avail' def get_default_config(self): config = super(EntropyStatCollector, self).get_default_config() config.update({'path': 'entropy'}) return config def collect(self): if (not os...
def run(func, *args, backend=None, backend_options=None): if (backend is None): backend = os.getenv('PURERPC_BACKEND', 'asyncio') _log.info('purerpc.run() selected {} backend'.format(backend)) if (backend == 'uvloop'): backend = 'asyncio' options = dict(use_uvloop=True) if (b...
.parametrize('case', [CaseReducesInx3OutComp, CaseIfBasicComp, CaseIfDanglingElseInnerComp, CaseIfDanglingElseOutterComp, CaseElifBranchComp, CaseNestedIfComp, CaseForRangeLowerUpperStepPassThroughComp, CaseIfExpInForStmtComp, CaseIfExpBothImplicitComp, CaseIfBoolOpInForStmtComp, CaseIfTmpVarInForStmtComp, CaseFixedSiz...
def test_entityref(): entref = OSC.EntityRef('ref_str') entref2 = OSC.EntityRef('ref_str') entref3 = OSC.EntityRef('ref_str2') prettyprint(entref.get_element()) assert (entref == entref2) assert (entref != entref3) entref4 = OSC.EntityRef.parse(entref.get_element()) assert (entref == ent...
class TestFindWebengineResources(): def qt_data_path(self, monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path): qt_data_path = (tmp_path / 'qt_data') qt_data_path.mkdir() monkeypatch.setattr(pakjoy.qtutils, 'library_path', (lambda _which: qt_data_path)) return qt_data_path d...
class TokenizerTrainingArguments(): base_tokenizer: Optional[str] = field(default='gpt2', metadata={'help': 'Base tokenizer to build new tokenizer from.'}) dataset_name: Optional[str] = field(default='transformersbook/codeparrot-train', metadata={'help': 'Dataset to train tokenizer on.'}) text_column: Optio...
class ForumTopicEdited(TelegramObject): __slots__ = ('name', 'icon_custom_emoji_id') def __init__(self, name: Optional[str]=None, icon_custom_emoji_id: Optional[str]=None, *, api_kwargs: Optional[JSONDict]=None): super().__init__(api_kwargs=api_kwargs) self.name: Optional[str] = name sel...
class SwiGLUFFNFused(SwiGLU): def __init__(self, in_features: int, hidden_features: Optional[int]=None, out_features: Optional[int]=None, act_layer: Callable[(..., nn.Module)]=None, drop: float=0.0, bias: bool=True) -> None: out_features = (out_features or in_features) hidden_features = (hidden_feat...
class IpPool(db.Model, AuditTimeMixin): __tablename__ = 'tb_ippool' id = db.Column(db.Integer) fixed_ip = db.Column(db.String(256), primary_key=True) region = db.Column(db.String(50), nullable=False) allocated = db.Column(db.Boolean, nullable=False, default=True) is_ipv6 = db.Column(db.Boolean, ...
class PyramidFeatures(nn.Module): def __init__(self, config, img_size=224, in_channels=3): super().__init__() model_path = config.swin_pretrained_path self.swin_transformer = SwinTransformer(img_size, in_chans=3) checkpoint = torch.load(model_path, map_location=torch.device(device))[...
class CoLightAgent(Agent): def __init__(self, dic_agent_conf=None, dic_traffic_env_conf=None, dic_path=None, cnt_round=None, best_round=None, bar_round=None, intersection_id='0'): super(CoLightAgent, self).__init__(dic_agent_conf, dic_traffic_env_conf, dic_path, intersection_id) self.att_regulatizat...
class GeneralGraph(Graph, ABC): def __init__(self, nodes: List[Node]): self.nodes: List[Node] = nodes self.num_vars: int = len(nodes) node_map: Dict[(Node, int)] = {} for i in range(self.num_vars): node = nodes[i] node_map[node] = i self.node_map: Dict...
def load_pos_conv_layer(full_name, value, pos_conv_embeddings, unused_weights): name = full_name.split('pos_conv.')[(- 1)] items = name.split('.') layer_id = int(items[0]) type_id = int(items[1]) weight_type = name.split('.')[(- 1)] if (type_id != 0): unused_weights.append(full_name) ...
def infer_typing_attr(node: Subscript, ctx: (context.InferenceContext | None)=None) -> Iterator[ClassDef]: try: value = next(node.value.infer()) except (InferenceError, StopIteration) as exc: raise UseInferenceDefault from exc if ((not value.qname().startswith('typing.')) or (value.qname() i...
('PyQt6.QtWidgets.QFileDialog.getOpenFileName') def test_on_action_open(dialog_mock, view, qtbot): root = os.path.dirname(__file__) filename = os.path.join(root, 'assets', 'test1item.bee') dialog_mock.return_value = (filename, None) view.on_loading_finished = MagicMock() view.scene.cancel_crop_mode ...
def RegisterPythonwin(register=True): import os lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1) classes_root = get_root_hkey() pythonwin_exe = os.path.join(lib_dir, 'Pythonwin', 'Pythonwin.exe') pythonwin_edit_command = (pythonwin_exe + ' /edit "%1"') keys_vals = [('Software\\Micro...
def test_update_if_modified_field_changed(sqldb): cursor = sqldb.cursor() rules_db.RulesRow(RuleID=501, Name='Long Press Rule', Type=MOCK_RULE_TYPE, State=1).update_db(cursor) rules_db.RuleDevicesRow(RuleDevicePK=1, RuleID=501, DeviceID=MOCK_UDN).update_db(cursor) db = rules_db.RulesDb(sqldb, MOCK_UDN, ...
def get_act_fn(name='relu'): if (not name): return None if (not (is_no_jit() or is_exportable() or is_scriptable())): if (name in _ACT_FN_ME): return _ACT_FN_ME[name] if (is_exportable() and (name in ('silu', 'swish'))): return swish if (not (is_no_jit() or is_exporta...
class APEv2File(AudioFile): IGNORE = ['file', 'index', 'introplay', 'dummy'] TRANS = {'subtitle': 'version', 'track': 'tracknumber', 'disc': 'discnumber', 'catalog': 'labelid', 'year': 'date', 'record location': 'location', 'album artist': 'albumartist', 'debut album': 'originalalbum', 'record date': 'recording...
class Minor(nn.Module): def __init__(self, G_ch=64, dim_z=128, bottom_width=4, resolution=128, G_kernel_size=3, G_attn='64', n_classes=1000, num_G_SVs=1, num_G_SV_itrs=1, G_shared=True, shared_dim=0, hier=False, cross_replica=False, mybn=False, G_activation=nn.ReLU(inplace=False), G_lr=5e-05, G_B1=0.0, G_B2=0.999, ...
class Source(object): def __init__(self, s): self.pos = 0 self.s = s self.ignore_space = False def at_end(self): s = self.s pos = self.pos if self.ignore_space: while True: if (pos >= len(s)): break e...
def sanity_check_dependencies(): import numpy import requests import six if (distutils.version.LooseVersion(numpy.__version__) < distutils.version.LooseVersion('1.10.4')): logger.warn("You have 'numpy' version %s installed, but 'gym' requires at least 1.10.4. HINT: upgrade via 'pip install -U nu...
class TwoInputsModel(torch.nn.Module): def __init__(self, num_classes=3): super(TwoInputsModel, self).__init__() self.conv1 = torch.nn.Conv2d(3, 16, kernel_size=2, stride=2, padding=2, bias=False) self.bn1 = torch.nn.BatchNorm2d(16) self.conv2 = torch.nn.Conv2d(3, 8, kernel_size=3, s...
def test_importorskip_dev_module(monkeypatch) -> None: try: mod = types.ModuleType('mockmodule') mod.__version__ = '0.13.0.dev-43290' monkeypatch.setitem(sys.modules, 'mockmodule', mod) mod2 = pytest.importorskip('mockmodule', minversion='0.12.0') assert (mod2 == mod) ...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) ...
class LSTM(nn.Module): def __init__(self, word_embedding_dimension: int, hidden_dim: int, num_layers: int=1, dropout: float=0, bidirectional: bool=True): nn.Module.__init__(self) self.config_keys = ['word_embedding_dimension', 'hidden_dim', 'num_layers', 'dropout', 'bidirectional'] self.word...
def extract_and_save_image(dataset, save_dir, discard, label2name): if osp.exists(save_dir): print('Folder "{}" already exists'.format(save_dir)) return print('Extracting images to "{}" ...'.format(save_dir)) mkdir_if_missing(save_dir) for i in range(len(dataset)): (img, label) =...
class cvode(IntegratorBase): valid_methods = {'adams': _cvode.CV_ADAMS, 'bdf': _cvode.CV_BDF} valid_iterations = {'functional': _cvode.CV_FUNCTIONAL, 'newton': _cvode.CV_NEWTON} def __init__(self, method='adams', iteration='functional', rtol=1e-06, atol=1e-12): if (method not in cvode.valid_methods)...
def run(config): state_dict = {'itr': 0, 'epoch': 0, 'save_num': 0, 'save_best_num': 0, 'best_IS': 0, 'best_FID': 999999, 'config': config} if config['config_from_name']: utils.load_weights(None, None, state_dict, config['weights_root'], config['experiment_name'], config['load_weights'], None, strict=Fa...
def mol_data_from_csv(csv_name: str): with open(csv_name, 'r') as csv_file: mol_confs = csv.DictReader(csv_file) rows = [] for row in mol_confs: row = dict(row) row['smiles'] = (row['smiles'] if row['smiles'] else None) row['multiplicity'] = (int(float(row...
class LiltConfig(PretrainedConfig): model_type = 'lilt' def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initia...
def test_push_pull_manifest_list_duplicate_manifest(v22_protocol, basic_images, liveserver_session, app_reloader, data_model): credentials = ('devtable', 'password') options = ProtocolOptions() blobs = {} manifest = v22_protocol.build_schema2(basic_images, blobs, options) builder = DockerSchema2Mani...
() def no_qt(monkeypatch): need_reload = False if _check_qt_installed(): need_reload = True monkeypatch.setenv('QT_API', 'bad_name') sys.modules.pop('qtpy') importlib.reload(pyvistaqt) assert ('qtpy' not in sys.modules) (yield) monkeypatch.undo() if need_reloa...
def analyze_enum_class_attribute_access(itype: Instance, name: str, mx: MemberContext) -> (Type | None): if (name in ENUM_REMOVED_PROPS): return report_missing_attribute(mx.original_type, itype, name, mx) if (name.startswith('__') and name.endswith('__') and (name.replace('_', '') != '')): retur...
class SemanticAnalyzerPluginInterface(): modules: dict[(str, MypyFile)] options: Options cur_mod_id: str msg: MessageBuilder def named_type(self, fullname: str, args: (list[Type] | None)=None) -> Instance: raise NotImplementedError def builtin_type(self, fully_qualified_name: str) -> Ins...
class Event(object): def __init__(self, console, input): pass def __repr__(self): if (self.type in ['KeyPress', 'KeyRelease']): s = ("%s char='%s'%d keysym='%s' keycode=%d:%x state=%x keyinfo=%s" % (self.type, self.char, ord(self.char), self.keysym, self.keycode, self.keycode, self.s...
def _parse_pmt(payload): table_id = payload[0] if (table_id != _TABLE_PMT): return None length = (((payload[1] & 15) << 8) | payload[2]) data = payload[8:(3 + length)] data = data[:(- 4)] meta_length = (((data[2] & 15) << 8) | data[3]) stream = data[(4 + meta_length):] while stre...
def read_freq_cpu(path, type_freq): freq = {} with open('{path}/cpufreq/{type_freq}_min_freq'.format(path=path, type_freq=type_freq), 'r') as f: freq['min'] = int(f.read()) with open('{path}/cpufreq/{type_freq}_max_freq'.format(path=path, type_freq=type_freq), 'r') as f: freq['max'] = int(f....
def get_help(cmd: Optional[str]) -> str: base = ['pipx'] args = ((base + ([cmd] if cmd else [])) + ['--help']) env_patch = os.environ.copy() env_patch['PATH'] = os.pathsep.join(([str(Path(sys.executable).parent)] + env_patch['PATH'].split(os.pathsep))) content = check_output(args, text=True, env=env...
class SwitchMetric(Metric): def __init__(self, args: Namespace, mode='all'): super(SwitchMetric, self).__init__(args) self.args = args self.mode = mode self.amax = args.padding_size self.use_lm = args.use_lm def __call__(self, gts: list, preds: list, mask: list) -> dict: ...
def rand_throw(): vp = np.random.uniform(low=0, high=360) goal = np.array([np.random.uniform(low=(- 0.3), high=0.3), np.random.uniform(low=(- 0.3), high=0.3)]) return dict(vp=vp, imsize=(64, 64), name='throw', goal=goal.tolist(), modelname='model/model_70000_3007.74_2728.77_268.42', modeldata='model/vdata_t...
class LidResults(Enum): inflow = 0 evap = 1 infil = 2 surfFlow = 3 drainFlow = 4 initVol = 5 finalVol = 6 surfDepth = 7 paveDepth = 8 soilMoist = 9 storDepth = 10 dryTime = 11 oldDrainFlow = 12 newDrainFlow = 13 pervArea = 14 flowToPerv = 15 evapRate =...
class SawyerDisassembleV1Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'wrench_pos': obs[3:6], 'peg_pos': obs[9:], 'unused_info': obs[6:9]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort...
def locate_cuda(): if ('CUDA_PATH' in os.environ): home = os.environ['CUDA_PATH'] print(('home = %s\n' % home)) nvcc = pjoin(home, 'bin', nvcc_bin) else: default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin') nvcc = find_in_path(nvcc_bin, ((os.environ['PATH'] + os.pa...
def pytest_addoption(parser: Parser) -> None: parser.addini('doctest_optionflags', 'Option flags for doctests', type='args', default=['ELLIPSIS']) parser.addini('doctest_encoding', 'Encoding used for doctest files', default='utf-8') group = parser.getgroup('collect') group.addoption('--doctest-modules',...
('pypyr.moduleloader.get_module') (Step, 'invoke_step') def test_run_pipeline_steps_with_retries(mock_invoke_step, mock_get_module): step = Step({'name': 'step1', 'retry': {'max': 0}}) context = get_test_context() original_len = len(context) mock_invoke_step.side_effect = [ValueError('arb'), None] w...
class BaseDB(DatabaseAPI): def set(self, key: bytes, value: bytes) -> None: self[key] = value def exists(self, key: bytes) -> bool: return self.__contains__(key) def __contains__(self, key: bytes) -> bool: if hasattr(self, '_exists'): return self._exists(key) else...
class JSONOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, 'wt') def writekvs(self, kvs): for (k, v) in sorted(kvs.items()): if hasattr(v, 'dtype'): kvs[k] = float(v) self.file.write((json.dumps(kvs) + '\n')) self.file.f...
(params=[lazy_fixture('example_git_ssh_url')]) def git_repo_factory(request, example_project): def git_repo(): repo = Repo.init(example_project.resolve()) repo.git.branch('-M', 'main') with repo.config_writer('repository') as config: config.set_value('user', 'name', 'semantic rel...
class TestToyDictionary(): XML_PATH = os.path.join(os.path.dirname(__file__), '..', 'dev_data', 'toy_dict.xml') def test_parse_xml(self): dct = parse_opencorpora_xml(self.XML_PATH) assert (dct.version == '0.92') assert (dct.revision == '389440') assert (dct.links[0] == ('5', '6',...
def merge_two_slices(fgraph, slice1, len1, slice2, len2): if (not isinstance(slice1, slice)): raise ValueError('slice1 should be of type `slice`') (sl1, reverse1) = get_canonical_form_slice(slice1, len1) (sl2, reverse2) = get_canonical_form_slice(slice2, len2) if (not isinstance(sl2, slice)): ...
class ChainChoiceType(click.Choice): def convert(self, value, param, ctx): if isinstance(value, int): return value elif (isinstance(value, str) and value.isnumeric()): try: return int(value) except ValueError: self.fail(f'invalid nu...
class DevDataset(Dataset): def __init__(self, args, raw_datasets, cache_root): self.raw_datasets = raw_datasets cache_path = os.path.join(cache_root, 'tab_fact_dev.cache') if (os.path.exists(cache_path) and args.dataset.use_cache): self.extended_data = torch.load(cache_path) ...
def asin_list_from_csv(mf): if os.path.isfile(mf): with open(mf) as f: csvread = csv.reader(f, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL) asinlist = [] filelist = [] for row in csvread: try: if (row[0] != '* NONE *...
class SponsorshipPackageManagerTests(TestCase): def test_filter_packages_by_current_year(self): current_year = SponsorshipCurrentYear.get_year() active_package = baker.make(SponsorshipPackage, year=current_year) baker.make(SponsorshipPackage, year=(current_year - 1)) qs = Sponsorship...
class MaxLengthCriteria(StoppingCriteria): def __init__(self, max_length: int): self.max_length = max_length _start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING) def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: return (input_ids.shape[(- 1)] >= s...
def get_dist_run_id(cfg, num_nodes): init_method = cfg.DISTRIBUTED.INIT_METHOD run_id = cfg.DISTRIBUTED.RUN_ID if ((init_method == 'tcp') and (cfg.DISTRIBUTED.RUN_ID == 'auto')): assert (num_nodes == 1), 'cfg.DISTRIBUTED.RUN_ID=auto is allowed for 1 machine only.' port = find_free_tcp_port()...
class DirectPalette(AbstractPalette): registry = BLOCK_STATES def get_bits_per_block(): return math.ceil(math.log2(sum((len(b['states']) for b in BLOCK_STATES.data.values())))) def encode(block: str, props: dict=None) -> int: props = ({} if (props is None) else props) block_data = BL...
def get_cache_dir() -> Path: if ((os.name == 'posix') and (sys.platform != 'darwin')): xdg = (os.environ.get('XDG_CACHE_HOME', None) or os.path.expanduser('~/.cache')) return Path(xdg, 'flit') elif (sys.platform == 'darwin'): return Path(os.path.expanduser('~'), 'Library/Caches/flit') ...
def anonymise_cli(args): if args.delete_unknown_tags: handle_unknown_tags = True elif args.ignore_unknown_tags: handle_unknown_tags = False else: handle_unknown_tags = None if (not args.keywords_to_leave_unchanged): keywords_to_leave_unchanged = () else: keywo...
def _split_text(asr, audio, speech2text): if (len(asr) < 2): return [(0, len(audio), asr)] try: timings = _get_timings(asr, audio, speech2text) except Exception: return [(0, len(audio), asr)] threshold = np.percentile((timings[1:] - timings[:(- 1)]), 98, interpolation='nearest') ...
def _show_fixtures_per_test(config: Config, session: Session) -> None: import _pytest.config session.perform_collect() curdir = Path.cwd() tw = _pytest.config.create_terminal_writer(config) verbose = config.getvalue('verbose') def get_best_relpath(func) -> str: loc = getlocation(func, st...
.parametrize('vectorize', [True, False]) def test_vf_ground_sky_2d_integ(test_system_fixed_tilt, vectorize): (ts, pts, vfs_gnd_sky) = test_system_fixed_tilt vf_integ = utils.vf_ground_sky_2d_integ(ts['rotation'], ts['gcr'], ts['height'], ts['pitch'], max_rows=1, npoints=3, vectorize=vectorize) expected_vf_i...
class ResourceCache(): def __init__(self) -> None: self._cache: t.Dict[(str, referencing.Resource[Schema])] = {} def __setitem__(self, uri: str, data: t.Any) -> referencing.Resource[Schema]: resource = referencing.Resource.from_contents(data, default_specification=DRAFT202012) self._cach...
class QueryBuilder(object): def __init__(self): self._query = [] self.current_field = None self.c_oper = None self.l_oper = None def field(self, field): self.current_field = field return self def order_descending(self): self._query.append('ORDERBYDESC{...
def assert_device_map(device_map, num_blocks): blocks = list(range(0, num_blocks)) device_map_blocks = [item for sublist in list(device_map.values()) for item in sublist] duplicate_blocks = [] for i in device_map_blocks: if ((device_map_blocks.count(i) > 1) and (i not in duplicate_blocks)): ...
def gcs_test_credential() -> Generator[(None, None, None)]: if ('GOOGLE_APPLICATION_CREDENTIALS' in os.environ): (yield) return if ('GOOGLE_APPLICATION_CREDENTIALS_JSON' in os.environ): with tempfile.NamedTemporaryFile('w') as f: f.write(os.environ['GOOGLE_APPLICATION_CREDENT...
def init_params(opt, ClothWarper, data_loader): iter_path = os.path.join(opt.checkpoints_dir, opt.name, 'iter.txt') (start_epoch, epoch_iter) = (1, 0) if opt.continue_train: if os.path.exists(iter_path): (start_epoch, epoch_iter) = np.loadtxt(iter_path, delimiter=',', dtype=int) ...
def _decode(data): code = '' for c in data: if (c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']): code += c elif (c not in [' ', '\n']): raise rse.BadParameter(("Cannot decode '%s' in '%s'" % (c, data))) return bytes.fromhex(code)...
class StubAttr(StubBase): def __init__(self, obj, attr_name): self.__dict__['_obj'] = obj self.__dict__['_attr_name'] = attr_name def obj(self): return self.__dict__['_obj'] def attr_name(self): return self.__dict__['_attr_name'] def __str__(self): return ('StubAt...
def get_tweets(): result = [] news_sources = AutoImportResource.objects.filter(type_res='twitter').exclude(in_edit=True).exclude(is_active=False) for source in news_sources: print('Process twitter', source) try: result.extend(_parse_tweets_data(get_tweets_by_url(source.link), sou...
class FileItem(BrowserItem): def __init__(self, parent, pathProxy, mode='normal'): BrowserItem.__init__(self, parent, pathProxy) self._mode = mode self._timeSinceLastDocString = 0 if ((self._mode == 'normal') and self.path().lower().endswith('.py')): self._createDummyItem...
def task(reindexed_root_dir, dataset, index): image_id = dataset._ids[index] examples = dataset.get_example(index) id_to_meta = {} for (i_example, example) in enumerate(examples): instance_id = f'{image_id}/{i_example:08d}' npz_file = (reindexed_root_dir / f'{instance_id}.npz') n...
class SharedAdam(optim.Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=0.001, weight_decay=0, amsgrad=True): defaults = defaultdict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(SharedAdam, self).__init__(params, defaults) for group i...
def test_geodesic_fwd_inv_inplace(): gg = Geod(ellps='clrk66') _BOSTON_LON = numpy.array([0], dtype=numpy.float64) _BOSTON_LAT = numpy.array([0], dtype=numpy.float64) _PORTLAND_LON = numpy.array([1], dtype=numpy.float64) _PORTLAND_LAT = numpy.array([1], dtype=numpy.float64) (az12, az21, dist) = ...
class TrainRegSet(torch.utils.data.Dataset): def __init__(self, data_root, image_size): super().__init__() self.transform = transforms.Compose([transforms.Resize(image_size), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) self.imgs = torchvision.datasets.Imag...
class DiscCentroidsLoss(nn.Module): def __init__(self, num_classes, feat_dim, size_average=True): super(DiscCentroidsLoss, self).__init__() self.num_classes = num_classes self.centroids = nn.Parameter(torch.randn(num_classes, feat_dim)) self.disccentroidslossfunc = DiscCentroidsLossF...
def writegen(fnfn, generator, header=None, sep=','): import codecs of = codecs.open(fnfn, 'w', encoding='utf-8') header_written = False for dx in generator(): if (not header_written): if (not header): if ('header' in dx): header = dx['header'] ...
class IsHasAccessOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if (request.method in permissions.SAFE_METHODS): return True user = request.user is_manager = user.groups.filter(name=MANAGER_GROUP).exists() return ((user == obj...
class SecretSerializer(SerializationBase): def serialize(obj: _DecryptedSecret) -> bytes: if (not isinstance(obj, _DecryptedSecret)): raise SerializationError(f'Can only serialize {_DecryptedSecret.__name__} objects') try: schema = class_schema(_DecryptedSecret, base_schema=B...
def window_accumulator(acc, new, diff=None, window=None, agg=None, with_state=False): if (acc is None): acc = {'dfs': [], 'state': agg.initial(new)} dfs = acc['dfs'] state = acc['state'] (dfs, old) = diff(dfs, new, window=window) if (new is not None): (state, result) = agg.on_new(sta...