code
stringlengths
281
23.7M
def _get_num_els_in_scene_range(zarr_dataset: ChunkedDataset, scene_index_start: int, scene_index_end: int) -> dict: assert (scene_index_end > scene_index_start) scene_start = zarr_dataset.scenes[scene_index_start] scene_end = zarr_dataset.scenes[(scene_index_end - 1)] frame_start = zarr_dataset.frames[...
def main(args): tf.logging.set_verbosity(tf.logging.INFO) model_cls_list = [models.get_model(model) for model in args.models] params_list = [default_parameters() for _ in range(len(model_cls_list))] params_list = [merge_parameters(params, model_cls.get_parameters()) for (params, model_cls) in zip(params...
class TestPattern(): def test_default(self, temp_dir, helpers): config = {'path': 'baz.py', 'pattern': True} metadata = ProjectMetadata(str(temp_dir), PluginManager(), {'project': {'name': 'foo', 'dynamic': ['version']}, 'tool': {'hatch': {'metadata': {'hooks': {'custom': {}}}}}}) file_path ...
def collect_results_gpu(result_part, size): (rank, world_size) = get_dist_info() part_tensor = torch.tensor(bytearray(pickle.dumps(result_part)), dtype=torch.uint8, device='cuda') shape_tensor = torch.tensor(part_tensor.shape, device='cuda') shape_list = [shape_tensor.clone() for _ in range(world_size)]...
def get_dummy_input(T=100, D=80, B=5, K=100): forward_input = {} feature = torch.randn(B, T, D) src_lengths = torch.from_numpy(np.random.randint(low=1, high=T, size=B, dtype=np.int64)) src_lengths[0] = T prev_output_tokens = [] for b in range(B): token_length = np.random.randint(low=1, h...
class Describe_MarkerFactory(): def it_constructs_the_appropriate_marker_object(self, call_fixture): (marker_code, stream_, offset_, marker_cls_) = call_fixture marker = _MarkerFactory(marker_code, stream_, offset_) marker_cls_.from_stream.assert_called_once_with(stream_, marker_code, offset...
class MinDistanceHandle(SliderHandle): tip = 'min_distance' def __init__(self, window, player): super().__init__(window, player, 1, 0.6) def get_value(self): return (self.player.min_distance / 5.0) def set_value(self, value): self.player.min_distance = (value * 5.0)
def dump(state): if (not options.DUMP_PRE_ERROR_STATE): return stdout.flush() stderr.flush() stdout.write('\n--- Pre-error state dump: \n') try: state.dump() finally: stdout.write('\n') stderr.write('\n') stdout.flush() stderr.flush()
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.browser = QWebEngineView() self.browser.setUrl(QUrl(' self.browser.urlChanged.connect(self.update_urlbar) self.browser.loadFinished.connect(self.update_t...
def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): t = time.time() file = Path(file) cookie = Path('cookie') print(f'Downloading as {file}... ', end='') file.unlink(missing_ok=True) cookie.unlink(missing_ok=True) out = ('NUL' if (platform.system() == 'Windows') els...
class GATModule(nn.Module): def __init__(self, dim, hidden_dim_multiplier, num_heads, dropout, **kwargs): super().__init__() _check_dim_and_num_heads_consistency(dim, num_heads) self.dim = dim self.num_heads = num_heads self.head_dim = (dim // num_heads) self.input_li...
.usefixtures('save_env') class TestInstallData(support.TempdirManager): def test_simple_run(self): (pkg_dir, dist) = self.create_dist() cmd = install_data(dist) cmd.install_dir = inst = os.path.join(pkg_dir, 'inst') one = os.path.join(pkg_dir, 'one') self.write_file(one, 'xxx...
class Effect5484(BaseEffect): runTime = 'early' type = 'passive' def handler(fit, implant, context, projectionRange, **kwargs): fit.appliedImplants.filteredItemMultiply((lambda mod: (mod.item.group.name == 'Special Edition Implant')), 'armorHpBonus2', implant.getModifiedItemAttr('implantSetChristmas...
def eth_nodes_to_cmds(nodes_configuration: List[Dict[(str, Any)]], eth_node_descs: List[EthNodeDescription], base_datadir: str, genesis_file: str, chain_id: ChainID, verbosity: str) -> List[Command]: cmds = [] for (config, node_desc) in zip(nodes_configuration, eth_node_descs): datadir = eth_node_to_dat...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--smiles_file', default='data/guacamol_v1_all.smiles') parser.add_argument('--seed', type=int, default=42) parser.add_argument('--population_size', type=int, default=100) parser.add_argument('--n_mutations', type=int, default=200) ...
def setup_environment(): global _ENV_SETUP_DONE if _ENV_SETUP_DONE: return _ENV_SETUP_DONE = True _configure_libraries() custom_module_path = os.environ.get('FASTREID_ENV_MODULE') if custom_module_path: setup_custom_environment(custom_module_path) else: pass
def node_mssp_start(wizard): mssp_module = mod_import(settings.MSSP_META_MODULE) filename = mssp_module.__file__ text = f''' MSSP (Mud Server Status Protocol) allows online MUD-listing sites/crawlers to continuously monitor your game and list information about it. Some of this, like active playe...
def gather_container(container, dst, group=None, cat_dim=0): group = (group or dist.group.WORLD) world_size = dist.get_world_size(group) this_rank = dist.get_rank(group) def _do_gather(tensor): if (this_rank == dst): tensor_list = [torch.empty_like(tensor) for _ in range(world_size)]...
def loads(__s: str, *, parse_float: ParseFloat=float) -> dict[(str, Any)]: src = __s.replace('\r\n', '\n') pos = 0 out = Output(NestedDict(), Flags()) header: Key = () parse_float = make_safe_parse_float(parse_float) while True: pos = skip_chars(src, pos, TOML_WS) try: ...
class HCaptcha(CaptchaService): __name__ = 'HCaptcha' __type__ = 'anticaptcha' __version__ = '0.04' __status__ = 'testing' __description__ = 'hCaptcha captcha service plugin' __license__ = 'GPLv3' __authors__ = [('GammaC0de', 'nitzo2001[AT]yahoo[DOT]com')] KEY_PATTERN = '(?:data-sitekey=...
def test_formatting(): _ = Catalogue('reahl-component') date = datetime.date(2012, 1, 10) with LocaleContextStub() as context: context.test_locale = 'en_gb' assert (_.current_locale == 'en_gb') actual = babel.dates.format_date(date, format='long', locale=_.current_locale) ass...
class UNet3D(Abstract3DUNet): def __init__(self, in_channels, out_channels, final_sigmoid=True, f_maps=64, layer_order='gcr', num_groups=8, num_levels=4, is_segmentation=True, **kwargs): super(UNet3D, self).__init__(in_channels=in_channels, out_channels=out_channels, final_sigmoid=final_sigmoid, basic_modul...
_rewriter([gemm_no_inplace]) def local_gemm_to_ger(fgraph, node): if (node.op == gemm_no_inplace): (z, a, x, y, b) = node.inputs if (x.broadcastable[1] and y.broadcastable[0]): xv = x.dimshuffle(0) yv = y.dimshuffle(1) try: bval = ptb.get_underlyin...
def construct_onion_error(reason: OnionRoutingFailureMessage, onion_packet: OnionPacket, our_onion_private_key: bytes) -> bytes: failure_msg = reason.to_bytes() failure_len = len(failure_msg) pad_len = (256 - failure_len) assert (pad_len >= 0) error_packet = failure_len.to_bytes(2, byteorder='big') ...
.parametrize('x, mode, exc', [(set_test_value(pt.dmatrix(), (lambda x: x.T.dot(x))(rng.random(size=(3, 3)).astype('float64'))), 'reduced', None), (set_test_value(pt.dmatrix(), (lambda x: x.T.dot(x))(rng.random(size=(3, 3)).astype('float64'))), 'r', None), (set_test_value(pt.lmatrix(), (lambda x: x.T.dot(x))(rng.integer...
_fixtures(WebFixture, FormLayoutFixture) def test_adding_checkboxes(web_fixture, form_layout_fixture): class DomainObjectWithBoolean(): fields = ExposedNames() fields.an_attribute = (lambda i: BooleanField(label='Some input', required=True)) fixture = form_layout_fixture fixture.domain_objec...
class Resource(): locator = (lambda class_name: locate(('recurly.resources.%s' % class_name))) def cast_file(cls, response): klass = cls.locator('BinaryFile') resource = klass() setattr(resource, 'data', response.body) return resource def cast_error(cls, response): if...
def collect_bn_params(model, bn_candidate_layers): params = [] names = [] for (nm, m) in model.named_modules(): for candidate in bn_candidate_layers: if isinstance(m, candidate): for (np, p) in m.named_parameters(): if (np in ['weight', 'bias']): ...
class SeedMixin(BaseMixin): def __init__(self, random_seed=None, *args, **kwargs): super(SeedMixin, self).__init__(*args, **kwargs) self.random_seed = random_seed self._rng = RNG(seed=self.random_seed) def make_random_seed(self): return self._rng.randint(((2 ** 31) - 1))
class Site(Object): name = Unicode.T(default='', xmltagname='Name') description = Unicode.T(optional=True, xmltagname='Description') town = Unicode.T(optional=True, xmltagname='Town') county = Unicode.T(optional=True, xmltagname='County') region = Unicode.T(optional=True, xmltagname='Region') co...
class open_with(Command): def execute(self): (app, flags, mode) = self._get_app_flags_mode(self.rest(1)) self.fm.execute_file(files=self.fm.thistab.get_selection(), app=app, flags=flags, mode=mode) def tab(self, tabnum): return self._tab_through_executables() def _get_app_flags_mode(...
def test_dist_name(copy_sample): td = copy_sample('altdistname') make_wheel_in((td / 'pyproject.toml'), td) res = (td / 'package_dist1-0.1-py2.py3-none-any.whl') assert_isfile(res) with unpack(res) as td_unpack: assert_isdir(Path(td_unpack, 'package_dist1-0.1.dist-info'))
class UnzipWrapper(): def __init__(self, fp): self.__decoder = zlib.decompressobj((- zlib.MAX_WBITS)) self.__data = b'' self.__crc = (zlib.crc32(self.__data) & CRC_MASK) self.__fp = fp self.__size = 0 self.__is_fully_read = False def read(self, sz=(- 1)): ...
def open_url(url: str, cache_dir: str=None, num_attempts: int=10, verbose: bool=True) -> Any: assert is_url(url) assert (num_attempts >= 1) url_md5 = hashlib.md5(url.encode('utf-8')).hexdigest() if (cache_dir is not None): cache_files = glob.glob(os.path.join(cache_dir, (url_md5 + '_*'))) ...
def regex_match_score(prediction, pattern): try: compiled = re.compile(pattern, flags=((re.IGNORECASE + re.UNICODE) + re.MULTILINE)) except BaseException: print(('Regular expression failed to compile: %s' % pattern)) return False return (compiled.match(prediction) is not None)
_settings(MEDIA_ROOT=tempfile.mkdtemp()) class TestReviewWavefront(SetUpTest, TestCase): fixtures = ['fixtures/simplemenu.json'] def setUp(self): super(TestReviewWavefront, self).setUp() login = self.client.login(username='creator', password='password') self.assertTrue(login) url...
_optionals.HAS_CPLEX.require_in_instance class CplexOptimizer(OptimizationAlgorithm): def __init__(self, disp: bool=False, cplex_parameters: Optional[Dict[(str, Any)]]=None) -> None: self._disp = disp self._cplex_parameters = cplex_parameters def is_cplex_installed(): return _optionals.H...
(everythings(min_int=(- ), max_int=, allow_null_bytes_in_keys=False, allow_datetime_microseconds=False), booleans()) def test_bson_converter(everything: Everything, detailed_validation: bool): converter = bson_make_converter(detailed_validation=detailed_validation) raw = converter.dumps(everything, codec_option...
class IndexedDataset(FairseqDataset): _HDR_MAGIC = b'TNTIDX\x00\x00' def __init__(self, path, fix_lua_indexing=False): super().__init__() self.path = path self.fix_lua_indexing = fix_lua_indexing self.data_file = None self.read_index(path) def read_index(self, path): ...
def distorted_inputs(data_dir, batch_size): filenames = [os.path.join(data_dir, ('data_batch_%d.bin' % i)) for i in xrange(1, 6)] for f in filenames: if (not tf.gfile.Exists(f)): raise ValueError(('Failed to find file: ' + f)) filename_queue = tf.train.string_input_producer(filenames) ...
(cache={}, maxmem=None) def bipartition_indices(N): result = [] if (N <= 0): return result for i in range((2 ** (N - 1))): part = [[], []] for n in range(N): bit = ((i >> n) & 1) part[bit].append(n) result.append((tuple(part[1]), tuple(part[0]))) r...
class Dragon(Monster): def __init__(self, name: str, hasWings: bool): self.name = name self.hasWings = hasWings self.canBreatheFire = True def copy(self) -> Monster: try: return deepcopy(self) except: raise CloneNotSupportedException
_on_failure .parametrize('channels_per_node', [CHAIN]) .parametrize('number_of_nodes', [3, 4, 5]) def test_mediated_transfer(raiden_network: List[RaidenService], number_of_nodes, deposit, token_addresses, network_wait, bench): apps = raiden_network token_address = token_addresses[0] chain_state = views.stat...
class DescribeRenderedPageBreak(): def it_raises_on_preceding_fragment_when_page_break_is_not_first_in_paragrah(self, fake_parent: t.ProvidesStoryPart): p_cxml = 'w:p/(w:r/(w:t"abc",w:lastRenderedPageBreak,w:lastRenderedPageBreak))' p = cast(CT_P, element(p_cxml)) lrpb = p.lastRenderedPageBr...
class RotationInvariantPooling(nn.Module): def __init__(self, nInputPlane, nOrientation=8): super(RotationInvariantPooling, self).__init__() self.nInputPlane = nInputPlane self.nOrientation = nOrientation def forward(self, x): (N, c, h, w) = x.size() x = x.view(N, (- 1), ...
class RFC822Name(GeneralName): def __init__(self, value: str) -> None: if isinstance(value, str): try: value.encode('ascii') except UnicodeEncodeError: raise ValueError('RFC822Name values should be passed as an A-label string. This means unicode charac...
def test_loop(dataloader, model, loss_fn): size = len(dataloader.dataset) num_batches = len(dataloader) (test_loss, correct) = (0, 0) with torch.no_grad(): for (X, y) in dataloader: pred = model(X) test_loss += loss_fn(pred, y).item() correct += (pred.argmax(1...
class PreferencesButton(Gtk.HBox): def __init__(self, browser, model): super().__init__() sort_orders = [(_('_Title'), self.__compare_title), (_('_People'), self.__compare_people), (_('_Date'), self.__compare_date), (_('_Date Added'), self.__compare_date_added), (_('_Original Date'), self.__compare_...
class Callback_Functions(): def read_mem(ql: Qiling, *args): user_data = args[(- 1)] buff = ql.mem.read(user_data['address'], user_data['bytes_size']) ql.log.info(f"Hook was triggered at -> {user_data['address']}") ql.log.info(buff) def read_reg(ql: Qiling, *args): user_d...
('plaintext, encoding, expected_parts, expected_encoding', [(u'', consts.SMPP_ENCODING_DEFAULT, [b'\x00'], consts.SMPP_ENCODING_DEFAULT), (u'', consts.SMPP_ENCODING_DEFAULT, [b'\x04\x10\x04O'], consts.SMPP_ENCODING_ISO10646), (u'e', consts.SMPP_ENCODING_ISO88591, [b'\xe9'], consts.SMPP_ENCODING_ISO88591)]) def test_mak...
def nth_product(index, *args): pools = list(map(tuple, reversed(args))) ns = list(map(len, pools)) c = reduce(mul, ns) if (index < 0): index += c if (not (0 <= index < c)): raise IndexError result = [] for (pool, n) in zip(pools, ns): result.append(pool[(index % n)]) ...
def on_vid_button_clicked(): global recording if (not recording): mode_tabs.setEnabled(False) encoder = H264Encoder() if (vid_tab.filetype.currentText() in ['mp4', 'mkv', 'mov', 'ts', 'avi']): output = FfmpegOutput(f"{(vid_tab.filename.text() if vid_tab.filename.text() else '...
def CheckProcList(): toRun = dict() toCreate = dict() procs = ops.processes.processlist.get_processlist() for secproduct in filter((lambda x: (x.proctype == 'SECURITY_PRODUCT')), procs): psps = re.search('^!!! (.*) !!!$', secproduct.friendlyname) psps = re.split('\\sor\\s', psps.group(1)...
class BNAfterConvTranspose(torch.nn.Module): def __init__(self, padding=0, stride=1, dilation=1, groups=1, output_padding=0): super(BNAfterConvTranspose, self).__init__() self.conv1 = torch.nn.ConvTranspose2d(10, 10, 3, padding=padding, stride=stride, dilation=dilation, groups=groups, output_padding...
class Effect3995(BaseEffect): runTime = 'early' type = ('projected', 'passive') def handler(fit, beacon, context, projectionRange, **kwargs): fit.ship.multiplyItemAttr('signatureRadius', beacon.getModifiedItemAttr('signatureRadiusMultiplier'), stackingPenalties=True, penaltyGroup='postMul', **kwargs...
def evaluate_metrics(all_prediction, SLOT_LIST): (total, turn_acc, joint_acc, F1_pred, F1_count) = (0, 0, 0, 0, 0) for (idx, dial) in all_prediction.items(): for (k, cv) in dial['turns'].items(): if (set(cv['turn_belief']) == set(cv['pred_belief'])): joint_acc += 1 ...
class MyOp(COp): __props__ = ('nin', 'name') def __init__(self, nin, name): self.nin = nin self.name = name def make_node(self, *inputs): assert (len(inputs) == self.nin) inputs = list(map(as_variable, inputs)) for input in inputs: if (input.type is not td...
class CollectReport(BaseReport): when = 'collect' def __init__(self, nodeid: str, outcome: "Literal['passed', 'failed', 'skipped']", longrepr: Union[(None, ExceptionInfo[BaseException], Tuple[(str, int, str)], str, TerminalRepr)], result: Optional[List[Union[(Item, Collector)]]], sections: Iterable[Tuple[(str, ...
class TestPredictor(unittest.TestCase): def setUp(self): test_path = os.path.dirname(os.path.realpath(__file__)) src = SourceField() tgt = TargetField() self.dataset = torchtext.data.TabularDataset(path=os.path.join(test_path, 'data/eng-fra.txt'), format='tsv', fields=[('src', src), ...
class TypeAreaMultiHeadAttention(nn.Module): def __init__(self, n_head: int, d_model: int, dropout: float=0.1): super().__init__() self.dim_per_head = d_model self.n_head = n_head self.linear_qs = nn.Linear(d_model, (n_head * d_model), bias=False) self.linear_ks = nn.Linear(d...
class AugMixAugment(): def __init__(self, ops, alpha=1.0, width=3, depth=(- 1), blended=False): self.ops = ops self.alpha = alpha self.width = width self.depth = depth self.blended = blended def _calc_blended_weights(self, ws, m): ws = (ws * m) cump = 1.0 ...
def load_dataset(path, split, add_targets=False, split_and_preprocess=False, batch_size=1, prefetch_factor=2): return DataLoader(FlagSimpleDatasetIterative(path=path, split=split, add_targets=add_targets, split_and_preprocess=split_and_preprocess), batch_size=batch_size, prefetch_factor=prefetch_factor, shuffle=Fal...
class spherical_caps_pdf(PDF): def __init__(self, shape, origin, importance_sampled_list): self.shape = shape self.origin = origin self.importance_sampled_list = importance_sampled_list self.l = len(importance_sampled_list) def value(self, ray_dir): PDF_value = 0.0 ...
def _create_effnet(model_kwargs, variant, pretrained=False): features_only = False model_cls = EfficientNet if model_kwargs.pop('features_only', False): features_only = True model_kwargs.pop('num_classes', 0) model_kwargs.pop('num_features', 0) model_kwargs.pop('head_conv', N...
def contractreceivechannelbatchunlock_from_event(canonical_identifier: CanonicalIdentifier, event: DecodedEvent) -> ContractReceiveChannelBatchUnlock: data = event.event_data args = data['args'] return ContractReceiveChannelBatchUnlock(canonical_identifier=canonical_identifier, receiver=args['receiver'], se...
class ErrorMessageBox(ErrorWidget): def __init__(self, view): super().__init__(view) alert = self.add_child(Alert(view, _('An error occurred:'), 'danger')) alert.add_child(HTMLElement(view, 'hr')) alert.add_child(P(view, text=self.error_message)) a = alert.add_child(A(view, U...
class _cupy_lombscargle_wrapper(object): def __init__(self, grid, block, kernel): if isinstance(grid, int): grid = (grid,) if isinstance(block, int): block = (block,) self.grid = grid self.block = block self.kernel = kernel def __call__(self, x, y,...
def test_cuda_mig_visible_devices_and_memory_limit_and_nthreads(loop): uuids = get_gpu_count_mig(return_uuids=True)[1] if (len(uuids) > 0): cuda_visible_devices = ','.join([i.decode('utf-8') for i in uuids]) else: pytest.skip('No MIG devices found') with patch.dict(os.environ, {'CUDA_VIS...
def test_update_mixin_missing_attrs(gl): class M(UpdateMixin, FakeManager): _update_attrs = gl_types.RequiredOptional(required=('foo',), optional=('bar', 'baz')) mgr = M(gl) data = {'foo': 'bar', 'baz': 'blah'} mgr._update_attrs.validate_attrs(data=data) data = {'baz': 'blah'} with pytes...
def test_process_search(s1_product: SentinelOne): s1_product.log = logging.getLogger('pytest_surveyor') s1_product._queries = {} s1_product.process_search(Tag('test_query'), {}, 'FileName containsCIS "svchost.exe"') assert (len(s1_product._queries[Tag('test_query')]) == 1) assert (s1_product._querie...
_callback_query((tools.option_filter('reposts') & tools.is_admin)) def reposts_config(bot: AutoPoster, callback_query: CallbackQuery): data = callback_query.data.split() value = (bool(int(data[2])) if data[2].isdigit() else data[2]) if (data[1] == 'global'): bot.config['settings']['send_reposts'] = ...
def get_aggregation_strategies(aggregation_strategies): import numpy as np try: from pypsa.clustering.spatial import _make_consense except Exception: from pypsa.clustering.spatial import _make_consense bus_strategies = dict(country=_make_consense('Bus', 'country')) bus_strategies.upd...
def setUpModule(): global cell, kpts L = 4 n = 15 cell = pgto.Cell() cell.build(unit='B', verbose=5, output='/dev/null', a=((L, 0, 0), (0, L, 0), (0, 0, L)), mesh=[n, n, n], atom=[['He', (((L / 2.0) - 0.5), (L / 2.0), ((L / 2.0) - 0.5))], ['He', ((L / 2.0), (L / 2.0), ((L / 2.0) + 0.5))]], basis={'H...
class Migration(migrations.Migration): dependencies = [('conditions', '0021_related_name')] operations = [migrations.AddField(model_name='condition', name='locked', field=models.BooleanField(default=False, help_text='Designates whether this condition can be changed.', verbose_name='Locked'))]
def sane_samples_from_playlist(pathserv, playlist_file): samples = [] rejected = [] for (sample, filename) in pathserv.playlist_generator_from_file(playlist_file): ext = os.path.splitext(sample)[1] if ((ext in {'.dbg', '.htm', '.html', '.json', '.log', '.pkl', '.py', '.txt'}) or (not os.path...
class InMemoryLogRotationContext(LogRotationContextInterface): def __init__(self, expired_logs, all_logs): self.expired_logs = expired_logs self.all_logs = all_logs def __enter__(self): return self def __exit__(self, ex_type, ex_value, ex_traceback): if ((ex_type is None) and...
class AutoConfig(object): def __init__(self): raise EnvironmentError('AutoConfig is designed to be instantiated using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method.') def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): if ('distilbert' in pretrained_model_...
.parametrize('has_artifacts', [False, True]) def test_msr_format_params(has_artifacts: bool): preset = PresetManager(None).default_preset_for_game(RandovaniaGame.METROID_SAMUS_RETURNS).get_preset() assert isinstance(preset.configuration, MSRConfiguration) configuration = dataclasses.replace(preset.configura...
def initialize(security_class, cmdpairs, security_level='read-write', restrict_path=None): global _allowed_requests, _security_level (security_level, restrict_path) = _set_security_level(security_class, security_level, restrict_path, cmdpairs) _security_level = security_level if restrict_path: r...
def test_arrange_items(view): item1 = BeePixmapItem(QtGui.QImage()) item1.do_flip() view.scene.addItem(item1) item2 = BeePixmapItem(QtGui.QImage()) item2.setRotation(90) view.scene.addItem(item2) item3 = BeePixmapItem(QtGui.QImage()) view.scene.addItem(item3) with patch.object(item1,...
def get_activations(files, data_type, model, batch_size, size, length, dims, device): model.eval() if (batch_size > len(files)): print('Warning: batch size is bigger than the data size. Setting batch size to data size') batch_size = len(files) transform = torchvision.transforms.Compose([tran...
def import_CSV(filename: os.PathLike) -> list[btypes.PyTrackObject]: objects = [] with open(filename, 'r') as csv_file: csvreader = csv.DictReader(csv_file, delimiter=',', quotechar='|') for (i, row) in enumerate(csvreader): data = {k: float(v) for (k, v) in row.items()} ...
def get_num_layer_layer_wise(var_name, num_max_layer=12): if (var_name in ('backbone.cls_token', 'backbone.mask_token', 'backbone.pos_embed')): return 0 elif var_name.startswith('backbone.downsample_layers'): stage_id = int(var_name.split('.')[2]) if (stage_id == 0): layer_id...
def test_cmd_list_input_with_simple_cmd_strings(): cmd1 = get_cmd('tests/testfiles/cmds/args.sh', 'tests\\testfiles\\cmds\\args.bat') cmd2 = get_cmd('tests/testfiles/cmds/args2.sh', 'tests\\testfiles\\cmds\\args2.bat') context = Context({'a': 'one', 'b': 'two two', 'c': 'three', 'd': cmd1, 'e': cmd2, 'cmd':...
def get_valid_reader_names(reader): new_readers = [] for reader_name in reader: if (reader_name in OLD_READER_NAMES): raise ValueError("Reader name '{}' has been deprecated, use '{}' instead.".format(reader_name, OLD_READER_NAMES[reader_name])) if (reader_name in PENDING_OLD_READER_N...
def main(base_dir, lang_pair): (src, tgt) = lang_pair.split('-') files = list(map((lambda x: os.path.join(base_dir, x)), os.listdir(base_dir))) files = list(filter((lambda x: ('tok' in x)), files)) src_vocab_size = 32003 src_model_prefix = os.path.join(base_dir, 'm_bpe') src_model_path = (src_mo...
def gcd1(u, v): assert (u > 0) assert (v > 0) shift = 0 while ((not (u & 1)) and (not (v & 1))): shift += 1 u >>= 1 v >>= 1 while (not (u & 1)): u >>= 1 while True: while (not (v & 1)): v >>= 1 if (u > v): (u, v) = (v, u) ...
class T5Config(PretrainedConfig): pretrained_config_archive_map = T5_PRETRAINED_CONFIG_ARCHIVE_MAP def __init__(self, vocab_size=32128, n_positions=512, d_model=512, d_kv=64, d_ff=2048, num_layers=6, num_heads=8, relative_attention_num_buckets=32, dropout_rate=0.1, layer_norm_epsilon=1e-06, initializer_factor=1...
def match_context(ds: List[Tuple[(str, str, int)]], docs: List[List[str]], sample_context=2) -> List[ContextualizedExample]: phrases = [] for tuple in ds: p1 = tuple[0] p2 = tuple[1] phrases.append(p1) phrases.append(p2) phrases = list(set(phrases)) raw_texts = [' '.join(...
class TFAgent(RLAgent): RESOURCE_SCOPE = 'resource' SOLVER_SCOPE = 'solvers' def __init__(self, world, id, json_data): self.tf_scope = 'agent' self.graph = tf.Graph() self.sess = tf.Session(graph=self.graph) super().__init__(world, id, json_data) self._build_graph(jso...
class Migration(migrations.Migration): dependencies = [('sponsors', '0041_auto__1313')] operations = [migrations.AlterField(model_name='sponsorshippackage', name='logo_dimension', field=models.PositiveIntegerField(blank=True, default=175, help_text='Internal value used to control logos dimensions at sponsors pa...
def _process_image_files_batch(coder, thread_index, ranges, name, all_sets, vocab, num_shards): num_threads = len(ranges) assert (not (num_shards % num_threads)) num_shards_per_batch = int((num_shards / num_threads)) shard_ranges = np.linspace(ranges[thread_index][0], ranges[thread_index][1], (num_shard...
class TestQuantSimRangeLearning(): def test_cpu_model_quantize_op_input_params_update(self): tf.compat.v1.reset_default_graph() with tf.device('/cpu:0'): model = tf.keras.Sequential() model.add(tf.keras.layers.Conv2D(32, kernel_size=3, input_shape=(28, 28, 3), activation='rel...
def filter_protocol(hostmap, *, allowed_protocols: Iterable[str]=None) -> Sequence[ServerAddr]: if (allowed_protocols is None): allowed_protocols = {PREFERRED_NETWORK_PROTOCOL} eligible = [] for (host, portmap) in hostmap.items(): for protocol in allowed_protocols: port = portmap...
def get_args(): parser = argparse.ArgumentParser(description='STPM anomaly detection') parser.add_argument('--phase', default='train') parser.add_argument('--data_path', type=str, default='D:/dataset/mvtec_anomaly_detection') parser.add_argument('--obj', type=str, default='zipper') parser.add_argume...
def test(model, path, dataset): data_path = os.path.join(path, dataset) image_root = '{}/images/'.format(data_path) gt_root = '{}/masks/'.format(data_path) model.eval() num1 = len(os.listdir(gt_root)) test_loader = test_dataset(image_root, gt_root, 352) maes = [] dscs = [] ious = [] ...
class _State(): clock_init: float = None clock_now: float = None caption_pid: int = None pmt_pids: list = field(default_factory=list) captions: list = field(default_factory=list) def seconds(self, ts): n = (ts - self.clock_init) if (n < 0): n += _CLOCK_FREQ re...
def calculate_metric_for_tensor(cal_func, tensor1, tensor2=None, LP_list=None): if (LP_list is None): metric_for_named_tensors = cal_func(tensor1, tensor2) return metric_for_named_tensors else: assert (type(LP_list) is list) metric_for_named_tensors_with_LP_dict = {} for ...
class InputsWidget(QtWidgets.QWidget): NO_LABEL_INPUTS = (BooleanInput,) def __init__(self, procedure_class, inputs=(), parent=None, hide_groups=True, inputs_in_scrollarea=False): super().__init__(parent) self._procedure_class = procedure_class self._procedure = procedure_class() ...
def _make_link_replacements() -> List[Tuple[(str, str)]]: top_level = ['Bloq', 'CompositeBloq', 'BloqBuilder', 'Register', 'Signature', 'Side', 'BloqInstance', 'Connection', 'Soquet'] replacements = [(f'`{name}`', f'[`{name}`](/reference/qualtran/{name}.md)') for name in top_level] return replacements