code stringlengths 101 5.91M |
|---|
.parametrize('arg', ('headers', 'query_string'))
def test_call_wsgi_overrides(mocker, arg, openapi_30):
spy = mocker.patch('werkzeug.Client.open', side_effect=ValueError)
original = {'A': 'X', 'B': 'X'}
case = Case(openapi_30['/users']['GET'], headers=original, query=original)
overridden = {'B': 'Y'}
... |
def _render_question_crowd_html(question_template: CritiqueQuestionTemplate) -> str:
question_input_crowd_html: str
if (question_template.question_type == QuestionType.FREE_RESPONSE):
question_input_crowd_html = textwrap.dedent(f' <crowd-text-area name="{question_template.name}" required></cr... |
def make_data_loader(cfg, is_train=True):
batch_size = cfg.SOLVER.IMS_PER_BATCH
if is_train:
batch_size = cfg.SOLVER.IMS_PER_BATCH
shuffle = True
else:
batch_size = cfg.TEST.IMS_PER_BATCH
shuffle = False
transforms = build_transforms(cfg, is_train)
datasets = build_da... |
def get_cudnn_mode(mode):
if (mode == 'RNN_RELU'):
return cudnn.CUDNN_RNN_RELU
elif (mode == 'RNN_TANH'):
return cudnn.CUDNN_RNN_TANH
elif (mode == 'LSTM'):
return cudnn.CUDNN_LSTM
elif (mode == 'GRU'):
return cudnn.CUDNN_GRU
else:
raise Exception('Unknown mod... |
class HistGradientBoostingClassifierBenchmark(Predictor, Estimator, Benchmark):
param_names = []
params = ()
def setup_cache(self):
super().setup_cache()
def make_data(self, params):
data = _synth_classification_dataset(n_samples=10000, n_features=100, n_classes=5)
return data
... |
def register_Ns3PointToPointChannel_methods(root_module, cls):
cls.add_constructor([param('ns3::PointToPointChannel const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Attach', 'void', [param('ns3::Ptr< ns3::PointToPointNetDevice >', 'device')])
cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDev... |
def FilesBelongToSameModule(filename_cc, filename_h):
if (not filename_cc.endswith('.cc')):
return (False, '')
filename_cc = filename_cc[:(- len('.cc'))]
if filename_cc.endswith('_unittest'):
filename_cc = filename_cc[:(- len('_unittest'))]
elif filename_cc.endswith('_test'):
fil... |
def test_check_response_method_unknown_method():
err_msg = 'RandomForestRegressor has none of the following attributes: unknown_method.'
with pytest.raises(AttributeError, match=err_msg):
_check_response_method(RandomForestRegressor(), 'unknown_method') |
def dist_init():
global rank, world_size, inited
try:
(rank, world_size) = _dist_init()
except RuntimeError as e:
if ('public' in e.args[0]):
logger.info(e)
logger.info('Warning: use single process')
(rank, world_size) = (0, 1)
else:
ra... |
def rotate_shift(x, shift, angle):
assert isinstance(angle, (np.float32, np.float16, float))
assert (shift.shape[(- 1)] == 2)
assert (x.shape[(- 1)] == 2)
return ((x rot_matrix(angle).T) + shift) |
class Identity(nn.Module):
def __init__(self, config):
super(Identity, self).__init__()
def forward(self, feature, att_mask, head_mask):
return [feature] |
def _get_listing_win(source_dir):
listing = glob.glob(os.path.join(source_dir, '*.pyd'))
listing.extend(glob.glob(os.path.join(source_dir, 'lib', '*.lib')))
listing.extend(glob.glob(os.path.join(source_dir, 'lib', '*.dll')))
return listing |
def get_policy(env):
policy_network = get_policy_network(env)
policy = GaussianMLPPolicy(name='policy', env_spec=env.spec, mean_network=policy_network)
return policy |
def test_non_unique_vocab():
vocab = ['a', 'b', 'c', 'a', 'a']
vect = CountVectorizer(vocabulary=vocab)
with pytest.raises(ValueError):
vect.fit([]) |
def clean_bg_vat(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame:
if (output_format not in {'compact', 'standard'}):
raise ValueError(f'output_format {output_format} is invalid. It needs to b... |
class PublishProvidedPatternsExperiment(TaskConfiguration):
def mode() -> str:
return 'publish {}'.format(RunProvidedPatternsExperiment.ID)
def tasks(self, config) -> List:
filter_ = PotentialHitsFilterTask()
publish = PublishFindingsTask(RunProvidedPatternsExperiment.ID, config.compiles... |
class objVars():
def __init__(self, rot, trans):
assert (rot.shape == (3,)), 'rot should of (3,) shape'
assert (trans.shape == (3,)), 'rot should of (3,) shape'
self.rot = rot
self.trans = trans |
class ResNet(nn.Module):
def __init__(self, cfg):
super(ResNet, self).__init__()
stage_specs = _STAGE_SPECS[cfg.MODEL.BACKBONE.TYPE]
self.stem = StemWithFixedBatchNorm(cfg)
num_groups = cfg.MODEL.RESNETS.NUM_GROUPS
width_per_group = cfg.MODEL.RESNETS.WIDTH_PER_GROUP
i... |
class LowRank2d(nn.Module):
def __init__(self, in_channels, out_channels):
super(LowRank2d, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.phi = DenseNet([2, 64, 128, (in_channels * out_channels)], torch.nn.ReLU)
self.psi = DenseNet([2, ... |
def numpy_or_pandas_and_seq_concat(datasets: Sequence[Union[(NumpyDataset, PandasDataset, SeqNumpyPandasDataset)]]) -> Union[(NumpyDataset, PandasDataset)]:
assert (len(datasets) == 2), 'should be 1 sequential and 1 plain dataset'
for (n, dataset) in enumerate(datasets):
if (type(dataset) == SeqNumpyPan... |
class RefAdaBound(RefSolver):
def __init__(self, alpha, beta1, beta2, eps, final_lr, gamma):
super().__init__()
self.alpha = alpha
self.init_alpha = alpha
self.beta1 = beta1
self.beta2 = beta2
self.eps = eps
self.final_lr = final_lr
self.gamma = gamma
... |
class ResNetV2(nn.Module):
def __init__(self, block_units, width_factor):
super().__init__()
width = int((64 * width_factor))
self.width = width
self.root = nn.Sequential(OrderedDict([('conv', StdConv2d(3, width, kernel_size=7, stride=2, bias=False, padding=3)), ('gn', nn.GroupNorm(3... |
.skipif((not has_pytorch()), reason='Pytorch not installed.')
_utils.test(arch=archs_support_ndarray_ad, default_fp=ti.f64)
def test_ad_reduce():
_utils.torch_op(output_shapes=[(1,)])
def test(x: ti.types.ndarray(), y: ti.types.ndarray()):
for i in x:
y[0] += (x[i] ** 2)
device = ('cuda'... |
def get_detr(device: torch.device) -> GetterReturnType:
N = 2
num_classes = 91
hidden_dim = 256
nheads = 8
num_encoder_layers = 6
num_decoder_layers = 6
model = models.DETR(num_classes=num_classes, hidden_dim=hidden_dim, nheads=nheads, num_encoder_layers=num_encoder_layers, num_decoder_layer... |
_end_docstrings(PIPELINE_INIT_ARGS, '\n return_all_scores (:obj:`bool`, `optional`, defaults to :obj:`False`):\n Whether to return all prediction scores or just the one of the predicted class.\n ')
class TextClassificationPipeline(Pipeline):
def __init__(self, return_all_scores: bool=False, **k... |
class StaticCamera(Camera):
def __init__(self, fov, aspect, nearval, farval, width, height, look_at, look_from, up_vector, cid, name, robot_id=None, objects=None):
self.nearval = nearval
self.farval = farval
self.fov = fov
self.aspect = aspect
self.look_from = look_from
... |
def PDO(filepath, df_splits=None, n_jobs=1):
t0 = time()
kwrgs_pp = {'selbox': (110, 260, 20, 70), 'format_lon': 'only_east'}
ds = core_pp.import_ds_lazy(filepath, **kwrgs_pp)
kwrgs_pp_eof_ds = kwrgs_pp
kwrgs_pp_eof_ds.update({'seldates': ('11-01', '03-31'), 'dailytomonths': True})
ds_monthly = ... |
class SasRec(L.LightningModule):
def __init__(self, tensor_schema: TensorSchema, block_count: int=2, head_count: int=1, hidden_size: int=50, max_seq_len: int=200, dropout_rate: float=0.2, ti_modification: bool=False, time_span: int=256, loss_type: str='CE', loss_sample_count: Optional[int]=None, negative_sampling_s... |
class ResNet34(nn.Module):
def __init__(self, n_inputs=12, numCls=17):
super().__init__()
resnet = models.resnet34(pretrained=False)
self.conv1 = nn.Conv2d(n_inputs, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.encoder = nn.Sequential(self.conv1, resnet.bn1... |
def collect_boostrap_contrastiveness(feat, num_sample, dummy_inputs):
num_negative = (num_sample - 1)
negative_ids = [i for (i, x) in enumerate(feat.ex.candidates) if (not x.ex)]
if (len(negative_ids) > num_negative):
negative_ids.sort(key=(lambda x: feat.ex.candidates[x].score), reverse=True)
... |
(sh=True)
.slow
def test_hydra_sweep_ddp_sim(tmp_path):
command = ([startfile, '-m', ('hydra.sweep.dir=' + str(tmp_path)), 'trainer=ddp_sim', 'trainer.max_epochs=3', '+trainer.limit_train_batches=0.01', '+trainer.limit_val_batches=0.1', '+trainer.limit_test_batches=0.1', 'model.optimizer.lr=0.005,0.01,0.02'] + over... |
_utils.test(require=ti.extension.sparse)
def test_struct_for_branching():
x = ti.field(dtype=ti.i32)
y = ti.field(dtype=ti.i32)
ti.root.pointer(ti.ij, (128 // 4)).dense(ti.ij, 4).place(x, y)
def func1():
for (i, j) in x:
if ((x[(i, j)] & 2) == 2):
y[(i, j)] = 1
de... |
class DonutSwinPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def load_examples_rotten_tomatoes(path, args):
hypotheses = [' negative', ' positive']
label_list = [' terrible', ' great']
label_path = './task_data/sst2/label_names_sentidict.txt'
label2synonym = load_label(label_path)
prompt = ' It was'
icl_str = ''
train_path = path.replace('dev', 'train... |
def dist_init(port, backend):
os.environ['DISTRIBUTED_BACKEND'] = backend
rank = get_rank()
world_size = get_world_size()
addr = None
num_gpus = torch.cuda.device_count()
print('num_gpus', num_gpus)
gpu_id = (rank % num_gpus)
torch.cuda.set_device(gpu_id)
if (world_size == 1):
... |
_memoize_get_funcs
def get_blas_funcs(names, arrays=(), dtype=None):
return _get_funcs(names, arrays, dtype, 'BLAS', _fblas, _cblas, 'fblas', 'cblas', _blas_alias) |
class CmdGroup(FBSOptional):
def init(self, fbs: bmodel_fbs.CmdGroup, buffer: memoryview):
self.tiu_num = fbs.BdcNum()
self.dma_num = fbs.GdmaNum()
self.tiu_cmd = Binary(fbs.BinaryBdc(), buffer)
self.dma_cmd = Binary(fbs.BinaryGdma(), buffer)
def _serialize(self, builder, save_bi... |
def tf_efficientnet_b1_ap(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('tf_efficientnet_b1_ap', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)
return model |
def from_asgi(schema_path: str, app: Any, *, base_url: (str | None)=None, method: (Filter | None)=None, endpoint: (Filter | None)=None, tag: (Filter | None)=None, operation_id: (Filter | None)=None, skip_deprecated_operations: bool=False, validate_schema: bool=False, force_schema_version: (str | None)=None, data_genera... |
def record_config_file(params=None, config_filename=None, net_save_filename=None, timestamp=None, train=True):
import shutil
utils.assert_arglist(params, [config_filename, net_save_filename])
if (params is not None):
_config_filename = params['fconfig']
if train:
_net_save_filena... |
def cross_entropy_with_label_smoothing(pred, target, label_smoothing=0.1):
logsoftmax = nn.LogSoftmax()
n_classes = pred.size(1)
target = torch.unsqueeze(target, 1)
soft_target = torch.zeros_like(pred)
soft_target.scatter_(1, target, 1)
soft_target = ((soft_target * (1 - label_smoothing)) + (lab... |
def dump_hls_lut_node2(f, name, lut, node):
f.write(('\ninline ap_uint<1> %s(\n' % make_lut_func_name(name, node)))
n = lut.get_node_connection_size(node)
s = lut.get_lut_table_size(node)
for i in range(n):
f.write((' ap_uint<1> in_data%d' % i))
if (i < (n - 1)):
f.wri... |
def log_string(element, base=None):
basestr = ((', base=' + str(base)) if base else '')
return ('log(%s%s)' % (element, basestr)) |
def test_connections():
mcp = MCP(a)
(costs, traceback) = mcp.find_costs([(1, 1), (7, 7), (1, 7)])
connections = set(mcp._conn.keys())
assert ((0, 1) in connections)
assert ((1, 2) in connections)
assert ((0, 2) in connections)
for position_tuples in mcp._conn.values():
n1 = len(posi... |
def compose_data_files() -> list:
data_files = [('sfepy', ['LICENSE', 'VERSION'])]
test_files = [('sfepy/tests', glob.glob('sfepy/tests/*.py'))]
mesh_data_files = data_dir_walk('meshes', 'sfepy')
example_files = data_dir_walk('examples', 'sfepy')
return (((data_files + test_files) + mesh_data_files)... |
def _make_win_cache():
idx = []
for i in range(3):
for j in range(7):
a = ((i * 7) + j)
idx.append([a, (a + 7), (a + 14), (a + 21)])
for i in range(6):
for j in range(4):
a = ((i * 7) + j)
idx.append([a, (a + 1), (a + 2), (a + 3)])
for i in... |
class OlympicRingSampler(RingSampler):
def __init__(self, radii: np.array=np.ones(5), width: float=0.5):
num_objects = radii.shape[0]
centers = (np.array([((- 140), 0), (0, 0), (140, 0), ((- 55), (- 50)), (55, (- 50))], np.float32) / float(50))
centers = centers[:num_objects]
super(O... |
def filter2D(img, kernel):
k = kernel.size((- 1))
(b, c, h, w) = img.size()
if ((k % 2) == 1):
img = F.pad(img, ((k // 2), (k // 2), (k // 2), (k // 2)), mode='reflect')
else:
raise ValueError('Wrong kernel size')
(ph, pw) = img.size()[(- 2):]
if (kernel.size(0) == 1):
im... |
def pretty_print_default(enable=True):
from sage.repl.rich_output import get_display_manager
dm = get_display_manager()
dm.preferences.text = ('latex' if enable else None) |
def test_string():
text = 'string'
parsedtype = ak.types.from_datashape(text, highlevel=False)
assert isinstance(parsedtype, ak.types.ListType)
assert (str(parsedtype) == text) |
def vectorize_input(batch, training=True, device=None, mode='train'):
if (not batch):
return None
srcs = torch.LongTensor(batch.sent1_word)
src_lens = torch.LongTensor(batch.sent1_length)
if (batch.sent2_word is not None):
targets = torch.LongTensor(batch.sent2_word)
target_lens ... |
def is_valid_url(url: str) -> bool:
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False |
class AWSKeyManager():
def __init__(self, auth: AWSAuthentication, local_key_dir: Path=(key_root / 'aws')):
self.auth = auth
self.local_key_dir = local_key_dir
def key_exists_aws(self, aws_region: str, key_name: str) -> bool:
ec2_client = self.auth.get_boto3_client('ec2', aws_region)
... |
def resnext50(baseWidth, cardinality):
model = ResNeXt(baseWidth, cardinality, [3, 4, 6, 3], 1000)
return model |
class ResNet(nn.Module):
def __init__(self, block, layers=(3, 4, 23, 3)):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
se... |
def random_init(size, rng=None, rng_type=None):
if (rng is None):
rng = default_rng
if (rng_type is None):
vals = rng.uniform(low=(- 0.05), high=0.05, size=size)
elif (rng_type == 'normal'):
vals = rng.standard_normal(size)
elif (rng_type == 'uniform'):
vals = rng.uniform... |
class OverconvergentDistributions_class(OverconvergentDistributions_abstract):
def _repr_(self):
s = ('Space of %s-adic distributions with k=%s action and precision cap %s' % (self._p, self._k, self._prec_cap))
twiststuff = []
if (self._dettwist is not None):
twiststuff.append(('... |
class HTTPServerWithCounter(HTTPServer):
def __init__(self, *args, **kwargs):
super(HTTPServerWithCounter, self).__init__(*args, **kwargs)
self.put_requests = 0 |
def run_aggregation_queries():
query_list = []
for method_name in args.keys():
requested = args[method_name]
if (requested and isinstance(requested, bool)):
query_list.append(getattr(queries, method_name))
for query in query_list:
logger.info(f"Query: '{query.__name__}', ... |
class VolumetricMaxUnpooling(Module):
def __init__(self, poolingModule):
super(VolumetricMaxUnpooling, self).__init__()
assert isinstance(poolingModule, VolumetricMaxPooling)
assert (poolingModule.kT == poolingModule.dT)
assert (poolingModule.kH == poolingModule.dH)
assert (p... |
class TensorboardXWriter(EventWriter):
def __init__(self, log_dir: str, window_size: int=20, **kwargs):
self.window_size = window_size
from torch.utils.tensorboard import SummaryWriter
self.writer = SummaryWriter(log_dir, **kwargs)
def write(self, **kwargs):
storage = get_event_s... |
def read_any_img(img_path: str, format='ndarray'):
img = read_rgb_image(img_path, format)
return img |
.parametrize('input_dim, output_dim, hidden_sizes, output_w_init_vals, n_heads', plain_settings)
def test_multi_headed_mlp_module_with_layernorm(input_dim, output_dim, hidden_sizes, output_w_init_vals, n_heads):
module = MultiHeadedMLPModule(n_heads=n_heads, input_dim=input_dim, output_dims=output_dim, hidden_sizes... |
def get_quantized_kernel_by_weights_qc(fw_info: FrameworkInfo, n: BaseNode, weights_qc: NodeWeightsQuantizationConfig, fw_impl: FrameworkImplementation):
if (weights_qc.weights_per_channel_threshold and (fw_info.kernel_channels_mapping is None)):
Logger.warning('Weights Per Channel Quantization requires cha... |
.gpu
def test_scalar_output():
def scaltest(A: dace.float64[(20, 20)]):
scal = dace.define_local_scalar(dace.float64)
for _ in dace.map[0:1]:
with dace.tasklet:
(inp << A[(1, 1)])
(out >> scal)
out = (inp + 5)
return scal
sdfg =... |
def test_binary_closing_noninteger_brute_force_passes_when_true():
data = numpy.ones([1])
assert (sndi.binary_erosion(data, iterations=2, brute_force=1.5) == sndi.binary_erosion(data, iterations=2, brute_force=bool(1.5)))
assert (sndi.binary_erosion(data, iterations=2, brute_force=0.0) == sndi.binary_erosio... |
class pAdicExtensionGeneric(pAdicGeneric):
def __init__(self, poly, prec, print_mode, names, element_class):
self._given_poly = poly
R = poly.base_ring()
print_mode['unram_name'] = names[2]
print_mode['ram_name'] = names[3]
print_mode['var_name'] = names[0]
names = na... |
def preprocess_image(image, output_height, output_width, random_mirror, is_training=False, resize_side_min=_RESIZE_SIDE_MIN, resize_side_max=_RESIZE_SIDE_MAX):
if is_training:
return preprocess_for_train(image, output_height, output_width, random_mirror, resize_side_min, resize_side_max)
else:
r... |
def do_retrieval():
for data in ['dl19', 'dl20', 'covid', 'nfc', 'touche', 'dbpedia', 'scifact', 'signal', 'news', 'robust04']:
print(('#' * 20))
print(f'Evaluation on {data}')
print(('#' * 20))
try:
searcher = LuceneSearcher.from_prebuilt_index(THE_INDEX[data])
... |
def run_make(arg):
if (system(('%s -j %s' % (args.make_tool, arg))) != 0):
print('\nBummer. Running serial build in order to recover the log and have a chance to fix the build')
assert (system(('%s %s' % (args.make_tool, arg))) == 0) |
def hfft2(x, s=None, axes=((- 2), (- 1)), norm=None, overwrite_x=False, workers=None):
return hfftn(x, s, axes, norm, overwrite_x, workers) |
def delsarte_bound_additive_hamming_space(n, d, q, d_star=1, q_base=0, return_data=False, solver='PPL', isinteger=False):
from sage.numerical.mip import MIPSolverException
if (q_base == 0):
q_base = q
kk = 0
while ((q_base ** kk) < q):
kk += 1
if ((q_base ** kk) != q):
print(... |
class InMemoryVesselDataset(torch_geometric.data.InMemoryDataset):
def __init__(self, root, pattern, split, purpose, transform=None, pre_transform=None):
self.root = root
self.pattern = pattern
self.purpose = purpose
self.split = split
super(InMemoryVesselDataset, self).__ini... |
def produceDict():
seg_name = ['wallbuilding', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug', 'field', 'armchai... |
def bleu_count(hypothesis, references, max_n=4):
ret_len_hyp = 0
ret_len_ref = 0
ret_clip_count = ([0] * max_n)
ret_count = ([0] * max_n)
for m in range(len(hypothesis)):
(hyp, ref) = (hypothesis[m], references[m])
x = hyp.split()
y = [r.split() for r in ref]
x_len = ... |
def to_directory(file_name, WIDTH, HEIGHT, tmp_dir, start_frame=None, end_frame=None):
if os.path.isdir(file_name):
for img_file in os.listdir(file_name):
if img_file.endswith('.png'):
img_index = int(img_file.split('.')[0])
if ((img_index >= (start_frame + 1)) an... |
def optimize_pb_model_command(input_pb_file, output_pb_file):
try:
import tensorflow as tf
from tensorflow.python.platform import gfile
from nnabla.utils.converter.tensorflow.common import OptimizePb
except ImportError:
raise ImportError('nnabla_converter python package is not fo... |
class CosineAnnealingRestartCyclicLR(_LRScheduler):
def __init__(self, optimizer, periods, restart_weights=(1,), eta_mins=(0,), last_epoch=(- 1)):
self.periods = periods
self.restart_weights = restart_weights
self.eta_mins = eta_mins
assert (len(self.periods) == len(self.restart_weig... |
class ManinSymbolList_gamma0(ManinSymbolList_group):
def __init__(self, level, weight):
ManinSymbolList_group.__init__(self, level, weight, p1list.P1List(level))
def __repr__(self):
return ('Manin Symbol List of weight %s for Gamma0(%s)' % (self.weight(), self.level())) |
class SeqCategoryIDColumn(CategoryColumn):
def __init__(self, field_desc, bucket_size):
assert isinstance(field_desc, FieldDesc)
self.field_desc = field_desc
self.bucket_size = bucket_size
def get_field_desc(self):
return [self.field_desc]
def new_feature_column_from(self, fi... |
def __getattr__(name):
return _sub_module_deprecation(sub_package='spatial', module='ckdtree', private_modules=['_ckdtree'], all=__all__, attribute=name) |
def get_model_value_fn_policy(model, sim_threads, boltzmann_rationality=1):
v_fn = get_model_value_fn(model, sim_threads)
def v_policy(mdp_state, mdp, agent_index):
successor_vals = []
for a in Action.INDEX_TO_ACTION:
joint_action = ((a, Direction.STAY) if (agent_index == 0) else (Di... |
def register_Ns3OlsrMprSelectorTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_constructor([])
cls.add_constructor([param('ns3::olsr::MprSelectorTuple const &', 'arg0')])
cls.add_instance_attribute('expirationTime', 'ns3::Time', is_const=False)
cls.add_instance_attr... |
class SDConvectTerm(Term):
name = 'ev_sd_convect'
arg_types = ('parameter_u', 'parameter_w', 'parameter_mv')
arg_shapes = {'parameter_u': 'D', 'parameter_w': 'D', 'parameter_mv': 'D'}
function = staticmethod(terms.d_sd_convect)
def get_fargs(self, par_u, par_w, par_mv, mode=None, term_mode=None, dif... |
class deV(Sersic):
def __init__(self, x=None, y=None, q=None, pa=None, re=None, amp=None):
Sersic.__init__(self, x, y, q, pa, re, amp, 4.0) |
def inference_pytorch(args, cfg, distributed, data_loader):
if (args.average_clips is not None):
if ((cfg.model.get('test_cfg') is None) and (cfg.get('test_cfg') is None)):
cfg.model.setdefault('test_cfg', dict(average_clips=args.average_clips))
elif (cfg.model.get('test_cfg') is not Non... |
class KNNOperation(Function):
def forward(ctx, pointsa, pointsb, knn):
nnidx = pl.knn_points(pointsa.contiguous(), pointsb.contiguous(), knn)
return nnidx |
def find_available_plugins(loaded=False):
active_plugins = set()
for plugin_func in plugin_store.values():
for (plugin, func) in plugin_func:
active_plugins.add(plugin)
d = {}
for plugin in plugin_provides:
if ((not loaded) or (plugin in active_plugins)):
d[plugin... |
def arch_mnasnet_small(variant, feat_multiplier=1.0, **kwargs):
arch_def = [['ds_r1_k3_s1_c8'], ['ir_r1_k3_s2_e3_c16'], ['ir_r2_k3_s2_e6_c16'], ['ir_r4_k5_s2_e6_c32_se0.25'], ['ir_r3_k3_s1_e6_c32_se0.25'], ['ir_r3_k5_s2_e6_c88_se0.25'], ['ir_r1_k3_s1_e6_c144']]
model_kwargs = dict(block_defs=decode_arch_def(arc... |
class ClassMemDataLoader():
def __init__(self, dataset, batch_size, drop_last=False, device='cuda'):
self.device = device
self.batch_size = batch_size
self.dataset = dataset
self.data = [d[0].to(device) for d in dataset]
self.targets = torch.tensor(dataset.targets, dtype=torc... |
class InferCell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(InferCell, self).__init__()
print(C_prev_prev, C_prev, C)
if (reduction_prev is None):
self.preprocess0 = Identity()
elif reduction_prev:
self.pr... |
def ensure_config(impdb: str, branch: str, update: bool) -> bool:
path = config_directory()
if ((((path / branch) / impdb) / '_meta.json').exists() and (not update)):
return True
obsolete = is_obsolete(impdb, branch)
if ((((path / branch) / impdb) / '_meta.json').exists() and (not obsolete)):
... |
class MemoryViewSliceNode(MemoryViewIndexNode):
is_memview_slice = True
is_ellipsis_noop = False
is_memview_scalar_assignment = False
is_memview_index = False
is_memview_broadcast = False
def analyse_ellipsis_noop(self, env, getting):
self.is_ellipsis_noop = all(((index.is_slice and inde... |
def data_parallel(f, input, params, mode, device_ids, output_device=None):
device_ids = list(device_ids)
if (output_device is None):
output_device = device_ids[0]
if (len(device_ids) == 1):
return f(input, params, mode)
params_all = Broadcast.apply(device_ids, *params.values())
param... |
class SemistandardSkewTableaux_all(SemistandardSkewTableaux):
def __init__(self, max_entry):
SemistandardSkewTableaux.__init__(self, category=InfiniteEnumeratedSets())
if (max_entry is None):
self.max_entry = PlusInfinity()
else:
self.max_entry = max_entry
def _re... |
class ClsCntRegHead(nn.Module):
def __init__(self, in_channel, class_num, GN=True, cnt_on_reg=True, prior=0.01):
super(ClsCntRegHead, self).__init__()
self.prior = prior
self.class_num = class_num
self.cnt_on_reg = cnt_on_reg
cls_branch = []
reg_branch = []
fo... |
def test_case109():
url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert')
headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata109), headers=headers)
print(r.conten... |
class Meld():
def init(action, target, src):
return (((jnp.int32(src) << 13) | (jnp.int32(target) << 7)) | jnp.int32(action))
def to_str(meld) -> str:
action = Meld.action(meld)
target = Meld.target(meld)
src = Meld.src(meld)
(suit, num) = ((target // 9), ((target % 9) + ... |
class AverageValueEstimationEvaluator(EvaluatorProtocol):
_episodes: Optional[Sequence[EpisodeBase]]
def __init__(self, episodes: Optional[Sequence[EpisodeBase]]=None):
self._episodes = episodes
def __call__(self, algo: QLearningAlgoProtocol, dataset: ReplayBuffer) -> float:
total_values = [... |
def ocp(F, bcs, J, y, u, p, config_ocp):
return cashocs.OptimalControlProblem(F, bcs, J, y, u, p, config=config_ocp) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.