code
stringlengths
281
23.7M
def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=False): if (torch.min(y) < (- 1.0)): print('min value is ', torch.min(y)) if (torch.max(y) > 1.0): print('max value is ', torch.max(y)) global mel_basis, hann_window dtype_device = ((str(y...
def search_func(model, column, key, iter_, handledirs): check = model.get_value(iter_, 0) if (check is None): return True elif ((not handledirs) or (os.sep not in key)): check = (os.path.basename(check) or os.sep) return ((key not in check.lower()) and (key not in check))
def main(): keylist = [('system\\currentcontrolset\\control\\timezoneinformation', 'OPS_EXTRA_TIMEZONE_KEY', ONE_DAY, True), ('SYSTEM\\CurrentControlSet\\Enum\\USB', 'OPS_USB_USB_KEY', ONE_DAY, True), ('SYSTEM\\CurrentControlSet\\Enum\\USBSTOR', 'OPS_USB_USBSTOR_KEY', ONE_DAY, True), ('Software\\Policies\\Microsoft...
class ExtensionTests(unittest.TestCase): def test_encode(self): with self.assertRaises(NotImplementedError): Extension().encode(Frame(Opcode.TEXT, b'')) def test_decode(self): with self.assertRaises(NotImplementedError): Extension().decode(Frame(Opcode.TEXT, b''))
def get_crystal_class(cell, ops=None, tol=SYMPREC): if (ops is None): ops = search_space_group_ops(cell, tol=tol) rotations = [] for op in ops: rotations.append(op.rot) rotations = np.unique(np.asarray(rotations), axis=0) maps = {(- 6): 0, (- 4): 1, (- 3): 2, (- 2): 3, (- 1): 4, 1: 5...
('hyperlink.contains_page_break is {value}') def then_hyperlink_contains_page_break_is_value(context: Context, value: str): actual_value = context.hyperlink.contains_page_break expected_value = {'True': True, 'False': False}[value] assert (actual_value == expected_value), f'expected: {expected_value}, got: ...
def weights_init_normal(m): classname = m.__class__.__name__ if (classname.find('Conv') != (- 1)): init.normal(m.weight.data, 0.0, 0.02) elif (classname.find('Linear') != (- 1)): init.normal(m.weight.data, 0.0, 0.02) elif (classname.find('BatchNorm') != (- 1)): init.normal(m.weig...
def _reduce_terms(terms, stabilizer_list, manual_input, fixed_positions): if (manual_input is False): fixed_positions = [] for (i, _) in enumerate(stabilizer_list): selected_stab = list(stabilizer_list[0].terms)[0] if (manual_input is False): for qubit_pauli in selected_stab:...
class ResNetShortCut(nn.Module): def __init__(self, in_channels: int, out_channels: int, stride: int=2): super().__init__() self.convolution = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False) self.normalization = nn.BatchNorm2d(out_channels) def forward(self...
.supported(only_if=(lambda backend: backend.pkcs7_supported()), skip_message='Requires OpenSSL with PKCS7 support') class TestPKCS7Loading(): def test_load_invalid_der_pkcs7(self, backend): with pytest.raises(ValueError): pkcs7.load_der_pkcs7_certificates(b'nonsense') def test_load_invalid_p...
def apply_find_items_viewed(df, item_mappings): import pandas as pd import numpy as np df = df.sort_values(by=['wcs_user_sk', 'tstamp', 'wcs_sales_sk', 'wcs_item_sk'], ascending=[False, False, False, False]) df.reset_index(drop=True, inplace=True) df['relevant_flag'] = ((df.wcs_sales_sk != 0) & (df....
class CICleanSetup(object): def setup_method(self): self.ci_env = (os.environ.get('CI') == 'true') reload(pysat) self.saved_path = copy.deepcopy(pysat.params['data_dirs']) if (not self.ci_env): pytest.skip('Skipping local tests to avoid breaking user setup') else:...
class CustomDatasetDataLoader(BaseDataLoader): def name(self): return 'CustomDatasetDataLoader' def initialize(self, opt): BaseDataLoader.initialize(self, opt) self.dataset = create_dataset(opt) self.dataloader = torch.utils.data.DataLoader(self.dataset, batch_size=opt.batchSize,...
def evaluate(args): opt = vars(args) opt['dataset_splitBy'] = ((opt['dataset'] + '_') + opt['splitBy']) if (args.cfg_file is not None): cfg_from_file(args.cfg_file) if (args.set_cfgs is not None): cfg_from_list(args.set_cfgs) print('Using config:') pprint.pprint(cfg) data_jso...
def qdot_sideinfo_simple(qp: QP, env_sys: System): dp_pos = (qp.vel * env_sys.active_pos) def op(qp_ang: jnp.ndarray, qp_rot: jnp.ndarray, active_rot: jnp.ndarray): return jnp.matmul(ang_to_quat((qp_ang * active_rot)), qp_rot) return (dp_pos, op(qp.ang, qp.rot, env_sys.active_rot))
def _load_or_init_impl(session, method_order, allow_drop_layers, allow_lr_init=True): for method in method_order: if (method == 'best'): ckpt_path = _checkpoint_path_or_none('best_dev_checkpoint') if ckpt_path: log_info('Loading best validating checkpoint from {}'.for...
def pytest_runtest_teardown(item, nextitem): reruns = get_reruns_count(item) if (reruns is None): return if (not hasattr(item, 'execution_count')): return _test_failed_statuses = getattr(item, '_test_failed_statuses', {}) if ((item.execution_count <= reruns) and any(_test_failed_stat...
class RagRetriever(): def __init__(self, config, question_encoder_tokenizer, generator_tokenizer, index=None, init_retrieval=True): self._init_retrieval = init_retrieval requires_backends(self, ['datasets', 'faiss']) super().__init__() self.index = (index or self._build_index(config)...
def generate_costing_table(pyscf_mf: scf.HF, cutoffs: np.ndarray, name: str='pbc', chi: int=10, beta: int=20, dE_for_qpe: float=0.0016, energy_method: str='MP2') -> pd.DataFrame: kmesh = kpts_to_kmesh(pyscf_mf.cell, pyscf_mf.kpts) cc_inst = build_cc_inst(pyscf_mf) exact_eris = cc_inst.ao2mo() if (energy...
class TaskRc(dict): UDA_TYPE_MAP = {'date': DateField, 'duration': DurationField, 'numeric': NumericField, 'string': StringField} def __init__(self, path=None, overrides=None): self.overrides = (overrides if overrides else {}) if path: self.path = os.path.normpath(os.path.expanduser(...
class VmfsFileSystem(LoopbackFileSystemMixin, MountFileSystem): type = 'vmfs' aliases = ['vmfs_volume_member'] guids = ['2AE031AA-0F40-DB11-9590-000C2911D1B8'] def mount(self): self._make_mountpoint() self._find_loopback() try: _util.check_call_(['vmfs-fuse', self.loo...
.parametrize('screenshot_manager', [{}, {'type': 'box'}, {'type': 'line'}, {'type': 'line', 'line_width': 1}, {'start_pos': 'top'}], indirect=True) def ss_memorygraph(screenshot_manager): widget = screenshot_manager.c.widget['memorygraph'] widget.eval(f'self.values={values}') widget.eval('self.draw()') ...
class InteractivePolicy(Policy): def __init__(self, env, agent_index): super(InteractivePolicy, self).__init__() self.env = env self.move = [False for i in range(4)] self.comm = [False for i in range(env.world.dim_c)] env.viewers[agent_index].window.on_key_press = self.key_pr...
class Projector(): def __init__(self, projector_model: Model, video_chunk_iterator_provider: VideoChunkIteratorProvider) -> None: self._projector_model = projector_model self._video_chunk_iterator_provider = video_chunk_iterator_provider def project(self, video_features: np.ndarray) -> np.ndarra...
class _VCTKBaseDataSource(FileDataSource): def __init__(self, data_root, speakers, labelmap, max_files): self.data_root = data_root for idx in range(len(speakers)): if (speakers[idx][0] == 'p'): speakers[idx] = speakers[idx][1:] if (speakers == 'all'): ...
def create_model(feat_dim, num_classes=1000, scale=16, stage1_weights=False, dataset=None, shot_phase='stage1', test=False, *args): print('Loading Dot Product Classifier.') print(num_classes, feat_dim) clf = CosNorm_Classifier(num_classes, feat_dim, scale) if (not test): if stage1_weights: ...
_tf class TFTransfoXLModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ((TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()) all_generative_model_classes = (() if is_tf_available() else ()) pipeline_model_mapp...
class IntegratorDiag(Integrator): integrator_options = {'eigensolver_dtype': 'dense'} support_time_dependant = False supports_blackbox = False method = 'diag' def __init__(self, system, options): if (not system.isconstant): raise ValueError('Hamiltonian system must be constant to...
_fixtures(WebFixture, SessionScopeFixture) def test_logging_in(web_fixture, session_scope_fixture): browser = Browser(web_fixture.new_wsgi_app(site_root=SessionScopeUI)) user = session_scope_fixture.user browser.open('/') browser.click(XPath.link().with_text('Log in')) browser.type(XPath.input_label...
class DeepAdversarialMetricLearning(TrainWithClassifier): def __init__(self, metric_alone_epochs=0, g_alone_epochs=0, g_triplets_per_anchor=100, *args, **kwargs): super().__init__(*args, **kwargs) self.original_loss_weights = copy.deepcopy(self.loss_weights) self.metric_alone_epochs = metric...
def generate_summary_html(root_dir: Path): test_groups = get_test_groups(root_dir) test_cases = get_test_cases(test_groups, (root_dir / 'tests')) summary_html = '' for type_checker in TYPE_CHECKERS: version_file = (((root_dir / 'results') / type_checker.name) / 'version.toml') try: ...
def make_KeyPress_from_keydescr(keydescr): keyinfo = KeyPress() if ((len(keydescr) > 2) and (keydescr[:1] == u'"') and (keydescr[(- 1):] == u'"')): keydescr = keydescr[1:(- 1)] while 1: lkeyname = keydescr.lower() if lkeyname.startswith(u'control-'): keyinfo.control = Tru...
class TaskbarTestCases(unittest.TestCase): def setUp(self): Timings.defaults() self.tm = _ready_timeout app = Application(backend='win32') app.start(os.path.join(mfc_samples_folder, u'TrayMenu.exe'), wait_for_idle=False) self.app = app self.dlg = app.top_window() ...
def test_retry_exec_iteration_raises_on_error_not_in_retryon(): rd = RetryDecorator({'max': 3, 'retryOn': ['KeyError', 'BlahError']}) context = Context({}) mock = MagicMock() mock.side_effect = ValueError('arb') with patch_logger('pypyr.dsl', logging.ERROR) as mock_logger_error: with pytest....
def _compute_statistics_of_path(path, model, batch_size, dims, cuda): if path.endswith('.npz'): f = np.load(path) (m, s) = (f['mu'][:], f['sigma'][:]) f.close() else: path = pathlib.Path(path) files = (list(path.glob('*.jpg')) + list(path.glob('*.png'))) (m, s) = ...
def export_chunks_from_ultrastar_data(audio_filename: str, ultrastar_data: UltrastarTxtValue, folder_name: str) -> None: print(f'{ULTRASINGER_HEAD} Export Ultrastar data as vocal chunks wav files') create_folder(folder_name) wave_file = wave.open(audio_filename, 'rb') (sample_rate, n_channels) = (wave_f...
def validate_metrics_list(metrics_list): metric_names = [metric.get_name() for metric in metrics_list] if (len(metric_names) != len(set(metric_names))): raise TrackEvalException('Code being run with multiple metrics of the same name') fields = [] for m in metrics_list: fields += m.fields...
def get_padding_shape(filter_shape, stride): def _pad_top_bottom(filter_dim, stride_val): pad_along = max((filter_dim - stride_val), 0) pad_top = (pad_along // 2) pad_bottom = (pad_along - pad_top) return (pad_top, pad_bottom) padding_shape = [] for (filter_dim, stride_val) i...
def get_all_pods(label_selector=None): pods = [] if label_selector: ret = cli.list_pod_for_all_namespaces(pretty=True, label_selector=label_selector) else: ret = cli.list_pod_for_all_namespaces(pretty=True) for pod in ret.items: pods.append([pod.metadata.name, pod.metadata.namesp...
class InlineQueryResultAudio(InlineQueryResult): def __init__(self, audio_url: str, title: str, id: str=None, performer: str='', audio_duration: int=0, caption: str='', parse_mode: Optional['enums.ParseMode']=None, caption_entities: List['types.MessageEntity']=None, reply_markup: 'types.InlineKeyboardMarkup'=None, ...
class TestNormalization(): def test_normalize(): with pytest.raises(TypeError): Normalize(dict(mean=[123.675, 116.28, 103.53]), [58.395, 57.12, 57.375]) with pytest.raises(TypeError): Normalize([123.675, 116.28, 103.53], dict(std=[58.395, 57.12, 57.375])) target_keys ...
class ThresholdValueTest(unittest.TestCase): _grad() def _test_accuracy_helper(self, labels: torch.Tensor, predictions: torch.Tensor, weights: torch.Tensor, expected_accuracy: torch.Tensor, threshold: float) -> None: num_task = labels.shape[0] batch_size = labels.shape[0] task_list = [] ...
class WithDescriptors(Serialisable): descriptor = Nested(expected_type=str) set_tuple = NestedSet(values=('a', 1, 0.0)) set_list = NestedSet(values=['a', 1, 0.0]) set_tuple_none = NestedSet(values=('a', 1, 0.0, None)) noneset_tuple = NestedNoneSet(values=('a', 1, 0.0)) noneset_list = NestedNoneS...
_ordering class Condition(): def __init__(self, operator): self.operator = operator assert isinstance(operator, TypeConditionOperator), (('the operator ' + str(operator)) + ' should be of type TypeConditionOperator') def _key(self): return (str(type(self)), str(self.operator)) def __...
class EmpiricalAPSParams(KiteParameterGroup): def __init__(self, model, **kwargs): scene = model.getScene() kwargs['type'] = 'group' kwargs['name'] = 'Scene.APS (empirical)' KiteParameterGroup.__init__(self, model=model, model_attr='scene', **kwargs) p = {'name': 'applied', '...
class Lookahead(nn.Module): def __init__(self, n_features, context): super(Lookahead, self).__init__() self.n_features = n_features self.weight = Parameter(torch.Tensor(n_features, (context + 1))) assert (context > 0) self.context = context self.register_parameter('bi...
class IntelHex16bit(IntelHex): def __init__(self, source=None): if isinstance(source, IntelHex): self.padding = source.padding self.start_addr = source.start_addr self._buf = source._buf self._offset = source._offset elif isinstance(source, dict): ...
def test_get_index(textpage): (x, y) = (60, (textpage.page.get_height() - 66)) index = textpage.get_index(x, y, 5, 5) assert ((index < textpage.count_chars()) and (index == 0)) charbox = textpage.get_charbox(index) char = textpage.get_text_bounded(*charbox) assert (char == 'L')
class OutputList(RecycleView): def __init__(self, **kwargs): super(OutputList, self).__init__(**kwargs) self.app = App.get_running_app() def update(self, outputs: Sequence['TxOutput']): res = [] for o in outputs: value = self.app.format_amount_and_units(o.value) ...
class MultiplyResponse(FrequencyResponse): responses = List.T(FrequencyResponse.T()) def __init__(self, responses=None, **kwargs): if (responses is None): responses = [] FrequencyResponse.__init__(self, responses=responses, **kwargs) def get_fmax(self): fmaxs = [resp.get_...
def to_vertex_format(format): if (format in wgpu.VertexFormat): return format elif (format in wgpu.IndexFormat): return format primitives = {'i1': 'sint8', 'u1': 'uint8', 'i2': 'sint16', 'u2': 'uint16', 'i4': 'sint32', 'u4': 'uint32', 'f2': 'float16', 'f4': 'float32'} primitive = primiti...
def rebuild_open(img: np.ndarray, kernel: np.ndarray, erode_time: int=1) -> np.ndarray: temp_img = img.copy() for i in range(erode_time): temp_img = cv2.erode(temp_img, kernel) '' dialate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) last_img = temp_img.copy() while True: ...
class TestContextManagerFixtureFuncs(): def test_simple(self, pytester: Pytester) -> None: pytester.makepyfile('\n import pytest\n \n def arg1():\n print("setup")\n yield 1\n print("teardown")\n def test_1(arg1):\n ...
_environment_variables(model=MyHandlerEnvVars) def my_handler(event: dict[(str, Any)], context: LambdaContext) -> dict[(str, Any)]: env_vars: MyHandlerEnvVars = get_environment_variables(model=MyHandlerEnvVars) return {'statusCode': HTTPStatus.OK, 'headers': {'Content-Type': 'application/json'}, 'body': json.du...
def fast_inplace_check(fgraph, inputs): Supervisor = pytensor.compile.function.types.Supervisor protected_inputs = [f.protected for f in fgraph._features if isinstance(f, Supervisor)] protected_inputs = sum(protected_inputs, []) protected_inputs.extend(fgraph.outputs) inputs = [i for i in inputs if ...
.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_trace(tmp_path): source = '\n def task_example():\n i = \n ' tmp_path.joinpath('task_module.py').write_text(textwrap.dedent(so...
def data_loader(args, test_path=False, segmentation=False): mean_vals = [0.485, 0.456, 0.406] std_vals = [0.229, 0.224, 0.225] input_size = (int(args.input_size), int(args.input_size)) crop_size = (int(args.crop_size), int(args.crop_size)) tsfm_train = transforms.Compose([transforms.Resize(input_siz...
def camel_to_snake(naming, name): if naming.prefix: assert name.startswith(naming.prefix) name = name[len(naming.prefix):] if naming.suffix: assert name.endswith(naming.suffix) name = name[:(- len(naming.suffix))] return re.sub('(?<!^)(?=[A-Z])', '_', name).lower()
def glc_to_material(l, item=None): line = l.strip().split() name = line.pop(0) nd = sfloat(line.pop(0)) vd = sfloat(line.pop(0)) density = sfloat(line.pop(0)) del line[:6] del line[:2] (a, num) = (sint(line.pop(0)), sint(line.pop(0))) coeff = np.array([sfloat(_) for _ in line[:num]])...
class Ametek7270(Instrument): SENSITIVITIES = [0.0, 2e-09, 5e-09, 1e-08, 2e-08, 5e-08, 1e-07, 2e-07, 5e-07, 1e-06, 2e-06, 5e-06, 1e-05, 2e-05, 5e-05, 0.0001, 0.0002, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0] SENSITIVITIES_IMODE = {0: SENSITIVITIES, 1: [(sen * 1e-06) for sen in SENSITIVI...
def iter_benchmark(iterator, num_iter: int, warmup: int=5, max_time_seconds: float=60) -> Tuple[(float, List[float])]: (num_iter, warmup) = (int(num_iter), int(warmup)) iterator = iter(iterator) for _ in range(warmup): next(iterator) timer = Timer() all_times = [] for curr_iter in tqdm.t...
def has_node_changed(task: PTask, node: (PTask | PNode)) -> bool: node_state = node.state() if (node_state is None): return True with DatabaseSession() as session: db_state = session.get(State, (task.signature, node.signature)) if (db_state is None): return True return (node_...
def main(unused_argv): parse_cmdline_gin_configurations() try: checkpoint_to_reload = gin.query_parameter('LearnerConfig.checkpoint_for_eval') except ValueError: try: checkpoint_to_reload = gin.query_parameter('LearnerConfig.pretrained_checkpoint') except ValueError: ...
class TestDetermineAttribEqOrder(): def test_default(self): assert ((42, None, 42, None) == _determine_attrib_eq_order(None, None, None, 42)) def test_eq_callable_order_boolean(self): assert ((True, str.lower, False, None) == _determine_attrib_eq_order(None, str.lower, False, True)) def test...
class NELDER_MEAD(Optimizer): _OPTIONS = ['maxiter', 'maxfev', 'disp', 'xatol', 'adaptive'] def __init__(self, maxiter: Optional[int]=None, maxfev: int=1000, disp: bool=False, xatol: float=0.0001, tol: Optional[float]=None, adaptive: bool=False) -> None: super().__init__() for (k, v) in list(loc...
def start_tunnel(dsz_cmd=None): assert verify_dsz_cmd_redirect_object(dsz_cmd), 'Given dsz_cmd must be a valid ops.cmd object for the redirect plugin.' tunnel = verify_tunnel(id=None, dsz_cmd=dsz_cmd, return_status=False) if (tunnel is not False): return int(tunnel.id) redir_obj = dsz_cmd.execut...
class TestPairingWithSymmetries(unittest.TestCase): def test_two_fermions(self): bins = [[1], [2], [3], [4]] count = 0 for pairing in pair_within_simultaneously_binned(bins): count += 1 self.assertEqual(len(pairing), 2) print(pairing) self.assertEq...
def optimize(struc, ff, optimizations=['conp', 'conp'], exe='gulp', pstress=None, path='tmp', label='_', clean=True, adjust=False): time_total = 0 for opt in optimizations: (struc, energy, time, error) = single_optimize(struc, ff, pstress=pstress, opt=opt, exe=exe, path=path, label=label, clean=clean) ...
class EGICheckinOpenIdConnect(OpenIdConnectAuth): name = 'egi-checkin' CHECKIN_ENV = 'prod' USERNAME_KEY = 'voperson_id' EXTRA_DATA = [('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True)] DEFAULT_SCOPE = ['openid', 'profile', 'email', 'voperso...
class PFS_No_Ksappend(ParserTest): def __init__(self, *args, **kwargs): ParserTest.__init__(self, *args, **kwargs) self.ks = '\nlang en_US\nkeyboard us\nautopart\n' def setUp(self): ParserTest.setUp(self) self._path = None def runTest(self): self._path = preprocessFro...
class ScanInplaceOptimizer(GraphRewriter): alloc_ops = (Alloc, AllocEmpty) def add_requirements(self, fgraph): fgraph.attach_feature(ReplaceValidate()) fgraph.attach_feature(DestroyHandler()) def attempt_scan_inplace(self, fgraph: FunctionGraph, node: Apply[Scan], output_indices: list[int]) ...
def _iter_params_for_processing(invocation_order: Sequence[Parameter], declaration_order: Sequence[Parameter]) -> list[Parameter]: def sort_key(item: Parameter) -> tuple[(bool, float)]: if (item.name == 'paths'): return (False, (- 3)) if (item.name == 'config'): return (False...
class BasicBlock(nn.Module): def __init__(self, in_channels, channels, kernel_size, stride=1, padding=0, **block_kwargs): super(BasicBlock, self).__init__() self.conv = layers.convnxn(in_channels, channels, kernel_size, stride=stride, padding=padding) self.relu = layers.relu() def forwar...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a text classification task') parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).') parser.add_argument('--predict_with_generate', type=b...
class VOTLTDataset(Dataset): def __init__(self, name, dataset_root, load_img=False): super(VOTLTDataset, self).__init__(name, dataset_root) with open(os.path.join(dataset_root, (name + '.json')), 'r') as f: meta_data = json.load(f) pbar = tqdm(meta_data.keys(), desc=('loading ' +...
class SubcommandsExample(cmd2.Cmd): def __init__(self): super().__init__() def base_foo(self, args): self.poutput((args.x * args.y)) def base_bar(self, args): self.poutput(('((%s))' % args.z)) def base_sport(self, args): self.poutput('Sport is {}'.format(args.sport)) ...
def main(): parser = argparse.ArgumentParser(description='symmetric alignment builer') parser.add_argument('--fast_align_dir', help='path to fast_align build directory') parser.add_argument('--mosesdecoder_dir', help='path to mosesdecoder root directory') parser.add_argument('--sym_heuristic', help='heu...
def main(argv=None): op = argparse.ArgumentParser() op.add_argument('-i', '--input', dest='input', help=_('a basis file to use for seeding the kickstart data (optional)')) op.add_argument('-o', '--output', dest='output', help=_('the location to write the finished kickstart file, or stdout if not given')) ...
class MobileNetV2ImageProcessor(BaseImageProcessor): model_input_names = ['pixel_values'] def __init__(self, do_resize: bool=True, size: Optional[Dict[(str, int)]]=None, resample: PILImageResampling=PILImageResampling.BILINEAR, do_center_crop: bool=True, crop_size: Dict[(str, int)]=None, do_rescale: bool=True, ...
def rename_key(orig_key): if ('model' in orig_key): orig_key = orig_key.replace('model.', '') if ('norm1' in orig_key): orig_key = orig_key.replace('norm1', 'attention.output.LayerNorm') if ('norm2' in orig_key): orig_key = orig_key.replace('norm2', 'output.LayerNorm') if ('norm'...
.skipif((sys.platform == 'win32'), reason='Windows only applies R/O to files') def test_destination_not_write_able(tmp_path, capsys): if (hasattr(os, 'geteuid') and (os.geteuid() == 0)): pytest.skip('no way to check permission restriction when running under root') target = tmp_path prev_mod = target...
class W_ComposableContinuation(W_Procedure): errorname = 'composable-continuation' _attrs_ = _immutable_fields_ = ['cont', 'prompt_tag'] def __init__(self, cont, prompt_tag=None): self.cont = cont self.prompt_tag = prompt_tag def get_arity(self, promote=False): from pycket.arity ...
def optimize_module(quant_module: QcQuantizeWrapper, x: torch.Tensor, xq: torch.Tensor, params: SeqMseParams): if quant_module.param_quantizers['weight'].use_symmetric_encodings: per_channel_max = torch.max(quant_module.weight.abs(), dim=1)[0].detach() per_channel_min = None else: per_ch...
class LoggedInteractiveConsole(code.InteractiveConsole): def __init__(self, _locals: Dict[(str, Any)], logpath: str) -> None: code.InteractiveConsole.__init__(self, _locals) self.output_file = logpath self.pid = os.getpid() self.pri = (syslog.LOG_USER | syslog.LOG_NOTICE) sel...
class PetitionCreateWizardViewTest(TestCase): def setUpTestData(cls): User = get_user_model() for org in orgs: o = Organization.objects.create(name=org) o.save() for user in users: u = User.objects.create_user(user, password=user) u.first_name ...
class TestFileMonitor(): def test_create_delete(self, temp_dir: Path): path = temp_dir monitor = BasicMonitor(path) some_file = (path / 'foo.txt') some_file.write_text('test') sleep(SLEEP_SECS) run_gtk_loop() assert monitor.changed, 'No events after creation' ...
def _gen_efficientnet_lite(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs): arch_def = [['ds_r1_k3_s1_e1_c16'], ['ir_r2_k3_s2_e6_c24'], ['ir_r2_k5_s2_e6_c40'], ['ir_r3_k3_s2_e6_c80'], ['ir_r3_k5_s1_e6_c112'], ['ir_r4_k5_s2_e6_c192'], ['ir_r1_k3_s1_e6_c320']] model_kwargs = dic...
class QuadraticProgram(): Status = QuadraticProgramStatus def __init__(self, name: str='') -> None: if (not name.isprintable()): warn('Problem name is not printable') self._name = '' self.name = name self._status = QuadraticProgram.Status.VALID self._variables...
def get_xml_type(val): LOG.info(('Inside get_xml_type(). val = "%s", type(val) = "%s"' % (val, type(val).__name__))) if (type(val).__name__ == 'NoneType'): LOG.info("type(val).__name__ == 'NoneType', returning 'null'") return 'null' elif (type(val).__name__ == 'bool'): LOG.info("type...
def test_paintEvent(skip_qtbot, canvas, mocker): event = MagicMock() mock_painter: MagicMock = mocker.patch('PySide6.QtGui.QPainter') canvas.paintEvent(event) mock_painter.assert_called_once_with(canvas) draw_ellipse: MagicMock = mock_painter.return_value.drawEllipse draw_ellipse.assert_any_call...
def basic_multivector_operations_2D(): Print_Function() (ex, ey) = MV.setup('e*x|y') print('g_{ij} =', MV.metric) X = MV('X', 'vector') A = MV('A', 'spinor') X.Fmt(1, 'X') A.Fmt(1, 'A') (X | A).Fmt(2, 'X|A') (X < A).Fmt(2, 'X<A') (A > X).Fmt(2, 'A>X') return
class TestRandomRegionEmpirical(): def setup_method(self): self.mexico = MEXICO.copy() self.cards = self.mexico.groupby(by='HANSON03').count().NAME.values.tolist() self.ids = self.mexico.index.values.tolist() self.w = libpysal.weights.Queen.from_dataframe(self.mexico) def test_ra...
class LightningModel(pl.LightningModule): def __init__(self, model, learning_rate): super().__init__() self.learning_rate = learning_rate self.model = model if hasattr(model, 'dropout_proba'): self.dropout_proba = model.dropout_proba self.save_hyperparameters(igno...
class untitled(App): def main(self): mainContainer = Container(width=706, height=445, margin='0px auto', style='position: relative') subContainer = HBox(width=630, height=277, style='position: absolute; left: 40px; top: 150px; background-color: #b6b6b6') vbox = VBox(width=300, height=250) ...
def test_lineanchors_with_startnum(): optdict = dict(lineanchors='foo', linenostart=5) outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) html = outfile.getvalue() assert re.search('<pre>\\s*<span>\\s*</span>\\s*<a id="foo-5" name="foo-5" href="#foo-5">', html)
def get_default_image_compressor(**kwargs): if imagecodecs.JPEGXL: this_kwargs = {'effort': 3, 'distance': 0.3, 'decodingspeed': 1} this_kwargs.update(kwargs) return JpegXl(**this_kwargs) else: this_kwargs = {'level': 50} this_kwargs.update(kwargs) return Jpeg2k(*...
class CQADupstackPhysicsRetrieval(AbsTaskRetrieval, BeIRTask): def description(self): return {'name': 'CQADupstackPhysicsRetrieval', 'beir_name': 'cqadupstack/physics', 'description': 'CQADupStack: A Benchmark Data Set for Community Question-Answering Research', 'reference': ' 'type': 'Retrieval', 'category...
def assert_gc_integrity(expect_storage_removed=True): removed_image_storages = [] remove_callback = model.config.register_image_cleanup_callback(removed_image_storages.extend) existing_digests = set() for storage_row in ImageStorage.select(): if storage_row.cas_path: existing_digests...
class unit_fusion(nn.Module): def __init__(self, num_class, in_channels=256): super(unit_fusion, self).__init__() self.fc = nn.Linear(in_channels, num_class) nn.init.normal(self.fc.weight, 0, math.sqrt((2.0 / num_class))) def forward(self, x1, x2): y = (x1 + x2) return se...
def get_core_candidates(pathtocheck): cmd = ops.cmd.getDszCommand('dir', path=('"%s"' % os.path.dirname(pathtocheck)), mask=('"%s"' % os.path.basename(pathtocheck))) obj = cmd.execute() if cmd.success: candidates = [f for d in obj.diritem for f in d.fileitem if (f.attributes.directory == 0) if (f.si...