code
stringlengths
101
5.91M
('spacy') class SpacySentenceSplitter(SentenceSplitter): def __init__(self, language: str='en_core_web_sm', rule_based: bool=False) -> None: self.spacy = get_spacy_model(language, parse=(not rule_based), ner=False, pos_tags=False) if rule_based: if (not self.spacy.has_pipe('sbd')): ...
class WeightNormalizedConvTranspose2d(_ConvTransposeMixin, _WeightNormalizedConvNd): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, scale=False, bias=False, dilation=1, init_factor=1, init_scale=1): kernel_size = _pair(kernel_size) stride = _pair(st...
def videos_resize(videoinfos): global count (videoid, videoname) = videoinfos if os.path.exists(os.path.join(output_path, videoname)): print(f'{videoname} is resized.') return inname = ((folder_path + '/') + videoname) outname = ((output_path + '/') + videoname) cmd = 'ffmpeg -y ...
def test_identities1(): x = np.array([(- 99.5), (- 9.5), (- 0.5), 0.5, 9.5, 99.5]) y = x.copy() (x, y) = np.meshgrid(x, y) z = (x + (1j * y)).flatten() dataset = np.vstack((z, gamma(z))).T def f(z): return np.exp(loggamma(z)) FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
def plot_rects(true_overlap, rand_overlap, savefile=None): true_count = Counter(true_overlap) rand_count = Counter(rand_overlap) true_percent = [(true_count[(i, False)] / (true_count[(i, False)] + true_count[(i, True)])) for i in range(3)] rand_percent = [(rand_count[(i, False)] / (rand_count[(i, False)...
class ConvBNReLU(nn.Sequential): def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1): padding = ((kernel_size - 1) // 2) super(ConvBNReLU, self).__init__(nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), nn.BatchNorm2d(out_planes), nn...
def register_Ns3GridBuildingAllocator_methods(root_module, cls): cls.add_constructor([param('ns3::GridBuildingAllocator const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Create', 'ns3::BuildingContainer', [param('uint32_t', 'n')], is_const=True) cls.add_method('GetTypeId', 'ns3::TypeId', [], i...
def main(unused_argv): assert (not (FLAGS.train_shards % FLAGS.num_threads)), 'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards' assert (not (FLAGS.validation_shards % FLAGS.num_threads)), 'Please make the FLAGS.num_threads commensurate with FLAGS.validation_shards' print(('Saving resu...
def upsample(x, size, mode): return F.interpolate(x.unsqueeze(1), size=size, mode=mode, align_corners=False).squeeze().numpy()
def get_times_for_device_framework_and_method(device, framework, method): times = [] for n in ns: time = res[(framework, device, n, method, 'time_per_epoch')] if (time == '-'): break times.append(time) times = np.array(times) return times
class ModelExpBiLSTMMulAttn(ModelTemplate): def __init__(self, token_emb_mat, glove_emb_mat, tds, cds, tl, scope): super(ModelExpBiLSTMMulAttn, self).__init__(token_emb_mat, glove_emb_mat, tds, cds, tl, scope) self.update_tensor_add_ema_and_opt() def build_network(self): _logger.add() ...
def str_to_number(value): is_neg = False if (value[:1] == '-'): is_neg = True value = value[1:] if (len(value) < 2): value = int(value, 0) elif (value[0] == '0'): literal_type = value[1] if (literal_type in 'xX'): value = int(value[2:], 16) eli...
def create_predict_net(predictor_export_meta): net = core.Net((predictor_export_meta.predict_net.name or 'predict')) net.Proto().op.extend(predictor_export_meta.predict_net.op) net.Proto().partition_info.extend(predictor_export_meta.predict_net.partition_info) net.Proto().external_input.extend((predicto...
class PolyhedralFan(SageObject): def __init__(self, gfan_polyhedral_fan, parameter_indices=None): if (parameter_indices is None): parameter_indices = [] fan_keys = ['AMBIENT_DIM', 'DIM', 'LINEALITY_DIM', 'RAYS', 'N_RAYS', 'LINEALITY_SPACE', 'ORTH_LINEALITY_SPACE', 'F_VECTOR', 'CONES', 'M...
class MultipleNegativesRankingLoss(nn.Module): def __init__(self, model: SentenceTransformer): super(MultipleNegativesRankingLoss, self).__init__() self.model = model def forward(self, sentence_features: Iterable[Dict[(str, Tensor)]], labels: Tensor): reps = [self.model(sentence_feature)...
class TestGrouping(TestCaseBase): def test_parenthesis(self): s = 'select (select (x3) x2) and (y2) bar' parsed = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, str(parsed)) self.assertEqual(len(parsed.tokens), 7) self.assert_(isinstance(parsed.tokens[2], sql.Parenthesis)) ...
def _ensure_project_exists(client: scaleapi.ScaleClient, project_name: str): with _scale_projects_lock: if (project_name not in _scale_projects): try: client.create_project(project_name=project_name, task_type=TaskType.TextCollection, rapid=True, params={}) hlog(f...
class MultiManagerEnvironment(EnasTrainEnv): def __init__(self, data_descriptive_features, is_enas='auto', *args, **kwargs): super(MultiManagerEnvironment, self).__init__(*args, **kwargs) assert (type(self.manager) is list), ('MultiManagerEnasEnvironment must have a List of manager instances, got %s...
_LAYERS.register_module() class DropBlock(nn.Module): def __init__(self, drop_prob, block_size, warmup_iters=2000, **kwargs): super(DropBlock, self).__init__() assert ((block_size % 2) == 1) assert (0 < drop_prob <= 1) assert (warmup_iters >= 0) self.drop_prob = drop_prob ...
_agent('simul_trans_text') class SimulTransTextAgent(SimulTransAgent): def build_word_splitter(self, args): self.word_splitter = {} self.word_splitter['src'] = SPLITTER_DICT[args.src_splitter_type](getattr(args, f'src_splitter_path')) self.word_splitter['tgt'] = SPLITTER_DICT[args.tgt_splitt...
def remove_cuda(config_list): cuda_config = {'device': 'cuda'} return [config for config in config_list if (cuda_config not in config)]
class HtmlBuilder(): def __init__(self, indent=None): self.html = [] self.indent_amount = indent self.indent_level = 0 self.add_count = 0 def add(self, data, one_line=False): self.add_count += 1 if one_line: self.html[(- 1)] += data else: ...
class DataSequencer(object): def __init__(self, sequence_strategy, time_horizon): self.sequence_strategy = sequence_strategy self.time_horizon = time_horizon if (sequence_strategy not in VALID_SEQUENCE_STRATEGIES): raise ValueError(('%s is not a valid sequence embedding strategy....
def _create_computational_graph(fun_list: List['goos.Function']) -> Tuple[(FunctionMap, Graph, Set[NodeId], NodeId)]: out_nodes = [id(fun) for fun in fun_list] fun_map = {node: fun for (node, fun) in zip(out_nodes, fun_list)} in_nodes = set() heavy_nodes = set() graph = {} qu = collections.deque...
def preprocess_mask(mask): mask = mask.convert('L') (w, h) = mask.size (w, h) = map((lambda x: (x - (x % 32))), (w, h)) mask = mask.resize(((w // 8), (h // 8)), resample=PIL.Image.NEAREST) mask = (np.array(mask).astype(np.float32) / 255.0) mask = np.tile(mask, (4, 1, 1)) mask = mask[None].tr...
_model def metaformer_pppa_s12_224(pretrained=False, **kwargs): layers = [2, 2, 6, 2] embed_dims = [64, 128, 320, 512] add_pos_embs = [None, None, None, partial(AddPositionEmb, spatial_shape=[7, 7])] token_mixers = [Pooling, Pooling, Pooling, Attention] mlp_ratios = [4, 4, 4, 4] downsamples = [T...
def mlp(x, dims, is_training=True, act_fn=None, dtype=tf.float32, add_bias=True, wd=None, init_std=None, init_method=None, scope='mlp', dropout=None, trainable=True): num_layer = (len(dims) - 1) h = x with tf.variable_scope(scope): for ii in range(num_layer): with tf.variable_scope('laye...
def ULIP_PN_SSG(args): vision_model = timm.create_model('vit_base_patch16_224', num_classes=0) point_encoder = Pointnet2_Ssg() pc_feat_dims = 256 model = ULIP_WITH_IMAGE(embed_dim=512, vision_width=768, point_encoder=point_encoder, vision_model=vision_model, context_length=77, vocab_size=49408, transfor...
def valid_file_prefix(prefix): if (os.path.dirname(prefix) != ''): raise argparse.ArgumentTypeError(('%s is not a valid output prefix (includes a directory).' % prefix)) return prefix
(datatype[(N, M)], datatype[(M, M)], datatype[M], datatype[M]) def correlation(data, corr, mean, stddev): def comp_mean(j: _[0:M], i: _[0:N]): (inp << data[(i, j)]) (out >> mean(1, (lambda x, y: (x + y)), 0)[j]) out = inp def comp_mean2(j: _[0:M]): (inp << mean[j]) (out >...
class Bottleneck(nn.Module): def __init__(self, in_planes, growth_rate): super(Bottleneck, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, (4 * growth_rate), kernel_size=1, bias=False) self.bn2 = nn.BatchNorm2d((4 * growth_rate)) self.c...
def test_pipeline_methods_pca_svm(): iris = load_iris() X = iris.data y = iris.target clf = SVC(gamma='scale', probability=True, random_state=0) pca = PCA(svd_solver='full', n_components='mle', whiten=True) pipe = Pipeline([('pca', pca), ('svc', clf)]) pipe.fit(X, y) pipe.predict(X) ...
class OverallNCALoss(nn.Module): def __init__(self, modules, device): super(OverallNCALoss, self).__init__() self.device = device self.criterion_dict = {} for module in modules: self.criterion_dict[module] = NCALoss(alpha=1, beta=1, ep=0.0) self.criterion_dict['jo...
def read_translations(path, n_repeats): segment_counter = 0 segment_translations = [] translations = defaultdict(list) for line in open(path): segment_translations.append(' '.join(line.split())) if (len(segment_translations) == n_repeats): translations[segment_counter] = segm...
def learn(*, policy, env, nsteps, total_episodes, ent_coef, lr, vf_coef=0.5, max_grad_norm=0.5, gamma=0.99, lam=0.95, log_interval=10, nminibatches=4, noptepochs=4, cliprange=0.2, save_interval=0, keep_all_ckpt=False, paths=100, epsilon=1.0): if isinstance(epsilon, float): epsilon = constfn(epsilon) els...
def mos_wav2vec2(refresh=False, *args, **kwargs): kwargs['ckpt'] = ' return mos_wav2vec2_url(*args, refresh=refresh, **kwargs)
def prior(D=10, lower_bound=(- 1.0), upper_bound=1.0, rng=None): if (rng is None): rng = np.random.default_rng() return rng.uniform(low=lower_bound, high=upper_bound, size=D)
class PreActivationResNet(nn.Module): def __init__(self, block, layers, sample_size, sample_duration, shortcut_type='B', num_classes=400, last_fc=True): self.last_fc = last_fc self.inplanes = 64 super(PreActivationResNet, self).__init__() self.conv1 = nn.Conv3d(3, 64, kernel_size=7, ...
def main(args): config_file = args.config_file config = utils.import_file(config_file, 'config_') if (config.base_random_seed is not None): random.seed(config.base_random_seed) torch.manual_seed(config.base_random_seed) network = LiftedGAN() network.initialize(config) log_dir = u...
class TestRaster2D(unittest.TestCase): def test_square(self): grid_x = np.arange(5) grid_y = np.arange(5) poly_xy = np.array([[1, 3.5, 3.5, 1], [1, 1, 3.5, 3.5]]) render = float_raster.raster_2D(poly_xy, grid_x, grid_y) np.testing.assert_array_almost_equal(render, np.array([[...
def make_eval_data(args): xgrid = np.linspace((- 0.5), 0.5, args.fr_size, endpoint=False) if (args.kernel_type == 'triangle'): kernel_param = (args.triangle_slope / args.signal_dim) else: kernel_param = (args.gaussian_std / args.signal_dim) return load_dataloader_fixed_noise(args.n_valid...
class AttentionValueDecoder(nn.Module): def __init__(self, h_dim, out_size): super().__init__() self.conv1 = nn.Conv2d(h_dim, h_dim, 1, stride=1, padding=0) self.conv2 = nn.Conv2d(h_dim, out_size, 1, stride=1, padding=0) def forward(self, x): hidden = F.relu(self.conv1(x)) ...
class SerialBlock_adapt_M(nn.Module): def __init__(self, seq_length, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm, shared_cpe=None, shared_crpe=None, adapt_method=None, num_domains=4): super().__init__() ...
class Resize(Function): def forward(ctx, tensor, sizes): ctx.sizes = sizes ctx.numel = reduce((lambda x, y: (x * y)), sizes, 1) if (tensor.numel() != ctx.numel): raise RuntimeError("requested resize to {} ({} elements in total), but the given tensor has a size of {} ({} elements)...
def get_windows_version(run_lambda): system_root = os.environ.get('SystemRoot', 'C:\\Windows') wmic_cmd = os.path.join(system_root, 'System32', 'Wbem', 'wmic') findstr_cmd = os.path.join(system_root, 'System32', 'findstr') return run_and_read_all(run_lambda, '{} os get Caption | {} /v Caption'.format(wm...
def load_word_vectors(file, vocab_word_vec_file, word2id, vector_size=300, header=False): word2vector = {} if os.path.exists(vocab_word_vec_file): print(('Loading vocabulary word vectors from %s...' % vocab_word_vec_file)) with open(vocab_word_vec_file, 'r', encoding='utf-8') as f: f...
class ImaginaryElement(AdditiveGroupElement): def __init__(self, parent, imag): if (parent is None): raise ValueError('parent must be provided') super().__init__(parent=parent) try: self._imag_ = parent.base()(imag) except (TypeError, ValueError) as e: ...
def postprocess_qa_predictions_with_beam_search(examples, features, predictions: Tuple[(np.ndarray, np.ndarray)], version_2_with_negative: bool=False, n_best_size: int=20, max_answer_length: int=30, start_n_top: int=5, end_n_top: int=5, output_dir: Optional[str]=None, prefix: Optional[str]=None, log_level: Optional[int...
class SensorCompliance(): def __init__(self): rospack = rospkg.RosPack() pkg_path = rospack.get_path('vrx_gazebo') self.config_dir = os.path.join(pkg_path, 'config', 'wamv_config') self.boxes = find_boxes(os.path.join(self.config_dir, 'sensor_compliance', 'bounding_boxes.yaml')) ...
class Parsopoulos(Benchmark): def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip(([(- 5.0)] * self.N), ([5.0] * self.N))) self.global_optimum = [[(pi / 2.0), pi]] self.fglob = 0 def fun(self, x, *args): self.nfev += 1 re...
def register_Ns3VhtConfiguration_methods(root_module, cls): cls.add_constructor([param('ns3::VhtConfiguration const &', 'arg0')]) cls.add_constructor([]) cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return
def postprocess_qa_predictions_with_beam_search(examples, features, predictions: Tuple[(np.ndarray, np.ndarray)], version_2_with_negative: bool=False, n_best_size: int=20, max_answer_length: int=30, start_n_top: int=5, end_n_top: int=5, output_dir: Optional[str]=None, prefix: Optional[str]=None, log_level: Optional[int...
class Denormalize(object): def __init__(self, mean, std): mean = np.array(mean) std = np.array(std) self._mean = ((- mean) / std) self._std = (1 / std) def __call__(self, tensor): if isinstance(tensor, np.ndarray): return ((tensor - self._mean.reshape((- 1), 1...
def reset_to_default() -> None: set_temp(0.015) set_low_freq(1, 'Hz') set_high_freq(3, 'GHz') set_t_exp(10, 'us')
def Cutout(img, v, max_v, bias=0): if (v == 0): return img v = (_float_parameter(v, max_v) + bias) v = int((v * min(img.size))) return CutoutAbs(img, v)
_utils.test() def test_check_matrix_field_member_shape(): a = ti.Matrix.field(2, 2, ti.i32) ti.root.dense(ti.i, 10).place(a.get_scalar_field(0, 0)) ti.root.dense(ti.i, 11).place(a.get_scalar_field(0, 1)) ti.root.dense(ti.i, 10).place(a.get_scalar_field(1, 0)) ti.root.dense(ti.i, 11).place(a.get_scal...
class Ax3DPose(object): def __init__(self, ax, joints, lcolor='#3498db', rcolor='#e74c3c', ccolor='#2fb551'): matplotlib.rcParams['animation.embed_limit'] = 200 self.joints = joints self.I = np.array([0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 20, 25, 2...
class BatchNormalizationLayer(Layer): def __call__(self, x, seq_len=None): n_out = int(x.get_shape()[(- 1)]) decay = self.decay eps = self.eps stddev = self.stddev phase_train = self.phase_train with tf.variable_scope(self.scope) as scope: self.check_reuse...
def _update_weights(state_dict, tensor_dict, prefix, suffix=None): dict_prefix = (f'{prefix}_{suffix}' if (suffix is not None) else f'{prefix}') for (layer_name, param_obj) in state_dict.items(): for (param_name, value) in param_obj.items(): key = '*'.join([dict_prefix, layer_name, param_nam...
def layout(): _ids = get_doc_ids_from_db() dropdown_dates = {num2str_month(_id): _id for _id in _ids} children_list = [html.Div([html.Div([html.H3('Write topic labels to database'), dcc.Markdown('\n This app allows a user to inspect the results for monthly topics from our production\n ...
def generate_constant(output_name, tensor_name, data_type, dims, vals): t = onnx.helper.make_tensor(tensor_name, data_type=data_type, dims=dims, vals=vals) c = onnx.helper.make_node('Constant', [], [output_name], value=t) return c
class PredicateMapping(): def __init__(self) -> None: self.symbols2predicate = {} self.counter = 0 def add_mapping(self, predicate: (BoolExpr or A_Expr)) -> Symbol: res = symbols(str(self.counter)) self.symbols2predicate[res] = predicate self.counter += 1 return r...
def conjugate_gradient(A, b, max_iters, res_tol=1e-10): x = torch.zeros_like(b) r = (b - A(x)) p = r rTr = (r.T r) for _ in range(max_iters): Ap = A(p) alpha = (rTr / (p.T Ap)) x = (x + (alpha * p)) r = (r - (alpha * Ap)) if (torch.norm(r) < res_tol): ...
def adjust_scales2image(size, opt): opt.num_scales = (math.ceil(math.log(math.pow((opt.min_size / size), 1), opt.scale_factor_init)) + 1) scale2stop = math.ceil(math.log((min([opt.max_size, size]) / size), opt.scale_factor_init)) opt.stop_scale = (opt.num_scales - scale2stop) opt.scale1 = min((opt.max_s...
class FieldPair(): def __init__(self, name, content): self.name = name self.content = content
def deconv5x5_relu(in_channels, out_channels, stride, output_padding): return deconv(in_channels, out_channels, 5, stride, 2, output_padding=output_padding, activation_fn=partial(nn.ReLU, inplace=True))
class FakeData(data.Dataset): def __init__(self, size=1000, image_size=(3, 224, 224), num_classes=10, transform=None, target_transform=None, random_offset=0): self.size = size self.num_classes = num_classes self.image_size = image_size self.transform = transform self.target_t...
def get_batch(bs, all_X, all_sup_Nary_Y, all_sup_Y, d, K): inds = np.random.randint(0, d, bs) X = np.zeros((bs, d), dtype=np.float32) Z = np.sign(np.random.randn(bs, K)).astype(np.float32) Y = np.zeros((bs, K), dtype=np.float32) for (j, ind) in enumerate(inds): X[j] = all_X[ind] Y[j]...
def remove_prefixes_line(line): line = line.strip().replace('\n', ' ').replace('\t', ' ').replace('<PARAGRAPH><PARAGRAPH>', '<PARAGRAPH>') line = line.replace('See Important Quotations Explained', '').strip() line = line.replace('Chapter 5: The Wine-shop', 'Chapter 5: The Wine shop').strip() line = line...
def get_argparse_groups(parser): groups = {} for group in parser._action_groups: group_dict = {a.dest: getattr(args, a.dest, None) for a in group._group_actions} groups[group.title] = argparse.Namespace(**group_dict) return groups
class TD3(TorchRLAlgorithm): def __init__(self, env, qf1, qf2, policy, exploration_policy, eval_policy=None, target_policy_noise=0.2, target_policy_noise_clip=0.5, policy_learning_rate=0.001, qf_learning_rate=0.001, policy_and_target_update_period=2, tau=0.005, qf_criterion=None, optimizer_class=optim.Adam, **kwarg...
def test_meta_post_init(synthetic_continuous_bandit_feedback: BanditFeedback) -> None: ope_ = ContinuousOffPolicyEvaluation(bandit_feedback=synthetic_continuous_bandit_feedback, ope_estimators=[ipw, ipw2]) assert (ope_.ope_estimators_ == {'ipw': ipw2}), '__post_init__ returns a wrong value' ope_ = Continuou...
def add_mim_extension(): if ('develop' in sys.argv): if (platform.system() == 'Windows'): mode = 'copy' else: mode = 'symlink' elif (('sdist' in sys.argv) or ('bdist_wheel' in sys.argv) or (platform.system() == 'Windows')): mode = 'copy' else: return ...
def abs_rel_metric(data_dict: dict, roi=None, max_distance=None): depth_prediction = data_dict['result'] depth_gt = data_dict['target'] (depth_prediction, depth_gt) = preprocess_roi(depth_prediction, depth_gt, roi) (depth_prediction, depth_gt) = get_positive_depth(depth_prediction, depth_gt) (depth_...
def semantic_attrs(attrs): whitelist = ['aria', 'tooltip', 'placeholder', 'label', 'title', 'name'] attrs = [value for (key, value) in attrs.items() if any(((k in key.lower()) for k in whitelist))] return ' '.join(attrs)
def run(image, heatmap_body, pose): heatmap_body = np.transpose(heatmap_body, (1, 2, 0)) bbox = same_margin_bounding_box(pose, model_type, model_['marginBox']) channel_ind = np.fromiter(model_['indexHM'], dtype=np.int) cropped_heatmap = crop_input(heatmap_body, bbox, model_['square'], model_['pad'], mod...
def map_checkpoint_to_state_dict(state_dict: Dict[(str, np.ndarray)]): d = {} for (full_s, v) in state_dict.items(): split = full_s.split('/') new = [] for (i, s) in enumerate(split): if (s == 'Transformer'): pass elif (m := re.match('encoderblock_...
class RobertaEmbeddings(BertEmbeddings): def __init__(self, config): super().__init__(config) self.padding_idx = 1 self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=self.padding_idx) self.position_embeddings = nn.Embedding(config.max_position_embe...
def test_argmin_argmax(): array = ak.highlevel.Array([[[np.datetime64('2022'), np.datetime64('2023'), np.datetime64('2025')], [], [np.datetime64('2027'), np.datetime64('2011')], [np.datetime64('2013')]], [], [[np.datetime64('2017'), np.datetime64('2019')], [np.datetime64('2023')]]], check_valid=True) assert (to...
class MinLengthLogitsProcessor(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def _make_dmc(obs_type, domain, task, frame_stack, action_repeat, seed, task_kwargs=None): visualize_reward = False if (task_kwargs is None): task_kwargs = {} task_kwargs['random'] = seed env = cdmc.make(domain, task, task_kwargs=task_kwargs, environment_kwargs=dict(flat_observation=True), visua...
class LabelledOrderedTrees(UniqueRepresentation, Parent): def __init__(self, category=None): if (category is None): category = Sets() Parent.__init__(self, category=category) def _repr_(self): return 'Labelled ordered trees' def cardinality(self): return Infinity ...
class StructureFormat(StructuredVoidFormat): def __init__(self, *args, **kwargs): warnings.warn('StructureFormat has been replaced by StructuredVoidFormat', DeprecationWarning, stacklevel=2) super(StructureFormat, self).__init__(*args, **kwargs)
def to_expression_or_string(string_expr: str) -> Any: try: return ast.literal_eval(string_expr) except ValueError: return string_expr
class ClassScope(Scope): def __init__(self, name, outer_scope): Scope.__init__(self, name, outer_scope, outer_scope) self.class_name = name self.doc = None def lookup(self, name): entry = Scope.lookup(self, name) if entry: return entry if (name == 'cla...
class Rouge(Rouge155): DEFAULT_OPTIONS = ['-a', '-n', 4, '-x', '-2', 4, '-u', '-c', 95, '-r', 1000, '-f', 'A', '-p', 0.5, '-t', 0, '-d'] def __init__(self, n_words=None, keep_files=False, options=None): if (options is None): self.options = self.DEFAULT_OPTIONS.copy() else: ...
class LightPoleCartPole(ModifiableCartPoleEnv): def __init__(self): super(LightPoleCartPole, self).__init__() self.masspole = self.EXTREME_LOWER_MASSPOLE self._followup() def parameters(self): parameters = super(LightPoleCartPole, self).parameters parameters.update({'mass...
def boardd_loop(rate=200): rk = Ratekeeper(rate) context = zmq.Context() can_init() logcan = messaging.pub_sock(context, service_list['can'].port) health_sock = messaging.pub_sock(context, service_list['health'].port) sendcan = messaging.sub_sock(context, service_list['sendcan'].port) while ...
class TestUniformRandomWalk(object): def test_parameter_checking(self): g = create_test_graph() urw = UniformRandomWalk(g) nodes = ['0'] n = 1 length = 2 seed = None with pytest.raises(ValueError): urw.run(nodes=None, n=n, length=length, seed=seed)...
def _get_global_header(im, info): version = b'87a' for extensionKey in ['transparency', 'duration', 'loop', 'comment']: if (info and (extensionKey in info)): if (((extensionKey == 'duration') and (info[extensionKey] == 0)) or ((extensionKey == 'comment') and (not (1 <= len(info[extensionKey]...
def timing(f): (f) def wrap(*args, **kw): if is_master(): ts = time.time() result = f(*args, **kw) te = time.time() mprint('func:{!r} took: {:2.4f} sec'.format(f.__name__, (te - ts))) else: result = f(*args, **kw) return result ...
def do_vcs_install(versionfile_source, ipy): GITS = ['git'] if (sys.platform == 'win32'): GITS = ['git.cmd', 'git.exe'] files = [versionfile_source] if ipy: files.append(ipy) try: my_path = __file__ if (my_path.endswith('.pyc') or my_path.endswith('.pyo')): ...
class BCELossWithQuant(nn.Module): def __init__(self, codebook_weight=1.0): super().__init__() self.codebook_weight = codebook_weight def forward(self, qloss, target, prediction, split): bce_loss = F.binary_cross_entropy_with_logits(prediction, target) loss = (bce_loss + (self.co...
class SawyerFaucetOpenEnvV2(SawyerXYZEnv): def __init__(self): hand_low = ((- 0.5), 0.4, (- 0.15)) hand_high = (0.5, 1, 0.5) obj_low = ((- 0.05), 0.8, 0.0) obj_high = (0.05, 0.85, 0.0) super().__init__(self.model_name, hand_low=hand_low, hand_high=hand_high) self.init...
def _build_tree(paths): assert all(((cp[(- 1)] == paths[0][(- 1)]) for cp in paths)) g = nx.DiGraph() node_set = {y for x in paths for y in x} g.add_nodes_from(node_set) for cp in paths: for ce in zip(cp[0:(- 1)], cp[1:]): g.add_edge(ce[1], ce[0]) root = paths[0][(- 1)] _...
class Logger(object): def __init__(self, log_dir: str): self.writer = tf.compat.v1.summary.FileWriter(log_dir) def scalar_summary(self, tag: str, value: float, step: int): summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)]) self.writer.add_summary(summary, step) ...
def get_dispatch_callee(declaration): if is_tensor_method(declaration): return 'self.{}'.format(declaration['name']) elif is_torch_function(declaration): namespace = function_namespace(declaration) return '{}::{}'.format(namespace, declaration['name']) else: raise RuntimeErro...
class VGGLoss(nn.Module): def __init__(self): super(VGGLoss, self).__init__() self.vgg = VGG19() self.vgg.eval() util.set_requires_grad(self.vgg, False) self.criterion = nn.L1Loss() self.weights = [(1.0 / 32), (1.0 / 16), (1.0 / 8), (1.0 / 4), 1.0] def forward(sel...
def print_and_export_results(results: dict, method: str): print('\n ') print(' Results summary ') print(' ') print(f" average image rocauc: {results['average image rocauc']:.2f} ") print(f" average pixel rocauc: {results['average pixel rocauc']:.2f} ") print(' \n') ...
class MaskedLossWrapper(nn.Module): def __init__(self, loss_fn, device): super().__init__() self.loss_fn = loss_fn self.device = device def _get_mask(self, targets): mask = torch.ones(targets.shape) mask[(targets == UNCERTAIN)] = 0 mask[(targets == MISSING)] = 0 ...