Dataset Viewer
Auto-converted to Parquet Duplicate
code
stringlengths
281
23.7M
def iter_selections(manifest, selections, *, unique=True): byname = {b.name: b for b in manifest.benchmarks} seen = set() included = [] excluded = set() for (op, _, kind, parsed) in selections: matches = _match_selection(manifest, kind, parsed, byname) if (op == '+'): for...
_funcify.register(DimShuffle) def jax_funcify_DimShuffle(op, **kwargs): def dimshuffle(x): res = jnp.transpose(x, op.transposition) shape = list(res.shape[:len(op.shuffle)]) for augm in op.augment: shape.insert(augm, 1) res = jnp.reshape(res, shape) if (not op.inp...
class IfNodeTest(_NodeTest): CODE = '\n if 0:\n print()\n\n if True:\n print()\n else:\n pass\n\n if "":\n print()\n elif []:\n raise\n\n if 1:\n print()\n elif True:\n print()\n elif...
def search_for_duplicates(inp_path, verbose=False): headers = swmmio.utils.text.get_inp_sections_details(inp_path)['headers'] dups_found = False for (header, cols) in headers.items(): if (cols != 'blob'): df = dataframe_from_inp(inp_path, section=header) elements = df.index ...
def get_semisup_dataloaders(train_dataset, test_dataset, val_dataset=None, batch_size=256, batch_size_test=256, num_workers=4, unsup_fraction=0.5): dataset_size = train_dataset.dataset_size train_batch_sampler = SemiSupervisedSampler(train_dataset.sup_indices, train_dataset.unsup_indices, batch_size, unsup_frac...
def configure(dir=None, format_strs=None, comm=None, log_suffix=''): if (dir is None): dir = os.getenv('OPENAI_LOGDIR') if (dir is None): dir = osp.join(tempfile.gettempdir(), datetime.datetime.now().strftime('openai-%Y-%m-%d-%H-%M-%S-%f')) assert isinstance(dir, str) dir = os.path.expan...
class Migration(migrations.Migration): dependencies = [('domain', '0047_attribute_locked')] operations = [migrations.AlterField(model_name='attribute', name='locked', field=models.BooleanField(default=False, help_text='Designates whether this attribute (and its descendants) can be changed.', verbose_name='Locke...
() def valid_tmp_game_root(tmp_path): game_root = tmp_path.joinpath('game_root') game_root.joinpath('files').mkdir(parents=True) game_root.joinpath('sys').mkdir() for f in ['default.dol', 'FrontEnd.pak', 'Metroid1.pak', 'Metroid2.pak']: game_root.joinpath('files', f).write_bytes(b'') game_ro...
class ImgWrapper(gym.ObservationWrapper): def __init__(self, env=None): super(ImgWrapper, self).__init__(env) obs_shape = self.observation_space.shape self.observation_space = spaces.Box(self.observation_space.low[(0, 0, 0)], self.observation_space.high[(0, 0, 0)], [obs_shape[2], obs_shape[0...
class KlapEncryptionSession(): def __init__(self, local_seed, remote_seed, user_hash): self.local_seed = local_seed self.remote_seed = remote_seed self.user_hash = user_hash self._key = self._key_derive(local_seed, remote_seed, user_hash) (self._iv, self._seq) = self._iv_deri...
def stat_proxy(path: str) -> os.stat_result: try: st = orig_stat(path) except OSError as err: print(f'stat({path!r}) -> {err}') raise else: print(('stat(%r) -> (st_mode=%o, st_mtime=%d, st_size=%d)' % (path, st.st_mode, st.st_mtime, st.st_size))) return st
def compute_dense_reward(self, action): reward = 0.0 cube_at_goal = (np.linalg.norm((self.obj.pose.p - self.goal_pos)) <= 0.02) is_robot_static = (np.max(np.abs(self.agent.robot.get_qvel()[:(- 2)])) <= 0.2) if (cube_at_goal and is_robot_static): reward += 2.25 return reward gripper_p...
def test_histogrambin(): hb = OSC.parameters._HistogramBin(1, OSC.Range(0, 1)) hb2 = OSC.parameters._HistogramBin(1, OSC.Range(0, 1)) hb3 = OSC.parameters._HistogramBin(1, OSC.Range(0, 2)) assert (hb == hb2) assert (hb != hb3) prettyprint(hb) hb4 = OSC.parameters._HistogramBin.parse(hb.get_e...
def test_regress_with_steps(ansi_bar: ProgressBar, ansi_io: BufferedIO) -> None: ansi_bar.start() ansi_bar.advance(4) ansi_bar.advance(4) ansi_bar.advance((- 2)) output = [' 0 [>]', ' 4 [---->]', ' 8 [>]', ' 6 [------>]'] expected = generate_output(output) assert (expected == ans...
def test_majorana_operator_with_basis_rotated_by(): H = (numpy.array([[1, 1], [1, (- 1)]]) / numpy.sqrt(2)) a = MajoranaOperator((0, 1), 2.0) op = a.with_basis_rotated_by(H) assert (op == MajoranaOperator.from_dict({(0, 1): (- 2.0)})) b = MajoranaOperator((0,), 2.0) op = b.with_basis_rotated_by(...
class PreImport(WorkerPlugin): def __init__(self, libraries): if (libraries is None): libraries = [] elif isinstance(libraries, str): libraries = libraries.split(',') self.libraries = libraries def setup(self, worker=None): for l in self.libraries: ...
_config def test_resize(manager): manager.c.screen[0].resize(x=10, y=10, w=100, h=100) (ignore_exceptions=AssertionError, fail_msg="Screen didn't resize") def run(): d = manager.c.screen[0].info() assert (d['width'] == 100) assert (d['height'] == 100) return d d = run() ...
def get_config(): config = get_default_configs() training = config.training training.sde = 'vpsde' training.continuous = True training.reduce_mean = True sampling = config.sampling sampling.method = 'pc' sampling.predictor = 'euler_maruyama' sampling.corrector = 'none' data = con...
class PlayMultiBlockChange(Packet): id = 59 to = 1 def __init__(self, chunk_sect_x: int, chunk_sect_y: int, chunk_sect_z: int, trust_edges: bool, blocks: list) -> None: super().__init__() self.chunk_sect_x = chunk_sect_x self.chunk_sect_y = chunk_sect_y self.chunk_sect_z = ch...
class Word(entity): def __init__(self, token, syllables=None, sylls_text=[], broken=False, lang=None): if (syllables == None): import prosodic if (lang == None): lang = prosodic.lang w = prosodic.dict[lang].get(token)[0] if (not len(w.__dict__)...
def test_misc_object_reader(tmpdir): tmpcatalog = os.path.join(tmpdir, 'my_catalog.xosc') cf = xosc.CatalogFile() cf.create_catalog(tmpcatalog, 'MiscObjectCatalog', 'My first miscobject catalog', 'Mandolin') orig = xosc.MiscObject('pole', 50, xosc.MiscObjectCategory.pole, xosc.BoundingBox(1, 1, 1, 1, 1,...
class RunModel(): def __init__(self, model, args, ID2wordVecIdx, ID2char, expName, m_name, m_train='train', m_dev='dev', m_test='test'): self.model = model self.tbWriter = None self.args = args self.ID2wordVecIdx = ID2wordVecIdx self.ID2char = ID2char self.expName = e...
.parametrize('fixture, result', [('script_callable_legacy_table', []), ('script_callable_legacy_string', []), ('script_reference_console', []), ('script_reference_file', [(Path('bin') / 'script.sh')])]) def test_builder_convert_script_files(fixture: str, result: list[Path]) -> None: project_root = ((Path(__file__)....
class QlArchMIPS(QlArch): type = QL_ARCH.MIPS bits = 32 def __init__(self, ql: Qiling, endian: QL_ENDIAN): super().__init__(ql) self._init_endian = endian _property def uc(self) -> Uc: endian = {QL_ENDIAN.EB: UC_MODE_BIG_ENDIAN, QL_ENDIAN.EL: UC_MODE_LITTLE_ENDIAN}[self.endia...
def ql_syscall_faccessat(ql: Qiling, dirfd: int, filename: int, mode: int): vpath = ql.os.utils.read_cstring(filename) vpath_at = virtual_abspath_at(ql, vpath, dirfd) if (vpath_at is None): regreturn = (- 1) else: hpath = ql.os.path.virtual_to_host_path(vpath_at) if (not ql.os.pa...
class NamespaceReader(abc.TraversableResources): def __init__(self, namespace_path): if ('NamespacePath' not in str(namespace_path)): raise ValueError('Invalid path') self.path = MultiplexedPath(*list(namespace_path)) def resource_path(self, resource): return str(self.path.jo...
class Migration(migrations.Migration): dependencies = [('successstories', '0008_auto__2000')] operations = [migrations.AlterField(model_name='story', name='slug', field=models.SlugField(max_length=200, unique=True)), migrations.AlterField(model_name='storycategory', name='slug', field=models.SlugField(max_lengt...
class TestHTML(): .parametrize('pause, expectation', [(0.4, 400), (1, '^((?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d$)')]) def test_durations(self, pytester, pause, expectation): pytester.makepyfile(f''' import time def test_sleep(): time.sleep({pause}) ''') ...
def test_add_row_button(): widget = QgridWidget(df=create_df()) event_history = init_event_history('row_added', widget=widget) widget._handle_qgrid_msg_helper({'type': 'add_row'}) assert (event_history == [{'name': 'row_added', 'index': 4, 'source': 'gui'}]) added_index = event_history[0]['index'] ...
def check_connection_end_to_end(wrap_client: Callable[([CA, socket.socket, str], SslSocket)], wrap_server: Callable[([LeafCert, socket.socket], SslSocket)], key_type: KeyType) -> None: def fake_ssl_client(ca: CA, raw_client_sock: socket.socket, hostname: str) -> None: try: wrapped_client_sock = ...
class DNSlog(): def __init__(self): self.headers = headers = {'Cookie': 'UM_distinctid=17d9ee9b99ad5-08c6a2266360e7-4c3f2779-1fa400-17d9ee9b99b2b1; CNZZDATA=--%7C; PHPSESSID=kolveuasn829nk9s0jfffjg4n2'} def getdomain(self): getdomain = requests.get(url=' headers=self.headers, timeout=60) ...
class Serial(SerialBase, PlatformSpecific): def open(self): if (self._port is None): raise SerialException('Port must be configured before it can be used.') if self.is_open: raise SerialException('Port is already open.') self.fd = None try: self.fd...
def basecompiledir_ls(): subdirs = [] others = [] for f in os.listdir(config.base_compiledir): if os.path.isdir(os.path.join(config.base_compiledir, f)): subdirs.append(f) else: others.append(f) subdirs = sorted(subdirs) others = sorted(others) print(f'Bas...
class _ModelFallbackWrapper(GenerationMixin): __slots__ = ('_optimized', '_default') def __init__(self, optimized, default): self._optimized = optimized self._default = default def __call__(self, *args, **kwargs): if (kwargs['past_key_values'] is None): return self._defau...
def loadAWSServiceControlPolicy(neo4j_session, data_path, account_name): logger.info("[*] Loading AWS Service Control Policy into neo4j instance for AWS account '%s'", account_name) ingest_aws_service_control_policy = 'merge(scp:AWSPolicy:AWSServiceControlPolicy {Arn:$Arn}) \n ...
class PedestrianAnimation(_AnimationType): def __init__(self, motion=None, animation=None): self.motion = convert_enum(motion, PedestrianMotionType, True) self.animation = animation self.gestures = [] def __eq__(self, other): if isinstance(other, PedestrianAnimation): ...
class ImportWizard(QtWidgets.QWizard): def __init__(self): QtWidgets.QWizard.__init__(self) self.setMinimumSize(500, 400) self.resize(700, 500) self.setPreviewData(None) self.selectFilePage = SelectFilePage() self.setParametersPage = SetParametersPage() self.r...
(frozen=True) class SuperMetroidPerGameOptions(PerGameOptions): input_path: (Path | None) = None output_directory: (Path | None) = None output_format: str = 'smc' def as_json(self): return {**super().as_json, 'input_path': (str(self.input_path) if (self.input_path is not None) else None), 'outpu...
def event_data_generator_bert_mrc_mul(input_Xs, Ys, token_type_ids, query_lens): for index in range(len(input_Xs)): input_x = input_Xs[index] y = Ys[index] token_type_id = token_type_ids[index] query_len = query_lens[index] (yield ((input_x, len(input_x), query_len, token_typ...
def StyleGAN2_FLOPCal(generator_dict): styled_conv_FLOPs = Styled_Conv_FLOPCal(generator_dict, return_detail=False) toRGB_FLOPs = ToRGB_Conv_FLOPCal(generator_dict, False) mapping_network_FLOPs = Mapping_Network_FLOPCal(generator_dict) style_mod_FLOPs = Style_Modulation_FLOPCal(generator_dict) all_F...
def parsexml_(infile, parser=None, **kwargs): if (parser is None): try: parser = etree_.ETCompatXMLParser() except AttributeError: parser = etree_.XMLParser() try: if isinstance(infile, os.PathLike): infile = os.path.join(infile) except AttributeEr...
def console_progress(): def progress(totalhashed, totalsize): msg = (' ' * 30) if (totalhashed < totalsize): msg = ('%5.1f%% complete' % ((totalhashed * 100.0) / totalsize)) sys.stdout.write((msg + ' \r')) sys.stdout.flush() try: return (progress if sys.stdout...
class DequantizeFunc(torch.autograd.Function): def forward(ctx, tensor: torch.Tensor, scale: torch.Tensor, offset: torch.Tensor): x_dequant = ((tensor + offset) * scale) ctx.tensor_requires_grad = tensor.requires_grad ctx.scale_requires_grad = scale.requires_grad ctx.offset_requires_...
def str_for_dist(dist: TensorVariable, formatting: str='plain', include_params: bool=True) -> str: if include_params: if isinstance(dist.owner.op, RandomVariable): dist_args = [_str_for_input_var(x, formatting=formatting) for x in dist.owner.inputs[3:]] else: dist_args = [_st...
def init_output_database(output_c, subset): schema._execute_sql(output_c, fragment_db.get_schema_template()) schema._execute_sql(output_c, '\nATTACH DATABASE ":memory:" AS merge;\n\nCREATE TABLE merge.required_constants (\n constant_smiles TEXT\n);\n\n ') output_c.executemany('\nINSERT INTO merge.requir...
.parametrize(('package_repo', 'dependency_repo', 'result'), [('pypi', None, True), ('private', None, True), ('pypi', 'pypi', True), ('private', 'private', True), ('pypi', 'private', False), ('private', 'pypi', False)]) def test_package_satisfies_on_repositories(package_repo: str, dependency_repo: (str | None), result: ...
def test_create_left_lane_split_second_lane(): lanedef = xodr.LaneDef(10, 20, 1, 2, 2) lanes = xodr.create_lanes_merge_split(0, [lanedef], 30, xodr.std_roadmark_solid_solid(), 3, 3) assert (len(lanes.lanesections) == 3) assert (lanes.lanesections[0].s == 0) assert (lanes.lanesections[1].s == 10) ...
class Scenario(ScenarioGenerator): def __init__(self): super().__init__() def road(self, **kwargs): roads = [] roads.append(xodr.create_road(xodr.Line(100), id=0, left_lanes=1, right_lanes=2)) roads.append(xodr.create_road(xodr.Line(100), id=1, left_lanes=0, right_lanes=1)) ...
def determine_bpi(data, frames, EMPTY=(b'\x00' * 10)): o = 0 asbpi = 0 while (o < (len(data) - 10)): part = data[o:(o + 10)] if (part == EMPTY): bpioff = (- ((len(data) - o) % 10)) break (name, size, flags) = struct.unpack('>4sLH', part) size = BitPadd...
class _SingleResponse(): def __init__(self, cert: x509.Certificate, issuer: x509.Certificate, algorithm: hashes.HashAlgorithm, cert_status: OCSPCertStatus, this_update: datetime.datetime, next_update: (datetime.datetime | None), revocation_time: (datetime.datetime | None), revocation_reason: (x509.ReasonFlags | Non...
def blank_fill(img: np.ndarray, start_coordination: (int, int)) -> np.ndarray: kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 9)) last_temp_img = np.zeros_like(img) last_temp_img[start_coordination] = 1 current_temp_img = cv2.dilate(last_temp_img, kernel) while (current_temp_img != last_temp...
class OmniglotClassDataset(ClassDataset): folder = 'omniglot' download_url_prefix = ' zips_md5 = {'images_background': '68d2efa1b9178cc56df9314c21c6e718', 'images_evaluation': '6b91aef0f799c5bb55b94e3f2daec811'} filename = 'data.hdf5' filename_labels = '{0}_labels.json' def __init__(self, root, ...
.fast def test_normalisation_mode(plot=True, close_plots=True, verbose=True, *args, **kwargs): from radis.test.utils import getTestFile _clean(plot, close_plots) (w, I) = np.loadtxt(getTestFile('calc_N2C_spectrum_Trot1200_Tvib3000.txt')).T s = calculated_spectrum(w, I, conditions={'Tvib': 3000, 'Trot': ...
def get_database(data, subset, root_path, video_path_formatter): video_ids = [] video_paths = [] annotations = [] for (key, value) in data['database'].items(): this_subset = value['subset'] if (this_subset == subset): video_ids.append(key) annotations.append(value...
def _get_proposal_section_choices(conference, action='edit'): if (action == 'create'): return [(str(cps.id), cps.name) for cps in ProposalSection.objects.filter(conferences=conference)] else: return [(str(cps.id), cps.name) for cps in ProposalSection.objects.filter(conferences=conference)]
class GuiAddImplantSetCommand(wx.Command): def __init__(self, fitID, itemIDs): wx.Command.__init__(self, True, 'Add Implant Set') self.internalHistory = InternalCommandHistory() self.fitID = fitID self.itemIDs = itemIDs def Do(self): results = [] for itemID in sel...
class Reaction(): def __init__(self, template=None, rxnname=None, smiles=None, reference=None): if (template is not None): self.smirks = template self.rxnname = rxnname self.smiles = smiles self.reference = reference rxn = AllChem.ReactionFromSmart...
class TestGenerateFunction(unittest.TestCase): def setUp(self) -> None: self.arg = RuntimeArg('arg', int_rprimitive) self.reg = Register(int_rprimitive, 'arg') self.block = BasicBlock(0) def test_simple(self) -> None: self.block.ops.append(Return(self.reg)) fn = FuncIR(Fu...
def _complex_compact(variables): compact_form = '' sequence = None for x in variables: if (sequence is None): sequence = SequenceOfSuccessiveVariables(x) elif (not sequence.can_be_extended_with(x.id)): compact_form += (str(sequence) if (compact_form == '') else (' ' +...
def main(args): at_step = args.step output_dir_name = args.output_dir layer_name = args.layer_name block_type = args.block_type postfix = args.postfix probe_type = args.probe_type normalized = args.normalized smoothed = args.smoothed lasso = (True if (args.lasso == 'yes') else False)...
class _FindFlags(): case_sensitive: bool = False backward: bool = False def to_qt(self): flags: _FindFlagType = QWebEnginePage.FindFlag(0) if self.case_sensitive: flags |= QWebEnginePage.FindFlag.FindCaseSensitively if self.backward: flags |= QWebEnginePage.Fi...
def perturb_logistic(net, x_nat, target): net.eval() x = (x_nat.detach() + (0.001 * torch.randn(x_nat.shape).cuda().detach())) for _ in range(args.num_steps): x.requires_grad_() with torch.enable_grad(): loss = torch.mean((1 + torch.exp((((- 1.0) * target.float()) * net(x).squeez...
class TCovers(PluginTestCase): def setUp(self) -> None: self.song = A_SONG self.blank_song = AudioFile() def test_cover_path_lastfm(self): plugin_cls = self.plugins['lastfm-cover'].cls assert isinstance(plugin_cls(self.song).cover_path, fsnative) assert isinstance(plugin_...
class IDirectSound3DBuffer(com.pIUnknown): _methods_ = [('GetAllParameters', com.STDMETHOD(LPDS3DBUFFER)), ('GetConeAngles', com.STDMETHOD(LPDWORD, LPDWORD)), ('GetConeOrientation', com.STDMETHOD(PD3DVECTOR)), ('GetConeOutsideVolume', com.STDMETHOD(LPLONG)), ('GetMaxDistance', com.STDMETHOD(PD3DVALUE)), ('GetMinDis...
_if_nothing_inferred def const_infer_binary_op(self: nodes.Const, opnode: (nodes.AugAssign | nodes.BinOp), operator: str, other: InferenceResult, context: InferenceContext, _: SuccessfulInferenceResult) -> Generator[((ConstFactoryResult | util.UninferableBase), None, None)]: not_implemented = nodes.Const(NotImpleme...
def gurobi_solve_problem(problem: Problem, initvals: Optional[np.ndarray]=None, verbose: bool=False, **kwargs) -> Solution: if (initvals is not None): warnings.warn('warm-start values are ignored by this wrapper') model = gurobipy.Model() if (not verbose): model.setParam(GRB.Param.OutputFlag...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a text classification task') parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).') parser.add_argument('--predict_with_generate', type=b...
def test_inferaugassign_picking_parent_instead_of_stmt() -> None: code = "\n from collections import namedtuple\n SomeClass = namedtuple('SomeClass', ['name'])\n items = [SomeClass(name='some name')]\n\n some_str = ''\n some_str += ', '.join(__(item) for item in items)\n " node = extract_node(...
class Effect4640(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): damageTypes = ('Em', 'Explosive', 'Kinetic', 'Thermal') for damageType in damageTypes: fit.ship.boostItemAttr('armor{0}DamageResonance'.format(damageType), ship.getModifiedItemA...
class ScalarBias(torch.autograd.Function): def forward(ctx, input, dim, bias_init): size = list(input.size()) size[dim] += 1 output = input.new(*size).fill_(bias_init) output.narrow(dim, 1, (size[dim] - 1)).copy_(input) ctx.dim = dim return output def backward(ctx...
class Freezer(object): def param_to_buffer(module, name): split_name = name.split('.') module_name_hierarchy = split_name[:(- 1)] param_name = split_name[(- 1)] tgt_module = module for module_name in module_name_hierarchy: tgt_module = getattr(tgt_module, module_n...
class AbstractMonitor(metaclass=ABCMeta): def real_time_update(self, timestamp: datetime): raise NotImplementedError('Should implement real_time_update()') def end_of_day_update(self, timestamp: datetime): raise NotImplementedError('Should implement end_of_day_update()') def end_of_trading_u...
class Bottleneck(nn.Module): def __init__(self, in_channels, out_channels, expansion=4, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN')): norm_cfg = copy.deepcopy(norm_cfg) super().__init__() assert (style in ['pytorch', 'caffe']...
('baseplate.lib.thrift_pool.RetryPolicy.new') class MaxRetriesRenameTests(unittest.TestCase): def test_default_is_3(self, new_retry_policy): thrift_pool.ThriftConnectionPool(EXAMPLE_ENDPOINT) new_retry_policy.assert_called_with(attempts=3) def test_default_through_parser(self, new_retry_policy):...
def build(cfg, registry, default_args=None): if (cfg is None): return None elif isinstance(cfg, (list, tuple)): modules = [build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg] return modules else: return build_from_cfg(cfg, registry, default_args)
class GetFromCacheTests(unittest.TestCase): def test_bogus_url(self): url = ' with self.assertRaisesRegex(ValueError, 'Connection error'): _ = get_from_cache(url) def test_file_not_found(self): url = hf_bucket_url(MODEL_ID, filename='missing.bin') with self.assertRais...
class ChildFilterLALR(ChildFilter): def __call__(self, children): filtered = [] for (i, to_expand, add_none) in self.to_include: if add_none: filtered += ([None] * add_none) if to_expand: if filtered: filtered += children[i]...
class ROIBoxHead(torch.nn.Module): def __init__(self, in_channels): super().__init__() self.feature_extractor = make_roi_box_feature_extractor() self.predictor = make_roi_box_predictor(self.feature_extractor.out_channels) self.post_processor = make_roi_box_post_processor() se...
class CassandraConcurrentTests(unittest.TestCase): def setUp(self): self.baseplate_observer = TestBaseplateObserver() baseplate = Baseplate({'cassandra.contact_points': cassandra_endpoint.address.host}) baseplate.register(self.baseplate_observer) baseplate.configure_context({'cassand...
class TestSuper_td(): N = 3 t1 = qutip.QobjEvo([(qutip.qeye(N) * (1 + 0.1j)), [(qutip.create(N) * (1 - 0.1j)), f]]) t2 = qutip.QobjEvo([(qutip.destroy(N) * (1 - 0.2j))]) t3 = qutip.QobjEvo([[(qutip.num(N) * (1 + 0.2j)), f]]) q1 = (qutip.qeye(N) * (1 + 0.3j)) q2 = (qutip.destroy(N) * (1 - 0.3j)) ...
class Index(CtrlNode): nodeName = 'Index' uiTemplate = [('axis', 'intSpin', {'value': 0, 'min': 0, 'max': 1000000}), ('index', 'intSpin', {'value': 0, 'min': 0, 'max': 1000000})] def processData(self, data): s = self.stateGroup.state() ax = s['axis'] ind = s['index'] if (ax =...
class OdeSolverBase(): def __init__(self, allow_free_variables: bool=False, duplicate_starting_point: bool=False): self.allow_free_variables = allow_free_variables self.duplicate_starting_point = duplicate_starting_point def integrator(self): raise RuntimeError('This method should be imp...
class CodeWriter(): def __init__(self, project, templates, language='core'): super().__init__() self.project = project self.templates = templates self.language = language self.comments = [] self.last_id = 0 self.current_sprite = '' self.jinja_environme...
class AlexOutputBlock(nn.Module): def __init__(self, in_channels, classes): super(AlexOutputBlock, self).__init__() mid_channels = 4096 self.fc1 = AlexDense(in_channels=in_channels, out_channels=mid_channels) self.fc2 = AlexDense(in_channels=mid_channels, out_channels=mid_channels) ...
_auth def db_del(request, pk): if (request.method == 'DELETE'): try: DBConfig.objects.get(id=pk).delete() return JsonResponse({'code': 200, 'data': None, 'msg': '!'}) except Exception as e: return JsonResponse({'code': 500, 'data': None, 'msg': '!{}'.format(e)})
class PolyvoreModel(object): def __init__(self, config, mode, train_inception=False): assert (mode in ['train', 'eval', 'inference']) self.config = config self.mode = mode self.train_inception = train_inception self.reader = tf.TFRecordReader() self.initializer = tf.r...
def online_kurtosis(data): n = 0 mean = 0 M2 = 0 M3 = 0 M4 = 0 for x in data: n1 = n n = (n + 1) delta = (x - mean) delta_n = (delta / n) delta_n2 = (delta_n * delta_n) term1 = ((delta * delta_n) * n1) mean = (mean + delta_n) M4 = (...
def _create_random_dataset(shape, channel_per_class): tmp = NamedTemporaryFile(delete=False) with h5py.File(tmp.name, 'w') as f: l_shape = w_shape = shape if (len(shape) == 4): l_shape = shape[1:] w_shape = shape[1:] if channel_per_class: l_shape = ((2...
def list_ready_nodes(cli, label_selector=None): nodes = [] try: if label_selector: ret = cli.list_node(pretty=True, label_selector=label_selector) else: ret = cli.list_node(pretty=True) except ApiException as e: logging.error(('Exception when calling CoreV1Api...
def save_coeffs(coeffs, out_dir=''): for platform in coeffs.keys(): fname = os.path.join(out_dir, ('%s_calibration_data.h5' % platform)) fid = h5py.File(fname, 'w') for chan in coeffs[platform].keys(): fid.create_group(chan) fid[chan]['datetime'] = coeffs[platform][ch...
class SelectiveKernelAttn(nn.Module): def __init__(self, channels, num_paths=2, attn_channels=32, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d): super(SelectiveKernelAttn, self).__init__() self.num_paths = num_paths self.fc_reduce = nn.Conv2d(channels, attn_channels, kernel_size=1, bias=Fals...
class TestForceDocumentEnd(): def _get_script(self, *, namespace, name): source = textwrap.dedent('\n // ==UserScript==\n // {}\n // {}\n // ==/UserScript==\n '.format(namespace, name)) _save_script(source, 'force.user.js') gm_manager = gr...
def verify_message_with_address(address: str, sig65: bytes, message: bytes, *, net=None): from .bitcoin import pubkey_to_address assert_bytes(sig65, message) if (net is None): net = constants.net try: h = sha256d(msg_magic(message)) (public_key, compressed) = ECPubkey.from_signat...
class LMDBDataset(data.Dataset): def __init__(self, db_path, noise_model=None, size=None, repeat=1, ratio_used_list=None): import lmdb self.db_path = db_path self.env = lmdb.open(db_path, max_readers=1, readonly=True, lock=False, readahead=False, meminit=False) with self.env.begin(wr...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
6