code stringlengths 101 5.91M |
|---|
def main():
arg_parser = ArgumentParser()
arg_parser.add_argument('bliss_filename', nargs='+')
arg_parser.add_argument('--output', default='/dev/stdout')
args = arg_parser.parse_args()
if args.output.endswith('.gz'):
out = gzip.GzipFile(args.output, mode='wb')
else:
out = open(ar... |
def runNonMotifTICC(inputName, outputName, clusters, beta, oldAssignmentsName):
runTest(0, inputName, outputName, clusters, beta, 1, 1, oldAssignmentsName) |
class TecoGANDiscriminator(nn.Module):
def __init__(self, resolution, input_channels):
super(TecoGANDiscriminator, self).__init__()
self.resolution = resolution
self.input_channels = input_channels
assert ((resolution & (resolution - 1)) == 0), ('resolution is not a power of two: %d'... |
class FacebookManagerSendMessage(VirtualFunctionTool):
name = 'FacebookManagerSendMessage'
summary = 'Send a message to another user.'
parameters: List[ArgParameter] = [{'name': 'recipient_id', 'type': 'string', 'description': 'The unique identifier of the recipient.', 'required': True}, {'name': 'content',... |
class FairseqDataset(torch.utils.data.Dataset):
def __getitem__(self, index):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def collater(self, samples):
raise NotImplementedError
def num_tokens(self, index):
raise NotImplementedError
def size(... |
def test_get_collaborators_for_task(assigner):
collaborators = assigner.get_collaborators_for_task('train', 2)
assert (collaborators == ['one', 'two']) |
class UniformReplayBuffer(ReplayBuffer):
def __init__(self):
self._episodes = []
def __len__(self):
return len(self._episodes)
def sample(self, num_episodes):
indices = np.random.choice(len(self._episodes), size=num_episodes, replace=True)
episodes = [self._episodes[i] for i ... |
def context_gate_factory(type, embeddings_size, decoder_size, attention_size, output_size):
gate_types = {'source': SourceContextGate, 'target': TargetContextGate, 'both': BothContextGate}
assert (type in gate_types), 'Not valid ContextGate type: {0}'.format(type)
return gate_types[type](embeddings_size, de... |
def get_F0(wav):
(f0, _, _) = librosa.pyin(wav, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))
return f0 |
def check_supported(metrics):
for mn in metrics:
if (mn not in supported_metrics):
raise ValueError(('metric name not supported %s, supported metrics: %s' % (mn, supported_metrics))) |
class OnPolicyVectorizedSampler(BatchSampler):
def __init__(self, algo, env, n_envs=None):
if (n_envs is None):
n_envs = (singleton_pool.n_parallel * 4)
super().__init__(algo, env)
self._n_envs = n_envs
self._vec_env = None
self._env_spec = self.env.spec
w... |
_utils.test()
def test_return_type_mismatch_2():
with pytest.raises(ti.TaichiCompilationError):
def foo() -> ti.math.vec4:
return ti.math.vec3([1, 2, 3])
foo() |
def test_multiannotator_events():
event_data1 = annotations.Events(np.array([[0.2, 0.3], [0.3, 0.4]]), 'seconds', ['event A', 'event B'], 'open', np.array([1.0, 1.0]))
event_data2 = annotations.Events(np.array([[0.2, 0.3], [0.3, 0.4]]), 'seconds', ['', 'a great label'], 'open', np.array([0.0, 1.0]))
event_d... |
.node
class Dot(dace.sdfg.nodes.LibraryNode):
implementations = {'pure': ExpandDotPure, 'OpenBLAS': ExpandDotOpenBLAS, 'MKL': ExpandDotMKL, 'cuBLAS': ExpandDotCuBLAS, 'FPGA_PartialSums': ExpandDotFpgaPartialSums, 'FPGA_Accumulate': ExpandDotFpgaAccumulate}
default_implementation = None
n = dace.properties.S... |
class DeclarationWriter(TreeVisitor):
indent_string = u' '
def __init__(self, result=None):
super(DeclarationWriter, self).__init__()
if (result is None):
result = LinesResult()
self.result = result
self.numindents = 0
self.tempnames = {}
self.tempb... |
class PandasPredictionCallback(BasePredictionCallback[PandasDataFrame]):
def _ids_to_result(self, query_ids: torch.Tensor, item_ids: torch.Tensor, item_scores: torch.Tensor) -> PandasDataFrame:
prediction = PandasDataFrame({self.query_column: query_ids.flatten().cpu().numpy(), self.item_column: list(item_id... |
def define(approx_order=1):
from sfepy import data_dir
filename_mesh = (data_dir + '/meshes/3d/block.mesh')
options = {'nls': 'newton', 'ls': 'ls', 'post_process_hook': 'verify_tractions'}
functions = {'linear_tension': (linear_tension,)}
fields = {'displacement': ('real', 3, 'Omega', approx_order)}... |
def apply_activation(W, funcs, n_double=0):
W = sym.Matrix(W)
if (n_double == 0):
for i in range(W.shape[0]):
for j in range(W.shape[1]):
W[(i, j)] = funcs[j](W[(i, j)])
else:
W_new = W.copy()
out_size = len(funcs)
for i in range(W.shape[0]):
... |
def _compute_variance(N, cur_data, expected_max_cond_n, pdfs):
variance_of_max_cond_n = []
for n in range(N):
cur_var = 0
for i in range(N):
cur_var += (((cur_data[i] - expected_max_cond_n[n]) ** 2) * pdfs[n][i])
cur_var = np.sqrt(cur_var)
variance_of_max_cond_n.appen... |
class Data():
def __init__(self, args, batch_size):
self.args = args
self.batch_size = batch_size
self.data_loader = None
def gen_data(self):
args = self.args
if (args.mask == 'indep'):
data = IndepMaskedCelebA(obs_prob=args.obs_prob)
elif (args.mask =... |
def inception_v4_base(input):
if (K.image_dim_ordering() == 'th'):
channel_axis = 1
else:
channel_axis = (- 1)
net = conv2d_bn(input, 32, 3, 3, subsample=(2, 2), border_mode='valid')
net = conv2d_bn(net, 32, 3, 3, border_mode='valid')
net = conv2d_bn(net, 64, 3, 3)
branch_0 = Max... |
def savefig(fname, dpi=None):
dpi = (150 if (dpi == None) else dpi)
plt.savefig(fname, dpi=dpi) |
.parametrize('generator,expected_result', [(ag.AssertionGenerator, "str_0 = 'foo bar'\nfloat_0 = 39.82\nhuman_0 = module_0.Human(str_0, float_0)\nassert f'{type(human_0).__module__}.{type(human_0).__qualname__}' == 'tests.fixtures.examples.assertions.Human'\nassert module_0.static_state == 0\nstr_1 = human_0.get_name()... |
def got4(all_potential_countries) -> operations.GraphOfOperations:
operations_graph = operations.GraphOfOperations()
sub_texts = operations.Generate(1, 1)
operations_graph.append_operation(sub_texts)
sub_paragraphs = []
for i in range(1, 5):
paragraph_id = f'Paragraph {i}'
sub_text =... |
.parametrize('version, details', (('3.0.2', "The provided definition doesn't match any of the expected formats or types."), ('3.1.0', "'type' is a required property")))
def test_invalid_schema_with_disabled_validation(testdir, cli, openapi_3_schema_with_invalid_security, version, details, snapshot_cli):
openapi_3_s... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes, affine=False)
self.conv2... |
def __loc_alias(anaphor_cleaned_tokens, antecedent_cleaned_tokens):
return (__starts_with(anaphor_cleaned_tokens, antecedent_cleaned_tokens) or __is_abbreviation(anaphor_cleaned_tokens, antecedent_cleaned_tokens)) |
class Settings():
def __init__(self, file):
self._filepath = os.path.split(file)[0]
with open(file) as fb:
self._data = json.load(fb)
if (self._data['version'] != 2):
raise Exception(('incorrect file version, expected 2 but got ' + self._data['version']))
def is_s... |
class Speech2TextFeatureExtractor(SequenceFeatureExtractor):
model_input_names = ['input_features', 'attention_mask']
def __init__(self, feature_size=80, sampling_rate=16000, num_mel_bins=80, padding_value=0.0, do_ceptral_normalize=True, normalize_means=True, normalize_vars=True, **kwargs):
if (not is_t... |
def richardson_lucy(image, psf, num_iter=50, clip=True, filter_epsilon=None):
float_type = _supported_float_type(image.dtype)
image = image.astype(float_type, copy=False)
psf = psf.astype(float_type, copy=False)
im_deconv = np.full(image.shape, 0.5, dtype=float_type)
psf_mirror = np.flip(psf)
ep... |
_module()
class MultiLevelNeck(nn.Module):
def __init__(self, in_channels, out_channels, scales=[0.5, 1, 2, 4], norm_cfg=None, act_cfg=None):
super(MultiLevelNeck, self).__init__()
assert isinstance(in_channels, list)
self.in_channels = in_channels
self.out_channels = out_channels
... |
class BinarySoftF1Loss(nn.Module):
def __init__(self, ignore_index: Optional[int]=None, eps=1e-06):
super().__init__()
self.ignore_index = ignore_index
self.eps = eps
def forward(self, preds: Tensor, targets: Tensor) -> Tensor:
targets = targets.view((- 1))
preds = preds.... |
class DebertaV2ForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def _get_default_scheme():
if (os.name == 'posix'):
return 'posix_prefix'
return os.name |
class Wander():
def calculate(self, boid):
wander_value = (getattr(boid, 'wander_value', 0.0) + uniform((- 0.5), 0.5))
if (wander_value < (- 2)):
wander_value = (- 2)
elif (wander_value > 2):
wander_value = 2
boid.wander_value = wander_value
desired_ve... |
def exp_t(u, t):
if (t == 1):
return u.exp()
else:
return (1.0 + ((1.0 - t) * u)).relu().pow((1.0 / (1.0 - t))) |
_representation(onnx.defs.OpSchema.FormalParameter, type_str='typeStr', param_type='option', homogeneous='isHomogeneous')
class ONNXParameter():
name = Property(dtype=str, desc='The parameter name')
description = Property(dtype=str, desc='A description of the parameter')
type_str = Property(dtype=str, desc=... |
def get_gdm():
_a = data.ply_where((X.method == 'gdm')).ply_select('*', test_metric=X.MSE)
_a = VirtualValidation(_a).fit((cv_group + ['method']), [('valid_error', {'larger_is_better': False})])
return _a[(cv_group + ['target_c', 'method', 'test_metric'])] |
def greedy_search_comma(input_string, predefined_list):
chunks = input_string.split(',')
results = []
buffer = ''
for chunk in chunks:
buffer = ((buffer + chunk) if buffer else chunk)
if (buffer.strip() in predefined_list):
results.append(buffer.strip())
buffer = ... |
class RESetParallelIterator(RESetMapReduce):
def map_function(self, z):
return (z,)
reduce_init = tuple
def __iter__(self):
self.setup_workers(reduce_locally=False)
self.start_workers()
active_proc = self._nprocess
while True:
newres = self._results.get()
... |
def test_junction_error_massages():
error = 'The input unit for the Josephson Junction is not correct. Look at the documentation for the correct input format.'
with pytest.raises(ValueError, match=error):
Junction(10, 'F') |
class TunableMeta(type):
def __getitem__(cls, values):
if (not isinstance(values, tuple)):
values = (values,)
return type('Tunable_', (Tunable,), {'__args__': values}) |
def convert_all_pt_checkpoints_to_tf(args_model_type, tf_dump_path, model_shortcut_names_or_path=None, config_shortcut_names_or_path=None, compare_with_pt_model=False, use_cached_models=False, only_convert_finetuned_models=False):
assert os.path.isdir(args.tf_dump_path), '--tf_dump_path should be a directory'
i... |
class SSIM(torch.nn.Module):
def __init__(self, window_size=11, size_average=True, val_range=None):
super(SSIM, self).__init__()
self.window_size = window_size
self.size_average = size_average
self.val_range = val_range
self.channel = 1
self.window = create_window(win... |
def SetEnvVar(env_var, value):
env_var = env_var.upper()
if (value is not None):
os.environ[env_var] = value
elif (env_var in os.environ):
del os.environ[env_var] |
class FFNLayer(nn.Module):
def __init__(self, d_model, dim_feedforward=2048, dropout=0.0, activation='relu', normalize_before=False):
super().__init__()
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_m... |
(0.2)
def verify_security_question(entities, *argv, **kargs):
if (entities['security_question'].lower() == 'toyota camry'):
return resp(True, msg='OK')
else:
return resp(False, msg='Sorry, the answer of the security question is wrong.') |
def read_xyz(file_path):
with open(file_path, 'r') as f:
n_atoms = None
(R, z) = ([], [])
for (i, line) in enumerate(f):
line = line.strip()
if (not n_atoms):
n_atoms = int(line)
cols = line.split()
(file_i, line_i) = divmod(i, ... |
def get_summary_writer(cfg: DictConfig, job_type: str):
outdir = Path(cfg.get('outdir', os.getcwd()))
jobdir = outdir.joinpath(job_type)
sdir = jobdir.joinpath('summaries')
sdir.mkdir(exist_ok=True, parents=True)
return tf.summary.create_file_writer(sdir.as_posix()) |
def get_device_properties(device):
if (not _initialized):
init()
if ((device < 0) or (device >= device_count())):
raise AssertionError('Invalid device id')
return _get_device_properties(device) |
class BallQuery(Function):
def forward(ctx, radius, nsample, xyz, new_xyz):
output = _ext.ball_query(new_xyz, xyz, radius, nsample)
ctx.mark_non_differentiable(output)
return output
def backward(ctx, grad_out):
return () |
def positive_tagging(tagging_scheme, slot_name, slot_size):
if (slot_name == OUTSIDE):
return [OUTSIDE for _ in range(slot_size)]
if (tagging_scheme == TaggingScheme.IO):
tags = [(INSIDE_PREFIX + slot_name) for _ in range(slot_size)]
elif (tagging_scheme == TaggingScheme.BIO):
if (sl... |
class InputProjectionA(nn.Module):
def __init__(self, samplingTimes):
super().__init__()
self.pool = nn.ModuleList()
for i in range(0, samplingTimes):
self.pool.append(nn.AvgPool3d(3, stride=2, padding=1))
def forward(self, input):
for pool in self.pool:
i... |
def get_effecitve_match_source(s, start, end):
_start = (- 1)
for i in range(start, (start - 2), (- 1)):
if (i < 0):
_start = (i + 1)
break
if is_span_separator(s[i]):
_start = i
break
if (_start < 0):
return None
_end = (- 1)
f... |
def get_simple_regression(device: torch.device) -> GetterReturnType:
N = 10
K = 10
loc_beta = 0.0
scale_beta = 1.0
beta_prior = dist.Normal(loc_beta, scale_beta)
X = torch.rand(N, (K + 1), device=device)
Y = torch.rand(N, 1, device=device)
beta_value = beta_prior.sample(((K + 1), 1))
... |
def _maybe_create_densepose_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
if (not cfg.MODEL.DENSEPOSE_ON):
return None
use_masks = cfg.MODEL.ROI_DENSEPOSE_HEAD.COARSE_SEGM_TRAINED_BY_MASKS
def has_densepose_annotations(instance: Instance) -> bool:
for ann in instance[... |
class UnivariateStatistic(BaseStatistic):
def update(self, num):
pass
def get(self):
pass
def remove(self, num):
pass |
def count_message_tokens(messages: List[Message], model: str='gpt-3.5-turbo-0301') -> int:
if model.startswith('gpt-3.5-turbo'):
tokens_per_message = 4
tokens_per_name = (- 1)
encoding_model = 'gpt-3.5-turbo'
elif (model.startswith('gpt-4') or (model == 'openai/gpt-4-0314')):
tok... |
def run_webapp(pickle_path):
run_file = subprocess.run(['streamlit', 'run', APP_PATH, '--', '--path', pickle_path])
return run_file |
class TFMPNetForQuestionAnswering():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def check_hexapod_dart_simu(conf):
includes_check = ['/usr/local/include', '/usr/include']
libs_check = ['/usr/local/lib', '/usr/lib']
if ('RESIBOTS_DIR' in os.environ):
includes_check = ([(os.environ['RESIBOTS_DIR'] + '/include')] + includes_check)
libs_check = ([(os.environ['RESIBOTS_DIR']... |
def make_transients_persistent(sdfg: SDFG, device: dtypes.DeviceType, toplevel_only: bool=True) -> Dict[(int, Set[str])]:
result: Dict[(int, Set[str])] = {}
for nsdfg in sdfg.all_sdfgs_recursive():
fsyms: Set[str] = nsdfg.free_symbols
persistent: Set[str] = set()
not_persistent: Set[str]... |
def _open_out_file(filename):
if (filename in ['NUL:', '/dev/null']):
return dev_null
else:
return open(filename, 'wb') |
def _batch_mahalanobis(bL, bx):
n = bx.size((- 1))
bx_batch_shape = bx.shape[:(- 1)]
bx_batch_dims = len(bx_batch_shape)
bL_batch_dims = (bL.dim() - 2)
outer_batch_dims = (bx_batch_dims - bL_batch_dims)
old_batch_dims = (outer_batch_dims + bL_batch_dims)
new_batch_dims = (outer_batch_dims + ... |
class ConditionalBatchNorm2d_for_skip_and_shared(nn.Module):
def __init__(self, num_features, z_dims_after_concat, spectral_norm):
super().__init__()
self.num_features = num_features
self.bn = batchnorm_2d(num_features, eps=0.0001, momentum=0.1, affine=False)
if spectral_norm:
... |
def visualize_attention(writer, attention_map, iteration, threshold=0):
stage = 'valid'
for i in range(len(attention_map)):
C = attention_map[i].shape[1]
attention_map_sb = F.interpolate(attention_map[i], C, mode='nearest')
attention_map_sb = attention_map_sb[0].transpose(0, 1).unsqueeze... |
class PSPHead(BaseSegHead):
def __init__(self, bins=(1, 2, 3, 6), **kwargs):
super(PSPHead, self).__init__(**kwargs)
self.bins = bins
self.psp = PPM(self.bins, self.in_channels, self.channels, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg)
self.bottleneck = Con... |
class RoFormerTokenizerFast(metaclass=DummyObject):
_backends = ['tokenizers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tokenizers']) |
def construct_rfv_to_ev(rfv_dictionary, q, d, verbose=False):
P = {(v,): [] for v in range(2, q)}
for exponent_vector in rfv_dictionary:
residue_field_vector = rfv_dictionary[exponent_vector]
rf_vector_start = (residue_field_vector[0],)
rf_vector_end = residue_field_vector[1:]
P[... |
def FwFMEstimator(linear_feature_columns, dnn_feature_columns, dnn_hidden_units=(256, 128, 64), l2_reg_linear=1e-05, l2_reg_embedding=1e-05, l2_reg_field_strength=1e-05, l2_reg_dnn=0, seed=1024, dnn_dropout=0, dnn_activation='relu', dnn_use_bn=False, task='binary', model_dir=None, config=None, linear_optimizer='Ftrl', ... |
def minimize_noise(show_warnings, ui, for_profiling):
result = {}
cmd = ['sudo', '-n', 'rebench-denoise']
if for_profiling:
cmd += ['--for-profiling']
cmd += ['--json', 'minimize']
try:
output = output_as_str(subprocess.check_output(cmd, stderr=subprocess.STDOUT))
try:
... |
class WindowedSlopeBanditTeacher():
def __init__(self, env, policy, window_size=10, abs=False, writer=None):
self.env = env
self.policy = policy
self.window_size = window_size
self.abs = abs
self.scores = [deque(maxlen=window_size) for _ in range(env.num_actions)]
sel... |
def count_all_paths_with_label_in_frame_inefficient(fsa: Fsa, num_frames: int, frame_idx: int, label: str) -> int:
return len([path for path in iterate_all_paths(fsa=fsa, num_frames=num_frames) if (path[frame_idx].label == label)]) |
_HEADS_REGISTRY.register()
class DensePoseROIHeads(StandardROIHeads):
def __init__(self, cfg, input_shape):
super().__init__(cfg, input_shape)
self._init_densepose_head(cfg, input_shape)
def _init_densepose_head(self, cfg, input_shape):
self.densepose_on = cfg.MODEL.DENSEPOSE_ON
... |
class DateMatcher(RegexMatchEach):
def __init__(self, *children, **kwargs):
kwargs['attrib'] = 'ner_tags'
kwargs['rgx'] = 'DATE'
super(DateMatcher, self).__init__(*children, **kwargs) |
def repetitive_adjacent_analysis(history: List[List[Set[Node]]], L, P):
for (i, found_sets) in enumerate(history):
lengths = [len(x) for x in found_sets]
print(f'-I- merge {i} Found set lengths {lengths}')
for l in lengths:
if ((l % P) == 0):
k = (l // P)
... |
def ngrams(sen, n):
sen = sen.split(' ')
output = []
for i in range(((len(sen) - n) + 1)):
output.append(tuple(sen[i:(i + n)]))
return output |
def init_logs(opt):
log_dir = safe_path(os.path.join(opt.data_root, 'explog{}'.format(opt.exp_id)))
if opt.istrain:
img_logs = safe_path(os.path.join(log_dir, 'train'))
else:
img_logs = safe_path(os.path.join(log_dir, 'eval'))
weight_logs = safe_path(os.path.join(log_dir, 'weights'))
... |
class TestGather2D(object):
def x(self):
x = tf.constant([[[1, 2], [2, 2], [3, 3]], [[4, 5], [5, 4], [6, 6]], [[7, 7], [8, 7], [9, 9]], [[0, 8], [1, 1], [2, 2]]], dtype=tf.int32)
return x
.usefixtures('clean_test_session')
def test(self, x):
i = tf.constant([[0, 2], [3, 0]], dtype=tf... |
class PAL_TD3(object):
def __init__(self, state_dim, action_dim, max_action, discount=0.99, tau=0.005, policy_noise=0.2, noise_clip=0.5, policy_freq=2, alpha=0.4, min_priority=1):
self.actor = Actor(state_dim, action_dim, max_action).to(device)
self.actor_target = copy.deepcopy(self.actor)
s... |
def _maybe_create_mask_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
if (not cfg.MODEL.MASK_ON):
return None
def has_mask_annotations(instance: Instance) -> bool:
return any((('segmentation' in ann) for ann in instance['annotations']))
return has_mask_annotations |
class GCN(nn.Layer):
def __init__(self, in_features, out_features, bias=True):
super(GCN, self).__init__()
self.in_features = in_features
self.out_features = out_features
stdv = (1.0 / math.sqrt(self.out_features))
self.weight = self.create_parameter(shape=[self.in_features, ... |
def test_dot_batched_outer_product():
a_raw = torch.tensor([[1.0, 2.0, 3.0], [(- 1.0), (- 2.0), (- 3.0)]])
b_raw = torch.tensor([[4.0, 5.0, 6.0], [4.0, 5.0, 6.0]])
batch_dim = Dim(dimension=2)
a_feature_dim = Dim(dimension=3)
b_feature_dim = Dim(dimension=3)
a = Tensor(name='a', dims=[batch_dim,... |
def make_input_pipeline_from_def(def_dict, mode, **kwargs):
if (not ('class' in def_dict)):
raise ValueError('Input Pipeline definition must have a class property.')
class_ = def_dict['class']
if (not hasattr(sys.modules[__name__], class_)):
raise ValueError('Invalid Input Pipeline class: {}... |
def get_ssa(net, blob_versions=None):
proto = (net.Proto() if isinstance(net, Net) else net)
assert isinstance(proto, caffe2_pb2.NetDef)
if (blob_versions is None):
blob_versions = {}
if isinstance(net, list):
return ([get_ssa(n, blob_versions) for n in net], blob_versions)
for i in ... |
def rect_2_cxy_wh(rect):
return (np.array([(rect[0] + (rect[2] / 2)), (rect[1] + (rect[3] / 2))]), np.array([rect[2], rect[3]])) |
.parametrize('likelihood_variance', [(- 1), 0.0])
def test_build_svgp_raises_for_invalid_likelihood_variance(likelihood_variance: float) -> None:
(qp, obs) = mock_data()
data = mk_dataset(qp, obs)
search_space = (Box([0.0], [1.0]) ** qp.shape[(- 1)])
with pytest.raises(TF_DEBUGGING_ERROR_TYPES):
... |
def ncr(n, r):
if (r > n):
return 0
r = min(r, (n - r))
numer = reduce(op.mul, range(n, (n - r), (- 1)), 1)
denom = reduce(op.mul, range(1, (r + 1)), 1)
return (numer // denom) |
def convert(name, in_dir, out_dir, resolution, skip_existing):
out_name = f'{name[0]}/{name}'
out_filename = (out_dir / f'{out_name}.json')
if (skip_existing and out_filename.is_file()):
return
music = muspy.read(((in_dir / name[0]) / name))
adjust_resolution(music, resolution)
end_time ... |
def parallel_execution_analysis(node, part_idx, cache):
if (node.scope in cache):
return cache[node.scope]
elif (node.stage_id != part_idx):
cache[node.scope] = (0, 0)
return (0, 0)
(longest_f, longest_b) = (0, 0)
for n in node.in_edges:
(f, b) = parallel_execution_analys... |
class CythonFunction(CythonVariable):
def __init__(self, module, name, cname, pf_cname, qualified_name, lineno, type=CObject, is_initmodule_function='False'):
super(CythonFunction, self).__init__(name, cname, qualified_name, type, lineno)
self.module = module
self.pf_cname = pf_cname
... |
def main(args):
dict = dictionary.Dictionary.load(args.dict)
ds = IndexedDataset(args.input, fix_lua_indexing=True)
for tensor_line in ds:
print(dict.string(tensor_line)) |
def test_coerce_to_string_io_with_path():
with tempfile.NamedTemporaryFile(delete=False) as f:
_to_string_io
def func(fh):
assert isinstance(fh, TextIOWrapper)
func(f.name) |
def get_arguments():
parser = argparse.ArgumentParser(description='DeepLab-ResNet Network')
parser.add_argument('--model', type=str, default=MODEL, help='Model Choice (DeeplabMulti/DeeplabVGG/Oracle).')
parser.add_argument('--data-dir', type=str, default=DATA_DIRECTORY, help='Path to the directory containin... |
def check_foreign_word(word: str) -> int:
word = word.strip()
word = re.sub('[\\u200B-\\u200D]', '', word)
if (not is_valid_malayalam_word(word)):
return 1
if has_sure_patterns(word):
return 1
return 0 |
def upload_onnx_model(model_name, zoo_dir, backup=False, only_local=False):
if only_local:
print('No uploading in local only mode.')
return
model_dir = os.path.join(zoo_dir, model_name)
suffix = ('-backup' if backup else '')
if backup:
print('Backing up the previous version of ON... |
class Mish_SENet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(Mish_SENet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_laye... |
def string_to_list(string: str) -> List[int]:
assert ((string[0] == '[') and (string[(- 1)] == ']')), 'String is not a list.'
return [int(num) for num in string[1:(- 1)].split(',')] |
def render_with_template(text=None, filename=None, preprocessor=None, template_kwargs={}):
from mako.template import Template
from mako import exceptions
tmpl = Template(text=text, filename=filename, preprocessor=preprocessor)
try:
return tmpl.render(**template_kwargs)
except Exception as e:... |
class SplAtConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, radix=2, reduction_factor=4, conv_op=nn.Conv2d, norm_op=nn.BatchNorm2d, dropblock_prob=0.0):
super(SplAtConv2d, self).__init__()
inter_channels = max(((in_ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.