code stringlengths 101 5.91M |
|---|
class Cifar100():
def __init__(self):
with open('cifar100/train', 'rb') as f:
self.train = pickle.load(f, encoding='latin1')
with open('cifar100/test', 'rb') as f:
self.test = pickle.load(f, encoding='latin1')
self.train_data = self.train['data']
self.train_la... |
class EnvSpecMeta(ABCMeta):
def __new__(cls: Any, name: str, parents: Tuple, attrs: Dict) -> Any:
base = parents[0]
parents = (base, EnvSpecMixin)
config_keys = base._config_keys
check_key_duplication(name, 'config', config_keys)
config_keys: List[str] = list(map((lambda s: s... |
def indices_values_to_sparse_tensor(indices, values, shape, return_idx=False):
indices = torch.from_numpy(indices)
values = torch.from_numpy(values)
shape = torch.Size(shape)
if (return_idx is True):
return (torch.sparse.FloatTensor(indices, values, shape), row2idx, col2idx)
else:
re... |
()
def random_seed(request) -> int:
manual_seed = request.config.getoption('--random-seed')
if (manual_seed is not None):
return int(manual_seed)
else:
rs = np.random.RandomState()
return rs.randint(0, 1000) |
class PapiloSolver(SCIPSolver):
solverId = 'PaPILO'
recognition_expr = re.compile('starting presolve of problem')
version_expr = re.compile('PaPILO version (\\S+)')
presolving_time_expr = re.compile('presolving finished after\\s+(\\S+)')
presolving_time_inf_expr = re.compile('presolving detected inf... |
def normalize_tensor_image(inp):
out = tf.convert_to_tensor(inp)
out = tf.dtypes.cast(out, tf.float32)
out = ((out - 127.5) / 127.5)
return out |
def convert(image_folder, video_file, fps, width, height):
images = sorted(glob.glob(os.path.join(image_folder, '*.jpg')), key=os.path.getmtime)
vw = cv2.VideoWriter(video_file, cv2.VideoWriter_fourcc(*'XVID'), fps, (width, height))
for i in trange(len(images)):
try:
I = cv2.imread(image... |
_input(sky_area=units.sr)
def schechter_smf(redshift, m_star, phi_star, alpha, m_min, m_max, sky_area, cosmology, noise=True):
z = schechter_smf_redshift(redshift, m_star, phi_star, alpha, m_min, m_max, sky_area, cosmology, noise)
if ((not callable(m_star)) and (np.ndim(m_star) > 0)):
m_star = np.interp... |
def train_interaction_model(x_train, y_train, x_test, y_test):
print('Training interaction model')
model = get_default_model(x_train.shape[1])
compile_model(model)
tf.keras.models.save_model(model, 'models/{}_random.h5'.format(FLAGS.dataset))
callback = tf.keras.callbacks.EarlyStopping(monitor='val_... |
.unit
.convert
def test_line_to_cols():
line = ['ID', 'RA', 'dec', 'test1', 'test2']
actual_cols = convert.line_to_cols(line)
expected_cols = line
expected_cols[0] = 'id'
expected_cols[1] = 'ra'
assert (expected_cols == actual_cols) |
class HierarchicalData(Dataset):
def __init__(self, x, act, dialog_used=5):
self.x = x
self.act = act
self.dialog_used = dialog_used
def __getitem__(self, index):
x = (([torch.tensor([101])] * (self.dialog_used - len(self.x[index]))) + [torch.tensor(([101] + item[:64])) for item ... |
def register_all_mapillary_vistas_panoptic(root):
metadata = get_metadata()
for (prefix, (image_root, panoptic_root, panoptic_json, semantic_root)) in _PREDEFINED_SPLITS_ADE20K_PANOPTIC.items():
register_mapillary_vistas_panoptic(prefix, metadata, os.path.join(root, image_root), os.path.join(root, panop... |
def create_dataframe(df, json):
sessions = list(json.keys())
session_id = 0
for session in sessions:
sub_section = list(json[session].keys())
for sub in sub_section:
if ((sub != 'noises') and (sub != 'background')):
length = len(json[session][sub])
... |
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument('plaintext_file', type=str, help='Plaintext file containing the raw input')
parser.add_argument('conllu_file', type=str, help='CoNLL-U file containing tokens and sentence breaks')
parser.add_argument('-o', '--output', default=None, t... |
def optimal_epsilon_integral():
def fp(eps, a, b, x, phi):
eps_a = np.power((1.0 * eps), (- a))
return ((((eps * np.cos(phi)) - (((a * x) * eps_a) * np.cos((a * phi)))) + 1) - b)
def arclength(eps, a, b, x, epsrel=0.01, limit=100):
return quad((lambda phi: np.sqrt((1 + (fp(eps, a, b, x, ... |
def SignExt(n, a):
if z3_debug():
_z3_assert(_is_int(n), 'First argument must be an integer')
_z3_assert(is_bv(a), 'Second argument must be a Z3 bit-vector expression')
return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx) |
def plot_results(result_path, legend=False, post_processing=None, key='AverageReturn', title=''):
if (not isinstance(result_path, (list, tuple))):
name_or_patterns = [result_path]
files = []
for name_or_pattern in name_or_patterns:
if name_or_pattern.startswith('/'):
target_path ... |
def create_exp_name(exp_prefix, exp_id=0, seed=0):
now = datetime.datetime.now(dateutil.tz.tzlocal())
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
return ('%s_%s-s-%d--%s' % (exp_prefix, timestamp, seed, str(exp_id))) |
def build(setup_kwargs):
setup_kwargs.update(ext_modules=cythonize(['auto_martini/optimization.pyx']), include_dirs=numpy.get_include()) |
class Discriminator(nn.Module):
def __init__(self):
super().__init__()
self.finetuning = False
def enable_finetuning(self, _=None):
self.finetuning = True
def forward(self, _):
pass |
def sample_function(session, session_id, itemnum, maxlen, neg_sample_num, neighbor_dict):
neg_sample_num = 20
seq = np.zeros([maxlen], dtype=np.int32)
pos = np.zeros([maxlen], dtype=np.int32)
neg = np.zeros([maxlen], dtype=np.int32)
ts = set(session)
for i in range(neg_sample_num):
neg[i... |
def get_vocabs(vocab_path, vocab_type):
mappings = read_pickle(vocab_path)
mapping_key = '{}_vocab'.format(vocab_type)
vocab = mappings[mapping_key]
print('{0} vocab size: {1}'.format(vocab_type, len(vocab)))
return vocab |
def tensor2array(image: torch.Tensor) -> np.ndarray:
image = image.detach().cpu().numpy()
image = normalize(image, origin_value_range=(0, 1), out_value_range=(0, 255), dtype=np.uint8)
return image |
def create(model_type_func, train=False, gpu_id=0):
model = DetectionModelHelper(name=model_type_func, train=train, num_classes=cfg.MODEL.NUM_CLASSES, init_params=train)
model.only_build_forward_pass = False
model.target_gpu_id = gpu_id
return get_func(model_type_func)(model) |
def check_empty(list_):
lists = [i for i in list_ if (len(i) > 0)]
if (len(lists) == 0):
return True
return False |
def make_optimizer(cfg, model):
params = []
for (key, value) in model.named_parameters():
if (not value.requires_grad):
continue
lr = cfg.lr
weight_decay = cfg.weight_decay
if ('bias' in key):
lr = (cfg.lr * cfg.bias_lr_factor)
weight_decay = c... |
class SelfAttention(nn.Module):
def __init__(self, dim: int, nhead: int, dropout: float=0.0, batch_first: bool=True, add_pe_to_qkv: List[bool]=[True, True, False]):
super().__init__()
self.self_attn = nn.MultiheadAttention(dim, nhead, dropout=dropout, batch_first=batch_first)
self.norm = nn.... |
.parametrize('sparse_container', ((CSC_CONTAINERS + DOK_CONTAINERS) + LIL_CONTAINERS))
def test_silhouette_reduce(sparse_container):
X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T
pdist_dense = pairwise_distances(X)
pdist_sparse = sparse_container(pdist_dense)
y = [0, 0, 0,... |
def validate_vatin(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]:
if isinstance(df, (pd.Series, dd.Series)):
return df.apply(vatin.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
class LeNetPHNTargetWrapper(PHNTarget):
def forward(self, x, weights=None):
logits = super().forward(x, weights)
return dict(logits_l=logits[0], logits_r=logits[1]) |
class CaseSource():
case: Case
response: GenericResponse
elapsed: float
def partial_deepcopy(self) -> CaseSource:
return self.__class__(case=self.case.partial_deepcopy(), response=self.response, elapsed=self.elapsed) |
def Subsets(s, k=None, submultiset=False):
if (k is not None):
k = Integer(k)
if isinstance(s, (int, Integer)):
if (s < 0):
raise ValueError('s must be non-negative')
from sage.sets.integer_range import IntegerRange
s = IntegerRange(1, (s + 1))
if (k is None):
... |
def start_preproc(python_args_dict=None):
args = get_basic_args(python_args_dict)
args.world_size = args.nprocs
cache = None
for rank in range(args.world_size):
print(f'-I- preprocessing data for rank {rank}/{(args.world_size - 1)} (word size is {args.world_size})...')
local_rank = rank
... |
('SoftmaxWithLoss')
def TranslateSoftmaxWithLoss(layer, pretrained_blobs, is_test, **kwargs):
softmax_op = core.CreateOperator('Softmax', [layer.bottom[0]], (layer.bottom[0] + '_translator_autogen_softmax'))
xent_op = core.CreateOperator('LabelCrossEntropy', [softmax_op.output[0], layer.bottom[1]], (layer.botto... |
def guess_pl(code):
if code:
return Guess().language_name(code.strip())
else:
return 'unknown' |
class Task():
def __init__(self, domain_name, task_name, requirements, types, objects, predicates, functions, init, goal, actions, axioms, use_metric):
self.domain_name = domain_name
self.task_name = task_name
self.requirements = requirements
self.types = types
self.objects =... |
class KRRCSimplyLacedElement(KRRiggedConfigurationElement):
_method
def cocharge(self):
cc = 0
rigging_sum = 0
for (a, p) in enumerate(self):
for (pos, i) in enumerate(p._list):
rigging_sum += p.rigging[pos]
for dim in self.parent().dims:
... |
class HeisenbergAlgebra(HeisenbergAlgebra_fd, HeisenbergAlgebra_abstract, LieAlgebraWithGenerators):
def __init__(self, R, n):
HeisenbergAlgebra_fd.__init__(self, n)
names = tuple((([('p%s' % i) for i in range(1, (n + 1))] + [('q%s' % i) for i in range(1, (n + 1))]) + ['z']))
LieAlgebraWithG... |
def parse_args():
parser = argparse.ArgumentParser(description='process parameters')
parser.add_argument('--input_data_dir', default='../data/synthetic/drug', help='input data directory')
parser.add_argument('--output_data_dir', default='pickles/cad_prescription_taken_by_patient.pkl', help='output data dire... |
def test_load_gds_diff_units():
with open(os.path.join(TESTDATA, 'rect_um.gds'), 'rb') as fp:
gds_file = gds.GDSImport(fp)
polygons = gds_file.get_polygons((100, 0))
assert (len(polygons) == 1)
np.testing.assert_almost_equal(polygons[0], [[(- 1000), 700], [(- 5000), 700], [(- 5000), 200], [(- 10... |
class TFRegNetXLayer(tf.keras.layers.Layer):
def __init__(self, config: RegNetConfig, in_channels: int, out_channels: int, stride: int=1, **kwargs):
super().__init__(**kwargs)
should_apply_shortcut = ((in_channels != out_channels) or (stride != 1))
groups = max(1, (out_channels // config.gro... |
def eval_supernet(valid_queue, model, criterion, theta):
model._arch_parameters.data.copy_(theta)
genotype = model.genotype()
(valid_acc, valid_obj) = infer(valid_queue, model, criterion, log=False, eval=False, theta=theta)
logging.info('valid_acc %f', valid_acc)
logging.info('valid_loss %f', valid... |
class HookBase():
trainer: 'TrainerBase' = None
def before_train(self):
pass
def after_train(self):
pass
def before_step(self):
pass
def after_step(self):
pass
def state_dict(self):
return {} |
class TranslationModule(SummarizationModule):
mode = 'translation'
loss_names = ['loss']
metric_names = ['bleu']
default_val_metric = 'bleu'
def __init__(self, hparams, **kwargs):
super().__init__(hparams, **kwargs)
self.dataset_kwargs['src_lang'] = hparams.src_lang
self.data... |
def _get_axis_wb(axis_wo_b, batch_dim_axis):
if (batch_dim_axis is None):
return axis_wo_b
if (axis_wo_b >= batch_dim_axis):
return (axis_wo_b + 1)
return axis_wo_b |
def _array_repr_dispatcher(arr, max_line_width=None, precision=None, suppress_small=None):
return (arr,) |
def create_binaural_wsj0mix3_csv(datapath, savepath, fs, version, savename='binaural_wsj0-3mix_', set_types=['tr', 'cv', 'tt']):
if (fs == 8000):
sample_rate = '8k'
elif (fs == 16000):
sample_rate = '16k'
else:
raise ValueError('Unsupported sampling rate')
for set_type in set_typ... |
def module_profiling(self, input, output, verbose):
ins = input[0].size()
outs = output.size()
t = type(self)
if isinstance(self, nn.Conv2d):
self.n_macs = (((((((ins[1] * outs[1]) * self.kernel_size[0]) * self.kernel_size[1]) * outs[2]) * outs[3]) // self.groups) * outs[0])
self.n_param... |
def init_process_group(rank: (int | str), world_size: (int | str), backend: Optional[str]=None) -> None:
import torch
import torch.distributed as dist
if torch.cuda.is_available():
backend = ('nccl' if (backend is None) else str(backend))
else:
backend = ('gloo' if (backend is None) else... |
.skip('Temporarily skipped because of out-of-memory error')
.mujoco
.no_cover
def test_pearl_metaworld_ml45():
assert (subprocess.run([str((EXAMPLES_ROOT_DIR / 'torch/pearl_metaworld_ml45.py')), '--num_epochs', '1', '--num_train_tasks', '1', '--num_test_tasks', '1', '--encoder_hidden_size', '1', '--net_size', '2', ... |
class ConvNet64(nn.Module):
def __init__(self, in_chan=3, out_chan=64, nh=32, out_activation='linear', activation='relu', num_groups=None, use_bn=False):
super().__init__()
self.conv1 = nn.Conv2d(in_chan, (nh * 4), kernel_size=5, bias=True, stride=2)
self.conv2 = nn.Conv2d((nh * 4), (nh * 8)... |
def produce_all_results():
(datasets, Tranges) = read_all_as_events()
results = dict()
for data_name in datasets.keys():
results_data = dict()
for algo_name in datasets[data_name].keys():
if (algo_name != 'groundtruth'):
results_data[algo_name] = pr_from_events(da... |
_numpy_output(check_dtype=True)
def test_ufunc_minimum_nan_ff(A: dace.float32[10], B: dace.float32[10]):
C = np.true_divide(A, 0)
return np.minimum(C, B) |
.ort
def test_bn_in_import():
class Module(torch.nn.Module):
def __init__(self):
super(Module, self).__init__()
self.bn = nn.BatchNorm2d(3, track_running_stats=False)
def forward(self, x):
return self.bn(x)
pt_module = Module()
dace_module = Module()
d... |
def test_neldermead_adaptive():
def func(x):
return np.sum((x ** 2))
p0 = [0., 0., 0., 0.4223638, 0., 0., 0.9692297, 0.4471682, 0., 0., 0., 0., 0., 0., 0.]
res = optimize.minimize(func, p0, method='Nelder-Mead')
assert_equal(res.success, False)
res = optimize.minimize(func, p0, method='Nelde... |
def test_load_audio():
dataset = tau2020sse_nigens.Dataset(TEST_DATA_HOME)
clip = dataset.clip('foa_dev/fold1_room1_mix001_ov1')
audio_path = clip.audio_path
(audio, sr) = tau2020sse_nigens.load_audio(audio_path)
assert (sr == 24000)
assert (type(audio) is np.ndarray)
assert (len(audio.shape... |
def get_args(parser):
parser.add('--iteration', type=int, default=0, help='Optional iteration number to start from')
parser.add('--log_frequency_loss', type=int, default=1)
parser.add('--log_frequency_images', type=int, default=100)
parser.add('--log_frequency_fixed_images', type=int, default=2500)
... |
def seed_test_case2():
var0 = {1, 2, 3}
var1 = module0.i_take_set(var0)
assert (var1 == 'not empty!') |
def wavlm_base_plus(refresh=False, *args, **kwargs):
kwargs['ckpt'] = '
return wavlm_url(*args, refresh=refresh, **kwargs) |
_sz(6)
def lanczos3(x):
(fw, to_dtype, eps) = set_framework_dependencies(x)
return ((((fw.sin((pi * x)) * fw.sin(((pi * x) / 3))) + eps) / ((((pi ** 2) * (x ** 2)) / 3) + eps)) * to_dtype((abs(x) < 3))) |
class BlobProtoVector(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _BLOBPROTOVECTOR |
def loading_testset(datasetname, test_interval, mode='test'):
datasetname = datasetname.upper()
cfg_data = getattr(setting, datasetname).cfg_data
Dataset = dataset.TestDataset
test_loader = createValTestData(datasetname, Dataset, cfg_data, test_interval, mode=mode)
restore_transform = createRestore(... |
def save_state(model, filename):
torch.save(model.state_dict(), filename)
print('Model saved to:', filename) |
def _load_arg_defaults(kwargs, app=None):
if (app is None):
app = current_app
if app:
bp = (app.blueprints.get(request.blueprint) if request else None)
kwargs.setdefault('cls', (bp.json_decoder if (bp and bp.json_decoder) else app.json_decoder))
else:
kwargs.setdefault('cls',... |
.parametrize('dt,val', [(ti.u32, ), (ti.u64, )])
_utils.test(require=ti.extension.data64)
def test_uint_max(dt, val):
impl.get_runtime().default_ip = dt
N = 16
f = ti.field(dt, shape=N)
def run():
for i in f:
f[i] = val
run()
fs = f.to_numpy()
for f in fs:
assert ... |
def _upgrade_columns_and_keys(old_metadata):
new_metadata = {}
columns = {}
fields = old_metadata.get('fields')
alternate_keys = []
primary_key = old_metadata.get('primary_key')
for (field, field_meta) in fields.items():
column_meta = {}
old_type = field_meta['type']
subt... |
_registry.register('fake_job_postings')
class FakeJobPostings(BaseMultiModalDataset):
_SOURCE = '
_INFO = {'train': {'url': (get_repo_url() + 'fake_job_postings/train.csv'), 'sha1sum': '78c37e46e844c9e268aa8eb6da6168b04a9e6556'}, 'test': {'url': (get_repo_url() + 'fake_job_postings/test.csv'), 'sha1sum': '30fb9... |
_converter_regitstry('DMA_matrix')
def DMA_matrix_converter(context: 'BM1688Context', reg: DMA_matrix_reg):
(res0, attr, opd0) = dma_reg_fmt_base(reg)
lane_mask = opd0['layout'].args[0]
(l, r) = memmap[MType.R]
s_addr = opd0['address']
is_trans = (reg.cmd_special_function == 1)
if ((s_addr >= l)... |
class BaseSubsetBatchMiner(BaseMiner):
def __init__(self, output_batch_size, **kwargs):
super().__init__(**kwargs)
self.output_batch_size = output_batch_size
def output_assertion(self, output):
assert (len(output) == self.output_batch_size) |
def test_valid_Armenteros_Podolanski_variables():
d1 = Vector3D(1.0, 2.0, 3.0)
d2 = Vector3D(1.0, (- 2.0), 3.0)
assert (Armenteros_Podolanski_variables(d1, d2) == (2.0, 0.0)) |
class BackwardDifferenceEncoder(BaseContrastEncoder):
def get_contrast_matrix(self, values_to_encode: np.array) -> ContrastMatrix:
return Diff().code_without_intercept(values_to_encode) |
def softsel(attn_to_input, align_scores, attn_to_mask, mask_add_head_dim_for_scores=False, input_add_multi_head_dim=False, score_add_hn_dim=False, axis=(- 2), name=None):
with tf.name_scope((name or 'softsel')):
if input_add_multi_head_dim:
attn_to_input = tf.expand_dims(attn_to_input, 1)
... |
def get_dense_input(features, feature_columns):
from . import feature_column as fc_lib
dense_feature_columns = (list(filter((lambda x: isinstance(x, fc_lib.DenseFeat)), feature_columns)) if feature_columns else [])
dense_input_list = []
for fc in dense_feature_columns:
if (fc.transform_fn is Non... |
def execute(chunk: np.ndarray, size: tuple=(3, 1, 1), mode: str='reflect'):
print('median filtering of chunk...')
chunk = median_filter(chunk, size=size, mode=mode)
return [chunk] |
_model_architecture('cmlm_transformer', 'cmlm_transformer_wmt_en_de')
def iter_nat_wmt_en_de(args):
base_architecture(args) |
class TemporalMaxPooling(Module):
def __init__(self, kW, dW=None):
super(TemporalMaxPooling, self).__init__()
self.kW = kW
self.dW = (dW or kW)
self.indices = None
def updateOutput(self, input):
if (self.indices is None):
self.indices = input.new()
sel... |
_if_pypy
def test_vectorizer_stop_words_inconsistent():
lstr = "\\['and', 'll', 've'\\]"
message = ('Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens %s not in stop_words.' % lstr)
for vec in [CountVectorizer(), TfidfVectorizer(), HashingVectorizer()]:
... |
class gen_dataset(Dataset):
def __init__(self, ann_file, transform, image_root, split='train', max_words=30, prompt=''):
self.ann = json.load(open(ann_file, 'r'))
self.transform = transform
self.image_root = image_root
self.max_words = max_words
self.split = split
sel... |
def sentence_tokenize(text_document: str) -> List[str]:
segments = segmenter.split(iter(Tokenizer().split(text_document)))
sentences = [''.join([(token.spacing + token.value) for token in sentence]).strip() for sentence in segments]
return sentences |
def create_uncertainty(args, questions):
result = []
count = 0
for qes in questions:
if (count == args.qes_limit):
break
uncertainty_record = generate_uncertainty_qes(args, qes)
result.append(uncertainty_record)
count += 1
if (args.sort_by == 'disagreement'):
... |
def load_dataset(name: str) -> pd.DataFrame:
path = _get_dataset_path(name)
df = pd.read_csv(path)
return df |
def unobserved_intrinsic_latencies_anomalous(num_samples):
return {'Product Service': halfnorm.rvs(size=num_samples, loc=0.1, scale=0.2), 'Shipping Cost Service': halfnorm.rvs(size=num_samples, loc=0.1, scale=0.2), 'Caching Service': (2 + halfnorm.rvs(size=num_samples, loc=0.1, scale=0.1)), 'Order DB': truncexpon.r... |
def ref_det(x):
y = np.zeros(x.shape[0], dtype=np.float32)
for i in range(x.shape[0]):
y[i] = np.linalg.det(x[i])
return y |
def get_inference_args():
parser = argparse.ArgumentParser(description='OpenUnmix_CrossNet(X-UMX)/OpenUnmix(UMX) Inference/Evaluation')
parser.add_argument('--inputs', type=str, nargs='+', help='List of paths to any audio files supported by FFMPEG.')
parser.add_argument('--targets', nargs='+', default=['bas... |
class VGG(nn.Module):
def __init__(self, features, output_dim, k_lipschitz=None, p_drop=None):
super(VGG, self).__init__()
self.features = features
if (k_lipschitz is not None):
(l_1, l_2, l_3) = (SpectralLinear(512, 512, k_lipschitz), SpectralLinear(512, 512, k_lipschitz), Spect... |
class UserSim():
def __init__(self, error_evaluator):
self.user_type = 'sim'
self.patience = 3
self.error_evaluator = error_evaluator
self.ground_truth = None
self.tag_seq = None
self.dec_seq = None
self.eval_outputs = None
self.true_selections = None
... |
def make_sample_her_transitions_prioritized_replay(replay_strategy, replay_k, reward_fun):
if ((replay_strategy == 'future') or (replay_strategy == 'final')):
future_p = (1 - (1.0 / (1 + replay_k)))
else:
future_p = 0
def _sample_proportional(self, rollout_batch_size, batch_size, T):
... |
def module_init():
root_module = Module('ns.config_store', cpp_namespace='::ns3')
return root_module |
def _segm_resnet(name, backbone_name, num_classes, output_stride, pretrained_backbone):
if (output_stride == 8):
replace_stride_with_dilation = [False, True, True]
aspp_dilate = [12, 24, 36]
else:
replace_stride_with_dilation = [False, False, True]
aspp_dilate = [6, 12, 18]
b... |
class VideoRecorder(object):
def __init__(self, env, path=None, metadata=None, enabled=True, base_path=None):
modes = env.metadata.get('render.modes', [])
self._async = env.metadata.get('semantics.async')
self.enabled = enabled
if (not self.enabled):
return
self.a... |
class TestDataset(Dataset):
def __init__(self, triples, args, mode, random_sampling):
self.len = len(triples['head'])
self.triples = triples
self.nentity = args.nentity
self.nrelation = args.nrelation
self.mode = mode
self.random_sampling = random_sampling
if ... |
def _get_type_string(attr_type):
if isinstance(attr_type, (list, tuple)):
if (len(attr_type) > 1):
return ((', '.join([x.__name__ for x in attr_type[:(- 1)]]) + ' or ') + attr_type[(- 1)].__name__)
return attr_type[0].__name__
return attr_type.__name__ |
def element_segmentation(measure, soup, staff=None):
(voice_starts, voice_ends) = ({}, {})
position = 0
for element in measure.contents:
if (element.name == 'note'):
if (element.duration is None):
continue
voice = element.voice.text
duration = int(... |
_criterion('cross_entropy')
class CrossEntropyCriterion(FairseqCriterion):
def __init__(self, task, sentence_avg):
super().__init__(task)
self.sentence_avg = sentence_avg
def forward(self, model, sample, reduce=True):
net_output = model(**sample['net_input'])
(loss, _) = self.com... |
class LSMDCChoiceDataModule(BaseDataModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def dataset_cls(self):
return LSMDCChoiceDataset
def dataset_cls_no_false(self):
return LSMDCChoiceDataset
def dataset_name(self):
return 'lsmdc_choice' |
(frozen=True)
class LightScenarioKey():
scenario_spec: ScenarioSpec
split: str
def __hash__(self):
return hash((self.scenario_spec, self.split)) |
def predict_shap(model, data, boosting=None):
assert (boosting is not None)
if (boosting == 'xgboost'):
return model.predict(data, pred_contribs=True)
elif (boosting == 'lightgbm'):
return model.predict(data, pred_contrib=True)
elif (boosting == 'catboost'):
return model.get_feat... |
def show_boxes_from_standard_json(json_file_path, classes, img_folder_path=None, output_folder_path=None, track_id=(- 1)):
dets = read_json_from_file(json_file_path)
for det in dets:
python_data = det
if (img_folder_path is None):
img_path = os.path.join(python_data['image']['folder'... |
def add_node(G, func_prefix, node, id, ids_in_basic_block):
node_check = ''
if (len(node_check) > 0):
if ((node_check in node) or (node_check == node)):
print('Found node', node)
assert (node is not None), 'Node none'
G.add_node((func_prefix + node), id=id)
if (ids_in_basic_block... |
def determine_source_details(configurator):
global _source
if _source:
return _source
result = {}
git_cmd = ['git']
if (configurator and configurator.options and configurator.options.git_repo):
git_cmd += ['-C', configurator.options.git_repo]
is_git_repo = (_exec((git_cmd + ['rev... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.