code
stringlengths
281
23.7M
class TestRSAVerification(): .supported(only_if=(lambda backend: backend.rsa_padding_supported(padding.PKCS1v15())), skip_message='Does not support PKCS1v1.5.') .supported(only_if=(lambda backend: backend.signature_hash_supported(hashes.SHA1())), skip_message='Does not support SHA1 signature.') def test_pkc...
def export(preprocessor: Union[('PreTrainedTokenizer', 'FeatureExtractionMixin')], model: Union[('PreTrainedModel', 'TFPreTrainedModel')], config: OnnxConfig, opset: int, output: Path, tokenizer: 'PreTrainedTokenizer'=None) -> Tuple[(List[str], List[str])]: if (not (is_torch_available() or is_tf_available())): ...
def get_config(): (config, warnings, errors) = process_cline() (config, warnings, errors) = check_config(config, warnings, errors) for warning in warnings: print('WARNING:', warning) for error in errors: print('ERROR', error) if len(errors): sys.exit(2) if ('pass' not in ...
def _run_reader_iter(reader: Any, buf: bytes, do_eof: bool) -> Generator[(Any, None, None)]: while True: event = reader(buf) if (event is None): break (yield event) if (type(event) is EndOfMessage): break if do_eof: assert (not buf) (yield ...
def get_control_names(control, allcontrols, textcontrols): names = [] friendly_class_name = control.friendly_class_name() names.append(friendly_class_name) cleaned = control.window_text() if (cleaned and control.has_title): names.append(cleaned) names.append((cleaned + friendly_class...
class MongoDBCollector(diamond.collector.Collector): MAX_CRC32 = def __init__(self, *args, **kwargs): self.__totals = {} super(MongoDBCollector, self).__init__(*args, **kwargs) def get_default_config_help(self): config_help = super(MongoDBCollector, self).get_default_config_help() ...
def main(args): device = torch.device(('cuda' if (torch.cuda.is_available() and (not args.no_cuda)) else 'cpu')) n_gpu = torch.cuda.device_count() logger.info('device: {}, n_gpu: {}, 16-bits training: {}'.format(device, n_gpu, args.fp16)) random.seed(args.seed) np.random.seed(args.seed) torch.ma...
def test_teardown_logging(pytester: Pytester) -> None: pytester.makepyfile("\n import logging\n\n logger = logging.getLogger(__name__)\n\n def test_foo():\n logger.info('text going to logger from call')\n\n def teardown_function(function):\n logger.info('text going ...
def get_non_trading_days(start, end): non_trading_rules = [] start = canonicalize_datetime(start) end = canonicalize_datetime(end) weekends = rrule.rrule(rrule.YEARLY, byweekday=(rrule.SA, rrule.SU), cache=True, dtstart=start, until=end) non_trading_rules.append(weekends) new_years = rrule.rrule...
class variable_size_graph(): def __init__(self, task_parameters): vocab_size = task_parameters['Voc'] nb_of_clust = task_parameters['nb_clusters_target'] clust_size_min = task_parameters['size_min'] clust_size_max = task_parameters['size_max'] p = task_parameters['p'] ...
class BufferOperation(enum.IntFlag): discard_read_buffer = VI_READ_BUF discard_read_buffer_no_io = VI_READ_BUF_DISCARD flush_write_buffer = VI_WRITE_BUF discard_write_buffer = VI_WRITE_BUF_DISCARD discard_receive_buffer = VI_IO_IN_BUF_DISCARD discard_receive_buffer2 = VI_IO_IN_BUF flush_tran...
class TestWebsiteCollector(CollectorTestCase): def setUp(self, config=None): if (config is None): config = get_collector_config('WebsiteCollector', {'url': ''}) else: config = get_collector_config('WebsiteCollector', config) self.collector = WebsiteMonitorCollector(co...
def test_point_distance(): with pytest.raises(AssertionError): utils.point_distance([1, 2], [1, 2]) with pytest.raises(AssertionError): p = np.array([1, 2, 3]) utils.point_distance(p, p) p = np.array([1, 2]) assert (utils.point_distance(p, p) == 0) p1 = np.array([2, 2]) a...
class SwaggerDeprecatedTest(object): def test_doc_parser_parameters(self, api): parser = api.parser() parser.add_argument('param', type=int, help='Some param') with pytest.warns(DeprecationWarning): ('/with-parser/') class WithParserResource(restx.Resource): ...
class SeasonalTiltMount(pvsystem.AbstractMount): monthly_tilts: list surface_azimuth: float = 180.0 def get_orientation(self, solar_zenith, solar_azimuth): tilts = [self.monthly_tilts[(m - 1)] for m in solar_zenith.index.month] return pd.DataFrame({'surface_tilt': tilts, 'surface_azimuth': s...
class TestEnvVars(EnvironmentTestCase): def test_run_no_env(self, runner, target): env = self.run_environ(runner, *target, environ={'USER': 'romain'}) assert (env.get('USER') == 'romain') def test_run_env(self, runner, target): env = self.run_environ(runner, *target, '--env', 'USER=serio...
class ChainBiMapper(SequenceBiMapper): def __init__(self, first_layer: SequenceMapper, second_layer: SequenceMapper): self.first_layer = first_layer self.second_layer = second_layer def apply(self, is_train, x, mask=None): with tf.variable_scope('out'): m1 = self.first_layer....
def generate_packets() -> List[bytes]: out = DNSOutgoing((const._FLAGS_QR_RESPONSE | const._FLAGS_AA)) address = socket.inet_pton(socket.AF_INET, '192.168.208.5') additionals = [{'name': 'HASS Bridge ZJWH FF5137._hap._tcp.local.', 'address': address, 'port': 51832, 'text': b'\x13md=HASS Bridge ZJWH\x06pv=1....
class Config(): (frozen=True) class InvocationParams(): args: Tuple[(str, ...)] plugins: Optional[Sequence[Union[(str, _PluggyPlugin)]]] dir: Path def __init__(self, *, args: Iterable[str], plugins: Optional[Sequence[Union[(str, _PluggyPlugin)]]], dir: Path) -> None: ...
class Effect6098(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Missile Launcher Operation')), 'reloadTime', ship.getModifiedItemAttr('shipBonusTacticalDestroyerCaldari2'), skill='Caldari Tactic...
class Person(QObject): def __init__(self, parent=None): super(Person, self).__init__(parent) self._name = '' self._shoe = ShoeDescription() (str) def name(self): return self._name def name(self, name): self._name = name (ShoeDescription) def shoe(self): ...
class Request(Awaitable[W]): def __init__(self, pg: dist.ProcessGroup, device: torch.device) -> None: super().__init__() self.pg: dist.ProcessGroup = pg self.req: Optional[dist.Work] = None self.tensor: Optional[W] = None self.a2ai = None self.qcomm_ctx = None ...
def run_setup(setup_script, args): setup_dir = os.path.abspath(os.path.dirname(setup_script)) with setup_context(setup_dir): try: sys.argv[:] = ([setup_script] + list(args)) sys.path.insert(0, setup_dir) working_set.__init__() working_set.callbacks.append(...
class CIFAR10Policy(): def __init__(self, fillcolor=(128, 128, 128)): self.policies = [SubPolicy(0.1, 'invert', 7, 0.2, 'contrast', 6, fillcolor), SubPolicy(0.7, 'rotate', 2, 0.3, 'translateX', 9, fillcolor), SubPolicy(0.8, 'sharpness', 1, 0.9, 'sharpness', 3, fillcolor), SubPolicy(0.5, 'shearY', 8, 0.7, 't...
_session def test_runningmeanstd(): for (x1, x2, x3) in [(np.random.randn(3), np.random.randn(4), np.random.randn(5)), (np.random.randn(3, 2), np.random.randn(4, 2), np.random.randn(5, 2))]: rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:]) U.initialize() x = np.concatenate([x1, x2, x3],...
class FC(): _activations = {None: tf.identity, 'ReLU': tf.nn.relu, 'tanh': tf.tanh, 'sigmoid': tf.sigmoid, 'softmax': tf.nn.softmax, 'swish': (lambda x: (x * tf.sigmoid(x)))} def __init__(self, output_dim, input_dim=None, activation=None, weight_decay=None, ensemble_size=1): (self.input_dim, self.output...
def test_generator(game_enum): from randovania.generator.base_patches_factory import BasePatchesFactory from randovania.generator.hint_distributor import HintDistributor from randovania.resolver.bootstrap import Bootstrap g = game_enum.generator assert isinstance(g.bootstrap, Bootstrap) assert i...
def getDoomsdayMult(mod, tgt, distance, tgtSigRadius): modRange = mod.maxRange if ((distance is not None) and modRange and (distance > modRange)): return 0 if {'superWeaponAmarr', 'superWeaponCaldari', 'superWeaponGallente', 'superWeaponMinmatar'}.intersection(mod.item.effects): if (tgt.isFi...
def save_import_snapshot_values(project, snapshots, checked): for snapshot in snapshots: assert (snapshot.pk is None) snapshot.project = project snapshot.save(copy_values=False) for value in snapshot.snapshot_values: if value.attribute: value_key = f'{valu...
def test_read_psm3_map_variables(): (data, metadata) = psm3.read_psm3(MANUAL_TEST_DATA, map_variables=True) columns_mapped = ['Year', 'Month', 'Day', 'Hour', 'Minute', 'dhi', 'ghi', 'dni', 'ghi_clear', 'dhi_clear', 'dni_clear', 'Cloud Type', 'temp_dew', 'solar_zenith', 'Fill Flag', 'albedo', 'wind_speed', 'wind...
def test_replace_output_layer(): with tempfile.TemporaryDirectory() as tmp_dir: saved_model_dir = os.path.join(tmp_dir, 'saved_model') inp = tf.keras.layers.Input(shape=(2,)) x = tf.keras.layers.Dense(units=1)(inp) x = tf.keras.layers.Dense(units=2)(x) model = tf.keras.Model(...
class UnavailableSession(Session): session_issue: ClassVar[str] def __init__(self, *args, **kwargs) -> None: raise ValueError(self.session_issue) def _get_attribute(self, attr): raise NotImplementedError() def _set_attribute(self, attr, value): raise NotImplementedError() def...
def test_annotation_based_injection_works_in_provider_methods(): class MyModule(Module): def configure(self, binder): binder.bind(int, to=42) def provide_str(self, i: int) -> str: return str(i) def provide_object(self) -> object: return object() inject...
def torch_full(*args, **kwargs): args = list(args) if (isinstance(args[1], torch.Tensor) and (args[1].device == torch.device('meta'))): args[1] = 1 kwargs_without_device = dict(kwargs) kwargs_without_device.pop('device', None) return torch.full(*args, **kwargs_without_device)
class PeleeBranch2(nn.Module): def __init__(self, in_channels, out_channels, mid_channels): super(PeleeBranch2, self).__init__() self.conv1 = conv1x1_block(in_channels=in_channels, out_channels=mid_channels) self.conv2 = conv3x3_block(in_channels=mid_channels, out_channels=out_channels) ...
class MMGNet(): def __init__(self, config): self.config = config self.model_name = self.config.NAME self.mconfig = mconfig = config.MODEL self.exp = config.exp self.save_res = config.EVAL self.update_2d = config.update_2d dataset = None if (config.MODE...
('pypyr.steps.filewrite.Path') def test_filewrite_binary(mock_path): context = Context({'k1': 'v1', 'fileWrite': {'path': '/arb/blah', 'payload': b'one\ntwo\nthree', 'binary': True}}) with io.BytesIO() as out_bytes: with patch('pypyr.steps.filewrite.open', mock_open()) as mock_output: mock_o...
class DockerLexer(RegexLexer): name = 'Docker' url = ' aliases = ['docker', 'dockerfile'] filenames = ['Dockerfile', '*.docker'] mimetypes = ['text/x-dockerfile-config'] version_added = '2.0' _keywords = '(?:MAINTAINER|EXPOSE|WORKDIR|USER|STOPSIGNAL)' _bash_keywords = '(?:RUN|CMD|ENTRYPO...
def load_data(data_path, dataset, images): all_datas = {} for split in ['train', 'val', 'test']: datas = [] dropdata = 0 if (not os.path.exists(((data_path + split) + '.json'))): continue with open(((data_path + split) + '.json'), 'r', encoding='utf-8') as fin: ...
class Requirement(): def damage(self, current_resources: ResourceCollection, database: ResourceDatabase) -> int: raise NotImplementedError def satisfied(self, current_resources: ResourceCollection, current_energy: int, database: ResourceDatabase) -> bool: raise NotImplementedError def patch_...
class RepairCore(ABC): problemDectors: Dict[(str, ProblemDetector)] patchSynthesizers: Dict[(str, PatchSynthesizer)] def name(self) -> str: pass def __init__(self, clsProblemDectors: Iterable[Type[ProblemDetector]], clsPatchSynthesizers: Iterable[Type[PatchSynthesizer]], detectorArgs: Optional[D...
class TelemetryData(MutableMapping): def __init__(self, *args, **kwargs): self.store = dict() self.update(dict(*args, **kwargs)) def __getitem__(self, key): value = self.store[self.__keytransform__(key)] if isinstance(value, dict): return self.__class__(value) ...
class CoreAudioSource(StreamingSource): def __init__(self, filename, file=None): self._bl = None self._file = file self._deleted = False self._file_obj = None self._audfile = None self._audref = None audref = ExtAudioFileRef() if (file is None): ...
def get_example_models(): example_dir = os.path.join(os.path.dirname(__file__), '..', 'examples') for filename in os.listdir(example_dir): if (filename.endswith('.py') and (not filename.startswith('run_')) and (not filename.startswith('__'))): modelname = filename[:(- 3)] if ((mo...
class PandaRealSensed435Config(PandaDefaultConfig): def __init__(self) -> None: super().__init__() self.urdf_path = '{PACKAGE_ASSET_DIR}/descriptions/panda_v3.urdf' def cameras(self): return CameraConfig(uid='hand_camera', p=[0, 0, 0], q=[1, 0, 0, 0], width=128, height=128, fov=1.57, nea...
class Tokenizer(): def add_file_to_dictionary(filename, dict, tokenize, append_eos=True): with open(filename, 'r') as f: for line in f: for word in tokenize(line): dict.add_symbol(word) if append_eos: dict.add_symbol(dict.eo...
class Effect3961(BaseEffect): type = 'passive' def handler(fit, module, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Repair Systems')), 'armorDamageAmount', module.getModifiedItemAttr('subsystemBonusGallenteDefensive'), skill='Gallente Defensive...
def main(filename, save): data = pd.read_csv(filename) data = data[['hit_x', 'hit_y']] df = pd.DataFrame([]) df['hit_x'] = data['hit_x'] df['hit_y'] = data['hit_y'] df['hit_area'] = pd.Series(to_area(data['hit_x'], data['hit_y'])) df.to_csv(save, index=False, encoding='utf-8')
def _build_hint(parser: argparse.ArgumentParser, arg_action: argparse.Action) -> str: suppress_hint = arg_action.get_suppress_tab_hint() if (suppress_hint or (arg_action.help == argparse.SUPPRESS)): return '' else: formatter = parser._get_formatter() formatter.start_section('Hint') ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size...
def default_argument_parser(): parser = argparse.ArgumentParser(description='Detectron2 Training') parser.add_argument('--config-file', default='configs/smoke_gn_vector.yaml', metavar='FILE', help='path to config file') parser.add_argument('--eval-only', action='store_true', help='perform evaluation only') ...
class VoteStorage(): def __init__(self, request, name, rate): self.request = request self.name = name self.items = request.session.get(name, []) self.rate = rate def add(self, instance): self.items.append(instance.pk) self.request.session[self.name] = self.items ...
class StyleElementDescription(): def __init__(self, name, description, defaultFormat): self._name = name self._description = description self._defaultFormat = StyleFormat(defaultFormat) def __repr__(self): return ('<"%s": "%s">' % (self.name, self.defaultFormat)) def name(sel...
def test_classical_truth_table(): truth_table = [] for (c, t) in itertools.product([0, 1], repeat=2): (out_c, out_t) = CNOT().call_classically(ctrl=c, target=t) truth_table.append(((c, t), (out_c, out_t))) assert (truth_table == [((0, 0), (0, 0)), ((0, 1), (0, 1)), ((1, 0), (1, 1)), ((1, 1),...
class FeaturesManager(): _TASKS_TO_AUTOMODELS = {} _TASKS_TO_TF_AUTOMODELS = {} if is_torch_available(): _TASKS_TO_AUTOMODELS = {'default': AutoModel, 'masked-lm': AutoModelForMaskedLM, 'causal-lm': AutoModelForCausalLM, 'seq2seq-lm': AutoModelForSeq2SeqLM, 'sequence-classification': AutoModelForSeq...
def test_call_after_hooks_in_correct_order(hookregistry, mocker): data = [] (order=2) def second_hook(features): data.append(2) (order=1) def first_hook(step): data.append(1) hookregistry.call('after', 'all', False, mocker.MagicMock()) assert (data == [2, 1])
class TestAssert_reprcompare_attrsclass(): def test_attrs(self) -> None: class SimpleDataObject(): field_a = attr.ib() field_b = attr.ib() left = SimpleDataObject(1, 'b') right = SimpleDataObject(1, 'c') lines = callequal(left, right) assert (lines is ...
class Cipher(typing.Generic[Mode]): def __init__(self, algorithm: CipherAlgorithm, mode: Mode, backend: typing.Any=None) -> None: if (not isinstance(algorithm, CipherAlgorithm)): raise TypeError('Expected interface of CipherAlgorithm.') if (mode is not None): assert isinstanc...
def test_filewritejson_empty_path_raises(): context = Context({'fileWriteJson': {'path': None}}) with pytest.raises(KeyInContextHasNoValueError) as err_info: filewrite.run_step(context) assert (str(err_info.value) == "context['fileWriteJson']['path'] must have a value for pypyr.steps.filewritejson."...
_lazy('cudf') def _register_cudf(): import cudf (cudf.DataFrame) (cudf.Series) (cudf.BaseIndex) def proxify_device_object_cudf_dataframe(obj, proxied_id_to_proxy, found_proxies, excl_proxies): return proxify(obj, proxied_id_to_proxy, found_proxies) try: from dask.array.dispatch i...
class EdgeBlock(nn.Module): def __init__(self, in_chs, out_chs, dilation=1, bottle_ratio=0.5, groups=1, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_layer=None, drop_block=None, drop_path=0.0): super(EdgeBlock, self).__init__() mid_chs = int(round((out_chs * bottle_ratio))) ckwargs = d...
def test_compile_single_qubit_gates(): q = cirq.LineQubit(0) c1 = cirq.Circuit() for _ in range(10): c1.append((random.choice([cirq.X, cirq.Y, cirq.Z])(q) ** random.random())) c2 = compile_single_qubit_gates(c1) assert (c1 != c2) assert (len(c2) == 2) assert isinstance(c2[0].operatio...
class AtspiMeta(BaseMeta): control_type_to_cls = {} def __init__(cls, name, bases, attrs): BaseMeta.__init__(cls, name, bases, attrs) for t in cls._control_types: AtspiMeta.control_type_to_cls[t] = cls def find_wrapper(element): try: wrapper_match = AtspiMeta....
class PornhubCom(SimpleDownloader): __name__ = 'PornhubCom' __type__ = 'downloader' __version__ = '0.62' __status__ = 'testing' __pattern__ = ' __config__ = [('enabled', 'bool', 'Activated', True), ('use_premium', 'bool', 'Use premium account if available', True), ('fallback', 'bool', 'Fallback ...
class FacesDisplay(): def __init__(self, size, padding, tk_vars): logger.trace('Initializing %s: (size: %s, padding: %s, tk_vars: %s)', self.__class__.__name__, size, padding, tk_vars) self.size = size self.display_dims = (1, 1) self.tk_vars = tk_vars self.padding = padding ...
def test_exclude_glob(pytester: Pytester) -> None: hellodir = pytester.mkdir('hello') hellodir.joinpath('test_hello.py').write_text('x y syntaxerror', encoding='utf-8') hello2dir = pytester.mkdir('hello2') hello2dir.joinpath('test_hello2.py').write_text('x y syntaxerror', encoding='utf-8') hello3dir...
(host=st.one_of(st.ip_addresses(), st.text()), port=st.one_of(st.none(), st.integers()), raises=st.booleans()) def test_setup_url_for_address(host: str, port: (int | None), raises: bool) -> None: kwargs = {} if raises: kwargs['side_effect'] = gaierror else: kwargs['return_value'] = '127.0.0....
def statistics_match(df1, df2): matches = [] bounds = {'red_light': {'type': 'discrete', 'eps': 0.005}, 'hazard_stop': {'type': 'discrete', 'eps': 0.005}, 'speed_sign': {'type': 'discrete', 'eps': 0.005}, 'center_distance': {'type': 'cont', 'eps': 0.02}, 'relative_angle': {'type': 'cont', 'eps': 0.01}, 'veh_dis...
class ResNet18(chainer.Chain): def __init__(self): super(ResNet18, self).__init__(conv1_relu=ConvolutionBlock(1, 32), res2a_relu=ResidualBlock(32, 32), res2b_relu=ResidualBlock(32, 32), res3a_relu=ResidualBlockB(32, 64), res3b_relu=ResidualBlock(64, 64), res4a_relu=ResidualBlockB(64, 128), res4b_relu=Residu...
.parametrize('qurl, expected', [(QUrl('ftp://example.com/'), ('ftp', 'example.com', 21)), (QUrl('ftp://example.com:2121/'), ('ftp', 'example.com', 2121)), (QUrl(' (' 'qutebrowser.org', 8010)), (QUrl(' (' 'example.com', 443)), (QUrl(' (' 'example.com', 4343)), (QUrl(' (' 'qutebrowser.org', 80))]) def test_host_tuple_val...
def get_argument_parser(): parser = argparse.ArgumentParser() parser.add_argument('-a', '--all', action='store_const', const=True, default=False) parser.add_argument('-b', '--black', action='store_const', const=True, default=False) parser.add_argument('-f', '--flake', action='store_const', const=True, d...
def degrade(species, kdeg): def degrade_name_func(rule_expression): cps = rule_expression.reactant_pattern.complex_patterns return '_'.join((_complex_pattern_label(cp) for cp in cps)) if isinstance(species, Monomer): species = species() species = as_complex_pattern(species) retur...
def make_vocab(name, filenames, size, tokenizer, num_workers=1): if (name == 'source'): vocab = onmt.Dict([opt.src_pad_token, opt.src_unk_token, opt.src_bos_token, opt.src_eos_token], lower=opt.lower) elif (name == 'target'): vocab = onmt.Dict([opt.tgt_pad_token, opt.tgt_unk_token, opt.tgt_bos_t...
class _RopeConfigSource(Source): name: str = 'config.py' run_globals: Dict def __init__(self, ropefolder: Folder): self.ropefolder = ropefolder self.run_globals = {} def _read(self) -> bool: if ((self.ropefolder is None) or (not self.ropefolder.has_child('config.py'))): ...
class CLexer(object): def __init__(self, cparser): self.cparser = cparser self.type_names = set() def input(self, tokens): self.tokens = tokens self.pos = 0 def token(self): while (self.pos < len(self.tokens)): t = self.tokens[self.pos] self.po...
class SourceLinesAdapter(): def __init__(self, source_code): self.code = source_code self.starts = None self._initialize_line_starts() def _initialize_line_starts(self): self.starts = [] self.starts.append(0) try: i = 0 while True: ...
def kasten96_lt(airmass_absolute, precipitable_water, aod_bb): delta_cda = ((- 0.101) + (0.235 * (airmass_absolute ** (- 0.16)))) delta_w = ((0.112 * (airmass_absolute ** (- 0.55))) * (precipitable_water ** 0.34)) delta_a = aod_bb lt = (((- (9.4 + (0.9 * airmass_absolute))) * np.log(np.exp(((- airmass_a...
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv3d(1, 32, 3, padding=1) self.conv2 = nn.Conv3d(32, 32, 3, padding=1) self.conv3 = nn.Conv3d(32, 64, 3, padding=1) self.conv4 = nn.Conv3d(64, 64, 3, padding=1) self.conv5 = nn.Con...
.network def test_get_transform_grid_list__source_id(): grids = get_transform_grid_list(bbox=BBox(170, (- 90), (- 170), 90), source_id='us_noaa', include_already_downloaded=True) assert (len(grids) > 5) source_ids = set() for grid in grids: source_ids.add(grid['properties']['source_id']) ass...
def to_cpu(list_of_tensor): if isinstance(list_of_tensor[0], list): list_list_of_tensor = list_of_tensor list_of_tensor = [to_cpu(list_of_tensor) for list_of_tensor in list_list_of_tensor] else: list_of_tensor = [tensor.cpu() for tensor in list_of_tensor] return list_of_tensor
def wsproto_demo(host: str, port: int) -> None: print(f'Connecting to {host}:{port}') conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.connect((host, port)) print('Opening WebSocket') ws = WSConnection(ConnectionType.CLIENT) net_send(ws.send(Request(host=host, target='server')), con...
def test_hotstart(): HSF_PATH = MODEL_WEIR_SETTING_PATH.replace('.inp', '.hsf') if os.path.exists(HSF_PATH): os.remove(HSF_PATH) assert (not os.path.exists(HSF_PATH)) with Simulation(MODEL_WEIR_SETTING_PATH) as sim: J1 = Nodes(sim)['J1'] for (ind, step) in enumerate(sim): ...
class ChartElement(Element): def __init__(self, chart: Chart, figsize: Tuple[(float, float)]=None, dpi=250, optimise=False, grid_proportion=GridProportion.Eight, comment: str='', html_figsize: Tuple[(float, float)]=None, float_setting: str=None, **savefig_settings): super().__init__(grid_proportion) ...
_stabilize _specialize _rewriter([log]) def local_log1p(fgraph, node): if (node.op == log): (log_arg,) = node.inputs if (log_arg.owner and (log_arg.owner.op == add)): (scalars, scalar_inputs, nonconsts) = scalarconsts_rest(log_arg.owner.inputs, only_process_constants=True) if...
class CleoNamespaceNotFoundError(CleoUserError): def __init__(self, name: str, namespaces: (list[str] | None)=None) -> None: message = f'There are no commands in the "{name}" namespace.' if namespaces: suggestions = _suggest_similar_names(name, namespaces) if suggestions: ...
def test_index(stream): df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) a = DataFrame(example=df, stream=stream) b = (a.index + 5) L = b.stream.gather().sink_to_list() a.emit(df) a.emit(df) wait_for((lambda : (len(L) > 1)), timeout=2, period=0.05) assert_eq(L[0], (df.index + 5)) ...
def channel_deposit_with_the_same_token_network(deposit_queue: List[ChannelDeposit]) -> None: while deposit_queue: to_delete = [] for (pos, channel_deposit) in enumerate(deposit_queue): channel = channel_details(channel_deposit.endpoint, channel_deposit.token_address, channel_deposit.par...
.parametrize('shape', [(), (3, 4)]) .parametrize('dtype', [None, torch.float, torch.double, torch.int]) .parametrize('device', ([None] + get_available_devices())) .parametrize('from_path', [True, False]) class TestConstructors(): .parametrize('shape_arg', ['expand', 'arg', 'kwarg']) def test_zeros(self, shape, ...
def evaluate(ground_truth_path, result_path, subset, top_k, ignore): (ground_truth, class_labels_map) = load_ground_truth(ground_truth_path, subset) result = load_result(result_path, top_k, class_labels_map) n_ground_truth = len(ground_truth) ground_truth = remove_nonexistent_ground_truth(ground_truth, ...
class ErrorCode(enum.Enum): bad_star_import = 1 cant_import = 2 unexpected_node = 3 undefined_name = 4 undefined_attribute = 5 attribute_is_never_set = 6 duplicate_dict_key = 7 unhashable_key = 8 bad_unpack = 9 unsupported_operation = 10 not_callable = 11 incompatible_cal...
def test_scenarios_none_found(pytester, pytest_params): testpath = pytester.makepyfile("\n import pytest\n from pytest_bdd import scenarios\n\n scenarios('.')\n ") result = pytester.runpytest_subprocess(testpath, *pytest_params) result.assert_outcomes(errors=1) result.stdout.fnma...
class PLMSSampler(object): def __init__(self, model, schedule='linear', **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if (type(attr) == torch.Tensor): ...
class StateActionDynEVAE(nn.Module): def __init__(self, traj_size, action_embed_size, state_embed_size, stack=4): super().__init__() self.traj_size = traj_size self.action_embed_size = action_embed_size self.state_embed_size = state_embed_size self.stack = stack self....
def create_train_state(model: FlaxAutoModelForSequenceClassification, learning_rate_fn: Callable[([int], float)], is_regression: bool, num_labels: int, weight_decay: float) -> train_state.TrainState: class TrainState(train_state.TrainState): logits_fn: Callable = struct.field(pytree_node=False) loss...
def test_get_module_raises(): with pytest.raises(PyModuleNotFoundError) as err: moduleloader.get_module('unlikelyblahmodulenameherexxssz') assert (str(err.value) == "unlikelyblahmodulenameherexxssz.py should be in your pipeline dir, or in your working dir, or it should be installed in the current python...
def construct_odenet(dims): layers = [] for (in_dim, out_dim) in zip(dims[:(- 1)], dims[1:]): layers.append(diffeq_layers.ConcatLinear(in_dim, out_dim)) layers.append(basic_layers.TimeDependentSwish(out_dim)) layers = layers[:(- 1)] return container_layers.SequentialDiffEq(*layers)
class LxDeviceListClass(gdb.Command): def __init__(self): super(LxDeviceListClass, self).__init__('lx-device-list-class', gdb.COMMAND_DATA) def invoke(self, arg, from_tty): if (not arg): for cls in for_each_class(): gdb.write('class {}:\t{}\n'.format(cls['name'].strin...
class Signature(Generic[T]): def __init__(self) -> None: self.pos: list[T] = [] self.kwonly: dict[(str, T)] = {} self.varpos: (T | None) = None self.varkw: (T | None) = None def __str__(self) -> str: def get_name(arg: Any) -> str: if isinstance(arg, inspect.Pa...
def assert_column_equality(output_df: DataFrame, target_df: DataFrame, output_column: Column, target_column: Column) -> None: if (not ((output_df.select(output_column).count() == target_df.select(target_column).count()) and (len(target_df.columns) == len(output_df.columns)))): raise AssertionError(f'''DataF...
class DataCollatorForWav2Vec2Pretraining(): model: Wav2Vec2ForPreTraining feature_extractor: Wav2Vec2FeatureExtractor padding: Union[(bool, str)] = 'longest' pad_to_multiple_of: Optional[int] = None max_length: Optional[int] = None def __call__(self, features: List[Dict[(str, Union[(List[int], t...