code stringlengths 101 5.91M |
|---|
def simSetIkElementProperties(ikGroupHandle, tipDummyHandle, constraints, precision=None, weight=None):
if (precision is None):
precision = ffi.NULL
if (weight is None):
weight = ffi.NULL
reserved = ffi.NULL
ret = lib.simSetIkElementProperties(ikGroupHandle, tipDummyHandle, constraints, ... |
class Block(nn.Module):
def __init__(self, embed_dim, num_heads, down_ratio=8, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.BatchNorm2d, drop=0.0):
super().__init__()
self.norm1 = norm_layer(embed_dim)
self.attn =... |
def list_connected_datapipes(scan_obj):
f = io.BytesIO()
p = pickle.Pickler(f)
def stub_pickler(obj):
return (stub_unpickler, ())
captured_connections = []
def reduce_hook(obj):
if (obj == scan_obj):
raise NotImplementedError
else:
captured_connections... |
def apply_mask(u_hat, mask):
if (mask is not None):
if (u_hat.ndim == mask.ndim):
mask = np.broadcast_to(mask, u_hat.shape)
if (mask.ndim == 1):
u_hat = apply_mask_1D(u_hat, mask)
elif (mask.ndim == 2):
u_hat = apply_mask_2D(u_hat, mask)
... |
def filter_prediction(datasets: dict[(DevTest, list[RawData])], predictions: dict[(DevTest, dict[(str, dict)])], filtering_type: Optional[str]=None) -> tuple[(dict[(DevTest, list[RawData])], dict[(DevTest, dict[(str, dict)])])]:
if (filtering_type is None):
return (datasets, predictions)
filtered_datase... |
def test_batch_meta_dataloader_splitter():
dataset = Sinusoid(20, num_tasks=1000, noise_std=None)
dataset = ClassSplitter(dataset, num_train_per_class=5, num_test_per_class=15)
meta_dataloader = BatchMetaDataLoader(dataset, batch_size=4)
batch = next(iter(meta_dataloader))
assert isinstance(batch, d... |
('/static/css/<path:path>')
def send_css(path):
return send_from_directory(safe_join(app.config['STATIC_FOLDER'], 'css'), path) |
class ResidualBlock(nn.Module):
def __init__(self, num_filters):
super(ResidualBlock, self).__init__()
self.block = nn.Sequential(nn.ReflectionPad2d(1), nn.Conv2d(in_channels=num_filters, out_channels=num_filters, kernel_size=3, stride=1, padding=0, bias=False), nn.BatchNorm2d(num_filters), nn.ReLU(... |
def get_fashionmnist(data_path, network_config):
print('loading Fashion MNIST')
if (not os.path.exists(data_path)):
os.mkdir(data_path)
batch_size = network_config['batch_size']
transform_train = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
transfor... |
def merge_args(args, model_args):
for (k, v) in model_args.items():
if (k not in args):
args[k] = model_args[k]
return args |
def create_model_single_class(input_dim, output_dim):
model = Sequential()
model.add(Dense(12, input_dim=input_dim, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(output_dim, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accu... |
def align_bpe_to_words(roberta, bpe_tokens: torch.LongTensor, other_tokens: List[str]):
assert (bpe_tokens.dim() == 1)
def clean(text):
return text.strip()
bpe_tokens = [roberta.task.source_dictionary.string([x]) for x in bpe_tokens]
bpe_tokens = [clean((roberta.bpe.decode(x) if (x not in {'<s>'... |
def find_all_spconv_keys(model: nn.Module, prefix='') -> Set[str]:
found_keys: Set[str] = set()
for (name, child) in model.named_children():
new_prefix = (f'{prefix}.{name}' if (prefix != '') else name)
if isinstance(child, spconv.conv.SparseConvolution):
new_prefix = f'{new_prefix}.... |
def _fix_json(json_string):
json_string.replace('",\n\t\t\t\t"lane_marker": {', '",\n\t\t\t\t"markers": [')
json_lines = json_string.split('\n')
json_lines.pop(1)
json_lines.pop((- 1))
json_lines.pop((- 1))
for i in range(len(json_lines)):
if (json_lines[i] == '\t\t"lanes": {'):
... |
def remove_pretrained_embedding_params(params: Params):
keys = params.keys()
if ('pretrained_file' in keys):
del params['pretrained_file']
for value in params.values():
if isinstance(value, Params):
remove_pretrained_embedding_params(value) |
def prepare_params(kwargs):
ddpg_params = dict()
env_name = kwargs['env_name']
def make_env():
if (env_name == 'Maze'):
from envs.maze_env import MazeEnv
env = MazeEnv(n=10)
elif (env_name == 'Kitchen'):
from d4rl_alt.kitchen.kitchen_envs import KitchenMic... |
def get_sample_inputs(args):
if (args.sample_image is None):
data_loader = build_detection_test_loader(cfg, cfg.DATASETS.TEST[0])
first_batch = next(iter(data_loader))
return first_batch
else:
original_image = detection_utils.read_image(args.sample_image, format=cfg.INPUT.FORMAT)... |
class BertTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = BertToke... |
class Vocab(collections.abc.Set):
def __init__(self, iterable, special_elems=(UNK, BOS, EOS)):
elements = list(special_elems)
elements.extend(iterable)
assert (len(elements) == len(set(elements)))
self.id_to_elem = {i: elem for (i, elem) in enumerate(elements)}
self.elem_to_i... |
def create_hparams(generate_parameters=False):
data_parameters_filename = 'data_parameters.pt'
if (not generate_parameters):
if (not os.path.exists(data_parameters_filename)):
raise FileNotFoundError(('Data Normalizing file not found! ' + 'Run "python generate_data_properties.py" first'))
... |
def error_rate(y_pred, y_true, correct_on_bs=None):
if (len(y_pred.shape) > 1):
y_pred = np.asarray([np.argmax(p) for p in y_pred])
if (len(y_true.shape) > 1):
y_true = np.asarray([np.argmax(p) for p in y_true])
amount = (y_pred.shape[0] if (correct_on_bs is None) else len(correct_on_bs))
... |
class TestHypotheses(unittest.TestCase):
def test_gnad(self):
labels = ['Web', 'Panorama', 'International', 'Wirtschaft', 'Sport', 'Inland', 'Etat', 'Wissenschaft', 'Kultur']
texts = [to_hypothesis(label, 'gnad10') for label in labels]
self.assertEqual(texts, ['Das ist ein Artikel aus der Ru... |
class MobileViTMobileNetLayer(nn.Module):
def __init__(self, config: MobileViTConfig, in_channels: int, out_channels: int, stride: int=1, num_stages: int=1) -> None:
super().__init__()
self.layer = nn.ModuleList()
for i in range(num_stages):
layer = MobileViTInvertedResidual(conf... |
class F1Metric(object):
def __init__(self, multi_label=True, na_id=(- 1), ignore_na=False, print_error_prob=0, rel2id=None):
self.print_error_prob = print_error_prob
self.multi_label = multi_label
self.na_id = na_id
self.ignore_na = ignore_na
self.id2rel = None
if (re... |
def bayes_acc_check(loader):
(correct_samples, num_samples) = (0, 0)
for (_, labels, conf) in loader:
correct_samples += torch.sum((torch.max(conf, 1)[1] == labels)).item()
num_samples += labels.size(0)
return ((100 * correct_samples) / num_samples) |
def uniform_exclude_inner(np_uniform, a, b, a_i, b_i):
if (not ((a < a_i) and (b_i < b))):
raise ValueError('Bad range, inner: ({},{}), outer: ({},{})'.format(a, b, a_i, b_i))
while True:
result = np_uniform(a, b)
if (((a <= result) and (result < a_i)) or ((b_i <= result) and (result < b... |
def test_clone_nan():
clf = MyEstimator(empty=np.nan)
clf2 = clone(clf)
assert (clf.empty is clf2.empty) |
class FriCASExpectFunction(ExpectFunction):
def __init__(self, parent, name):
if name.endswith('_q'):
name = (name[:(- 2)] + '?')
elif name.endswith('_e'):
name = (name[:(- 2)] + '!')
ExpectFunction.__init__(self, parent, name) |
((not workspace.C.use_mkldnn), 'No MKLDNN support.')
class ElementwiseSumTest(hu.HypothesisTestCase):
(size=st.integers(7, 9), input_channels=st.integers(1, 3), batch_size=st.integers(1, 3), inputs=st.integers(2, 7), inplace=st.booleans(), **mu.gcs)
def test_elementwise_sum(self, size, input_channels, batch_siz... |
def scatter_inputs_and_indices(Xs: List[Any], indices: List[int], device_ids: List[int]) -> Tuple[(List[List[Any]], List[List[int]])]:
copied_Xs = deepcopy(Xs)
copied_indices = deepcopy(indices)
devices = [torch.device(f'cuda:{i}') for i in device_ids]
def _map_to_device(X: Any, device: torch.device):
... |
class AutoInt(BaseModel):
def __init__(self, linear_feature_columns, dnn_feature_columns, att_layer_num=3, att_head_num=2, att_res=True, dnn_hidden_units=(256, 128), dnn_activation='relu', l2_reg_dnn=0, l2_reg_embedding=1e-05, dnn_use_bn=False, dnn_dropout=0, init_std=0.0001, seed=1024, task='binary', device='cpu',... |
class DISTORT_TRANSFORMATIONS(Enum):
X = 'x'
Y = 'y'
PIXELATE = 'pixelate'
CONTRAST = 'contrast'
BRIGHTNESS = 'brightness' |
class SortRef(AstRef):
def as_ast(self):
return Z3_sort_to_ast(self.ctx_ref(), self.ast)
def get_id(self):
return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
def kind(self):
return _sort_kind(self.ctx, self.ast)
def subsort(self, other):
return False
def cast(self, v... |
def flat_accuracy(seq_pred, seq_labels):
m = seq_pred.argmax(axis=2)
m2 = m.flatten()
m2 = m2.detach().cpu().numpy()
l2 = seq_labels.flatten()
l2 = l2.to('cpu').numpy()
(tp, tn, fp, fn) = (0, 0, 0, 0)
for idx in range(len(m2)):
if ((l2[idx] == 1) and (m2[idx] == 1)):
tp +... |
class TranspositionCipher(SymmetricKeyCipher):
def __init__(self, parent, key):
n = parent.block_length()
if (isinstance(key, list) and (not (len(key) == n))):
raise ValueError(('key (= %s) must have block length %s' % (key, n)))
SymmetricKeyCipher.__init__(self, parent, key)
... |
class ScanTransformer(TransformerMixin, Task):
VALID_NUM_WORKERS = 0
def create_datasets(self):
self.batch_dim = 1
self.train_set = dataset.Scan(['train'], split_type=self.helper.args.scan.train_split)
self.valid_sets.val = dataset.Scan(['test'], split_type=self.helper.args.scan.train_sp... |
def main():
print('Welcome to Flappy Bird.')
args = parseArgs()
if (args.algo == 'Baseline'):
agent = BaselineAgent(actions=[0, 1], probFlap=args.probFlap)
agent.train(numIters=args.numTrainIters, evalPerIters=args.evalPerIters, numItersEval=args.numTestIters)
elif (args.algo == 'QLearni... |
def main(args):
dataset = load_dataset('seungheondoh/LP-MusicCaps-MC')
train_data = [i for i in dataset['train'] if i['is_crawled']]
test_data = [i for i in dataset['test'] if i['is_crawled']]
(_, tr_ground_truths) = inference_parsing(train_data, args.prediction_col)
(predictions, ground_truths) = i... |
def calcPubChemFingerPart2(mol):
bits = ([0] * 148)
bits = func_1(mol, bits)[1]
bits = func_2(mol, bits)[1]
bits = func_3(mol, bits)[1]
bits = func_4(mol, bits)[1]
bits = func_5(mol, bits)[1]
bits = func_6(mol, bits)[1]
bits = func_7(mol, bits)[1]
bits = func_8(mol, bits)
return ... |
def get_shape(tensor):
shape = tensor.shape
if torch.onnx.is_in_onnx_export():
shape = [i.cpu().numpy() for i in shape]
return shape |
class RandomNormalAcrobot(ModifiableAcrobotEnv):
def LINK_MASS_1(self):
return self.mass
def LINK_MASS_2(self):
return self.mass
def LINK_LENGTH_1(self):
return self.length
def LINK_LENGTH_2(self):
return self.length
def LINK_MOI(self):
return self.inertia
... |
def extract_features_from_examples(args, tokenizer, examples):
features = []
for ex in tqdm(examples, desc='Indexing', total=len(examples)):
feat = _extract_feature_from_example(args, tokenizer, ex)
features.append(feat)
return features |
def apply(operation: APIOperation, bundles: dict[(str, CaseInsensitiveDict)], connections: APIOperationConnections) -> None:
all_status_codes = list(operation.definition.resolved['responses'])
for (status_code, link) in get_all_links(operation):
target_operation = link.get_target_operation()
str... |
def test_pad_none():
assert (ak.operations.pad_none(empty, 0, axis=0).to_list() == [])
assert (ak.operations.pad_none(empty, 0, axis=1).to_list() == [])
assert (ak.operations.pad_none(empty, 0, axis=2).to_list() == [])
assert (ak.operations.pad_none(empty, 1, axis=0).to_list() == [None])
assert (ak.... |
def register_Ns3FfMacCschedSapUserCschedLcConfigCnfParameters_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::FfMacCschedSapUser::CschedLcConfigCnfParameters const &', 'arg0')])
cls.add_instance_attribute('m_logicalChannelIdentity', 'std::vector< unsigned char >', is_cons... |
def _extend_span_to_full_words(tensorizer: Tensorizer, tokens: List[int], span: Tuple[(int, int)]) -> Tuple[(int, int)]:
(start_index, end_index) = span
max_len = len(tokens)
while ((start_index > 0) and tensorizer.is_sub_word_id(tokens[start_index])):
start_index -= 1
while ((end_index < (max_l... |
def test_single_outedge_branch():
sdfg = dace.SDFG('tester')
sdfg.add_array('result', [1], dace.float64)
state1 = sdfg.add_state()
state2 = sdfg.add_state()
state2.add_edge(state2.add_tasklet('save', {}, {'out'}, 'out = 2'), 'out', state2.add_write('result'), None, dace.Memlet('result'))
sdfg.ad... |
class CheckpointEveryNEpochs(pl.Callback):
def __init__(self, save_epoch_frequency, prefix='', use_modelcheckpoint_filename=False):
self.save_epoch_frequency = save_epoch_frequency
self.prefix = prefix
self.use_modelcheckpoint_filename = use_modelcheckpoint_filename
def on_train_batch_en... |
class semantic_NCELoss(nn.Module):
def __init__(self, temperature):
super(semantic_NCELoss, self).__init__()
self.temperature = temperature
self.criterion = nn.CrossEntropyLoss()
def forward(self, k, q, pseudo_label):
logits = torch.mm(k, q.transpose(1, 0))
target = torch... |
class Function_arccoth(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'arccoth', latex_name='\\operatorname{arcoth}', conversions=dict(maxima='acoth', sympy='acoth', mathematica='ArcCoth', giac='acoth', fricas='acoth'))
def _eval_numpy_(self, x):
return arctanh((1.0 / x)) |
def test_call_if2():
A = np.random.randint(1, 10, size=(10,), dtype=np.int32)
ref = np.copy(A)
ref[0] = 0
i = 1
fib = 1
while ((fib < 50) and (i < 10)):
ref[i] = fib
fib += ref[i]
i += 1
call_if2(A)
assert np.array_equal(A, ref) |
def reset():
global pytaichi
old_kernels = pytaichi.kernels
pytaichi.clear()
pytaichi = PyTaichi(old_kernels)
for k in old_kernels:
k.reset()
_ti_core.reset_default_compile_config() |
class LinformerEncoder(RobertaEncoder):
def __init__(self, args, dictionary):
super().__init__(args, dictionary)
self.sentence_encoder = LinformerSentenceEncoder(padding_idx=dictionary.pad(), vocab_size=len(dictionary), num_encoder_layers=args.encoder_layers, embedding_dim=args.encoder_embed_dim, ff... |
class AMT():
def __init__(self, config, model_path, batch_size=1, verbose_flag=False):
if (verbose_flag is True):
print(('torch version: ' + torch.__version__))
print(('torch cuda : ' + str(torch.cuda.is_available())))
if torch.cuda.is_available():
self.device =... |
class TestFBMS(torch.utils.data.Dataset):
def __init__(self, root):
self.root = root
self.video_list = sorted(os.listdir(os.path.join(root, 'JPEGImages')))
self.to_tensor = tv.transforms.ToTensor()
def __len__(self):
return len(self.video_list)
def __getitem__(self, idx):
... |
_model
def mobilenetv3_rw(pretrained=False, **kwargs):
if pretrained:
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
model = _gen_mobilenet_v3_rw('mobilenetv3_rw', 1.0, pretrained=pretrained, **kwargs)
return model |
def randlin(start, stop, num):
lst = np.linspace(start, stop, (num + 1))[:(- 1)]
lst += np.random.uniform(low=0.0, high=(lst[1] - lst[0]), size=lst.shape)
return lst.tolist() |
class MSRVTTChoiceDataset(BaseDataset):
def __init__(self, *args, split='', **kwargs):
assert (split in ['train', 'val', 'test'])
self.split = split
if (self.split == 'train'):
Exception('no train data provided')
self.metadata = None
self.ans_lab_dict = None
... |
class ChildFilterLALR_NoPlaceholders(ChildFilter):
def __init__(self, to_include, node_builder):
self.node_builder = node_builder
self.to_include = to_include
def __call__(self, children):
filtered = []
for (i, to_expand) in self.to_include:
if to_expand:
... |
class SquadExample(object):
def __init__(self, qas_id, question_text, doc_tokens, paragraph_indices=None, orig_answer_text=None, all_answers=None, start_position=None, end_position=None, switch=None):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
... |
def test_log_softmax_noneaxis(log_softmax_x, log_softmax_expected):
x = log_softmax_x.reshape(2, 2)
expected = log_softmax_expected.reshape(2, 2)
assert_allclose(sc.log_softmax(x), expected, rtol=1e-13) |
class ProbabilisticMatrixFactorizationModel(keras.Model):
def __init__(self, num_users, num_items, embed_mf_size, lambda_weights, gaussian_variance, learning_rate=0.01, name='MF', **kwargs):
super().__init__(name=name, **kwargs)
tf.random.set_seed(42)
self.num_users = num_users
self.... |
class AmazonReviewParser():
def __call__(self, file_path: str):
for item in ElementTree.parse(file_path).getroot():
rating = int(float(item.findtext('rating')))
if ((rating == 1) or (rating == 2)):
label = 'negative'
elif ((rating == 4) or (rating == 5)):
... |
def validate_ca_bn(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(bn.is_valid)
elif isinstance(df, (pd.DataFrame, dd.DataFrame)):
if (column != ''):
... |
def make_output_format(format, ev_dir, log_suffix=''):
os.makedirs(ev_dir, exist_ok=True)
if (format == 'stdout'):
return HumanOutputFormat(sys.stdout)
elif (format == 'log'):
return HumanOutputFormat(osp.join(ev_dir, ('log%s.txt' % log_suffix)))
elif (format == 'json'):
return J... |
class ModelLogger(object):
def __init__(self, config, dirname=None, pretrained=None):
self.config = config
if (dirname is None):
if (pretrained is None):
raise Exception('Either --dir or --pretrained needs to be specified.')
self.dirname = pretrained
e... |
def infer(nlu1, table_name, data_table, path_db, db_name, model, model_bert, bert_config, max_seq_length, num_target_layers, beam_size=4, show_table=False, show_answer_only=False):
model.eval()
model_bert.eval()
engine = DBEngine(os.path.join(path_db, f'{db_name}.db'))
nlu = [nlu1]
nlu_t1 = tokenize... |
class Encoder(nn.Module):
def __init__(self, attn_layers, conv_layers=None, norm_layer=None):
super(Encoder, self).__init__()
self.attn_layers = nn.ModuleList(attn_layers)
self.conv_layers = (nn.ModuleList(conv_layers) if (conv_layers is not None) else None)
self.norm = norm_layer
... |
class Dataset(Generic[T_co]):
def __getitem__(self, index) -> T_co:
raise NotImplementedError
def __add__(self, other: 'Dataset[T_co]') -> 'ConcatDataset[T_co]':
return ConcatDataset([self, other]) |
def test_logsumexp_b_shape():
a = np.zeros((4, 1, 2, 1))
b = np.ones((3, 1, 5))
logsumexp(a, b=b) |
def get_data(args):
print('==> Preparing data..')
(clean_trainset, clean_trainloader, testset, testloader) = _baseset_picker(args)
(trainset, trainloader) = _dataset_picker(args, clean_trainset)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
return (trainl... |
class Transformer(Module):
def __init__(self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation='relu', custom_encoder=None, custom_decoder=None):
super(Transformer, self).__init__()
if (custom_encoder is not None):
self.encod... |
def test():
array = ak.Array([[0, 1, 2, 3], [3, 3, 3, 2, 1]])
is_valid = (array != 3)
assert (ak.operations.mask(array, is_valid).to_list() == [[0, 1, 2, None], [None, None, None, 2, 1]])
assert (ak.operations.sort(ak.operations.mask(array, is_valid)).to_list() == [[0, 1, 2, None], [1, 2, None, None, No... |
def conv_module(net, num_res_layers, num_kernels, reuse=None, scope=None):
with tf.variable_scope(scope, 'conv', [net], reuse=reuse):
if (scope == 'conv1'):
for i in range(len(num_kernels)):
with tf.variable_scope(('layer_%d' % i), reuse=reuse):
net = slim.con... |
def parse_dir(path_to_dir):
files = sorted(glob((path_to_dir + '/*')))
set_name = path_to_dir.split('/')[(- 1)]
nls = {}
skip = 0
for file in tqdm(files, 'parsing {}'.format(path_to_dir)):
(tree, nl) = parse(file)
nl = clean_nl(nl)
if is_invalid_com(nl):
skip += 1... |
def save_checkpoint_best_only(state, dir='checkpoints/', name='checkpoint'):
os.makedirs(dir, exist_ok=True)
best_filename = os.path.join(dir, (name + '_model_best.pth'))
torch.save(state, best_filename) |
class ThompsonSamplerFromTrajectory(ThompsonSampler[HasTrajectorySampler]):
def sample(self, model: ProbabilisticModel, sample_size: int, at: TensorType, select_output: Callable[([TensorType], TensorType)]=select_nth_output) -> TensorType:
tf.debugging.assert_positive(sample_size)
tf.debugging.asser... |
def pascal_palette():
palette = {(0, 0, 0): 0, (128, 0, 0): 1, (0, 128, 0): 2, (128, 128, 0): 3, (0, 0, 128): 4, (128, 0, 128): 5, (0, 128, 128): 6, (128, 128, 128): 7, (64, 0, 0): 8, (192, 0, 0): 9, (64, 128, 0): 10, (192, 128, 0): 11, (64, 0, 128): 12, (192, 0, 128): 13, (64, 128, 128): 14, (192, 128, 128): 15, (... |
class Function_log1(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'log', latex_name='\\log', conversions=dict(maxima='log', fricas='log', mathematica='Log', giac='ln')) |
def insert_node_before_node(graph: Graph, node_to_insert: BaseNode, last_node: BaseNode):
first_nodes = graph.get_prev_nodes(last_node)
if (len(first_nodes) != 1):
Logger.error('Can only insert if there is only one input')
first_node = first_nodes[0]
insert_node_between_two_nodes(graph, node_to_... |
def Seg_Model(num_classes, criterion=None, pretrained_model=None):
model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes, criterion)
if (pretrained_model is not None):
model = load_model(model, pretrained_model)
return model |
def eval_(pred_path, gt_path, classes, txt_file):
pred_path = pred_path
gt_path = gt_path
with open(txt_file) as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
output_list = []
label_list = []
for (i, file) in enumerate(lines):
print(i)
file_name = (f... |
class ThreeCropsTransform():
def __init__(self, trans_weak, trans_strong0, trans_strong1):
self.trans_weak = trans_weak
self.trans_strong0 = trans_strong0
self.trans_strong1 = trans_strong1
def __call__(self, x):
x1 = self.trans_weak(x)
x2 = self.trans_strong0(x)
... |
class StatementFilter():
def __init__(self):
self._in_declare = False
self._in_dbldollar = False
self._is_create = False
self._begin_depth = 0
def _reset(self):
self._in_declare = False
self._in_dbldollar = False
self._is_create = False
self._begin... |
def AA(A, edge_index, batch_size=100000):
multiplier = (1 / np.log(A.sum(axis=0)))
multiplier[np.isinf(multiplier)] = 0
A_ = A.multiply(multiplier).tocsr()
link_loader = DataLoader(range(edge_index.size(1)), batch_size)
scores = []
for ind in link_loader:
(src, dst) = (edge_index[(0, ind... |
def fit_nn_potentials(model, x, y, lr=0.001, num_epochs=10, minibatch_size=256, use_cuda=False):
solver = torch.optim.Adam(model.parameters(), lr=lr)
iterator = Shuffle(x, y, minibatch_size)
model.train()
for epoch in range(num_epochs):
n = 0
loss_accum = 0
acc = 0
for (x... |
def run(plotIt=True):
mesh = discretize.TensorMesh([10])
VGparams = richards.empirical.VanGenuchtenParams()
leg = []
for p in dir(VGparams):
if (p[0] == '_'):
continue
leg += [p]
params = getattr(VGparams, p)
(k_fun, theta_fun) = richards.empirical.van_genucht... |
def iterate_function(outputs, side):
funcs = []
def visitor(f):
if (f.name != 'Sink'):
funcs.append(f)
if isinstance(outputs, nn.Variable):
outputs.visit(visitor)
else:
y = F.sink(*outputs)
y.visit(visitor)
for f in funcs:
(yield f) |
class ThresholdParameter(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _THRESHOLDPARAMETER |
def check(input):
output = (torch.from_numpy(input) if (type(input) == np.ndarray) else input)
return output |
class A002620(SloaneSequence):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
def _repr_(self):
return 'Quarter-squares: floor(n/2)*ceiling(n/2). Equivalently, floor(n^2/4).'
def _eval(self, n):
return ZZ(((n ** 2) // 4)) |
def test_ebsb():
dims = {'B': 2, 'J': 32, 'N': 8}
reduce_dim = 'B'
warp_reduce_dim = 'J'
non_reduce_dim = 'N'
base_layout = ''.join(dims.keys())
inp = np.ascontiguousarray(np.random.rand(*dims.values()), dtype='float16')
scale = np.ascontiguousarray(np.random.rand(dims[non_reduce_dim]), dtyp... |
def update_nested_dict(cfg: dict, keys: List[str], value: Optional[str]):
if value:
for key in keys[:(- 1)]:
cfg = cfg.setdefault(key, {})
cfg[keys[(- 1)]] = value |
def test_rrdbnet_backbone():
net = RRDBNet(in_channels=3, out_channels=3, mid_channels=8, num_blocks=2, growth_channels=4, upscale_factor=4)
net.init_weights(pretrained=None)
input_shape = (1, 3, 12, 12)
img = _demo_inputs(input_shape)
output = net(img)
assert (output.shape == (1, 3, 48, 48))
... |
class Resize(object):
def __init__(self, size: tuple=(512, 512)):
self.size = size
def __call__(self, img, mask):
assert (img.size == mask.size)
return (img.resize(self.size, Image.BICUBIC), mask.resize(self.size, Image.NEAREST)) |
()
def convolutional_model_without_final_activation(random_data):
(x, y) = random_data
model = tf.keras.Sequential([tf.keras.layers.Conv2D(16, (3, 3), activation=None, name='conv_1', input_shape=list(x.shape[1:])), tf.keras.layers.ReLU(name='activation_1'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(2)])
... |
def fan_isomorphism_generator(fan1, fan2):
if (not fan_isomorphic_necessary_conditions(fan1, fan2)):
return
graph1 = fan1.vertex_graph()
graph2 = fan2.vertex_graph()
graph_iso = graph1.is_isomorphic(graph2, edge_labels=True, certificate=True)
if (not graph_iso[0]):
return
graph_i... |
def etl_sk_omop_program() -> None:
parser = argparse.ArgumentParser(description='An extraction tool for SK-OMOP sources')
parser.add_argument('omop_source', type=str, help='Path of the folder to the omop source')
parser.add_argument('target_location', type=str, help='The place to store the extract')
par... |
def test_temperature_scaling_bad_input_type():
ts = TemperatureCalibration()
x_train = [[1, 1], [2, 3.5]]
y_train = [[0.9, 0.1], [0.2, 0.8]]
x_val = [[0, 2]]
y_val = [[0.8, 0.2]]
with pytest.raises(ValueError):
ts.fit(x_train=None, y_train=np.array(y_train))
with pytest.raises(ValueE... |
class LLama2Int8Engine(CausalEngine):
config_name: str = 'llama2_int8_engine'
def __init__(self, weights_path: Optional[Union[(str, Path)]]=None):
super().__init__(model_name='daryl149/llama-2-7b-chat-hf', weights_path=weights_path, load_8bit=True, trust_remote_code=True)
self.tokenizer.pad_toke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.