code stringlengths 101 5.91M |
|---|
class ArchVariant():
def __init__(self, name, is_custom=False):
self.name = name
self.is_custom = is_custom
def render(self):
extra_parts = (['custom'] if self.is_custom else [])
return '_'.join(([self.name] + extra_parts)) |
def compute_aspect_ratios(dataset, indices=None):
if hasattr(dataset, 'get_height_and_width'):
return _compute_aspect_ratios_custom_dataset(dataset, indices)
if isinstance(dataset, torchvision.datasets.CocoDetection):
return _compute_aspect_ratios_coco_dataset(dataset, indices)
if isinstance... |
def verbosity_to_loglevel(verbosity: int, extended=True):
if extended:
if (verbosity <= 0):
log_level = logging.ERROR
elif (verbosity == 1):
log_level = logging.INFO
elif (verbosity == 2):
log_level = logging.INFO2
elif (verbosity == 3):
... |
def sox_func(inputs):
(files, root, out_root, speaker) = inputs
for name in tqdm.tqdm(files, desc=('Process for speaker: ' + speaker)):
if name.endswith('.mp3'):
split = name.split('-')[1]
out_dir = os.path.join(out_root, split)
os.makedirs(out_dir, exist_ok=True)
... |
class MapieCalibrator(BaseEstimator, ClassifierMixin):
fit_attributes = ['estimator', 'calibrators']
named_calibrators = {'sigmoid': _SigmoidCalibration(), 'isotonic': IsotonicRegression(out_of_bounds='clip')}
valid_methods = ['top_label']
valid_cv = ['prefit', 'split']
valid_inputs = ['multiclass',... |
(frozen=True)
class PerspectiveAPIRequestResult():
success: bool
cached: bool
text_to_toxicity_attributes: Dict[(str, ToxicityAttributes)] = field(default_factory=dict)
error: Optional[str] = None |
def eval_task1(version_dir: Path):
if (not ((version_dir / 'dev_task1.csv').is_file() and (version_dir / 'test_task1.csv').is_file())):
logging.warning(f'Directory {version_dir} does not contain task 1')
return {}
stats = {}
dev_pred = pd.read_csv((version_dir / 'dev_task1.csv'))
dev_pre... |
class ErrorMetrics():
def preprocess(self, text):
preprocessed = ' '.join(text.strip().split())
return preprocessed
def calculate_metrics(self, predicted_text, transcript):
cer = (ed.eval(predicted_text, transcript) / float(len(transcript)))
pred_spl = predicted_text.split()
... |
def plot_mesh(ax, coors, conn, edges, color='k', **plot_kwargs):
dim = coors.shape[1]
ax = _get_axes(ax, dim)
coors = _to2d(coors)
for el in conn:
eds = el[edges]
for ed in eds:
cc = coors[ed]
ax.plot(*cc.T, color=color, **plot_kwargs)
return ax |
def test_all_zero_stats():
import numpy as np
from pysad.statistics import AbsStatistic
from pysad.statistics import RunningStatistic
from pysad.statistics import AverageMeter
from pysad.statistics import CountMeter
from pysad.statistics import MaxMeter
from pysad.statistics import MedianMet... |
def _seg_29():
return [(12289, 'V'), (12290, 'M', u'.'), (12291, 'V'), (12342, 'M', u''), (12343, 'V'), (12344, 'M', u''), (12345, 'M', u''), (12346, 'M', u''), (12347, 'V'), (12352, 'X'), (12353, 'V'), (12439, 'X'), (12441, 'V'), (12443, '3', u' '), (12444, '3', u' '), (12445, 'V'), (12447, 'M', u''), (12448, 'V')... |
class CosineSimilarityLoss(nn.Module):
def __init__(self, model: SentenceTransformer):
super(CosineSimilarityLoss, self).__init__()
self.model = model
def forward(self, sentence_features: Iterable[Dict[(str, Tensor)]], labels: Tensor):
reps = [self.model(sentence_feature)['sentence_embed... |
class TestLayout(unittest.TestCase):
def test_add_fnod(self):
L = Layout('defstr.lay')
L.add_fnod(p=(10, 10))
self.assertEqual(L.Np, 13)
def test_add_furniture(self):
L = Layout('defstr.lay')
L.add_furniture(name='R1_C', matname='PARTITION', origin=(5.0, 5.0), zmin=0.0, h... |
def hear_scene_kfolds(target_dir: str, cache_dir: str, dataset_root: str, test_fold: int, num_folds: int, get_path_only: bool=False):
assert (test_fold < num_folds), f'test_fold id must be smaller than num_folds. get test_fold={test_fold} and num_folds={num_folds}'
target_dir = Path(target_dir)
train_csv = ... |
class Locator(object):
source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz')
binary_extensions = ('.egg', '.exe', '.whl')
excluded_extensions = ('.pdf',)
wheel_tags = None
downloadable_extensions = (source_extensions + ('.whl',))
def __init__(self, scheme='default'):
... |
def class_doc_from_option(arg: Any) -> Optional[str]:
if (arg in ('both', 'class', 'init')):
return arg
else:
raise ValueError((__('invalid value for class-doc-from option: %s') % arg)) |
def test_string_cast():
str_arr = np.array(['1234', '1234\x00\x00'], dtype='S')
uni_arr1 = str_arr.astype('>U')
uni_arr2 = str_arr.astype('<U')
if (sys.version_info[0] < 3):
assert_array_equal(str_arr, uni_arr1)
assert_array_equal(str_arr, uni_arr2)
else:
assert_((str_arr != ... |
def schema_with_payload(empty_open_api_3_schema):
empty_open_api_3_schema['paths'] = {'/data': {'post': {'requestBody': {'required': True, 'content': {'text/plain': {'schema': {'type': 'string'}}}}, 'responses': {'200': {'description': 'OK'}}}}}
return schemathesis.from_dict(empty_open_api_3_schema) |
class bodypose_model(nn.Module):
def __init__(self):
super(bodypose_model, self).__init__()
no_relu_layers = ['conv5_5_CPM_L1', 'conv5_5_CPM_L2', 'Mconv7_stage2_L1', 'Mconv7_stage2_L2', 'Mconv7_stage3_L1', 'Mconv7_stage3_L2', 'Mconv7_stage4_L1', 'Mconv7_stage4_L2', 'Mconv7_stage5_L1', 'Mconv7_stage5... |
def _fd_or_path_or_tempfile(fd, mode='w+b', tempfile=True):
close_fd = False
if ((fd is None) and tempfile):
fd = TemporaryFile(mode=mode)
close_fd = True
if isinstance(fd, basestring):
fd = open(fd, mode=mode)
close_fd = True
try:
if isinstance(fd, os.PathLike):
... |
class NNPolicy(Policy, Serializable):
def __init__(self, env_spec, observation_ph, actions, scope_name=None):
Serializable.quick_init(self, locals())
self._observations_ph = observation_ph
self._actions = actions
self._scope_name = (tf.get_variable_scope().name if (not scope_name) el... |
class TestPointerStructures():
def test_scalars(self):
s = readsav(path.join(DATA_PATH, 'struct_pointers.sav'), verbose=False)
assert_identical(s.pointers.g, np.array(np.float32(4.0), dtype=np.object_))
assert_identical(s.pointers.h, np.array(np.float32(4.0), dtype=np.object_))
asser... |
class RegularPartitionTuples_all(RegularPartitionTuples):
def __init__(self, regular):
RegularPartitionTuples.__init__(self, regular, category=InfiniteEnumeratedSets())
def _repr_(self):
return '{}-Regular partition tuples'.format(self._ell)
def __iter__(self):
for N in NN:
... |
def top_sources_all(args: Dict[(str, Any)]) -> List[object]:
query = [{'$match': {'body': {'$ne': ''}, 'quotesUpdated': {'$exists': True}, 'outlet': {'$in': args['outlets']}, 'publishedAt': {'$gte': args['begin_date'], '$lt': (args['end_date'] + timedelta(days=1))}}}, {'$project': {'outlet': 1, 'sourcesMale': 1, 's... |
def _mnist_dataset(dtype=np.float32):
(X, y) = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)
X = X.astype(dtype, copy=False)
X = MaxAbsScaler().fit_transform(X)
(X, X_val, y, y_val) = train_test_split(X, y, test_size=0.1, random_state=0)
return (X, X_val, y, y_val) |
def test_date_time_units():
array1 = np.array(['2020-07-27T10:41:11', '2019-01-01', '2020-01-01'], 'datetime64[s]')
array2 = np.array(['2020-07-27T10:41:11', '2019-01-01', '2020-01-01'], 'datetime64[25s]')
ak_a1 = ak.highlevel.Array(array1).layout
ak_a2 = ak.highlevel.Array(array2).layout
np_ar1 = a... |
def split_supernet(run_manager, args, split_eid, split_crit, split_num, dis_metric='cos'):
run_manager.net.train()
if (split_crit == 'grad'):
if (split_eid is None):
eids = []
for i in range(1, len(run_manager.net.blocks)):
if (run_manager.net.blocks[i].mobile_inv... |
class InvertedResidual(nn.Module):
def __init__(self, inp, oup, stride, expand_ratio):
super(InvertedResidual, self).__init__()
self.blockname = None
self.stride = stride
assert (stride in [1, 2])
self.use_res_connect = ((self.stride == 1) and (inp == oup))
self.conv ... |
class EmptySlot(FixedSlot):
def __init__(self, slot_name, py3=True, py2=True, ifdef=None):
FixedSlot.__init__(self, slot_name, '0', py3=py3, py2=py2, ifdef=ifdef) |
class ElementwiseLoss(ElementwiseMetric):
def __init__(self, loss_fn, name=None):
self.loss_fn = loss_fn
if (name is None):
name = 'loss'
super().__init__(name=name)
def _compute_element_wise(self, y_pred, y_true):
return self.loss_fn(y_pred, y_true)
def worst(sel... |
def _opti_file_loader(ctx, fileloaders, nnp, filename, ext):
file_type = get_buf_type(filename)
if (file_type == 'protobuf'):
opti_proto = nnabla_pb2.NNablaProtoBuf()
with get_file_handle_load(nnp, filename, '.protobuf') as f:
opti_proto.MergeFromString(f.read())
for p_opti i... |
def _impl(array, counts, axis, highlevel, behavior, attrs):
axis = regularize_axis(axis)
with HighLevelContext(behavior=behavior, attrs=attrs) as ctx:
(layout, maybe_counts_layout) = ensure_same_backend(ctx.unwrap(array, allow_record=False, primitive_policy='error').to_packed(), ctx.unwrap(counts, allow... |
class Issue57ExecutableOnPath(ReBenchTestCase):
def setUp(self):
super(Issue57ExecutableOnPath, self).setUp()
self._set_path(__file__)
def test_sleep_gives_results(self):
store = DataStore(self.ui)
cnf = Configurator(load_config((self._path + '/issue_57.conf')), store, self.ui, d... |
class BenchmarkRunner(object):
def __init__(self, args):
self.args = args
self.iters = 100
self.has_explicit_iteration_count = False
self.multiplier = 2
self.predefined_minimum_secs = 1
self.max_iters = 1000000.0
self.use_jit = args.use_jit
self.num_ru... |
def check_file_exist(dir_name, file_name, md5=None):
dir_name = os.path.expanduser(dir_name)
file_path = os.path.join(dir_name, file_name)
if (md5 is not None):
return (os.path.exists(file_path) and check_md5(file_path, md5))
else:
return os.path.exists(file_path) |
def parallel_workload(x):
def parallel_task(x):
for i in range(int((INTERNAL_ITER / PARALLEL_TASKS_NUM))):
x = torch.mm(x, x)
return x
futs = []
for i in range(PARALLEL_TASKS_NUM):
futs.append(torch.jit._fork(parallel_task, x))
for i in range(PARALLEL_TASKS_NUM):
... |
.parametrize('device', ['cpu', 'cuda'])
.parametrize('fl', [1, 2, 3, 4, 5])
.parametrize('fp', [1, 2, 3, 4, 5])
.parametrize('center', [True, False])
def test_compatibility(device, fl, fp, center, T=20):
if ((device == 'cuda') and (not torch.cuda.is_available())):
return
if (fl < fp):
return
... |
def get_call(method_name, func_type, args, kwargs):
kwargs_str = ', '.join([((k + '=') + str(v)) for (k, v) in kwargs.items()])
self_arg = args[0]
if (func_type == 'method'):
args = args[1:]
argument_str = ', '.join(args)
argument_str += (', ' if (len(args) and len(kwargs)) else '')
argu... |
def trpo_step_td(policy_net, value_net, states, actions, next_states, rewards, masks, gamma, advantages, max_kl, damping, lambda_td=0, method_name='TRPO-TD', returns=0, mtd=1):
if (method_name == 'TRPO-TD'):
values_pred = value_net(states)
next_v = value_net(next_states)
target_v = (rewards ... |
class IteratorUtilsTest(tf.test.TestCase):
def testGetIterator(self):
tgt_vocab_table = src_vocab_table = lookup_ops.index_table_from_tensor(tf.constant(['a', 'b', 'c', 'eos', 'sos']))
src_dataset = tf.contrib.data.Dataset.from_tensor_slices(tf.constant(['f e a g', 'c c a', 'd', 'c a']))
tgt... |
def ParseArguments(args):
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=', 'linelength=', 'extensions='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat... |
class SerializedError():
type: RuntimeErrorType
title: (str | None)
message: (str | None)
extras: list[str]
exception: str
exception_with_traceback: str
def with_exception(cls, type_: RuntimeErrorType, title: (str | None), message: (str | None), extras: list[str], exception: Exception) -> Se... |
def execute_sql_with_column_info(sql_query, database='restaurants', user='select_user', password='select_user', unprotected=False):
start_time = time.time()
conn = psycopg2.connect(database=database, user=user, password=password, host='127.0.0.1', port='5432', options='-c statement_timeout=30000 -c client_encod... |
class BidirectionalGRU(nn.Module):
def __init__(self, rnn_dim, hidden_size, dropout, batch_first):
super(BidirectionalGRU, self).__init__()
self.BiGRU = nn.GRU(input_size=rnn_dim, hidden_size=hidden_size, num_layers=1, batch_first=batch_first, bidirectional=True)
self.layer_norm = nn.LayerNo... |
class TILGAN():
def __init__(self, hparams, mode):
self.hparams = hparams
self.vocab_size = hparams.from_vocab_size
self.num_units = hparams.num_units
self.emb_dim = hparams.emb_dim
self.num_layers = hparams.num_layers
self.num_heads = hparams.num_heads
self.l... |
def test_bayesian_optimizer_optimize_raises_for_invalid_rule_keys_and_default_acquisition() -> None:
optimizer = BayesianOptimizer((lambda x: x[:1]), Box([(- 1)], [1]))
(data, models) = ({FOO: empty_dataset([1], [1])}, {FOO: _PseudoTrainableQuadratic()})
with pytest.raises(ValueError):
optimizer.opt... |
class PointwiseConv1d(nn.Module):
def __init__(self, in_channels: int, out_channels: int, stride: int=1, padding: int=0, bias: bool=True) -> None:
super(PointwiseConv1d, self).__init__()
self.conv = nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=p... |
def create_param_table(params=None, height=100):
if ((params is None) or (len(params) == 0)):
data = [{'Parameter': '', 'Value': ''}]
else:
data = [{'Parameter': key, 'Value': str(value['default'])} for (key, value) in params.items()]
table = dash_table.DataTable(data=data, columns=[{'id': '... |
def test_shannon_all_unique():
img = np.arange(64)
res = shannon_entropy(img, base=2)
assert_almost_equal(res, (np.log(64) / np.log(2))) |
class NLTKTokenizer():
def word_tokenize(self, text: str) -> List[str]:
text = text.replace('.', DUMMYTOKEN)
text = text.replace('', '.')
tokens = nltk.word_tokenize(text)
new_tokens = []
for token in tokens:
token = token.replace('.', '')
token = toke... |
def make_net(genome, config, _batch_size):
input_coords = [[(- 1.0), 0.0], [0.0, 0.0], [1.0, 0.0], [0.0, (- 1.0)]]
output_coords = [[(- 1.0), 0.0], [0.0, 0.0], [1.0, 0.0]]
return AdaptiveLinearNet.create(genome, config, input_coords=input_coords, output_coords=output_coords, weight_threshold=0.4, batch_size... |
class _MaxPoolNd(Module):
__constants__ = ['kernel_size', 'stride', 'padding', 'dilation', 'return_indices', 'ceil_mode']
return_indices: bool
ceil_mode: bool
def __init__(self, kernel_size: _size_any_t, stride: Optional[_size_any_t]=None, padding: _size_any_t=0, dilation: _size_any_t=1, return_indices:... |
def test_matches_datetime_format():
result = matches_datetime_format('1/1/2020', '%m/%d/%Y')
assert (result is True) |
def create_vadd_sdfg(name, array_shape=dace.symbol('n'), map_range=dace.symbol('n')):
def vadd(x: dace.float32[array_shape], y: dace.float32[array_shape], z: dace.float32[array_shape]):
for i in dace.map[0:map_range]:
with dace.tasklet:
(xin << x[i])
(yin << y[i])... |
def test_to_categorical_none():
array = ak.Array(['one', 'two', 'three', None, 'one', 'two', 'three', None, 'one', 'two', 'three', None])
assert (not ak.operations.ak_is_categorical.is_categorical(array))
categorical = ak.str.to_categorical(array)
assert ak.operations.ak_is_categorical.is_categorical(ca... |
()
class MinMaxRewardScaler(RewardScaler):
minimum: Optional[float] = None
maximum: Optional[float] = None
multiplier: float = 1.0
def fit_with_transition_picker(self, episodes: Sequence[EpisodeBase], transition_picker: TransitionPickerProtocol) -> None:
assert (not self.built)
rewards =... |
def test_lm_example_handles_ignore_id():
Pos = hax.Axis('Pos', 10)
Vocab = hax.Axis('vocab', (Pos.size + 1))
tokens = hax.arange(Pos, dtype=jnp.int32)
ignore_id = 6
ex_ignore = LmExample.causal(tokens, ignore_id=ignore_id)
ex_no_ignore = LmExample.causal(tokens)
assert (ex_ignore.loss_mask[(... |
def make_all_rules(operations: list[APIOperation], bundles: dict[(str, CaseInsensitiveDict)], connections: APIOperationConnections) -> dict[(str, Rule)]:
rules = {}
for operation in operations:
new_rule = make_rule(operation, bundles[operation.path][operation.method.upper()], connections)
if (ne... |
class Sequential(torch.nn.Module):
def __init__(self, *args, **kwargs):
super(Sequential, self).__init__()
if ((len(args) == 1) and isinstance(args[0], OrderedDict)):
for (key, module) in args[0].items():
self.add_module(key, module)
else:
for (idx, mo... |
def options():
global _options_singelton
if (_options_singelton is None):
_options_singelton = _parse_options()
return _options_singelton |
def model_file_has_bert(filename):
checkpoint = torch.load(filename, (lambda storage, loc: storage))
return any((x.startswith('bert_model.') for x in checkpoint['model'].keys())) |
def acc_and_f1(preds, labels):
warnings.warn(DEPRECATION_WARNING, FutureWarning)
requires_backends(acc_and_f1, 'sklearn')
acc = simple_accuracy(preds, labels)
f1 = f1_score(y_true=labels, y_pred=preds)
return {'acc': acc, 'f1': f1, 'acc_and_f1': ((acc + f1) / 2)} |
def weights_init(m):
if isinstance(m, torch.nn.Conv2d):
torch.nn.init.xavier_normal_(m.weight) |
def get_scorep_config(config_line=None):
(return_code, std_out, std_err) = call(['scorep-info', 'config-summary'])
if (return_code != 0):
raise RuntimeError('Cannot call Score-P, reason {}'.format(std_err))
if (config_line is None):
return std_out.split('\n')
else:
for line in st... |
class DWConv(nn.Module):
def __init__(self, dim=768):
super(DWConv, self).__init__()
self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
def forward(self, x, H, W):
(B, N, C) = x.shape
x = x.transpose(1, 2).view(B, C, H, W)
x = self.dwconv(x)
x = x.f... |
def __run_shadow(args):
if (args.shadow_exe is None):
logging.warning('Cannot find shadow in your PATH. Do you have shadow installed? Did you update your PATH?')
logging.warning('Unable to run simulation without shadow.')
return None
shadow_cmd_str = f'{args.shadow_exe} {args.shadow_args... |
def index_class_label(arr: np.ndarray):
(_, idx) = np.unique(arr, return_inverse=True)
return idx |
class Trainer():
def __init__(self, dataset, config, _type='qa'):
Model = QA.Model
self.model = Model(config, pre_embed=dataset.vec.embeddings)
self.metrics = calc_metrics_qa
self.display_metrics = True
def train(self, train_data, test_data, n_iters=20, save_on_metric='accuracy')... |
def _format(val: Any, output_format: str='standard', split: bool=False, errors: str='coarse') -> Any:
val = str(val)
result: Any = []
if (val in NULL_VALUES):
return [np.nan]
if (not validate_ar_cuit(val)):
if (errors == 'raise'):
raise ValueError(f'Unable to parse value {val... |
class CyBreak(CythonCommand):
name = 'cy break'
command_class = gdb.COMMAND_BREAKPOINTS
def _break_pyx(self, name):
(modulename, _, lineno) = name.partition(':')
lineno = int(lineno)
if modulename:
cython_module = self.cy.cython_namespace[modulename]
else:
... |
def _get_average_score(concept, _keywords):
word_list = concept.split()
word_counter = 0
total = 0
for word in word_list:
total += _keywords[word]
word_counter += 1
return (total / word_counter) |
def skip(save_csv_train, save_csv_dev, save_csv_test):
skip = (os.path.isfile(save_csv_train) and os.path.isfile(save_csv_dev) and os.path.isfile(save_csv_test))
return skip |
class Pairs_Y(ParentWithSetFactory, DisjointUnionEnumeratedSets):
def __init__(self, y, policy):
self._y = y
ParentWithSetFactory.__init__(self, (None, y), policy=policy, category=EnumeratedSets().Finite())
DisjointUnionEnumeratedSets.__init__(self, LazyFamily(range(MAX), self.single_pair), ... |
class FblasTranspose(aenum.AutoNumberEnum):
FblasNoTrans = ((),)
FblasTrans = ((),)
FblasTransUndef = () |
def printModels(models):
string = ''
for m in models:
string += (str(m) + '|')
return string[:(- 1)] |
class InfoGANDiscriminator(Network):
def __init__(self, output_length, stride=2, kernel=5, start_depth=64, scope_name='infoGANDiscriminator', *args, **kwargs):
super(InfoGANDiscriminator, self).__init__(*args, scope_name=scope_name, **kwargs)
self.output_length = output_length
self.stride = ... |
def get_documents_statistics(documents: List[Document]):
max_depths = [get_max_depth(d) for d in documents]
return {'n_text_blocks': get_measures([len(d.text_blocks) for d in documents]), 'max_depth': get_measures(max_depths), 'label_counts': {'continuous': get_measures([len([l for l in d.labels if (l == ListAc... |
.parametrize('test_input', [0, (- 1), None, 'True', 'False', bool, int, 1.5, False])
def test_initialize_bad_background_knowledge_number_of_cycles(test_input):
with pytest.raises(ValueError):
_ = Background(number_of_cycles=test_input) |
def test_suite_assertion_minimization():
ass_min = pp.AssertionMinimization()
chromosome = MagicMock()
suite = MagicMock(test_case_chromosomes=[chromosome, chromosome])
ass_min.visit_test_suite_chromosome(suite)
chromosome.accept.assert_has_calls([call(ass_min), call(ass_min)]) |
def create_model(model_class):
(layer1, layer2, likelihood_layer) = create_layers()
dgp = gpflux.models.DeepGP([layer1, layer2], likelihood_layer, default_model_class=model_class)
return dgp |
def add_evaluation_args(parser):
group = parser.add_argument_group('validation', 'validation configurations')
group.add_argument('--eval-batch-size', type=int, default=None, help='Data Loader batch size for evaluation datasets.Defaults to `--batch-size`')
group.add_argument('--eval-iters', type=int, default... |
.parametrize('ctx, func_name', ctxs_rand_beta)
.parametrize('alpha, beta', [(0.5, 0.5), (5, 1), (1, 3), (2, 5), (2, 2)])
.parametrize('shape', [[50], [100, 100], [32, 4, 16, 16]])
.parametrize('seed', [(- 1), 313])
def test_rand_beta_forward(seed, ctx, func_name, alpha, beta, shape):
with nn.context_scope(ctx):
... |
class ModelOutput(OrderedDict):
def __post_init__(self):
class_fields = fields(self)
if (not len(class_fields)):
raise ValueError(f'{self.__class__.__name__} has no fields.')
if (not all(((field.default is None) for field in class_fields[1:]))):
raise ValueError(f'{se... |
def grid(nx=4, ny=2, height=6.0, n_caxes=0, large_margin=0.02, small_margin=0.02, sep=0.02, cbar_width=0.03):
left = large_margin
right = small_margin
top = small_margin
bottom = large_margin
panel_size = ((((1.0 - top) - bottom) - ((ny - 1) * sep)) / ny)
width = (height * (((left + (nx * panel_... |
class CamVid(SegmentationDataset):
num_classes = 11
def __init__(self, root, subset='train', transform=None, file_path=False, num_images=None, mode='labeled'):
self.d_idx = 'CVD'
self.mode = mode
self.images_root = f'{root}/{subset}/'
self.labels_root = f'{root}/{subset}annot/'
... |
def get_coco_metrics_from_path(path_to_results):
all_gt_boxes = []
all_detection_boxes = []
each_image_metrics = []
for i in tqdm(os.listdir(os.path.join(path_to_results, 'groundtruths'))):
gt_txt_file = open(os.path.join(path_to_results, 'groundtruths', i), 'r')
detection_txt_file = ope... |
class ParagraphInfo(object):
def __init__(self, dictionary):
self.dictionary = dictionary
def get_word_piece_map(self, sentence):
return [self.dictionary.is_start_word(i) for i in sentence]
def get_word_at_k(self, sentence, left, right, k, word_piece_map=None):
num_words = 0
... |
def resize_images(input_dir, output_dir, size):
for idir in os.scandir(input_dir):
if (not idir.is_dir()):
continue
if (not os.path.exists(((output_dir + '/') + idir.name))):
os.makedirs(((output_dir + '/') + idir.name))
images = os.listdir(idir.path)
n_images... |
def r_stmt(t):
stmt = t[0]
def fn(world, n):
if (n > MAX_FUNC_CALL):
return (world, n, False)
return stmt(world, (n + 1))
return [('stmt', fn)] |
class TChAIn(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, ChA, _BfC=0):
_snap.TChAIn_swiginit(self, _snap.new_TChAIn(ChA, _BfC))
def New(ChA):
return _snap.TChAIn_New(ChA)
... |
.overload_attribute(NumpyType, 'dtype', inline='always')
def Numpy_dtype(builder):
def get(builder):
return builder._data.dtype
return get |
class IdentityEncoder(Encoder):
def __init__(self, config: EncoderConfig):
super().__init__(config)
def embedded2hidden(self, embedded: torch.FloatTensor, mask: torch.BoolTensor=None):
return embedded |
def add_to_partition(_partition, _setting_str, _log_str):
slurm_cmd = ('srun --gres=gpu:1 --partition=%s --mem=%s' % (_partition, args.cpu_memory))
log_dir = ('%s/%s' % (out_dir, _log_str))
if (not os.path.exists(log_dir)):
os.makedirs(log_dir)
with open(('%s/%s' % (log_dir, 'run.cmd')), 'w') as... |
class BasicBlock(nn.Module):
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)
self.conv2 = nn.Conv2d(planes, planes, ker... |
_without_pywt
def test_invariant_denoise():
denoised_img = denoise_invariant(noisy_img, _denoise_wavelet)
denoised_mse = mse(denoised_img, test_img)
original_mse = mse(noisy_img, test_img)
assert_((denoised_mse < original_mse)) |
class PDEProblem(abc.ABC):
def __init__(self, db: database.Database) -> None:
self.db = db
self.config = db.config
self.has_solution = False
def solve(self) -> Union[(fenics.Function, List[fenics.Function])]:
pass |
class CifarResNeXt(nn.Module):
def __init__(self, cardinality, depth, nlabels, base_width, widen_factor=4):
super(CifarResNeXt, self).__init__()
self.cardinality = cardinality
self.depth = depth
self.block_depth = ((self.depth - 2) // 9)
self.base_width = base_width
s... |
def replace_pat2(matched_str):
if (matched_str.group(1) != ''):
num = matched_str.group(1).strip()
else:
num = matched_str.group(2).strip()
try:
ret = matched_str.group(0).replace(num, str(w2n.word_to_num(num)))
except ValueError:
num = matched_str.group(2).strip()
... |
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), (- 1)) |
def init_test_mot15():
config['resume'] = '/media/ssm/seagate/weights/MOT17/0601-E120-M80-G30-weights/sst300_0712_83000.pth'
config['mot_root'] = '/media/ssm/seagate/dataset/MOT15/2DMOT2015'
config['log_folder'] = '/media/ssm/seagate/logs/1005-mot15-test-5'
config['batch_size'] = 1
config['write_fil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.