code
stringlengths
281
23.7M
class LoggerDepthLoss(): def __init__(self, type='train', empty_value=0.0): super(LoggerDepthLoss, self).__init__() self.type = type self.empty_value = empty_value def tick(self, logs, out_rgb, target_rgb, out_depth, target_depth=None): if (target_depth is None): retu...
_cache(maxsize=1) def _float_max_string_len() -> int: PA_POS_FLOAT64_MAX_STR_BYTES = pc.binary_length(pc.cast(pa.scalar(np.finfo(np.float64).max, type=pa.float64()), pa.string())).as_py() PA_NEG_FLOAT64_MAX_STR_BYTES = pc.binary_length(pc.cast(pa.scalar(np.finfo(np.float64).min, type=pa.float64()), pa.string())...
class UnboundCollector(diamond.collector.ProcessCollector): def get_default_config_help(self): config_help = super(UnboundCollector, self).get_default_config_help() config_help.update({'bin': 'Path to unbound-control binary', 'histogram': 'Include histogram in collection'}) return config_hel...
class Tiny200_boxes(datasets.ImageFolder): def __init__(self, root, transform_rcrop, transform_ccrop, init_box=(0.0, 0.0, 1.0, 1.0), **kwargs): super().__init__(root=root, **kwargs) self.transform_rcrop = transform_rcrop self.transform_ccrop = transform_ccrop self.boxes = torch.tenso...
.parametrize('iterators', [[[1, 2, 3], [4, 5], [6, 7, 8]], [(i for i in range(1, 7)), (i for i in range(7, 9))]]) def test_flatten(iterators): source = Stream() L = source.flatten().sink_to_list() for iterator in iterators: source.emit(iterator) assert (L == [1, 2, 3, 4, 5, 6, 7, 8])
class MultiChoiceInstruction(Instruction): def __init__(self, data_name: str, data_list: List, verbalizer: Dict, instruction: str, keys_order: List[str], data_type: str): super(MultiChoiceInstruction, self).__init__(data_name, data_list, verbalizer, instruction, keys_order, data_type) self.NO_ANSWER...
class CNN_encoder(nn.Module): def __init__(self, hidden_states=256): super(CNN_encoder, self).__init__() self.encoder = nn.Sequential(nn.Conv2d(3, 32, (15, 23), stride=9), nn.ReLU(True), nn.Conv2d(32, 64, 3, stride=(1, 3)), nn.ReLU(True), nn.Conv2d(64, 96, (7, 3), stride=(1, 3)), nn.ReLU(True)) ...
class UserPersonalAccessTokenManager(CreateMixin, RESTManager): _path = '/users/{user_id}/personal_access_tokens' _obj_cls = UserPersonalAccessToken _from_parent_attrs = {'user_id': 'id'} _create_attrs = RequiredOptional(required=('name', 'scopes'), optional=('expires_at',)) _types = {'scopes': Arra...
def cache(repository_cache_dir: Path, repository_one: str, mock_caches: None) -> FileCache[dict[(str, str)]]: cache: FileCache[dict[(str, str)]] = FileCache(path=(repository_cache_dir / repository_one)) cache.remember('cachy:0.1', (lambda : {'name': 'cachy', 'version': '0.1'}), minutes=None) cache.remember(...
(st.sets(text)) def test_map_with_pad(tmpdir_factory, keys): trie = marisa_trie.Trie(keys) dirname = f'{str(uuid4())}_' path = str(tmpdir_factory.mktemp(dirname).join('trie.bin')) trie.save(path) data = ((b'pad' + open(path, 'rb').read()) + b'pad') trie2 = marisa_trie.Trie() trie2.map(memory...
def _send_twilio(msg, numbers): twilio_sid = (SMS_CREDENTIALS['sid'].strip().split(' ')[0] if ('sid' in SMS_CREDENTIALS) else None) twilio_token = (SMS_CREDENTIALS['token'].strip().split(' ')[0] if ('token' in SMS_CREDENTIALS) else None) twilio_from = (SMS_CREDENTIALS['from'].strip().split(' ')[0] if ('from...
def test_archs_platform_specific(platform, intercepted_build_args, monkeypatch): monkeypatch.setenv('CIBW_ARCHS', 'unused') monkeypatch.setenv('CIBW_ARCHS_LINUX', 'ppc64le') monkeypatch.setenv('CIBW_ARCHS_WINDOWS', 'x86') monkeypatch.setenv('CIBW_ARCHS_MACOS', 'x86_64') main() options = intercep...
('/api_save', methods=['POST']) def api_save(): flag = request.form['flag'] req_host = request.form['host'] req_api_name = request.form['api_name'] req_project_name = request.form['project_name'] req_url = request.form['url'] req_method = request.form['method'] req_data = request.form['data'...
class InitializationSection(BasePathMixin): tag = ext_x_map def __init__(self, base_uri, uri, byterange=None): self.base_uri = base_uri self.uri = uri self.byterange = byterange def __str__(self): output = [] if self.uri: output.append(('URI=' + quoted(sel...
def convert_net_g(ori_net, crt_net): for (crt_k, crt_v) in crt_net.items(): if ('style_mlp' in crt_k): ori_k = crt_k.replace('style_mlp', 'style') elif ('constant_input.weight' in crt_k): ori_k = crt_k.replace('constant_input.weight', 'input.input') elif ('style_conv1...
def get_word_list(line, dictionary): splitted_words = json.loads(line.lower()).split() words = ['<bos>'] for word in splitted_words: word = filter_symbols.search(word)[0] if (len(word) > 1): if dictionary.word2idx.get(word, False): words.append(word) e...
def import_question(element, save=False, user=None): try: question = Question.objects.get(uri=element.get('uri')) except Question.DoesNotExist: question = Question() set_common_fields(question, element) set_foreign_field(question, 'attribute', element) question.is_collection = (eleme...
def pytest_configure(config: pytest.Config): markers = [] if config.option.skip_generation_tests: markers.append('not skip_generation_tests') if config.option.skip_resolver_tests: markers.append('not skip_resolver_tests') if config.option.skip_gui_tests: markers.append('not skip_...
class CPythonmacOsFramework(CPython, metaclass=ABCMeta): def can_describe(cls, interpreter): return (is_mac_os_framework(interpreter) and super().can_describe(interpreter)) def create(self): super().create() target = self.desired_mach_o_image_path() current = self.current_mach_o_...
class BackBone(nn.Module): def __init__(self, opt): super(BackBone, self).__init__() self._name = 'BackBone' self._opt = opt self.model = self._init_create_networks() def _init_create_networks(self): if ((self._opt.pretrained_dataset == 'ferplus') or (self._opt.pretrained...
.fast def test_line_survey(verbose=True, plot=False, warnings=True, *args, **kwargs): _temp_file = 'radis_test_line_survey.html' if exists(_temp_file): os.remove(_temp_file) s = load_spec(getTestFile('CO_Tgas1500K_mole_fraction0.01.spec'), binary=True) s.line_survey(overlay='abscoeff', writefile...
def pytest_configure(config: Config) -> None: if config.getvalue('lsof'): checker = LsofFdLeakChecker() if checker.matching_platform(): config.pluginmanager.register(checker) config.addinivalue_line('markers', 'pytester_example_path(*path_segments): join the given path segments to `p...
def convert_folder_with_preds_back_to_BraTS_labeling_convention(input_folder: str, output_folder: str, num_processes: int=12): maybe_mkdir_p(output_folder) nii = subfiles(input_folder, suffix='.nii.gz', join=False) with multiprocessing.get_context('spawn').Pool(num_processes) as p: p.starmap(load_co...
class AutoTokenizer(object): def __init__(self): raise EnvironmentError('AutoTokenizer is designed to be instantiated using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method.') def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): if ('t5' in pretrai...
class BotConfigureTest(TestCase): def test_kwargs(self): bot = bot_factory() bot.provider.get_file.return_value = (None, None) bot.configure(branch='bogus-branch', pin='bogus-pin', close_prs='bogus-close') self.assertEqual(bot.config.branch, 'bogus-branch') self.assertEqual(b...
class ForwardSchedule(object): def __init__(self, timesteps, beta_start=0.0001, beta_end=0.02, mode='linear'): self.timesteps = timesteps self.beta_start = beta_start self.beta_end = beta_end self.mode = mode.lower() self.calc_vars() def get_scheduler(self): if (s...
def test_first_query_delay(): type_ = '_ zeroconf_browser = Zeroconf(interfaces=['127.0.0.1']) _wait_for_start(zeroconf_browser) old_send = zeroconf_browser.async_send first_query_time = None def send(out, addr=const._MDNS_ADDR, port=const._MDNS_PORT): nonlocal first_query_time i...
def test_outer_loading_bad_item_quantity(): bad_quantity_data = change(outer_sample_data, ['items', 0, 'quantity'], Decimal(0)) raises_exc(AggregateLoadError(f'while loading model {Receipt}', [with_trail(AggregateLoadError(f'while loading iterable {list}', [with_trail(AggregateLoadError(f'while loading model {R...
def performance(ob, fo, grade_list=[1e-30], member_list=None, save_path=None, show=False, dpi=300, title=''): sup_fontsize = 10 hfmc_array = hfmc(ob, fo, grade_list) pod = pod_hfmc(hfmc_array) sr = sr_hfmc(hfmc_array) leftw = 0.6 rightw = 2 uphight = 1.2 lowhight = 1.2 axis_size_x = ...
def update_alpha(gamma, p, Ap, has_converged, xnp): denom = xnp.sum((xnp.conj(p) * Ap), axis=(- 2), keepdims=True) alpha = do_safe_div(gamma, denom, xnp=xnp) device = xnp.get_device(p) alpha = xnp.where(has_converged, xnp.array(0.0, dtype=p.dtype, device=device), alpha) return alpha
class QAReplayMemory(object): def __init__(self, capacity=100000, priority_fraction=0.0, seed=None): self.rng = np.random.RandomState(seed) self.priority_fraction = priority_fraction self.alpha_capacity = int((capacity * priority_fraction)) self.beta_capacity = (capacity - self.alpha...
class KubernetesPodmanExecutor(KubernetesExecutor): def __init__(self, *args, **kwargs): super(KubernetesExecutor, self).__init__(*args, **kwargs) self.namespace = self.executor_config.get('BUILDER_NAMESPACE', 'builder') self.image = self.executor_config.get('BUILDER_CONTAINER_IMAGE', 'quay....
.functions def test_truncate_datetime_dataframe_all_parts(): x = datetime(2022, 3, 21, 9, 1, 15, 666) df = pd.DataFrame({'dt': [x], 'foo': [np.nan]}, copy=False) result = df.truncate_datetime_dataframe('second') assert (result.loc[(0, 'dt')] == datetime(2022, 3, 21, 9, 1, 15, 0)) result = df.truncat...
class TestLanguageModeling(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) def test_fconv_lm(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fconv_lm') as...
class A(HTMLElement): def from_bookmark(cls, view, bookmark): if bookmark.is_page_internal: raise ProgrammerError('You cannot use page-internal Bookmarks directly, first add it to a Bookmark to a View') return cls(view, bookmark.href, description=bookmark.description, ajax=bookmark.ajax,...
('pytube.cli._download') ('pytube.cli.YouTube') def test_download_audio_none(youtube, download): youtube_instance = youtube.return_value youtube_instance.streams.filter.return_value.order_by.return_value.last.return_value = None with pytest.raises(SystemExit): cli.download_audio(youtube_instance, 'f...
def _math_define_validator(value, values): if (not isinstance(value, tuple)): raise ValueError('Input value {} of trigger_select should be a tuple'.format(value)) if (len(value) != 3): raise ValueError('Number of parameters {} different from 3'.format(len(value))) output = (sanitize_source(v...
def test_request_pattern_generic_arg(): check_request_pattern(P[Dict].generic_arg(0, str), [LocatedRequest(loc_map=LocMap(TypeHintLoc(Dict))), LocatedRequest(loc_map=LocMap(TypeHintLoc(str), GenericParamLoc(0)))], fail=False) check_request_pattern(P[Dict].generic_arg(0, str), [LocatedRequest(loc_map=LocMap(Type...
.parametrize('key', FUNCTION_METHODS) def test_given_function_is_set_then_reading_avaliable(resetted_dmm6500, key): if (key[(- 2):] == 'ac'): getattr(resetted_dmm6500, FUNCTION_METHODS[key])(ac=True) elif (key[(- 2):] == '4W'): getattr(resetted_dmm6500, FUNCTION_METHODS[key])(wires=4) else: ...
class BloqExample(): _func: Callable[([], Bloq)] = field(repr=False, hash=False) name: str bloq_cls: Type[Bloq] generalizer: Callable[([Bloq], Optional[Bloq])] = (lambda x: x) def make(self) -> Bloq: return self._func() def __call__(self) -> Bloq: return self.make()
.parametrize('aoi_model', ['sapm', 'ashrae', 'physical', 'martin_ruiz']) def test_aoi_models_singleon_weather_single_array(sapm_dc_snl_ac_system, location, aoi_model, weather): mc = ModelChain(sapm_dc_snl_ac_system, location, dc_model='sapm', aoi_model=aoi_model, spectral_model='no_loss') mc.run_model(weather=[...
def test_kaiming_init(): conv_module = nn.Conv2d(3, 16, 3) kaiming_init(conv_module, bias=0.1) assert conv_module.bias.allclose(torch.full_like(conv_module.bias, 0.1)) kaiming_init(conv_module, distribution='uniform') with pytest.raises(AssertionError): kaiming_init(conv_module, distribution...
def get_external_models(): mmcv_home = _get_mmcv_home() default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json') default_urls = load_file(default_json_path) assert isinstance(default_urls, dict) external_json_path = osp.join(mmcv_home, 'open_mmlab.json') if osp.exists(external...
class Properties(PymiereBaseObject): def __init__(self, pymiere_id=None): super(Properties, self).__init__(pymiere_id) def bind(self, eventName, function): self._check_type(eventName, str, 'arg "eventName" of function "Properties.bind"') self._check_type(function, any, 'arg "function" of...
def test_set_scale(qapp, imgfilename3x3): item = BeePixmapItem(QtGui.QImage(imgfilename3x3), imgfilename3x3) item.prepareGeometryChange = MagicMock() item.setScale(3) assert (item.scale() == 3) assert (item.pos().x() == 0) assert (item.pos().y() == 0) item.prepareGeometryChange.assert_called...
class JWNumberRestrictOperatorTest(unittest.TestCase): def test_jw_restrict_operator(self): n_qubits = 4 target_electrons = 2 penalty_const = 10.0 number_sparse = jordan_wigner_sparse(number_operator(n_qubits)) bias_sparse = jordan_wigner_sparse(sum([FermionOperator(((i, 1), ...
class FlowchartViewBox(ViewBox): def __init__(self, widget, *args, **kwargs): ViewBox.__init__(self, *args, **kwargs) self.widget = widget def getMenu(self, ev): self._fc_menu = QtWidgets.QMenu() self._subMenus = self.getContextMenus(ev) for menu in self._subMenus: ...
class ImbalancedDatasetSampler(torch.utils.data.sampler.Sampler): def __init__(self, dataset, indices=None, num_samples=None): self.indices = (list(range(len(dataset))) if (indices is None) else indices) self.num_samples = (len(self.indices) if (num_samples is None) else num_samples) label_t...
def test_get_transfer_secret_none_for_none_transfer_state(chain_state): secret = factories.make_secret() transfer = factories.create(factories.LockedTransferUnsignedStateProperties(secret=secret)) secrethash = transfer.lock.secrethash payment_state = InitiatorPaymentState(initiator_transfers={secrethash...
class VQModel(pl.LightningModule): def __init__(self, ddconfig, lossconfig, n_embed, embed_dim, ckpt_path=None, ignore_keys=[], image_key='image', colorize_nlabels=None, monitor=None, remap=None, sane_index_shape=False): super().__init__() self.image_key = image_key self.encoder = Encoder(**...
class MessageDataModel(): def _count_tokens(test_string: str) -> int: enc = tiktoken.get_encoding('cl100k_base') tokens = len(enc.encode(test_string)) return tokens def _get_num_tokens_from_messages(cls, buffer: List[BaseMessage]) -> int: return sum([cls._count_tokens(m.content) ...
def model_fixture(request: SubRequest, factory_name: str) -> Any: factoryboy_request: FactoryboyRequest = request.getfixturevalue('factoryboy_request') factoryboy_request.evaluate(request) assert request.fixturename fixture_name = request.fixturename prefix = ''.join((fixture_name, SEPARATOR)) f...
def fold_all_batch_norms(sess: tf.compat.v1.Session, input_op_names: Union[(str, List[str])], output_op_names: Union[(str, List[str])]) -> Tuple[(tf.compat.v1.Session, List[Tuple[(tf.Operation, tf.Operation)]])]: if (not isinstance(input_op_names, (str, List))): logger.error('start op names must be passed a...
class PipelineTestCase(TestCase): if PY2: def assertRaisesRegex(self, *args, **kwargs): return self.assertRaisesRegexp(*args, **kwargs) def test_construction(self): p0 = Pipeline() self.assertEqual(p0.columns, {}) self.assertIs(p0.screen, None) columns = {'f':...
def parse_config(): parser = ArgumentParser() parser.add_argument('--gpu', type=int, nargs='+', default=(0,), help='specify gpu devices') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--config_path', default='config/2DPASS-semantickitti.yaml') parser.add_argument('--log_dir...
class ResNet(nn.Module): def __init__(self, *, d_numerical: int, categories: ty.Optional[ty.List[int]], d_embedding: int, d: int, d_hidden_factor: float, n_layers: int, activation: str, normalization: str, hidden_dropout: float, residual_dropout: float, d_out: int) -> None: super().__init__() def ma...
class PyTorchClassifier(object): def __init__(self, inputdim, nclasses, l2reg=0.0, batch_size=64, seed=1111, cudaEfficient=False): np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) self.inputdim = inputdim self.nclasses = nclasses self.l2reg = ...
def INSgrow_Gap(sub_ptn, I): global compnum global NumbS global sDB global IPLUS compnum = (compnum + 1) support = 0 global ptn_len ptn_len = len(sub_ptn) p = sub_ptn[(ptn_len - 1)].end IPLUS = copy.deepcopy(I) for i in range(0, NumbS): if (len(sDB[i].S) > 0): ...
def main(): connection = establish_tcp_connection() h2_connection = h2.connection.H2Connection() settings_header_value = h2_connection.initiate_upgrade_connection() send_initial_request(connection, settings_header_value) extra_data = get_upgrade_response(connection) connection.sendall(h2_connect...
_sentencepiece _tokenizers class MBartTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = MBartTokenizer rust_tokenizer_class = MBartTokenizerFast test_rust_tokenizer = True test_sentencepiece = True def setUp(self): super().setUp() tokenizer = MBartTokenizer...
class IfExp(NodeNG): _astroid_fields = ('test', 'body', 'orelse') test: NodeNG body: NodeNG orelse: NodeNG def postinit(self, test: NodeNG, body: NodeNG, orelse: NodeNG) -> None: self.test = test self.body = body self.orelse = orelse def get_children(self): (yield...
def dbref(inp, reqhash=True): if (reqhash and (not (isinstance(inp, str) and inp.startswith('#')))): return None if isinstance(inp, str): inp = inp.lstrip('#') try: if (int(inp) < 0): return None except Exception: return None return inp
class Data(object): time = 0 host = None plugin = None plugininstance = None type = None typeinstance = None def __init__(self, **kw): [setattr(self, k, v) for (k, v) in kw.items()] def datetime(self): return datetime.fromtimestamp(self.time) def source(self): ...
class RacketLexer(RegexLexer): name = 'Racket' url = ' aliases = ['racket', 'rkt'] filenames = ['*.rkt', '*.rktd', '*.rktl'] mimetypes = ['text/x-racket', 'application/x-racket'] version_added = '1.6' _keywords = ('#%app', '#%datum', '#%declare', '#%expression', '#%module-begin', '#%plain-ap...
class CodeGenOnnxConfig(OnnxConfigWithPast): def __init__(self, config: PretrainedConfig, task: str='default', patching_specs: List[PatchingSpec]=None, use_past: bool=False): super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past) if (not getattr(self._config, 'pad_toke...
def _create_session_with_discord_token(sa: ServerApp, sid: (str | None)) -> User: discord_user = sa.discord.fetch_user() if (sa.enforce_role is not None): if (not sa.enforce_role.verify_user(discord_user.id)): logger().info('User %s is not authorized for connecting to the server', discord_us...
def ground_sort(i_op, qdmr, grounding_out): assert (qdmr.ops[i_op] == 'sort') if (len(qdmr.args[i_op]) == 3): (data_arg, sort_arg, sort_dir_arg) = qdmr.args[i_op] else: (data_arg, sort_arg) = qdmr.args[i_op] sort_dir_arg = None if (sort_dir_arg is not None): is_ascending_...
_module() class XMLDataset(CustomDataset): def __init__(self, min_size=None, **kwargs): assert (self.CLASSES or kwargs.get('classes', None)), 'CLASSES in `XMLDataset` can not be None.' super(XMLDataset, self).__init__(**kwargs) self.cat2label = {cat: i for (i, cat) in enumerate(self.CLASSES)...
class BoW(nn.Module): def __init__(self, vocab: List[str], word_weights: Dict[(str, float)]={}, unknown_word_weight: float=1, cumulative_term_frequency: bool=True): super(BoW, self).__init__() vocab = list(set(vocab)) self.config_keys = ['vocab', 'word_weights', 'unknown_word_weight', 'cumul...
class LineEditDelegate(QtWidgets.QStyledItemDelegate): def createEditor(self, parent, option, index): editor = QtWidgets.QLineEdit(parent) editor.setValidator(ExpressionValidator()) return editor def setEditorData(self, editor, index): value = index.data(QtCore.Qt.ItemDataRole.Di...
def check_resp(resp, value, frequency, limit_db, prelude, context): try: value_resp = num.abs(evaluate1(resp, frequency)) except response.InvalidResponseError as e: return Delivery(log=[('warning', ('Could not check response: %s' % str(e)), context)]) if (value_resp == 0.0): return D...
class Panorama(Primitive): def __init__(self, panorama, center=vec3(0.0, 0.0, 0.0), light_intensity=0.0, blur=0.0): super().__init__(center, SkyBox_Material(panorama, light_intensity, blur), shadow=False) l = SKYBOX_DISTANCE self.light_intensity = light_intensity self.collider_list +...
def find_memory_type(phys_addr): if (phys_addr == 0): return 'N/A' if is_system_ram(phys_addr): return 'System RAM' if is_persistent_mem(phys_addr): return 'Persistent Memory' f.seek(0, 0) for j in f: m = re.split('-|:', j, 2) if (int(m[0], 16) <= phys_addr <=...
class Blocks(): def __init__(self, tessellation, edges, buildings, id_name, unique_id): self.tessellation = tessellation self.edges = edges self.buildings = buildings self.id_name = id_name self.unique_id = unique_id if (id_name in buildings.columns): rais...
class Target(object): def __init__(self, targetInfo: Dict, browserContext: 'BrowserContext', sessionFactory: Callable[([], Coroutine[(Any, Any, CDPSession)])], ignoreHTTPSErrors: bool, defaultViewport: Optional[Dict], screenshotTaskQueue: List, loop: asyncio.AbstractEventLoop) -> None: self._targetInfo = ta...
def extract_and_save_image(dataset, save_dir): if osp.exists(save_dir): print('Folder "{}" already exists'.format(save_dir)) return print('Extracting images to "{}" ...'.format(save_dir)) mkdir_if_missing(save_dir) for i in range(len(dataset)): (img, label) = dataset[i] c...
class ResNet101FeatureExtractor(nn.Module): def __init__(self, use_input_norm=True, device=torch.device('cpu')): super(ResNet101FeatureExtractor, self).__init__() model = torchvision.models.resnet101(pretrained=True) self.use_input_norm = use_input_norm if self.use_input_norm: ...
class CbEnterpriseEdr(Product): product: str = 'cbc' profile: str = 'default' token: Optional[str] = None org_key: Optional[str] = None _device_group: Optional[list[str]] = None _device_policy: Optional[list[str]] = None _conn: CBCloudAPI _limit: int = (- 1) _raw: bool = False de...
def _best_effort_input_batch_size(flat_input): for input_ in flat_input: shape = input_.shape if (shape.ndims is None): continue if (shape.ndims < 2): raise ValueError(('Expected input tensor %s to have rank at least 2' % input_)) batch_size = shape[1].value ...
def main(options, arguments): global previous_time previous_time = time.time() phases_path = options.input if (options.output == None): outfile = phases_path.replace('.txt', '-diffs.json') else: outfile = options.output hashes_dic = read_phashes_manifest(phases_path) hashes =...
def extract_T1_features(wf, feature_type='histogram_whole_scan'): feature_type = feature_type.lower() basename = (lambda name: splitext(name)[0]) if (wf.mri_name is not None): prefix = (basename(wf.mri_name) + '_') else: prefix = '' out_csv_name = '{}{}_features.csv'.format(prefix, f...
class ToggleValidationFixture(FileUploadInputFixture): make_validation_fail = False def new_domain_object(self): fixture = self class DomainObject(): fields = ExposedNames() def make_field(self): field = FileField(allow_multiple=True, label='Attached files...
class PlayQueryBlockNBT(Packet): id = 1 to = 0 def __init__(self, transaction_id: int, x: int, y: int, z: int) -> None: super().__init__() self.transaction_id = transaction_id (self.x, self.y, self.z) = (x, y, z) def decode(cls, buf: Buffer) -> PlayQueryBlockNBT: return c...
def icon_name(name): return {'stackoverflow': 'stack-overflow', 'google-oauth': 'google', 'google-oauth2': 'google', 'google-openidconnect': 'google', 'yahoo-oauth': 'yahoo', 'facebook-app': 'facebook', 'email': 'envelope', 'vimeo': 'vimeo-square', 'linkedin-oauth2': 'linkedin', 'vk-oauth2': 'vk', 'live': 'windows'...
class Net(): def __init__(self, points, features, is_training, setting): bn_decay = setting.get_bn_decay(tf.train.get_global_step()) l0_xyz = points l0_points = None num_class = setting.num_class (l1_xyz, l1_points) = pointnet_sa_module_msg(l0_xyz, l0_points, 512, [0.1, 0.2, ...
_reduction _guvectorize(['(uint8[:], int64[:], int8[:], float64[:])', '(uint64[:], int64[:], int8[:], float64[:])', '(int8[:], int64[:], int8[:], float64[:])', '(int64[:], int64[:], int8[:], float64[:])', '(float32[:], int64[:], int8[:], float32[:])', '(float64[:], int64[:], int8[:], float64[:])'], '(n),(n),(c)->(c)') ...
def update_world(world, time_elapsed): num_substeps = world.env.get_num_update_substeps() timestep = (time_elapsed / num_substeps) num_substeps = (1 if (time_elapsed == 0) else num_substeps) for i in range(num_substeps): world.update(timestep) valid_episode = world.env.check_valid_episod...
class Continuous_MountainCarEnv(gym.Env): metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 30} def __init__(self): self.min_action = (- 1.0) self.max_action = 1.0 self.min_position = (- 1.2) self.max_position = 0.6 self.max_speed = 0.07 ...
_cell_magic def workspacefile(line: str, cell: str) -> None: workspace = get_workspace() (fs, path) = fsspec.core.url_to_fs(workspace) path = posixpath.join(path, line) base = posixpath.dirname(path) if (not fs.exists(base)): fs.mkdirs(base, exist_ok=True) with fs.open(path, 'wt') as f: ...
class Stem(nn.Module): def __init__(self, in_channels, stem_channels, out_channels, expand_ratio, conv_cfg=None, norm_cfg=dict(type='BN'), with_cp=False): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.conv_cfg = conv_cfg self.norm_cfg...
class VContainer(SplitContainer): def __init__(self, area): SplitContainer.__init__(self, area, QtCore.Qt.Orientation.Vertical) def type(self): return 'vertical' def updateStretch(self): x = 0 y = 0 sizes = [] for i in range(self.count()): (wx, wy)...
def _set_image_or_guide(self, image_or_guide: torch.Tensor, attr: str, comparison_only: bool=False, **kwargs: Any) -> None: for op in self._losses(): if (comparison_only and (not isinstance(op, loss.ComparisonLoss))): continue setter = getattr(op, f'set_{attr}') setter(image_or_g...
class WeaviateUploader(BaseUploader): client = None upload_params = {} def init_client(cls, host, distance, connection_params, upload_params): url = f" WEAVIATE_DEFAULT_PORT)}" cls.client = Client(url, **connection_params) cls.upload_params = upload_params cls.connection_para...
def fake_validator(*errors): errors = list(reversed(errors)) class FakeValidator(): def __init__(self, *args, **kwargs): pass def iter_errors(self, instance): if errors: return errors.pop() return [] def check_schema(self, schema): ...
.usefixtures('mock_os_environ') def test_file_argument_force_overwrite(testdir): testdir.makeini('\n [pytest]\n env_files =\n myenv.txt\n ') testdir.maketxtfile(myenv='FOO=BAR\nSPAM=EGGS') tmp_env_file = testdir.maketxtfile(tmpenv='FOO=BAZ\nBAR=SPAM') testdir.makepyfile("\n ...
def collate_fn_mmg(batch): (obj_point_list, obj_label_list, obj_2d_feats) = ([], [], []) rel_label_list = [] (edge_indices, descriptor) = ([], []) batch_ids = [] count = 0 for (i, b) in enumerate(batch): obj_point_list.append(b[0]) obj_2d_feats.append(b[1]) obj_label_list...
class MultiSelfAttention(SequenceMapper): def __init__(self, n_heads: int, project_size: Optional[int], memory_size: Optional[int]=None, shared_project: bool=False, project_bias: bool=False, bilinear_comp: bool=False, init='glorot_uniform', merge: Optional[MergeLayer]=None, scale=True, bias=True): self.n_he...
def tensor6(name: Optional[str]=None, *, dtype: Optional['DTypeLike']=None, shape: Optional[tuple[(ST, ST, ST, ST, ST, ST)]]=(None, None, None, None, None, None)) -> 'TensorVariable': if (dtype is None): dtype = config.floatX shape = _validate_static_shape(shape, ndim=6) type = TensorType(dtype, sha...
def test_fips_metadata_excludes_md5_and_blake2(monkeypatch): replaced_blake2b = pretend.raiser(ValueError('fipsmode')) replaced_md5 = pretend.raiser(ValueError('fipsmode')) monkeypatch.setattr(package_file.hashlib, 'md5', replaced_md5) monkeypatch.setattr(package_file.hashlib, 'blake2b', replaced_blake2...
def test_all_coarse_grains_for_blackbox(): blackbox = macro.Blackbox(((0, 1),), (0, 1)) assert (list(macro.all_coarse_grains_for_blackbox(blackbox)) == [macro.CoarseGrain(((0, 1),), (((0, 1), (2,)),)), macro.CoarseGrain(((0, 1),), (((0, 2), (1,)),)), macro.CoarseGrain(((0, 1),), (((0,), (1, 2)),))])