code
stringlengths
281
23.7M
def test_parse_command_only_expands_alias(parser): line = 'fake foobar.py "somebody.py' statement = parser.parse_command_only(line) assert (statement == 'foobar.py "somebody.py') assert (statement.args == statement) assert (statement.arg_list == []) assert (statement.command == 'run_pyscript') ...
class PancakeHouseMenu(Menu): menuItems: List[str] def __init__(self): self.menuItems = [] self.addItem("K&B's Pancake Breakfast") self.addItem('Regular Pancake Breakfast') self.addItem('Blueberry Pancakes') self.addItem('Waffles') def addItem(self, name: str) -> None...
_events class EventObject(DefaultObject): _events = {'drop': (['character', 'obj'], OBJECT_DROP), 'get': (['character', 'obj'], OBJECT_GET), 'time': (['object'], OBJECT_TIME, None, time_event)} _property def callbacks(self): return CallbackHandler(self) def at_get(self, getter): super()....
def _test(): import torch pretrained = False models = [mnasnet] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) assert ((model != mnasnet) or (weight_count ==...
_api() class rate_limit(Stream): _graphviz_shape = 'octagon' def __init__(self, upstream, interval, **kwargs): self.interval = convert_interval(interval) self.next = 0 kwargs['ensure_io_loop'] = True Stream.__init__(self, upstream, **kwargs) def update(self, x, who=None, meta...
def get_linear_schedule_with_warmup(optimizer: Optimizer, num_warmup_steps: int, num_training_steps: int, last_epoch: int=(- 1)): def lr_lambda(current_step: int): if (current_step < num_warmup_steps): return max(1e-06, (float(current_step) / float(max(1, num_warmup_steps)))) return max(...
class Full(BaseElectrolyteConductivity): def __init__(self, param, options=None): super().__init__(param, options=options) def get_fundamental_variables(self): phi_e_dict = {} variables = {} for domain in self.options.whole_cell_domains: Dom = domain.capitalize().spli...
class L2Loss(Loss): def evaluate(self, predict: np.ndarray, target: np.ndarray) -> np.ndarray: self._validate_shapes(predict, target) if (len(predict.shape) <= 1): return ((predict - target) ** 2) else: return (np.linalg.norm((predict - target), axis=tuple(range(1, le...
() def remove_old_client_ids(days=90): old_cutoff = (get_ad_day() - datetime.timedelta(days=days)) while True: offer_ids = Offer.objects.filter(date__lt=old_cutoff, client_id__isnull=False).values('pk')[:1000] offers_changed = Offer.objects.filter(pk__in=offer_ids).update(client_id=None) ...
class TutorialReadable(TutorialObject): def at_object_creation(self): super().at_object_creation() self.db.tutorial_info = "This is an object with a 'read' command defined in a command set on itself." self.db.readable_text = ('There is no text written on %s.' % self.key) self.cmdset....
class TestNativeMSGPadder(unittest.TestCase): def prepare_padder(test_dict): dataset_id = test_dict['dataset_id'] img_bounds = test_dict['img_bounds'] is_full_disk = test_dict['is_full_disk'] dataset = test_dict['dataset'] final_shape = test_dict['final_shape'] expect...
def particle_grid(dim_x, dim_y, dim_z, lower, radius, jitter): points = np.meshgrid(np.linspace(0, dim_x, dim_x), np.linspace(0, dim_y, dim_y), np.linspace(0, dim_z, dim_z)) points_t = (((np.array((points[0], points[1], points[2])).T * radius) * 2.0) + np.array(lower)) points_t = (points_t + ((np.random.ran...
def test_cli_async_reduce_without_curry(runner, reactor, server, capsys): base_url = ' in_stream = ''.join((base_url.format(i) for i in [6, 2, 1])) args = ['async-map', 'await asks.get ! f"{types.SimpleNamespace(**x.json()).delay}"', 'map', 'json.loads', 'reduce', 'operator.truediv'] expected = '3.0\n'...
class LinearColormap(ColorMap): def __init__(self, colors, index=None, vmin=0.0, vmax=1.0, caption='', max_labels=10, tick_labels=None): super().__init__(vmin=vmin, vmax=vmax, caption=caption, max_labels=max_labels) self.tick_labels = tick_labels n = len(colors) if (n < 2): ...
class AlgorithmResult(ABC, collections.UserDict): def __init__(self, a_dict: Optional[Dict]=None) -> None: super().__init__() if a_dict: self.data.update(a_dict) def __setitem__(self, key: object, item: object) -> None: raise TypeError("'__setitem__' invalid for this object."...
def numpy_random_mtrand_transform(): return parse("\n def beta(a, b, size=None): return uninferable\n def binomial(n, p, size=None): return uninferable\n def bytes(length): return uninferable\n def chisquare(df, size=None): return uninferable\n def choice(a, size=None, replace=True, p=None): return u...
class TensoredMeasFitter(): def __init__(self, results: Union[(Result, List[Result])], mit_pattern: List[List[int]], substate_labels_list: List[List[str]]=None, circlabel: str=''): self._result_list = [] self._cal_matrices = None self._circlabel = circlabel self._mit_pattern = mit_pa...
def all_dna_locations(game: GameDescription, config: AM2RArtifactConfig): locations = [] for node in game.region_list.all_nodes: if isinstance(node, PickupNode): name = node.extra['object_name'] if (config.prefer_metroids and name.startswith('oItemDNA_')): locatio...
def _CKD_priv(parent_privkey: bytes, parent_chaincode: bytes, child_index: bytes, is_hardened_child: bool) -> Tuple[(bytes, bytes)]: try: keypair = ecc.ECPrivkey(parent_privkey) except ecc.InvalidECPointException as e: raise BitcoinException('Impossible xprv (not within curve order)') from e ...
def remove_all_but_largest_component_from_segmentation(segmentation: np.ndarray, labels_or_regions: Union[(int, Tuple[(int, ...)], List[Union[(int, Tuple[(int, ...)])]])], background_label: int=0) -> np.ndarray: mask = np.zeros_like(segmentation, dtype=bool) if (not isinstance(labels_or_regions, list)): ...
def test_on_action_delete_items(view, item): view.scene.cancel_crop_mode = MagicMock() view.scene.addItem(item) item.setSelected(True) view.on_action_delete_items() assert (view.scene.items() == []) assert (view.undo_stack.isClean() is False) view.scene.cancel_crop_mode.assert_called_once()
class TestInputGeneration(unittest.TestCase): def test_tape_inputs(self): for env_kls in ALL_TAPE_ENVS: env = env_kls() for size in range(2, 5): input_tape = env.generate_input_data(size) self.assertTrue(all(((0 <= x <= env.base) for x in input_tape)),...
def LSTMCell(prev_cell, prev_out, input_or_inputs=tuple(), num_units=None, peepholes=True, weight_init=init.Normal(), bias_init=init.Constant(), peepholes_W_init=init.Normal(), forgetgate_nonlinearity=lasagne.nonlinearities.sigmoid, inputgate_nonlinearity=lasagne.nonlinearities.sigmoid, outputgate_nonlinearity=lasagne....
class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='Commit', fields=[('sha', models.CharField(help_text='The SHA hash of this commit.', max_length=40, primary_key=True, serialize=False)), ('message', models.TextField(help_text='The commit messag...
def single_run(E=30000.0, P=25.0, w=0.1, x=0.0): ops.wipe() ops.model('basic', '-ndm', 2, '-ndf', 3) ops.node(1, x, 0) ops.node(2, 0, 144) ops.node(3, 240, 144) ops.node(4, 240, 0) ops.fix(1, 1, 1, 1) ops.fix(4, 1, 1, 1) Ag = 25.0 Ig = 1500.0 Ac = 29.0 Ic = 2000.0 gse...
class TestSerializeStream(): def _set_status(self, stream, status): stream.status.return_value = status def stream_mock(self): m = unittest.mock.MagicMock(spec=QDataStream) m.status.return_value = QDataStream.Status.Ok return m def test_serialize_pre_error_mock(self, stream_m...
def calc_time(lower_bound, upper_bound, latitude, longitude, attribute, value, altitude=0, pressure=101325, temperature=12, horizon='+0:00', xtol=1e-12): (obs, sun) = _ephem_setup(latitude, longitude, altitude, pressure, temperature, horizon) def compute_attr(thetime, target, attr): obs.date = thetime ...
.parametrize('keys, expected', [([127995], '<>'), ([171510], '<>'), ([Qt.Key.Key_Shift, 171510], '<Shift><>'), ([128104, 8205, 128104, 8205, 128102], '<><\u200d><><\u200d><>')]) _enum_workaround_skip def test_surrogate_sequences(keys, expected): infos = [keyutils.KeyInfo(Qt.Key(key)) for key in keys] seq = keyu...
def _run_on_single_gpu(model, batch_list_t, batch_list_v, batch_sequence_output_list, batch_seq_features_list, batch_visual_output_list): sim_matrix = [] for (idx1, b1) in enumerate(batch_list_t): (input_mask, segment_ids, *_tmp) = b1 sequence_output = batch_sequence_output_list[idx1] se...
class _RemoteEnv(object): def __init__(self, env_pkl, policy_pkl): self._sess = tf_utils.create_session() self._sess.run(tf.global_variables_initializer()) self._env = pickle.loads(env_pkl) self._policy = pickle.loads(policy_pkl) if hasattr(self._env, 'initialize'): ...
def main_worker(local_rank, args): args.local_rank = local_rank args.global_rank = (args.local_rank + (args.node_rank * args.ngpus_per_node)) args.distributed = (args.world_size > 1) print(args) config = load_yaml_config(args.config_file) config = merge_opts_to_config(config, args.opts) if a...
def write_preprocessing_parameters(params: namedtuple) -> None: dict_path = (params.dataset_dir + 'preprocessing_params.csv') keys_to_write = ['atom_types', 'formal_charge', 'imp_H', 'chirality', 'group_size', 'max_n_nodes', 'use_aromatic_bonds', 'use_chirality', 'use_explicit_H', 'ignore_H'] with open(dict...
class Storage(Resource): ('StorageResource', rus.optional(str), rus.optional(ss.Session), rus.optional(sab.Base), rus.optional(dict), rus.optional(rus.one_of(SYNC, ASYNC, TASK))) (rus.nothing) def __init__(self, id=None, session=None, _adaptor=None, _adaptor_state={}, _ttype=None): self._resrc = sup...
def before_after_plots_for_quantized_model(before_weights_map, after_weights_map): for key in before_weights_map.keys(): before_quantization_data = before_weights_map[key] after_quantization_data = after_weights_map[key] compare_boxplots_before_after_quantization(before_quantization_data, af...
class ListItemWrapper(uiawrapper.UIAWrapper): _control_types = ['DataItem', 'ListItem'] def __init__(self, elem, container=None): super(ListItemWrapper, self).__init__(elem) self.container = container def is_checked(self): return (self.iface_toggle.ToggleState_On == toggle_state_on) ...
def rand_real(): vp = np.random.uniform(low=0, high=360) vangle = np.random.uniform(low=(- 40), high=(- 70)) cam_dist = np.random.uniform(low=1.5, high=2.5) distlow = 0.4 distobj = np.random.uniform(low=distlow, high=0.7) distmult = np.random.uniform(low=1.7, high=2.1) object_ = [(- (distobj...
_edge_encoder('LinearEdge') class LinearEdgeEncoder(torch.nn.Module): def __init__(self, emb_dim): super().__init__() if (cfg.dataset.name in ['MNIST', 'CIFAR10']): self.in_dim = 1 else: raise ValueError('Input edge feature dim is required to be hardset or refactored ...
class TestLinearMapper(QiskitNatureTestCase): spin_op1 = SpinOp({'Y_0^2': ((- 0.432) + 1.32j)}, 0.5, 1) ref_qubit_op1 = SparsePauliOp(['II', 'ZZ'], coeffs=[((- 0.054) + 0.165j), (0.054 - 0.165j)]) spin_op2 = SpinOp({'X_0 Z_0': ((- 1.139) + 0.083j)}, 0.5, 2) ref_qubit_op2 = SparsePauliOp(['IIYX', 'IIXY']...
def ssim3D(img1, img2, window_size=11, size_average=True): (_, channel, _, _, _) = img1.size() window = create_window_3D(window_size, channel) if img1.is_cuda: window = window.cuda(img1.get_device()) window = window.type_as(img1) return _ssim_3D(img1, img2, window, window_size, channel, size...
def load_sentence(path): sentences = [] sentence = [] for line in codecs.open(path, 'r', 'utf8'): line = json.loads(line) doc_id = line[0] sentence_text = line[1] tag = line[(- 1)] sentence.append(sentence_text) sentences.append(line) chars = [[x for x in ...
def test_lock_file_should_not_have_mixed_types(locker: Locker, root: ProjectPackage) -> None: package_a = get_package('A', '1.0.0') package_a.add_dependency(Factory.create_dependency('B', '^1.0.0')) package_a.add_dependency(Factory.create_dependency('B', {'version': '>=1.0.0', 'optional': True})) packag...
class Model(object): def __init__(self, environment): self.environment = environment self._converter = None def get_value(self, formula, model_completion=True): raise NotImplementedError def get_values(self, formulae, model_completion=True): res = {} for f in formulae...
def _expand_requires_extra(re): for (extra, reqs) in sorted(re.items()): for req in reqs: if (';' in req): (name, envmark) = req.split(';', 1) (yield '{} ; extra == "{}" and ({})'.format(name, extra, envmark)) else: (yield '{} ; extra =...
def cifar10_iterator(cfg, kv): train_rec = os.path.join(cfg.dataset.data_dir, 'cifar10_train.rec') val_rec = os.path.join(cfg.dataset.data_dir, 'cifar10_val.rec') mean = [125.31, 123.01, 113.91] std = [63.01, 62.09, 66.71] train = mx.io.ImageRecordIter(path_imgrec=train_rec, label_width=1, data_name...
def fix_gnu_param(arch, ex): d = collections.defaultdict(list) version = None for item in ex: if item.get('linux_version'): if (not version): version = item.get('linux_version') else: raise Exception('More than one linux_version defined') ...
class ApocalypticMetropolis(pm.Metropolis): stats_dtypes_shapes = {**pm.Metropolis.stats_dtypes_shapes, 'warning': (SamplerWarning, None)} def astep(self, q0): (draw, stats) = super().astep(q0) stats[0]['warning'] = SamplerWarning(WarningType.BAD_ENERGY, 'Asteroid incoming!', 'warn') ret...
def cannot_combine_with_fragment_options(ctx, cache): if (cache is None): return used_names = ctx.meta[fragment_click.FRAGMENTATION_OPTION_NAMES] if (not used_names): return names = sorted((name_to_command_line(name) for name in used_names)) if (len(names) == 1): raise click....
class MatchCase(_base_nodes.MultiLineBlockNode): _astroid_fields = ('pattern', 'guard', 'body') _multi_line_block_fields = ('body',) lineno: None col_offset: None end_lineno: None end_col_offset: None def __init__(self, *, parent: (NodeNG | None)=None) -> None: self.pattern: Pattern ...
def verify_onnx(model, path, force_cpu): import onnxruntime import numpy as np model_weight_file = os.path.join(path, (model + '.pth')) model_weight_file = './weights/GPEN-512.pth' model_setenv(force_cpu) torch_model = get_model(model_weight_file) torch_model.eval() onnx_file_name = os.p...
def no_envs(monkeypatch): monkeypatch.delenv('PYPYR_CMD_ENCODING', raising=False) monkeypatch.delenv('PYPYR_ENCODING', raising=False) monkeypatch.delenv('PYPYR_SKIP_INIT', raising=False) monkeypatch.delenv('PYPYR_CONFIG_GLOBAL', raising=False) monkeypatch.delenv('PYPYR_CONFIG_LOCAL', raising=False) ...
def train(args, train_dataset, model, tokenizer): if (args.local_rank in [(- 1), 0]): tb_writer = SummaryWriter() args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu)) train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else DistributedSampler(train_dat...
def load_w2v_embedding(word_list, uniform_scale, dimension_size): embed_file = '../../../code/embedding/GoogleNews-vectors-negative300.bin' model = gensim.models.KeyedVectors.load_word2vec_format(embed_file, binary=True) word_vectors = [] for word in word_list: if (word in model): wo...
def traverse_imports(names): pending = [names] while pending: node = pending.pop() if (node.type == token.NAME): (yield node.value) elif (node.type == syms.dotted_name): (yield ''.join([ch.value for ch in node.children])) elif (node.type == syms.dotted_as_...
class FC3_AutoPart(KickstartCommand): removedKeywords = KickstartCommand.removedKeywords removedAttrs = KickstartCommand.removedAttrs def __init__(self, writePriority=100, *args, **kwargs): KickstartCommand.__init__(self, writePriority, *args, **kwargs) self.autopart = kwargs.get('autopart',...
_register class CodecListObject(BaseObject): GUID = guid2bytes('86D15240-311D-11D0-A3A4-00A0C90348F6') def _parse_entry(self, data, offset): (type_, offset) = cdata.uint16_le_from(data, offset) (units, offset) = cdata.uint16_le_from(data, offset) next_offset = (offset + (units * 2)) ...
class F18_TestCase(F17_TestCase): def runTest(self, iscrypted=False): F17_TestCase.runTest(self, iscrypted=iscrypted) self.assert_parse('bootloader --location=mbr --timeout=5 --append="rhgb quiet"') self.assert_parse('bootloader --location=mbr --timeout=5 --leavebootorder --append="rhgb quie...
class ADE20K(BaseDataLoader): def __init__(self, data_dir, batch_size, split, crop_size=None, base_size=None, scale=True, num_workers=1, val=False, shuffle=False, flip=False, rotate=False, blur=False, augment=False, val_split=None, return_id=False): self.MEAN = [0., 0., 0.4294] self.STD = [0., 0., 0...
class MFWPositionWiseFeedForward(torch.nn.Module): def __init__(self, model_size, inner_size, dropout=0.0, variational=False, activation='relu', n_languages=1, rank=1, use_multiplicative=False, weight_drop=0.0, mfw_activation='none', glu=False, no_bias=False): super().__init__() self.variational = v...
class AbstractLazyTensor(ABC): def logical_not(self): return new_lazy_tensor(torch.Tensor.logical_not, [self]) def logical_and(self, arg): return new_lazy_tensor(torch.Tensor.logical_and, [self, arg]) def logical_or(self, arg): return new_lazy_tensor(torch.Tensor.logical_or, [self, a...
.parametrize(('permalink', 'version'), [('CrhkAGTOLJD7Kf6Y', 10), ('DLhkAGTOLJD7Kf6Y', 12)]) def test_decode_old_version(permalink: str, version: int): expect = f'Given permalink has version {version}, but this Randovania support only permalink of version {Permalink.current_schema_version()}.' with pytest.raise...
class AttrVI_ATTR_WIN_ACCESS_PRIV(EnumAttribute): resources = [(constants.InterfaceType.vxi, 'INSTR'), (constants.InterfaceType.vxi, 'MEMACC')] py_name = '' visa_name = 'VI_ATTR_WIN_ACCESS_PRIV' visa_type = 'ViUInt16' default = constants.VI_DATA_PRIV (read, write, local) = (True, True, True) ...
_db def test_add_slot_fails_when_not_logged(conference_factory, graphql_client): conference = conference_factory(start=datetime(2020, 4, 2, tzinfo=pytz.UTC), end=datetime(2020, 4, 2, tzinfo=pytz.UTC)) resp = graphql_client.query('\n mutation AddScheduleSlot($code: ID!, $day: Date!, $duration: Int!) {\n ...
def write_title(title, stream=None, sep='~'): if (stream is None): stream = sys.stderr (width, height) = shutil.get_terminal_size() fill = int((((width - len(title)) - 2) / 2)) line = ' '.join([(sep * fill), title, (sep * fill)]) if (len(line) < width): line += (sep * (width - len(li...
class ExeclineLexer(RegexLexer): name = 'execline' aliases = ['execline'] filenames = ['*.exec'] url = ' version_added = '2.7' tokens = {'root': [include('basic'), include('data'), include('interp')], 'interp': [('\\$\\{', String.Interpol, 'curly'), ('\\$[\\#]+', Name.Variable), ('\\$', Text)], ...
def main(cfg: DictConfig, **unused_kwargs): if isinstance(cfg, Namespace): cfg = convert_namespace_to_omegaconf(cfg) utils.import_user_module(cfg.common) use_fp16 = cfg.common.fp16 use_cuda = (torch.cuda.is_available() and (not cfg.common.cpu)) if use_cuda: torch.cuda.set_device(cfg....
_tokenizers class MarkupLMTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = MarkupLMTokenizer rust_tokenizer_class = MarkupLMTokenizerFast test_rust_tokenizer = True from_pretrained_kwargs = {'cls_token': '<s>'} test_seq2seq = False def setUp(self): super().set...
() ('-i', '--input-file', help='The name of the input file containing a molecule to be parameterised.', type=click.Path(exists=True, dir_okay=False, resolve_path=True, readable=True)) ('-sm', '--smiles', help='The smiles string of the molecule to be parameterised.', type=click.STRING) ('-m', '--multiplicity', type=clic...
class TestSelect(BaseTestCase): def setUp(self): super().setUp() sync(self.page.goto((self.url + 'static/select.html'))) async def test_select(self): value = (await self.page.select('select', 'blue')) self.assertEqual(value, ['blue']) _input = (await self.page.evaluate('r...
def test_invalid_compute_mask(): model = Sequential() model.add(Conv2D(1, [2, 2], input_shape=[3, 3, 1])) assert (model.layers[0].supports_masking is False) assert (model.layers[0].compute_mask([model.input], [None]) is None) mask = np.array([[0.0, 1.0], [1.0, 0.0]]) with pytest.raises(TypeError...
class TopK(): def __init__(self, k: int): self.k = k def __repr__(self) -> str: repr = f'Filter {self.__class__.__name__}' repr += f''' k: {self.k}''' return repr def __call__(self, documents: typing.Union[typing.List[typing.List[typing.Dict[(str, str)]]]], **kwargs) -> typi...
(netloc='fakegitlab', path='/api/v4/projects/4/repository/files/Dockerfile$') def dockerfile_handler(_, request): if (not (request.headers.get('Authorization') == 'Bearer foobar')): return {'status_code': 401} return {'status_code': 200, 'headers': {'Content-Type': 'application/json'}, 'content': json.d...
class EpisodeDescriptionConfig(object): def __init__(self, num_ways, num_support, num_query, min_ways, max_ways_upper_bound, max_num_query, max_support_set_size, max_support_size_contrib_per_class, min_log_weight, max_log_weight, ignore_dag_ontology, ignore_bilevel_ontology): arg_groups = {'num_ways': (num_...
def _generate_html(data): extra_params = {'initial_header_level': '2', 'syntax_highlight': 'short', 'input_encoding': 'utf-8', 'exit_status_level': 2, 'compact_p': False, 'embed_stylesheet': False} pub = docutils.core.Publisher(source_class=docutils.io.StringInput, destination_class=docutils.io.StringOutput) ...
def check_all_auto_mapping_names_in_config_mapping_names(): check_missing_backends() failures = [] mappings_to_check = {'IMAGE_PROCESSOR_MAPPING_NAMES': IMAGE_PROCESSOR_MAPPING_NAMES, 'FEATURE_EXTRACTOR_MAPPING_NAMES': FEATURE_EXTRACTOR_MAPPING_NAMES, 'PROCESSOR_MAPPING_NAMES': PROCESSOR_MAPPING_NAMES} ...
def get_cfg(cls=CN): cfg = cls() cfg.NUM_GPUS = 8 cfg.TRAIN = cls() cfg.TRAIN.HYPERPARAMETER_1 = 0.1 cfg.TRAIN.SCALES = (2, 4, 8, 16) cfg.MODEL = cls() cfg.MODEL.TYPE = 'a_foo_model' cfg.STR = cls() cfg.STR.KEY1 = 1 cfg.STR.KEY2 = 2 cfg.STR.FOO = cls() cfg.STR.FOO.KEY1 = ...
class DS1000Problem(): def __init__(self, problem_path: Union[(str, Path)]): self.problem_path = Path(problem_path) self.problem_id = int(self.problem_path.name.replace('q', '')) self.data = dict() problem_config = configparser.RawConfigParser() problem_config.read((self.prob...
def sample_info_video(video_frames, time_window, time_stride): samples = ([0] * len(video_frames)) area_sum_samples = ([0] * len(video_frames)) for (i, video) in enumerate(video_frames): samples[i] = ((len(video) - time_window) // time_stride) if (i != 0): area_sum_samples[i] = s...
def composite(*args): import qutip.core.superop_reps if (not all((isinstance(arg, Qobj) for arg in args))): raise TypeError('All arguments must be Qobjs.') if all(map(_isoperlike, args)): if any((arg.issuper for arg in args)): return super_tensor(*map(qutip.core.superop_reps.to_s...
.parametrize(('requirement_string', 'expected'), [('extras_dep', None), ('missing_dep', ('missing_dep',)), ('requireless_dep', None), ('extras_dep[undefined_extra]', None), ('extras_dep[extra-without-associated-deps]', None), ('extras_dep[extra-with-unmet-deps]', ('extras_dep[extra-with-unmet-deps]', 'unmet_dep; extra ...
def get_decode_dir_name(ckpt_name): if (('train' in FLAGS.full_data_path) or ('train' in FLAGS.partial_data_path)): dataset = 'train' elif (('val' in FLAGS.full_data_path) or ('val' in FLAGS.partial_data_path)): dataset = 'val' elif (('test' in FLAGS.full_data_path) or ('test' in FLAGS.parti...
class DevDataset(Dataset): def __init__(self, meta_args, tasks_dev_data): self.meta_args = meta_args self.meta_dev_data = MultiTaskWrapper(args_path2dataset=tasks_dev_data, meta_args=meta_args, section='dev') def __getitem__(self, index) -> T_co: return self.meta_dev_data[index] def ...
class PositionwiseFeedForward(nn.Module): def __init__(self, d_in, d_hid, dropout=0.1): super().__init__() self.w_1 = nn.Conv1d(d_in, d_hid, kernel_size=hp.fft_conv1d_kernel[0], padding=hp.fft_conv1d_padding[0]) self.w_2 = nn.Conv1d(d_hid, d_in, kernel_size=hp.fft_conv1d_kernel[1], padding=h...
class TestWindow(pyglet.window.Window): def __init__(self, *args, **kwargs): super(TestWindow, self).__init__(*args, **kwargs) self.batch = pyglet.graphics.Batch() self.document = pyglet.text.decode_html(doctext) self.margin = 2 self.layout = layout.IncrementalTextLayout(self...
def model_info(model, verbose=True): n_p = sum((x.numel() for x in model.parameters())) n_g = sum((x.numel() for x in model.parameters() if x.requires_grad)) device = next(model.parameters()).device if verbose: print(('%5s %60s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters...
def info_from_p2p_addr(addr: Multiaddr) -> PeerInfo: if (addr is None): raise InvalidAddrError('`addr` should not be `None`') parts = addr.split() if (not parts): raise InvalidAddrError(f'`parts`={parts} should at least have a protocol `P_P2P`') p2p_part = parts[(- 1)] last_protocol_...
.parametrize('method, signal, timeout', [('waitSignal', None, None), ('waitSignal', None, 1000), ('waitSignals', [], None), ('waitSignals', [], 1000), ('waitSignals', None, None), ('waitSignals', None, 1000)]) def test_signal_blocker_none(qtbot, method, signal, timeout): meth = getattr(qtbot, method) with pytes...
class TFVisualization(unittest.TestCase): def test_visualize_weight_ranges_single_layer(self): tf.compat.v1.reset_default_graph() _ = ResNet50(weights=None) model = tf.compat.v1.get_default_graph() init = tf.compat.v1.global_variables_initializer() sess = tf.compat.v1.Session...
.parametrize('dist_args, size, cm', [pytest.param([set_test_value(pt.dvector(), np.array([100000, 1, 1], dtype=np.float64))], None, contextlib.suppress()), pytest.param([set_test_value(pt.dmatrix(), np.array([[100000, 1, 1], [1, 100000, 1], [1, 1, 100000]], dtype=np.float64))], (10, 3), contextlib.suppress()), pytest.p...
def create_rand_tensors_given_shapes(input_shape: Union[(Tuple, List[Tuple])]) -> List[np.ndarray]: if isinstance(input_shape, List): input_shapes = input_shape else: input_shapes = [input_shape] rand_tensors = [] for shape in input_shapes: rand_tensors.append(np.random.rand(*sha...
.parametrize('transform, gcps, rpcs', [((Affine.identity() * Affine.scale(2.0)), None, None), (None, [rasterio.control.GroundControlPoint(0, 0, 0, 0, 0)], None), (None, None, gen_rpcs())]) def test_no_notgeoref_warning(transform, gcps, rpcs): with rasterio.MemoryFile() as mem: with mem.open(driver='GTiff', ...
.mosaiqdb def test_get_qcls_by_date(connection: pymedphys.mosaiq.Connection): a_completion_datetime = QCL_COMPLETED_DATETIMES[0] large_time_delta = np.timedelta64(90, 'D') start = (np.datetime64(a_completion_datetime) - large_time_delta) end = (np.datetime64(a_completion_datetime) + large_time_delta) ...
class SepConvLSTM2DCell(DropoutRNNCellMixin, Layer): def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), depth_multiplier=1, activation='tanh', recurrent_activation='hard_sigmoid', use_bias=True, kernel_initializer='glorot_uniform', recurrent_initializer...
class Prf(): DIGESTS_1 = {enums.HashId_1.MD5: (hashlib.md5, 16), enums.HashId_1.SHA: (hashlib.sha1, 20), enums.HashId_1.SHA2_256: (hashlib.sha256, 32), enums.HashId_1.SHA2_384: (hashlib.sha384, 48), enums.HashId_1.SHA2_512: (hashlib.sha512, 64)} DIGESTS = {enums.PrfId.PRF_HMAC_MD5: (hashlib.md5, 16), enums.PrfI...
() ('project_name') _tracking def init(project_name): print(f'Creating {project_name} template project') dir_path = os.path.dirname(os.path.realpath(__file__)) shutil.copytree(os.path.join(dir_path, 'dbt_template'), project_name) with open(f'{project_name}/dbt_project.yml', 'w') as f: f.write(re...
def final_i_index_finder(min_switch_ind, i_omega, m_omega): assert (type(min_switch_ind) == int), 'min_switch_ind should be an int.' assert (type(i_omega) == list), 'i_omega should be a list.' assert (type(m_omega) == list), 'm_omega should be a list.' final_i_index = np.searchsorted(i_omega, m_omega[mi...
class Extension(): persist = True def __init__(self, name: Optional[str]=None): self._name = (name or underscore(self.__class__.__name__)) def name(self): return self._name def flag(self) -> str: return f'--{dasherize(self.name)}' def help_text(self) -> str: if (self....
class CostFuncWrapper(): def __init__(self, maxeval=5000, progressbar=True, logp_func=None, dlogp_func=None): self.n_eval = 0 self.maxeval = maxeval self.logp_func = logp_func if (dlogp_func is None): self.use_gradient = False self.desc = 'logp = {:,.5g}' ...
.parametrize('username,password', users) .parametrize('project_id', projects) def test_list(db, client, username, password, project_id): client.login(username=username, password=password) url = reverse(urlnames['list'], args=[project_id]) response = client.get(url) if (project_id in view_snapshot_permis...
def solar_holiday_to_number(string) -> str: solar = {'': '11', '': '214', '': '22', '': '38', '': '312', '': '322', '': '41', '': '422', '': '423', '': '51', '': '54', '': '54', '': '512', '': '518', '': '519', '': '61', '': '71', '': '711', '': '81', '': '910', '': '918', '': '101', '': '118', '': '1117', '': '121...
def run(parser, args): from pyrocko import squirrel as sq squirrel = args.make_squirrel() kwargs = args.squirrel_query kinds = kwargs.pop('kind', sq.supported_content_kinds()) codes_query = kwargs.pop('codes', None) for kind in kinds: for (kind_id, codes, deltat, _, count) in sorted(squi...