code
stringlengths
281
23.7M
def setup_model_and_optimizer(model_provider_func): args = get_args() model = get_model(model_provider_func) optimizer = get_optimizer(model) lr_scheduler = get_learning_rate_scheduler(optimizer) if (args.load is not None): args.iteration = load_checkpoint(model, optimizer, lr_scheduler) ...
('view') def view() -> None: try: container_list = get_list_environments() if (not container_list): print(':computer: No freshenv environments found.') for container in container_list: if ('Exited' in container.get('Status')): img = ':arrow_down: ' ...
_small_list(immutable=True, unbox_num=True) class W_ImpVectorStar(W_InterposeVector): import_from_mixin(ImpersonatorMixin) errorname = 'impersonate-vector' def self_arg(self): return True def post_set_cont(self, new, i, env, cont, app=None): return imp_vec_set_cont(self.inner, i, app, en...
class ConstantType(click.ParamType): name = 'SMILES' def convert(self, value, param, ctx): if (not isinstance(value, str)): return value try: (mol, frags) = parse_smiles_then_fragment(value) if (not (1 <= len(frags) <= 3)): raise MolProcessingE...
(frozen=True) class FakeCommand(): name: str = '' desc: str = '' hide: bool = False debug: bool = False deprecated: bool = False completion: Any = None maxsplit: int = None takes_count: Callable[([], bool)] = (lambda : False) modes: Tuple[usertypes.KeyMode] = (usertypes.KeyMode.norma...
.parametrize('username,password', users) .parametrize('issue_id', issues) def test_update(db, client, username, password, issue_id): client.login(username=username, password=password) url = reverse(urlnames['detail'], args=[issue_id]) data = {} response = client.put(url, data, content_type='application/...
def my_syscall_write(ql: Qiling, fd: int, buf: int, count: int): try: data = ql.mem.read(buf, count) fobj = ql.os.fd[fd] if hasattr(fobj, 'write'): fobj.write(data) except: ret = (- 1) else: ret = count ql.log.info(f'my_syscall_write({fd}, {buf:#x}, {c...
class SeqEntityScore(object): def __init__(self, id2label, markup='bio'): self.id2label = id2label self.markup = markup self.reset() def reset(self): self.origins = [] self.founds = [] self.rights = [] def compute(self, origin, found, right): recall = ...
_REGISTRY.register() class bjzBlack(bjzStation, ImageDataset): dataset_name = 'bjzblack' def __init__(self, root='datasets'): self.root = root self.dataset_dir = osp.join(self.root, self.dataset_dir) self.query_dir = osp.join(self.dataset_dir, 'benchmark/black_general_reid/query') ...
class ArchX86(Arch): def __init__(self): super().__init__() def arch_insn_size(self): return 15 def regs(self): return ('eax', 'ebx', 'ecx', 'edx', 'esp', 'ebp', 'esi', 'edi', 'eip', 'ss', 'cs', 'ds', 'es', 'fs', 'gs', 'eflags') def read_insn(self, address: int) -> bytes: ...
class FakeNetCDF4FileHandlerMimicLow(FakeNetCDF4FileHandler): def get_test_content(self, filename, filename_info, filetype_info): dt_s = filename_info.get('start_time', DEFAULT_DATE) dt_e = filename_info.get('end_time', DEFAULT_DATE) if (filetype_info['file_type'] == 'mimicTPW2_comp'): ...
def bit_mask_of_modes_acted_on_by_fermionic_terms(fermion_term_list, n_qubits=None): if (n_qubits is None): n_qubits = 0 for term in fermion_term_list: n_qubits = max(n_qubits, count_qubits(term)) mask = numpy.zeros((n_qubits, len(fermion_term_list)), dtype=bool) for (term_number...
class TestFactoryMethods(): def test_empty(self, shape, density): nnz = (int(((shape[0] * shape[1]) * density)) or 1) base = csr.empty(shape[0], shape[1], nnz) sci = base.as_scipy(full=True) assert isinstance(base, data.CSR) assert isinstance(sci, scipy.sparse.csr_matrix) ...
def join_user_profile(user_profile_file, behavior_file, joined_file): user_profile_dict = {} with open(user_profile_file, 'r') as f: for line in f: (uid, aid, gid) = line[:(- 1)].split(',') user_profile_dict[uid] = ','.join([aid, gid]) newlines = [] with open(behavior_fil...
_module() class MobileNetV2(nn.Module): arch_settings = [[1, 16, 1], [6, 24, 2], [6, 32, 3], [6, 64, 4], [6, 96, 3], [6, 160, 3], [6, 320, 1]] def __init__(self, widen_factor=1.0, strides=(1, 2, 2, 2, 1, 2, 1), dilations=(1, 1, 1, 1, 1, 1, 1), out_indices=(1, 2, 4, 6), frozen_stages=(- 1), conv_cfg=None, norm_c...
class C(nn.Module): def __init__(self, nIn, nOut, kSize, stride=1): super().__init__() padding = int(((kSize - 1) / 2)) self.conv = nn.Conv2d(nIn, nOut, (kSize, kSize), stride=stride, padding=(padding, padding), bias=False) def forward(self, input): output = self.conv(input) ...
def attack_one_batch(sess, ops, attacked_data): is_training = False attacked_label = (np.ones(shape=len(attacked_data), dtype=int) * TARGET) attacked_label = np.squeeze(attacked_label) lower_bound = np.zeros(BATCH_SIZE) WEIGHT = (np.ones(BATCH_SIZE) * INITIAL_WEIGHT) upper_bound = (np.ones(BATCH...
def mpl_time_axis(axes, approx_ticks=5.0): from matplotlib.ticker import Locator, Formatter class labeled_float(float): pass class TimeLocator(Locator): def __init__(self, approx_ticks=5.0): self._approx_ticks = approx_ticks Locator.__init__(self) def __call__...
def eval_adv_test_blackbox(model_target, model_source, device, test_loader): model_target.eval() model_source.eval() robust_err_total = 0 natural_err_total = 0 for (data, target) in test_loader: (data, target) = (data.to(device), target.to(device)) (X, y) = (Variable(data, requires_g...
def test_abi_label_convertor(): tmp_dir = tempfile.TemporaryDirectory() dict_file = osp.join(tmp_dir.name, 'fake_dict.txt') _create_dummy_dict_file(dict_file) label_convertor = ABIConvertor(dict_file=dict_file, max_seq_len=10) label_convertor.end_idx strings = ['hell'] targets_dict = label_c...
def test_calculate_ssim(): with pytest.raises(AssertionError): calculate_ssim(np.ones((16, 16)), np.ones((10, 10)), crop_border=0) with pytest.raises(ValueError): calculate_ssim(np.ones((16, 16)), np.ones((16, 16)), crop_border=1, input_order='WRONG') out = calculate_ssim(np.ones((10, 10, 3)...
def test_trustme_cli_expires_on(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.chdir(tmp_path) main(argv=['--expires-on', '2035-03-01']) assert tmp_path.joinpath('server.key').exists() assert tmp_path.joinpath('server.pem').exists() assert tmp_path.joinpath('client.pem').exist...
.skipif((not modeltest.HAS_QT_TESTER), reason='No Qt modeltester available') def test_qt_tester_invalid(testdir): testdir.makeini('\n [pytest]\n qt_log_level_fail = NO\n ') testdir.makepyfile('\n from pytestqt.qt_compat import qt_api\n from pytestqt import modeltest\n\n ass...
def read_validation_evaluation_run(save_dir: str) -> Optional[EvaluationRun]: save_path = os.path.join(save_dir, VALIDATION_EVALUATION_DIR, EVALUATION_RUN_PICKLE_FILE_NAME) if (not os.path.exists(save_path)): return None with open(save_path, 'rb') as pkl_file: return pickle.load(pkl_file)
def _normalize(x, params, forward=True): assert ('scale' in params) if isinstance(x, np.ndarray): x = torch.from_numpy(x) scale = params['scale'] offset = params['offset'] x = x.to(device=scale.device, dtype=scale.dtype) src_shape = x.shape x = x.reshape((- 1), scale.shape[0]) if...
.supported(only_if=(lambda backend: backend.ed25519_supported()), skip_message='Requires OpenSSL with Ed25519 support') _tests('eddsa_test.json') def test_ed25519_signature(backend, wycheproof): assert (wycheproof.testgroup['key']['curve'] == 'edwards25519') key = Ed25519PublicKey.from_public_bytes(binascii.unh...
class TestConvModuleMeta(): def test_main(self): conv_module_meta = {'kernel_size': (2,), 'stride': (3,), 'padding': (4,), 'dilation': (5,)} x = make_conv_module(nn.Conv1d, **conv_module_meta) actual = meta.conv_module_meta(x) desired = conv_module_meta assert (actual == desi...
class DynamicImportPatchTest(TestPyfakefsUnittestBase): def __init__(self, methodName='runTest'): super(DynamicImportPatchTest, self).__init__(methodName) def test_os_patch(self): import os os.mkdir('test') self.assertTrue(self.fs.exists('test')) self.assertTrue(os.path.e...
def transcribe(audio, speech2text=None, config=None): if (config is None): config = TranscribeConfig() if (speech2text is None): speech2text = load_default_model() if isinstance(audio, str): audio = librosa.load(audio, sr=config.samplerate)[0] nsamples = len(audio) pos = 0 ...
class FSDPStrategy(Strategy): process_group: Optional[ProcessGroup] = None sharding_strategy: Optional[ShardingStrategy] = None cpu_offload: Optional[CPUOffload] = None auto_wrap_policy: Optional[Callable[([torch.nn.Module, bool, int], bool)]] = None backward_prefetch: Optional[BackwardPrefetch] = B...
class ReconnectLDAPObject(SimpleLDAPObject): __transient_attrs__ = {'_l', '_ldap_object_lock', '_trace_file', '_reconnect_lock', '_last_bind'} def __init__(self, uri, trace_level=0, trace_file=None, trace_stack_limit=5, bytes_mode=None, bytes_strictness=None, retry_max=1, retry_delay=60.0, fileno=None): ...
class ResUnit(nn.Module): def __init__(self, in_channels, out_channels, stride, padding=1, dilation=1, bottleneck=True, conv1_stride=False): super(ResUnit, self).__init__() self.resize_identity = ((in_channels != out_channels) or (stride != 1)) if bottleneck: self.body = ResBottl...
def main(): args = parse_args() root_path = args.root_path split_info = mmcv.load(osp.join(root_path, 'annotations', 'train_valid_test_split.json')) split_info['training'] = split_info.pop('train') split_info['val'] = split_info.pop('valid') for split in ['training', 'val', 'test']: prin...
def _read_spotting_detections_and_labels(args: Dict, num_classes: int) -> Tuple[(List[np.ndarray], List[np.ndarray])]: splits_dir = Path(args[ARGS_SPLITS_DIR]) results_dir = Path(args[ARGS_RESULTS_DIR]) labels_dir = Path(args[ARGS_LABELS_DIR]) features_dir = Path(args[ARGS_FEATURES_DIR]) game_one_ho...
def _list_paths_with_resource(game, print_only_area: bool, resource: ResourceInfo, needed_quantity: (int | None)): from randovania.game_description.game_description import GameDescription count = 0 game = typing.cast(GameDescription, game) for area in game.region_list.all_areas: area_had_resourc...
class Selector(Layer): def __init__(self, select, **kwargs): super(Selector, self).__init__(**kwargs) self.select = select self.select_neuron = K.constant(value=self.select) def build(self, input_shape): super(Selector, self).build(input_shape) def call(self, x): retu...
(nodes.TypeAlias) def verify_typealias(stub: nodes.TypeAlias, runtime: MaybeMissing[Any], object_path: list[str]) -> Iterator[Error]: stub_target = mypy.types.get_proper_type(stub.target) stub_desc = f'Type alias for {stub_target}' if isinstance(runtime, Missing): (yield Error(object_path, 'is not p...
class PFContextMenuPref(PreferenceView): def populatePanel(self, panel): self.title = _t('Context Menus') self.settings = ContextMenuSettings.getInstance() self.mainFrame = gui.mainFrame.MainFrame.getInstance() self.dirtySettings = False mainSizer = wx.BoxSizer(wx.VERTICAL) ...
def test_lowest_common_ancestor(graph_nodes, test_instance, root=None): leaves = imagenet_spec.get_leaves(graph_nodes) for _ in range(10000): first_ind = np.random.randint(len(leaves)) second_ind = np.random.randint(len(leaves)) while (first_ind == second_ind): second_ind = n...
class inconv(nn.Module): def __init__(self, in_ch, out_ch, kernel_size=[3, 3, 3], block=BasicBlock, norm=nn.BatchNorm3d): super().__init__() if isinstance(kernel_size, int): kernel_size = ([kernel_size] * 3) pad_size = [(i // 2) for i in kernel_size] self.conv1 = nn.Conv3...
def search(word, exact=True, return_words=True, cache=True): response_text = request_search(word, cache=cache) soup = bs4.BeautifulSoup(response_text, 'html.parser') definitions = soup.find_all('h2', class_='vignette__title') if (definitions is None): return [] urlnames = [] for definiti...
def test_parameterized_types(hive_client): hms = HMS(hive_client) client = HiveMetastoreClient(hms) table = client.schema('test_db', 'test_table3') fields = table.fields assert (len(fields) == 7) assert (fields[0].extra_attrs['name'] == 'col16') assert isinstance(fields[0], UnionType) as...
def update_last_accessed(token_or_user): if (not config.app_config.get('FEATURE_USER_LAST_ACCESSED')): return threshold = timedelta(seconds=config.app_config.get('LAST_ACCESSED_UPDATE_THRESHOLD_S', 120)) if ((token_or_user.last_accessed is not None) and ((datetime.utcnow() - token_or_user.last_acces...
def _create_walkable_graph(state: EnvironmentState): doors = state.get_nodes_by_attr('class_name', 'door') doorjambs = state.get_nodes_by_attr('class_name', 'doorjamb') adj_lists = {} for door_node in doors: door_rooms = state.get_nodes_from(door_node, Relation.BETWEEN) if (len(door_room...
() def eggs_clean(context): with context.cd(TASK_ROOT_STR): dirs = set() dirs.add('.eggs') for name in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs)
def get_nuScenes_label_name(label_mapping): with open(label_mapping, 'r') as stream: nuScenesyaml = yaml.safe_load(stream) nuScenes_label_name = dict() for i in sorted(list(nuScenesyaml['learning_map'].keys()))[::(- 1)]: val_ = nuScenesyaml['learning_map'][i] nuScenes_label_name[val_...
_wraps(_stdlib_socket.socketpair, assigned=(), updated=()) def socketpair(family: FamilyT=FamilyDefault, type: TypeT=SocketKind.SOCK_STREAM, proto: int=0) -> tuple[(SocketType, SocketType)]: (left, right) = _stdlib_socket.socketpair(family, type, proto) return (from_stdlib_socket(left), from_stdlib_socket(right...
class ConfigOptionsHandler(ConfigHandler['Distribution']): section_prefix = 'options' def __init__(self, target_obj: 'Distribution', options: AllCommandOptions, ignore_option_errors: bool, ensure_discovered: expand.EnsurePackagesDiscovered): super().__init__(target_obj, options, ignore_option_errors, en...
class RegexTest(object): .parametrize('value', ['123', '', '00000']) def test_valid_input(self, value): num_only = inputs.regex('^[0-9]+$') assert (num_only(value) == value) .parametrize('value', ['abc', '123abc', 'abc123', '']) def test_bad_input(self, value): num_only = inputs....
def main(): config = read_config(sys.argv[1]) if ('logging' in config): logging.config.dictConfig(config['logging']) else: logging.basicConfig(level=logging.INFO) downloader = Downloader(config) db = SQLiteTLE(config['database']['path'], config['platforms'], config['text_writer']) ...
def rouge(hypotheses, references): hyps_and_refs = zip(hypotheses, references) hyps_and_refs = [_ for _ in hyps_and_refs if (len(_[0]) > 0)] (hypotheses, references) = zip(*hyps_and_refs) rouge_1 = [rouge_n([hyp], [ref], 1) for (hyp, ref) in zip(hypotheses, references)] rouge_2 = [rouge_n([hyp], [re...
class SvgDraggablePoint(gui.SvgRectangle, DraggableItem): def __init__(self, app_instance, name_coord_x, name_coord_y, compatibility_iterable, **kwargs): self.w = 15 self.h = 15 super(SvgDraggablePoint, self).__init__(0, 0, self.w, self.h, **kwargs) DraggableItem.__init__(self, app_i...
.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_integration_per...
class SYSTEM_PROCESS_INFORMATION(Structure): _fields_ = [('NextEntryOffset', ULONG), ('NumberOfThreads', ULONG), ('WorkingSetPrivate', LARGE_INTEGER), ('HardFaultCount', ULONG), ('NumberOfThreadsHighWatermark', ULONG), ('CycleTime', c_ulonglong), ('CreateTime', LARGE_INTEGER), ('UserTime', LARGE_INTEGER), ('KernelT...
class Describe_NumberingDefinitions(): def it_knows_how_many_numbering_definitions_it_contains(self, len_fixture): (numbering_definitions, numbering_definition_count) = len_fixture assert (len(numbering_definitions) == numbering_definition_count) (params=[0, 1, 2, 3]) def len_fixture(self, r...
def test_exit(manager_nospawn, minimal_conf_noscreen): qewidget = widget.QuickExit(timer_interval=0.001, countdown_start=1) config = minimal_conf_noscreen config.screens = [libqtile.config.Screen(top=libqtile.bar.Bar([qewidget], 10))] manager_nospawn.start(config) topbar = manager_nospawn.c.bar['top...
def make_loop_careduce(loop_orders, dtypes, loop_tasks, sub): def loop_over(preloop, code, indices, i): iterv = f'ITER_{int(i)}' update = '' suitable_n = '1' for (j, index) in enumerate(indices): var = sub[f'lv{int(j)}'] update += f'''{var}_iter += {var}_jump{...
class Venue(Object): def __init__(self, *, client: 'pyrogram.Client'=None, location: 'types.Location', title: str, address: str, foursquare_id: str=None, foursquare_type: str=None): super().__init__(client) self.location = location self.title = title self.address = address se...
class VariationalEncoderDecoderGen(keras.utils.Sequence): def __init__(self, feature_root, modalities, split_root, phase, batch_size, shuffle=True): assert (phase in ['train', 'val', 'test']), 'phase must be one of train, val, test!' index_path = os.path.join(split_root, '{}.txt'.format(phase)) ...
def test_unicode_issue368(pytester: Pytester) -> None: path = pytester.path.joinpath('test.xml') log = LogXML(str(path), None) ustr = '!' class Report(BaseReport): longrepr = ustr sections: List[Tuple[(str, str)]] = [] nodeid = 'something' location = ('tests/filename.py',...
def test_load_adaptor_twice(): old_sys_path = sys.path path = os.path.split(os.path.abspath(__file__))[0] sys.path.append(path) Engine()._load_adaptors(['mockadaptor_enabled', 'mockadaptor_enabled']) cpis = Engine().loaded_adaptors() mocks = cpis['radical.saga.job.Job']['mock'] assert (len(m...
def add_verbosity_args(parser, train=False): verbosity_group = parser.add_argument_group('Verbosity') verbosity_group.add_argument('--log-verbose', action='store_true', help='Whether to output more verbose logs for debugging/profiling.') verbosity_group.add_argument('--args-verbosity', default=1, type=int, ...
def negative_sampling(pos_samples, num_entity, negative_rate): size_of_batch = len(pos_samples) num_to_generate = (size_of_batch * negative_rate) neg_samples = np.tile(pos_samples, (negative_rate, 1)) labels = np.zeros((size_of_batch * (negative_rate + 1)), dtype=np.float32) labels[:size_of_batch] =...
def main(): multiprocessing.freeze_support() import randovania randovania.setup_logging('INFO', None, quiet=True) logging.debug('Starting Randovania...') dotnet_path = randovania.get_data_path().joinpath('dotnet_runtime') if (randovania.is_frozen() and dotnet_path.exists()): os.environ['...
class PreActivationBottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(PreActivationBottleneck, self).__init__() self.bn1 = nn.BatchNorm3d(inplanes) self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False) self.bn...
def make_layers(cfg, batch_norm=False, deconv=None): layers = [] in_channels = 3 if (not deconv): for v in cfg: if (v == 'M'): layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) ...
def _get_ticklabels(band_type, kHz, separator): if (separator is None): import locale separator = locale.localeconv()['decimal_point'] if (band_type == 'octave'): if (kHz is True): ticklabels = TICKS_OCTAVE_KHZ else: ticklabels = TICKS_OCTAVE elif (kHz...
class PassportElementErrorSelfie(PassportElementError): __slots__ = ('file_hash',) def __init__(self, type: str, file_hash: str, message: str, *, api_kwargs: Optional[JSONDict]=None): super().__init__('selfie', type, message, api_kwargs=api_kwargs) with self._unfrozen(): self.file_ha...
def get_service_ips_and_ports(component_name): try: get_service_cmd = ['kubectl', 'get', 'service', component_name, '-o', 'json'] service_spec = subprocess.check_output(get_service_cmd).strip().decode('UTF-8') spec = json.loads(service_spec) external_ips = spec['spec'].get('externalI...
class Conv2d_Atari(nn.Module): def __init__(self, in_channels=4, feature_dim=512): super().__init__() self.conv1 = layer_init(nn.Conv2d(in_channels, 32, kernel_size=8, stride=4)) self.conv2 = layer_init(nn.Conv2d(32, 64, kernel_size=4, stride=2)) self.conv3 = layer_init(nn.Conv2d(64,...
class Win32Raw(Escpos): def is_usable() -> bool: return is_usable() _win32print def __init__(self, printer_name: str='', *args, **kwargs) -> None: Escpos.__init__(self, *args, **kwargs) self.printer_name = printer_name self.job_name = '' self._device: Union[(Literal[F...
('PyQt6.QtWidgets.QGraphicsPixmapItem.keyPressEvent') def test_key_press_event_other(key_mock, qapp, item): item.exit_crop_mode = MagicMock() event = MagicMock() event.key.return_value = Qt.Key.Key_Space item.keyPressEvent(event) item.exit_crop_mode.assert_not_called() key_mock.assert_called_onc...
class BacktestPositionFactory(): def create_position(ticker: Ticker) -> BacktestPosition: sec_type = ticker.security_type if (sec_type == SecurityType.STOCK): return BacktestEquityPosition(ticker) elif (sec_type == SecurityType.FUTURE): return BacktestFuturePosition(t...
def run_gat_target(args, device, data): (train_g, val_g, test_g, in_feats, labels, n_classes, g, num_heads) = data train_nid = train_g.nodes() val_nid = val_g.nodes() test_nid = test_g.nodes() sampler = dgl.dataloading.MultiLayerNeighborSampler([int(fanout) for fanout in args.fan_out.split(',')]) ...
def get_files(**kwargs): relative_root = kwargs.get('relative_root', '') files = [File(Path(relative_root, f.path), f.contents) for f in get_template_files(**kwargs)] files.extend((File(Path(relative_root, kwargs['package_name'], 'lib.so'), ''), File(Path(relative_root, '.hgignore'), 'syntax: glob\n*.pyc\n\...
.end_to_end() .skipif((not _TEST_SHOULD_RUN), reason='pygraphviz is required') .parametrize('layout', _GRAPH_LAYOUTS) .parametrize('format_', _TEST_FORMATS) .parametrize('rankdir', ['LR']) def test_create_graph_via_cli(tmp_path, runner, format_, layout, rankdir): if ((sys.platform == 'win32') and (format_ == 'pdf')...
class SmtLib20Parser(SmtLibParser): def __init__(self, environment=None, interactive=False): SmtLibParser.__init__(self, environment, interactive) del self.commands['check-sat-assuming'] del self.commands['declare-const'] del self.commands['define-fun-rec'] del self.commands[...
def SelectPeakIndex(FFT_Data, endpoint=True): D1 = (FFT_Data[1:(- 1)] - FFT_Data[0:(- 2)]) D2 = (FFT_Data[1:(- 1)] - FFT_Data[2:]) D3 = np.logical_and((D1 > 0), (D2 > 0)) tmp = np.where((D3 == True)) sel_ind = (tmp[0] + 1) if endpoint: if ((FFT_Data[0] - FFT_Data[1]) > 0): se...
class ConcatInternalConnectivity(InternalConnectivity): def __init__(self, input_mask_and_length_tuple: List[Tuple[(List, int)]], output_mask_and_length_tuple: List[Tuple[(List, int)]]): assert (len(input_mask_and_length_tuple) > 1) assert (len(output_mask_and_length_tuple) == 1) super().__i...
class VanillaOption(Instrument): def __init__(self, option_type, expiry_type, strike, expiry_date, derivative_type): self.option_type = (option_type or VanillaOptionType.CALL.value) self.expiry_type = (expiry_type or ExpiryType.EUROPEAN.value) self.strike = strike self.expiry_date = ...
def listen_cli(args): dicom_listener = DicomListener(host=args.host, port=args.port, ae_title=args.aetitle, storage_directory=args.storage_directory) logging.info('Starting DICOM listener') logging.info('IP: %s', args.host) logging.info('Port: %s', args.port) logging.info('AE Title: %s', args.aetitl...
class TestInterpreterVersion(): def test_warn(self, monkeypatch): class MockConfigVar(): def __init__(self, return_): self.warn = None self._return = return_ def __call__(self, name, warn): self.warn = warn return self._...
class CIFARPyramidNet(nn.Module): def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), num_classes=10): super(CIFARPyramidNet, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() self...
def parse_args(): parser = argparse.ArgumentParser(description='Collect data to be submitted to the server') group = parser.add_mutually_exclusive_group() group.add_argument('--plugins', action='store_true', help='Only run plugins (no commands)') group.add_argument('--commands', action='store_true', hel...
_fixtures(WebFixture) def test_activating_javascript(web_fixture): (Widget) class WidgetWithJavaScript(Widget): def __init__(self, view, fake_js): super().__init__(view) self.fake_js = fake_js def get_js(self, context=None): return [self.fake_js] class MyP...
class MultiWozV22(datasets.GeneratorBasedBuilder): VERSION = datasets.Version('2.2.0') def _info(self): features = datasets.Features({'dialogue_id': datasets.Value('string'), 'db_root_path': datasets.Value('string'), 'services': datasets.Sequence(datasets.Value('string')), 'db_paths': datasets.Sequence(...
class HeisenbergModel(LatticeModel): def __init__(self, lattice: Lattice, coupling_constants: tuple=(1.0, 1.0, 1.0), ext_magnetic_field: tuple=(0.0, 0.0, 0.0)) -> None: super().__init__(lattice) self.coupling_constants = coupling_constants self.ext_magnetic_field = ext_magnetic_field def...
def any_causes_overload_ambiguity(items: list[CallableType], return_types: list[Type], arg_types: list[Type], arg_kinds: list[ArgKind], arg_names: (Sequence[(str | None)] | None)) -> bool: if all_same_types(return_types): return False actual_to_formal = [map_formals_to_actuals(arg_kinds, arg_names, item...
class Cache(): def __init__(self, cache_file_location: str='.pyspark_ai.json', file_format: str='json'): self._staging_updates: Dict[(str, str)] = {} if (file_format == 'json'): self._file_cache: FileCache = JsonCache(cache_file_location) else: self._file_cache = SQLi...
class TestExpandXarrayDims(object): def setup_method(self): self.test_inst = pysat.Instrument(inst_module=pysat.instruments.pysat_ndtesting, use_header=True) self.start_time = pysat.instruments.pysat_ndtesting._test_dates[''][''] self.data_list = [] self.out = None self.meta ...
def evaluate(instruction, input=None, temperature=0.1, top_p=0.75, top_k=40, num_beams=4, max_new_tokens=256, **kwargs): prompt = generate_prompt(instruction, input) inputs = tokenizer(prompt, return_tensors='pt') input_ids = inputs['input_ids'].to(device) generation_config = GenerationConfig(temperatur...
.parametrize(('t', 't2', 'result'), ((TClass[(int, int)], str, TClass(TClass(1, 2), 'a')), (List[TClass[(int, int)]], str, TClass([TClass(1, 2)], 'a')))) def test_structure_nested_generics(converter: BaseConverter, t, t2, result): res = converter.structure(asdict(result), TClass[(t, t2)]) assert (res == result)
class FCNHead(nn.Sequential): def __init__(self, in_channels, channels): inter_channels = (in_channels // 4) layers = [nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False), nn.BatchNorm2d(inter_channels), nn.ReLU(), nn.Dropout(0.1), nn.Conv2d(inter_channels, channels, 1)] super(F...
class CallError(Error): def __str__(self) -> str: if (len(self.args) == 1): return self.args[0] (instance, method, args, kwargs, original_error, stack) = self.args cls = (instance.__class__.__name__ if (instance is not None) else '') full_method = '.'.join((cls, method.__...
class GitVisionConfig(PretrainedConfig): model_type = 'git_vision_model' def __init__(self, hidden_size=768, intermediate_size=3072, num_hidden_layers=12, num_attention_heads=12, num_channels=3, image_size=224, patch_size=16, hidden_act='quick_gelu', layer_norm_eps=1e-05, attention_dropout=0.0, initializer_rang...
def test_one(args, wav_root, store_root, rescale, soundstream): (wav, sr) = librosa.load(wav_root, sr=args.sr) wav = torch.tensor(wav).unsqueeze(0) wav = wav.unsqueeze(1).cuda() compressed = soundstream.encode(wav, target_bw=args.target_bw) print('finish compressing') out = soundstream.decode(co...
_module() class BCELossWithLogits(BaseWeightedLoss): def __init__(self, loss_weight=1.0, class_weight=None): super().__init__(loss_weight=loss_weight) self.class_weight = None if (class_weight is not None): self.class_weight = torch.Tensor(class_weight) def _forward(self, cls...
class TResNet(nn.Module): def __init__(self, layers, in_chans=3, num_classes=1000, width_factor=1.0, v2=False, global_pool='fast', drop_rate=0.0): self.num_classes = num_classes self.drop_rate = drop_rate super(TResNet, self).__init__() aa_layer = BlurPool2d self.inplanes = i...
class ScheduleInvitation(): id: strawberry.ID option: ScheduleInvitationOption notes: str title: str submission: Submission dates: List[ScheduleInvitationDate] def from_django_model(cls, instance): return cls(id=instance.submission.hashid, title=instance.title, option=ScheduleInvitat...
class CMDefaults(): user = User(1, 'First name', False) custom_title: str = 'PTB' is_anonymous: bool = True until_date: datetime.datetime = to_timestamp(datetime.datetime.utcnow()) can_be_edited: bool = False can_change_info: bool = True can_post_messages: bool = True can_edit_messages: ...