code
stringlengths
101
5.91M
class AfterExecution(CurrentOperationMixin, ExecutionEvent): method: str path: str relative_path: str verbose_name: str status: Status data_generation_method: list[DataGenerationMethod] result: SerializedTestResult elapsed_time: float correlation_id: str thread_id: int = field(de...
class BaseRCA(BaseModel): def __init__(self): self.logger = get_logger(self.__class__.__name__) def train(self, **kwargs): def find_root_causes(self, **kwargs) -> RCAResults:
def to_format(arg, size=None): if isinstance(arg, FormatObject): return arg else: r = StringFormatObject(str(arg)) if (size is not None): r.size = size return r
class TestUtils(unittest.TestCase): def setUp(self) -> None: self.straight_path = {'start_pose': [421., 1087., 2.], 'end_pose': [391., 1100., 2.], 'shape': 'LSR', 'radius': 999.999, 'segment_length': [0., 28., 3.]} self.left_path = {'start_pose': [391., 1100., 2.], 'end_pose': [372., 1093., (- 2.)],...
class RPNModule(torch.nn.Module): def __init__(self, cfg, in_channels): super(RPNModule, self).__init__() self.cfg = cfg.clone() anchor_generator = make_anchor_generator(cfg) rpn_head = registry.RPN_HEADS[cfg.MODEL.RPN.RPN_HEAD] head = rpn_head(cfg, in_channels, anchor_genera...
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad): m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad) m.weight.data.normal_(0, 0.1) return m
def get_membership(labels: np.ndarray, dtype=bool, n_labels: Optional[int]=None) -> sparse.csr_matrix: n: int = len(labels) if (n_labels is None): shape = (n, (max(labels) + 1)) else: shape = (n, n_labels) ix = (labels >= 0) data = np.ones(ix.sum()) row = np.arange(n)[ix] col...
_properties class ArrayElimination(ppl.Pass): CATEGORY: str = 'Simplification' def modifies(self) -> ppl.Modifies: return (ppl.Modifies.Descriptors | ppl.Modifies.AccessNodes) def should_reapply(self, modified: ppl.Modifies) -> bool: return (modified & ppl.Modifies.AccessNodes) def depen...
def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ...
def filter_answers_open_close(train_qa_pairs, val_qa_pairs, min_occurence): occurence_open = {} occurence_close = {} qa_pairs = train_qa_pairs.append(val_qa_pairs) qa_pairs['answer'] = qa_pairs['answer'].apply((lambda x: str(x))) qa_pairs_open = qa_pairs[(qa_pairs['answer_type'] == 'OPEN')] qa_p...
class MM(ReidBaseDataModule): dataset_dir = 'ReID_format' def __init__(self, cfg, **kwargs): super().__init__(cfg, **kwargs) self.dataset_dir = osp.join(cfg.DATASETS.ROOT_DIR, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'bounding_box_train') self.query_dir = osp...
def script_call(function_name_at_script_name: str, script_handle_or_type: int, ints=(), floats=(), strings=(), bytes='') -> Tuple[(List[int], List[float], List[str], str)]: return sim.simExtCallScriptFunction(function_name_at_script_name, script_handle_or_type, list(ints), list(floats), list(strings), bytes)
_function def file_hash(filename): path = os.path.normpath(filename) prefix = ('%d:%s' % (len(path), path)).encode('UTF-8') m = hashlib.md5(prefix) with open(path, 'rb') as f: data = f.read(65000) while data: m.update(data) data = f.read(65000) return m.hexdig...
_file_in_work_dir(['script_name']) _low_level_step def undo_edit_script(script_name, work_dir='.', **kwargs): backup_files = glob.glob(os.path.join(work_dir, 'backup', f'{script_name}_*')) if (len(backup_files) == 0): raise EnvException('There is no change to undo.') try: backup_files.sort()...
class Relation(BratBase): def __init__(self, id_, doc_name, rela_type, args): super(Relation, self).__init__(id_, rela_type, doc_name) self.args = args self.abs_char_start = 0 self.abs_char_end = 0 def init_args(self, entity_map): self.args = sorted([entity_map[arg_id] fo...
def get_caption(path_to_image): headers = {'Ocp-Apim-Subscription-Key': API_KEY, 'Content-Type': 'application/octet-stream'} params = {'visualFeatures': 'Description', 'language': 'en'} payload = open(path_to_image, 'rb').read() response = requests.post(ANALYZE_URL, headers=headers, params=params, data=...
class DistributedDataParallelCPU(Module): def __init__(self, module): super(DistributedDataParallelCPU, self).__init__() self.module = module self.sync_parameters() def allreduce_params(): if self.needs_reduction: self.needs_reduction = False ...
class Data(): def __init__(self, survey, dobs=None, relative_error=None, noise_floor=None, standard_deviation=None, **kwargs): super().__init__(**kwargs) self.survey = survey if (dobs is None): dobs = np.full(survey.nD, np.nan) self.dobs = dobs self.relative_error...
def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstru...
def main(in_filepath, out_dir, threshold=10.0, clip_duration_threshold=[60.0], clip_duration=10.0, force_duration=True, num_clips=3, force_num_clips=True, anneal_factor=1.2, sampling='random', cut_random_clips=None, calc_diversity_with_sum=False, **kwargs): if (not os.path.isfile(in_filepath)): sys.exit('No...
class GradualStyleEncoder(Module): def __init__(self, num_layers, mode='ir', opts=None): super(GradualStyleEncoder, self).__init__() assert (num_layers in [50, 100, 152]), 'num_layers should be 50,100, or 152' assert (mode in ['ir', 'ir_se']), 'mode should be ir or ir_se' blocks = ge...
def pesq_score(utts_r, utts_g, h): pesq_score = Parallel(n_jobs=30)((delayed(eval_pesq)(utts_r[i].squeeze().cpu().numpy(), utts_g[i].squeeze().cpu().numpy(), h.sampling_rate) for i in range(len(utts_r)))) pesq_score = np.mean(pesq_score) return pesq_score
class WikiEnv(gym.Env): def __init__(self): super().__init__() self.page = None self.obs = None self.lookup_keyword = None self.lookup_list = None self.lookup_cnt = None self.steps = 0 self.answer = None self.observation_space = self.action_spa...
class MultiDomainBasicAuth(AuthBase): def __init__(self, prompting=True, index_urls=None): self.prompting = prompting self.index_urls = index_urls self.passwords = {} self._credentials_to_save = None def _get_index_url(self, url): if ((not url) or (not self.index_urls)): ...
def get_numeric_features(df, target_column): numeric_dtypes = ['int', 'bigint', 'long', 'float', 'double', 'decimal'] numeric_features = [column_name for (column_name, column_type) in df.dtypes if ((column_type in numeric_dtypes) and (column_name != target_column))] return numeric_features
def find_token(sentence, start_pos): found_tok = None for tok in sentence: if (tok.idx == start_pos): found_tok = tok break return found_tok
def main(): print('Preparing training ...') with codecs.open(opt.train_src, 'r', 'utf-8') as src_file: src_line = src_file.readline().strip().split() (_, _, nFeatures) = onmt.IO.extract_features(src_line) fields = onmt.IO.ONMTDataset.get_fields(nFeatures) print('Building Training...') ...
def _read_json(path, encoding='utf-8', fields=None, dropna=True): if fields: fields = set(fields) with open(path, 'r', encoding=encoding) as f: for (line_idx, line) in enumerate(f): data = json.loads(line) if (fields is None): (yield (line_idx, data)) ...
def get_reporter(mode, *args, **kwargs): reporter_cls = _hpopt_modes.get(mode) if (reporter_cls is None): logger.warning(f'hpopt_mode {mode} is not supported, reverting to generic') reporter_cls = _hpopt_modes[DEFAULT_REPORTER] reporter = reporter_cls(*args, **kwargs) if (not reporter.is...
class ConcatGenerator(NetworkBase): def __init__(self, bg_dim, src_dim, tsf_dim, conv_dim=64, repeat_num=6): super(ConcatGenerator, self).__init__() self._name = 'concat_generator' self.n_down = 3 self.repeat_num = repeat_num self.bg_model = ResNetGenerator(conv_dim=conv_dim,...
def test_byte(): a = ak.highlevel.Array(np.array([ord(x) for x in 'hey there'], dtype=np.uint8), check_valid=True) a = ak.with_parameter(a, '__array__', 'byte') assert (bytes(a) == b'hey there') assert (str(a) == str([ord(c) for c in 'hey there'])) assert (ak.to_list(a) == b'hey there')
_numpy_output(positive=True, casting=np.float64) def test_powr(A: dace.int64[1], B: dace.int64[(5, 5)]): return (A ** B)
class CosineScheduler(BaseLearningRateScheduler): def __init__(self, init_lr, max_iter): self.init_lr = init_lr self.max_iter = max_iter def get_learning_rate(self, iter): return (self.init_lr * ((math.cos((((iter * 1.0) / self.max_iter) * math.pi)) + 1.0) * 0.5))
def main(instanc_size=511, num_threads=24): crop_path = './crop{:d}'.format(instanc_size) if (not exists(crop_path)): makedirs(crop_path) for sub_set in sub_sets: sub_set_base_path = join(got10k_base_path, sub_set) for video_set in sorted(listdir(sub_set_base_path)): vide...
def test__setup_logging_single_verbose_without_log_file(): logging.shutdown() importlib.reload(logging) _setup_logging(1, False) logger = logging.getLogger('') assert (len(logger.handlers) == 1) assert (logger.level == logging.INFO) logging.shutdown() importlib.reload(logging)
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10, drop_rate=0.0): super(ResNet, self).__init__() self.in_planes = 64 self.droprate = drop_rate self.conv1 = conv3x3(3, 64) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, ...
def tidy_ylabel(metric): if (metric == 'val_mi'): return 'MI' elif (metric == 'val_au'): return 'AU' elif (metric == 'train_unweighted_reg_loss'): return 'KL' elif (metric == 'val_ppl'): return 'Validation PPL' return 'FIXFIXFIXFIXFIX'
class VermaModuleHomset(Homset): def __call__(self, x, **options): if isinstance(x, VermaModuleMorphism): if (x.parent() is self): return x if (x.parent() == self): x._set_parent(self) return x if (x.domain() != self.domain(...
def __eval(run_args): trainer = SyMuxTrainer(run_args) trainer.eval(dataset_path=run_args.dataset_path, types_path=run_args.types_path, input_reader_cls=input_reader.JsonInputReader)
class LayerModelHelper(model_helper.ModelHelper): def __init__(self, name, input_feature_schema, trainer_extra_schema, keep_blobs=False, use_attribution=True): super(LayerModelHelper, self).__init__(name=name) self._layer_names = set() self._layers = [] self._param_to_shape = {} ...
.parametrize('val1,val2,result', [(0, 1, 0), (1, 1, 1), ('b', 'b', inf), (Decimal(0.5), Decimal(0.3), 1.2)]) def test_lt(val1, val2, result): assert (_lt(val1, val2) == result)
def load_data_by_class(args, path): if (path is None): return (None, None, None) if (args.model == 'cvae'): (x_train, nt, image_dim) = load_data_set(path, batch=args.batch_size) elif (args.model == 'cvae-style'): (x_train, nt, image_dim) = load_data_set(path, isArray=True) x_...
def pattern_subst(pattern: List[str], rule_symbols: List[str], substitute_dict: Dict[(str, str)]) -> List[str]: out = pattern for symbol in rule_symbols: out = subst(out, symbol, substitute_dict[symbol]) return out
def make_setuptools_bdist_wheel_args(setup_py_path, global_options, build_options, destination_dir): args = make_setuptools_shim_args(setup_py_path, global_options=global_options, unbuffered_output=True) args += ['bdist_wheel', '-d', destination_dir] args += build_options return args
def compare_slot_values(slot_values_ref, slot_values_hyp, service, use_fuzzy_match): list_cor = [] slot_active = [] slot_cat = [] for slot in service['slots']: slot_name = slot['name'] slot_cat.append(slot['is_categorical']) if (slot_name in slot_values_ref): slot_act...
def test_jim3(): text = str(ak.to_categorical(ak.Array(['one', 'one', 'two', 'three', 'one', 'three'])).type) print(text) parsedtype = deduce_type(text, True) assert isinstance(parsedtype, ak.types.ArrayType) assert (str(parsedtype) == text)
def ispitch(x): return ((len(x) == 2) and (x[0] in char2pit) and ((x[1] == 'O') or x[1].isdigit()))
class FQEImpl(ContinuousQFunctionMixin, FQEBaseImpl): _q_func_forwarder: DiscreteEnsembleQFunctionForwarder _targ_q_func_forwarder: DiscreteEnsembleQFunctionForwarder
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, mobilebert_config_file, pytorch_dump_path): config = MobileBertConfig.from_json_file(mobilebert_config_file) print(f'Building PyTorch model from configuration: {config}') model = MobileBertForPreTraining(config) model = load_tf_weights_in_mobilebe...
class ParallelRunner(): def __init__(self, args, logger): self.args = args self.logger = logger self.batch_size = self.args.batch_size_run (self.parent_conns, self.worker_conns) = zip(*[Pipe() for _ in range(self.batch_size)]) env_fn = env_REGISTRY[self.args.env] if (...
def _make_unique_name(seen, name, min_version=0): assert (name is not None) i = min_version x = (('%s_%d' % (name, i)) if i else name) while (x in seen): i += 1 x = ('%s_%d' % (name, i)) seen.add(x) return x
def create_hparams(flags): return tf.contrib.training.HParams(src=flags.src, tgt=flags.tgt, train_prefix=flags.train_prefix, dev_prefix=flags.dev_prefix, test_prefix=flags.test_prefix, vocab_prefix=flags.vocab_prefix, embed_prefix=flags.embed_prefix, out_dir=flags.out_dir, num_units=flags.num_units, num_layers=flag...
class Decoder(DecoderBase): tiu_head_length = 50 dma_head_length = 39 def __init__(self, context: 'BM1688Context') -> None: super().__init__() self.context = context def decode_tiu_cmd(self, reg_buf: memoryview, *, cmd_id, offset, subnet_id, core_id) -> TiuCmd: assert (cmd_id is ...
def test_set_progress_bar_enabled(): disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert (not are_progress_bars_disabled())
def register_Ns3RectangleValue_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::Rectangle const &', 'value')]) cls.add_constructor([param('ns3::RectangleValue const &', 'arg0')]) cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=Tr...
_utils.test(arch=archs_support_ndarray_ad, require=ti.extension.adstack) def test_multiple_ib_multiple_outermost(): x = ti.ndarray(float, (), needs_grad=True) y = ti.ndarray(float, (), needs_grad=True) def compute_y(x: ti.types.ndarray(), y: ti.types.ndarray()): for j in range(2): for i ...
class MemoryChunkCCRetval(MemoryChunk): def declare_class_members(self): return '' def declare_call_locals(self): return je(ri(8, '\n cdef ComplexNumber {{ myself.name }} = (self.domain_element._new())\n '), myself=self) def declare_parameter(self): return ('%s ...
class BlenderbotTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] slow_tokenizer_class = BlenderbotTo...
class RandomIdentitySamplerGcn(Sampler): def __init__(self, data_source, batch_size, num_instances): self.data_source = data_source self.batch_size = batch_size self.num_instances = num_instances self.num_pids_per_batch = (self.batch_size // self.num_instances) self.index_dic...
def load_config_from_file(file_path): ret = copy.deepcopy(g_cfg) ret.merge_from_file(file_path) return ret
def CalculateGutmanTopo(mol): nAT = mol.GetNumAtoms(onlyExplicit=True) deltas = np.array([x.GetDegree() for x in mol.GetAtoms()]) Distance = Chem.GetDistanceMatrix(mol) res = _Gutman(Distance, deltas, nAT) return res
class Function(EntryBase): def __init__(self, j): super().__init__(j, 'function') self.return_value_type = None self.params = [] self.is_device_command = False if ('parameters' in j): for x in j['parameters']: field = Field(x) if (f...
class BuildModel_M3_Full(object): if (__name__ == '__main__'): port = '/dev/ttyUSB0' step = 1000 repeat = 10 N = (5000 * 125) samples = 1000 timebase = 1 post_trigger = True threshold = 2000 posedge_trigger = True vertical_offset = 0 ...
def get_model_bicond_sepembed(batch_size, max_seq_length, input_size, hidden_size, target_size, vocab_size, pretrain, tanhOrSoftmax, dropout): inputs = tf.placeholder(tf.int32, [batch_size, max_seq_length]) inputs_cond = tf.placeholder(tf.int32, [batch_size, max_seq_length]) cont_train = True if (pretra...
def merge_meta(meta1, meta2): links = {} for link in meta2['links'][0]: if (link[0] in links): links[link[0]].append([link[2], link[3]]) else: links[link[0]] = [[link[2], link[3]]] s_start = meta1['start'] links_with_context = {k: [[(s + s_start), (e + s_start)] f...
_safe_enum _enum class OMPScheduleType(aenum.AutoNumberEnum): Default = () Static = () Dynamic = () Guided = ()
def bench4(): desc = 'Rational polynomial arithmetic using Sage. Compute (x^29+17*x-5)^200.' x = PolynomialRing(QQ, 'x').gen() t = cputime() f = (((x ** 29) + (17 * x)) - 5) a = (f ** 200) return (desc, cputime(t))
class Graph(Layer): def __init__(self): self.namespace = set() self.nodes = OrderedDict() self.inputs = {} self.input_order = [] self.outputs = {} self.output_order = [] self.input_config = [] self.output_config = [] self.node_config = [] ...
class Hook(object): def __init__(self): raise NotImplementedError def __call__(self, sess, epoch, iteration, model, loss): raise NotImplementedError
def write_can_to_msg(data, src, msg): if (not isinstance(data[0], Sequence)): data = [data] can_msgs = msg.init('can', len(data)) for (i, d) in enumerate(data): if (d[0] < 0): continue cc = can_msgs[i] cc.address = d[0] cc.busTime = 0 cc.dat = hex_...
def shuffle_in_unison_scary(data): rng_state = np.random.get_state() for d in data: np.random.set_state(rng_state) np.random.shuffle(data[d]) return data
.parametrize('traj,instance,output', [(trjdat, first_instance, (1.0 / 3.0)), (trjdat, second_instance, (1.0 / 2.0))]) def test_location_sequence_match(traj, instance, output): at = attacks.LocationSequenceAttack(knowledge_length=1) results = [] for i in range(1, 7): results.append(at._match(single_t...
class TestRangePlugin(unittest.TestCase): def test_max_range(self): msg = rospy.wait_for_message('/sonar2', Range) self.assertAlmostEqual(msg.range, msg.max_range) def test_inside_range(self): msg = rospy.wait_for_message('/sonar', Range) self.assertTrue(((msg.range < 0.25) and (...
class NeuralStyleTransfer(BaseModel): def __init__(self): super().__init__() def build_model(self, style_weight=0.01, content_weight=10000.0): self.content_layers = ['block5_conv2'] self.style_layers = ['block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'] ...
def make_texture_2d_rgba8(tex: ti.types.rw_texture(num_dimensions=2, fmt=ti.Format.rgba8, lod=0), n: ti.i32): for (i, j) in ti.ndrange(n, n): ret = ti.cast(taichi_logo((ti.Vector([i, j]) / n)), ti.f32) tex.store(ti.Vector([i, j]), ti.Vector([ret, 0.0, 0.0, 0.0]))
class NLLEntropy(_Loss): logger = logging.getLogger() def __init__(self, padding_idx, config, rev_vocab=None, key_vocab=None): super(NLLEntropy, self).__init__() self.padding_idx = padding_idx self.avg_type = config.avg_type if ((rev_vocab is None) or (key_vocab is None)): ...
(scope='module', params=[{'dim': 1, 'approx_order': 3}]) def dg_test_env(request): return DGTermTestEnvornment(**request.param)
_properties class PatternMatchAndApply(ppl.Pass): CATEGORY: str = 'Helper' transformations = properties.ListProperty(element_type=xf.PatternTransformation, default=[], desc='The list of transformations to apply') permissive = properties.Property(dtype=bool, default=False, desc='Whether to apply in permissiv...
class Corana(Benchmark): def __init__(self, dimensions=4): Benchmark.__init__(self, dimensions) self._bounds = list(zip(([(- 5.0)] * self.N), ([5.0] * self.N))) self.global_optimum = [[0 for _ in range(self.N)]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 ...
def test_rpow(): value = 2 proxy = tt.ObjectProxy(value) assert ((3 ** value) == (3 ** proxy)) assert (int in tt.UsageTraceNode.from_proxy(proxy).children['__rpow__'].arg_types[0])
class attentionNet(nn.Module): def __init__(self, squeezeFilters=64, expandFilters=64, depth=3): super(attentionNet, self).__init__() self.inputConv = nn.Conv2d(3, squeezeFilters, 3, 1, 1) depthAttenBlock = [] for i in range(depth): depthAttenBlock.append(attentionGuidedR...
def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('std::string', 'typeId')]) cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=...
def get_data_iterator_and_num_class(args): if args.train_csv: from nnabla.utils.data_iterator import data_iterator_csv_dataset data_iterator = data_iterator_csv_dataset if args.test_csv: assert os.path.isfile(args.test_csv), 'csv file for test not found.' with open(ar...
def main(): args = parse_args() assert (args.out or args.show), 'Please specify at least one operation (save/show the video) with the argument "--out" or "--show"' model = init_detector(args.config, args.checkpoint, device=args.device) video_reader = mmcv.VideoReader(args.video) video_writer = None ...
def inparams(params): ip = [] for param in params: if is_in_param(param): ip.append(param) return ip
def eisenstein_series_lseries(weight, prec=53, max_imaginary_part=0, max_asymp_coeffs=40): f = eisenstein_series_qexp(weight, prec) from sage.lfunctions.all import Dokchitser j = weight L = Dokchitser(conductor=1, gammaV=[0, 1], weight=j, eps=((- 1) ** Integer((j // 2))), poles=[j], residues=('[sqrt(Pi)...
class Mean(Sum): def __init__(self, dimension): super(Mean, self).__init__(dimension, True)
class OPTInt8(CausalInt8Model): config_name: str = 'opt_int8' def __init__(self, weights_path: Optional[str]=None): super().__init__(OPTInt8Engine.config_name, weights_path)
_task_model('remote_homology', 'resnet') class ProteinResNetForSequenceClassification(ProteinResNetAbstractModel): def __init__(self, config): super().__init__(config) self.resnet = ProteinResNetModel(config) self.classify = SequenceClassificationHead(config.hidden_size, config.num_labels) ...
class JunctorCondition(Condition): __hash__ = Condition.__hash__ def __eq__(self, other): return ((self.hash == other.hash) and (self.__class__ is other.__class__) and (self.parts == other.parts)) def change_parts(self, parts): return self.__class__(parts)
def load_default_identifiers(n, g, l): if (n is None): n = n_identifier if (g is None): g = g_identifier if (l is None): l = l_identifier return (n, g, l)
_version(mp, '0.19') def test_gammainc(): assert_mpmath_equal(gammainc, (lambda a, x: mp.gammainc(a, b=x, regularized=True)), [Arg(0, 100, inclusive_a=False), Arg(0, 100)], nan_ok=False, rtol=1e-17, n=50, dps=50)
def write_summary_results(summaries, cls, output_folder): fields = sum([list(s.keys()) for s in summaries], []) values = sum([list(s.values()) for s in summaries], []) default_order = ['HOTA', 'DetA', 'AssA', 'DetRe', 'DetPr', 'AssRe', 'AssPr', 'LocA', 'RHOTA', 'HOTA(0)', 'LocA(0)', 'HOTALocA(0)', 'MOTA', '...
def scaled_sigmoid(x, scale=2.5): vals = (np.tanh((scale * (1 - x))) / np.tanh(scale)).reshape((- 1)) return np.where((x > 2.0), (- 1.0), np.where((x < 0), 1.0, vals))
def predict(path): img = Image.open(path).resize((224, 224)) x = np.array(img) if (len(x.shape) == 2): x = np.stack(([x] * 3), 2) else: pass x = ((x - x.mean()) / x.std()) x = np.expand_dims(x, axis=0) preds = model.predict(x) np.sort(preds) print("Model's top 3 predi...
class CustomProcessor(ProcessorMixin): feature_extractor_class = 'AutoFeatureExtractor' tokenizer_class = 'AutoTokenizer'
def save_model(model, model_dir, params, net_params, optimizer, epoch, ID='model.pkl'): checkpoint_dict = {'model': model.state_dict(), 'epoch': epoch, 'name': str(model), 'optimizer': optimizer.state_dict(), 'metadata': {'date': datetime.now().strftime('%Y-%m-%d'), 'params': params, 'net_params': net_params}} ...
def online_learning_misp_perfect(user, agent, online_data_loader, train_table, update_iter, model_save_path, record_save_path, max_seq_length=222, num_target_layers=2, st_pos=0, end_pos=(- 1)): assert (args.ask_structure and (args.user == 'gold_sim') and (args.err_detector == 'perfect')) cnt = 0 interaction...
def test_explorer(): tmon1 = scq.TunableTransmon(EJmax=40.0, EC=0.2, d=0.1, flux=0.0, ng=0.3, ncut=40, truncated_dim=5) tmon2 = scq.TunableTransmon(EJmax=15.0, EC=0.15, d=0.02, flux=0.0, ng=0.0, ncut=30, truncated_dim=5) resonator = scq.Oscillator(E_osc=4.5, truncated_dim=4) hilbertspace = scq.HilbertSp...
class TestDomain(object): def test_getdomain(self): x = [1, 10, 3, (- 1)] tgt = [(- 1), 10] res = pu.getdomain(x) assert_almost_equal(res, tgt) x = [(1 + 1j), (1 - 1j), 0, 2] tgt = [(- 1j), (2 + 1j)] res = pu.getdomain(x) assert_almost_equal(res, tgt) ...