code
stringlengths
281
23.7M
def test_create_options(db, settings): Option.objects.all().delete() xml_file = (((Path(settings.BASE_DIR) / 'xml') / 'elements') / 'options.xml') root = read_xml_file(xml_file) version = root.attrib.get('version') elements = flat_xml_to_elements(root) elements = convert_elements(elements, versi...
def test(base_model, psnet_model, decoder, regressor_delta, test_dataloader, args): global use_gpu global epoch_best_aqa, rho_best, L2_min, RL2_min global epoch_best_tas, pred_tious_best_5, pred_tious_best_75 true_scores = [] pred_scores = [] pred_tious_test_5 = [] pred_tious_test_75 = [] ...
class Trainer(DefaultTrainer): def build_evaluator(cls, cfg, dataset_name, output_folder=None): if (output_folder is None): output_folder = os.path.join(cfg.OUTPUT_DIR, 'inference') os.makedirs(output_folder, exist_ok=True) evaluator_list = [] evaluator_type = Metadat...
class PetConfig(ABC): def __repr__(self): return repr(self.__dict__) def save(self, path: str): with open(path, 'w', encoding='utf8') as fh: json.dump(self.__dict__, fh) def load(cls, path: str): cfg = cls.__new__(cls) with open(path, 'r', encoding='utf8') as fh: ...
def test_get_style_defs_contains_default_line_numbers_styles(): style_defs = HtmlFormatter().get_style_defs().splitlines() assert (style_defs[1] == 'td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }') assert (style_defs[2] == 'span.linenos { color: ...
def _resolve_ship(fitting, sMkt, b_localized): shipType = fitting.getElementsByTagName('shipType').item(0).getAttribute('value') anything = None if b_localized: try: (shipType, anything) = _extract_match(shipType) except ExtractingError: pass limit = 2 ship = ...
class Graphsn_GIN(nn.Module): def __init__(self, nfeat, nhid, nclass, dropout): super(Graphsn_GIN, self).__init__() self.nn = Linear(nfeat, nhid) self.fc = Linear(nhid, nclass) self.dropout = dropout self.eps = nn.Parameter(torch.FloatTensor(1)) self.reset_parameters(...
def train_sample_places_low_shot(low_shot_trainer: SVMLowShotTrainer, k_values: List[int], sample_inds: List[int], sample_num: int, output_dir: str, layername: str, cfg: AttrDict): set_env_vars(local_rank=0, node_id=0, cfg=cfg) for low_shot_kvalue in k_values: checkpoint_dir = f'{output_dir}/sample{samp...
def test_verify_args(parser: CompatibleArgumentParser, capsys: CaptureFixture) -> None: with pytest.raises(SystemExit) as ex: parser.parse_args(['--no-license-path']) capture = capsys.readouterr().err for arg in ('--no-license-path', '--with-license-file'): assert (arg in capture) with p...
class MultiRcTaskHelper(TaskHelper): def add_special_input_features(self, input_example: InputExample, input_features: InputFeatures) -> None: input_features.meta['question_idx'] = input_example.meta['question_idx'] def add_features_to_dict(self, features: List[InputFeatures], feature_dict: Dict[(str, t...
def pass_calibration_data(sim_model, forward_pass_args=None): data_loader = ImageNetDataPipeline.get_val_dataloader() batch_size = 64 max_batch_counter = 16 sim_model.eval() current_batch_counter = 0 with torch.no_grad(): for (input_data, target_data) in data_loader: inputs_b...
class PreTrainedTokenizer(object): vocab_files_names = {} pretrained_vocab_files_map = {} pretrained_init_configuration = {} max_model_input_sizes = {} SPECIAL_TOKENS_ATTRIBUTES = ['bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', 'additional_special_tokens'...
class CIFARQuick(HybridBlock): def __init__(self, block, fix_layers, pooling, channels, classes, fix_conv=False, **kwargs): super(CIFARQuick, self).__init__() self.fix_conv = fix_conv self.fix_layers = fix_layers assert ('fw' in kwargs.keys()), 'no_fw' self.fw = kwargs['fw'] ...
class TestModel(BaseModel): def name(self): return 'TestModel' def modify_commandline_options(parser, is_train=True): assert (not is_train), 'TestModel cannot be used in train mode' parser = CycleGANModel.modify_commandline_options(parser, is_train=False) parser.set_defaults(data...
class MongoStoreTests(TestCase): def setUp(self): self.db_hosts = ['localhost'] self.db_name = ('coal-mine-test-' + str(uuid.uuid4())) self.db_conn = MongoClient() self.db = self.db_conn[self.db_name] self.store = MongoStore(self.db_hosts, self.db_name, None, None) def te...
class PreprocessForEfficientRouletteSelectionTest(unittest.TestCase): def assertPreprocess(self, weights): (alternates, keep_chances) = _preprocess_for_efficient_roulette_selection(weights) self.assertEqual(len(alternates), len(keep_chances)) target_weight = (sum(weights) // len(alternates))...
def patchify_augmentation(args, batch): aug_batch = dict() img = batch['image'] label = batch['label'] batch_size = img.size()[0] patch_dim = (img.size()[(- 1)] // args.mask_patch_size) images_patch = rearrange(img, 'b c (h p1) (w p2) (d p3) -> (b h w d) c p1 p2 p3 ', p1=(args.mask_patch_size //...
def test_clip_column(): assert (_utils.clip_column(0, [], 0) == 0) assert (_utils.clip_column(2, ['123'], 0) == 2) assert (_utils.clip_column(3, ['123'], 0) == 3) assert (_utils.clip_column(5, ['123'], 0) == 3) assert (_utils.clip_column(0, ['\n', '123'], 0) == 0) assert (_utils.clip_column(1, [...
def new_export_path_for_album(album_id: AlbumId) -> Path: stem = f'{album_id.title} - {album_id.artist}' path = Path(join_path_with_escaped_name_of_legal_length(str(EXPORT_DIR_PATH), stem, EXPORT_EXTENSION)) trim_count = 1 while path.exists(): new_stem = (path.stem[:(- trim_count)] + uuid.uuid4(...
def fix_lyft(root_folder='./data/lyft', version='v1.01'): lidar_path = 'lidar/host-a011_lidar1_.bin' root_folder = os.path.join(root_folder, f'{version}-train') lidar_path = os.path.join(root_folder, lidar_path) assert os.path.isfile(lidar_path), f'Please download the complete Lyft dataset and make sure...
class FilterLogoPlacementsSerializer(serializers.Serializer): publisher = serializers.ChoiceField(choices=[(c.value, c.name.replace('_', ' ').title()) for c in PublisherChoices], required=False) flight = serializers.ChoiceField(choices=[(c.value, c.name.replace('_', ' ').title()) for c in LogoPlacementChoices],...
class MatchedMolecularPair(object): __slots__ = ('id1', 'id2', 'smirks', 'constant_smiles', 'min_constant_radius', 'max_constant_radius') def __init__(self, id1, id2, smirks, constant_smiles, min_constant_radius, max_constant_radius): self.id1 = id1 self.id2 = id2 self.smirks = smirks ...
class TestFrameDecoderExtensions(): class FakeExtension(wpext.Extension): name = 'fake' def __init__(self) -> None: self._inbound_header_called = False self._inbound_rsv_bit_set = False self._inbound_payload_data_called = False self._inbound_complete_c...
def save_video(video_frames, filename): import cv2 _make_dir(filename) video_frames = np.flip(video_frames, axis=(- 1)) fourcc = cv2.VideoWriter_fourcc(*'MJPG') fps = 30.0 (height, width, _) = video_frames[0].shape writer = cv2.VideoWriter(filename, fourcc, fps, (width, height)) for vide...
class ErrorHandling(): _error_messages = [] def error_logging(cls, func): logger = qf_logger.getChild(__class__.__name__) def wrapped_function(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: error_message = '{}: A...
class Tnspoison(Tnscmd): PACKET_REGISTER = b'\x00h\x00\x00\x01\x00\x00\x00\x019\x01,\x00\x81\x08\x00\x7f\xff\x7f\x08\x00\x00\x01\x00\x00.\x00:\x00\x00\x07\xf8\x0c\x0c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00(CONNECT_DATA=(COMMAND=service_register_NSGR))' PA...
def session(device): with tf.device(device): graph = tf.Graph() with graph.as_default(): model = tf.keras.Sequential((tf.keras.layers.Conv2D(32, kernel_size=3, input_shape=(28, 28, 3), activation='relu'), tf.keras.layers.Conv2D(64, kernel_size=3))) init = tf.compat.v1.global_...
class AttributeDevice(Switch): EVENT_TYPE_ATTRIBUTE_LIST = 'attributeList' _state_property: str _attr_name = '_attributes' def __init__(self, *args: Any, **kwargs: Any) -> None: assert isinstance(self._state_property, str) setattr(self, self._attr_name, {}) class_hints = get_type...
def resolve_file(filename, relroot=None): resolved = os.path.normpath(filename) resolved = os.path.expanduser(resolved) if (not os.path.isabs(resolved)): if (not relroot): relroot = os.getcwd() elif (not os.path.isabs(relroot)): raise NotImplementedError(relroot) ...
def sa_scaffold_hop() -> GoalDirectedBenchmark: specification = uniform_specification(1, 10, 100) benchmark_object = scaffold_hop() sa_biased = ScoringFunctionSAWrapper(benchmark_object.objective, SAScoreModifier()) return GoalDirectedBenchmark(name='SA_scaffold_hop', objective=sa_biased, contribution_s...
class FitEcmBurstScanresDampsGraph(FitGraph): hidden = True internalName = 'ecmBurstScanresDamps' name = 'ECM Burst + Scanres Damps' xDefs = [XDef(handle='tgtDps', unit=None, label='Enemy DPS', mainInput=('tgtDps', None)), XDef(handle='tgtScanRes', unit='mm', label='Enemy scanres', mainInput=('tgtScanRe...
class Image_Dataset(object): def __init__(self, image_dir, transform=None, image_ext=['.jpg', '.bmp', '.png']): assert (transform is not None) self._transform = transform self.image_dir = image_dir self.image_ext = image_ext self._read_dataset() def __getitem__(self, inde...
def clean_up_offset_payload(payload): if ('0,' in payload): payload = '{index},'.join(payload.rsplit('0,')) if ('OFFSET' in payload): payload = 'OFFSET {index} '.join(payload.rsplit('OFFSET 0')) if ('DB_NAME' in payload): payload = payload.replace('DB_NAME(0)', 'DB_NAME({index})') ...
def ignore_exceptions(func): assert asyncio.iscoroutinefunction(func), 'func needs to be a coroutine' async def wrapper(*args, **kwargs): try: return (await func(*args, **kwargs)) except asyncio.CancelledError: raise except Exception as e: pass ret...
def main(): args = parse_args() cfg = get_cfg(args) cudnn.benchmark = True timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) log_file = os.path.join(cfg.work_dir, f'{timestamp}.cfg') with open(log_file, 'a') as f: f.write(cfg.pretty_text) logger = build_logger(cfg.work_dir...
_start_docstrings('\n BiT Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ', BIT_START_DOCSTRING) class BitForImageClassification(BitPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels =...
def crop(text, width=None, suffix='[...]'): width = (width if width else settings.CLIENT_DEFAULT_WIDTH) ltext = len(text) if (ltext <= width): return text else: lsuffix = len(suffix) text = (text[:width] if (lsuffix >= width) else ('%s%s' % (text[:(width - lsuffix)], suffix))) ...
class CacheMixin(): def _apply_cache_config(cls, encoders: Union[(Encoder, Dict[(str, Encoder)])], cache_config: CacheConfig) -> Union[(Encoder, Dict[(str, Encoder)])]: if (cache_config.cache_type == CacheType.NONE): return encoders if ((not cache_config.cache_type) and (not cache_config...
def init_weight(module_list, conv_init, norm_layer, bn_eps, bn_momentum, **kwargs): if isinstance(module_list, list): for feature in module_list: __init_weight(feature, conv_init, norm_layer, bn_eps, bn_momentum, **kwargs) else: __init_weight(module_list, conv_init, norm_layer, bn_ep...
def _compute_segment_xform(pos0, pos1): mid = ((pos0 + pos1) * 0.5) height = (pos1 - pos0).GetLength() dir = ((pos1 - pos0) / height) rot = Gf.Rotation() rot.SetRotateInto((0.0, 0.0, 1.0), Gf.Vec3d(dir)) scale = Gf.Vec3f(1.0, 1.0, height) return (mid, Gf.Quath(rot.GetQuat()), scale)
def write_json_file(file_name, mv_array, metric, basis_names, compression=True, transpose=False, sparse=False, support=None, compression_opts=1): data_dict = {} data_dict['version'] = '0.0.1' dset_data = {} if transpose: dset_data['data'] = mv_array.T.tolist() dset_data['transpose'] = Tr...
def _conv2d_wrapper(x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True, impl='cuda'): (out_channels, in_channels_per_group, kh, kw) = _get_weight_shape(w) if (not flip_weight): w = w.flip([2, 3]) if ((kw == 1) and (kh == 1) and (stride == 1) and (padding in [0, [0, 0], (0, 0)]) a...
def get_expire_assets(): assets = Assets.objects.all() expire_assets = [] for asset in assets: expire_days = (asset.asset_expire_day - datetime.date.today()).days if (0 < expire_days <= 30): expire_assets.append({'asset_type': asset.get_asset_type_display(), 'asset_nu': asset.ass...
class ElasticUploader(BaseUploader): client: Elasticsearch = None upload_params = {} def get_mp_start_method(cls): return ('forkserver' if ('forkserver' in mp.get_all_start_methods()) else 'spawn') def init_client(cls, host, distance, connection_params, upload_params): init_params = {**{...
def test_window_by_position__equal_spaced_windows(): ds = simulate_genotype_call_dataset(n_variant=5, n_sample=3, seed=0) assert (not has_windows(ds)) ds['variant_position'] = (['variants'], np.array([1, 4, 6, 8, 12])) ds = window_by_position(ds, size=5, offset=1) assert has_windows(ds) np.testi...
def returnArray(wrapArgs, lenArgs, inArgs, includeOutput=False): def decorator(func): (func) def inner(*args): orig = getattr(_egl, func.__name__) newArgs = list(args) for argnum in sorted((wrapArgs + lenArgs)): if (argnum in wrapArgs): ...
class ResNet(nn.Module): def __init__(self, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], num_classes: int=1000, zero_init_residual: bool=False, groups: int=1, width_per_group: int=64, replace_stride_with_dilation: Optional[List[bool]]=None, norm_layer: Optional[Callable[(..., nn.Module)]]=nn.Gro...
('torch.__version__', torch_version) .parametrize('in_w,in_h,in_t,in_channel,out_channel,kernel_size,stride,padding,dilation', [(10, 10, 10, 1, 1, 3, 1, 0, 1), (20, 20, 20, 3, 3, 5, 2, 1, 2)]) def test_conv3d(in_w, in_h, in_t, in_channel, out_channel, kernel_size, stride, padding, dilation): x_empty = torch.randn(0...
class catch_warnings(warnings.catch_warnings): def __init__(self, *classes): super(catch_warnings, self).__init__(record=True) self.classes = classes def __enter__(self): warning_list = super(catch_warnings, self).__enter__() treat_deprecations_as_exceptions() if (len(sel...
def constant_str(value): if (type(value) == bool): if value: return 'true' else: return 'false' elif (type(value) == str): return (('"' + str(value.encode('unicode-escape').decode())) + '"') elif isinstance(value, ctypes.Array): return (('{' + ', '.joi...
(netloc='fakegitlab', path='/api/v4/projects/4/deploy_keys/1$', method='DELETE') def delete_deploykey_handker(_, request): if (not (request.headers.get('Authorization') == 'Bearer foobar')): return {'status_code': 401} return {'status_code': 200, 'headers': {'Content-Type': 'application/json'}, 'content...
class TestQuota(): (autouse=True) def setup(self, initialized_db): user = get_user('devtable') self.org = create_organization(ORG_NAME, f'{ORG_NAME}', user) self.repo1 = create_repository(ORG_NAME, REPO1_NAME, user) self.repo1manifest1 = create_manifest_for_testing(self.repo1, [B...
class MediaLoader(): def __init__(self, folder): logger.debug("Initializing %s: (folder: '%s')", self.__class__.__name__, folder) logger.info('[%s DATA]', self.__class__.__name__.upper()) self._count = None self.folder = folder self.vid_reader = self.check_input_folder() ...
class PackageQueue(object): class Empty(Exception): def __init__(self): Exception.__init__(self, 'pop from an empty PackageQueue') pass def __init__(self, N, discard_mode='old'): self._q = deque() self._condition = threading.Condition() self._maxlen = int(N) ...
class TestAgentInsert(unittest.TestCase): def _get_simple_dataset(self) -> ChunkedDataset: dataset = ChunkedDataset('') dataset.scenes = np.zeros(1, dtype=SCENE_DTYPE) dataset.frames = np.zeros(3, dtype=FRAME_DTYPE) dataset.agents = np.zeros(6, dtype=AGENT_DTYPE) dataset.scen...
def test_create_manifest_cannot_load_config_blob(initialized_db): repository = create_repository('devtable', 'newrepo', None) layer_json = json.dumps({'config': {}, 'rootfs': {'type': 'layers', 'diff_ids': []}, 'history': [{'created': '2018-04-03T18:37:09.Z', 'created_by': 'do something'}]}) (_, config_dige...
def test_run_model_singleton_weather_single_array(cec_dc_snl_ac_system, location, weather): mc = ModelChain(cec_dc_snl_ac_system, location, aoi_model='no_loss', spectral_model='no_loss') mc.run_model([weather]) assert isinstance(mc.results.weather, tuple) assert isinstance(mc.results.total_irrad, tuple)...
(maxsplit=1, no_cmd_split=True, no_replace_variables=True, deprecated_name='repeat') ('win_id', value=cmdutils.Value.win_id) ('count', value=cmdutils.Value.count) def cmd_repeat(times: int, command: str, win_id: int, count: int=None) -> None: if (count is not None): times *= count if (times < 0): ...
def test_inspiralfuns_numerical(): logMc = 1.4 q = 0.8 flow = 10.0 merger_type = 'BH' D = 100.0 (M, eta) = ins.get_M_and_eta(logMc=logMc, q=q) start_x = ins.startx(M, flow) end_x = ins.endx(eta, merger_type) (x, xtimes, dt) = ins.PN_parameter_integration(start_x, end_x, M, eta) a...
class NumpyDataCollatorIntegrationTest(unittest.TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]'] self.vocab_file = os.path.join(self.tmpdirname, 'vocab.txt') with open(self.vocab_file, 'w', encoding='utf-8'...
class CsvLogger(): def __init__(self, filepath='./', filename='validate_record.csv', data=None, fieldsnames=['epoch', 'train_loss', 'val_loss', 'Bleu_4', 'METEOR', 'ROUGE_L', 'CIDEr']): self.log_path = filepath if (not os.path.exists(filepath)): os.makedirs(filepath) if filename:...
def test_append_with_list_input(): context = Context({'arblist': [1, 2], 'append': {'list': PyString('arblist'), 'addMe': 3}}) append.run_step(context) context['append']['addMe'] = 4 append.run_step(context) assert (context['arblist'] == [1, 2, 3, 4]) assert (len(context) == 2)
class SourceGroup(): def __init__(self) -> None: self.audio_format = None self.video_format = None self.info = None self.duration = 0.0 self._timestamp_offset = 0.0 self._dequeued_durations = [] self._sources = [] self.is_player_source = False def ...
class InlineQueryResultAudio(InlineQueryResult): __slots__ = ('reply_markup', 'caption_entities', 'caption', 'title', 'parse_mode', 'audio_url', 'performer', 'input_message_content', 'audio_duration') def __init__(self, id: str, audio_url: str, title: str, performer: Optional[str]=None, audio_duration: Optional...
class ArgSpecCache(): DEFAULT_ARGSPECS = implementation.get_default_argspecs() def __init__(self, options: Options, ts_finder: TypeshedFinder, ctx: CanAssignContext, *, vnv_provider: Callable[([str], Optional[Value])]=(lambda _: None)) -> None: self.vnv_provider = vnv_provider self.options = opt...
def getSaveFileName(*, parent, title, filename, filter='', default_extension: str=None, default_filter: str=None, config: 'SimpleConfig') -> Optional[str]: directory = config.get('io_dir', os.path.expanduser('~')) path = os.path.join(directory, filename) file_dialog = QFileDialog(parent, title, path, filter...
class TestText(unittest.TestCase): def setUp(self): self.text_mock = mock.Mock() def test_setting_text(self): Text._set_text(self.text_mock, 'foo') self.assertEqual(self.text_mock.text, 'foo') def test_setting_color_with_color_provided(self): Text._set_color(self.text_mock, '...
class _ImageCollection(pystiche.ComplexObject): def __init__(self, images: Mapping[(str, _Image)]) -> None: self._images = images def __len__(self) -> int: return len(self._images) def __getitem__(self, name: str) -> _Image: return self._images[name] def __iter__(self) -> Iterato...
def test_gmail_checker_invalid_response(fake_qtile, monkeypatch, fake_window): monkeypatch.setitem(sys.modules, 'imaplib', FakeIMAP('imaplib')) reload(gmail_checker) gmc = gmail_checker.GmailChecker() fakebar = FakeBar([gmc], window=fake_window) gmc._configure(fake_qtile, fakebar) text = gmc.pol...
def setup_custom_environment(custom_module_path): module = import_file('maskrcnn_benchmark.utils.env.custom_module', custom_module_path) assert (hasattr(module, 'setup_environment') and callable(module.setup_environment)), "Custom environment module defined in {} does not have the required callable attribute 's...
class MCLP(LocateSolver, BaseOutputMixin, CoveragePercentageMixin): def __init__(self, name: str, problem: pulp.LpProblem): super().__init__(name, problem) def __add_obj(self, weights: np.array, range_clients: range) -> None: dem_vars = getattr(self, 'cli_vars') self.problem += (pulp.lpS...
class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False, norm=True, no_ffn=False, no_encoder_self_att=False): super().__init__() self.no_ffn = no_ffn self.no_encoder_self_att = no_encoder_self_a...
class QueryCreator(): def __init__(self, strict_mode=False): self.namer = VariableNamer() self.creator_for_op_name = {} self.creator_for_op_name['aggregate'] = QueryStepAggregate self.creator_for_op_name['select'] = QueryStepSelect self.creator_for_op_name['project'] = QueryS...
.parametrize('func', [(lambda x: x.sum()), (lambda x: x.count()), (lambda x: x.apply((lambda x: x))), (lambda x: x.full()), (lambda x: x.var()), (lambda x: x.std())], ids=['sum', 'count', 'apply', 'full', 'var', 'std']) def test_ewm_notimplemented(func): sdf = DataFrame(example=pd.DataFrame(columns=['x', 'y'])) ...
def pylsp_lint(workspace: Workspace, document: Document) -> List[Dict]: settings = load_settings(workspace, document.path) checks = run_ruff_check(document=document, settings=settings) diagnostics = [create_diagnostic(check=c, settings=settings) for c in checks] return converter.unstructure(diagnostics)
def decode_header(trf_header_contents: bytes) -> Header: match = _header_match(trf_header_contents) groups = match.groups() date = groups[0].decode('utf-8') timezone = groups[1].decode('utf-8') field = groups[2].decode('utf-8') machine = groups[3].decode('utf-8') mu = np.frombuffer(groups[4]...
class CalcChangeFitSystemSecurityCommand(wx.Command): def __init__(self, fitID, secStatus): wx.Command.__init__(self, True, 'Change Fit System Security') self.fitID = fitID self.secStatus = secStatus self.savedSecStatus = None def Do(self): pyfalog.debug('Doing changing s...
class TestSharedoc(ZiplineTestCase): def test_copydoc(self): def original_docstring_function(): pass (original_docstring_function) def copied_docstring_function(): pass self.assertEqual(original_docstring_function.__doc__, copied_docstring_function.__doc__)
def add_shared_install_options(parser: argparse.ArgumentParser): parser.add_argument('--user', action='store_true', default=None, help='Do a user-local install (default if site.ENABLE_USER_SITE is True)') parser.add_argument('--env', action='store_false', dest='user', help='Install into sys.prefix (default if s...
class TestDrivenMilesCompositeMetric(unittest.TestCase): def test_zero_miles(self) -> None: metric_results: Dict[(str, torch.Tensor)] = {metrics.SimulatedDrivenMilesMetric.metric_name: torch.zeros(10)} simulation_output = mock.Mock() validation_results = mock.Mock() dm_metric = cm.Dr...
class DebugInfoCommand(Command): name = 'debug info' description = 'Shows debug information.' def handle(self) -> int: poetry_python_version = '.'.join((str(s) for s in sys.version_info[:3])) self.line('') self.line('<b>Poetry</b>') self.line('\n'.join([f'<info>Version</info>...
.parametrize('when', ['setup', 'call', 'teardown']) def test_crashing_item(pytester, when) -> None: code = dict(setup='', call='', teardown='') code[when] = 'os._exit(1)' p = pytester.makepyfile('\n import os\n import pytest\n\n \n def fix():\n {setup}\n yie...
def get_user_field(question: str, default_value: Optional[str]=None, is_valid_answer: Optional[Callable]=None, convert_to: Optional[Callable]=None, fallback_message: Optional[str]=None) -> Any: if (not question.endswith(' ')): question = (question + ' ') if (default_value is not None): question ...
_fixtures(WebFixture) def test_distinguishing_identical_field_names(web_fixture): fixture = web_fixture class ModelObject(): fields = ExposedNames() fields.field_name = (lambda i: IntegerField()) model_object1 = ModelObject() model_object2 = ModelObject() class MyForm(Form): ...
_model def caformer_m36_in21ft1k(pretrained=False, **kwargs): model = MetaFormer(depths=[3, 12, 18, 3], dims=[96, 192, 384, 576], token_mixers=[SepConv, SepConv, Attention, Attention], head_fn=MlpHead, **kwargs) model.default_cfg = default_cfgs['caformer_m36_in21ft1k'] if pretrained: state_dict = to...
class LDAPUrlExtension(): def __init__(self, extensionStr=None, critical=0, extype=None, exvalue=None): self.critical = critical self.extype = extype self.exvalue = exvalue if extensionStr: self._parse(extensionStr) def _parse(self, extension): extension = ext...
def makeCfdMeshImported(name='ImportedCFDMesh'): doc = FreeCAD.ActiveDocument obj = doc.addObject('Fem::FemMeshObjectPython', name) _CaeMeshImported._CaeMeshImported(obj) if FreeCAD.GuiUp: from cfdguiobjects._ViewProviderCaeMesh import _ViewProviderCaeMesh _ViewProviderCaeMesh(obj.ViewOb...
class MemIfcRTL2FLAdapter(Component): def construct(s, ReqType, RespType): s.left = MemMinionIfcRTL(ReqType, RespType) s.right = MemMasterIfcFL() _once def up_memifc_rtl_fl_blk(): if (s.left.req.en and s.left.resp.rdy): if (s.left.req.msg.type_ == MemMsgTy...
def on_draw(): window.clear() glLoadIdentity() glLightfv(GL_LIGHT0, GL_POSITION, lightfv((- 40.0), 200.0, 100.0, 0.0)) glLightfv(GL_LIGHT0, GL_AMBIENT, lightfv(0.2, 0.2, 0.2, 1.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, lightfv(0.5, 0.5, 0.5, 1.0)) glEnable(GL_LIGHT0) glEnable(GL_LIGHTING) glE...
class ObjectMapping(): _models = morefusion.datasets.YCBVideoModels() def __init__(self): self.reset() self._n_votes = rospy.get_param('~n_votes', 3) self._base_frame = rospy.get_param('~frame_id', 'map') self._pub = rospy.Publisher('~output/poses', ObjectPoseArray, queue_size=1,...
class StructureMixIn(object): def __str__(self): lines = [] for (field_name, _) in getattr(self, '_fields_', []): lines.append(('%20s\t%s' % (field_name, getattr(self, field_name)))) return '\n'.join(lines) def __eq__(self, other): fields = getattr(self, '_fields_', [...
class Self_Attn(nn.Module): def __init__(self, in_dim, latent_dim=8): super(Self_Attn, self).__init__() self.channel_in = in_dim self.channel_latent = (in_dim // latent_dim) self.query_conv = nn.Conv2d(in_channels=in_dim, out_channels=(in_dim // latent_dim), kernel_size=1) se...
class Request(): first_party_url: Optional[QUrl] request_url: QUrl is_blocked: bool = False resource_type: Optional[ResourceType] = None def block(self) -> None: self.is_blocked = True def redirect(self, url: QUrl, *, ignore_unsupported: bool=False) -> None: raise NotImplementedE...
.end_to_end() def test_dry_run_skipped_successful(runner, tmp_path): source = '\n import pytask\n\n .produces("out.txt")\n def task_example(produces):\n produces.touch()\n ' tmp_path.joinpath('task_example.py').write_text(textwrap.dedent(source)) result = runner.invoke(cli, [tmp_path.as_p...
.parametrize('x, cohort, n, axis', [_random_cohort_data((20,), n=3, axis=0), _random_cohort_data((20, 20), n=2, axis=0, dtype=np.float32), _random_cohort_data((10, 10), n=2, axis=(- 1), scale=30, dtype=np.int16), _random_cohort_data((20, 20), n=3, axis=(- 1), missing=0.3), _random_cohort_data((7, 103, 4), n=5, axis=1, ...
class TestUmath(TestCase): def q(self): return ([1, 2, 3, 4] * pq.J) def test_prod(self): self.assertQuantityEqual(np.prod(self.q), (24 * (pq.J ** 4))) def test_sum(self): self.assertQuantityEqual(np.sum(self.q), (10 * pq.J)) def test_nansum(self): c = ([1, 2, 3, np.nan] ...
class ResourceDatabaseGenericModel(QtCore.QAbstractTableModel): def __init__(self, db: ResourceDatabase, resource_type: ResourceType): super().__init__() self.db = db self.resource_type = resource_type self.allow_edits = True def _get_items(self): return self.db.get_by_ty...
def names_modified_in_lvalue(lvalue: Lvalue) -> list[NameExpr]: if isinstance(lvalue, NameExpr): return [lvalue] elif isinstance(lvalue, StarExpr): return names_modified_in_lvalue(lvalue.expr) elif isinstance(lvalue, (ListExpr, TupleExpr)): result: list[NameExpr] = [] for ite...
def test_fixed_time_dependent_ding(): ocp = prepare_ocp(model=Model(time_as_states=False), n_stim=10, n_shooting=10, final_time=1, time_bimapping=False, use_sx=True) sol = ocp.solve() (force_vector, cn_vector, time_vector) = result_vectors(sol) plt.plot(time_vector, force_vector) plt.plot(time_vecto...
def test_initialize(): rnd = np.random.RandomState(0) x = rnd.normal(size=(13, 5)) y = rnd.randint(3, size=13) crf = ChainCRF(n_states=3, n_features=5) crf.initialize([x], [y]) crf = ChainCRF() crf.initialize([x], [y]) assert_equal(crf.n_states, 3) assert_equal(crf.n_features, 5) ...