code stringlengths 101 5.91M |
|---|
class LinearElasticYPADTerm(Term):
name = 'dw_lin_elastic_yp_ad'
arg_types = (('material_1', 'material_2', 'virtual', 'state'),)
arg_shapes = {'material_1': '1, 1', 'material_2': '1, 1', 'virtual': ('D', 'state'), 'state': 'D'}
modes = ('weak',)
diff_info = {'material_1': 1, 'material_2': 1}
def... |
class Accumulator():
def __init__(self):
self.count = 0
self.accum = None
def __call__(self, x):
self.count += 1
if (self.accum is None):
self.accum = np.array(x)
else:
self.accum += x |
def test_restore_state(files, seq_len):
batch_size = (32, 16)
n_batches = 32
loader_train_iter = create_iterator_from_tfrecords_files(files, seq_len=seq_len, batch_size=batch_size)
for _ in range(n_batches):
next(loader_train_iter)
check_sample = next(loader_train_iter)
loader_train_iter... |
class GimpPaletteFile():
rawmode = 'RGB'
def __init__(self, fp):
self.palette = [(o8(i) * 3) for i in range(256)]
if (fp.readline()[:12] != b'GIMP Palette'):
raise SyntaxError('not a GIMP palette file')
for i in range(256):
s = fp.readline()
if (not s)... |
def sorting_keys(element):
x = element._x
P = x.parent()
CR = P.cohomology_raw(x.degree())
V = CR.V()
return list(CR(V(x.basis_coefficients()))) |
def remove_intensity_images(path):
for filename in glob.iglob((path + '**/*/photo/*_intensity.jpg'), recursive=True):
os.remove(filename)
for filename in glob.iglob((path + '**/*/photo/*_resized.jpg'), recursive=True):
os.remove(filename) |
def tokenize(src_file: str, tgt_file: str, tokenizer: Tokenizer, split: str, annotator: Optional[str]=None, batch_size=100, max_position=1024, max_tgt_position=256, save_to_file=True, datadir: Optional[str]=None) -> Dict:
def tokenize_batch(batched, data):
src_docs = tokenizer.pipe([x[1] for x in batched], ... |
def load_tf_weights_in_transfo_xl(*args, **kwargs):
requires_pytorch(load_tf_weights_in_transfo_xl) |
def __getattr__(name):
return _sub_module_deprecation(sub_package='signal', module='waveforms', private_modules=['_waveforms'], all=__all__, attribute=name) |
def main(args):
out_dir = args.output
with open(args.config, 'r') as f:
cfg = json.loads(f.read())
makedirs(out_dir, exist_ok=True)
copy(args.config, out_dir)
expt_cfg = cfg['expt']
model_cfg = cfg['model']
net = BUnet(nb_ch=model_cfg['nb_ch'], nb_kers=model_cfg['nb_kers'], nb_mc=mod... |
def hdfs_preprocessed_logrecord():
path = os.path.join(TEST_DATA_PATH, 'HDFS_AD', 'HDFS_5k_preprocessed_logrecord.csv')
return LogRecordObject.load_from_csv(path) |
def get_cleva_bias_metric_specs() -> List[MetricSpec]:
demographic_categories = ['race', 'gender']
target_categories = ['adjective', 'profession']
cross_dem_target = itertools.product(demographic_categories, target_categories)
return ([MetricSpec(class_name='helm.benchmark.metrics.cleva_harms_metrics.CL... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes, namenet='ResNet', modalities=4, kmax=0.5, kmin=None, alpha=0.6, dropout=0.0):
assert (num_classes > 1), 'Number of classes must be > 1 ....[NOT OK]'
self.num_classes = num_classes
self.namenet = namenet
self.inpl... |
class Multi_Trainer_dist_OSCC(Multi_BaseTrainer_dist):
def __init__(self, args, model, loss, metrics, optimizer, config, data_loader, valid_data_loader=None, lr_scheduler=None, len_epoch=None, writer=None, visualizer=None, tokenizer=None, max_samples_per_epoch=50000):
super().__init__(args, model, loss, met... |
class PolynomialLR(_LRScheduler):
def __init__(self, optimizer, step_size, iter_warmup, iter_max, power, min_lr=0, last_epoch=(- 1)):
self.step_size = step_size
self.iter_warmup = int(iter_warmup)
self.iter_max = int(iter_max)
self.power = power
self.min_lr = min_lr
s... |
class NoMixBlock(StateDictSerializationMixin, eqx.Module):
ln_1: hnn.LayerNorm
ln_2: hnn.LayerNorm
mlp: BackpackMlp
resid_dropout1: hnn.Dropout
resid_dropout2: hnn.Dropout
def init(config: BackpackConfig, *, key) -> 'NoMixBlock':
k_mlp = jrandom.split(key, 1)[0]
ln_1 = hnn.LayerN... |
def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag, assignable, nonempty):
pos = s.position()
calling_convention = p_calling_convention(s)
if (s.sy == '*'):
s.next()
if (s.systring == 'const'):
const_pos = s.position()
s.next()
const_base = p_c... |
def _add_strip(sub_tab, full_tab, length):
if ((sum(sub_tab) + length) > sum(full_tab)):
raise ValueError('strip does not fit')
if (not sub_tab):
cliff_list = []
else:
cliff_list = [int((sub_tab[0] != full_tab[0]))]
for row in range(1, len(sub_tab)):
if (sub_tab[row] == f... |
class OutputImageGif(OutputBase):
def __init__(self, gif):
self.gif = OutputBuffer(gif)
def example(cls):
return cls(importlib.resources.read_binary(__package__, 'example.gif'))
def html_fragment(self):
b64 = bytes_to_str(base64.b64encode(self.gif.get()), 'ascii')
return '<im... |
def load_sample_json_for_exp(exp):
alg = get_alg_names(exp)[0]
exp_path = make_exp_path(alg, exp)
exp_path = os.path.join(exp_path, f'{alg}.json')
if (not os.path.exists(exp_path)):
print('No algorithms exist in the experiment directory...')
raise FileExistsError
with open(exp_path) ... |
class MisconfiguredStorageBackend(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message) |
def test_recordarray_6():
def test_recordarray_6(x):
return (2 * (x.y ** 2))
(value_jvp, jvp_grad) = jax.jvp(test_recordarray_6, (test_recordarray,), (test_recordarray_tangent,))
(value_vjp, vjp_func) = jax.vjp(test_recordarray_6, test_recordarray)
assert (ak.to_list(value_jvp) == [[[2.0], [2.0,... |
def linear(input_, output_size, with_w=False, reuse=False, name=None):
shape = input_.get_shape().as_list()
with tf.variable_scope((name or 'linear'), reuse=reuse):
try:
matrix = tf.get_variable('Matrix', [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=0.02))
... |
class Sub(Problem):
name = 'Sub'
dependencies = {}
symbols = ['-']
def generate(self):
max_num = (10 ** self.config['max_digits'])
left = random.randrange(0, max_num)
right = random.randrange(0, max_num)
if (left < right):
return (right, left)
return (... |
def open_with_intermediates(filepath, mode):
d = os.path.dirname(filepath)
if d:
if (not os.path.exists(d)):
os.makedirs(d)
elif (not os.path.isdir(d)):
raise IOError(('The file "%s" cannot be created because "%s" exists but is not a directory' % (filepath, d)))
retur... |
class FundamentalGroupGLElement(FundamentalGroupElement):
def act_on_classical_ambient(self, wt):
return wt.map_support(self.parent().action(self.value())) |
def kl_div(input, targets, reduction='batchmean'):
return F.kl_div(F.log_softmax(input, dim=1), F.softmax(targets, dim=1), reduction=reduction) |
(scope='package')
def verysimple_vpacket_collection(nb_simulation_verysimple):
spectrum_frequency = nb_simulation_verysimple.transport.spectrum_frequency.value
return VPacketCollection(rpacket_index=0, spectrum_frequency=spectrum_frequency, number_of_vpackets=0, v_packet_spawn_start_frequency=0, v_packet_spawn_... |
def get_score(cm, grouping, lambda_):
from botsim.botsim_utils.clana.optimize import calculate_score
inter_cluster_err = 0.0
weights = create_weight_matrix(grouping)
inter_cluster_err = calculate_score(cm, weights)
return ((lambda_ * inter_cluster_err) - sum(grouping)) |
class Agent(object):
def action(self, state):
return NotImplementedError()
def set_agent_index(self, agent_index):
self.agent_index = agent_index
def set_mdp(self, mdp):
self.mdp = mdp
def reset(self):
pass |
class TokenizedSequence(TokenizedLine):
def __init__(self, tokens: List[Token], max_seq_length: int, eos_token_id: int):
if (max_seq_length < 1):
err_msg = f'Cannot have zero / negative max_seq_length. Found max_seq_length == {max_seq_length}'
raise ValueError(err_msg)
if (le... |
def worst_approximated(data, est, workload, eps, prng=None):
if (prng == None):
prng = np.random
errors = np.array([])
for (ax, W) in workload:
x = data.project(ax).datavector()
xest = est.project(ax).datavector()
W = matrix.Identity(x.size)
errors = np.append(errors,... |
def test_random_blur():
results = {}
results['lq'] = np.ones((8, 8, 3)).astype(np.float32)
model = RandomBlur(params=dict(kernel_size=[41], kernel_list=['iso'], kernel_prob=[1], sigma_x=[0.2, 10], sigma_y=[0.2, 10], rotate_angle=[(- 3.1416), 3.1416]), keys=['lq'])
results = model(results)
assert (re... |
def get_info_backend():
if _torchaudio_available():
return torchaudio_info
if _sndfile_available():
return soundfile_info |
class SPPCSPC(nn.Module):
def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)):
super(SPPCSPC, self).__init__()
c_ = int(((2 * c2) * e))
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv(c_, c_, 3, 1)
self.cv4 = Conv(c_, ... |
class spark_nlp_labeling_function(base_nlp_labeling_function):
_lf_cls = SparkNLPLabelingFunction |
def register_Ns3NonCommunicatingNetDevice_methods(root_module, cls):
cls.add_constructor([param('ns3::NonCommunicatingNetDevice const &', 'arg0')])
cls.add_constructor([])
cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty,... |
def get_metadata(task: TaskType, transform: dict[(str, Any)], model: AnomalyModule) -> dict[(str, Any)]:
data_metadata = {'task': task, 'transform': transform}
model_metadata = get_model_metadata(model)
metadata = {**data_metadata, **model_metadata}
for (key, value) in metadata.items():
if isins... |
def register_op(opname, op, domain, version):
if ((domain is None) or (version is None)):
warnings.warn('ONNX export failed. The ONNX domain and/or version to register are None.')
global _registry
if (not is_registered_version(domain, version)):
_registry[(domain, version)] = {}
_registr... |
def register_Ns3MeshWifiInterfaceMac_methods(root_module, cls):
cls.add_constructor([])
cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')])
cls.add_method('CheckSupportedRates', 'bool', [param('ns3::SupportedRates', 'rates')], is_const=True)
cls.add_method('Enqueue', 'void', [param(... |
.node
class Gemm(dace.sdfg.nodes.LibraryNode):
implementations = {'pure': ExpandGemmPure, 'MKL': ExpandGemmMKL, 'OpenBLAS': ExpandGemmOpenBLAS, 'cuBLAS': ExpandGemmCuBLAS, 'rocBLAS': ExpandGemmRocBLAS, 'PBLAS': ExpandGemmPBLAS, 'FPGA1DSystolic': ExpandGemmFPGA1DSystolic}
default_implementation = None
transA... |
def find_multitokentargets(examples, split):
multitoktargs = tottargs = 0.0
for tr in examples:
tottargs += 1
if (len(tr.targetframedict) > 1):
multitoktargs += 1
tfs = set(tr.targetframedict.values())
if (len(tfs) > 1):
raise Exception('differ... |
def convert_bort_checkpoint_to_pytorch(bort_checkpoint_path: str, pytorch_dump_folder_path: str):
bort_4_8_768_1024_hparams = {'attention_cell': 'multi_head', 'num_layers': 4, 'units': 1024, 'hidden_size': 768, 'max_length': 512, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10... |
def parallel_apply(modules, inputs, kwargs_tup=None, devices=None):
assert (len(modules) == len(inputs))
if (kwargs_tup is not None):
assert (len(modules) == len(kwargs_tup))
else:
kwargs_tup = (({},) * len(modules))
if (devices is not None):
assert (len(modules) == len(devices))... |
def test_set_smart_llm_model(config: Config):
smart_llm_model = config.smart_llm_model
config.set_smart_llm_model('gpt-4-test')
assert (config.smart_llm_model == 'gpt-4-test')
config.set_smart_llm_model(smart_llm_model) |
def get_most_recent(models):
model_numbers = [(int(model.split('model.pt')[0]) if (model != 'model.pt') else 0) for model in models]
return (str(max(model_numbers)) + 'model.pt') |
def load_eth_accounts(root_path):
path = os.path.join(root_path, 'emulator_data')
filename = os.path.join(path, 'accounts.json')
if (os.path.exists(filename) is False):
getEmulatorAccounts(path, 'accounts.json')
with open(filename) as json_file:
eth_accounts = json.load(json_file)
co... |
def merge_files(paths):
data = []
for path in paths:
with open(path, 'r') as f:
data.append(f.read())
data = ''.join(data)
out_path = input('Please specify output file path: ')
with open(out_path, 'w') as f:
f.write(data)
print('Merge files done!') |
def batch_pesq(clean, noisy):
pesq_score = Parallel(n_jobs=(- 1))((delayed(pesq_loss)(c, n) for (c, n) in zip(clean, noisy)))
pesq_score = np.array(pesq_score)
if ((- 1) in pesq_score):
return None
pesq_score = ((pesq_score + 0.5) / 5)
return torch.FloatTensor(pesq_score).to('cuda') |
class ConformerLargeConfig(ConformerConfig):
encoder_dim: int = 512
decoder_dim: int = 640
num_encoder_layers: int = 17
num_attention_heads: int = 8 |
.parametrize('reference', [0.0, [0.0], [[0.0]]])
def test_divide_conquer_non_dominated_partition_bounds_raises_for_reference_with_invalid_shape(reference: SequenceN[float]) -> None:
partition = DividedAndConquerNonDominated(tf.constant([[0.0, 2.0, 1.0], [7.0, 6.0, 0.0], [9.0, 0.0, 1.0]]))
with pytest.raises(TF_... |
def grad_test_fwd(tifunc, npfunc=None):
npfunc = (npfunc or tifunc)
print(f'arch={ti.lang.impl.current_cfg().arch} default_fp={ti.lang.impl.current_cfg().default_fp}')
x = ti.field(ti.lang.impl.current_cfg().default_fp)
y = ti.field(ti.lang.impl.current_cfg().default_fp)
ti.root.dense(ti.i, 1).place... |
class TestGenerateSimpleLabelMatrix(unittest.TestCase):
def setUp(self) -> None:
self.m = 10
self.n = 1000
def _test_generate_L(self, k: int, decimal: Optional[int]=2) -> None:
np.random.seed(123)
(P, Y, L) = generate_simple_label_matrix(self.n, self.m, k)
P_emp = LFAnaly... |
_grad()
def ddim_inversion(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt=''):
ddim_latents = ddim_loop(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt)
return ddim_latents |
class CustomHelpFormatter(HelpFormatter):
def _format_action(self, action):
if (type(action) == _SubParsersAction):
msg = ''
for subaction in action._get_subactions():
msg += self._format_action(subaction)
return msg
else:
return super(... |
def scatter(tensor, devices, chunk_sizes=None, dim=0, streams=None):
return tuple(torch._C._scatter(tensor, devices, chunk_sizes, dim, streams)) |
_if_pypy
.parametrize('data_id, dataset_params, n_samples, n_features, n_targets', [(61, {'data_id': 61}, 150, 4, 1), (61, {'name': 'iris', 'version': 1}, 150, 4, 1), (2, {'data_id': 2}, 11, 38, 1), (2, {'name': 'anneal', 'version': 1}, 11, 38, 1), (561, {'data_id': 561}, 209, 7, 1), (561, {'name': 'cpu', 'version': 1}... |
def get_adv_losses(discriminator_real_outputs, discriminator_fake_outputs, kind):
if (kind == 'classic'):
loss_fn = classic_gan_losses
elif (kind == 'nonsaturating'):
loss_fn = nonsaturating_gan_losses
elif (kind == 'imbalanced-nonsaturating-0.5'):
loss_fn = (lambda r, f: imbalanced_... |
class ResidualCNN(nn.Module):
def __init__(self, in_channels, out_channels, kernel, stride, dropout, n_feats):
super(ResidualCNN, self).__init__()
self.cnn1 = nn.Conv2d(in_channels, out_channels, kernel, stride, padding=(kernel // 2))
self.cnn2 = nn.Conv2d(out_channels, out_channels, kernel,... |
class ConfusionMatrix():
def __init__(self, num_classes, class_names=None):
self.n_classes = num_classes
if (class_names is None):
self.class_names = map(str, range(num_classes))
else:
self.class_names = class_names
max_len = max(map(len, self.class_names))
... |
def get_prior(batch_size, num_points, inp_dim):
return (((torch.rand(batch_size, num_points, inp_dim) * 2) - 1.0) * 1.5) |
def download_and_extract(url, dst, remove=True):
gdown.download(url, dst, quiet=False)
if dst.endswith('.tar.gz'):
tar = tarfile.open(dst, 'r:gz')
tar.extractall(os.path.dirname(dst))
tar.close()
if dst.endswith('.tar'):
tar = tarfile.open(dst, 'r:')
tar.extractall(os... |
def r_while(tn, t):
(cond, stmt) = (t[2], t[5])
token_hit = ((tn[:2] + tn[3:5]) + tn[6:])
def fn(world, n):
if (n > MAX_FUNC_CALL):
return (token_hit, n, False)
(hit_c, n, s, c) = cond(world, n)
if (not s):
return ((token_hit + hit_c), n, s)
total_hit ... |
def remove_punctuation(in_str):
in_str = str(in_str).lower().strip()
sp_char = ['-', ':', '_', '*', '^', '/', '\\', '~', '`', '+', '=', ',', '', ':', '?', '!', '', '', ';', '', '', '', '......', '', '', '', '', '(', ')', '-', '~', '', '']
out_segs = []
for char in in_str:
if (char in sp_char):
... |
def register_Ns3OlsrDuplicateTuple_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_constructor([])
cls.add_constructor([param('ns3::olsr::DuplicateTuple const &', 'arg0')])
cls.add_instance_attribute('address', 'ns3::Ipv4Address', is_const=False)
cls.add_instance_attribut... |
def init_warprna(verbose=False):
global _tf_mod
if _tf_mod:
return
assert is_checked_out(), 'submodule not checked out? Run `git submodule update --init --recursive`'
enable_gpu = OpCodeCompiler.cuda_available()
enable_cpu = os.path.exists(('%s/core_cpu.cpp' % submodule_dir))
src_files =... |
def to_numpy(tensor):
if isinstance(tensor, np.ndarray):
return tensor
elif isinstance(tensor, torch.Tensor):
return tensor.detach().cpu().numpy()
elif isinstance(tensor, list):
return np.array(tensor)
else:
raise TypeError('Unsupported type for conversion to numpy array'... |
class Vincent(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([0.25] * self.N), ([10.0] * self.N)))
self.global_optimum = [[7. for _ in range(self.N)]]
self.fglob = (- float(self.N))
self.change_dimensionality = True... |
def test_run_ignore():
parser = _get_command_line_parser(['valid-detector'], [], [])
black_list = ['a', 'b', 'c']
result = parser.parse_args((['run', 'ex1', 'valid-detector', '--skip'] + black_list))
assert (result.black_list == black_list) |
def test_sub(Poly):
c1 = list((random((4,)) + 0.5))
c2 = list((random((3,)) + 0.5))
p1 = Poly(c1)
p2 = Poly(c2)
p3 = (p1 - p2)
assert_poly_almost_equal((p2 - p1), (- p3))
assert_poly_almost_equal((p1 - c2), p3)
assert_poly_almost_equal((c2 - p1), (- p3))
assert_poly_almost_equal((p1 ... |
def makeHeatmap(bitmap, x_ws, y_ti, vmax=None, title=None, saveas=None):
x_min = np.min(x_ws)
x_max = np.max(x_ws)
y_min = np.min(y_ti)
y_max = np.max(y_ti)
maxval = np.max(np.abs([bitmap.min(), bitmap.max()]))
if vmax:
maxval = vmax
vmin = (- maxval)
if ((title == 'Floris time')... |
def imread(path, is_grayscale=False):
if is_grayscale:
return scipy.misc.imread(path, flatten=True).astype(np.float)
else:
return scipy.misc.imread(path).astype(np.float) |
class compression_module(nn.Module):
def __init__(self, input_channel=256, hidden_channel=128, noise=10, channel=1, spatial=0):
super(compression_module, self).__init__()
self.conv1 = nn.Conv2d((input_channel + 1), hidden_channel, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(hi... |
def ClassFunction(group, values):
try:
return group.class_function(values)
except AttributeError:
pass
if isinstance(values, LibGapElement):
return ClassFunction_libgap(group, values)
return ClassFunction_gap(group, values) |
def sigmoid(x):
x = np.asarray(x, dtype=np.float64)
np.clip(x, _MIN_CLIP, _MAX_CLIP)
return (np.exp(x) / (1 + np.exp(x))) |
class GeneralEdgeAttConvVisualization(nn.Module):
def __init__(self, dim_in, dim_out, bias=False, **kwargs):
super(GeneralEdgeAttConvVisualization, self).__init__()
self.model = GeneralEdgeAttConvLayerVis(dim_in, dim_out, bias=bias)
def forward(self, batch):
batch.node_feature = self.mod... |
.parametrize('output_dims,expected_shape', [(1, [120]), (2, [24, 5]), (3, [6, 4, 5]), (4, [2, 3, 4, 5])])
def test_flatten_leading_dims_output_dims(output_dims: int, expected_shape: list[int]) -> None:
x_old = tf.random.uniform([2, 3, 4, 5])
(flat_x_old, unflatten) = flatten_leading_dims(x_old, output_dims=outp... |
def generate_image_info(img_path, images_info):
img = cv2.imread(img_path)
img_name = img_path.split('/')[(- 1)]
img_w = img.shape[1]
img_h = img.shape[0]
info = {'file_name': img_name, 'height': img_h, 'width': img_w, 'id': img_name[:(- 4)]}
images_info.append(info)
return images_info |
def linear_lognormal_size(magnitude, a_mu, b_mu, sigma, size=None):
return late_type_lognormal_size(magnitude, ((- a_mu) / 0.4), ((- a_mu) / 0.4), b_mu, (- np.inf), sigma, sigma, size=size) |
class Res50_SCAR(nn.Module):
def __init__(self, pretrained=True):
super(Res50_SCAR, self).__init__()
self.seen = 0
self.backend_feat = [512, 512, 512, 256, 128, 64]
self.frontend = []
self.backend = make_layers(self.backend_feat, in_channels=1024, dilation=True)
self.... |
class SummarizationHumanEvalAnalyzer():
def __init__(self, dataset: str, eval_download_path: str, shots: int):
self.dataset = dataset
self.eval_download_path = eval_download_path
self.shots = shots
os.makedirs(eval_download_path, exist_ok=True)
self.load_humaneval_data()
... |
def memory_none(agent_test_config: Config, mock_get_embedding):
was_memory_backend = agent_test_config.memory_backend
agent_test_config.set_memory_backend('no_memory')
(yield get_memory(agent_test_config))
agent_test_config.set_memory_backend(was_memory_backend) |
def test_symbols():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
assert (symbols('x') == x)
assert (symbols('x ') == x)
assert (symbols(' x ') == x)
assert (symbols('x,') == (x,))
assert (symbols('x, ') == (x,))
assert (symbols('x ,') == (x,))
assert (symbols('x , y') == (x, y... |
class SegformerLayer(nn.Module):
def __init__(self, config, hidden_size, num_attention_heads, drop_path, sequence_reduction_ratio, mlp_ratio):
super().__init__()
self.layer_norm_1 = nn.LayerNorm(hidden_size)
self.attention = SegformerAttention(config, hidden_size=hidden_size, num_attention_h... |
class Environment():
def __init__(self, use_offline_controller, grid_size=0.25, fov=100.0, offline_data_dir='/tmp/data_dhm/AI2thor_Dataset/Scene_Data', detection_feature_file_name='det_feature_60_categories.hdf5', images_file_name='resnet18_featuremap.hdf5', visible_object_map_file_name='visible_object_map.json', l... |
def save_args_to_json(args, output_file):
args_dict = to_dict(args)
with open(output_file, 'w') as f:
f.write(json.dumps(args_dict)) |
class GPTSanJapanesePreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
_properties
class StreamTransient(transformation.SingleStateTransformation):
with_buffer = Property(dtype=bool, default=True, desc='Use an intermediate buffer for accumulation')
tasklet = transformation.PatternNode(nodes.Tasklet)
map_exit = transformation.PatternNode(nodes.MapExit)
outer_map_exit = tran... |
def _parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--split', required=True, help='split to operate on')
args = parser.parse_args()
print('split', args.split)
return args |
class DistanceToken(ElementSetToken):
__metaclass__ = abc.ABCMeta
def __init__(self, token, classes=None):
super(DistanceToken, self).__init__(classes)
assert (token.return_type == ElementSet)
self._token = token
def _execute(self, env):
return_elems = set()
elem_set ... |
class ProphetNetPreTrainedModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class SpacyParallelismModel(Coref, SpacyModel):
def __init__(self, model):
self.model = model
def predict(self, text, a, b, pronoun_offset, a_offset, b_offset, **kwargs):
(doc, tokens, pronoun_offset, a_offset, b_offset, a_span, b_span, pronoun_token, a_tokens, b_tokens) = self.tokenize(text, a,... |
def find_array_typestr(behavior: (None | Mapping), parameters: (None | Mapping[(str, Any)]), default: (str | None)=None) -> (str | None):
if (parameters is None):
return default
behavior = overlay_behavior(behavior)
return behavior.get(('__typestr__', parameters.get('__list__')), default) |
def read_permutation(cm_file: str, perm_file: Optional[str]) -> List[int]:
if (not os.path.isfile(cm_file)):
raise ValueError(f'cm_file={cm_file} is not a file')
if ((perm_file is not None) and os.path.isfile(perm_file)):
with open(perm_file) as data_file:
if perm_file.lower().endswi... |
def register_Ns3MmWaveMacCschedSapUser_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::MmWaveMacCschedSapUser const &', 'arg0')])
cls.add_method('CschedCellConfigCnf', 'void', [param('ns3::MmWaveMacCschedSapUser::CschedCellConfigCnfParameters const &', 'params')], is_pure... |
class SpectralNorm(object):
def __init__(self, name='weight', n_power_iterations=1, dim=0, eps=1e-12):
self.name = name
self.dim = dim
if (n_power_iterations <= 0):
raise ValueError('Expected n_power_iterations to be positive, but got n_power_iterations={}'.format(n_power_iterati... |
def full_group_by(l, key=None):
if (key is None):
key = (lambda x: x)
elements = defaultdict(list)
original_keys = {}
for item in l:
k = key(item)
s = str(k)
if (s in original_keys):
if (original_keys[s] != k):
raise ValueError('two distinct el... |
def get_net_name(netlike):
if isinstance(netlike, Net):
return netlike.Proto().name
elif isinstance(netlike, caffe2_pb2.NetDef):
return netlike.name
else:
return netlike |
class AdaptiveMaxPool2d(_AdaptiveMaxPoolNd):
output_size: _size_2_opt_t
def forward(self, input: Tensor) -> Tensor:
return F.adaptive_max_pool2d(input, self.output_size, self.return_indices) |
def v1_cached_gpt3_turbo_request_v2(**kwargs):
if ('stringify_request' in kwargs):
kwargs = json.loads(kwargs['stringify_request'])
return openai.chat.completions.create(**kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.