def run_tests(data_name): test = Test() test.linear_search_grid_test(data_name) test.poly_search_grid_test(data_name) #test.precomputed_search_grid_test(data_name) test.rbf_search_grid_test(data_name) test.sigmoid_search_grid_test(data_name)
def start_tests(path='.', log_level=default_log_level): """ Function to run tests at chosen directory Params: path: string - path to chosen directory log_level?: string - one of ERROR, WARNING, INFO, SUCCESS The system logs messages with level not bigger than chosen log_level. For example if chosen level is WARNING - the system will show ERROR and WARNING messages. """ set_log_level(log_level) print_info('Starting...') tests = Test.collect_tests(path) Test.run_tests(tests) failed_tests = Test.get_failed_tests(tests) print_info('Finished!') if len(failed_tests): print_error('Not all tests successfully passed :(') print_error('Failed tests:') for test in failed_tests: print_error(test) else: print_success('All tests successfully pased!')
def test_comparison_adaptive_taylor4_tdrk4(): # define ODE t_0 = 0.0 t_fin = 3.0 ode = ODEs(y, f, dfdt, dfdt, dfdt, f_n, dfdt_n, t_0, t_fin) # define the schemes to test adapt_taylor = AdaptiveTaylor4Scheme(ode, 'taylor4') adapt_tdrk4 = AdaptiveTDRK4Scheme(ode, 'tdrk4') # define tolerances factor = 1e0 eps_abs = np.array([1e-2, 1e-4, 1e-6, 1e-8, 1e-10, 1e-12]) #eps_abs = np.array([1e-8]) eps_rel = factor * eps_abs print('% -------------------------------------------------------------------------------------------- %') print(' adaptive taylor4') print('% -------------------------------------------------------------------------------------------- %\n') test_taylor = Test(examples[example_num], test_params, adapt_taylor, 'example-') test_taylor.test_adaptive(eps_abs, eps_rel) #test_taylor.plot_results('adaptive-taylor4-') print('% -------------------------------------------------------------------------------------------- %') print(' adaptive tdrk4') print('% -------------------------------------------------------------------------------------------- %\n') test_tdrk4 = Test(examples[example_num], test_params, adapt_tdrk4, 'example-') test_tdrk4.test_adaptive(eps_abs, eps_rel) #test_tdrk4.plot_results('adaptive-tdrk4-') test_tdrk4.compare_results([test_taylor], ['tdrk4', 'taylor'], 'taylor4-tdrk4-')
def test(self, ): """ Test the generator. """ print("\nTesting...\n") num_classes = len(self.class_encoding) # We are going to use the CrossEntropyLoss loss function as it's most # frequently used in classification problems with multiple classes # which fits the problem. This criterion combines LogSoftMax and # NLLLoss. criterion = nn.CrossEntropyLoss(weight=self.class_weights) # Evaluation metric ignore_index = list(class_encoding).index('unlabeled') metric = IoU(num_classes, ignore_index=ignore_index) # Test the trained model on the test set test = Test(self.generator, self.test_loader, criterion, metric, self.device) print(">>>> Running test dataset") loss, (iou, miou) = test.run_epoch(iteration_loss=True) class_iou = dict(zip(class_encoding.keys(), iou)) print(">>>> Avg. loss: {0:.4f} | Mean IoU: {1:.4f}".format(loss, miou)) # Print per class IoU for key, class_iou in zip(class_encoding.keys(), iou): print("{0}: {1:.4f}".format(key, class_iou))
def main(config): from torch.backends import cudnn # For fast training cudnn.benchmark = True data_loader = get_loader( config.mode_data, config.image_size, config.batch_size, config.dataset_fake, config.mode, num_workers=config.num_workers, all_attr=config.ALL_ATTR, c_dim=config.c_dim) from misc.scores import set_score if set_score(config): return if config.mode == 'train': from train import Train Train(config, data_loader) from test import Test test = Test(config, data_loader) test(dataset=config.dataset_real) elif config.mode == 'test': from test import Test test = Test(config, data_loader) if config.DEMO_PATH: test.DEMO(config.DEMO_PATH) else: test(dataset=config.dataset_real)
def main(): '''main function''' parser = argparse.ArgumentParser() parser.add_argument('--state', default='test', help='train or test') parser.add_argument('--n_in', default=3, type=int, help='输入层大小') parser.add_argument('--n_hide', default=5, type=int, help='隐藏层大小') parser.add_argument('--n_out', default=1, type=int, help='输出层大小') parser.add_argument('--epoch', default=100000, type=int, help='训练次数') parser.add_argument('--lr', default=0.001, help='学习速率') parser.add_argument('--data', default='train.csv', help='训练数据集') parser.add_argument('--checkpoint', default='ckpt\\model.ckpt', help='持久化文件名') opt = parser.parse_args() print(opt) if opt.state == 'train': model = train.train_net(opt.n_in, opt.n_hide, opt.n_out, opt.checkpoint, opt.epoch, opt.lr) x, y = get_samples(opt.data, opt.n_in, opt.n_out) model.train(x, y) elif opt.state == 'test': test = Test(opt.n_in, opt.n_hide, opt.n_out, opt.checkpoint) # 14.61,13.49,22.67,17.81 x = np.array([[14.61, 13.49, 22.67]], dtype=np.float32) test.test(x) else: print('Error state, must choose from train and eval!')
def test(model, test_loader, class_weights, class_encoding): print("Testing...") num_classes = len(class_encoding) criterion = nn.CrossEntropyLoss(weight=class_weights) if use_cuda: criterion = criterion.cuda() # Evaluation metric if args.ignore_unlabeled: ignore_index = list(class_encoding).index('unlabeled') else: ignore_index = None metric = IoU(num_classes, ignore_index=ignore_index) # Test the trained model on the test set test = Test(model, test_loader, criterion, metric, use_cuda) print(">>>> Running test dataset") loss, (iou, miou) = test.run_epoch(args.print_step) class_iou = dict(zip(class_encoding.keys(), iou)) print(">>>> Avg. loss: {0:.4f} | Mean IoU: {1:.4f}".format(loss, miou)) # Print per class IoU for key, class_iou in zip(class_encoding.keys(), iou): print("{0}: {1:.4f}".format(key, class_iou))
def test_comparison_srtdrk2_mrtdrk2(): # define ODE t_0 = 0.0 t_fin = 5.0 ode = ODEs(y, f, dfdt, J_y, J_t, f_n, dfdt_n, t_0, t_fin, F, JF_y, dFdt) # define the schemes to test tdrk2_sr = AdaptiveTDRK2SingleRateScheme(ode, 'sr-tdrk2') tdrk2_mr = AdaptiveTDRK2MultiRateScheme(ode, 'mr-tdrk2') # define tolerances factor = 1e0 if examples[example_num] == 2: eps_abs = np.array([1e-2, 1e-3, 1e-4, 1e-5, 1e-6]) else: eps_abs = np.array([1e-4, 1e-5, 1e-6, 1e-7, 1e-8]) eps_rel = factor * eps_abs print('% -------------------------------------------------------------------------------------------- %') print(' adaptive tdrk2 (2 * neq function call per step)') print('% -------------------------------------------------------------------------------------------- %\n') test_sr = Test(examples[example_num], test_params, tdrk2_sr, 'system-') test_sr.test_adaptive(eps_abs, eps_rel) print('% -------------------------------------------------------------------------------------------- %') print(' multirate adaptive tdrk2') print('% -------------------------------------------------------------------------------------------- %\n') test_mr = Test(examples[example_num], test_params, tdrk2_mr, 'system-') test_mr.test_adaptive(eps_abs, eps_rel) test_sr.compare_results([test_mr], ['sr-tdrk2', 'mr-tdrk2'], 'sr-vs-mr-tdrk2-')
def __init__(self, monitor, model): self.metrics = monitor.train_metrics(model) self.lr = tf.placeholder(tf.float32, shape=[]) self.optimizer = tf.train.GradientDescentOptimizer( learning_rate=self.lr).minimize( self.metrics[monitor.train_loss_index]) self.tester = Test(monitor, model)
class TestSunrise(unittest.TestCase): def setUp(self): self.test = Test() def test_get_all_commands(self): cmd_list = map(lambda f: f.func_name, self.test.get_all_commands()) cmd_list.sort() self.assertListEqual(cmd_list, ['do_bye', 'do_hello', 'do_list_commands']) def test_parse_args_with_a_command_only(self): result1 = self.test.parse_args('hello'.split()) self.assertSequenceEqual(result1, ('hello', {'single': None, 'multiple': None}, [])) def test_parse_args_with_a_command_and_arguments(self): result1 = self.test.parse_args('hello world how are you?'.split()) self.assertSequenceEqual(result1, ('hello', {'single': None, 'multiple': None}, ['world', 'how', 'are', 'you?'])) def test_parse_args_with_a_command_and_arguments_plus_one_option(self): result1 = self.test.parse_args('--single well hello world how are you?'.split()) self.assertSequenceEqual(result1, ('hello', {'single':['well'], 'multiple': None}, ['world', 'how', 'are', 'you?'])) def test_parse_args_with_a_command_and_arguments_plus_two_options(self): result1 = self.test.parse_args('hello world how are you? --multiple well fine '.split()) self.assertSequenceEqual(result1, ('hello', {'single': None, 'multiple': ['well', 'fine']}, ['world', 'how', 'are', 'you?']))
def schedule_tester(self, cycle=TESTER_CYCLE): """定时测试代理""" test = Test() while True: print(' 测试器开始运行 ') test.run() time.sleep(cycle)
def test(model, test_loader, class_weights, class_encoding): print("\nTesting...\n") num_classes = len(class_encoding) criterion = nn.CrossEntropyLoss(weight=class_weights) # Evaluation metric if args.ignore_unlabeled: ignore_index = list(class_encoding).index('unlabeled') else: ignore_index = None metric = IoU(num_classes, ignore_index=ignore_index) # Test the trained model on the test set test = Test(model, test_loader, criterion, metric, device) print(">>>> Running test dataset") loss, (iou, miou) = test.run_epoch(iteration_loss=False) class_iou = dict(zip(class_encoding.keys(), iou)) print(">>>> Avg. loss: {0:.4f} | Mean IoU: {1:.4f}".format(loss, miou)) # Print per class IoU for key, class_iou in zip(class_encoding.keys(), iou): print("{0}: {1:.4f}".format(key, class_iou)) # Show a batch of samples and labels # if args.imshow_batch: if True: print("A batch of predictions from the test set...") images, _ = next(iter(test_loader)) predict(model, images, class_encoding)
def wrongPassword(pseudo, mdp): browser = setBrowser() test = Test(browser) test.title('Home Page') action = Action(browser) action.connection(pseudo, mdp) assert "Bibliotheque" not in browser.title browser.quit()
def test_shuzi(self): #下面三引号对方法的注释会显示在报告的表格中 '''两个数字相加以及两个数字相减''' # 对test文件中的Test类初始化 shuzi = Test(7, 3) self.assertEqual(shuzi.add(), 10) self.assertEqual(shuzi.dele(), 4)
def gain_coin(n): request_num = 10 print('Starting Request : '+ str(n) + '\n') r = Test('app', 'test', '18671188982', '123456') for v in range(request_num): print(str(n) + '--- ' + str(v) + '\n') r.get_request('/member/assets/coin') print(str(r.response_code) + '\n') print(r.response_data, '\n')
def __init__(self, dbname, dbpsd, host, user): Test.__init__(self) self.__dbName = dbname self.__dbPsd = dbpsd self.__dbHost = host self.__dbUser = user self.__dbHandle = None self.__dbCursor = None self.__dbTable = None self.m_connect()
def __init__(self): super().__init__('depth_predict') self.bridge = CvBridge() self.pub = self.create_publisher(Image, '/endoscope/image/depth', 10) self.sub = self.create_subscription(Image, '/endoscope_image', self.image_callback, 10) self.test = Test()
def delete_test(): if request.method == 'GET': return render_template('delete_test.html', tests=Test.get_all()) elif request.method == 'POST': test = Test.find(int(request.form['tests'])) test.delete() app.logger.info('Test "%s" was deleted successfully', request.form['tests']) return redirect('/homepage')
def test(model, test_loader): print("\nTesting...\n") criterion = nn.MSELoss() # Test the trained model on the test set test = Test(model, test_loader, criterion, device) print(">>>> Running test dataset") loss, (iou, miou) = test.run_epoch(args.print_step) print(">>>> Avg. loss: {0:.4f} | Mean IoU: {1:.4f}".format(loss, miou))
def __init__(self, mode): logging.debug("IOUTILS::init") # Setting mode self.mode = mode ## State to retrieve current finger's position self.currentState = State() ## init MYO self.myo = Myoutils(mode) if (self.mode == OPERATION_MODE): self.myo.startThreadMyo() ## Test helper class attribute self.test = Test(self.myo) # Initialize raspberry board GPIO.setmode(GPIO.BCM) # Initialize input elements #GPIO.setup(GPIO_INPUT_BUTTON_0, GPIO.IN) #GPIO.setup(GPIO_INPUT_BUTTON_1, GPIO.IN) #GPIO.setup(GPIO_INPUT_SWITCH_0, GPIO.IN) #GPIO.setup(GPIO_INPUT_SWITCH_1, GPIO.IN) #GPIO.setup(GPIO_INPUT_SWITCH_2, GPIO.IN) #GPIO.setup(GPIO_INPUT_SWITCH_3, GPIO.IN) # Initialize output elements GPIO.setup(GPIO_OUTPUT_LED_VBAT_OK, GPIO.OUT) GPIO.setup(GPIO_OUTPUT_LED_VBAT_LOW, GPIO.OUT) #GPIO.setup(GPIO_OUTPUT_POWER_CUT, GPIO.OUT) GPIO.setup(MOT_0_A_CTRL, GPIO.OUT) GPIO.setup(MOT_0_B_CTRL, GPIO.OUT) GPIO.setup(MOT_1_A_CTRL, GPIO.OUT) GPIO.setup(MOT_1_B_CTRL, GPIO.OUT) GPIO.setup(MOT_2_A_CTRL, GPIO.OUT) GPIO.setup(MOT_2_B_CTRL, GPIO.OUT) # Initialize PWM # TODO - Here or in fingerControl? #self.pwm = PCA9685(PCA_I2C_ADDR) #self.pwm.set_pwm_freq(PWM_FRQUENCY) #initialize ADC # TODO - Here or in fingerControl? self.adc = MCP3008(clk=GPIO_BUS_SCLK, cs=GPIO_BUS_ADC_CS, miso=GPIO_BUS_MISO, mosi=GPIO_BUS_MOSI)
def test(self): ok = True vector = Vector(5, 4, 6) result = vector.selfLength() if (result != math.sqrt(77)): ok = False Test.logError( self, " selfLength() test error:" + "\n Actual: " + str(result) + "\n Expected: " + str(math.sqrt(77))) return ok
def train(train_loader, val_loader): print("\nTraining...\n") model = SparseConvNet().to(device) criterion = nn.MSELoss(reduction='none') optimizer = optim.Adam( model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay) # Learning rate decay scheduler lr_updater = lr_scheduler.StepLR(optimizer, args.lr_decay_epochs, args.lr_decay) # Optionally resume from a checkpoint if args.resume: model, optimizer, start_epoch, best_loss = utils.load_checkpoint( model, optimizer, args.save_dir, args.name) print("Resuming from model: Start epoch = {0} " "| Best mean loss = {1:.4f}".format(start_epoch, best_loss)) else: start_epoch = 0 best_loss = 1000 # Start Training print() train = Train(model, train_loader, optimizer, criterion, device) val = Test(model, val_loader, criterion, device) for epoch in range(start_epoch, args.epochs): print(">>>> [Epoch: {0:d}] Training".format(epoch)) epoch_loss = train.run_epoch(lr_updater, args.print_step) print(">>>> [Epoch: {0:d}] Avg. loss: {1:.4f}". format(epoch, epoch_loss)) if (epoch + 1) % 1 == 0 or epoch + 1 == args.epochs: print(">>>> [Epoch: {0:d}] Validation".format(epoch)) loss = val.run_epoch(args.print_step) print(">>>> [Epoch: {0:d}] Avg. loss: {1:.4f}". format(epoch, loss)) # Save the model if it's the best thus far if loss < best_loss: print("\nBest model thus far. Saving...\n") best_loss = loss utils.save_checkpoint(model, optimizer, epoch + 1, best_loss, args) return model
def __init__(self, students, versions, discarded=[], boundaries=None, texts=None, subboundaries=None, question_discriminations=None, question_weights=None, student_locations=None): Test.__init__(self, students, versions, discarded, boundaries, texts, subboundaries, question_discriminations, question_weights, student_locations)
def main(): n = 11 k = 5 train = Train() test = Test() beta = np.zeros((k, n)) for i in range(k): beta[i] = train.solve(i + 1) test.predict(beta, k)
def test(model, test_loader, class_weights, class_encoding): print("\nTesting...\n") num_classes = len(class_encoding) if torch.cuda.is_available(): if args.cuda: device = 'cuda' if torch.cuda.device_count() > 1: model = torch.nn.DataParallel(model) torch.cuda.empty_cache() else: device = 'cpu' else: device = 'cpu' # We are going to use the CrossEntropyLoss loss function as it's most # frequentely used in classification problems with multiple classes which # fits the problem. This criterion combines LogSoftMax and NLLLoss. criterion_seg = nn.CrossEntropyLoss(weight=class_weights) #criterion_cls = nn.BCEWithLogitsLoss(weight=class_weights) criterion_cls = nn.KLDivLoss(reduction='sum') criterion = [criterion_seg, criterion_cls] # Evaluation metric if args.ignore_unlabeled: ignore_index = list(class_encoding).index('unlabeled') else: ignore_index = None metric = IoU(num_classes, ignore_index=ignore_index) # Test the trained model on the test set test = Test(model, test_loader, criterion, metric, device) print(">>>> Running test dataset") loss, (iou, miou) = test.run_epoch(args.print_step) # class_iou = dict(zip(class_encoding.keys(), iou)) print(">>>> Avg. loss: {0:.4f} | Mean IoU: {1:.4f}".format(loss, miou)) # Print per class IoU for key, class_iou in zip(class_encoding.keys(), iou): print("{0}: {1:.4f}".format(key, class_iou)) # Show a batch of samples and labels if args.imshow_batch: print("A batch of predictions from the test set...") images, _ = iter(test_loader).next() predict(model, images, class_encoding, device)
def main(): if not os.path.isdir(training_set): print("Cropping faces and making train and test sets") face = FaceDetect() face.face_return() train_test_split.split() print("Training....") train_set = Eigen(training_set) train_image_label = train_set.label_extract() train_stacked_images, mean_face = train_set.image_processing() _, eig_face = train_set.eigen_value() # selecting no of eigen faces, the first values are the largest ones no need to sort them eig_face = eig_face[:, :no_of_eigfaces] train_weights, recons_train = train_set.weights_calculation( eig_face, mean_face) # display selected eigen faces # train_set.display_data(eig_face, 'Selected Eigen faces') # # # display original images # train_set.display_data(train_stacked_images, 'Original faces') # # # display reconstructed training face # train_set.display_data(recons_train, 'reconstructed training data') print("Training finished, testing ......") test_set = Eigen(testing_set) test_image_label = test_set.label_extract() print('Original label:', test_image_label) test_stacked_images, _ = test_set.image_processing(mean_face) test_weights, recons_test = test_set.weights_calculation( eig_face, mean_face) # display original test face test_set.display_data(test_stacked_images, 'original testfaces') # display reconstructed test face test_set.display_data(recons_test, 'reconstructed test data') test = Test(train_stacked_images, train_weights, test_weights) predicted_label = test.match_index(train_image_label) print('Predicted label:', predicted_label) match_check = [ 1 if tl == pl else 0 for tl, pl in zip(test_image_label, predicted_label) ] print(match_check) print("Accuracy:", sum(match_check) / len(predicted_label))
def sprawdzWyswietlacz(): Test.runChannel(169) print("Czy wyswietalcz swieci poprawnie?") print("1) Tak") print("2) Nie") input = input() while input != "1" and input != "2": print("Czy wyswietalcz swieci poprawnie?") print("1) Tak") print("2) Nie") input = input() if input == "1": self.testsResults["display"] = True else: self.testsResults["display"] = False
def test(model, test_loader): print("\nTesting...\n") critertion = nn.MSELoss() outimage_path = os.path.join(args.data_dir, 'outimage') outaudio_path = os.path.join(args.data_dir, 'outaudio') test = Test(model, test_loader, critertion, device, outimage_path, outaudio_path) print(">>>>Running test dataset") loss = test.run_epoch(iteration_loss=True) print(">>>>Avg. loss on test data: {0:.6f}".format(loss))
def delete_question(): if request.method == 'GET': return render_template('delete_question.html', questions=Question.get_all()) elif request.method == 'POST': # id is an int, which is why conversion is necessary question = Question.find(int(request.form['questions'])) # delete tests containing the deleted question Test.delete_tests_w_deleted_question(question) question.delete() app.logger.info("Question %s was successfully deleted", request.form['question']) return redirect('/homepage')
class Train: def __init__(self, monitor, model): self.metrics = monitor.train_metrics(model) self.lr = tf.placeholder(tf.float32, shape=[]) self.optimizer = tf.train.GradientDescentOptimizer( learning_rate=self.lr).minimize( self.metrics[monitor.train_loss_index]) self.tester = Test(monitor, model) def train(self, opts, monitor, train_set, test_set, model): for bat in tq.tqdm(range(monitor.n_batch)): # Cest ici le probleme. ; batch_sample = train_set.sample(monitor.batch_size) lr = model.lr_schedule(monitor, bat) _, metrics = model.sess.run( [self.optimizer, self.metrics], feed_dict={ self.lr: lr, model.inputs: batch_sample['inputs'], model.labels: batch_sample['labels'] }) monitor.train_update(metrics) if bat % monitor.checkpoint == 0: monitor.checking(metrics) if bat % monitor.n_train_batch_epoch == 0: metrics = self.tester.valid(monitor, test_set, model) monitor.end_epoch(opts, bat, metrics, model)
def expand(self, case_filename, case_name, case_values, encoding): frontmatter = self._frontmatter(case_filename, case_values) body = self.expand_regions(self.source, case_values) assert encoding == 'utf-8' return Test(self.attribs['meta']['path'] + case_name + '.js', source=codecs.encode(frontmatter + '\n' + body, encoding))
def main(): img_files = glob.glob("oxbuild-images/*.jpg") # img_names = ['all_souls_000000', ...] # query_indices = [11, 21, ...] img_names = utils.get_images_names(img_files) query_indices = utils.get_queries(img_names) files_for_codebook = img_files for index in query_indices: del files_for_codebook[index] del img_names[index] img_names = utils.get_images_names(img_files) land_marks = ['all_souls','ashmolean','balliol','bodleian','christ_church','cornmarket','hertford','keble','magdalen','pitt_rivers','radcliffe_camera'] #64 print("leyendo codebook...") codebook = np.loadtxt("clusters64.csv", delimiter=",") print("leyendo vlad matrix...") vlad = np.loadtxt("vlad64.csv", delimiter=",") print("listo") print("vlad matrix shape: ") print(vlad.shape) test = Test(vlad,codebook,img_names,"euclidean") precisions = [] for lm in land_marks: for i in range(5): index = str(i+1) precision = test.do_query(lm + "_" + index) precisions.append(precision) print("64 euclidean map = "), print(np.average(precisions)) test = Test(vlad,codebook,img_names,"hellinger") precisions = [] for lm in land_marks: for i in range(5): index = str(i+1) precision = test.do_query(lm + "_" + index) precisions.append(precision) print("64 hellinger map = "), print(np.average(precisions))
def __init__(self, database, container, tests=None): Test.__init__(self) if tests is None: self.__tests = [ self.compare_partially_filled_test, self.compare_filled_sum_test, self.compare_filled_test, self.compare_new_sum_test, self.compare_new_test, self.compare_partially_filled_sum_test, self.compare_partially_filled_test, self.compare_rejected_sum_test, self.compare_rejected_test, self.compare_to_provider_sum_test, self.compare_to_provider_test, ] else: self.__tests = tests self.__database = database self.__container = container
def go(self): self.display("...crawling", "<b>$<b>", 'url') times = 0 while True: try: self.ghost.open(self.location) current_url, resources = self.ghost.evaluate('window.location.href') # redirect self.location = str(current_url) r = urlparse.urlparse(self.location) self.host = r.netloc # slash(r.scheme + "://" + r.netloc) self.display(self.location, "<a href='$'>$<a>", 'url') self.url_queue.append(self.location) break except TimeoutError: times = times + 1 if times == 5: self.display("TimeoutError", '<font color=red>$</font>', 'url') self.exit() self.crawler_page(self.location, 0) # url, depth # Test for url in self.url_queue: t = Test(self.ghost, url, self.mainwindow) t.test() self.exit()
def userReport(sid): path = USER_PATH+os.path.basename(sid) test = Test() if not os.path.exists(path+'/test'): return {} test.readFromFile(path+'/test') answer = Answer() if not os.path.exists(path+'/answer'): return {} answer.readFromFile(path+'/answer') test.applyAnswers(answer) ret = {} qcount = test.questionsCount() ret['QUESTION_COUNT'] = str(qcount) aqcount = test.rightAnsweredQuestionsCount() ret['ANSWERED_QUESTION_COUNT'] = str(aqcount) ret['ANSWERED_QUESTION_COUNT_PERCENT'] = str(aqcount*100/qcount) ret['TEST_TITLE'] = escape(test.caption) db_conn = sqlite3.connect(USER_DB) db_cursor = db_conn.cursor() db_cursor.execute('SELECT `date`, `name`, `result`, `rank` FROM `users` WHERE `sid`=?', (sid,)) for row in db_cursor: try: date = datetime.fromtimestamp(int(row[0])).strftime("%d.%m.%Y %H:%m") except: date = "" ret['DATE'] = date user_names = row[1].split(' ') full_user_name = user_names[0] for user_name in user_names[1:]: if len(user_name): full_user_name += " "+user_name[0]+"." ret['USER_NAME'] = escape(full_user_name) ret['TEST_RESULT'] = str(row[2]) ret['USER_RANK'] = escape(row[3]) db_cursor.close() db_conn.close() return ret
def testBinary(): k = 2 data = Data(k, 0, 0) data.importDataFromMat() data.normalize() train = TrainerValidator(k, 70, 100, 10, 0.1, 0.2, 1, data) train.trainAndClassify() train.plotResults() test = Test(train.getMLP(), data, k) test.classify() test.examples() test.plot_confusion_matrix()
def userControlTestHtml(sid): path = USER_PATH+os.path.basename(sid) test = Test() if not os.path.exists(path+'/test'): return u"Пользователь не проходил тест" test.readFromFile(path+'/test') answer = Answer() if not os.path.exists(path+'/answer'): return u"Пользователь не оправлял ответов" answer.readFromFile(path+'/answer') test.applyAnswers(answer) return test.serializeForHtml(show_hint=False)
def message_handler(message): Assert.equals("Hello world!", message['body']) Test.complete()
def vio_orchestration(oms_spec, log_dir, cluster_spec=None, tests=None): """ VIO end to end CI orchestration layer. Deploy vApp, create OpenStack cluster and run various tests. :param oms_spec: oms spec dict, see below sample. { "build": "3037963", "ova_path": "", "username": "******", "password": "******", "host_ip": "192.168.111.151", "gateway": "192.168.111.1", "netmask": "255.255.255.0", "dns": "192.168.111.1", "ntp_server": "", "omjs_properties": {"oms.use_linked_clone": "true", "oms.skip_cluster_vmotion_check": "true", "oms.disable_datastores_anti_affinity": "true"}, "patches": ["vio-patch-201_2.0.1.3309787_all.deb"], "vc_host": "192.168.111.130", "vc_user": "******", "vc_password": "******", "datacenter": "vio-datacenter", "cluster": "mgmt_cluster", "datastore": "vdnetSharedStorage", "network": "VM Network", "openstack_creds_provider": "dynamic", "ext_net_cidr": "192.168.112.0/24", "ext_net_start_ip": "192.168.112.170", "ext_net_end_ip": "192.168.112.200", "ext_net_gateway": "192.168.112.1", "public_vip_range": "192.168.112.201-192.168.112.203", "private_vip_range": "192.168.111.201-192.168.111.203" } :param log_dir: directory deployment and test logs. :param cluster_spec: dict spec for creating OpenStack cluster from oms api. :param tests: string test name separated by comma. """ LOG.debug("OMS spec: %s" % oms_spec) LOG.debug("Log path: %s" % log_dir) result = PASS vio_setup = VIO(oms_spec, cluster_spec, log_dir) vio_setup.deploy_vapp() if "omjs_properties" in oms_spec: vio_setup.config_omjs(oms_spec["omjs_properties"]) if "version" not in oms_spec: oms_spec["version"] = vio_setup.get_version() if cluster_spec: LOG.debug("Cluster spec: %s" % cluster_spec) vio_setup.deploy_openstack() if "compute_clusters" in oms_spec and len(oms_spec["compute_clusters"]) > 1: day2_compute_clusters = oms_spec["compute_clusters"][1:] for cluster in day2_compute_clusters: vio_setup.add_compute_cluster(cluster) if "patches" in oms_spec: public_vip_range = oms_utils.get_ip_range(oms_spec, "public_vip_range") private_vip_range = oms_utils.get_ip_range(oms_spec, "private_vip_range") for patch in oms_spec["patches"]: # Applying patches continuously is easy to fail. In real world, # user won't apply them like this. So sleep 3 minutes beforehand. LOG.debug("Sleep 3 minutes before patching.") time.sleep(60 * 3) vio_setup.apply_patch(patch) if "-upgrade-" in patch: public_vip = public_vip_range.next().format() private_vip = private_vip_range.next().format() cluster_spec = vio_setup.upgrade(public_vip, private_vip) if tests: LOG.debug("Tests: %s" % tests) result = Test.run_tests(tests, log_dir, oms_spec, cluster_spec) vio_setup.get_support_bundle() return result
def setUp(self): self.test = Test()
#!/usr/bin/env python from test import Test from datetime import datetime from timeit import timeit from time import sleep from time import time if __name__ == "__main__": MULTI = False t = Test() t.run() if MULTI: t.run_multi()
#!/usr/bin/env python3.4 from test import Test if __name__ == "__main__": test = Test("./test.txt") test.launch()
def __init__(self): self._logger = Util.getLogger(self.__class__.__name__) Test.__init__(self)
suite.addTest(ut.TestLoader().loadTestsFromTestCase(magnetic.MagneticTransientAxisymmetric)) # rf te suite.addTest(ut.TestLoader().loadTestsFromTestCase(rf_te.RFTEHarmonicPlanar)) suite.addTest(ut.TestLoader().loadTestsFromTestCase(rf_te.RFTEHarmonicAxisymmetric)) # rf tm suite.addTest(ut.TestLoader().loadTestsFromTestCase(rf_tm.RFTMHarmonicPlanar)) suite.addTest(ut.TestLoader().loadTestsFromTestCase(rf_tm.RFTMHarmonicAxisymmetric)) # run tests suite.run(result) from test import Test test_complete = Test(error_file='test_complete.err') # contains sets of tests obtained by varying previously present coupling tests # various combinations of hard/weak and linear/nonlinear are tested # in some couplings, the forms are the same for one of fields being steadystate or transient. # in our implementation, however, two sets of forms are present (two identical copies). # Those forms are also tested by changing steadystate problem artificaly to transient and # setting coefficients of the time derivative term to zero, thus obtaining the same results # based on test_coupling_1_planar.py test_complete.add("coupled_problems/test_coup1_curr_steady_lin_heat_steady_lin_elast_lin_weak_planar.py") test_complete.add("coupled_problems/test_coup1_curr_steady_lin_heat_trans_lin_elast_lin_weak_planar.py") test_complete.add("coupled_problems/test_coup1_curr_steady_lin_weak_with_heat_steady_lin_hard_with_elast_lin_planar.py") test_complete.add("coupled_problems/test_coup1_curr_steady_lin_weak_with_heat_steady_nl_hard_with_elast_nl_planar.py") test_complete.add("coupled_problems/test_coup1_curr_steady_nl_hard_with_heat_steady_nl_weak_with_elast_lin_planar.py") test_complete.add("coupled_problems/test_coup1_curr_steady_nl_heat_steady_nl_elast_nl_hard_planar.py")
def end_handler(): Assert.true('foo' in messages) Assert.true('bar' in messages) Assert.true('baz' in messages) Test.complete()
def load_student_data(filename): """A function that reads data from a CSV file and stores it into objects. Args: filename: Name of the file Returns: A dictionary of Grade objects. """ grades_dict = {} csv_f = open(filename, 'r') i = 0 for line in csv_f: # print "line no:", i, "=", line if i > 0: # We don't need to read the header, so # we do not read line 0 line_list = [] line_list = line.split(',') grade_number = int(line_list[0]) # Only create a grade object if it doesn't already exist if grade_number in grades_dict: grade_temp = grades_dict[grade_number] else: grade_temp = Grade(grade_number) sections_dict = grade_temp.get_sections() section_number = int(line_list[1]) # Only create a section object if it doesn't already exist # in that grade if section_number in sections_dict: section_temp = sections_dict[section_number] else: section_temp = Section(section_number) students_dict = section_temp.get_students() student_name = line_list[2] # Only create a student object if it doesn't already exist # in that section if student_name in students_dict: student_temp = students_dict[student_name] else: student_temp = Student(student_name) subjects_dict = student_temp.get_subjects() subject_name = line_list[3] # Only create a subjects object if it doesn't already exist # in that student object if subject_name in subjects_dict: subject_temp = subjects_dict[subject_name] else: subject_temp = Subject(subject_name) tests_dict = subject_temp.get_tests() test_obj = Test(line_list[4], int(line_list[5]), int(line_list[6]), line_list[7], line_list[8]) tests_dict[test_obj.get_test_name()] = test_obj subject_temp.set_tests(tests_dict) subjects_dict[subject_temp.get_subject_name()] = subject_temp student_temp.set_subjects(subjects_dict) students_dict[student_temp.get_student_name()] = student_temp section_temp.set_students(students_dict) sections_dict[section_temp.get_section_number()] = section_temp grade_temp.set_sections(sections_dict) grades_dict[grade_temp.get_grade_number()] = grade_temp # variable i tracks line numbers read i = i + 1 csv_f.close() return grades_dict
there exist natural numbers m > 1, and k > 1 such that mk = n. Your task is to check whether a given integer is a perfect power. If it is a perfect power, return a pair m and k with mk = n as a proof. Otherwise return Nothing, Nil, null, None or your language's equivalent. Note: For a perfect power, there might be several pairs. For example 81 = 3^4 = 9^2, so (3,4) and (9,2) are valid solutions. However, the tests take care of this, so if a number is a perfect power, return any pair that proves it. ''' def isPP(n): i, k = 2, 2 while i**k <= n: while i**k <= n: if i**k == n: return [i, k] k += 1 k = 2 i += 1 return test = Test() test.assert_equals(isPP(4), [2,2], "4 = 2^2") test.assert_equals(isPP(4), [2,2], "4 = 2^2") test.assert_equals(isPP(9), [3,2], "9 = 3^2") test.assert_equals(isPP(5), None, "5 isn't a perfect power") test.report()
"abcde" -> 0 # no characters repeats more than once "aabbcde" -> 2 # 'a' and 'b' "aabbcdeB" -> 2 # 'a' and 'b' "indivisibility" -> 1 # 'i' "Indivisibilities" -> 2 # 'i' and 's' ''' # first attempt def duplicate_count2(text): k = 0 for c in set(text.lower()): if text.lower().count(c) > 1: k += 1 return k # refined def duplicate_count(text): return len([c for c in set(text.lower()) if text.lower().count(c) > 1]) test = Test() test.assert_equals(duplicate_count("abcde"), 0) test.assert_equals(duplicate_count("abcdea"), 1) test.assert_equals(duplicate_count("indivisibility"), 1) test.assert_equals(duplicate_count("Indivisibilities"), 2) test.assert_equals(duplicate_count("Doggydog"), 3) test.report()
def main(): test = Test(); test.say();
def __init__(self, filename): self.BORDER = 50 Test.__init__(self, filename)
def show(self, http_handler, param, form=None): param_count = len(param) if param_count == 1: if form: #Add new test test_name = form['new_test_name'].value.decode("utf-8") test = Test(test_name) tid = http_handler.testSet.addTest(test) self.redirect(http_handler, '/edit/'+tid) else: #Show list of all available test template = Template('base.html') template.setTemplate('CONTENT', 'edit.html') template.setTemplate('INFO_BLOCK', 'admin_menue.html') template.setData('TEST_LIST', http_handler.testSet.htmlLinkList()) self.answer(http_handler, template.show()) elif param_count == 3 and param[1]=='del': http_handler.testSet.delTest(param[2]) self.redirect(http_handler, '/edit/') elif param_count == 2: if form: try: qcount = int(form['qcount'].value) except: qcount = 0 #Save modifications for test test = Test(form['caption'].value.decode("utf-8")) for i in xrange(qcount): if form.has_key('q%i'%i): try: points = int(form['p%i'%i].value) except: points = 1 if form.has_key('h%i'%i): qhint = form['h%i'%i].value.decode("utf-8") else: qhint = "" question = Question(form['q%i'%i].value.decode("utf-8"), qhint, points) try: acount = int(form['acount%i'%i].value) except: acount = 0 for a in xrange(acount): akey = 'a%i_%i'%(i, a) if form.has_key(akey): if form.has_key('r%i_%i'%(i, a)): question.addRight(form[akey].value.decode("utf-8")) else: question.addWrong(form[akey].value.decode("utf-8")) test.addQuestion(question) http_handler.testSet.replaceTest(test, param[1]) self.answer(http_handler, '<ok/>', context_type="text/xml") else: template = Template('base.html') template.setTemplate('CONTENT', 'edit_test_item.html') template.setTemplate('INFO_BLOCK', 'admin_menue.html') template.setData('TEST_NAME', param[1]) self.answer(http_handler, template.show())
import os from test import Test #http://sametmax.com/quelques-erreurs-tordues-et-leurs-solutions-en-python/ #https://stackoverflow.com/questions/33837717/systemerror-parent-module-not-loaded-cannot-perform-relative-import if __name__ == '__main__': t = Test() t.run()
def ack_handler(error): Assert.not_null(error) Test.complete()
def load_tests_from_map(tests, debugs = []): """ Loads tests from tests/tests.xml configuration file \param tests {} : Test by serial. { str: [ Test ] } \return True if loaded successfully and all tests validated """ # Load test directory tests_xml_path = os.path.join(TESTS_DIR, 'tests.xml') try: doc = minidom.parse(tests_xml_path) except IOError: print >> sys.stderr, "Could not load tests description from '%s'. IOError, file may be invalid."%(tests_xml_path) return False except Exception: print >> sys.stderr, "Could not load tests description from '%s'. Unknown exception."%(tests_xml_path) import traceback traceback.print_exc() return False # Loads tests by serial number of part test_elements = doc.getElementsByTagName('test') for tst in test_elements: if not tst.attributes.has_key('serial'): print >> sys.stderr, "Tst XML element does not have attribute \"serial\". Unable to load. XML: %s" % str(tst) return False serial = tst.attributes['serial'].value if not len(serial) == 7: print >> sys.stderr, "Serial number is invalid: %s" % serial return False if not tst.attributes.has_key('file'): print >> sys.stderr, "Test XML element does not have attribute \"file\". Unable to load. XML: %s" % str(tst) return False test_file = tst.attributes['file'].value if not tst.attributes.has_key('descrip'): print >> sys.stderr, "Test XML element does not have attribute \"descrip\". Unable to load. XML: %s" % str(tst) return False descrip = tst.attributes['descrip'].value # Mark as debug test, which allows us to run outside debug mode debug_test = tst.attributes.has_key('debug') and tst.attributes['debug'].value.lower() == "true" if debug_test: debugs.append(serial) test_path = os.path.join(os.path.join(TESTS_DIR, test_file)) test_dir = os.path.dirname(test_path) test_str = open(test_path).read() my_test = Test(descrip, serial[3:7]) try: if not my_test.load(test_str, test_dir): print >> sys.stderr, "Unable to load test %s" % descrip return False except Exception, e: print >> sys.stderr, "Unable to load test %s" % descrip import traceback traceback.print_exc() return False my_test.debug_ok = debug_test tests.setdefault(serial, []).append(my_test)
from test import Test test_coupled = Test(error_file='test_coupled_problems.err') # coupled problems test_coupled.add("coupled_problems/test_coupled_cf_1_planar.py") test_coupled.add("coupled_problems/test_coupled_cf_2_axisymmetric.py") test_coupled.add("coupled_problems/test_coupled_cf_3_axisymmetric_nonlin.py") test_coupled.add("coupled_problems/test_coupled_cf_4_transient_planar.py") # contains sets of test_coupleds obtained by varying previously present coupling test_coupleds # various combinations of hard/weak and linear/nonlinear are test_coupleded # in some couplings, the forms are the same for one of fields being steadystate or transient. # in our implementation, however, two sets of forms are present (two identical copies). # Those forms are also test_coupleded by changing steadystate problem artificaly to transient and # setting coefficients of the time derivative term to zero, thus obtaining the same results # based on test_coupled_coupling_1_planar.py test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_lin_heat_steady_lin_elast_lin_weak_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_lin_heat_trans_lin_elast_lin_weak_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_lin_weak_with_heat_steady_lin_hard_with_elast_lin_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_lin_weak_with_heat_steady_nl_hard_with_elast_nl_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_nl_hard_with_heat_steady_nl_weak_with_elast_lin_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_nl_heat_steady_nl_elast_nl_hard_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_nl_heat_steady_nl_elast_nl_weak_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_nl_heat_trans_nl_elast_nl_hard_planar.py") test_coupled.add("coupled_problems/test_coupled_coup1_curr_steady_nl_heat_trans_nl_elast_nl_weak_planar.py") # based on test_coupled_coupling_2_axisymmetric.py test_coupled.add("coupled_problems/test_coupled_coup2_mag_harm_lin_heat_steady_lin_weak_axisym.py") test_coupled.add("coupled_problems/test_coupled_coup2_mag_harm_lin_heat_trans_lin_weak_axisym.py")
def load_configs_from_map(config_files): """ Loads configuration scripts from config/configs.xml configuration file \param tests {} : Configs by serial. { str: [ Test ] } \return True if loaded successfully and all tests validated """ # Load part configuration scripts config_xml_path = os.path.join(CONFIG_DIR, 'configs.xml') try: doc = minidom.parse(config_xml_path) except IOError: print >> sys.stderr, "Could not load configuation scripts from '%s'. IOError, file may be invalid."%(config_xml_path) return False except Exception: print >> sys.stderr, "Could not load tests description from '%s'. Unknown exception."%(tests_xml_path) import traceback traceback.print_exc() return False config_elements = doc.getElementsByTagName('config') for conf in config_elements: if not conf.attributes.has_key('serial'): print >> sys.stderr, "Test XML element does not have attribute \"serial\". Unable to load. XML: %s" % str(conf) return False serial = conf.attributes['serial'].value if not len(serial) == 7: print >> sys.stderr, "Serial number is invalid: %s" % serial return False if not conf.attributes.has_key('file'): print >> sys.stderr, "Test XML element does not have attribute \"file\". Unable to load. XML: %s" % str(conf) return False test_file = conf.attributes['file'].value if not conf.attributes.has_key('descrip'): print >> sys.stderr, "Test XML element does not have attribute \"descrip\". Unable to load. XML: %s" % str(conf) return False descrip = conf.attributes['descrip'].value powerboard = True if conf.attributes.has_key('powerboard'): powerboard = conf.attributes['powerboard'].value.lower() == "true" timeout = 600 if conf.attributes.has_key('timeout'): timeout = int(conf.attributes['timeout'].value) # Generate test XML. If we need power board, add prestartup/shutdown # to turn on/off power tst = ['<test name="%s" id="%s" >' % (descrip, serial)] if powerboard: tst.append('<pre_startup name="Power On" timeout="30">scripts/power_cycle.launch</pre_startup>') tst.append('<pre_startup name="%s" timeout="%d">config/%s</pre_startup>' % (descrip, timeout, test_file)) tst.append('<subtest name="%s Test" timeout="30">config/subtest_conf.launch</subtest>' % (descrip)) if powerboard: tst.append('<shutdown name="Shutdown" timeout="30">scripts/power_board_disable.launch</shutdown>') tst.append('</test>') test_str = '\n'.join(tst) my_conf = Test(descrip, serial[3:7]) if not my_conf.load(test_str, QUAL_DIR): print >> sys.stderr, "Unable to load test %s" % descrip print >> sys.stderr, "Test XML: %s" % tst return False my_conf.debug_ok = conf.attributes.has_key('debug') and conf.attributes['debug'].value.lower() == "true" config_files.setdefault(serial, []).append(my_conf) return True
from test import Test test = Test() test.say_hello()
if now < deadline and\ (io_loop._callbacks or io_loop._timeouts): io_loop.add_timeout(now + 1, stop_loop) else: logging.info('正在关闭 IO Loop...') io_loop.stop() stop_loop() mode = tornado.options.options.mode port = tornado.options.options.port if mode == 'develop' or mode == 'product': app = create_app(mode) global http_server http_server = tornado.httpserver.HTTPServer(app) http_server.listen(port) signal.signal(signal.SIGQUIT, sig_handler) signal.signal(signal.SIGTERM, sig_handler) signal.signal(signal.SIGINT, sig_handler) print('开始以 %s 模式在 %d 端口运行 Tornado 服务...' % (mode, port)) tornado.ioloop.IOLoop.instance().start() logging.info("Tornado 服务已经彻底关闭") elif mode == 'test': test = Test() test.run()
2.0.0 07/11/2014 Dave Tan Moved all codes into a new Test Class and converted all Functions to Test Class Methods. 4.1.0 15/11/2014 Dave Tan Test based on v4.1.0 Baseline. """ #================== #1. Initialisation. #================== print("==================") print("a. Initialisation.") print("==================") from test import Test strWorkingDirectory = "F:\Python\CS4243\Project\CS4243_V4.1.0_Baseline\cs4243" strImageFileName = "project.jpeg" test = Test(strWorkingDirectory, "..\\" + strImageFileName) print("\n") #========= #2. Tests. #========= print("=========") print("2. Tests.") print("=========") print("\n") #================================== #a. Perform selected Test Scenario. #================================== print("==================================") print("a. Perform selected Test Scenario.")
def ack_handler(error=None): Assert.null(error) Test.complete()