code
stringlengths
281
23.7M
def decode_frame(offset): try: numchannels = _numchannels sample_size = _sample_size _file.seek(offset) inp = BitInputStream(_file) temp = inp.read_byte() if (temp == (- 1)): return False sync = ((temp << 6) | inp.read_uint(6)) if (sync != ...
class MemorySnapshot(Callback): def __init__(self, *, output_dir: str, memory_snapshot_params: Optional[MemorySnapshotParams]=None) -> None: self.memory_snapshot_profiler = MemorySnapshotProfiler(output_dir=output_dir, memory_snapshot_params=memory_snapshot_params) def on_train_step_end(self, state: Sta...
class SPMTokenizer(): def __init__(self, vocab_file, split_by_punct=False, sp_model_kwargs: Optional[Dict[(str, Any)]]=None): self.split_by_punct = split_by_punct self.vocab_file = vocab_file self.sp_model_kwargs = ({} if (sp_model_kwargs is None) else sp_model_kwargs) spm = sp.Sente...
def set_parser(argv: Optional[Sequence[str]]=None) -> int: parser = argparse.ArgumentParser(description='Command line utility for pysondb', epilog=example_uses, formatter_class=argparse.RawDescriptionHelpFormatter) subparsers = parser.add_subparsers(dest='command') create_parser = subparsers.add_parser('cre...
def test_data(): assert (str(data) == "<module 'pretf.blocks.data'>") assert (str(data.null_data_source) == "<module 'pretf.blocks.data.null_data_source'>") assert (str(data.null_data_source.test) == '${data.null_data_source.test}') assert (str(data.null_data_source['test']) == '${data.null_data_source....
def get_dim_reducer(total_num_samplets, dr_name='variancethreshold', reduced_dim='all'): dr_name = dr_name.lower() if (dr_name in ['isomap']): from sklearn.manifold import Isomap dim_red = Isomap(n_components=reduced_dim) dr_param_grid = None elif (dr_name in ['lle']): from s...
class BotCommandScopeChat(BotCommandScope): def __init__(self, chat_id: Union[(int, str)]): super().__init__('chat') self.chat_id = chat_id async def write(self, client: 'pyrogram.Client') -> 'raw.base.BotCommandScope': return raw.types.BotCommandScopePeer(peer=(await client.resolve_peer...
def rotate_faces(bm, cylinder, dir, left, prop): mid = (len(cylinder) // 2) vts = sort_verts(cylinder, dir) angle = math.atan((left.z / left.xy.length)) bmesh.ops.rotate(bm, verts=vts[(- mid):], cent=calc_verts_median(vts[(- mid):]), matrix=Matrix.Rotation(angle, 4, dir.cross((- left)))) if prop.bot...
class NoiseIdentity(nn.Module): def __init__(self, noise_type=None, scheduler='cosine_anne', **kwargs): super(NoiseIdentity, self).__init__() self.noise_type = noise_type if (self.noise_type is not None): self.scheduler = scheduler self.base_lr = kwargs['base_lr'] ...
def main(args): torch.manual_seed(args.seed) if (not os.path.exists(args.res_dir)): os.mkdir(args.res_dir) if (not os.path.exists(args.model_dir)): os.mkdir(args.model_dir) log_dir = os.path.join('./log', ('Align_' + str(args.split))) if (not os.path.exists(log_dir)): os.mkdi...
def read_lm(model_path, inference_config): lm_config = Namespace(**json.load(open(str((model_path / 'lm_config.json'))))) assert (lm_config.model == 'phone_ipa'), 'only phone_ipa model is supported for allosaurus now' assert (lm_config.backend == 'numpy'), 'only numpy backend is supported for allosaurus now...
def block2(): for i in range(40): regexs[14].sub('', 'fryrpgrq', subcount[14]) regexs[15].sub('', 'fryrpgrq', subcount[15]) for i in range(39): re.sub('\\buvqqra_ryrz\\b', '', 'vachggrkg uvqqra_ryrz', 0) regexs[3].search('vachggrkg ') regexs[3].search('vachggrkg') ...
class QCSchemaInput(_QCBase): schema_name: str schema_version: int molecule: QCTopology driver: str model: QCModel keywords: Mapping[(str, Any)] def from_dict(cls, data: dict[(str, Any)]) -> QCSchemaInput: model = QCModel(**data.pop('model')) molecule = QCTopology(**data.pop(...
def read_aff_wild2(): total_data = pickle.load(open(args.aff_wild2_pkl, 'rb')) data = total_data['EXPR_Set']['Training_Set'] paths = [] labels = [] for video in data.keys(): df = data[video] labels.append(df['label'].values.astype(np.float32)) paths.append(df['path'].values) ...
class WMSBase(): def __init__(self): pass def ask_for_legend(self, wms, wmslayer): if hasattr(wms, 'add_legend'): try: img = wms.fetch_legend(silent=True) if (img is not None): self._ask_for_legend(wms, wmslayer, img) ex...
def detach_inputs(sgv, control_inputs=False): sgv = subgraph.make_view(sgv) with sgv.graph.as_default(): input_placeholders = [tf_array_ops.placeholder(dtype=input_t.dtype, name=util.placeholder_name(input_t)) for input_t in sgv.inputs] reroute.swap_inputs(sgv, input_placeholders) if control_inp...
def test_ini_controls_global_log_level(pytester: Pytester) -> None: pytester.makepyfile('\n import pytest\n import logging\n def test_log_level_override(request, caplog):\n plugin = request.config.pluginmanager.getplugin(\'logging-plugin\')\n assert plugin.log_level == log...
_constructor.register(np.ndarray) def tensor_constructor(value, name=None, strict=False, allow_downcast=None, borrow=False, shape=None, target='cpu', broadcastable=None): if isinstance(value, np.ma.MaskedArray): raise NotImplementedError('MaskedArrays are not supported') if (broadcastable is not None): ...
.parametrize(('seed_number', 'expected_ids'), [(5000, [122, 129, 1638535, 393260, 4522032, , 4260106, 2097251, 38, 589851, 2162826, 1245332, 1572998, 1245307, 3342446, 524321, 2949235, 1966093, 3538975, 152]), (9000, [2949235, 129, 152, 4522032, 4260106, 1245332, 1966093, 122, 1638535, 393260, , 589851, 1572998, 38, 20...
def run_data_migration(apps, schema_editor): Attribute = apps.get_model('domain', 'Attribute') QuestionSet = apps.get_model('questions', 'QuestionSet') questionsets = QuestionSet.objects.filter(is_collection=True) for questionset in questionsets: if (questionset.attribute.key != 'id'): ...
.end_to_end() .skipif((not IS_PEXPECT_INSTALLED), reason='pexpect is not installed.') .skipif((sys.platform == 'win32'), reason='pexpect cannot spawn on Windows.') def test_breakpoint(tmp_path): source = '\n def task_example():\n i = \n breakpoint()\n ' tmp_path.joinpath('task_module.py').wr...
class TestMPMWithPlating(TestCase): def test_well_posed_reversible_plating_not_implemented(self): options = {'lithium plating': 'reversible'} with self.assertRaises(NotImplementedError): pybamm.lithium_ion.MPM(options) def test_well_posed_irreversible_plating_not_implemented(self): ...
class _FallbackLocalTimezone(datetime.tzinfo): def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: if self._isdst(dt): return DSTOFFSET else: return STDOFFSET def dst(self, dt: datetime.datetime) -> datetime.timedelta: if self._isdst(dt): ...
class StackManipulationAPI(ABC): def stack_pop_ints(self, num_items: int) -> Tuple[(int, ...)]: ... def stack_pop_bytes(self, num_items: int) -> Tuple[(bytes, ...)]: ... def stack_pop_any(self, num_items: int) -> Tuple[(Union[(int, bytes)], ...)]: ... def stack_pop1_int(self) -> ...
def enumerate_permutations(dataset, smiles): if ('[*]' in smiles): wildcard_pat = _bracket_wildcard_pat wildcard = '[*]' elif ('*' in smiles): wildcard_pat = _organic_wildcard_pat wildcard = '*' n = smiles.count('*') if (n == 1): (yield ('1', smiles.replace(wildca...
class TestConfigurationReader(): def test_basic(self, tmpdir): (_, config) = fake_env(tmpdir, '[metadata]\nversion = 10.1.1\nkeywords = one, two\n\n[options]\nscripts = bin/a.py, bin/b.py\n') config_dict = read_configuration(('%s' % config)) assert (config_dict['metadata']['version'] == '10....
def test_upload_mixin_with_filepath_and_filedata(gl): class TestClass(UploadMixin, FakeObject): _upload_path = '/tests/{id}/uploads' url = ' responses.add(method=responses.POST, url=url, json={'id': 42, 'file_name': 'test.txt', 'file_content': 'testing contents'}, status=200, match=[responses.matche...
def LDOS1D_e(x, E, psi, m, step=0.001, margin=0.02, broad=0.005): Emax = (max(E['Ee']) + (margin * q)) Emin = (min(E['Ee']) - (margin * q)) energy = np.arange(Emin, Emax, (step * q)) LDOS = np.zeros((len(energy), len(x))) for (i, ee) in enumerate(E['Ee']): m_plane = calculate_in_plane_masses...
class TagTreeSplitUtilTest(TestCase): def test_split_tree_none(self): parts = tag_utils.split_tree_name('') self.assertEqual(len(parts), 0) def test_split_tree_one(self): parts = tag_utils.split_tree_name('one') self.assertEqual(len(parts), 1) self.assertEqual(parts[0], '...
def assignment_matrix(cal_data: Dict[(int, Dict[(int, int)])], num_qubits: int, qubits: Optional[List[int]]=None) -> np.array: if (qubits is not None): qubits = np.asarray(qubits) dim = (1 << qubits.size) mask = _amat_mask(qubits, num_qubits) accum_func = partial(_amat_accum_local, q...
class ItemTraits(wx.Panel): def __init__(self, parent, stuff, item): wx.Panel.__init__(self, parent) mainSizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(mainSizer) self.traits = wx.html.HtmlWindow(self) bgcolor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) fgcolo...
class TestVectorize(): .change_flags(cxx='') def test_shape(self): vec = tensor(shape=(None,), dtype='float64') mat = tensor(shape=(None, None), dtype='float64') node = shape(vec).owner [vect_out] = vectorize_node(node, mat).outputs assert equal_computations([vect_out], [...
def reapply(layer_or_layers, replacements, **kwargs): assert isinstance(replacements, dict), 'replacements must be a dictionary {old_layer:new_layer}' assert (isinstance(layer_or_layers, Layer) or hasattr(layer_or_layers, '__getitem__')), 'layers must be either a single layer, dict-like or iterable of layers. I...
def test_eval_hook(): with pytest.raises(AssertionError): test_dataset = Model() data_loader = DataLoader(test_dataset) EvalHook(data_loader, save_best=True) with pytest.raises(TypeError): test_dataset = Model() data_loader = [DataLoader(test_dataset)] EvalHook(da...
class Migration(migrations.Migration): dependencies = [('conferences', '0026_move_speaker_voucher_in_conferences'), ('schedule', '0036_store_when_the_voucher_email_was_sent')] operations = [migrations.AlterField(model_name='speakervoucher', name='conference', field=models.ForeignKey(on_delete=django.db.models.d...
class ChaiscriptLexer(RegexLexer): name = 'ChaiScript' url = ' aliases = ['chaiscript', 'chai'] filenames = ['*.chai'] mimetypes = ['text/x-chaiscript', 'application/x-chaiscript'] version_added = '2.0' flags = (re.DOTALL | re.MULTILINE) tokens = {'commentsandwhitespace': [('\\s+', Text)...
class OS(ContentManageable, NameSlugModel): class Meta(): verbose_name = 'Operating System' verbose_name_plural = 'Operating Systems' ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return reverse('download:download_os_list', kwarg...
class BasicModule(torch.nn.Module): def __init__(self, args): super(BasicModule, self).__init__() self.args = args self.model_name = str(type(self)) def pad_doc(self, words_out, doc_lens): pad_dim = words_out.size(1) max_doc_len = max(doc_lens) sent_input = [] ...
def test_future(zarr_dataset: ChunkedDataset, cfg: dict) -> None: steps = (1, 2, 4) for step in steps: gen_partial = get_partial(cfg, 2, step, 0.1) data = gen_partial(state_index=10, frames=np.asarray(zarr_dataset.frames[90:150]), agents=zarr_dataset.agents, tl_faces=np.zeros(0), selected_track_...
class Migration(migrations.Migration): dependencies = [('styles', '0010_rename_Review_model_and_file_field')] operations = [migrations.AlterField(model_name='review', name='resource', field=models.ForeignKey(blank=True, help_text='The reviewed Style.', null=True, on_delete=django.db.models.deletion.CASCADE, to=...
class RandomSampleDataset(Dataset): def __init__(self, db, sample_rate_dict=None): self.db = db self.rank = (dist.get_rank() if dist.is_initialized() else 0) np.random.seed(self.rank) self.world_size = (dist.get_world_size() if dist.is_initialized() else 0) self.keys = sorted...
def setup_domains(app, config): for role in HoverXRefBaseDomain.hoverxref_types: app.add_role_to_domain('std', role, XRefRole(lowercase=True, innernodeclass=nodes.inline, warn_dangling=True)) domain = types.new_class('HoverXRefStandardDomain', (HoverXRefStandardDomainMixin, app.registry.domains.get('std...
class SudsStationcomp(SudsStructBase, namedtuple('SudsStationcomp', 'sc_name, azim, incid, st_lat, st_long, elev, enclosure, annotation, recorder, rockclass, rocktype, sitecondition, sensor_type, data_type, data_units, polarity, st_status, max_gain, clip_value, con_mvolts, channel, atod_gain, effective, clock_correct, ...
class CacheDecorator(DecoratorBase): binder_cls = CacheDecoratorBinder def __init__(self, *args): super().__init__(*args) self._cache = {} def name(self): return '' def dirty(self, *args): try: del self._cache[args] except KeyError: pass ...
def test_is_pure_async_fn(): assert is_pure_async_fn(lazy_fn) assert (not is_pure_async_fn(test_lazy)) assert (not is_pure_async_fn(async_fn)) assert is_pure_async_fn(pure_async_fn) assert (not is_pure_async_fn(DisallowSetting())) assert is_pure_async_fn(MyClass.get_cls) assert (not is_pure_...
class last_fc(nn.Linear): def __init__(self, in_features, out_features, bias=True): super(last_fc, self).__init__(in_features, out_features, bias) self.layer_type = 'LFC' def forward(self, x): max = self.weight.data.max() weight_q = self.weight.div(max).mul(127).round().div(127)....
class SpacedDiffusion(GaussianDiffusion): def __init__(self, use_timesteps, **kwargs): self.use_timesteps = set(use_timesteps) self.timestep_map = [] self.original_num_steps = len(kwargs['betas']) base_diffusion = GaussianDiffusion(**kwargs) last_alpha_cumprod = 1.0 n...
def create_energy_cell(cell_index: int, resource_database: ResourceDatabase) -> PickupEntry: return PickupEntry(name=f'Energy Cell {(cell_index + 1)}', progression=((resource_database.get_item(corruption_items.ENERGY_CELL_ITEMS[cell_index]), 1),), extra_resources=((resource_database.get_item(corruption_items.ENERGY...
def generate_network_parameters(param_range: Optional[Union[(float, List[float])]]=(2 * pi), num_params: Optional[int]=None, load_from: Optional[str]=None) -> List[float]: if load_from: all_params = np.loadtxt(load_from) if (len(np.shape(all_params)) < 2): all_params = np.array([all_para...
class Session(nodes.Collector): Interrupted = Interrupted Failed = Failed _setupstate: SetupState _fixturemanager: FixtureManager exitstatus: Union[(int, ExitCode)] def __init__(self, config: Config) -> None: super().__init__(name='', path=config.rootpath, fspath=None, parent=None, confi...
def train(args, model, teacher, epoch, train_loader, optimizer, log): model.train() teacher.eval() losses = AverageMeter() MSE_loss = nn.MSELoss(reduction='sum') for (data, _, _) in tqdm(train_loader): data = data.to(device) (z, output, mu, log_var) = model(data) (s_activatio...
def _normalize_darwin_path(filename, canonicalise=False): filename = path2fsn(filename) if canonicalise: filename = os.path.realpath(filename) filename = os.path.normpath(filename) data = fsn2bytes(filename, 'utf-8') decoded = data.decode('utf-8', 'quodlibet-osx-path-decode') try: ...
def cfg_to_dict(cfg_node, key_list=[]): _VALID_TYPES = {tuple, list, str, int, float, bool} if (not isinstance(cfg_node, CfgNode)): if (type(cfg_node) not in _VALID_TYPES): logging.warning(f"Key {'.'.join(key_list)} with value {type(cfg_node)} is not a valid type; valid types: {_VALID_TYPES}...
def main(unused_argv): assert FLAGS.checkpoint_dir, '`checkpoint_dir` is missing.' assert FLAGS.eval_dir, '`eval_dir` is missing.' (model_config, train_config, input_config, eval_config) = get_configs_from_pipeline_file() model_fn = functools.partial(build_man_model, model_config=model_config, is_traini...
class GameConnectionWindow(QtWidgets.QMainWindow, Ui_GameConnectionWindow): ui_for_builder: dict[(ConnectorBuilder, BuilderUi)] layout_uuid_for_builder: dict[(ConnectorBuilder, uuid.UUID)] def __init__(self, window_manager: MainWindow, network_client: QtNetworkClient, options: Options, game_connection: Game...
_flax class FlaxRobertaModelTest(FlaxModelTesterMixin, unittest.TestCase): test_head_masking = True all_model_classes = ((FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestio...
class Ator(): _caracter_ativo = 'A' _caracter_destruido = ' ' def __init__(self, x=0, y=0): self.y = y self.x = x self.status = ATIVO def caracter(self): return (self._caracter_ativo if (self.status == ATIVO) else self._caracter_destruido) def calcular_posicao(self, t...
class QuestionAnswers(): __slots__ = ('ucast', 'mcast_now', 'mcast_aggregate', 'mcast_aggregate_last_second') def __init__(self, ucast: _AnswerWithAdditionalsType, mcast_now: _AnswerWithAdditionalsType, mcast_aggregate: _AnswerWithAdditionalsType, mcast_aggregate_last_second: _AnswerWithAdditionalsType) -> None...
def run_proc(cpu_id, file_list, wiki5m_alias2qid, wiki5m_qid2alias, head_cluster, min_seq_len=100, max_seq_len=300, output_folder='./pretrain_data/data/'): if (not os.path.exists(output_folder)): os.makedirs(output_folder) target_filename = os.path.join(output_folder, 'data_{}.json'.format((cpu_id + 100...
def _load_spec(spec: ModuleSpec, module_name: str) -> ModuleType: name = getattr(spec, '__name__', module_name) if (name in sys.modules): return sys.modules[name] module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module
class BinaryWeightedMultipleFixedPredictor(WeightedPredictionLayer): def __init__(self, fc_init='glorot_uniform', pos_weight=None): self.fc_init = fc_init self.pos_weight = pos_weight def apply(self, is_train, x, weights, answer: List): init = get_keras_initialization(self.fc_init) ...
def create_output_string(args: CustomNamespace) -> str: output_fields = get_output_fields(args) if args.summary: table = create_summary_table(args) else: table = create_licenses_table(args, output_fields) sortby = get_sortby(args) if (args.format_ == FormatArg.HTML): html = t...
def align_features_to_words(roberta, features, alignment): assert (features.dim() == 2) bpe_counts = Counter((j for bpe_indices in alignment for j in bpe_indices)) assert (bpe_counts[0] == 0) denom = features.new([bpe_counts.get(j, 1) for j in range(len(features))]) weighted_features = (features / d...
def find_invalid_scalar_params(paramdomains: Dict[('str', Domain)]) -> Dict[('str', Tuple[(Union[(None, float)], Union[(None, float)])])]: invalid_params = {} for (param, paramdomain) in paramdomains.items(): (lower_edge, upper_edge) = (None, None) if (np.ndim(paramdomain.lower) == 0): ...
def main(args=None): if (args is None): args = sys.argv[1:] args = parse_args(args) backbone = models.backbone(args.backbone) check_keras_version() if args.gpu: os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu keras.backend.tensorflow_backend.set_session(get_session()) if args.c...
class AutumnStyle(Style): name = 'autumn' styles = {Whitespace: '#bbbbbb', Comment: 'italic #aaaaaa', Comment.Preproc: 'noitalic #4c8317', Comment.Special: 'italic #0000aa', Keyword: '#0000aa', Keyword.Type: '#00aaaa', Operator.Word: '#0000aa', Name.Builtin: '#00aaaa', Name.Function: '#00aa00', Name.Class: 'und...
class PLCSiemens(Image): icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABcAAAAvCAYAAAAIA1FgAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAADmwAAA5sBPN8HMQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANGSURBVFiF7ZbNbxtFGIefmR2vP+PUjkntxHGapmmpKpIoECggjpyQEBKqeoIjXDhw5cD/wZ0LEgiJEzck1EIrlUYBl7RJ1bQlbUpCHNux15+7MxycW...
(Widget) class CoactiveWidgetStub(Widget): def __init__(self, view, css_id, coactive_widgets): super().__init__(view) self._coactive_widgets = coactive_widgets self.css_id = css_id def render_contents(self): return ('<%s>' % self.css_id) def coactive_widgets(self): re...
class Cookie(_Cookie): _attrs = ('version', 'name', 'value', 'port', 'port_specified', 'domain', 'domain_specified', 'domain_initial_dot', 'path', 'path_specified', 'secure', 'expires', 'discard', 'comment', 'comment_url', 'rfc2109', '_rest') def __eq__(self, other): return all(((getattr(self, a) == get...
def get_sample_fn(params, is_training=False, use_prior=False, reuse=False, output_length=None): def model(inputs): outputs = get_seq_encoding_model(inputs, params, is_training, reuse) outputs = get_latent_encoding_model(inputs, outputs, params, is_training, use_prior, reuse) outputs = get_la...
def main(args: Any=None) -> None: if (args is None): args = sys.argv[1:] (parser, parent_parser, subparsers) = create_parser() codec_lookup = {} for cls in codec_classes: codec_class = cls() codec_lookup[codec_class.name] = codec_class codec_parser = subparsers.add_parser...
def main(): with open(FLAGS.hq_replay_set) as f: replay_list = sorted(json.load(f)) race_vs_race = os.path.basename(FLAGS.hq_replay_set).split('.')[0] global_feature_path = os.path.join(FLAGS.parsed_replay_path, 'GlobalFeatures', race_vs_race) for race in set(race_vs_race.split('_vs_')): ...
_metaclass(BaseMeta) class BaseWrapper(object): friendlyclassname = None windowclasses = [] can_be_label = False has_title = True def __new__(cls, element_info, active_backend): return BaseWrapper._create_wrapper(cls, element_info, BaseWrapper) def _create_wrapper(cls_spec, element_info,...
(...) def test_mapping_validation(detailed_validation: bool): c = Converter(detailed_validation=detailed_validation) if detailed_validation: with pytest.raises(IterableValidationError) as exc: c.structure({'1': 1, '2': 'b', 'c': 3}, Dict[(int, int)]) assert (repr(exc.value.exceptions...
class TestOrderedBiMap(): def test_inverse(self): d = OrderedBiMap([('one', 1), ('two', 2)]) assert (d.inverse == OrderedBiMap([(1, 'one'), (2, 'two')])) assert (d.inverse.inverse is d) def test_annotation(self): def foo() -> OrderedBiMap[(str, int)]: pass
def split_interval_pattern(pattern: str) -> list[str]: seen_fields = set() parts = [[]] for (tok_type, tok_value) in tokenize_pattern(pattern): if (tok_type == 'field'): if (tok_value[0] in seen_fields): parts.append([]) seen_fields.clear() see...
class BitextOutputFromGen(object): def __init__(self, predictions_bpe_file, bpe_symbol=None, nbest=False, prefix_len=None, target_prefix_frac=None): if nbest: (pred_source, pred_hypo, pred_score, pred_target, pred_pos_score) = reprocess_nbest(predictions_bpe_file) else: (pred...
class convLR(nn.Module): def __init__(self, in_out_channels=2048, kernel_size=(1, 9)): super(convLR, self).__init__() self.conv = nn.Sequential(nn.Conv2d(in_out_channels, in_out_channels, kernel_size, stride=1, padding=(((kernel_size[0] - 1) // 2), ((kernel_size[1] - 1) // 2))), nn.ReLU(inplace=True...
def _init_distributed(use_gpu: bool): distributed_world_size = int(os.environ['WORLD_SIZE']) distributed_rank = int(os.environ['RANK']) backend = ('nccl' if use_gpu else 'gloo') torch.distributed.init_process_group(backend=backend, init_method='env://', world_size=distributed_world_size, rank=distribute...
class _TimeSuite(): params = ([10000, 100000, 1000000], ['all', 'finite', 'pairs', 'array']) def setup(self, nelems, connect): self.xdata = np.arange(nelems, dtype=np.float64) self.ydata = rng.standard_normal(nelems, dtype=np.float64) if (connect == 'array'): self.connect_arr...
def mode_dot(tensor, matrix, mode): new_shape = tensor.get_shape().as_list() if (matrix.get_shape().as_list()[1] != tensor.get_shape().as_list()[mode]): raise ValueError("Shape error. {0}(matrix's 2nd dimension) is not as same as {1} (dimension of the tensor)".format(matrix.get_shape().as_list()[1], ten...
def download(url, dirpath): filename = url.split('/')[(- 1)] filepath = os.path.join(dirpath, filename) u = urllib.request.urlopen(url) f = open(filepath, 'wb') filesize = int(u.headers['Content-Length']) print(('Downloading: %s Bytes: %s' % (filename, filesize))) downloaded = 0 block_sz...
class SelectAdaptivePool2d(nn.Module): def __init__(self, output_size=1, pool_type='fast', flatten=False): super(SelectAdaptivePool2d, self).__init__() self.pool_type = (pool_type or '') self.flatten = (nn.Flatten(1) if flatten else nn.Identity()) if (pool_type == ''): se...
class GameHighScore(Object): def __init__(self, *, client: 'pyrogram.Client'=None, user: 'types.User', score: int, position: int=None): super().__init__(client) self.user = user self.score = score self.position = position def _parse(client, game_high_score: raw.types.HighScore, u...
_model def poolformer_s36(pretrained=False, **kwargs): layers = [6, 6, 18, 6] embed_dims = [64, 128, 320, 512] mlp_ratios = [4, 4, 4, 4] downsamples = [True, True, True, True] model = PoolFormer(layers, embed_dims=embed_dims, mlp_ratios=mlp_ratios, downsamples=downsamples, layer_scale_init_value=1e-...
.mssql_server_required class TestErrorInSP(unittest.TestCase): def setUp(self): self.pymssql = pymssqlconn() cursor = self.pymssql.cursor() sql = u"\n CREATE PROCEDURE [dbo].[SPThatRaisesAnError]\n AS\n BEGIN\n -- RAISERROR -- Generates an error message and in...
class TestForumTopicEdited(): def test_slot_behaviour(self, topic_edited): for attr in topic_edited.__slots__: assert (getattr(topic_edited, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(topic_edited)) == len(set(mro_slots(topic_edited)))), 'duplicate slot' ...
class ChannelPatchSchema(BaseSchema): total_deposit = IntegerToStringField(default=None, missing=None) total_withdraw = IntegerToStringField(default=None, missing=None) reveal_timeout = IntegerToStringField(default=None, missing=None) state = fields.String(default=None, missing=None, validate=validate.O...
.parametrize('include_menu_mod', [False, True]) def test_apply_patcher_file(include_menu_mod: bool, valid_tmp_game_root, mocker: pytest_mock.MockerFixture): mock_run_with_args = mocker.patch('randovania.games.prime2.patcher.claris_randomizer._run_with_args', autospec=True) mock_create_progress_update_from_succe...
def main(): with open('Dockerfile.j2') as f: template = jinja2.Template(f.read(), trim_blocks=True, lstrip_blocks=True) parser = argparse.ArgumentParser() parser.add_argument('config', choices=CONFIGS) args = parser.parse_args() config = CONFIGS[args.config] with open('Dockerfile', 'w') ...
_required def version_update(request, package_name, version): plugin = get_object_or_404(Plugin, package_name=package_name) version = get_object_or_404(PluginVersion, plugin=plugin, version=version) if (not check_plugin_access(request.user, plugin)): return render(request, 'plugins/version_permissio...
def get_generator_loc(opt): if (opt.model == 'DCGAN'): return (((((g.default_model_dir + 'DCGAN/') + opt.data) + '/netG_epoch_') + str(opt.epoch)) + '.pth') elif (opt.model == 'WGAN'): return (((((g.default_model_dir + 'WGAN/') + opt.data) + '/netG_epoch_') + str(opt.epoch)) + '.pth') elif (...
class KnowValues(unittest.TestCase): def test_label_orb_symm(self): l = addons.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, mf.mo_coeff) lab0 = ['A1', 'A1', 'B2', 'A1', 'B1', 'A1', 'B2', 'B2', 'A1', 'A1', 'B1', 'B2', 'A1', 'A2', 'B1', 'A1', 'B2', 'B2', 'A1', 'B1', 'A2', 'A1', 'A1', 'B2'] ...
def test_guess_syntax(): for name in ('plain',): assert (botogram.syntaxes.guess_syntax('', name) is None) for name in ('md', 'markdown', 'Markdown'): assert (botogram.syntaxes.guess_syntax('', name) == 'Markdown') for name in ('html', 'HTML'): assert (botogram.syntaxes.guess_syntax(...
def train(dataset='mnist', model_name='d2l', batch_size=128, epochs=50, noise_ratio=0): print(('Dataset: %s, model: %s, batch: %s, epochs: %s, noise ratio: %s%%' % (dataset, model_name, batch_size, epochs, noise_ratio))) (X_train, y_train, X_test, y_test) = get_data(dataset, noise_ratio, random_shuffle=True) ...
class FavoriteItemsMixin(ContextMixin): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if likes_enable(): pass date = (datetime.datetime.now() - datetime.timedelta(days=12)) items = Item.objects.filter(status='active', related_t...
class FakeServer(ServerAsync): def __init__(self, loop, dictionary): ServerAsync.__init__(self, loop=loop, dictionary=dictionary, enable_pkt_verify=True, debug=True) def handle_auth_packet(self, protocol, pkt, addr): print('Received an authentication request with id ', pkt.id) print('Aut...
def _pool(type, raw, input, x, kernel_size, stride, padding, ceil_mode): layer_name = log.add_layer(name='{}_pool'.format(type)) top_blobs = log.add_blobs([x], name='{}_pool_blob'.format(type)) layer = caffe_net.Layer_param(name=layer_name, type='Pooling', bottom=[log.blobs(input)], top=top_blobs) layer...
def sample_and_group(npoint, radius, nsample, xyz, points, knn=False, use_xyz=True): sample_idx = farthest_point_sample(npoint, xyz) new_xyz = gather_point(xyz, sample_idx) if knn: (_, idx) = knn_point(nsample, xyz, new_xyz) else: (idx, pts_cnt) = query_ball_point(radius, nsample, xyz, n...
class TestAmavisCollector(CollectorTestCase): def setUp(self): config = get_collector_config('AmavisCollector', {'amavisd_exe': MOCK_PATH}) self.collector = amavis.AmavisCollector(config, None) (Collector, 'publish') def test_publish(self, publish_mock): self.collector.collect() ...