code stringlengths 101 5.91M |
|---|
class Grassberger(EntropyEstimator):
def g_series():
GG = {}
gamma0 = ndd.fnsb.gamma0
log_two = numpy.log(2.0)
def gterm(n):
if (n in GG):
return GG[n]
if (n <= 2):
if (n < 1):
value = 0.0
eli... |
class ActuatedDampedPendulum(ActuatedSimplePendulum):
def __init__(self, params=None):
if (params is None):
params = torch.abs(torch.randn(4))
super().__init__(params=params[:3])
self._visc_force = ViscousJointDampingForce(params[(- 1)].reshape(1, self._qdim))
self._gener... |
class Vocab(object):
def __init__(self):
self._count_dict = dict()
self._predefined_list = [PAD, UNK, ASPECT]
def add(self, word):
if (word in self._count_dict):
self._count_dict[word] += 1
else:
self._count_dict[word] = 1
def add_list(self, words):
... |
def test_single_objective_max_loss_negative():
with pytest.raises(ValueError):
SingleObjectiveCDV(max_empirical_loss=max_empirical_loss_neg) |
class Model(torch.nn.Module):
def __init__(self, backbone):
super(Model, self).__init__()
module_list = list(backbone.children())
self.conv_net = torch.nn.Sequential(*module_list[:(- 1)])
def forward(self, x):
x = self.conv_net(x)
x = torch.flatten(x, 1)
return x |
def expand_scalar(x, shp):
if np.isscalar(x):
x *= np.ones(shp)
else:
assert (x.shape == shp)
return x |
def remove_explain_phase(settings: hypothesis.settings) -> hypothesis.settings:
if (Phase.explain in settings.phases):
phases = tuple((phase for phase in settings.phases if (phase != Phase.explain)))
return hypothesis.settings(settings, phases=phases)
return settings |
class ContextualAttentionModule(nn.Module):
def __init__(self, unfold_raw_kernel_size=4, unfold_raw_stride=2, unfold_raw_padding=1, unfold_corr_kernel_size=3, unfold_corr_stride=1, unfold_corr_dilation=1, unfold_corr_padding=1, scale=0.5, fuse_kernel_size=3, softmax_scale=10, return_attention_score=True):
s... |
class FlaxBigBirdForSequenceClassification(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def AG(n, q, x=None):
if (x is None):
x = 'x'
F = GF(q, x)
P = ProjectiveSpace(n, F)
A = Matrix(F, [list(p) for p in P if (not (list(p)[0] == 0))]).transpose()
M = Matroid(A)
M.rename(((((('AG(' + str(n)) + ', ') + str(q)) + '): ') + repr(M)))
return M |
def find_representative(m):
target_class = None
if hasattr(m, 'REPRESENTATIVE'):
target_class = getattr(m, 'REPRESENTATIVE')
else:
for (name, obj) in inspect.getmembers(m):
if inspect.isclass(obj):
target_class = getattr(m, name)
break
return t... |
def write_rd_page(f, is_64, is_replay):
if is_64:
bytes = bytearray([15, 5, 195])
else:
bytes = bytearray([205, 128, 195])
nocall_bytes = bytearray([49, 192, 195])
f.write(bytes)
f.write(bytes)
f.write(bytes)
if is_replay:
f.write(bytes)
else:
f.write(noca... |
def video_list_from_file(video_list_fpath: str, base_path: Optional[str]=None):
video_list = []
with PathManager.open(video_list_fpath, 'r') as io:
for line in io:
video_list.append(maybe_prepend_base_path(base_path, str(line.strip())))
return video_list |
def interaction_information(ar, ks=None, estimator='nsb', axis=0, r=None):
def iinfo(X, ks, estimator):
info = 0.0
S = len(X)
for T in range(1, (S + 1)):
sgn = ((- 1) ** (S - T))
info += (sgn * sum(from_data(X, ks=ks, estimator=estimator, r=T)))
return (- info... |
def test_hash_same(default_test_case, variable_reference_mock, field_mock):
statement = stmt.FieldStatement(default_test_case, field_mock, variable_reference_mock)
statement2 = stmt.FieldStatement(default_test_case, field_mock, variable_reference_mock)
memo = {variable_reference_mock: 0, statement.ret_val: ... |
class ScalarNoiseModel(NoiseModel):
def whiten_scalar(self, x: sf.Scalar, bounded_away_from_zero: bool=False) -> sf.Scalar:
pass
def whiten(self, unwhitened_residual: sf.Matrix.MatrixT) -> sf.Matrix.MatrixT:
return unwhitened_residual.applyfunc(self.whiten_scalar)
def whiten_norm(self, resid... |
class M_PHATE(phate.PHATE):
def __init__(self, n_components=2, intraslice_knn=2, interslice_knn=25, decay=5, t='auto', gamma=0, n_landmark=4000, normalize=True, mds_solver='smacof', n_pca=100, n_svd=100, n_jobs=(- 2), random_state=None, verbose=1, knn=None, **phate_kwargs):
if (knn is not None):
... |
class docSect1TypeSub(supermod.docSect1Type):
def __init__(self, id=None, title='', para=None, sect2=None, internal=None, mixedclass_=None, content_=None):
supermod.docSect1Type.__init__(self, mixedclass_, content_) |
def test_IndexedOptionArray_NumpyArray():
v2a = ak.contents.indexedoptionarray.IndexedOptionArray(ak.index.Index(np.array([2, 2, (- 1), 1, (- 1), 5, 4], np.int64)), ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5])))
_cuda.jit(extensions=[ak.numba.cuda])
def f(out, obj):
out... |
class ModelLib(BaseModelLib):
def __init__(self, args):
self.ultralytics_model = YOLOReplacer(args[MODEL_NAME])
self.dataset_name = COCO_DATASET
self.preprocess = yolov8_preprocess_chw_transpose
model_weights = self.ultralytics_model.model.state_dict()
self.model = self.ultra... |
class LabelSmoothing(nn.Module):
def __init__(self, padding_idx, smoothing=0.0):
super(LabelSmoothing, self).__init__()
self.padding_idx = padding_idx
self.confidence = (1.0 - smoothing)
self.smoothing = smoothing
def forward(self, x, target):
logprobs = torch.nn.function... |
class PuzzlePiece():
def __eq__(self, other) -> bool:
if isinstance(other, PuzzlePiece):
return (self.border() == other.border())
else:
return False
def __hash__(self):
return hash((type(self), self.border()))
def border(self) -> tuple:
return tuple((s... |
def validate_args(args):
assert (args.text or args.file), 'Either text or file must be provided Matcha-T(ea)TTS need sometext to whisk the waveforms.'
assert (args.temperature >= 0), 'Sampling temperature cannot be negative'
assert (args.speaking_rate >= 0), 'Speaking rate must be greater than 0'
return... |
class OSNet(nn.Module):
def __init__(self, blocks, layers, channels, bn_norm, IN=False, **kwargs):
super(OSNet, self).__init__()
num_blocks = len(blocks)
assert (num_blocks == len(layers))
assert (num_blocks == (len(channels) - 1))
self.conv1 = ConvLayer(3, channels[0], 7, bn... |
class CKConv(torch.nn.Module):
def __init__(self, in_channels: int, out_channels: int, horizon: int, kernel_dim_linear=2, kernel_n_points=36, kernel_radius=0.002, kernel_coord_std=0.1, conv_use_fft=False, conv_bias=True, conv_padding='same', conv_stride=1):
super().__init__()
self.Kernel = ckconv.nn... |
def test_wrap_index_numpy():
data = np.arange(10, dtype=np.int64)
index = ak.index.Index64(data)
other_data = np.asarray(index)
assert np.shares_memory(data, other_data) |
_cuda.jit(extensions=[ak.numba.cuda])
def pass_record_through(array, out):
tid = nb_cuda.grid(1)
out[tid] = array.x[tid] |
def get_full_version_string(major, minor, build, revision):
global GIT_HASH, GIT_DESCRIBE
res = ('Z3 %s.%s.%s.%s' % (major, minor, build, revision))
if GIT_HASH:
res += (' ' + GIT_HASH)
if GIT_DESCRIBE:
branch = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
res += ((... |
def test_mwt_ner_conversion():
doc = CoNLL.conll2doc(input_str=MWT_NER)
assert (len(doc.sentences) == 1)
sentence = doc.sentences[0]
assert (len(sentence.tokens) == 5)
assert (not sentence.has_enhanced_dependencies())
EXPECTED_NER = ['O', 'O', 'S-PERSON', 'O', 'O']
EXPECTED_WORDS = [1, 1, 2,... |
def spherical_bessel_formulas(n):
x = sym.symbols('x')
f = [(sym.sin(x) / x)]
a = (sym.sin(x) / x)
for i in range(1, n):
b = (sym.diff(a, x) / x)
f += [sym.simplify((b * ((- x) ** i)))]
a = sym.simplify(b)
return f |
class CleanData():
def __init__(self, df_train, df_test, run_train):
self.df_train = df_train
self.df_test = df_test
self.run_train = run_train
def clean(self):
if self.run_train:
self.df_train.drop(['index'], axis=1, inplace=True)
self.df_train.reset_inde... |
_level_function(module='ak.str')
def replace_substring(array, pattern, replacement, *, max_replacements=None, highlevel=True, behavior=None, attrs=None):
(yield (array,))
return _impl(array, pattern, replacement, max_replacements, highlevel, behavior, attrs) |
class StyleEncoder(torch.nn.Module):
def __init__(self, in_dim=513, hidden_dim=128, out_dim=256):
super().__init__()
self.in_dim = in_dim
self.hidden_dim = hidden_dim
self.out_dim = out_dim
self.kernel_size = 5
self.n_head = 2
self.dropout = 0.1
self.s... |
class ROITagHead(torch.nn.Module):
def __init__(self):
super(ROITagHead, self).__init__()
self.feature_extractor = make_roi_tag_feature_extractor()
self.predictor = make_roi_tag_predictor()
self.loss_evaluator = WeightedCeLoss(cfg.runtime_info.cls_pos_wts, cfg.runtime_info.cls_neg_wt... |
def register_Ns3DlDciListElement_s_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::DlDciListElement_s const &', 'arg0')])
cls.add_instance_attribute('m_aggrLevel', 'uint8_t', is_const=False)
cls.add_instance_attribute('m_cceIndex', 'uint8_t', is_const=False)
cls.a... |
class LaneSprite():
def __init__(self, street_map, lane_id, batch, group_marking, group_road):
self.street_map = street_map
self._lane_id = lane_id
self._lane_node = self.street_map.graph.lanes[lane_id]
self._batch = batch
self._group_road = group_road
self._group_mar... |
def embedding_computation_loop(split, set_loader, stat_file):
if (not os.path.isfile(stat_file)):
logger.debug('Extracting deep embeddings and diarizing')
embeddings = np.empty(shape=[0, params['emb_dim']], dtype=np.float64)
modelset = []
segset = []
params['mean_var_norm_emb... |
def test_constant_schedule():
cs = ConstantSchedule(5)
for i in range((- 100), 100):
assert np.isclose(cs.value(i), 5) |
class Zettl(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 5.0)] * self.N), ([10.0] * self.N)))
self.global_optimum = [[(- 0.), 0.0]]
self.fglob = (- 0.)
def fun(self, x, *args):
self.nfev += 1
retur... |
def build_transform(is_train, args):
mean = IMAGENET_DEFAULT_MEAN
std = IMAGENET_DEFAULT_STD
if is_train:
transform = create_transform(input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode... |
class Pipeline():
def __init__(self, commands, negate=False, pipe_err=False):
self.commands = commands
self.negate = negate
self.pipe_err = pipe_err
def __repr__(self):
return ('Pipeline(%r, %r, %r)' % (self.commands, self.negate, self.pipe_err))
def __eq__(self, other):
... |
class TGCN(torch.nn.Module):
def __init__(self, in_channels: int, out_channels: int, improved: bool=False, cached: bool=False, id: int=(- 1)):
super(TGCN, self).__init__()
assert (id >= 0), 'kwarg id is required.'
self.in_channels = in_channels
self.out_channels = out_channels
... |
class MemoryOptimizedGroupedGLU(torch.autograd.Function):
.amp.custom_fwd
def forward(ctx, x, w1, v1, w2, batch_sizes, num_input_bits, num_remat_bits, activation_fn):
if ((not x.is_contiguous()) or (not w1.is_contiguous()) or (not v1.is_contiguous()) or (not w2.is_contiguous())):
raise Value... |
class DummyEncoder(Encoder):
def __init__(self, input_shape: Shape):
super().__init__()
self.input_shape = input_shape
self.dummy_parameter = torch.nn.Parameter(torch.rand(1, self.get_feature_size()))
def forward(self, x: TorchObservation) -> torch.Tensor:
if isinstance(x, torch.... |
def addDBPointer(turn):
domains = ['restaurant', 'hotel', 'attraction', 'train']
pointer_vector = np.zeros((6 * len(domains)))
for domain in domains:
num_entities = dbPointer.queryResult(domain, turn)
pointer_vector = dbPointer.oneHotVector(num_entities, domain, pointer_vector)
return po... |
def dataclass_with_default_init(_cls=None, *args, **kwargs):
def wrap(cls):
user_init = getattr(cls, '__init__')
delattr(cls, '__init__')
result = dataclass(cls, *args, **kwargs)
setattr(result, '__default_init__', result.__init__)
setattr(result, '__init__', user_init)
... |
def load_mixed_5b(state_dict, name_pth, name_tf):
load_conv2d(state_dict, (name_pth + '.branch0'), (name_tf + '/Branch_0/Conv2d_1x1'))
load_conv2d(state_dict, (name_pth + '.branch1.0'), (name_tf + '/Branch_1/Conv2d_0a_1x1'))
load_conv2d(state_dict, (name_pth + '.branch1.1'), (name_tf + '/Branch_1/Conv2d_0b_... |
class FunnelForMultipleChoice(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def get_relevant_deps_and_context(line, args):
dep_type = args.dependency_type
parse = nlp.annotate(line, properties={'annotators': 'tokenize,ssplit,pos,depparse', 'outputFormat': 'json', 'ssplit.isOneSentence': True})
deps = []
tokens = parse['sentences'][0]['tokens']
pos = [tok['pos'] for tok in t... |
class TestRowWiseCounter(hu.HypothesisTestCase):
def test_rowwise_counter(self):
h = (8 * 20)
n = 5
curr_iter = np.array([100], dtype=np.int64)
update_counter = np.random.randint(99, size=h).astype(np.float64)
prev_iter = np.random.rand(h, 1).astype(np.int64)
indices ... |
def GDPPLoss(phiFake, phiReal, backward=True):
def compute_diversity(phi):
phi = F.normalize(phi, p=2, dim=1)
SB = torch.mm(phi, phi.t())
(eigVals, eigVecs) = torch.symeig(SB, eigenvectors=True)
return (eigVals, eigVecs)
def normalize_min_max(eigVals):
(minV, maxV) = (tor... |
class TestMMIOSparseCSR(TestMMIOArray):
def setup_method(self):
self.tmpdir = mkdtemp()
self.fn = os.path.join(self.tmpdir, 'testfile.mtx')
def teardown_method(self):
shutil.rmtree(self.tmpdir)
def check(self, a, info):
mmwrite(self.fn, a)
assert_equal(mminfo(self.fn)... |
class AttrDict(dict):
def __getattr__(self, name):
if (name in self.__dict__):
return self.__dict__[name]
elif (name in self):
return self[name]
else:
raise AttributeError(name)
def __setattr__(self, name, value):
if (name in self.__dict__):
... |
_module()
class FPN_UNet(BaseModule):
def __init__(self, in_channels, out_channels, init_cfg=dict(type='Xavier', layer=['Conv2d', 'ConvTranspose2d'], distribution='uniform')):
super().__init__(init_cfg=init_cfg)
assert (len(in_channels) == 4)
assert isinstance(out_channels, int)
bloc... |
def test_UnmaskedArray_RecordArray_NumpyArray():
v2a = ak.contents.unmaskedarray.UnmaskedArray(ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3]))], ['nest']))
assert (to_list(ak_from_buffers(*ak_to_buffers(v2a))) == to_list(v2a)) |
def num_errors(all_possible_countries: List[str], state: Dict) -> float:
try:
if (('sub_text' in state) and ((state['sub_text'] != '') or (state['current'] == '{}')) and (len(state['sub_text']) < (len(state['original']) * 0.75))):
text = state['sub_text']
correct_freq_dict = dict()
... |
class Encoder(nn.Module):
def __init__(self, img_channels, latent_size, m):
super(Encoder, self).__init__()
self.latent_size = latent_size
self.img_channels = img_channels
self.conv1 = nn.Conv2d(img_channels, 32, 4, stride=2)
self.conv2 = nn.Conv2d(32, 64, 4, stride=2)
... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes, momentum=BN_MOMENTUM)
self.conv2 = ... |
class DiscreteGaussianDistributionPolynomialSampler(SageObject):
def __init__(self, P, n, sigma):
if isinstance(sigma, DiscreteGaussianDistributionIntegerSampler):
self.D = sigma
else:
self.D = DiscreteGaussianDistributionIntegerSampler(RR(sigma))
self.n = ZZ(n)
... |
class GeneralizedRCNN(nn.Module):
def __init__(self, backbone, rpn, roi_heads, track_heads, transform, n_channel_backbone):
super(GeneralizedRCNN, self).__init__()
self.transform = transform
self.backbone = backbone
self.rpn = rpn
self.roi_heads = roi_heads
self.track... |
_node_type()
class WaveguideModeOverlap(optplan.EmOverlap):
type = schema_utils.polymorphic_model_type('overlap.waveguide_mode')
center = optplan.vec3d()
extents = optplan.vec3d()
normal = optplan.vec3d()
mode_num = types.IntType()
power = types.FloatType() |
def make_false_data(N, F_bin, T):
mock = torch.rand([N, F_bin, T], dtype=torch.float32)
mock2 = ((mock + (torch.rand([N, F_bin, T], dtype=torch.float32) * 1)) - 0.5)
mock = torch.stack([mock, mock2], dim=1)
return mock |
def _compute_statistics_of_path(path, model, batch_size, dims, cuda):
if path.endswith('.npz'):
f = np.load(path)
(m, s) = (f['mu'][:], f['sigma'][:])
f.close()
else:
path = pathlib.Path(path)
files = (list(path.glob('*.jpg')) + list(path.glob('*.png')))
imgs = np... |
def add_evaluation_config(cfg: CN):
_C = cfg
_C.DENSEPOSE_EVALUATION = CN()
_C.DENSEPOSE_EVALUATION.TYPE = 'iou'
_C.DENSEPOSE_EVALUATION.STORAGE = 'none'
_C.DENSEPOSE_EVALUATION.MIN_IOU_THRESHOLD = 0.5
_C.DENSEPOSE_EVALUATION.DISTRIBUTED_INFERENCE = True
_C.DENSEPOSE_EVALUATION.EVALUATE_MESH... |
_module()
class DeformableDETR(DETR):
def __init__(self, *args, **kwargs):
super(DETR, self).__init__(*args, **kwargs) |
class BidirectionalLSTM(AbstractTapeModel):
_hparams.capture
def __init__(self, n_symbols: int, n_units: int=1024, n_layers: int=3, dropout: Optional[float]=0.1) -> None:
super().__init__(n_symbols)
if (dropout is None):
dropout = 0
self.embedding = Embedding(n_symbols, 128)
... |
class Cylinder(Element):
def __init__(self, P1, P2, Radius=50, Priority=10):
Element.__init__(self, 'Cylinder')
self['Priority'] = Priority
self['P1'] = Point(P1)
self['P2'] = Point(P2)
self['Radius'] = Radius |
def test_none_correct():
from pysad.evaluation import PrecisionMetric, AUPRMetric, AUROCMetric, RecallMetric
import numpy as np
from pysad.utils import fix_seed
fix_seed(61)
metric_classes = {PrecisionMetric: 0.0, AUROCMetric: 0.0, RecallMetric: 0.0}
y_true = np.random.randint(0, 2, size=(25,), ... |
class DoWhileScope(ControlFlow):
sdfg: SDFG
test: CodeBlock
body: GeneralBlock
def as_cpp(self, codegen, symbols) -> str:
if (self.test is not None):
test = unparse_interstate_edge(self.test.code[0], self.sdfg, codegen=codegen)
else:
test = 'true'
expr = '... |
def test_isotonic_regression_with_ties_in_differently_sized_groups():
x = np.array([0, 1, 1, 2, 3, 4])
y = np.array([0, 0, 1, 0, 0, 1])
y_true = np.array([0.0, 0.25, 0.25, 0.25, 0.25, 1.0])
ir = IsotonicRegression()
ir.fit(x, y)
assert_array_almost_equal(ir.transform(x), y_true)
assert_array... |
class codelineType(GeneratedsSuper):
subclass = None
superclass = None
def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None):
self.external = external
self.lineno = lineno
self.refkind = refkind
self.refid = refid
if (highlight is No... |
def register_Ns3VsaInfo_methods(root_module, cls):
cls.add_constructor([param('ns3::VsaInfo const &', 'arg0')])
cls.add_constructor([param('ns3::Mac48Address', 'peer'), param('ns3::OrganizationIdentifier', 'identifier'), param('uint8_t', 'manageId'), param('ns3::Ptr< ns3::Packet >', 'vscPacket'), param('uint32_... |
def etl_simple_femr_program() -> None:
parser = argparse.ArgumentParser(description='An extraction tool for generic OMOP sources')
parser.add_argument('simple_source', type=str, help='Path of the folder to the simple femr input source')
parser.add_argument('target_location', type=str, help='The place to sto... |
def _impl(array, axis, highlevel, behavior, attrs):
axis = regularize_axis(axis)
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
layout = ctx.unwrap(array, allow_record=False, primitive_policy='error')
if (not is_integer(axis)):
raise TypeError(f"'axis' must be an integer, not ... |
_utils.test()
def test_struct_arg_with_matrix():
mat = ti.types.matrix(3, 2, ti.f32)
s0 = ti.types.struct(a=mat, b=ti.f32)
s1 = ti.types.struct(a=ti.i32, b=s0)
def foo(a: s1) -> ti.i32:
ret = (a.a + a.b.b)
for i in range(3):
for j in range(2):
ret += ((a.b.a[(... |
class LazyMappingExample(LazyMapping):
def __init__(self, cache):
super(LazyMappingExample, self).__init__(cache)
self.computes_called = Counter()
def compute_batch(self, keys):
for key in keys:
self.computes_called[key] += 1
return [(k * 2) for k in keys] |
def split_filtered_relations(relations):
team_relations = set()
player_relations = set()
for (_, num, rel, label) in relations:
if isinstance(label, bool):
team_relations.add((num[3], rel, label))
elif isinstance(label, str):
player_relations.add((num[3], rel, label))... |
def evaluate(dataloader, cnn_model, rnn_model, batch_size, labels):
cnn_model.eval()
rnn_model.eval()
s_total_loss = 0
w_total_loss = 0
t_total_loss = 0
for (step, data) in enumerate(dataloader, 0):
(imgs, captions, cap_lens, class_ids, keys) = prepare_data(data)
(words_features,... |
def check_model_works_with_seqlen(model_type, config, input_len):
key = PRNGKey(0)
Vocab = hax.Axis('vocab', 128)
model = model_type.init(Vocab, config, key=key)
input_ids = hax.arange(config.Pos.resize(input_len), dtype=jax.numpy.int32)
causal_mask = AttentionMask.causal()
a1 = model(input_ids,... |
def test_set_from_mat():
empty_param = CameraParameter(name='test_set')
mat_3x3 = np.eye(3)
mat_4x4 = np.eye(4)
vec_3 = np.zeros(shape=[3])
empty_param.set_KRT(K_mat=mat_3x3, R_mat=mat_3x3, T_vec=vec_3)
empty_param.set_KRT(K_mat=mat_3x3, R_mat=mat_3x3, T_vec=vec_3, inverse_extrinsic=True)
wi... |
def slice_signal_index(path, window_size, stride):
(signal, rate) = librosa.load(path, 16000)
assert (stride <= 1), stride
assert (stride > 0), stride
assert (signal.ndim == 1), signal.ndim
n_samples = signal.shape[0]
slices = []
offset = int((window_size * stride))
for beg_i in range(0,... |
def degseq_to_data(degree_sequence):
degree_sequence.sort()
return sum(((di * (10 ** i)) for (i, di) in enumerate(degree_sequence))) |
def get_openvino_throughput(model_path: Path, test_dataset: Dataset) -> float:
inferencer = OpenVINOInferencer(((model_path / 'openvino') / 'model.xml'), ((model_path / 'openvino') / 'metadata.json'))
start_time = time.time()
for image_path in test_dataset.samples.image_path:
inferencer.predict(imag... |
class CNN(nn.Module):
def __init__(self, bn=True, dataset='mnist', init='ortho'):
super(CNN, self).__init__()
nhiddens = [200, 500, 700, 1000]
if (dataset == 'mnist'):
self.channel = 1
self.sz = 28
elif ('cifar' in dataset):
self.channel = 3
... |
def to_attribute(name, attr_string):
attr_classes = (NominalAttribute, NumericAttribute, DateAttribute, StringAttribute, RelationalAttribute)
for cls in attr_classes:
attr = cls.parse_attribute(name, attr_string)
if (attr is not None):
return attr
raise ParseArffError(('unknown a... |
def xmlread(filename):
global _xml_path_zip
global _xml_zfile
path = filename
pos_at = path.index('')
if (pos_at == (- 1)):
print(("character '' is not found from the given path '%s'" % path))
assert 0
path_zip = path[0:pos_at]
path_xml = path[(pos_at + 2):]
if (not os.pa... |
def register_Ns3ErpInformation_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_constructor([param('ns3::ErpInformation const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DeserializeInformationField', 'uint8_t', [param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'leng... |
def get_from_cache(url: str, cache_dir=None, force_download=False, proxies=None, etag_timeout=10, resume_download=False, user_agent: Union[(Dict, str, None)]=None, use_auth_token: Union[(bool, str, None)]=None, local_files_only=False) -> Optional[str]:
if (cache_dir is None):
cache_dir = TRANSFORMERS_CACHE
... |
def bcd_beamforming_given_csi(file_path_channel, file_path_beamforming='bcd_perfect_csi.mat'):
channel = sio.loadmat(file_path_channel)
channel_true = (channel['channel_bs_user'], channel['channel_irs_user'], channel['channel_bs_irs'])
beamforming_data = sio.loadmat(file_path_beamforming)
(w_bcd, theta_... |
def compute_aspect_term_metrics(result_dict, labels, predictions):
all_true = []
all_pred = []
all_correct = 0
all_total = 0
for (true, pred) in zip(labels, predictions):
l = true.split('<|term|>')[(- 1)].split('<|endofterm|>')[0].strip()
p = pred.split('<|term|>')[(- 1)].split('<|en... |
def _get_fig_filenames(ebase, images_dir):
fig_base = ebase2fbase(ebase)
if (ebase in custom):
custom_options = custom.get(ebase)
if ('sfepy-view-options' in custom_options):
custom_view_options = custom_options['sfepy-view-options']
for fig_filename in _get_image_names(c... |
def extra_index_url():
return Option('--extra-index-url', dest='extra_index_urls', metavar='URL', action='append', default=[], help='Extra URLs of package indexes to use in addition to --index-url. Should follow the same rules as --index-url.') |
def test_gammaincc_neg_x_array():
with pytest.raises(ValueError):
gammaincc(0.5, [3.0, 2.0, 1.0, 0.0, (- 1.0)]) |
class PipelineDataset(Dataset):
def __init__(self, dataset, process, params):
self.dataset = dataset
self.process = process
self.params = params
def __len__(self):
return len(self.dataset)
def __getitem__(self, i):
item = self.dataset[i]
processed = self.proce... |
class CBLoss(Loss):
def __init__(self, loss: Union[(str, Callable)], loss_params: Optional[Dict]=None, fw_func: Optional[Callable]=None, bw_func: Optional[Callable]=None):
self.loss_params = {}
if (loss_params is not None):
self.loss_params = loss_params
if (type(loss) is str):
... |
class PatchEmbed(nn.Module):
def __init__(self, c1=3, c2=32, patch_size=7, stride=4):
super().__init__()
self.proj = nn.Conv2d(c1, c2, patch_size, stride, (patch_size // 2))
self.norm = nn.LayerNorm(c2)
def forward(self, x: Tensor) -> Tensor:
x = self.proj(x)
(_, _, H, W)... |
class RNN(nn.Module):
def __init__(self, input_size=50, hidden_size=256, dropout=0, bidirectional=False, num_layers=1, activation_function='tanh'):
super().__init__()
if bidirectional:
hidden_size /= 2
self.rnn = nn.RNN(input_size, hidden_size, num_layers, nonlinearity=activation... |
class BaseConfig():
def __init__(self) -> None:
self.init_member_classes(self)
def init_member_classes(obj):
for key in dir(obj):
if (key == '__class__'):
continue
var = getattr(obj, key)
if inspect.isclass(var):
i_var = var()
... |
('Solving conda environment')
def conda_solve(name=None, prefix=None, channels=('pytorch-nightly',), override_channels=False):
if (prefix is not None):
existing_env = True
env_opts = ['--prefix', prefix]
elif (name is not None):
existing_env = True
env_opts = ['--name', name]
... |
def load_extension_if_needed():
global _extension_loaded
if _extension_loaded:
return
if _warn_first_load:
warnings.warn('Loading `cdf_ops` extension. If this is the first compilation on this machine, up to 10 minutes is needed. Subsequent loading will use cached results. Use `pqe.cdf_ops.di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.