code
stringlengths
101
5.91M
def load_wav_to_torch(full_path): (sampling_rate, data) = read(full_path) return (torch.FloatTensor(data.astype(np.float32)), sampling_rate)
def calculate_metrics(threshold, dist, actual_issame): predict_issame = np.less(dist, threshold) true_positives = np.sum(np.logical_and(predict_issame, actual_issame)) false_positives = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame))) true_negatives = np.sum(np.logical_and(np.logica...
def query_on_voxel(query, feature, min_, max_, use_ste=False, boundary_check=False, ctx=None): func = LanczosQueryOnVoxel(ctx, min_, max_, use_ste, boundary_check) return func(query, feature)
def _simplify_cells(d): for key in d: if isinstance(d[key], mat_struct): d[key] = _matstruct_to_dict(d[key]) elif _has_struct(d[key]): d[key] = _inspect_cell_array(d[key]) return d
def decompress(data_blocks): d = zlib.decompressobj() for data in data_blocks: (yield bytearray(d.decompress(data))) (yield bytearray(d.flush()))
class TwistedAffineIndices(UniqueRepresentation, Set_generic): def __classcall_private__(cls, cartan_type): cartan_type = CartanType(cartan_type) if ((not cartan_type.is_affine()) or cartan_type.is_untwisted_affine()): raise ValueError('the Cartan type must be a twisted affine type') ...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM) self.relu = nn.ReLU() self.co...
def variation_of_information(image0=None, image1=None, *, table=None, ignore_labels=()): (h0g1, h1g0) = _vi_tables(image0, image1, table=table, ignore_labels=ignore_labels) return np.array([h1g0.sum(), h0g1.sum()])
(Output('female-corpus-stats', 'children'), [Input('topic-data', 'data'), Input('date-dropdown', 'value')]) def display_female_corpus_stats(data, date_val): female_corpus_size = data['params']['femaleDominantArticleCount'] display_text = f''' In {num2str_month(date_val)}, there were {female_corpus_size:...
class ArchGenerate(BaseArchGenerate): def __init__(self, super_network, config): super(ArchGenerate, self).__init__(super_network, config) def derive_archs(self, betas, head_alphas, stack_alphas, if_display=True): self.update_arch_params(betas, head_alphas, stack_alphas) derived_archs = ...
class rel_pyramid_module(nn.Module): def __init__(self, num_backbone_stages): super().__init__() fpn_dim = cfg.FPN.DIM self.num_backbone_stages = num_backbone_stages self.prd_conv_lateral = nn.ModuleList() for i in range(self.num_backbone_stages): if cfg.FPN.USE_G...
class CountingIterator(object): def __init__(self, iterable, start=None, total=None): self.iterable = iterable self.itr = iter(self) if (start is None): self.n = getattr(iterable, 'n', 0) else: self.n = start if (total is None): self.total ...
class InterpretCompilerDirectives(CythonTransform): unop_method_nodes = {'typeof': ExprNodes.TypeofNode, 'operator.address': ExprNodes.AmpersandNode, 'operator.dereference': ExprNodes.DereferenceNode, 'operator.preincrement': ExprNodes.inc_dec_constructor(True, '++'), 'operator.predecrement': ExprNodes.inc_dec_cons...
class LinearGRP(T.nn.Linear): def __init__(self, in_features: int, out_features: int, bias: bool=True, device=None, dtype=None, proj_dim_ratio: Optional[float]=None, proj_dim: Optional[int]=None, proj_dim_min: Optional[int]=None, proj_dim_max: Optional[int]=None, matmul: MatMulType='gaussian', generator: Optional[T...
class InstallWithExtras(install): def run(self) -> None: super().run() build_ext_obj = self.distribution.get_command_obj('build_ext') build_dir = Path(self.distribution.get_command_obj('build_ext').build_temp) self.copy_file(find_symengine_wrapper(build_dir, build_ext_obj.get_ext_fil...
def test_clean_remove_stopwords(df_text: pd.DataFrame) -> None: pipeline = [{'operator': 'remove_stopwords'}] df_clean = clean_text(df_text, 'text', pipeline=pipeline) df_check = df_text.copy() df_check['text'] = ["'ZZZZZ!' IMDb would allow one-word reviews, that's mine would be.", 'cast played Shakespe...
def get_setup_nets(key, steps_or_nets, target): init_net = core.Net((key + '/init')) exit_net = core.Net((key + '/exit')) init_nets = [] exit_nets = [] objs = [] for step_or_net in steps_or_nets: if hasattr(step_or_net, 'get_all_attributes'): objs += step_or_net.get_all_attri...
class WFRadiationMeshSliceMax(RadiationField): glossary_name = 'params/Mesh/sliceMax' def __init__(self, wf): super(WFRadiationMeshSliceMax, self).__init__(wf) self.attributes.update({'limits': '[1:LONG_MAX]', 'alias': 'mesh.eStart'}) def value(self): return self._wf._srwl_wf.mesh.eF...
class GiniIndex(BaseMetric): def __init__(self, recommendations, config, params, eval_objects): super().__init__(recommendations, config, params, eval_objects) self._cutoff = self._evaluation_objects.cutoff self._num_items = self._evaluation_objects.num_items self._item_count = {} ...
def ia_minus_iadag_sparse(dimension: int, prefactor: Union[(float, complex, None)]=None) -> csc_matrix: prefactor = (prefactor if (prefactor is not None) else 1.0) return (prefactor * ((1j * annihilation_sparse(dimension)) - (1j * creation_sparse(dimension))))
def convert_element_list(monitor_descriptions: List[MonitorDescription]) -> MonitorDescriptionList: monitor_dict = {} for m in monitor_descriptions: if (m.joiner_id in monitor_dict): m_joined = monitor_dict[m.joiner_id] if (not (m.monitor_type == m_joined.monitor_type)): ...
class VGG(nn.Module): def __init__(self, features, num_classes=1000, init_weights=True): super(VGG, self).__init__() self.features = features self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) self.classifier = nn.Sequential(nn.Linear(((512 * 7) * 7), 4096), nn.ReLU(True), nn.Dropout(), nn....
def mask_and_save_to_dicom(dcm_path, args, filename): dicom = Dicom(dcm_path) metadata = dicom.metadata() included_path = os.path.join(args.savepath, 'included') excluded_path = os.path.join(args.savepath, 'excluded') filename = number_image(filename, metadata['patient_name']) outpath = os.path....
class Algorithm(metaclass=ABCMeta): def run_classification(x, y, epsilon, delta, lambda_param, learning_rate, num_iters): return NotImplemented def name(self): return NotImplemented
class ExcludeFeatures(): def __init__(self, feature_names): self.feature_names = feature_names def __call__(self, inputs): outputs = dict(((k, inputs[k]) for k in inputs if (k not in self.feature_names))) return outputs
def register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeAccessor > const &', 'arg0')]) cls.add_method('Delete', 'void', [param('ns3::AttributeAccessor *', 'object')], is_static=True) return
def cal_rouge(evaluated_ngrams, reference_ngrams): reference_count = len(reference_ngrams) evaluated_count = len(evaluated_ngrams) overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams) overlapping_count = len(overlapping_ngrams) if (evaluated_count == 0): precision = 0.0 e...
def down_sample(x, scale_factor_h, scale_factor_w): (_, h, w, _) = x.get_shape().as_list() new_size = [(h // scale_factor_h), (w // scale_factor_w)] return tf.image.resize_nearest_neighbor(x, size=new_size)
class TwitterProcessor(QueryNERProcessor): def get_labels(self): return ['PER', 'LOC', 'ORG', 'O']
class PositionWiseFeedForwardNet(nn.Module): def __init__(self, d_model: int=512, d_ff: int=2048, dropout_p: float=0.3, ffnet_style: str='ff') -> None: super(PositionWiseFeedForwardNet, self).__init__() self.ffnet_style = ffnet_style.lower() if (self.ffnet_style == 'ff'): self.fe...
class BDFuncType(Enum): UNKNOWN = (- 1) CONV_NEURON = 0 DEPTHWISE_OR_POOLING = 1 FC = 2 TENSOR_ARITHMETIC = 3 FC2 = 4 CONV_CORRELATION = 5 TABLE_LOOKUP = 6 MD_SUM = 7 MD_SCALAR = 8 MD_SFU = 9 MD_LINEAR = 10 LOCALMEM_ARANGE = 11 DECOMPRESS = 12 MD_CMP = 13 ...
def _parse_inputs(actual: Any, expected: Any, *, allow_subclasses: bool) -> Tuple[(Optional[_TestingErrorMeta], Optional[Union[(_TensorPair, List, Dict)]])]: error_meta: Optional[_TestingErrorMeta] if (isinstance(actual, collections.abc.Sequence) and (not isinstance(actual, str)) and isinstance(expected, collec...
def add_code_sample_docstrings(*docstr, processor_class=None, checkpoint=None, output_type=None, config_class=None, mask='[MASK]', qa_target_start_index=14, qa_target_end_index=15, model_cls=None, modality=None, expected_output=None, expected_loss=None, real_checkpoint=None): def docstring_decorator(fn): mo...
class TSTestDataset(Dataset): def __init__(self, x): self.x = x def __len__(self): return len(self.x) def __getitem__(self, idx): return self.x[idx]
class ModularPolynomialDatabase(): def _dbpath(self, level): return ('PolMod/%s/pol.%03d.dbz' % (self.model, level)) def __repr__(self): if self.model.startswith('Cls'): head = 'Classical' elif self.model.startswith('Atk'): head = 'Atkin' elif self.model.s...
def phi_square_calc(chi_square, POP): try: return (chi_square / POP) except Exception: return 'None'
def _to_polynomials(lf, R): n = max((max((part[0] for part in f.support() if part), default=0) for f in lf)) n = max(n, 1) P = PolynomialRing(R, [('v%s' % a) for a in range(1, (n + 1))]) if (n == 1): return [P({part.to_exp(n)[0]: c for (part, c) in f}) for f in lf] return [P({tuple(part.to_e...
class DefaultProcessingUnitConfig(dict, ProcessingUnitConfig): def unit_name(self): return self['unit_name'] def set_unit_name(self, value): self['unit_name'] = value def to_dict(self): return self def from_dict(cls, obj_dict): return cls(obj_dict)
.parametrize('param_distributions, expected_n_candidates', [({'a': [1, 2]}, 2), ({'a': randint(1, 3)}, 10)]) def test_random_search_discrete_distributions(param_distributions, expected_n_candidates): n_samples = 1024 (X, y) = make_classification(n_samples=n_samples, random_state=0) base_estimator = FastClas...
def mock_latex_file(): with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.tex') as f: latex_str = f'\documentclass{{article}}egin{{document}}{plain_text_str}\end{{document}}' f.write(latex_str) return f.name
_model def regnetx_040(pretrained=False, **kwargs): return _regnet('regnetx_040', pretrained, **kwargs)
class AlgebraMorphism(ModuleMorphismByLinearity): def __init__(self, domain, on_generators, position=0, codomain=None, category=None, anti=False): assert (position == 0) assert (codomain is not None) if (category is None): if anti: category = ModulesWithBasis(doma...
class Seq2SeqModelCaffe2(object): def _build_model(self, init_params): model = Seq2SeqModelHelper(init_params=init_params) self._build_shared(model) self._build_embeddings(model) forward_model = Seq2SeqModelHelper(init_params=init_params) self._build_shared(forward_model) ...
class FromTableauIsomorphism(Morphism): def _repr_type(self): return 'Crystal Isomorphism' def __invert__(self): return FromRCIsomorphism(Hom(self.codomain(), self.domain())) def _call_(self, x): conj = x.to_tableau().conjugate() ct = self.domain().cartan_type() act =...
def parse_args(): parser = argparse.ArgumentParser(description='Script that retags a tree file') parser.add_argument('--lang', default='vi', type=str, help='Language') parser.add_argument('--input_file', default='data/constituency/vi_vlsp21_train.mrg', help='File to retag') parser.add_argument('--output...
def test_object(): image = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool) e...
def register_Ns3RvBatteryModelHelper_methods(root_module, cls): cls.add_constructor([param('ns3::RvBatteryModelHelper const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_virtual=True) cls.add_method('DoIn...
def set_principled_node(principled_node: bpy.types.Node, base_color: Tuple[(float, float, float, float)]=(0.6, 0.6, 0.6, 1.0), subsurface: float=0.0, subsurface_color: Tuple[(float, float, float, float)]=(0.8, 0.8, 0.8, 1.0), subsurface_radius: Tuple[(float, float, float)]=(1.0, 0.2, 0.1), metallic: float=0.0, specular...
class EchoingStdin(object): def __init__(self, input, output): self._input = input self._output = output def __getattr__(self, x): return getattr(self._input, x) def _echo(self, rv): self._output.write(rv) return rv def read(self, n=(- 1)): return self._ec...
def from_path(path: PathLike, *, app: Any=None, base_url: (str | None)=None, data_generation_methods: DataGenerationMethodInput=DEFAULT_DATA_GENERATION_METHODS, code_sample_style: str=CodeSampleStyle.default().name, rate_limit: (str | None)=None, encoding: str='utf8', sanitize_output: bool=True) -> GraphQLSchema: w...
def setup(with_data=False): if (not os.path.exists(TEST_PATH)): os.mkdir(TEST_PATH) if with_data: with_data_path = (lambda f: os.path.join(DATA_DIR, f)) with_test_path = (lambda f: os.path.join(TEST_PATH, f)) copy_file = (lambda f: shutil.copy(with_data_path(f), with_test_path(f)...
def report_errors(dataset, result_file): df = pd.read_csv(((RESULT_ROOT / dataset) / result_file)) evaluate_errors(df['error'])
class ConsumedResource(Resource): def update_agent_infos(self, state_infos, agent_infos): super().update_agent_infos(state_infos, agent_infos) if (self._reward_this_step > 0): return agent_infos['inventory'][self._resource_name] = 0
def ocp_mixed(F, bcs_m, J_m, state_m, controls, adjoint_m, config_picard): return cashocs.OptimalControlProblem(F, bcs_m, J_m, state_m, controls, adjoint_m, config=config_picard)
class ContrastMemory(nn.Module): def __init__(self, inputSize, outputSize, K, T=0.07, momentum=0.5): super(ContrastMemory, self).__init__() self.nLem = outputSize self.unigrams = torch.ones(self.nLem) self.multinomial = AliasMethod(self.unigrams) self.multinomial.cuda() ...
def _reduced_texutalization_method(expr, entity_label_map): textual_form = textualize_s_expr(expr) toks = textual_form.split(' ') norm_toks = [] for t in toks: if t.startswith('m.'): if (t in entity_label_map): t = entity_label_map[t] else: ...
class Indices2Dataset(Dataset): def __init__(self, dataset): self.dataset = dataset self.indices = None def load(self, indices: list): self.indices = indices def __getitem__(self, idx): idx = self.indices[idx] (image, label) = self.dataset[idx] return (image, ...
def get_prefix(sentence, prefix_len): tokens = sentence.strip('\n').split() if (prefix_len >= len(tokens)): return sentence.strip('\n') else: return ' '.join(tokens[:prefix_len])
class FiniteField_prime_modn(FiniteField_generic, integer_mod_ring.IntegerModRing_generic): def __init__(self, p, check=True, modulus=None): p = Integer(p) if (check and (not p.is_prime())): raise ArithmeticError('p must be prime') self.__char = p integer_mod_ring.Integer...
class AverageMeter(): def __init__(self, last_n=None): self._records = [] self.last_n = last_n def update(self, result): if isinstance(result, (list, tuple)): self._records += result else: self._records.append(result) def reset(self): self._rec...
def test_execute_filter_endpoint(app, schema_url): schema = oas_loaders.from_uri(schema_url, endpoint=['success']) execute(schema) assert_incoming_requests_num(app, 1) assert_request(app, 0, 'GET', '/api/success') assert_not_request(app, 'GET', '/api/failure')
def test_unbounded_state(cl): input = NamedVideoStream(cl, 'test1') frame = cl.io.Input([input]) slice_frame = cl.streams.Slice(frame, partitions=[cl.partitioner.all(50)]) increment = cl.ops.TestIncrementUnbounded(ignore=slice_frame) unsliced_increment = cl.streams.Unslice(increment) output = Na...
def b_cubed(clusters, mention_to_gold): (num, dem) = (0, 0) for c in clusters: if (len(c) == 1): continue gold_counts = Counter() correct = 0 for m in c: if (m in mention_to_gold): gold_counts[tuple(mention_to_gold[m])] += 1 for (c2...
def load_sqls(in_json, normalize_variables): def fill_in_variables(s, s_vars, variables): var_list = {} for (v_key, v_val) in s_vars.items(): if (len(v_val) == 0): for var in variables: if (var['name'] == v_key): v_val = var['ex...
def make_dense(targets, noclass): with tf.device('/cpu:0'): shape = tf.shape(targets) batch_size = shape[0] indices = (targets + (noclass * tf.range(0, batch_size))) length = tf.expand_dims((batch_size * noclass), 0) dense = tf.sparse_to_dense(indices, length, 1.0, 0.0) r...
def get_training_stats(stats): if (('nll_loss' in stats) and ('ppl' not in stats)): stats['ppl'] = utils.get_perplexity(stats['nll_loss']) stats['wall'] = round(metrics.get_meter('default', 'wall').elapsed_time, 0) return stats
def printTensor(dataTable, message='', nPrintedRows=0, nPrintedCols=0, interval=10): dims = dataTable.getDimensions() nRows = int(dims[0]) if (nPrintedRows != 0): nPrintedRows = min(nRows, nPrintedRows) else: nPrintedRows = nRows block = SubtensorDescriptor() dataTable.getSubtens...
.parametrize('ctx', ctx_list) .parametrize('seed', [313]) .parametrize('window_size, stride, fft_size', [(16, 2, 16), (16, 4, 16), (16, 8, 32)]) .parametrize('window_type', ['hanning', 'hamming', 'rectangular']) .parametrize('center', [True, False]) .parametrize('pad_mode', ['reflect', 'constant']) .parametrize('as_ist...
def scatter(tensor, **kwargs): assert (torch.distributed.deprecated._initialized == _INITIALIZED_PG), 'collective only supported in process-group mode' my_rank = get_rank() src = kwargs.pop('src', my_rank) scatter_list = kwargs.pop('scatter_list', None) _group = kwargs.pop('group', group.WORLD) ...
def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, args) -> Tuple[(torch.Tensor, torch.Tensor)]: if (tokenizer.mask_token is None): raise ValueError('This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the --mlm flag if you want to use this to...
def read_mk(fobj, start_length, size): start = start_length[0] fobj.seek(start) pixel_size = ((size[0] * size[2]), (size[1] * size[2])) sizesq = (pixel_size[0] * pixel_size[1]) band = Image.frombuffer('L', pixel_size, fobj.read(sizesq), 'raw', 'L', 0, 1) return {'A': band}
def batch_data_test(cfg, data, device='cuda'): batch = {} roi_keys = ['im_H', 'im_W', 'roi_img', 'inst_id', 'roi_coord_2d', 'roi_cls', 'score', 'roi_extent', 'bbox', 'bbox_est', 'bbox_mode', 'roi_wh', 'scale', 'resize_ratio'] for key in roi_keys: if (key in ['roi_cls']): dtype = torch.lo...
def convert_ndarray(x): y = list(range(len(x))) for (k, v) in x.items(): y[int(k)] = v return np.array(y)
def init_array(A, B, C, D, G): ni = NI.get() nj = NJ.get() nk = NK.get() nl = NL.get() nm = NM.get() for i in range(ni): for j in range(nk): A[(i, j)] = (datatype((((i * j) + 1) % ni)) / (5 * ni)) for i in range(nk): for j in range(nj): B[(i, j)] = (da...
class TensorDataset(Dataset): def __init__(self, *tensors): assert all(((tensors[0].size(0) == tensor.size(0)) for tensor in tensors)) self.tensors = tensors def __getitem__(self, index): return tuple((tensor[index] for tensor in self.tensors)) def __len__(self): return self....
def parse_opt(): parser = argparse.ArgumentParser() parser.add_argument('--input_json', type=str, default='data/coco.json', help='path to the json file containing additional info and vocab') parser.add_argument('--input_fc_h5', type=str, default='data/coco_ai_challenger_talk_fc.h5', help='path to the direct...
def log_2items_per_user(spark): date = datetime(2019, 1, 1) return spark.createDataFrame(data=[[0, 0, date, 1.0], [0, 1, date, 1.0], [1, 0, date, 1.0], [1, 1, date, 1.0], [2, 2, date, 1.0], [2, 3, date, 1.0]], schema=INTERACTIONS_SCHEMA)
def double_linear_logits(args, size, bias, bias_start=0.0, scope=None, mask=None, wd=0.0, input_keep_prob=1.0, is_train=None): with tf.variable_scope((scope or 'Double_Linear_Logits')): first = tf.tanh(linear(args, size, bias, bias_start=bias_start, scope='first', wd=wd, input_keep_prob=input_keep_prob, is_...
def synchronized(func): (func) def wrapper(*args, **kwargs): with _module_lock: return func(*args, **kwargs) return wrapper
def test_constructor_statement_clone(default_test_case, constructor_mock): int_prim = st.IntPrimitiveStatement(default_test_case, 5) method_stmt = st.ConstructorStatement(default_test_case, constructor_mock, {'y': int_prim.ret_val}) default_test_case.add_statement(int_prim) default_test_case.add_stateme...
class ReportBuilderBase(): def __init__(self, file=None): database_file = (file if (file is not None) else ':memory:') self._connection = sqlite3.connect(database_file) self._create_report_tables() def process_tracker(self, tracker): tracker.populate_report(self) return s...
def main(): (args, cfg) = parse_config() logger = common_utils.create_logger() logger.info('Quick Demo') (train_set, train_loader, train_sampler) = build_dataloader(dataset_cfg=cfg.DATA_CONFIG, class_names=cfg.CLASS_NAMES, batch_size=1, dist=False, workers=0, logger=logger, training=True, merge_all_iter...
def inception_block_2b(X): X_3x3 = fr_utils.conv2d_bn(X, layer='inception_4e_3x3', cv1_out=160, cv1_filter=(1, 1), cv2_out=256, cv2_filter=(3, 3), cv2_strides=(2, 2), padding=(1, 1)) X_5x5 = fr_utils.conv2d_bn(X, layer='inception_4e_5x5', cv1_out=64, cv1_filter=(1, 1), cv2_out=128, cv2_filter=(5, 5), cv2_stride...
class Decoder_64(nn.Module): def __init__(self, img_size=64, latent_dim=10, noise_dim=100): super(Decoder_64, self).__init__() in_channels = (latent_dim + noise_dim) self.linear = snlinear(in_features=in_channels, out_features=512) self.deconv1 = snconvTrans2d(in_channels=512, out_ch...
class TestGeneralController(testing_utils.TestCase): def setUp(self): super(TestGeneralController, self).setUp() self.session = tf.Session() (self.model_space, _) = testing_utils.get_example_conv1d_space() self.controller = architect.GeneralController(model_space=self.model_space, bu...
def test_RecordArray(): array = ak.highlevel.Array([{'x': 0.0, 'y': []}, {'x': 8.0, 'y': [1]}, {'x': 2.2, 'y': [2, 2]}, {'x': 3.3, 'y': [3, 1, 3]}, {'x': 4.4, 'y': [4, 1, 1, 4]}, {'x': 5.5, 'y': [5, 4, 5]}, {'x': 1.1, 'y': [6, 1]}, {'x': 7.7, 'y': [7]}, {'x': 10.0, 'y': [99]}]) assert (ak._do.is_unique(array.la...
def numpy_azimint_hist(data, radius, npt): histu = np.histogram(radius, npt)[0] histw = np.histogram(radius, npt, weights=data)[0] return (histw / histu)
class Config(BaseConfig): numPeriods: int = 60 tstep: int = 5 elasmu: float = 1.45 prstp: float = 0.015 gama: float = 0.3 pop0: float = 6838 popadj: float = 0.134 popasym: float = 10500 dk: float = 0.1 q0: float = 63.69 k0: float = 135 a0: float = 3.8 ga0: float = 0.0...
_SEG_HEADS_REGISTRY.register() class BasePixelDecoder(nn.Module): def __init__(self, input_shape: Dict[(str, ShapeSpec)], *, conv_dim: int, mask_dim: int, norm: Optional[Union[(str, Callable)]]=None): super().__init__() input_shape = sorted(input_shape.items(), key=(lambda x: x[1].stride)) s...
def create_units(fst_dir: Path, in_labels: str, vocab: Dictionary) -> Path: in_units_file = (fst_dir / f'kaldi_dict.{in_labels}.txt') if (not in_units_file.exists()): logger.info(f'Creating {in_units_file}') with open(in_units_file, 'w') as f: print('<eps> 0', file=f) i =...
def split(s, splitter, reg=False): if (not reg): return s.split(splitter) import re return re.split(splitter, s)
class DlaRoot(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, residual): super(DlaRoot, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, 1, stride=1, bias=False, padding=((kernel_size - 1) // 2)) self.bn = nn.BatchNorm2d(out_channels) self.relu...
def convert_file_if_needed(file, debug): if file.endswith('.sgm'): return sgm2raw(file, debug) elif file.endswith('.tmx'): return tmx2raw(file, debug) elif file.endswith('wiki/fi-en/titles.fi-en'): return cut_wikitles(file, debug) elif file.endswith('.tsv'): return cut_ts...
class GaussianMLPTwoHeadedModuleEx(GaussianMLPTwoHeadedModule, ForwardWithTransformTrait, ForwardWithChunksTrait, ForwardModeTrait): pass
def i_take_set(s: set) -> str: if (len(s) > 0): return 'not empty!' else: return 'empty!'
def _find_loop_nest_roots(loop_nest_tree: Dict[(SDFGState, Set[SDFGState])]) -> Set[SDFGState]: all_nodes = set() child_nodes = set() for (parent, children) in loop_nest_tree.items(): all_nodes.add(parent) all_nodes.update(children) child_nodes.update(children) roots = (all_nodes...
class runtime_validation_disabled(object): prev: bool def __init__(self) -> None: global _runtime_validation_enabled self.prev = _runtime_validation_enabled _runtime_validation_enabled = False def __enter__(self) -> None: pass def __exit__(self, exc_type: Any, exc_value: ...
def scalar_imp_test(listener=False): data = [('blue', (240.0, 100.0, 100.0)), ('blue', (180.0, 100.0, 100.0)), ('teal', (240.0, 100.0, 100.0)), ('teal', (180.0, 100.0, 100.0))] return pairs_to_insts(data, listener=listener)
def create_f0_hparams(hparams_string=None, verbose=False): hparams = tf.contrib.training.HParams(type=3, layers=3, blocks=2, dilation_channels=130, residual_channels=130, skip_channels=240, input_channel=60, condition_channel=1126, cgm_factor=4, initial_kernel=10, kernel_size=2, bias=True) if hparams_string: ...
class RegularPartitions_all(RegularPartitions): def __init__(self, ell): RegularPartitions.__init__(self, ell, bool((ell > 1))) def _repr_(self): return '{}-Regular Partitions'.format(self._ell) def __iter__(self): if (self._ell == 1): (yield self.element_class(self, []))...