code
stringlengths
101
5.91M
def data_to_batches(data, batch_size, eval_mode, sort_during_eval, min_length_to_batch_separately): res = [] if (not eval_mode): data = sorted(data, key=(lambda x: len(x[0])), reverse=(random.random() > 0.5)) data_orig_idx = None elif sort_during_eval: ((data,), data_orig_idx) = sort...
def register_Ns3FlowProbeFlowStats_methods(root_module, cls): cls.add_constructor([param('ns3::FlowProbe::FlowStats const &', 'arg0')]) cls.add_constructor([]) cls.add_instance_attribute('bytes', 'uint64_t', is_const=False) cls.add_instance_attribute('bytesDropped', 'std::vector< unsigned long long >', ...
class TestHeadFinder(unittest.TestCase): def setUp(self): self.head_finder = head_finders.HeadFinder() def test_get_head_np(self): self.assertEqual(nltk.ParentedTree('NNS', ['police']), self.head_finder.get_head(nltk.ParentedTree.fromstring('(NP (JJ Local) (NNS police))'))) self.assertEq...
def add_arguments(parser): parser.add_argument('paths', nargs='+', help='path to input coordinates file') parser.add_argument('--destdir', required=True, help='directory to write per image files') parser.add_argument('--invert-y', action='store_true', help='invert (mirror) the y-axis particle coordinates. a...
class FixedLearnRateScheduler(object): def __init__(self, sess, model, base_lr, lr_decay_steps, lr_list=None): self.model = model self.sess = sess self.lr = base_lr self.lr_list = lr_list self.lr_decay_steps = lr_decay_steps self.model.assign_lr(self.sess, self.lr) ...
def main(): strBasepath = (os.path.split(os.path.abspath(__file__))[0] + '/../') strHeaders = [] strSources = [] strDefines = [] strObjects = [] if (force_cuda or torch.cuda.is_available()): strHeaders += ['MYTH/include/MYTH.h'] strSources += ['MYTH/src/MYTH.c'] strDefine...
class ExSocket(object): def __init__(self, sock): self.sock = sock def recvall(self, nbytes): res = [] nread = 0 while (nread < nbytes): chunk = self.sock.recv(min((nbytes - nread), 1024)) nread += len(chunk) res.append(chunk) return b'...
def desc_loss(img_features, pc_features, mask, pos_margin=0.1, neg_margin=1.4, log_scale=10, num_kpt=512): pos_mask = mask neg_mask = (1 - mask) dists = (1 - torch.sum((img_features.unsqueeze((- 1)) * pc_features.unsqueeze((- 2))), dim=1)) pos = (dists - (100000.0 * neg_mask)) pos_weight = (pos - po...
def get_max_wd(ordered_ref_weights): (d0, d1) = (np.zeros(len(ordered_ref_weights)), np.zeros(len(ordered_ref_weights))) d0[np.argmax(ordered_ref_weights)] = 1 d1[np.argmin(ordered_ref_weights)] = 1 max_wd = wasserstein_distance(ordered_ref_weights, ordered_ref_weights, d0, d1) return max_wd
class PyTorchTrainingWrapperBase(TrainingWrapperBase): def __init__(self, model, dummy_input, dummy_label, criterion, optimizer): super(PyTorchTrainingWrapperBase, self).__init__(model, criterion, optimizer) self.dummy_input = dummy_input self.dummy_label = dummy_label def launch(self): ...
def flatten_callback(func: Callable, node: ast.Call, global_vars: Dict[(str, Any)]): unflatten_instructions: List[Tuple[(int, Callable, int, bool)]] = [] curarg = 0 instructions_exist = False args_to_remove = [] kwargs_to_remove = [] for (i, arg) in enumerate(node.args): (call, inc, cons...
def load_gpx(file, user_id=None): track = [([p['properties']['time']] + list(p['geometry']['coordinates'])) for p in fiona.open(file, layer='track_points')] tdf = TrajDataFrame(track, datetime=0, longitude=1, latitude=2) if (user_id is not None): tdf['uid'] = [user_id for _ in range(len(tdf))] r...
def main(device='cpu'): experiment_dir = pathlib.Path(__file__).resolve().parent hparams_file = (experiment_dir / 'hyperparams_quaternion_net.yaml') data_folder = '../../samples/ASR' data_folder = (experiment_dir / data_folder).resolve() with open(hparams_file) as fin: hparams = load_hyperpy...
class ReturnnDatasetPerEpochMapDataPipe(torch.utils.data.MapDataPipe): def __int__(self, returnn_dataset: ReturnnDataset, *, reset_callback: Optional[ResetCallbackT]=None): assert (returnn_dataset.have_corpus_seq_idx() and returnn_dataset.have_get_corpus_seq()) self._dataset = returnn_dataset ...
def with_metaclass(meta, *bases): class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
def test_README_links(recipe_folder='tests/recipes', readme_field='Readme_file', must_link=['Result_url', 'HF_repo']): check = True for recipe_csvfile in os.listdir(recipe_folder): if (recipe_csvfile in __skip_list): continue with open(os.path.join(recipe_folder, recipe_csvfile), new...
class DSModifier_dir(DSModifier): def __init__(self, ds_modifier: Optional[DSModifier]=None): self.name = 'dir_modifier' self.ds_modifier = ds_modifier self.params = {'modifier': '{}'.format(self._get_name())} def _ds_input_modification(self, data_input: str, mod_path: str) -> str: ...
class BottleneckWithGN(Bottleneck): def __init__(self, in_channels, bottleneck_channels, out_channels, num_groups=1, stride_in_1x1=True, stride=1, dilation=1, dcn_config={}): super(BottleneckWithGN, self).__init__(in_channels=in_channels, bottleneck_channels=bottleneck_channels, out_channels=out_channels, n...
class KnowledgeGraph(): def __init__(self, data_dir, gran=1, rev_set=0): self.data_dir = data_dir self.entity_dict = {} self.gran = gran self.entities = [] self.relation_dict = {} self.n_entity = 0 self.n_relation = 0 self.training_triples = [] ...
def build_detection_test_loader(cfg, dataset_name, mapper=None): dataset_dicts = get_detection_dataset_dicts([dataset_name], filter_empty=False, proposal_files=([cfg.DATASETS.PROPOSAL_FILES_TEST[list(cfg.DATASETS.TEST).index(dataset_name)]] if cfg.MODEL.LOAD_PROPOSALS else None)) dataset = DatasetFromList(datas...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--source_file', type=str, help='File with all games.') parser.add_argument('--min_moves', default=10, type=int, help='Minimum number of moves in games.') parser.add_argument('--max_moves', default=150, type=int, help='Maximum numb...
def soft_sync(targ_model: nn.Module, model: nn.Module, tau: float) -> None: with torch.no_grad(): params = model.parameters() targ_params = targ_model.parameters() for (p, p_targ) in zip(params, targ_params): p_targ.data.mul_((1 - tau)) p_targ.data.add_((tau * p.data)...
def register_Ns3Ipv6AddressHelper_methods(root_module, cls): cls.add_constructor([param('ns3::Ipv6AddressHelper const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix'), param('ns3::Ipv6Address', 'base', default_value='ns3::Ipv...
class FPN_Resnet(ResNet): def __init__(self, block, layers, num_classes): super(FPN_Resnet, self).__init__(block, layers) num_feats = 256 bias = False self.latlayer1 = nn.Conv2d(2048, num_feats, kernel_size=1, stride=1, padding=0, bias=bias) self.latlayer2 = nn.Conv2d(1024, n...
() def arepo_snapshot_fname(tardis_ref_path): return ((Path(tardis_ref_path) / 'arepo_data') / 'arepo_snapshot.json')
.box(ArrayBuilderType) def box_ArrayBuilder(arraybuildertype, arraybuilderval, c): ArrayBuilder_obj = c.pyapi.unserialize(c.pyapi.serialize_object(ak.highlevel.ArrayBuilder)) serializable2dict_obj = c.pyapi.unserialize(c.pyapi.serialize_object(ak._connect.numba.arrayview.serializable2dict)) behavior2_obj = ...
class UperNetConvModule(nn.Module): def __init__(self, in_channels: int, out_channels: int, kernel_size: Union[(int, Tuple[(int, int)])], padding: Union[(int, Tuple[(int, int)], str)]=0, bias: bool=False, dilation: Union[(int, Tuple[(int, int)])]=1) -> None: super().__init__() self.conv = nn.Conv2d(...
def create_constant(value: Any, node: Optional[ast.AST]=None) -> ast.AST: if (sys.version_info >= (3, 8)): newnode = ast.Constant(value=value, kind='') elif (value is None): newnode = ast.NameConstant(value=None) elif isinstance(value, str): newnode = ast.Str(s=value) else: ...
def get_dataloader(model, question, paragraphs, tokenizer, batch_size): if (model == 'qa'): examples = read_qa_example(question, paragraphs) max_seq_length = 300 elif (model == 'classifier'): examples = read_classification_examples(question, paragraphs) max_seq_length = 400 e...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--unimorph', required=True, type=str) parser.add_argument('--past', required=True, type=str) parser.add_argument('--outdir') parser.add_argument('--split', default=0.2, type=float) parser.add_argument('--nchar', default=4, t...
def test_get_aggregated_tensor(nparray, tensor_key): db = TensorDB() db.cache_tensor({tensor_key: nparray}) (tensor_name, origin, round_number, report, tags) = tensor_key tensor_key = TensorKey(tensor_name, 'col2', round_number, report, ('model',)) db.cache_tensor({tensor_key: nparray}) collabor...
class TIntIntH(object): thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag') __repr__ = _swig_repr HashPrimes = _snap.TIntIntH_HashPrimes def __init__(self, *args): _snap.TIntIntH_swiginit(self, _snap.new_TIntIntH(*args)) def Load(self, ...
class SquadProcessor(DataProcessor): def get_train_examples(self, filename=None): input_data = readGZip(filename) return self._create_examples(input_data, 'train') def get_dev_examples(self, filename=None): input_data = readGZip(filename) return self._create_examples(input_data, ...
class MyModule(nn.Module): def forward(self, x): raise NotImplementedError def module_str(self): raise NotImplementedError def config(self): raise NotImplementedError def build_from_config(config): raise NotImplementedError def get_flops(self, x): raise NotImp...
class GroupingOperation(Function): def forward(ctx, features, idx): (B, nfeatures, nsample) = idx.size() (_, C, N) = features.size() ctx.for_backwards = (idx, N) return pl.group_points(features.contiguous(), idx) def backward(ctx, grad_out): (idx, N) = ctx.for_backwards ...
def get_logger(filename: str='g-tracker-fastapi') -> logging.Logger: filename = (f'{filename}.log' if (not filename.endswith('.log')) else filename) Path('logs').mkdir(parents=True, exist_ok=True) log = logging.getLogger(filename) log.setLevel(logging.INFO) format = logging.Formatter('%(asctime)s - ...
class BaseWordSegmenter(BaseSegmenter): def __init__(self, segmenter=None, reranker=None, ensembler=None): self.segmenter_model = segmenter self.reranker_model = reranker self.ensembler = ensembler def get_segmenter(self): return self.segmenter_model.model def get_reranker(se...
def maybe_mask(attn, attn_mask): if (attn_mask is not None): assert all((((a == 1) or (b == 1) or (a == b)) for (a, b) in zip(attn.shape[::(- 1)], attn_mask.shape[::(- 1)]))), f'Attention mask shape {attn_mask.shape} should be broadcastable with attention shape {attn.shape}' attn.data.masked_fill_(a...
class GRUStep(nn.Module): def __init__(self, hidden_size, input_size): super(GRUStep, self).__init__() self.linear_z = nn.Linear((hidden_size + input_size), hidden_size, bias=False) self.linear_r = nn.Linear((hidden_size + input_size), hidden_size, bias=False) self.linear_t = nn.Line...
def tfidf_loading(use_tfidf, w_emb, args): if use_tfidf: if args.use_RAD: dict = dataset_RAD.Dictionary.load_from_file(os.path.join(args.RAD_dir, 'dictionary.pkl')) if args.use_RAD: if (os.path.isfile(os.path.join(args.RAD_dir, 'embed_tfidf_weights.pkl')) == True): ...
def register_Ns3SimpleRefCount__Ns3MacTxMiddle_Ns3Empty_Ns3DefaultDeleter__lt__ns3MacTxMiddle__gt___methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::SimpleRefCount< ns3::MacTxMiddle, ns3::empty, ns3::DefaultDeleter< ns3::MacTxMiddle > > const &', 'o')]) return
def require_sigopt(test_case): if (not is_sigopt_available()): return unittest.skip('test requires SigOpt')(test_case) else: return test_case
def register_Ns3Ipv4RawSocketImpl_methods(root_module, cls): cls.add_constructor([param('ns3::Ipv4RawSocketImpl const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_virtual=True) cls.add_method('Bind', 'int', [], is_virtual=True) cl...
def getAlisaBucket(): ep = os.getenv('SQLFLOW_OSS_ALISA_ENDPOINT') ak = os.getenv('SQLFLOW_OSS_AK') sk = os.getenv('SQLFLOW_OSS_SK') bucketName = os.getenv('SQLFLOW_OSS_ALISA_BUCKET') if ((ep == '') or (ak == '') or (sk == '')): return SQLFlowDiagnostic('should define SQLFLOW_OSS_ALISA_ENDPO...
class Upsampler(nn.Module): def __init__(self, K, child_model, input_dim): super().__init__() if (len(input_dim) == 1): self.tabular = True elif (len(input_dim) == 3): self.tabular = False self.transposed_cnn = nn.Sequential(nn.ConvTranspose2d(K, K, kernel...
def faster_rcnn(model): logger.warn('Deprecated: use `MODEL.TYPE: generalized_rcnn` with `MODEL.FASTER_RCNN: True`') return generalized_rcnn(model)
class OffsetBricksSetBBreakoutWorld(RandomOffsetBricksBreakoutWorld): brick_offset_range_start = 80 brick_offset_range_end = 100
def register_Ns3BlockAckManager_methods(root_module, cls): cls.add_constructor([]) cls.add_method('AlreadyExists', 'bool', [param('uint16_t', 'currentSeq'), param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')], is_const=True) cls.add_method('CompleteAmpduExchange', 'void', [param('ns3::Mac48Add...
def generate_list(description_file): file_list = [] job_list = [] file_list.append((description_file, None)) while (len(file_list) > 0): (cur_file, parent) = file_list.pop((- 1)) print(cur_file) with open(cur_file) as f: data = json.load(f) job = Job(data[...
def test_non_root_branch_coverage_goal(branch_goal): assert (branch_goal.predicate_id == 0) assert (branch_goal.value is True)
_utils.test() def test_sort(): def test_sort_for_dtype(dtype, N): keys = ti.field(dtype, N) values = ti.field(dtype, N) def fill(): for i in keys: keys[i] = (ti.random() * N) values[i] = keys[i] fill() ti.algorithms.parallel_sort(ke...
class MobileNetV3(nn.Module): def __init__(self, setting='large', widen_factor=1.0, norm='bn', activation=H_Swish, drop_rate=0.0, num_classes=1000): super(MobileNetV3, self).__init__() block = LinearBottleneck self.widen_factor = widen_factor self.norm = norm self.se_reduce_m...
class Lamb(Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-06, weight_decay=0, adam=False): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= eps)): raise ValueError('Invalid epsilon value: {}'.format(ep...
def test_irshift(): value = 2 copy = proxy = tt.ObjectProxy(value) value >>= 1 proxy >>= 1 assert (value == proxy) assert (int in tt.UsageTraceNode.from_proxy(copy).children['__irshift__'].arg_types[0])
class gompertz_gen(rv_continuous): def _shape_info(self): return [_ShapeInfo('c', False, (0, np.inf), (False, False))] def _pdf(self, x, c): return np.exp(self._logpdf(x, c)) def _logpdf(self, x, c): return ((np.log(c) + x) - (c * sc.expm1(x))) def _cdf(self, x, c): retur...
def test_cli_video_speed(): with patch_sys_argv_helper(['ti', 'video_speed', '-i', 'video.mp4', '-s', '2.0']) as custom_argv: cli = TaichiMain(test_mode=True) args = cli() assert (args.input_file == 'video.mp4') assert (args.speed == 2.0) assert (args.output_file == 'video-sp...
def get_config_var(var): try: return sysconfig.get_config_var(var) except IOError as e: warnings.warn('{}'.format(e), RuntimeWarning) return None
class LengthEval(PROBINGEval): def __init__(self, task_path, seed=1111): task_path = os.path.join(task_path, 'sentence_length.txt') PROBINGEval.__init__(self, 'Length', task_path, seed)
class BasicCNNModel(nn.Module): def __init__(self, vocab_size, embed_dim, n_classes, n_filters, filter_sizes, dropout, pad_idx): super(BasicCNNModel, self).__init__() self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embed_dim, padding_idx=pad_idx) self.convs = nn.Module...
def do_paired_ttest(run1, run2, qrels, measurement): run1_list = measure_per_query(run1, qrels, measurement) run2_list = measure_per_query(run2, qrels, measurement) (stat, p) = stats.ttest_rel(run1_list, run2_list) diff_run1_run2 = [sum(x) for x in zip(run2_list, [(- x) for x in run1_list])] effect_...
class PassiveAggressiveRegressor(BaseSGDRegressor): _parameter_constraints: dict = {**BaseSGDRegressor._parameter_constraints, 'loss': [StrOptions({'epsilon_insensitive', 'squared_epsilon_insensitive'})], 'C': [Interval(Real, 0, None, closed='right')], 'epsilon': [Interval(Real, 0, None, closed='left')]} def __...
def make_index(data_path): metadata_rel_path = os.path.join('meta', 'esc50.csv') index = {'version': '2.0.0', 'clips': {}, 'metadata': {'esc50.csv': [metadata_rel_path, md5(os.path.join(data_path, metadata_rel_path))]}} audio_dir = os.path.join(data_path, 'audio') wavfiles = glob.glob(os.path.join(audio...
def _average_by_key(list_of_dicts: List[Dict[(str, float)]]): return pd.DataFrame.from_dict(list_of_dicts).mean().to_dict()
class IWSLT(TranslationDataset): base_url = ' name = 'iwslt' base_dirname = '{}-{}' def splits(cls, exts, fields, root='.data', train='train', validation='IWSLT16.TED.tst2013', test='IWSLT16.TED.tst2014', **kwargs): cls.dirname = cls.base_dirname.format(exts[0][1:], exts[1][1:]) cls.urls...
def mkdir_if_missing(directory): if (not osp.exists(directory)): try: os.makedirs(directory) except OSError as e: if (e.errno != errno.EEXIST): raise
def cost_matrix(x, y, p=2): x_col = x.unsqueeze(1) y_lin = y.unsqueeze(0) c = torch.sum((torch.abs((x_col - y_lin)) ** p), 2) return c
def epoch_train(net, save_path, root): net.eval() with torch.no_grad(): for folder in os.listdir(os.path.join(root, 'train')): for file_name in os.listdir(os.path.join(root, 'train', str(folder))): image = Image.open(os.path.join(root, 'train', str(folder), file_name)).conver...
class SFU_reg(atomic_reg): OP_NAME = 'SFU' _fields_ = [('cmd_short', ctypes.c_uint64, 1), ('op_code', ctypes.c_uint64, 16), ('cmd_id_dep', ctypes.c_uint64, 24), ('tsk_typ', ctypes.c_uint64, 4), ('tsk_eu_typ', ctypes.c_uint64, 5), ('opt_rq', ctypes.c_uint64, 1), ('tsk_opd_num', ctypes.c_uint64, 2), ('pad_mode', ...
class MetricsRecorder(object): def __init__(self, device, *metric_names): self.metric_names = list(metric_names) self.metric_group_names = {n: n for n in metric_names} self.device = device self.metrics_value = {} self.metrics_count = {} for metric_name in metric_names...
class SmoothedValue(object): def __init__(self, window_size=1): self.deque = deque(maxlen=window_size) self.total = 0.0 self.count = 0 def update(self, value): self.deque.append(value) self.count += 1 self.total += value def median(self): d = torch.ten...
class ByteMaskedArray(Content): def __init__(self, mask, content, validwhen): assert isinstance(mask, list) assert isinstance(content, Content) assert isinstance(validwhen, bool) assert (len(mask) <= len(content)) for x in mask: assert isinstance(x, bool) ...
class ApplyMask(nn.Module): def __init__(self, complex=True, log_amp=False): super().__init__() self.amp2db = audio_nn.DbToAmplitude() self.complex = complex self.log_amp = log_amp def forward(self, bd): if (not self.complex): Y_hat = (bd['mag_X'] * bd['M_hat'...
.parametrize('tags,add_field,remove_field,expected_result', [(('abc', 'def', 'def'), 'def', None, ('abc', 'def')), (('abc', 'def', 'def'), None, 'def', ('abc',)), (('abc', 'def', 'def'), 'ghi', 'abc', ('def', 'ghi'))]) def test_change_tags_duplicate_fields_in_tags(tags, add_field, remove_field, expected_result): re...
class WhisperOnnxConfig(OnnxSeq2SeqConfigWithPast): def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: common_inputs = OrderedDict([('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'})]) if self.use_past: common_inputs['decoder_input_ids'] = {0: 'batch'} ...
class SPADEModelModules(nn.Module): def __init__(self, opt): opt = copy.deepcopy(opt) if (len(opt.gpu_ids) > 0): opt.gpu_ids = opt.gpu_ids[:1] self.gpu_ids = opt.gpu_ids super(SPADEModelModules, self).__init__() self.opt = opt self.model_names = ['G'] ...
class RandomResizedCrop(object): def __init__(self, size, scale=(0.5, 1.0), ignore_idx=255): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size if isinstance(scale, tuple): self.scale = scale else: ...
def search_clang_format(): base = 'clang-format' versions = ['10', '12'] for c in [(base + '-{}'.format(v)) for v in versions]: clang = which(c) if (clang is not None): return clang raise ValueError('Not found: clang-format-12')
def get_status(obj): return [('Attributes', [('socket', obj.socket), ('mem_latency', obj.mem_latency), ('sync_period', obj.sync_period)])]
def zero_ext(x, n, axis=(- 1)): if (n < 1): return x zeros_shape = list(x.shape) zeros_shape[axis] = n zeros = np.zeros(zeros_shape, dtype=x.dtype) ext = np.concatenate((zeros, x, zeros), axis=axis) return ext
def bool_gather_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes): dy = grad_inputs[0] m0 = inputs[1] dx = F.bool_scatter(dy, m0) dm = None return (dx, dm)
def train_one_epoch(epoch, model, loader, optimizer, loss_fn, args, lr_scheduler=None, saver=None, output_dir='', amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None, optimizers=None): if (args.mixup_off_epoch and (epoch >= args.mixup_off_epoch)): if (args.prefetcher and loader.mixup_enab...
def is_locally_represented_number_at_place(self, m, p) -> bool: self.local_representation_conditions(silent_flag=True) return self.__local_representability_conditions.is_locally_represented_at_place(m, p)
def list_contains_pain_mention(list): b = any(((term in dict_pain) for term in list)) return (True if b else False)
def gen_random_replay_w_prob(device, cl_setting, abbr_seq, model, replay_prob, replay_mask_img=False, use_gt_sg=False, setting_idx=1, **kwargs): root_dir = kwargs.get('root_dir', '/Users/stan') print(f'ROOT={root_dir}') print(f'DEVICE={device}') tmpl = 'if [ ! -f "{}" ] ; then \n CUDA_VISIBLE_DEVICES=$D...
def simScaleObject(shapeHandle, scale_x, scale_y, scale_z): ret = lib.simScaleObject(shapeHandle, scale_x, scale_y, scale_z, 0) _check_return(ret)
def sympy_divide_fix(expr): nexpr = expr if (not isinstance(expr, sympy.Basic)): return expr int_floor = sympy.Function('int_floor') processed = 1 while (processed > 0): processed = 0 for candidate in nexpr.find(sympy.Mul): for (i, arg) in enumerate(candidate.args...
def c4c6_model(c4, c6, assume_nonsingular=False): if (not assume_nonsingular): if (not c4c6_nonsingular(c4, c6)): return None return EllipticCurve([0, 0, 0, ((- c4) / 48), ((- c6) / 864)])
_model def gluon_resnet50_v1s(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['gluon_resnet50_v1s'] model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, stem_width=64, stem_type='deep', **kwargs) model.default_cfg = default_cfg if pre...
def train(fold=0, data_name='dstc8', model_name='HiGRU+ATTN', dialog_used=10): print('[TRAIN ACTION]') data_name = data_name.split('<>')[(- 1)] data_name = data_name.replace('\r', '') model_name = model_name.replace('\r', '') print('dialog used', dialog_used) name = f'act_{data_name}_{model_name...
def check_stoppers(obj, stoppers): optimal = [] critical = [] for stopper in stoppers: l = stopper['left'](obj) r = stopper['right'](obj) if (stopper['stopType'] == 'optimal'): optimal.append((l <= r)) if (stopper['stopType'] == 'critical'): critical.a...
class CubicHeckeExtensionRing(LaurentPolynomialRing_mpair): def __init__(self, names, order='degrevlex', ring_of_definition=None, third_unity_root_name='e3', markov_trace_version=False): self._ring_of_definition = None self._splitting_algebra = None if (ring_of_definition is not None): ...
def _get_line_annotations_for_branch_coverage(lineno: int, code_object_coverage: dict[(int, CoverageEntry)], predicate_coverage: dict[(int, CoverageEntry)]) -> LineAnnotation: total = CoverageEntry() branches = CoverageEntry() branchless_code_objects = CoverageEntry() if (lineno in code_object_coverage)...
class TestShapTabular(unittest.TestCase): def test(self): base_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..') task = TabularClassification(base_folder).train_adult(num_training_samples=2000) predict_function = (lambda z: task.model.predict_proba(task.transform.transf...
def simulate(n=200, p=100, s=10, signal=(0.5, 1), sigma=2, alpha=0.1, B=1000): (X, y, truth) = gaussian_instance(n=n, p=p, s=s, equicorrelated=False, rho=0.5, sigma=sigma, signal=signal, random_signs=True, scale=False)[:3] dispersion = (sigma ** 2) S = X.T.dot(y) covS = (dispersion * X.T.dot(X)) smo...
def HyperellipticCurve(f, h=0, names=None, PP=None, check_squarefree=True): F = ((h ** 2) + (4 * f)) if (not isinstance(F, Polynomial)): raise TypeError(('Arguments f (= %s) and h (= %s) must be polynomials' % (f, h))) P = F.parent() f = P(f) h = P(h) df = f.degree() dh_2 = (2 * h.de...
def get_transform(transform_type='default', image_size=32, args=None): if (transform_type == 'imagenet'): mean = (0.485, 0.456, 0.406) std = (0.229, 0.224, 0.225) interpolation = args.interpolation crop_pct = args.crop_pct train_transform = transforms.Compose([transforms.Resi...
class Function_zetaderiv(GinacFunction): def __init__(self): GinacFunction.__init__(self, 'zetaderiv', nargs=2, conversions=dict(maple='Zeta')) def _evalf_(self, n, x, parent=None, algorithm=None): return _mpmath_utils_call(_mpmath_zeta, x, 1, n, parent=parent) def _method_arguments(self, k,...
def ellip_harm_2(h2, k2, n, p, s): with np.errstate(all='ignore'): return _ellip_harm_2_vec(h2, k2, n, p, s)
def extract_model_weights(model): attention_params = [] all_params = [] for (name, p) in model.named_parameters(): all_params.append(p.data.cpu().numpy()) if (('bias' not in name) and (('c_proj' in name) or ('c_attn' in name))): (_, _, block, _, l, _) = name.split('.') ...
class KBQA(): def __init__(self, output_model_path='./models/model.best.hdf5'): self.output_model_path = output_model_path self.dataset = None def load_data(self, dataset_name, split): pass def build_model(self): self.model_train = Model(inputs=[question_input], outputs=[answ...