Best Python code snippet using autotest_python
main.py
Source:main.py
1import argparse2from neural_CR.dataSet import DataGenerator3from neural_CR.dataloader import DataSampler4from neural_CR.nets import NCR5from neural_CR.models import NCRTrainer6from neural_CR.testeval import check_valid, chk_logic7import torch8import pandas as pd9import logging10logging.basicConfig()11logging.getLogger().setLevel(logging.DEBUG)12device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # set pytorch device for computation13def main():14 arg_par = argparse.ArgumentParser(description='Experiment')15 arg_par.add_argument('--threshold', type=int, default=4,16 )17 arg_par.add_argument('--order', type=bool, default=True,18 )19 arg_par.add_argument('--leave_n', type=int, default=1,20 )21 arg_par.add_argument('--keep_n', type=int, default=5,22 )23 arg_par.add_argument('--max_history_length', type=int, default=5,24 )25 arg_par.add_argument('--n_neg_train', type=int, default=1,26 )27 arg_par.add_argument('--n_neg_val_test', type=int, default=100,28 )29 arg_par.add_argument('--training_batch_size', type=int, default=128,30 )31 arg_par.add_argument('--val_test_batch_size', type=int, default=128 * 2,32 )33 arg_par.add_argument('--seed', type=int, default=2022,34 )35 arg_par.add_argument('--emb_size', type=int, default=64,36 )37 arg_par.add_argument('--dropout', type=float, default=0.0,38 )39 arg_par.add_argument('--lr', type=float, default=0.001,40 )41 arg_par.add_argument('--l2', type=float, default=0.0001,42 )43 arg_par.add_argument('--r_weight', type=float, default=0.1,44 )45 arg_par.add_argument('--val_metric', type=str, default='ndcg@5',46 )47 arg_par.add_argument('--test_metrics', type=list, default=['ndcg@5', 'ndcg@10', 'hit@5', 'hit@10'],48 )49 arg_par.add_argument('--n_epochs', type=int, default=100,50 )51 arg_par.add_argument('--early_stop', type=int, default=5,52 )53 arg_par.add_argument('--at_least', type=int, default=20,54 )55 arg_par.add_argument('--save_load_path', type=str, default="saved-models/best_model.json",56 )57 arg_par.add_argument('--n_times', type=int, default=10,58 )59 arg_par.add_argument('--dataset', type=str, default="movielens_100k",60 )61 arg_par.add_argument('--test_only', type=bool, default=False,62 )63 arg_par.add_argument('--premise_threshold', type=int, default=0,64 )65 arg_par.add_argument('--remove_double_not', type=bool, default=False,66 )67 init_args, init_extras = arg_par.parse_known_args()68 if init_args.dataset == "movielens_100k":69 raw_dataset = pd.read_csv("datasets/movielens-100k/movielens_100k.csv")70 dataset = DataGenerator(raw_dataset)71 dataset.manupulate_data(threshold=init_args.threshold, order=init_args.order, leave_n=init_args.leave_n,72 keep_n=init_args.keep_n, max_history_length=init_args.max_history_length,73 premise_threshold=init_args.premise_threshold)74 if init_args.test_only:75 pass76 else:77 t_load = DataSampler(dataset.t_set, dataset.user_item_matrix, n_neg_samples=init_args.n_neg_train,78 batch_size=init_args.training_batch_size, shuffle=True, seed=init_args.seed,79 device=device)80 v_loa = DataSampler(dataset.v_set, dataset.user_item_matrix,81 n_neg_samples=init_args.n_neg_val_test, batch_size=init_args.val_test_batch_size,82 shuffle=False, seed=init_args.seed, device=device)83 t_loa = DataSampler(dataset.test_set, dataset.user_item_matrix, n_neg_samples=init_args.n_neg_val_test,84 batch_size=init_args.val_test_batch_size, shuffle=False, seed=init_args.seed,85 device=device)86 ncr_net = NCR(dataset.all_users, dataset.all_items, emb_size=init_args.emb_size, dropout=init_args.dropout,87 seed=init_args.seed, remove_double_not=init_args.remove_double_not).to(device)88 ncr_model = NCRTrainer(ncr_net, learning_rate=init_args.lr, l2_weight=init_args.l2,89 logic_reg_weight=init_args.r_weight)90 if init_args.test_only:91 pass92 else:93 ncr_model.train(t_load, valid_data=v_loa, valid_metric=init_args.val_metric,94 valid_func=check_valid(chk_logic), num_epochs=init_args.n_epochs,95 at_least=init_args.at_least, e_stop=init_args.early_stop,96 save_path=init_args.save_load_path, verbose=1)97 ncr_model.m_load(init_args.save_load_path)98 ncr_model.test(t_loa, test_metrics=init_args.test_metrics, n_times=init_args.n_times)99if __name__ == '__main__':...
test_backends.py
Source:test_backends.py
1import asyncio2import pytest3from tamarco.core.settings.backends import EtcdSettingsBackend4from tests.functional.core.settings.conftest import settings_backends5@pytest.mark.asyncio6@pytest.mark.parametrize("settings_class,init_args", settings_backends)7async def test_settings_get(settings_class, init_args, event_loop, loaded_test_settings):8 settings = settings_class(*init_args)9 redis_port = await settings.get("redis.port")10 assert redis_port == 700611 redis_host = await settings.get("redis.host")12 assert redis_host == "127.0.0.1"13 redis_conf = await settings.get("redis")14 assert redis_conf["host"] == "127.0.0.1"15 elasticsearch = await settings.get("elasticsearch")16 assert len(elasticsearch) == 217 assert all("127.0.0.1" in x for x in elasticsearch)18 not_a_key = await settings.get("not_a_key", default=99)19 assert not_a_key == 9920@pytest.mark.asyncio21@pytest.mark.parametrize("settings_class,init_args", settings_backends)22async def test_settings_get_wrong_key(settings_class, init_args, event_loop):23 settings = settings_class(loop=event_loop, *init_args)24 with pytest.raises(KeyError):25 await settings.get("non_existing_key")26@pytest.mark.asyncio27@pytest.mark.parametrize("settings_class,init_args", settings_backends)28async def test_settings_get_multiple_dict_level(settings_class, init_args, event_loop, loaded_test_settings):29 settings = settings_class(loop=event_loop, *init_args)30 signaler = await settings.get("signaler")31 assert signaler["redis"]["port"] == 700632@pytest.mark.asyncio33@pytest.mark.parametrize("settings_class,init_args", settings_backends)34async def test_settings_set(settings_class, init_args, event_loop, add_logging):35 settings = settings_class(loop=event_loop, *init_args)36 await settings.set("redis.port", 9999)37 assert (await settings.get("redis.port")) == 999938 await settings.set("redis.host", "127.0.0.2")39 assert (await settings.get("redis.host")) == "127.0.0.2"40 await settings.set("logging.test.loggers", "StreamLogger")41 assert (await settings.get("logging.test.loggers")) == "StreamLogger"42@pytest.mark.asyncio43@pytest.mark.parametrize("settings_class,init_args", settings_backends)44async def test_settings_delete(settings_class, init_args, event_loop, loaded_test_settings):45 settings = settings_class(loop=event_loop, *init_args)46 await settings.delete("redis.port")47 with pytest.raises(KeyError):48 await settings.get("redis.port")49 await settings.delete("elasticsearch")50 with pytest.raises(KeyError):51 await settings.get("elasticsearch")52@pytest.mark.asyncio53@pytest.mark.parametrize("settings_class,init_args", settings_backends)54async def test_settings_watch_set(settings_class, init_args, event_loop):55 settings = settings_class(loop=event_loop, *init_args)56 fut = asyncio.Future()57 async def callback(key, value):58 fut.set_result((key, value))59 await settings.set("redis.port", 8888)60 await settings.watch("redis.port", callback)61 await asyncio.sleep(0.1)62 await settings.set("redis.port", 9999)63 key, value = await fut64 assert key == "redis.port"65 assert value == 999966@pytest.mark.asyncio67@pytest.mark.parametrize("settings_class,init_args", settings_backends)68async def test_settings_watch_delete(settings_class, init_args, event_loop):69 settings = settings_class(loop=event_loop, *init_args)70 fut = asyncio.Future()71 async def callback(key, value):72 fut.set_result((key, value))73 await settings.watch("redis.port", callback)74 await asyncio.sleep(0.1)75 await settings.delete("redis.port")76 key, value = await fut77 assert key == "redis.port"78 assert value is None79@pytest.mark.asyncio80async def test_etcd_settings_check_machines():81 backend = EtcdSettingsBackend({"host": "127.0.0.1", "port": 2379})...
multiple_dispatch.py
Source:multiple_dispatch.py
1# Copyright 2016 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Utilities for type-dependent behavior used in py2tf-generated code."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19import six20from tensorflow.contrib.py2tf.utils.type_check import is_tensor21from tensorflow.python.ops import control_flow_ops22def run_cond(condition, true_fn, false_fn):23 """Type-dependent functional conditional.24 Args:25 condition: A Tensor or Python bool.26 true_fn: A Python callable implementing the true branch of the conditional.27 false_fn: A Python callable implementing the false branch of the28 conditional.29 Returns:30 result: The result of calling the appropriate branch. If condition is a31 Tensor, tf.cond will be used. Otherwise, a standard Python if statement will32 be ran.33 """34 if is_tensor(condition):35 return control_flow_ops.cond(condition, true_fn, false_fn)36 else:37 return py_cond(condition, true_fn, false_fn)38def py_cond(condition, true_fn, false_fn):39 if condition:40 return true_fn()41 else:42 return false_fn()43def run_while(cond_fn, body_fn, init_args):44 """Type-dependent functional while loop.45 Args:46 cond_fn: A Python callable implementing the stop conditions of the loop.47 body_fn: A Python callable implementing the body of the loop.48 init_args: The initial values of the arguments that will be passed to both49 cond_fn and body_fn.50 Returns:51 result: A list of values with the same shape and type as init_args. If any52 of the init_args, or any variables closed-over in cond_fn are Tensors,53 tf.while_loop will be used, otherwise a Python while loop will be ran.54 Raises:55 ValueError: if init_args is not a tuple or list with one or more elements.56 """57 if not isinstance(init_args, (tuple, list)) or not init_args:58 raise ValueError(59 'init_args must be a non-empty list or tuple, found %s' % init_args)60 # TODO(alexbw): statically determine all active variables in cond_fn,61 # and pass them directly62 closure_vars = tuple(63 [c.cell_contents for c in six.get_function_closure(cond_fn) or []])64 possibly_tensors = tuple(init_args) + closure_vars65 if is_tensor(*possibly_tensors):66 return control_flow_ops.while_loop(cond_fn, body_fn, init_args)67 else:68 return py_while_loop(cond_fn, body_fn, init_args)69def py_while_loop(cond_fn, body_fn, init_args):70 state = init_args71 while cond_fn(*state):72 state = body_fn(*state)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!