code
stringlengths
281
23.7M
class TestNumberAttribute(): def test_number_attribute(self): attr = NumberAttribute() assert (attr.attr_type == NUMBER) attr = NumberAttribute(default=1) assert (attr.default == 1) def test_number_serialize(self): attr = NumberAttribute() assert (attr.serialize(3...
class Perpendicular(Base): _id = 28 _entityDef = (_lw, _lw) _workplane = True _iconName = 'Assembly_ConstraintPerpendicular.svg' _tooltip = QT_TRANSLATE_NOOP('asm3', 'Add a "{}" constraint to make planar faces or linear edges of two\nparts perpendicular.') def prepare(cls, obj, solver): ...
def getBatches(data, batch_size): random.shuffle(data) batches = [] data_len = len(data) def genNextSamples(): for i in range(0, data_len, batch_size): (yield data[i:min((i + batch_size), data_len)]) for samples in genNextSamples(): batch = createBatch(samples) ba...
def try_to_load_from_cache(cache_dir, repo_id, filename, revision=None, commit_hash=None): if ((commit_hash is not None) and (revision is not None)): raise ValueError('`commit_hash` and `revision` are mutually exclusive, pick one only.') if ((revision is None) and (commit_hash is None)): revisio...
def _get_area_extent_from_cf_axis(x, y): (ll_x, ll_y) = (x['first'], y['last']) (ur_x, ur_y) = (x['last'], y['first']) ll_x -= ((x['sign'] * 0.5) * x['spacing']) ur_x += ((x['sign'] * 0.5) * x['spacing']) ll_y += ((y['sign'] * 0.5) * y['spacing']) ur_y -= ((y['sign'] * 0.5) * y['spacing']) r...
def test_ohem_sampler(): with pytest.raises(AssertionError): sampler = OHEMPixelSampler(context=_context_for_ohem()) seg_logit = torch.randn(1, 19, 45, 45) seg_label = torch.randint(0, 19, size=(1, 1, 89, 89)) sampler.sample(seg_logit, seg_label) sampler = OHEMPixelSampler(contex...
def _prompt_user_for_file(window: QtWidgets.QWidget, caption: str, filter: str, dir: (str | None)=None, new_file: bool=False) -> (Path | None): if new_file: method = QtWidgets.QFileDialog.getSaveFileName else: method = QtWidgets.QFileDialog.getOpenFileName open_result = method(window, captio...
class Effect6526(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Capacitor Emission Systems')), 'powerTransferAmount', src.getModifiedItemAttr('shipBonusForceAuxiliaryA1'), skill='Amarr Ca...
def import_chrome(profile, bookmark_types, output_format): out_template = {'bookmark': '{url} {name}', 'quickmark': '{name} {url}', 'search': "c.url.searchengines['{keyword}'] = '{url}'", 'oldsearch': '{keyword} {url}'} if ('search' in bookmark_types): webdata = sqlite3.connect(os.path.join(profile, 'We...
class PPM(nn.ModuleList): def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg, act_cfg, align_corners): super(PPM, self).__init__() self.pool_scales = pool_scales self.align_corners = align_corners self.in_channels = in_channels self.channels = channels ...
('Not ready for production yet') class SshConfig(Config): def setUp(self): self.instance = pynag.Parsers.SshConfig(host='localhost', username='palli') def tearDown(self): pass def testParseMaincfg(self): self.instance.parse_maincfg() def testParse(self): self.instance.par...
class Packages_Contains_Environment_1_TestCase(ParserTest): def __init__(self, *args, **kwargs): ParserTest.__init__(self, *args, **kwargs) self.ks = '\n%packages\^whatever-environment\n%end\n' def runTest(self): with warnings.catch_warnings(record=True): warnings.simplefilte...
def params_to_string(num_params: float, units: Optional[str]=None, precision: int=2) -> str: if (units is None): if ((num_params // (10 ** 6)) > 0): return (str(round((num_params / (10 ** 6)), precision)) + ' M') elif (num_params // (10 ** 3)): return (str(round((num_params /...
def unique_in_window(iterable, n, key=None): if (n <= 0): raise ValueError('n must be greater than 0') window = deque(maxlen=n) uniques = set() use_key = (key is not None) for item in iterable: k = (key(item) if use_key else item) if (k in uniques): continue ...
class SessionStore(object): def __init__(self, inactivity_timeout=10, sweep_time=1, attach_timeout=60, timeout_disable_mode='soft'): if (timeout_disable_mode not in ['soft', 'hard']): raise ValueError("timeout_disable_mode must be 'hard' or 'soft'") self.inactivity_timeout = inactivity_t...
def check_model_compatibilty(config: AttrDict, state_dict: Dict[(str, Any)]): from vissl.models import is_feature_extractor_model (trunk_append_prefix, heads_append_prefix) = ('trunk._feature_blocks.', 'heads.') if is_feature_extractor_model(config.MODEL): trunk_append_prefix = 'trunk.base_model._fe...
class KnownValues(unittest.TestCase): def test_ea_adc2(self): myadc.method_type = 'ea' (e, v, p, x) = myadc.kernel(nroots=3) e_corr = myadc.e_corr self.assertAlmostEqual(e_corr, (- 0.), 6) self.assertAlmostEqual(e[0], 0., 6) self.assertAlmostEqual(e[1], 0., 6) ...
def get_geolocation(request, force=False): if force: return get_geoipdb_geolocation(request) if hasattr(request, 'geo'): return request.geo log.warning('No geolocation data set by middleware (see CloudflareGeoIpMiddleware). Consider enabling a GeoIp middleware for ad targeting.') return ...
class CCCVFunctionControl(FunctionControl): def __init__(self, param, options): super().__init__(param, self.cccv, options, control='differential with max') pybamm.citations.register('Mohtat2021') def cccv(self, variables): K_aw = 1 Q = self.param.Q I_var = variables['Cur...
def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None: lineno = method.__code__.co_firstlineno filename = inspect.getfile(method) module = method.__module__ mod_globals = method.__globals__ try: warnings.warn_explicit(message, type(message), filename=filename, module=mo...
.parametrize('num_spin_orb, num_bits_rot_aa', ((8, 3), (20, 3), (57, 3))) def test_sparse_costs_against_openfermion(num_spin_orb, num_bits_rot_aa): num_bits_state_prep = 12 cost = 0 bloq = SelectSparse(num_spin_orb) (_, sigma) = bloq.call_graph() cost += sigma[TGate()] (bloq, num_non_zero) = mak...
def get_print_full(x): old_stdout = sys.stdout sys.stdout = newstdout = StringIO() try: pd.set_option('display.max_rows', len(x)) print(x) string = newstdout.getvalue() except: raise finally: sys.stdout = old_stdout pd.reset_option('display.max_rows') ...
(strat=unstructure_strats, detailed_validation=..., prefer_attrib=..., dict_factory=one_of(just(dict), just(OrderedDict))) def test_copy_func_hooks(converter_cls: Type[BaseConverter], strat: UnstructureStrategy, prefer_attrib: bool, detailed_validation: bool, dict_factory: Callable): c = converter_cls(unstruct_stra...
def get_elec_ddpm_discrete_config(): config = get_default_configs() config.weight_decay = None config.reduce_mean = True config.likelihood_weighting = False config.batch_size = 64 config.epochs = 20 modeling = config.modeling modeling.num_scales = 100 modeling.beta_min = 0.01 mod...
def netting_channel_state(chain_state, token_network_state, token_network_registry_state, partner): if (partner is None): partner = factories.make_address() canonical_identifier = factories.make_canonical_identifier(token_network_address=token_network_state.address) channel_state = factories.create(...
.supported(only_if=(lambda backend: backend.cipher_supported(algorithms._IDEAInternal((b'\x00' * 16)), modes.CBC((b'\x00' * 8)))), skip_message='Does not support IDEA CBC') class TestIDEAModeCBC(): test_cbc = generate_encrypt_test(load_nist_vectors, os.path.join('ciphers', 'IDEA'), ['idea-cbc.txt'], (lambda key, **...
class SKConvBlock(nn.Module): def __init__(self, in_channels, out_channels, stride, groups=32, num_branches=2, reduction=16, min_channels=32): super(SKConvBlock, self).__init__() self.num_branches = num_branches self.out_channels = out_channels mid_channels = max((in_channels // redu...
class ScenarioTestCase(unittest.TestCase): store_id = 'crust2_mf' store_id_static = 'ak135_static' tempdirs = [] def tearDownClass(cls): for d in cls.tempdirs: continue shutil.rmtree(d) (*have_gf_store(store_id)) def test_scenario_waveforms(self): tempdir ...
def create_shortcut(downsample_type, layers: LayerFn, in_chs, out_chs, stride, dilation, **kwargs): assert (downsample_type in ('avg', 'conv1x1', '')) if ((in_chs != out_chs) or (stride != 1) or (dilation[0] != dilation[1])): if (not downsample_type): return None elif (downsample_typ...
def test_wcs_comparison(): wcs1 = WCS(naxis=3) wcs1.wcs.crpix = np.array([50.0, 45.0, 30.0], dtype='float32') wcs2 = WCS(naxis=3) wcs2.wcs.crpix = np.array([50.0, 45.0, 30.0], dtype='float64') wcs3 = WCS(naxis=3) wcs3.wcs.crpix = np.array([50.0, 45.0, 31.0], dtype='float64') wcs4 = WCS(naxis...
def aimet_spatial_svd(model: torch.nn.Module, evaluator: aimet_common.defs.EvalFunction): greedy_params = aimet_torch.defs.GreedySelectionParameters(target_comp_ratio=Decimal(0.75), num_comp_ratio_candidates=10) auto_params = aimet_torch.defs.SpatialSvdParameters.AutoModeParams(greedy_params, modules_to_ignore=...
def downloadFileWithJSONPost(url, file, post_json_str, descriptor): global PROXY if ('/' in file): makeDirs(os.path.dirname(file)) if os.path.exists(file): logging.debug(f'Skipping json post to url: {url} ({descriptor}) as already downloaded') opener = getUrlOpener(PROXY) opener.addh...
def get_prep_freqs(receptacle, df_objects): template_prep_dict = {} for tem in rec_templates: template_list = [] object_list = [] for (idx, row) in df_objects.iterrows(): template_list.append(tem.format(row['entity'], '<mask>', receptacle)) object_list.append(row[...
(frozen=True) class Timezone(AnnotatedTypesCheck): value: Union[(str, timezone, type(...), None)] def predicate(self, value: Any) -> bool: if (not isinstance(value, datetime)): return False if (self.value is None): return (value.tzinfo is None) elif (self.value is...
def add_interactive_args(parser): group = parser.add_argument_group('Interactive') group.add_argument('--buffer-size', default=0, type=int, metavar='N', help='read this many sentences into a buffer before processing them') group.add_argument('--input', default='-', type=str, metavar='FILE', help='file to re...
class EmbeddingSimilarityEvaluator(SentenceEvaluator): def __init__(self, sentences1: List[str], sentences2: List[str], scores: List[float], batch_size: int=16, main_similarity: SimilarityFunction=None, name: str='', show_progress_bar: bool=False, write_csv: bool=True): self.sentences1 = sentences1 ...
def list_jobs(session, inprogress='False'): conn = get_database_conn() curs = query_execute_wrapper(conn, query_string="SELECT * FROM scansweep_queue WHERE session=? AND inprogress=? AND complete='False'", query_list=[session, inprogress], no_return=False) job_list = [] for row in curs: job_list...
class EoctConv(nn.Module): def __init__(self, in_channels, num_channels, kernel_size=3, stride=1, padding=1, bias=True, name=None): super(EoctConv, self).__init__() self.stride = stride if ((type(in_channels) is tuple) and (len(in_channels) == 3)): (in_h, in_l, in_ll) = in_channe...
def M_eq(mu_new, C, mu, m, n): csums = [sum([C[i][h] for i in range(m)]) for h in range(n)] eqs = ([0] * (n + 1)) for j in range(n): temp = sum([(mu_new[h] * csums[h]) for h in range(n)]) eqs[j] = (((mu[j] * temp) - (mu_new[j] * csums[j])) - mu_new[n]) eqs[n] = (sum(mu_new[:n]) - 1) ...
def test_analytical_azimuth(): times = pd.date_range(start='1/1/2015 0:00', end='12/31/2015 23:00', freq='H').tz_localize('Etc/GMT+8') (lat, lon) = (37.8, (- 122.25)) lat_rad = np.deg2rad(lat) output = solarposition.spa_python(times, lat, lon, 100) solar_azimuth = np.deg2rad(output['azimuth']) s...
class BackgroundGenerator(threading.Thread): def __init__(self, generator, local_rank, max_prefetch=6): super(BackgroundGenerator, self).__init__() self.queue = Queue.Queue(max_prefetch) self.generator = generator self.local_rank = local_rank self.daemon = True self.s...
class MaxViT_CASCADE_Small(nn.Module): def __init__(self, n_class=1, img_size=224): super(MaxViT_CASCADE_Small, self).__init__() self.conv = nn.Sequential(nn.Conv2d(1, 3, kernel_size=1), nn.BatchNorm2d(3), nn.ReLU(inplace=True)) if (img_size == 224): self.backbone = maxvit_rmlp_s...
_dataframe_method def fill_missing_timestamps(df: pd.DataFrame, frequency: str, first_time_stamp: pd.Timestamp=None, last_time_stamp: pd.Timestamp=None) -> pd.DataFrame: check('frequency', frequency, [str]) check('first_time_stamp', first_time_stamp, [pd.Timestamp, type(None)]) check('last_time_stamp', last...
def getBoundingBoxes(): allBoundingBoxes = BoundingBoxes() import glob import os currentPath = os.path.dirname(os.path.abspath(__file__)) folderGT = os.path.join(currentPath, 'groundtruths') os.chdir(folderGT) files = glob.glob('*.txt') files.sort() allBoundingBoxes = BoundingBoxes()...
def hierarchical_subsequence(sequential, first, last, after, upto, share_weights=False, depth=0): assert ((last is None) or (upto is None)) assert ((first is None) or (after is None)) if (first is last is after is upto is None): return (sequential if share_weights else copy.deepcopy(sequential)) ...
class TestDataset(Dataset): def __init__(self, args, raw_datasets, cache_root): self.raw_datasets = raw_datasets cache_path = os.path.join(cache_root, 'multiwoz_test.cache') if (os.path.exists(cache_path) and args.dataset.use_cache): self.extended_data = torch.load(cache_path) ...
def weights_init_orthogonal(m): classname = m.__class__.__name__ print(classname) if (classname.find('Conv') != (- 1)): init.orthogonal(m.weight.data, gain=1) elif (classname.find('Linear') != (- 1)): init.orthogonal(m.weight.data, gain=1) elif (classname.find('BatchNorm2d') != (- 1)...
def test_load_spectrum(plot=False, verbose=True, warnings=True, *args, **kwargs): setup_test_line_databases() temp_file_name = '_test_database_co2_tempfile.spec' assert (not exists(temp_file_name)) try: sf = SpectrumFactory(wavelength_min=4190, wavelength_max=4200, mole_fraction=0.0004, path_len...
def configure_tagged_union(union: Any, converter: Converter, tag_generator: Callable[([Type], str)]=default_tag_generator, tag_name: str='_type', default: Optional[Type]=NOTHING) -> None: args = union.__args__ tag_to_hook = {} exact_cl_unstruct_hooks = {} for cl in args: tag = tag_generator(cl) ...
class TopKCompressor(): def __init__(self): self.residuals = {} self.sparsities = [] self.zero_conditions = {} self.values = {} self.indexes = {} self.c = 0 self.t = 0.0 self.name = 'topk' self.zc = None self.current_ratio = 1 s...
def getLESTurbulencePropertiesTemplate(LESModel='dynamicKEqn'): return ('\n simulationType LES;\n\n LES\n {\n LESModel %s;\n\n turbulence on;\n\n printCoeffs on;\n\n delta cubeRootVol;\n\n dynamicKEqnCoeffs\n {\n filter simple;...
_on_failure .parametrize('number_of_nodes', [3]) .parametrize('channels_per_node', [CHAIN]) def test_secret_revealed_on_chain(raiden_chain: List[RaidenService], deposit, settle_timeout, token_addresses, retry_interval_initial): (app0, app1, app2) = raiden_chain token_address = token_addresses[0] token_netwo...
def query_client_id(display, wid): specs = [{'client': wid, 'mask': XRes.LocalClientPIDMask}] r = display.res_query_client_ids(specs) for id in r.ids: if ((id.spec.client > 0) and (id.spec.mask == XRes.LocalClientPIDMask)): for value in id.value: return value return N...
class Road(): _safe def build(cls, context, prop): name = ('road_' + str('{:0>3}'.format((len(bpy.data.objects) + 1)))) obj = create_object(name, create_mesh((name + '_mesh'))) link_obj(obj) bm = bm_from_obj(obj) vertex_count = cls.create_vertex_outline(bm, prop) ...
def test_align_right_multiline(): text = 'foo\nshoes' fill_char = '-' width = 7 aligned = cu.align_right(text, fill_char=fill_char, width=width) assert (aligned == '----foo\n--shoes') reset_all = str(ansi.TextStyle.RESET_ALL) blue = str(ansi.Fg.BLUE) red = str(ansi.Fg.RED) green = st...
def find_subtitle(title, delimiters=DEFAULT_SUB_SPLITTERS): if isinstance(title, bytes): title = title.decode('utf-8', 'replace') for pair in delimiters: if ((len(pair) == 2) and (pair[0] in title[:(- 1)]) and title.endswith(pair[1])): r = len(pair[1]) l = title[0:(- r)]....
def gen_train_txt(txt_path): global train_cnt f = open(txt_path, 'w') for (i, path) in enumerate(trainval_path): img_names = open(path, 'r').readlines() for img_name in img_names: img_name = img_name.strip() xml_path = (((anno_path[i] + '/') + img_name) + '.xml') ...
def urun(b, mo0=None, dm0=None): mol = gto.Mole() mol.build(verbose=5, output=('o2uhf-%3.2f.out' % b), atom=[['O', (0, 0, (b / 2))], ['O', (0, 0, ((- b) / 2))]], basis='cc-pvdz', spin=2) mf = scf.UHF(mol) mf.scf(dm0) mc = mcscf.CASSCF(mf, 12, 8) if (mo0 is not None): mo0 = mcscf.project_...
_if_mysql class ModelTaggedQuerysetOptionsSingleTest(TagTestManager, TestCase): manage_models = [test_models.SingleTagFieldOptionsModel] def setUpExtra(self): self.test_model = test_models.SingleTagFieldOptionsModel self.test_model.objects.create(name='Test 1', case_sensitive_true='Mr', case_sen...
def read_gda(file_in, tokenizer, max_seq_length=1024): pmids = set() features = [] maxlen = 0 with open(file_in, 'r') as infile: lines = infile.readlines() for (i_l, line) in enumerate(tqdm(lines)): line = line.rstrip().split('\t') pmid = line[0] if (p...
def dist_factory(path_item, entry, only): lower = entry.lower() is_egg_info = lower.endswith('.egg-info') is_dist_info = (lower.endswith('.dist-info') and os.path.isdir(os.path.join(path_item, entry))) is_meta = (is_egg_info or is_dist_info) return (distributions_from_metadata if is_meta else (find_...
def test_asyncio_marker_compatibility_with_xfail(pytester: Pytester): pytester.makepyfile(dedent(' import pytest\n\n pytest_plugins = "pytest_asyncio"\n\n .xfail(reason="need a failure", strict=True)\n .asyncio\n async def test_asyncio_marke...
def test_time_tracking_mixin(): class TestClass(TimeTrackingMixin): pass obj = TestClass() assert hasattr(obj, 'time_stats') assert hasattr(obj, 'time_estimate') assert hasattr(obj, 'reset_time_estimate') assert hasattr(obj, 'add_spent_time') assert hasattr(obj, 'reset_spent_time')
def test_context_share_texture(): w1 = window.Window(200, 200) w1.switch_to() textures = c_uint() glGenTextures(1, byref(textures)) texture = textures.value glBindTexture(GL_TEXTURE_2D, texture) data = (c_ubyte * 4)() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_...
class ANSI_input(unittest.TestCase): def test(self): run_test(self, ['-A', ''], ' Month/Day/Year H:M:S 06/11/2013 20:46:11 GPS\n Modified Julian Date 56454. GPS\n GPSweek DayOfWeek SecOfWeek 720 2 247571.000000\n FullGPSweek Zcount 1744 165...
def test_adding_entry_points_affect_entry_point_map(easter_fixture): easter_fixture.stub_egg.add_entry_point_from_line(easter_fixture.group_name, 'test1 = reahl.stubble_dev.test_easteregg:TestClass1') easter_fixture.stub_egg.add_entry_point(easter_fixture.group_name, 'test2', TestClass2) epmap = easter_fixt...
class MSatBoolUFRewriter(IdentityDagWalker): def __init__(self, environment): IdentityDagWalker.__init__(self, environment) self.get_type = self.env.stc.get_type self.mgr = self.env.formula_manager def walk_function(self, formula, args, **kwargs): from pysmt.typing import Functio...
class Keithley2600(Instrument): def __init__(self, adapter, name='Keithley 2600 SourceMeter', **kwargs): super().__init__(adapter, name, **kwargs) self.ChA = Channel(self, 'a') self.ChB = Channel(self, 'b') def error(self): err = self.ask('print(errorqueue.next())') err =...
def get_logger(name: str=None, rank: Optional[int]=None, **kwargs): if (rank is None): rank = int(os.environ.get('RANK', (- 1))) logger = logging.getLogger(name) level = logging.INFO log_format = LOG_FORMAT.format(rank=(f'[Rank {rank}]' if (rank > (- 1)) else '')) logging.basicConfig(level=l...
def colour_path(image, path) -> None: start_node = path[(- 1)] finish_node = path[0] pixels = image.load() red_fade = np.linspace(255, 0, (finish_node.distance + 1)).astype(int) blue_fade = np.linspace(0, 255, (finish_node.distance + 1)).astype(int) step = 0 for (node1, node2) in zip(path[:(...
class PerceiverOnnxConfig(OnnxConfig): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: if (self.task == 'multiple-choice'): dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'} else: dynamic_axis = {0: 'batch', 1: 'sequence'} return OrderedDict([('inputs',...
def channel_pruning_auto_mode(): sess = tf.compat.v1.Session() with sess.graph.as_default(): _ = VGG16(weights=None, input_shape=(224, 224, 3)) init = tf.compat.v1.global_variables_initializer() sess.run(init) conv2d = sess.graph.get_operation_by_name('block1_conv1/Conv2D') modules_t...
class PaymentMockDriver(PaymentTerminalDriver): def __init__(self): super(PaymentMockDriver, self).__init__() self._set_terminal_status(terminal_id='0', status='connected') def transaction_start(self, data): payment_info = data['payment_info'] transaction_id = data['transaction_i...
class NonLinearProgram(): def __init__(self, phase_dynamics: PhaseDynamics): self.casadi_func = {} self.contact_forces_func = None self.soft_contact_forces_func = None self.control_type = ControlType.CONSTANT self.cx = None self.dt = None self.dynamics = None ...
def test_incompatible_ok(hatch, helpers, temp_dir_data, config_file): config_file.model.template.plugins['default']['tests'] = False config_file.save() project_name = 'My.App' with temp_dir_data.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), result.output p...
class PersistentController(YadageController): def __init__(self, model, backend=None): self.model = model super(PersistentController, self).__init__(self.model.load(), backend) def transaction(self, sync=True): self.adageobj = self.model.load() if sync: log.debug('syn...
class Class_Decode(): def func_url(self, encode_type, source_text): try: result_text = str(urllib.parse.unquote(source_text, encode_type)) except Exception as e: return [0, '', 'Url'] return [1, result_text.strip(), 'Url'] def func_unicode(self, encode_type, sourc...
def train_pipeline(root_path): (opt, args) = parse_options(root_path, is_train=True) opt['root_path'] = root_path torch.backends.cudnn.benchmark = True resume_state = load_resume_state(opt) if (resume_state is None): make_exp_dirs(opt) if (opt['logger'].get('use_tb_logger') and ('deb...
def test_get_tag_by_manifest_id_multiple_tags_returns_latest(initialized_db): repo = model.repository.create_repository('devtable', 'newrepo', None) (manifest, _) = create_manifest_for_testing(repo, '1') before_ms = (get_epoch_timestamp_ms() - (timedelta(hours=24).total_seconds() * 1000)) count = Tag.up...
class TestTracer(unittest.TestCase): def test_trace_async_module(self) -> None: class NeedWait(LazyAwaitable[torch.Tensor]): def __init__(self, obj: torch.Tensor) -> None: super().__init__() self._obj = obj def _wait_impl(self) -> torch.Tensor: ...
def test_L4_subcomp_index(): a = CaseBits32ArrayConnectSubCompAttrComp.DUT() a.elaborate() a.apply(StructuralRTLIRGenL4Pass(gen_connections(a))) connections = a.get_metadata(StructuralRTLIRGenL2Pass.connections) comp = CurComp(a, 's') assert (connections[10] == (SubCompAttr(ComponentIndex(CurCom...
def download(platforms, version, use_v8, max_workers, robust): if (not max_workers): max_workers = len(platforms) archives = {} with ThreadPoolExecutor(max_workers=max_workers) as pool: func = functools.partial(_get_package, version=version, robust=robust, use_v8=use_v8) for (pl_name...
def contractreceivesecretreveal_from_event(event: DecodedEvent) -> ContractReceiveSecretReveal: secret_registry_address = event.originating_contract data = event.event_data args = data['args'] return ContractReceiveSecretReveal(secret_registry_address=SecretRegistryAddress(secret_registry_address), secr...
class CompoundModelProcessor(SourceProcessor): __implements__ = 'CompoundModel' def process(self, sources, sandbox, nthreads=0): result = {'processor_profile': dict(), 'displacement.e': np.zeros(sandbox.frame.npixel), 'displacement.n': np.zeros(sandbox.frame.npixel), 'displacement.d': np.zeros(sandbox.f...
def get_best_routes(chain_state: ChainState, token_network_address: TokenNetworkAddress, one_to_n_address: Optional[OneToNAddress], from_address: InitiatorAddress, to_address: TargetAddress, amount: PaymentAmount, previous_address: Optional[Address], privkey: PrivateKey, our_address_metadata: AddressMetadata, pfs_proxy...
class PreconditionerTest(): def __init__(self): self.x1 = (torch.randn(int((mconfig.K / 2)), mconfig.M).cuda().half() / 100) self.x2 = torch.zeros_like(self.x1) self.x = torch.cat([self.x1, self.x2], 0) self.y = (torch.randn(mconfig.K, mconfig.N).cuda().half() / 100) self.y_i...
def parse_mit_splits(): class_mapping = {} with open('data/mit/annotations/moments_categories.txt') as f_cat: for line in f_cat.readlines(): (cat, digit) = line.rstrip().split(',') class_mapping[cat] = int(digit) def line_to_map(x): video = osp.splitext(x[0])[0] ...
def calculate_metrics(y_true: np.ndarray, y_pred: np.ndarray, task_type: Union[(str, TaskType)], prediction_type: Optional[Union[(str, PredictionType)]], y_info: dict[(str, Any)]) -> dict[(str, Any)]: task_type = TaskType(task_type) if (prediction_type is not None): prediction_type = PredictionType(pred...
class _PatchWithDescription(codemod.Patch): def __init__(self, start_line_number: int, end_line_number: Optional[int]=None, new_lines: Optional[List[str]]=None, path: Optional[str]=None, description: Optional[str]=None) -> None: super().__init__(start_line_number, end_line_number, new_lines, path) s...
class GRAFLoss(BaseLoss): def __init__(self, runner, d_loss_kwargs=None, g_loss_kwargs=None): if runner.enable_amp: raise NotImplementedError('GRAF loss does not support automatic mixed precision training yet.') self.d_loss_kwargs = (d_loss_kwargs or dict()) self.r1_gamma = self....
def snooze_issue(hostname, issue_name, snooze_until): db = get_db() spec = {'closed_at': {'$exists': False}, '$or': [{'unsnooze_at': {'$exists': False}}, {'unsnooze_at': {'$lt': snooze_until}}]} if hostname: spec['hostname'] = hostname if issue_name: spec['name'] = issue_name ids = [...
def wavelet_color_fix(target: Image, source: Image): to_tensor = ToTensor() target_tensor = to_tensor(target).unsqueeze(0) source_tensor = to_tensor(source).unsqueeze(0) result_tensor = wavelet_reconstruction(target_tensor, source_tensor) to_image = ToPILImage() result_image = to_image(result_te...
class ObjectDeleteView(LoginRequiredMixin, ObjectDetailView, EvenniaDeleteView): model = class_from_module(settings.BASE_OBJECT_TYPECLASS) template_name = 'website/object_confirm_delete.html' access_type = 'delete' def delete(self, request, *args, **kwargs): obj = str(self.get_object()) ...
class WeightedAvgMetricTest(unittest.TestCase): target_clazz: Type[RecMetric] = WeightedAvgMetric target_compute_mode: RecComputeMode = RecComputeMode.UNFUSED_TASKS_COMPUTATION task_name: str = 'weighted_avg' def test_weighted_avg_unfused(self) -> None: rec_metric_value_test_launcher(target_claz...
class _FoldArrow(QWidget): def __init__(self, parent=None): super().__init__(parent) self._folded = True def fold(self, folded): self._folded = folded self.update() def paintEvent(self, _event): opt = QStyleOption() opt.initFrom(self) painter = QPainte...
.allow_backend_process .requires_internet def test_build_dependencies(hatch, temp_dir, helpers): project_name = 'My.App' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), result.output project_path = (temp_dir / 'my-app') data_path = (temp_dir / ...
class SquadFeatures(): def __init__(self, input_ids, attention_mask, token_type_ids, cls_index, p_mask, example_index, unique_id, paragraph_len, token_is_max_context, tokens, token_to_orig_map, start_position, end_position, is_impossible, qas_id: str=None, encoding: BatchEncoding=None): self.input_ids = inp...
def filter_args_by_frequency(args_list: List[EventPredictedArgs], similarity_threshold: float=0.7) -> Tuple[(EventPredictedArgs, List[str])]: n_generations = len(args_list) role_to_type_str_pairs = defaultdict(list) _prev_event_type = None for (generation_id, predicted_args) in enumerate(args_list): ...
_optimizer('adam', dataclass=FairseqAdamConfig) class FairseqAdam(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) fused_adam_cls = get_fused_adam_class() use_fused_adam = ((not getattr(args, 'use_old_adam', False)) and (fused_adam_cls is not None) and torch.cuda.i...
def val(net, dataset, criterion, max_iter=2): print('Start val') for p in crnn.parameters(): p.requires_grad = False net.eval() data_loader = torch.utils.data.DataLoader(dataset, shuffle=True, batch_size=opt.batchSize, num_workers=int(opt.workers)) val_iter = iter(data_loader) i = 0 ...