Best JavaScript code snippet using unexpected
data_analysis_tool_tester.py
Source:data_analysis_tool_tester.py
1#!/Users/zhiyang/anaconda3/bin/python32###!/usr/local/bin/python33###!/Users/zhiyang/anaconda3/bin/python34"""5 This Python script is written by Zhiyang Ong to test6 miscellaneous tasks in analyzing data.7 Synopsis:8 Test the miscellaneous tasks in analyzing data.9 Revision History:10 December 15, 2017 Version 0.1, initial build.11"""12__author__ = 'Zhiyang Ong'13__version__ = '1.0'14__date__ = 'December 15, 2017'15# The MIT License (MIT)16# Copyright (c) <2014-2018> <Zhiyang Ong>17# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:18# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.19# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.20# Email address: echo "cukj -wb- 23wU4X5M589 TROJANS cqkH wiuz2y 0f Mw Stanford" | awk '{ sub("23wU4X5M589","F.d_c_b. ") sub("Stanford","d0mA1n"); print $5, $2, $8; for (i=1; i<=1; i++) print "6\b"; print $9, $7, $6 }' | sed y/kqcbuHwM62z/gnotrzadqmC/ | tr 'q' ' ' | tr -d [:cntrl:] | tr -d 'ir' | tr y "\n" Che cosa significa?21###############################################################22"""23 Import modules from The Python Standard Library.24 sys Get access to any command-line arguments.25 os Use any operating system dependent functionality.26 os.path For pathname manipulations.27 subprocess -> call28 To make system calls.29 time To measure elapsed time.30 warnings Raise warnings.31 re Use regular expressions.32 collections -> namedtuple33 To use named tuples.34 operator -> attrgetter35 To manipulate attributes of a named tuple as callable36 objects.37 statistics Module with functions for mathematical statistics38 functions.39 math Use the math.isclose(number_1,number_2) function40 to determine if the numbers "number_1" and41 "number_2" are approximately equal.42 numpy.testing43 To use numpy.testing.assert_almost_equal() function.44 + To compare if two numbers are approximately the same.45"""46#import sys47#import os48#import os.path49#from subprocess import call50#import time51import warnings52#import re53#from collections import namedtuple54#from operator import attrgetter55import statistics as s56import math57import numpy as np58"""59 To use the npt.assert_approx_equal() function.60 Or, np.testing.assert_almost_equal() function.61 Or, numpy.testing.assert_almost_equal() function.62"""63#import np.testing as npt64import numpy.testing as npt65###############################################################66# Import Custom Python Modules67"""68 Package and module to print statistics of software testing69 results.70"""71from statistics_pkg.test_statistics import statistical_analysis72"""73 Package and module to perform miscellaneous tasks in data74 analysis.75"""76from statistics_pkg.data_analysis_tool import data_analysis77###############################################################78"""79 Module that tests the methods for performing miscellaneous80 tasks in data analysis.81 Support for class instantiation is not provided, to avoid82 acquiring a collection of useless "statistical_analysis"83 objects.84 Test each static method of the "data_analysis" class.85"""86class data_analysis_tester:87 ## =========================================================88 # Method to test the method determining if each object89 # in a list is an integer or a floating-point number.90 # @param - None.91 # @return - Nothing.92 # O(n) method, where "n" is the maximum size of the lists93 # being tested.94 @staticmethod95 def test_is_list_of_numbers():96 print(" Testing is_list_of_numbers() method.")97 list_of_objs = None98 prompt = " ... Test: is_list_of_numbers(None) == False {}"99 statistical_analysis.increment_number_test_cases_used()100 if False == data_analysis.is_list_of_numbers(None):101 print(prompt .format("OK"))102 statistical_analysis.increment_number_test_cases_passed()103 else:104 print(prompt .format("FAIL!!!"))105 not_a_list_obj = data_analysis()106 prompt = " ... Test: is_list_of_numbers(not_a_list_obj) == False {}"107 statistical_analysis.increment_number_test_cases_used()108 if False == data_analysis.is_list_of_numbers(not_a_list_obj):109 print(prompt .format("OK"))110 statistical_analysis.increment_number_test_cases_passed()111 else:112 print(prompt .format("FAIL!!!"))113 prompt = " ... Test: is_list_of_numbers([]) == False {}"114 statistical_analysis.increment_number_test_cases_used()115 if False == data_analysis.is_list_of_numbers([]):116 print(prompt .format("OK"))117 statistical_analysis.increment_number_test_cases_passed()118 else:119 print(prompt .format("FAIL!!!"))120 list_not_pure_numbers_1 = [-221, 247, 0, "Ciao tutti!", 576372.32604]121 prompt = " ... Test: is_list...numb(lst_not_pure_numb_1) == False {}"122 statistical_analysis.increment_number_test_cases_used()123 if False == data_analysis.is_list_of_numbers(list_not_pure_numbers_1):124 print(prompt .format("OK"))125 statistical_analysis.increment_number_test_cases_passed()126 else:127 print(prompt .format("FAIL!!!"))128 list_not_pure_numbers_2 = ["Buona serata!"]129 prompt = " ... Test: is_list...numb(lst_not_pure_numb_2) == False {}"130 statistical_analysis.increment_number_test_cases_used()131 if False == data_analysis.is_list_of_numbers(list_not_pure_numbers_2):132 print(prompt .format("OK"))133 statistical_analysis.increment_number_test_cases_passed()134 else:135 print(prompt .format("FAIL!!!"))136 list_not_pure_numbers_3 = ["Laszlo Tabori is a world record holder!", 2673, 92.23, 7823, 10129, 478334]137 prompt = " ... Test: is_list...numb(lst_not_pure_numb_3) == False {}"138 statistical_analysis.increment_number_test_cases_used()139 if False == data_analysis.is_list_of_numbers(list_not_pure_numbers_3):140 print(prompt .format("OK"))141 statistical_analysis.increment_number_test_cases_passed()142 else:143 print(prompt .format("FAIL!!!"))144 list_not_pure_numbers_4 = [54.2, 0.232, 2439, 1392849, "Albert-László Barabási"]145 prompt = " ... Test: is_list...numb(lst_not_pure_numb_4) == False {}"146 statistical_analysis.increment_number_test_cases_used()147 if False == data_analysis.is_list_of_numbers(list_not_pure_numbers_4):148 print(prompt .format("OK"))149 statistical_analysis.increment_number_test_cases_passed()150 else:151 print(prompt .format("FAIL!!!"))152 a = data_analysis()153 b = data_analysis()154 c = data_analysis()155 list_not_pure_numbers_5 = [2247, 273805, 0.23423, 9234.2347832, "network science", a, 785398, 0.23423, b, 45678, c, "data science", 5623]156 prompt = " ... Test: is_list...numb(lst_not_pure_numb_5) == False {}"157 statistical_analysis.increment_number_test_cases_used()158 if False == data_analysis.is_list_of_numbers(list_not_pure_numbers_5):159 print(prompt .format("OK"))160 statistical_analysis.increment_number_test_cases_passed()161 else:162 print(prompt .format("FAIL!!!"))163 list_pure_numbers_1 = [4567809, 67890, 5678090, 1, 9, 436790]164 prompt = " ... Test: is_list...numb(lst_pure_pos_integers) == True {}"165 statistical_analysis.increment_number_test_cases_used()166 if True == data_analysis.is_list_of_numbers(list_pure_numbers_1):167 print(prompt .format("OK"))168 statistical_analysis.increment_number_test_cases_passed()169 else:170 print(prompt .format("FAIL!!!"))171 list_pure_numbers_2 = [-2569, -1, -62739, 0, -93, -864]172 prompt = " ... Test: is_list...numb(lst_integers_not_pos) == True {}"173 statistical_analysis.increment_number_test_cases_used()174 if True == data_analysis.is_list_of_numbers(list_pure_numbers_2):175 print(prompt .format("OK"))176 statistical_analysis.increment_number_test_cases_passed()177 else:178 print(prompt .format("FAIL!!!"))179 list_pure_numbers_3 = [-2569, -1, -62739, -0, -93, -864]180 prompt = " ... Test: is_list...numb(lst_integers_neg_0) == True {}"181 statistical_analysis.increment_number_test_cases_used()182 if True == data_analysis.is_list_of_numbers(list_pure_numbers_3):183 print(prompt .format("OK"))184 statistical_analysis.increment_number_test_cases_passed()185 else:186 print(prompt .format("FAIL!!!"))187 list_pure_numbers_4 = [0.437693, 1.3224, 346973.5679, -0.34367, -242.235623]188 prompt = " ... Test: is_list...numb(lst_pure_fp_num) == True {}"189 statistical_analysis.increment_number_test_cases_used()190 if True == data_analysis.is_list_of_numbers(list_pure_numbers_4):191 print(prompt .format("OK"))192 statistical_analysis.increment_number_test_cases_passed()193 else:194 print(prompt .format("FAIL!!!"))195 list_pure_numbers_5 = [-210.437693, -56971.3224, -9.5679, -0.45634367, -32242.235623]196 prompt = " ... Test: is_list...numb(lst_pure_neg_fp_num) == True {}"197 statistical_analysis.increment_number_test_cases_used()198 if True == data_analysis.is_list_of_numbers(list_pure_numbers_5):199 print(prompt .format("OK"))200 statistical_analysis.increment_number_test_cases_passed()201 else:202 print(prompt .format("FAIL!!!"))203 list_pure_numbers_6 = [0, 0, 0, 0, 0, 0 , 0]204 prompt = " ... Test: is_list...numb(lst_pure_0s) == True {}"205 statistical_analysis.increment_number_test_cases_used()206 if True == data_analysis.is_list_of_numbers(list_pure_numbers_6):207 print(prompt .format("OK"))208 statistical_analysis.increment_number_test_cases_passed()209 else:210 print(prompt .format("FAIL!!!"))211 list_pure_numbers_7 = [0]212 prompt = " ... Test: is_list...numb([0]) == True {}"213 statistical_analysis.increment_number_test_cases_used()214 if True == data_analysis.is_list_of_numbers(list_pure_numbers_7):215 print(prompt .format("OK"))216 statistical_analysis.increment_number_test_cases_passed()217 else:218 print(prompt .format("FAIL!!!"))219 list_pure_numbers_8 = [-56970]220 prompt = " ... Test: is_list...numb([-56970]) == True {}"221 statistical_analysis.increment_number_test_cases_used()222 if True == data_analysis.is_list_of_numbers(list_pure_numbers_8):223 print(prompt .format("OK"))224 statistical_analysis.increment_number_test_cases_passed()225 else:226 print(prompt .format("FAIL!!!"))227 list_pure_numbers_9 = [723]228 prompt = " ... Test: is_list...numb([723]) == True {}"229 statistical_analysis.increment_number_test_cases_used()230 if True == data_analysis.is_list_of_numbers(list_pure_numbers_9):231 print(prompt .format("OK"))232 statistical_analysis.increment_number_test_cases_passed()233 else:234 print(prompt .format("FAIL!!!"))235 list_pure_numbers_10 = [54869, 2.23, 0.2345, 8203, 102.23, 12, 7.23, 923]236 prompt = " ... Test: is_list...numb(lst_fp_int_only) == True {}"237 statistical_analysis.increment_number_test_cases_used()238 if True == data_analysis.is_list_of_numbers(list_pure_numbers_10):239 print(prompt .format("OK"))240 statistical_analysis.increment_number_test_cases_passed()241 else:242 print(prompt .format("FAIL!!!"))243 ## =========================================================244 # Method to test the method that accesses reference values245 # for a corresponding particular attribute/property,246 # using the Python dictionary containing pairs/2-tuples247 # of attributes/properties and values.248 # @param - None.249 # @return - Nothing.250 # O(1) method.251 @staticmethod252 def test_get_reference_value():253 print(" Testing get_reference_value() method.")254 speed_of_light = 299792458255 #prompt = " ... Test: get_reference_value(c) == 299792458 {}"256 prompt = " ... Test: get_reference_value(c) == "257 prompt = prompt + str(speed_of_light) + " {}"258 statistical_analysis.increment_number_test_cases_used()259 if speed_of_light == data_analysis.get_reference_value("c"):260 print(prompt .format("OK"))261 statistical_analysis.increment_number_test_cases_passed()262 else:263 print(prompt .format("FAIL!!!"))264 prompt = " ... Test: method with default option == "265 prompt = prompt + str(speed_of_light) + " {}"266 statistical_analysis.increment_number_test_cases_used()267 if speed_of_light == data_analysis.get_reference_value():268 print(prompt .format("OK"))269 statistical_analysis.increment_number_test_cases_passed()270 else:271 print(prompt .format("FAIL!!!"))272 standard_acceleration_due_to_gravity = 9.80665273 prompt = " ... Test: get_reference_value(g) == "274 prompt = prompt + str(standard_acceleration_due_to_gravity) + " {}"275 statistical_analysis.increment_number_test_cases_used()276 if standard_acceleration_due_to_gravity == data_analysis.get_reference_value("standard acceleration due to gravity"):277 print(prompt .format("OK"))278 statistical_analysis.increment_number_test_cases_passed()279 else:280 print(prompt .format("FAIL!!!"))281 standard_atmosphere = 101325282 prompt = " ... Test: get_reference_value(std atm) == "283 prompt = prompt + str(standard_atmosphere) + " {}"284 statistical_analysis.increment_number_test_cases_used()285 if standard_atmosphere == data_analysis.get_reference_value("standard atmosphere"):286 print(prompt .format("OK"))287 statistical_analysis.increment_number_test_cases_passed()288 else:289 print(prompt .format("FAIL!!!"))290 standard_atmosphere = 101325291 prompt = " ... Test: get_ref..._val('random string') == "292 prompt = prompt + str(standard_atmosphere) + " {}"293 statistical_analysis.increment_number_test_cases_used()294 if None == data_analysis.get_reference_value("random string"):295 print(prompt .format("OK"))296 statistical_analysis.increment_number_test_cases_passed()297 else:298 print(prompt .format("FAIL!!!"))299 ## =========================================================300 # Method to test the method that determines the actual301 # change between quantity1 and quantity2.302 # @param - None.303 # @return - Nothing.304 # O(1) method.305 @staticmethod306 def test_get_actual_change():307 print(" Testing get_actual_change() method.")308 prompt = " ... Test: default option, get_actual_change(0,0) == 0 {}"309 statistical_analysis.increment_number_test_cases_used()310 if 0 == data_analysis.get_actual_change():311 print(prompt .format("OK"))312 statistical_analysis.increment_number_test_cases_passed()313 else:314 print(prompt .format("FAIL!!!"))315 """316 non_number_object = data_analysis()317 prompt = " Test:get_act..._change(non-number_object,13.23) == None {}"318 statistical_analysis.increment_number_test_cases_used()319 if None == data_analysis.get_actual_change(non_number_object,13.23):320 print(prompt .format("OK"))321 statistical_analysis.increment_number_test_cases_passed()322 else:323 print(prompt .format("FAIL!!!"))324 prompt = " Test:get_act..._change(-7692,non-number_object) == None {}"325 statistical_analysis.increment_number_test_cases_used()326 if None == data_analysis.get_actual_change(-7692,non_number_object):327 print(prompt .format("OK"))328 statistical_analysis.increment_number_test_cases_passed()329 else:330 print(prompt .format("FAIL!!!"))331 """332 prompt = " ... Test: get_actual_change(19,13) == 6 {}"333 statistical_analysis.increment_number_test_cases_used()334 if 6 == data_analysis.get_actual_change(19,13):335 print(prompt .format("OK"))336 statistical_analysis.increment_number_test_cases_passed()337 else:338 print(prompt .format("FAIL!!!"))339 prompt = " ... Test: get_actual_change(10,14) == -4 {}"340 statistical_analysis.increment_number_test_cases_used()341 if -4 == data_analysis.get_actual_change(10, 14):342 print(prompt .format("OK"))343 statistical_analysis.increment_number_test_cases_passed()344 else:345 print(prompt .format("FAIL!!!"))346 prompt = " ... Test: get_actual_change(-20,27) == -47 {}"347 statistical_analysis.increment_number_test_cases_used()348 if -47 == data_analysis.get_actual_change(-20,27):349 print(prompt .format("OK"))350 statistical_analysis.increment_number_test_cases_passed()351 else:352 print(prompt .format("FAIL!!!"))353 prompt = " ... Test: get_actual_change(-7,-3) == -4 {}"354 statistical_analysis.increment_number_test_cases_used()355 if -4 == data_analysis.get_actual_change(-7,-3):356 print(prompt .format("OK"))357 statistical_analysis.increment_number_test_cases_passed()358 else:359 print(prompt .format("FAIL!!!"))360 prompt = " ... Test: get_actual_change(-4,-9) == 5 {}"361 statistical_analysis.increment_number_test_cases_used()362 if 5 == data_analysis.get_actual_change(-4,-9):363 print(prompt .format("OK"))364 statistical_analysis.increment_number_test_cases_passed()365 else:366 print(prompt .format("FAIL!!!"))367 prompt = " ... Test: get_actual_change(3,-4) == 7 {}"368 statistical_analysis.increment_number_test_cases_used()369 if 7 == data_analysis.get_actual_change(3,-4):370 print(prompt .format("OK"))371 statistical_analysis.increment_number_test_cases_passed()372 else:373 print(prompt .format("FAIL!!!"))374 prompt = " ... Test: get_act...(object,569) == None {}"375 statistical_analysis.increment_number_test_cases_used()376 a = data_analysis()377 if None == data_analysis.get_actual_change(a,569):378 print(prompt .format("OK"))379 statistical_analysis.increment_number_test_cases_passed()380 else:381 print(prompt .format("FAIL!!!"))382 prompt = " ... Test: get_act...(865.12,'Buona serata!') == None {}"383 statistical_analysis.increment_number_test_cases_used()384 if None == data_analysis.get_actual_change(865.12,"Buona serata!"):385 print(prompt .format("OK"))386 statistical_analysis.increment_number_test_cases_passed()387 else:388 print(prompt .format("FAIL!!!"))389 prompt = " ... Test: get_act...(97623.23,None) == None {}"390 statistical_analysis.increment_number_test_cases_used()391 if None == data_analysis.get_actual_change(97623.23,None):392 print(prompt .format("OK"))393 statistical_analysis.increment_number_test_cases_passed()394 else:395 print(prompt .format("FAIL!!!"))396 ## =========================================================397 # Method to test the method that determines the absolute398 # difference between quantity1 and quantity2.399 # @param - None.400 # @return - Nothing.401 # O(1) method.402 @staticmethod403 def test_get_absolute_difference():404 print(" Testing get_absolute_difference() method.")405 prompt = " ...Test:default,get_absolute_difference(0,0) == 0 {}"406 statistical_analysis.increment_number_test_cases_used()407 if 0 == data_analysis.get_absolute_difference():408 print(prompt .format("OK"))409 statistical_analysis.increment_number_test_cases_passed()410 else:411 print(prompt .format("FAIL!!!"))412 prompt = " ... Test: get_absolute_difference(19,13) == 6 {}"413 statistical_analysis.increment_number_test_cases_used()414 if 6 == data_analysis.get_absolute_difference(19,13):415 print(prompt .format("OK"))416 statistical_analysis.increment_number_test_cases_passed()417 else:418 print(prompt .format("FAIL!!!"))419 prompt = " ... Test: get_absolute_difference(10,14) == 4 {}"420 statistical_analysis.increment_number_test_cases_used()421 if 4 == data_analysis.get_absolute_difference(10, 14):422 print(prompt .format("OK"))423 statistical_analysis.increment_number_test_cases_passed()424 else:425 print(prompt .format("FAIL!!!"))426 prompt = " ... Test: get_absolute_difference(-20,27) == 47 {}"427 statistical_analysis.increment_number_test_cases_used()428 if 47 == data_analysis.get_absolute_difference(-20,27):429 print(prompt .format("OK"))430 statistical_analysis.increment_number_test_cases_passed()431 else:432 print(prompt .format("FAIL!!!"))433 prompt = " ... Test: get_absolute_difference(-7,-3) == 4 {}"434 statistical_analysis.increment_number_test_cases_used()435 if 4 == data_analysis.get_absolute_difference(-7,-3):436 print(prompt .format("OK"))437 statistical_analysis.increment_number_test_cases_passed()438 else:439 print(prompt .format("FAIL!!!"))440 prompt = " ... Test: get_absolute_difference(-4,-9) == 5 {}"441 statistical_analysis.increment_number_test_cases_used()442 if 5 == data_analysis.get_absolute_difference(-4,-9):443 print(prompt .format("OK"))444 statistical_analysis.increment_number_test_cases_passed()445 else:446 print(prompt .format("FAIL!!!"))447 prompt = " ... Test: get_absolute_difference(3,-4) == 7 {}"448 statistical_analysis.increment_number_test_cases_used()449 if 7 == data_analysis.get_absolute_difference(3,-4):450 print(prompt .format("OK"))451 statistical_analysis.increment_number_test_cases_passed()452 else:453 print(prompt .format("FAIL!!!"))454 prompt = " ... Test: get_abs..._diff(object,569) == None {}"455 statistical_analysis.increment_number_test_cases_used()456 a = data_analysis()457 if None == data_analysis.get_absolute_difference(a,569):458 print(prompt .format("OK"))459 statistical_analysis.increment_number_test_cases_passed()460 else:461 print(prompt .format("FAIL!!!"))462 prompt = " ... Test: get_abs..._diff(865.12,'Buona...') == None {}"463 statistical_analysis.increment_number_test_cases_used()464 if None == data_analysis.get_absolute_difference(865.12,"Buona serata!"):465 print(prompt .format("OK"))466 statistical_analysis.increment_number_test_cases_passed()467 else:468 print(prompt .format("FAIL!!!"))469 prompt = " ... Test: get_abs..._diff(112.08723,None) == None {}"470 statistical_analysis.increment_number_test_cases_used()471 if None == data_analysis.get_absolute_difference(112.08723,None):472 print(prompt .format("OK"))473 statistical_analysis.increment_number_test_cases_passed()474 else:475 print(prompt .format("FAIL!!!"))476 ## =========================================================477 # Method to test the method that determines the relative change478 # between quantity1 and quantity2.479 # @param - None.480 # @return - Nothing.481 # O(1) method.482 @staticmethod483 def test_get_relative_change():484 print(" Testing get_relative_change() method.")485 prompt = " ... Test: default, get_relative_change(1,1) == 0 {}"486 statistical_analysis.increment_number_test_cases_used()487 if 0 == data_analysis.get_relative_change():488 print(prompt .format("OK"))489 statistical_analysis.increment_number_test_cases_passed()490 else:491 print(prompt .format("FAIL!!!"))492 prompt = " ... Test: get_relative_change(15,12) == 0.25 {}"493 statistical_analysis.increment_number_test_cases_used()494 if 0.25 == data_analysis.get_relative_change(15,12):495 print(prompt .format("OK"))496 statistical_analysis.increment_number_test_cases_passed()497 else:498 print("data_analysis.get_relative_change(15,12):",data_analysis.get_relative_change(15,12),"=")499 print(prompt .format("FAIL!!!"))500 prompt = " ... Test: get_relative_change(18,20) == -0.10 {}"501 statistical_analysis.increment_number_test_cases_used()502 if -0.10 == data_analysis.get_relative_change(18,20):503 print(prompt .format("OK"))504 statistical_analysis.increment_number_test_cases_passed()505 else:506 #print("data_analysis.get_relative_change(18,20):",data_analysis.get_relative_change(18,20),"=")507 print(prompt .format("FAIL!!!"))508 prompt = " ... Test: get_relative_change(-97,-100) == -0.03 {}"509 statistical_analysis.increment_number_test_cases_used()510 if -0.03 == data_analysis.get_relative_change(-97,-100):511 print(prompt .format("OK"))512 statistical_analysis.increment_number_test_cases_passed()513 else:514 #print("data_analysis.get_relative_change(18,20):",data_analysis.get_relative_change(18,20),"=")515 print(prompt .format("FAIL!!!"))516 prompt = " ... Test: get_relative_change(3,0) can't compute {}"517 try:518 statistical_analysis.increment_number_test_cases_used()519 relative_change_error = data_analysis.get_relative_change(3,0)520 print(prompt .format("FAIL!!!"))521 except:522 print(prompt .format("OK"))523 statistical_analysis.increment_number_test_cases_passed()524 prompt = " ...Test: get_relative_change(-100,-110) ~ -0.0909090909 {}"525 statistical_analysis.increment_number_test_cases_used()526 if math.isclose(-0.0909090909, data_analysis.get_relative_change(-100,-110)):527 print(prompt .format("OK"))528 statistical_analysis.increment_number_test_cases_passed()529 else:530 #print("data_analysis.get_relative_change(18,20):",data_analysis.get_relative_change(18,20),"=")531 print(prompt .format("FAIL!!!"))532 print("data_analysis.get_relative_change(-100,-110) is:",data_analysis.get_relative_change(-100,-110),".")533 prompt = " ...Test: get_relative_change(-98,-105) ~ -0.06666666666 {}"534 statistical_analysis.increment_number_test_cases_used()535 if math.isclose(-0.06666666666, data_analysis.get_relative_change(-98,-105)):536 print(prompt .format("OK"))537 statistical_analysis.increment_number_test_cases_passed()538 else:539 #print("data_analysis.get_relative_change(18,20):",data_analysis.get_relative_change(18,20),"=")540 print(prompt .format("FAIL!!!"))541 prompt = " ... Test: get_rel..._change(object,569) == None {}"542 statistical_analysis.increment_number_test_cases_used()543 a = data_analysis()544 if None == data_analysis.get_relative_change(a,569):545 print(prompt .format("OK"))546 statistical_analysis.increment_number_test_cases_passed()547 else:548 print(prompt .format("FAIL!!!"))549 prompt = " ... Test: get_rel..._change(865.12,'Buona...') == None {}"550 statistical_analysis.increment_number_test_cases_used()551 if None == data_analysis.get_relative_change(865.12,"Buona serata!"):552 print(prompt .format("OK"))553 statistical_analysis.increment_number_test_cases_passed()554 else:555 print(prompt .format("FAIL!!!"))556 prompt = " ... Test: get_rel..._change(232,None) == None {}"557 statistical_analysis.increment_number_test_cases_used()558 if None == data_analysis.get_relative_change(232,None):559 print(prompt .format("OK"))560 statistical_analysis.increment_number_test_cases_passed()561 else:562 print(prompt .format("FAIL!!!"))563 ## =========================================================564 # Method to test the method that determines the percentage change565 # between quantity1 and quantity2.566 # @param - None.567 # @return - Nothing.568 # O(1) method.569 @staticmethod570 def test_get_percentage_change():571 print(" Testing get_percentage_change() method.")572 prompt = " ... Test: default, get_percentage_change(1,1) == 0 {}"573 statistical_analysis.increment_number_test_cases_used()574 if 0 == data_analysis.get_percentage_change():575 print(prompt .format("OK"))576 statistical_analysis.increment_number_test_cases_passed()577 else:578 print(prompt .format("FAIL!!!"))579 prompt = " ... Test: get_percentage_change(15,12) == 0.25 {}"580 statistical_analysis.increment_number_test_cases_used()581 if 25 == data_analysis.get_percentage_change(15,12):582 print(prompt .format("OK"))583 statistical_analysis.increment_number_test_cases_passed()584 else:585 print("data_analysis.get_percentage_change(15,12):",data_analysis.get_percentage_change(15,12),"=")586 print(prompt .format("FAIL!!!"))587 prompt = " ... Test: get_percentage_change(18,20) == -0.10 {}"588 statistical_analysis.increment_number_test_cases_used()589 if -10 == data_analysis.get_percentage_change(18,20):590 print(prompt .format("OK"))591 statistical_analysis.increment_number_test_cases_passed()592 else:593 #print("data_analysis.get_percentage_change(18,20):",data_analysis.get_percentage_change(18,20),"=")594 print(prompt .format("FAIL!!!"))595 prompt = " ... Test: get_percentage_change(-97,-100) == -0.03 {}"596 statistical_analysis.increment_number_test_cases_used()597 if -3 == data_analysis.get_percentage_change(-97,-100):598 print(prompt .format("OK"))599 statistical_analysis.increment_number_test_cases_passed()600 else:601 #print("data_analysis.get_percentage_change(18,20):",data_analysis.get_percentage_change(18,20),"=")602 print(prompt .format("FAIL!!!"))603 prompt = " ... Test: get_percentage_change(3,0) can't compute {}"604 try:605 statistical_analysis.increment_number_test_cases_used()606 relative_change_error = data_analysis.get_percentage_change(3,0)607 print(prompt .format("FAIL!!!"))608 except:609 print(prompt .format("OK"))610 statistical_analysis.increment_number_test_cases_passed()611 prompt = " ..Test:get_percentage_change(-100,-110) ~ -0.0909090909 {}"612 statistical_analysis.increment_number_test_cases_used()613 if math.isclose(-9.09090909, data_analysis.get_percentage_change(-100,-110)):614 print(prompt .format("OK"))615 statistical_analysis.increment_number_test_cases_passed()616 else:617 #print("data_analysis.get_percentage_change(18,20):",data_analysis.get_percentage_change(18,20),"=")618 print(prompt .format("FAIL!!!"))619 prompt = " ..Test:get_percentage_change(-98,-105) ~ -0.06666666666 {}"620 statistical_analysis.increment_number_test_cases_used()621 if math.isclose(-6.666666666, data_analysis.get_percentage_change(-98,-105)):622 print(prompt .format("OK"))623 statistical_analysis.increment_number_test_cases_passed()624 else:625 #print("data_analysis.get_percentage_change(18,20):",data_analysis.get_percentage_change(18,20),"=")626 print(prompt .format("FAIL!!!"))627 prompt = " ... Test: get_pct_change(object,569) == None {}"628 statistical_analysis.increment_number_test_cases_used()629 a = data_analysis()630 if None == data_analysis.get_percentage_change(a,569):631 print(prompt .format("OK"))632 statistical_analysis.increment_number_test_cases_passed()633 else:634 print(prompt .format("FAIL!!!"))635 prompt = " ... Test: get_pct_change(865.12,'Buona...') == None {}"636 statistical_analysis.increment_number_test_cases_used()637 if None == data_analysis.get_percentage_change(865.12,"Buona serata!"):638 print(prompt .format("OK"))639 statistical_analysis.increment_number_test_cases_passed()640 else:641 print(prompt .format("FAIL!!!"))642 prompt = " ... Test: get_pct_change(232,None) == None {}"643 statistical_analysis.increment_number_test_cases_used()644 if None == data_analysis.get_percentage_change(232,None):645 print(prompt .format("OK"))646 statistical_analysis.increment_number_test_cases_passed()647 else:648 print(prompt .format("FAIL!!!"))649 ## =========================================================650 # Method to test the method that determines the relative651 # error between experimental_value and theoretical_value.652 # @param - None.653 # @return - Nothing.654 # O(1) method.655 @staticmethod656 def test_get_relative_error():657 print(" Testing get_relative_error() method.")658 prompt = " ... Test: default, get_relative_error(1,1) == 0 {}"659 statistical_analysis.increment_number_test_cases_used()660 if 0 == data_analysis.get_relative_error():661 print(prompt .format("OK"))662 statistical_analysis.increment_number_test_cases_passed()663 else:664 print(prompt .format("FAIL!!!"))665 prompt = " ... Test: get_relative_error(15,12) == 0.25 {}"666 statistical_analysis.increment_number_test_cases_used()667 if 0.25 == data_analysis.get_relative_error(15,12):668 print(prompt .format("OK"))669 statistical_analysis.increment_number_test_cases_passed()670 else:671 print(prompt .format("FAIL!!!"))672 prompt = " ... Test: get_relative_error(16,20) == 0.2 {}"673 statistical_analysis.increment_number_test_cases_used()674 if 0.2 == data_analysis.get_relative_error(16,20):675 print(prompt .format("OK"))676 statistical_analysis.increment_number_test_cases_passed()677 else:678 print(prompt .format("FAIL!!!"))679 prompt = " ... Test: get_relative_error(-9,-10) == 0.1 {}"680 statistical_analysis.increment_number_test_cases_used()681 if 0.1 == data_analysis.get_relative_error(-9,-10):682 print(prompt .format("OK"))683 statistical_analysis.increment_number_test_cases_passed()684 else:685 print(prompt .format("FAIL!!!"))686 prompt = " ... Test: get_relative_error(-13,-10) == 0.3 {}"687 statistical_analysis.increment_number_test_cases_used()688 if 0.3 == data_analysis.get_relative_error(-13,-10):689 print(prompt .format("OK"))690 statistical_analysis.increment_number_test_cases_passed()691 else:692 print(prompt .format("FAIL!!!"))693 prompt = " ... Test: get_relative_error(-3,-2) == 0.5 {}"694 statistical_analysis.increment_number_test_cases_used()695 if 0.5 == data_analysis.get_relative_error(-3,-2):696 print(prompt .format("OK"))697 statistical_analysis.increment_number_test_cases_passed()698 else:699 print(prompt .format("FAIL!!!"))700 prompt = " ... Test: get_relative_error(3,0) can't compute {}"701 try:702 statistical_analysis.increment_number_test_cases_used()703 relative_change_error = data_analysis.get_relative_error(3,0)704 print(prompt .format("FAIL!!!"))705 except:706 print(prompt .format("OK"))707 statistical_analysis.increment_number_test_cases_passed()708 prompt = " ... Test: get_rel..._err(object,7643) == None {}"709 statistical_analysis.increment_number_test_cases_used()710 a = data_analysis()711 if None == data_analysis.get_relative_error(a,7643):712 print(prompt .format("OK"))713 statistical_analysis.increment_number_test_cases_passed()714 else:715 print(prompt .format("FAIL!!!"))716 prompt = " ... Test: get_rel..._err(67923.23,'Buona...') == None {}"717 statistical_analysis.increment_number_test_cases_used()718 if None == data_analysis.get_relative_error(67923.23,"Buona serata!"):719 print(prompt .format("OK"))720 statistical_analysis.increment_number_test_cases_passed()721 else:722 print(prompt .format("FAIL!!!"))723 prompt = " ... Test: get_rel..._err(8346,None) == None {}"724 statistical_analysis.increment_number_test_cases_used()725 if None == data_analysis.get_relative_error(8346,None):726 print(prompt .format("OK"))727 statistical_analysis.increment_number_test_cases_passed()728 else:729 print(prompt .format("FAIL!!!"))730 ## =========================================================731 # Method to test the method that determines the percent732 # error between experimental_value and theoretical_value.733 # @param - None.734 # @return - Nothing.735 # O(1) method.736 @staticmethod737 def test_get_percent_error():738 print(" Testing get_percent_error() method.")739 prompt = " ... Test: default, get_percent_error(1,1) == 0 {}"740 statistical_analysis.increment_number_test_cases_used()741 if 0 == data_analysis.get_percent_error():742 print(prompt .format("OK"))743 statistical_analysis.increment_number_test_cases_passed()744 else:745 print(prompt .format("FAIL!!!"))746 prompt = " ... Test: get_percent_error(15,12) == 25 {}"747 statistical_analysis.increment_number_test_cases_used()748 if 25 == data_analysis.get_percent_error(15,12):749 print(prompt .format("OK"))750 statistical_analysis.increment_number_test_cases_passed()751 else:752 print(prompt .format("FAIL!!!"))753 754 prompt = " ... Test: get_percent_error(16,20) == 0.2 {}"755 statistical_analysis.increment_number_test_cases_used()756 if 20 == data_analysis.get_percent_error(16,20):757 print(prompt .format("OK"))758 statistical_analysis.increment_number_test_cases_passed()759 else:760 print(prompt .format("FAIL!!!"))761 prompt = " ... Test: get_percent_error(-9,-10) == 0.1 {}"762 statistical_analysis.increment_number_test_cases_used()763 if 10 == data_analysis.get_percent_error(-9,-10):764 print(prompt .format("OK"))765 statistical_analysis.increment_number_test_cases_passed()766 else:767 print(prompt .format("FAIL!!!"))768 prompt = " ... Test: get_percent_error(-13,-10) == 0.3 {}"769 statistical_analysis.increment_number_test_cases_used()770 if 30 == data_analysis.get_percent_error(-13,-10):771 print(prompt .format("OK"))772 statistical_analysis.increment_number_test_cases_passed()773 else:774 print(prompt .format("FAIL!!!"))775 prompt = " ... Test: get_percent_error(-3,-2) == 0.5 {}"776 statistical_analysis.increment_number_test_cases_used()777 if 50 == data_analysis.get_percent_error(-3,-2):778 print(prompt .format("OK"))779 statistical_analysis.increment_number_test_cases_passed()780 else:781 print(prompt .format("FAIL!!!"))782 prompt = " ... Test: get_percent_error(3,0) can't compute {}"783 try:784 statistical_analysis.increment_number_test_cases_used()785 relative_change_error = data_analysis.get_percent_error(3,0)786 print(prompt .format("FAIL!!!"))787 except:788 print(prompt .format("OK"))789 statistical_analysis.increment_number_test_cases_passed()790 prompt = " ... Test: get_pct_err(object,6325) == None {}"791 statistical_analysis.increment_number_test_cases_used()792 a = data_analysis()793 if None == data_analysis.get_percent_error(a,6325):794 print(prompt .format("OK"))795 statistical_analysis.increment_number_test_cases_passed()796 else:797 print(prompt .format("FAIL!!!"))798 prompt = " ... Test: get_pct_err(8.212,'Buona...') == None {}"799 statistical_analysis.increment_number_test_cases_used()800 if None == data_analysis.get_percent_error(8.212,"Buona serata!"):801 print(prompt .format("OK"))802 statistical_analysis.increment_number_test_cases_passed()803 else:804 print(prompt .format("FAIL!!!"))805 prompt = " ... Test: get_pct_err(362,None) == None {}"806 statistical_analysis.increment_number_test_cases_used()807 if None == data_analysis.get_percent_error(362,None):808 print(prompt .format("OK"))809 statistical_analysis.increment_number_test_cases_passed()810 else:811 print(prompt .format("FAIL!!!"))812 ## =========================================================813 # Method to test the method that calculates the arithmetic814 # mean for the absolute values of a given list of numbers.815 # @param - None.816 # @return - Nothing.817 # O(n) method, where n is the number of elements in the lists818 # used to test the specified method.819 @staticmethod820 def test_get_arithmetic_average_of_absolute_values():821 print(" Testing get_arithmetic_average_of_absolute_values() method.")822 prompt = " ... Test: list_of_numbers is None {}"823 statistical_analysis.increment_number_test_cases_used()824 if None == data_analysis.get_arithmetic_average_of_absolute_values(None):825 print(prompt .format("OK"))826 statistical_analysis.increment_number_test_cases_passed()827 else:828 print(prompt .format("FAIL!!!"))829 prompt = " ... Test: list_of_numbers is '', empty string {}"830 statistical_analysis.increment_number_test_cases_used()831 if None == data_analysis.get_arithmetic_average_of_absolute_values(""):832 print(prompt .format("OK"))833 statistical_analysis.increment_number_test_cases_passed()834 else:835 print(prompt .format("FAIL!!!"))836 prompt = " ... Test: list_of_numbers is 'Ciao mondo!', a string {}"837 statistical_analysis.increment_number_test_cases_used()838 if None == data_analysis.get_arithmetic_average_of_absolute_values("Ciao mondo!"):839 print(prompt .format("OK"))840 statistical_analysis.increment_number_test_cases_passed()841 else:842 print(prompt .format("FAIL!!!"))843 not_a_list_obj = data_analysis()844 prompt = " ... Test: list_of_numbers is 'not_a_list_obj' {}"845 statistical_analysis.increment_number_test_cases_used()846 if None == data_analysis.get_arithmetic_average_of_absolute_values(not_a_list_obj):847 print(prompt .format("OK"))848 statistical_analysis.increment_number_test_cases_passed()849 else:850 print(prompt .format("FAIL!!!"))851 prompt = " ... Test: list_of_numbers is [], empty list {}"852 statistical_analysis.increment_number_test_cases_used()853 if None == data_analysis.get_arithmetic_average_of_absolute_values([]):854 print(prompt .format("OK"))855 statistical_analysis.increment_number_test_cases_passed()856 else:857 print(prompt .format("FAIL!!!"))858 a = data_analysis()859 b = data_analysis()860 c = data_analysis()861 list_not_pure_numbers = [2247, 273805, 0.23423, 9234.2347832, "network science", a, 785398, 0.23423, b, 45678, c, "data science", 5623]862 prompt = " ... Test: list_of_numbers is 'list_not_pure_numbers' {}"863 statistical_analysis.increment_number_test_cases_used()864 if None == data_analysis.get_arithmetic_average_of_absolute_values(list_not_pure_numbers):865 print(prompt .format("OK"))866 statistical_analysis.increment_number_test_cases_passed()867 else:868 print(prompt .format("FAIL!!!"))869 list_pure_numbers = [23, -46, 12, 13, 65, -75, 10, 0.23423, -56, 38]870 prompt = " ... Test: [23,-46,12,13,65,-75,10,0.23423,-56,38] {}"871 statistical_analysis.increment_number_test_cases_used()872 arith_mean_abs = data_analysis.get_arithmetic_average_of_absolute_values(list_pure_numbers)873 if math.isclose(33.823423, arith_mean_abs):874 #if npt.assert_approx_equal(33.823423, arith_mean_abs):875 print(prompt .format("OK"))876 statistical_analysis.increment_number_test_cases_passed()877 else:878 print(prompt .format("FAIL!!!"))879 print(" results is:",arith_mean_abs,".")880 list_pure_numbers = [2,5,7,9,1,4,8]881 prompt = " ... Test: [2,5,7,9,1,4,8] {}"882 statistical_analysis.increment_number_test_cases_used()883 arith_mean_abs = data_analysis.get_arithmetic_average_of_absolute_values(list_pure_numbers)884 if math.isclose(5.14285714286, arith_mean_abs):885 print(prompt .format("OK"))886 statistical_analysis.increment_number_test_cases_passed()887 else:888 print(prompt .format("FAIL!!!"))889 print(" results is:",arith_mean_abs,".")890 list_pure_numbers = [0,-5,-235,-345.346346,-34534.67239,-23408,-0.242]891 prompt = " Test:[0,-5,-235,-345.346346,-34534.67239,-23408,-0.242] {}"892 statistical_analysis.increment_number_test_cases_used()893 arith_mean_abs = data_analysis.get_arithmetic_average_of_absolute_values(list_pure_numbers)894 if math.isclose(8361.18010514, arith_mean_abs):895 print(prompt .format("OK"))896 statistical_analysis.increment_number_test_cases_passed()897 else:898 print(prompt .format("FAIL!!!"))899 print(" results is:",arith_mean_abs,".")900 list_pure_numbers = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]901 prompt = " ... Test: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] {}"902 statistical_analysis.increment_number_test_cases_used()903 arith_mean_abs = data_analysis.get_arithmetic_average_of_absolute_values(list_pure_numbers)904 if math.isclose(0.0, arith_mean_abs):905 print(prompt .format("OK"))906 statistical_analysis.increment_number_test_cases_passed()907 else:908 print(prompt .format("FAIL!!!"))909 print(" results is:",arith_mean_abs,".")910 list_pure_numbers = [-743024.367935]911 prompt = " ... Test: [-743024.367935] {}"912 statistical_analysis.increment_number_test_cases_used()913 arith_mean_abs = data_analysis.get_arithmetic_average_of_absolute_values(list_pure_numbers)914 if math.isclose(743024.367935, arith_mean_abs):915 print(prompt .format("OK"))916 statistical_analysis.increment_number_test_cases_passed()917 else:918 print(prompt .format("FAIL!!!"))919 print(" results is:",arith_mean_abs,".")920 ## =========================================================921 # Method to test the method that calculates the relative922 # difference.923 # @param - None.924 # @return - Nothing.925 # O(1) method.926 @staticmethod927 def test_get_relative_difference():928 print(" Testing get_relative_difference() method.")929 prompt = " ... Test: default get_relative_difference(1,1) == 0 {}"930 statistical_analysis.increment_number_test_cases_used()931 if 0 == data_analysis.get_relative_difference():932 print(prompt .format("OK"))933 statistical_analysis.increment_number_test_cases_passed()934 else:935 print(prompt .format("FAIL!!!"))936 not_number_obj = data_analysis()937 prompt = " ...Test:get_rel..._diff(not_number_obj,56897) == None {}"938 statistical_analysis.increment_number_test_cases_used()939 if None == data_analysis.get_relative_difference(not_number_obj,56897):940 print(prompt .format("OK"))941 statistical_analysis.increment_number_test_cases_passed()942 else:943 print(prompt .format("FAIL!!!"))944 prompt = " ...Test:get_rel..._diff(-32.15, not_number_obj)==None {}"945 statistical_analysis.increment_number_test_cases_used()946 if None == data_analysis.get_relative_difference(-32.15, not_number_obj):947 print(prompt .format("OK"))948 statistical_analysis.increment_number_test_cases_passed()949 else:950 print(prompt .format("FAIL!!!"))951 prompt = " ... Test: get_rel..._diff(-32.15, []) == None {}"952 statistical_analysis.increment_number_test_cases_used()953 if None == data_analysis.get_relative_difference(-32.15, []):954 print(prompt .format("OK"))955 statistical_analysis.increment_number_test_cases_passed()956 else:957 print(prompt .format("FAIL!!!"))958 prompt = " ... Test: get_rel..._diff(972, [623, 2032]) == None {}"959 statistical_analysis.increment_number_test_cases_used()960 if None == data_analysis.get_relative_difference(972, [623, 2032, 12.087623]):961 print(prompt .format("OK"))962 statistical_analysis.increment_number_test_cases_passed()963 else:964 print(prompt .format("FAIL!!!"))965 prompt = " ... Test: get_rel..._diff('Hola', 96) == None {}"966 statistical_analysis.increment_number_test_cases_used()967 if None == data_analysis.get_relative_difference("Hola", 96):968 print(prompt .format("OK"))969 statistical_analysis.increment_number_test_cases_passed()970 else:971 print(prompt .format("FAIL!!!"))972 """973 Testing for cases |quantity1 - quantity2| = 0.974 975 Cases |quantity1 - quantity2| < 0 cannot be tested,976 since this is mathematically impossible.977 If such cases occur, it is because there are bugs978 with implementing the method to determine979 |quantity1 - quantity2|.980 """981 prompt = " ... Test: get_rel..._diff(0, 0) == None {}"982 statistical_analysis.increment_number_test_cases_used()983 if None == data_analysis.get_relative_difference(0, 0):984 print(prompt .format("OK"))985 statistical_analysis.increment_number_test_cases_passed()986 else:987 print(prompt .format("FAIL!!!"))988 prompt = " ... Test: get_rel..._diff(5, 5) == 0 {}"989 statistical_analysis.increment_number_test_cases_used()990 if 0 == data_analysis.get_relative_difference(5, 5):991 print(prompt .format("OK"))992 statistical_analysis.increment_number_test_cases_passed()993 else:994 print(prompt .format("FAIL!!!"))995 prompt = " ... Test: get_rel..._diff(-1.23, -1.23) == 0 {}"996 statistical_analysis.increment_number_test_cases_used()997 if 0 == data_analysis.get_relative_difference(-1.23, -1.23):998 print(prompt .format("OK"))999 statistical_analysis.increment_number_test_cases_passed()1000 else:1001 print(prompt .format("FAIL!!!"))1002 prompt = " ... Test: get_rel..._diff(-48, -48) == 0 {}"1003 statistical_analysis.increment_number_test_cases_used()1004 if 0 == data_analysis.get_relative_difference(-48, -48):1005 print(prompt .format("OK"))1006 statistical_analysis.increment_number_test_cases_passed()1007 else:1008 print(prompt .format("FAIL!!!"))1009 prompt = " ... Test: get_rel..._diff(9.23, 9.23) == 0 {}"1010 statistical_analysis.increment_number_test_cases_used()1011 if 0 == data_analysis.get_relative_difference(9.23, 9.23):1012 print(prompt .format("OK"))1013 statistical_analysis.increment_number_test_cases_passed()1014 else:1015 print(prompt .format("FAIL!!!"))1016 """1017 We cannot test for:1018 + 0 <= (|quantity1| + |quantity1|)1019 + 0 <= 0.5 * (|quantity1| + |quantity1|)1020 1021 This is because both quantity1 and quantity2 cannot1022 be zero.1023 + Our implementation would return None if the following1024 is true: quantity1 = quantity2 = 0.1025 1026 Hence, we cannot test for the folowing:1027 + 0 = (|quantity1| + |quantity1|)1028 + 0 = 0.5 * (|quantity1| + |quantity1|)1029 1030 As for the following cases,1031 + 0 < (|quantity1| + |quantity1|)1032 + 0 < 0.5 * (|quantity1| + |quantity1|)1033 they are mathematically impossible to test.1034 If these cases occur, it is because the functions1035 to implement these have (software) bugs/errors.1036 """1037 prompt = " ... Test: get_rel..._diff(15, 12) == 0.22222222222 {}"1038 statistical_analysis.increment_number_test_cases_used()1039 if math.isclose(data_analysis.get_relative_difference(15, 12),0.22222222222):1040 print(prompt .format("OK"))1041 statistical_analysis.increment_number_test_cases_passed()1042 else:1043 print(prompt .format("FAIL!!!"))1044 prompt = " ... Test: get_rel..._diff(45, 50) == 0.10526315789 {}"1045 statistical_analysis.increment_number_test_cases_used()1046 if math.isclose(data_analysis.get_relative_difference(45, 50),0.10526315789):1047 print(prompt .format("OK"))1048 statistical_analysis.increment_number_test_cases_passed()1049 else:1050 print(prompt .format("FAIL!!!"))1051 prompt = " ... Test: get_rel..._diff(-30,-35) == 0.15384615384 {}"1052 statistical_analysis.increment_number_test_cases_used()1053 if math.isclose(data_analysis.get_relative_difference(-30, -35),0.15384615384):1054 print(prompt .format("OK"))1055 statistical_analysis.increment_number_test_cases_passed()1056 else:1057 print(prompt .format("FAIL!!!"))1058 prompt = " ... Test: get_rel..._diff(-2.8,-2.41) == 0.14971209213 {}"1059 statistical_analysis.increment_number_test_cases_used()1060 if math.isclose(data_analysis.get_relative_difference(-2.8, -2.41),0.14971209213):1061 print(prompt .format("OK"))1062 statistical_analysis.increment_number_test_cases_passed()1063 else:1064 print(prompt .format("FAIL!!!"))1065 prompt = " ... Test: get_rel..._diff(8.1,8.73) == 0.07486631016 {}"1066 statistical_analysis.increment_number_test_cases_used()1067 if math.isclose(data_analysis.get_relative_difference(8.1,8.73),0.07486631016):1068 print(prompt .format("OK"))1069 statistical_analysis.increment_number_test_cases_passed()1070 else:1071 print(prompt .format("FAIL!!!"))1072 prompt = " ... Test: get_rel..._diff(-2,1.5) == 2 {}"1073 statistical_analysis.increment_number_test_cases_used()1074 if math.isclose(data_analysis.get_relative_difference(-2,1.5),2):1075 print(prompt .format("OK"))1076 statistical_analysis.increment_number_test_cases_passed()1077 else:1078 print(prompt .format("FAIL!!!"))1079 """1080 print("data_analysis.get_relative_difference(-2,1.5):",data_analysis.get_relative_difference(-2,1.5),"=")1081 print("data_analysis.get_absolute_difference(-2,1.5):",data_analysis.get_absolute_difference(-2,1.5),"=")1082 """1083 prompt = " ... Test: get_rel..._diff(1.5,-2) == 2 {}"1084 statistical_analysis.increment_number_test_cases_used()1085 if math.isclose(data_analysis.get_relative_difference(1.5,-2),2):1086 print(prompt .format("OK"))1087 statistical_analysis.increment_number_test_cases_passed()1088 else:1089 print(prompt .format("FAIL!!!"))1090 #print("data_analysis.get_relative_difference(1.5,-2):",data_analysis.get_relative_difference(1.5,-2),"=")1091 ## =========================================================1092 # Method to test the method that calculates the relative1093 # percentage difference.1094 # @param - None.1095 # @return - Nothing.1096 # O(1) method.1097 @staticmethod1098 def test_get_relative_percentage_difference():1099 print(" Testing get_relative_percentage_difference() method.")1100 prompt = " ... Test: default get_rel_pct_diff(1,1) == 0 {}"1101 statistical_analysis.increment_number_test_cases_used()1102 if 0 == data_analysis.get_relative_percentage_difference():1103 print(prompt .format("OK"))1104 statistical_analysis.increment_number_test_cases_passed()1105 else:1106 print(prompt .format("FAIL!!!"))1107 not_number_obj = data_analysis()1108 prompt = " ...Test:get_rel_pct_diff(not_number_obj,56897) == None {}"1109 statistical_analysis.increment_number_test_cases_used()1110 if None == data_analysis.get_relative_percentage_difference(not_number_obj,56897):1111 print(prompt .format("OK"))1112 statistical_analysis.increment_number_test_cases_passed()1113 else:1114 print(prompt .format("FAIL!!!"))1115 prompt = " ...Test:get_rel_pct_diff(-32.15, not_number_obj)==None {}"1116 statistical_analysis.increment_number_test_cases_used()1117 if None == data_analysis.get_relative_percentage_difference(-32.15, not_number_obj):1118 print(prompt .format("OK"))1119 statistical_analysis.increment_number_test_cases_passed()1120 else:1121 print(prompt .format("FAIL!!!"))1122 prompt = " ... Test: get_rel_pct_diff(-32.15, []) == None {}"1123 statistical_analysis.increment_number_test_cases_used()1124 if None == data_analysis.get_relative_percentage_difference(-32.15, []):1125 print(prompt .format("OK"))1126 statistical_analysis.increment_number_test_cases_passed()1127 else:1128 print(prompt .format("FAIL!!!"))1129 prompt = " ... Test: get_rel_pct_diff(972, [623, 2032]) == None {}"1130 statistical_analysis.increment_number_test_cases_used()1131 if None == data_analysis.get_relative_percentage_difference(972, [623, 2032, 12.087623]):1132 print(prompt .format("OK"))1133 statistical_analysis.increment_number_test_cases_passed()1134 else:1135 print(prompt .format("FAIL!!!"))1136 prompt = " ... Test: get_rel_pct_diff('Hola', 96) == None {}"1137 statistical_analysis.increment_number_test_cases_used()1138 if None == data_analysis.get_relative_percentage_difference("Hola", 96):1139 print(prompt .format("OK"))1140 statistical_analysis.increment_number_test_cases_passed()1141 else:1142 print(prompt .format("FAIL!!!"))1143 """1144 Testing for cases |quantity1 - quantity2| = 0.1145 1146 Cases |quantity1 - quantity2| < 0 cannot be tested,1147 since this is mathematically impossible.1148 If such cases occur, it is because there are bugs1149 with implementing the method to determine1150 |quantity1 - quantity2|.1151 """1152 prompt = " ... Test: get_rel_pct_diff(0, 0) == None {}"1153 statistical_analysis.increment_number_test_cases_used()1154 if None == data_analysis.get_relative_percentage_difference(0, 0):1155 print(prompt .format("OK"))1156 statistical_analysis.increment_number_test_cases_passed()1157 else:1158 print(prompt .format("FAIL!!!"))1159 prompt = " ... Test: get_rel_pct_diff(5, 5) == 0 {}"1160 statistical_analysis.increment_number_test_cases_used()1161 if 0 == data_analysis.get_relative_percentage_difference(5, 5):1162 print(prompt .format("OK"))1163 statistical_analysis.increment_number_test_cases_passed()1164 else:1165 print(prompt .format("FAIL!!!"))1166 prompt = " ... Test: get_rel_pct_diff(-1.23, -1.23) == 0 {}"1167 statistical_analysis.increment_number_test_cases_used()1168 if 0 == data_analysis.get_relative_percentage_difference(-1.23, -1.23):1169 print(prompt .format("OK"))1170 statistical_analysis.increment_number_test_cases_passed()1171 else:1172 print(prompt .format("FAIL!!!"))1173 prompt = " ... Test: get_rel_pct_diff(-48, -48) == 0 {}"1174 statistical_analysis.increment_number_test_cases_used()1175 if 0 == data_analysis.get_relative_percentage_difference(-48, -48):1176 print(prompt .format("OK"))1177 statistical_analysis.increment_number_test_cases_passed()1178 else:1179 print(prompt .format("FAIL!!!"))1180 prompt = " ... Test: get_rel_pct_diff(9.23, 9.23) == 0 {}"1181 statistical_analysis.increment_number_test_cases_used()1182 if 0 == data_analysis.get_relative_percentage_difference(9.23, 9.23):1183 print(prompt .format("OK"))1184 statistical_analysis.increment_number_test_cases_passed()1185 else:1186 print(prompt .format("FAIL!!!"))1187 """1188 We cannot test for:1189 + 0 <= (|quantity1| + |quantity1|)1190 + 0 <= 0.5 * (|quantity1| + |quantity1|)1191 1192 This is because both quantity1 and quantity2 cannot1193 be zero.1194 + Our implementation would return None if the following1195 is true: quantity1 = quantity2 = 0.1196 1197 Hence, we cannot test for the folowing:1198 + 0 = (|quantity1| + |quantity1|)1199 + 0 = 0.5 * (|quantity1| + |quantity1|)1200 1201 As for the following cases,1202 + 0 < (|quantity1| + |quantity1|)1203 + 0 < 0.5 * (|quantity1| + |quantity1|)1204 they are mathematically impossible to test.1205 If these cases occur, it is because the functions1206 to implement these have (software) bugs/errors.1207 """1208 prompt = " ... Test: get_rel_pct_diff(15, 12) == 22.2222222222 {}"1209 statistical_analysis.increment_number_test_cases_used()1210 if math.isclose(data_analysis.get_relative_percentage_difference(15, 12),22.222222222):1211 print(prompt .format("OK"))1212 statistical_analysis.increment_number_test_cases_passed()1213 else:1214 print(prompt .format("FAIL!!!"))1215 print("answer=",data_analysis.get_relative_percentage_difference(15, 12),".")1216 prompt = " ... Test: get_rel_pct_diff(45, 50) == 10.526315789 {}"1217 statistical_analysis.increment_number_test_cases_used()1218 if math.isclose(data_analysis.get_relative_percentage_difference(45, 50),10.526315789):1219 print(prompt .format("OK"))1220 statistical_analysis.increment_number_test_cases_passed()1221 else:1222 print(prompt .format("FAIL!!!"))1223 prompt = " ... Test: get_rel_pct_diff(-30,-35) == 15.384615384 {}"1224 statistical_analysis.increment_number_test_cases_used()1225 if math.isclose(data_analysis.get_relative_percentage_difference(-30, -35),15.384615384):1226 print(prompt .format("OK"))1227 statistical_analysis.increment_number_test_cases_passed()1228 else:1229 print(prompt .format("FAIL!!!"))1230 prompt = " ... Test: get_rel_pct_diff(-2.8,-2.41) == 14.971209213 {}"1231 statistical_analysis.increment_number_test_cases_used()1232 if math.isclose(data_analysis.get_relative_percentage_difference(-2.8, -2.41),14.971209213):1233 print(prompt .format("OK"))1234 statistical_analysis.increment_number_test_cases_passed()1235 else:1236 print(prompt .format("FAIL!!!"))1237 prompt = " ... Test: get_rel_pct_diff(8.1,8.73) == 7.486631016 {}"1238 statistical_analysis.increment_number_test_cases_used()1239 if math.isclose(data_analysis.get_relative_percentage_difference(8.1,8.73),7.486631016):1240 print(prompt .format("OK"))1241 statistical_analysis.increment_number_test_cases_passed()1242 else:1243 print(prompt .format("FAIL!!!"))1244 prompt = " ... Test: get_rel_pct_diff(-2,1.5) == 200 {}"1245 statistical_analysis.increment_number_test_cases_used()1246 if math.isclose(data_analysis.get_relative_percentage_difference(-2,1.5),200):1247 print(prompt .format("OK"))1248 statistical_analysis.increment_number_test_cases_passed()1249 else:1250 print(prompt .format("FAIL!!!"))1251 """1252 print("data_analysis.get_relative_difference(-2,1.5):",data_analysis.get_relative_difference(-2,1.5),"=")1253 print("data_analysis.get_absolute_difference(-2,1.5):",data_analysis.get_absolute_difference(-2,1.5),"=")1254 """1255 prompt = " ... Test: get_rel_pct_diff(1.5,-2) == 200 {}"1256 statistical_analysis.increment_number_test_cases_used()1257 if math.isclose(data_analysis.get_relative_percentage_difference(1.5,-2),200):1258 print(prompt .format("OK"))1259 statistical_analysis.increment_number_test_cases_passed()1260 else:1261 print(prompt .format("FAIL!!!"))1262 # =========================================================1263 # Method to test the method that calculates the relative1264 # percentage difference.1265 # @param - None.1266 # @return - Nothing.1267 # O(1) method.1268 # Test cases for this module end before the following string:1269 # = Testing the utilities package.1270 @staticmethod1271 def test_data_analysis():1272 print("")1273 print("")1274 print("-------------------------------------------------")1275 print("== Testing class: data_analysis.")1276 data_analysis_tester.test_is_list_of_numbers()1277 print("")1278 data_analysis_tester.test_get_reference_value()1279 print("")1280 data_analysis_tester.test_get_actual_change()1281 print("")1282 data_analysis_tester.test_get_absolute_difference()1283 print("")1284 data_analysis_tester.test_get_relative_change()1285 print("")1286 data_analysis_tester.test_get_percentage_change()1287 print("")1288 data_analysis_tester.test_get_relative_error()1289 print("")1290 data_analysis_tester.test_get_percent_error()1291 print("")1292 data_analysis_tester.test_get_arithmetic_average_of_absolute_values()1293 print("")1294 data_analysis_tester.test_get_relative_difference()1295 print("")1296 data_analysis_tester.test_get_relative_percentage_difference()...
date_time_processing_tester.py
Source:date_time_processing_tester.py
1#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python32### /usr/bin/python3"""4 This Python script is written by Zhiyang Ong to perform5 date and time operations.6 Synopsis:7 Test different/all date and time operations.8 Notes/Assumptions:9 Revision History:10 August 1, 2018 Version 0.1, initial build.11"""12__author__ = 'Zhiyang Ong'13__version__ = '1.0'14__date__ = 'August 1, 2018'15# The MIT License (MIT)16# Copyright (c) <2018> <Zhiyang Ong>17# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:18# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.19# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.20# Email address: echo "cukj -wb- 23wU4X5M589 TROJANS cqkH wiuz2y 0f Mw Stanford" | awk '{ sub("23wU4X5M589","F.d_c_b. ") sub("Stanford","d0mA1n"); print $5, $2, $8; for (i=1; i<=1; i++) print "6\b"; print $9, $7, $6 }' | sed y/kqcbuHwM62z/gnotrzadqmC/ | tr 'q' ' ' | tr -d [:cntrl:] | tr -d 'ir' | tr y "\n" Che cosa significa?21###############################################################22"""23 Import modules from The Python Standard Library.24 sys Get access to any command-line arguments.25 os Use any operating system dependent functionality.26 os.path For pathname manipulations.27 subprocess -> call28 To make system calls.29 time To measure elapsed time.30 warnings Raise warnings.31 re Use regular expressions.32 filecmp For file comparison.33"""34import sys35import os36import os.path37from subprocess import call38import time39import warnings40import re41import filecmp42###############################################################43# Import Custom Python Modules44"""45 Package and module to print statistics of software testing46 results.47"""48from statistics.test_statistics import statistical_analysis49# Package and module to process input arguments to the script/program.50from utilities.queue_ip_arguments import queue_ip_args51# Package and module to perform date and time operations.52from utilities.date_time_processing import date_time_operations53"""54 Module to generate the filename for storing the experimental55 results and simulation output.56"""57from utilities.generate_results_filename import generate_filename58###############################################################59"""60 Module with methods that perform date and time operations.61 Support for class instantiation is not provided, to avoid62 acquiring a collection of useless "date_time_operations"63 objects.64 Test each static method of the "date_time_operations" class.65"""66class date_time_operations_tester:67 ## =========================================================68 # Method to test the methods that perform time operations.69 # @return - Nothing.70 # O(1) method.71 @staticmethod72 def test_time_operations():73 print("== Testing class: date_time_operations.")74 print(" Testing date_time_operations.is_valid_time() method.")75 prompt = " ... Test: single error, hh {}"76 statistical_analysis.increment_number_test_cases_used()77 if not date_time_operations.is_valid_time(34,5,3,124395):78 print(prompt .format("OK"))79 statistical_analysis.increment_number_test_cases_passed()80 else:81 print(prompt .format("FAIL!!!"))82 prompt = " ... Test: single error, mm {}"83 statistical_analysis.increment_number_test_cases_used()84 if not date_time_operations.is_valid_time(4,-8215,3,124395):85 print(prompt .format("OK"))86 statistical_analysis.increment_number_test_cases_passed()87 else:88 print(prompt .format("FAIL!!!"))89 prompt = " ... Test: single error, ss {}"90 statistical_analysis.increment_number_test_cases_used()91 if not date_time_operations.is_valid_time(4,15,586,124395):92 print(prompt .format("OK"))93 statistical_analysis.increment_number_test_cases_passed()94 else:95 print(prompt .format("FAIL!!!"))96 prompt = " ... Test: single error, us {}"97 statistical_analysis.increment_number_test_cases_used()98 if not date_time_operations.is_valid_time(4,15,56,123435435434395):99 print(prompt .format("OK"))100 statistical_analysis.increment_number_test_cases_passed()101 else:102 print(prompt .format("FAIL!!!"))103 prompt = " ... Test: double errors, ss and us {}"104 statistical_analysis.increment_number_test_cases_used()105 if not date_time_operations.is_valid_time(4,15,956,123435435434395):106 print(prompt .format("OK"))107 statistical_analysis.increment_number_test_cases_passed()108 else:109 print(prompt .format("FAIL!!!"))110 prompt = " ... Test: multiple errors, hh, ss, and us {}"111 statistical_analysis.increment_number_test_cases_used()112 if not date_time_operations.is_valid_time(42390534,15,956,123435435434395):113 print(prompt .format("OK"))114 statistical_analysis.increment_number_test_cases_passed()115 else:116 print(prompt .format("FAIL!!!"))117 prompt = " ... Test: no error {}"118 statistical_analysis.increment_number_test_cases_used()119 if date_time_operations.is_valid_time(23,59,59,124395):120 print(prompt .format("OK"))121 statistical_analysis.increment_number_test_cases_passed()122 else:123 print(prompt .format("FAIL!!!"))124 prompt = " ... Test: no error {}"125 statistical_analysis.increment_number_test_cases_used()126 if date_time_operations.is_valid_time(0,0,0,000000):127 print(prompt .format("OK"))128 statistical_analysis.increment_number_test_cases_passed()129 else:130 print(prompt .format("FAIL!!!"))131 prompt = " ... Test: no error {}"132 statistical_analysis.increment_number_test_cases_used()133 if date_time_operations.is_valid_time(1,1,1,1):134 print(prompt .format("OK"))135 statistical_analysis.increment_number_test_cases_passed()136 else:137 print(prompt .format("FAIL!!!"))138 ## =========================================================139 # Method to test method that determines if year is valid.140 # @return - Nothing.141 # O(1) method.142 @staticmethod143 def test_is_valid_year():144 print(" Testing date_time_operations.is_valid_year() method.")145 prompt = " ... Test: year < 2014 {}"146 statistical_analysis.increment_number_test_cases_used()147 if not date_time_operations.is_valid_year(2010):148 print(prompt .format("OK"))149 statistical_analysis.increment_number_test_cases_passed()150 else:151 print(prompt .format("FAIL!!!"))152 prompt = " ... Test: year = -467 {}"153 statistical_analysis.increment_number_test_cases_used()154 if not date_time_operations.is_valid_year(-467):155 print(prompt .format("OK"))156 statistical_analysis.increment_number_test_cases_passed()157 else:158 print(prompt .format("FAIL!!!"))159 prompt = " ... Test: year > 3645 {}"160 statistical_analysis.increment_number_test_cases_used()161 if not date_time_operations.is_valid_year(3645):162 print(prompt .format("OK"))163 statistical_analysis.increment_number_test_cases_passed()164 else:165 print(prompt .format("FAIL!!!"))166 prompt = " ... Test: year = 2019 {}"167 statistical_analysis.increment_number_test_cases_used()168 if date_time_operations.is_valid_year(2019):169 print(prompt .format("OK"))170 statistical_analysis.increment_number_test_cases_passed()171 else:172 print(prompt .format("FAIL!!!"))173 ## =========================================================174 # Method to test method that determines if month is valid.175 # @return - Nothing.176 # O(1) method.177 @staticmethod178 def test_is_valid_month():179 print(" Testing date_time_operations.is_valid_month() method.")180 prompt = " ... Test: month = 0 {}"181 statistical_analysis.increment_number_test_cases_used()182 if not date_time_operations.is_valid_month(0):183 print(prompt .format("OK"))184 statistical_analysis.increment_number_test_cases_passed()185 else:186 print(prompt .format("FAIL!!!"))187 prompt = " ... Test: month = -7 {}"188 statistical_analysis.increment_number_test_cases_used()189 if not date_time_operations.is_valid_month(-7):190 print(prompt .format("OK"))191 statistical_analysis.increment_number_test_cases_passed()192 else:193 print(prompt .format("FAIL!!!"))194 prompt = " ... Test: month > 12 {}"195 statistical_analysis.increment_number_test_cases_used()196 if not date_time_operations.is_valid_month(15):197 print(prompt .format("OK"))198 statistical_analysis.increment_number_test_cases_passed()199 else:200 print(prompt .format("FAIL!!!"))201 prompt = " ... Test: month = 10 {}"202 statistical_analysis.increment_number_test_cases_used()203 if date_time_operations.is_valid_month(10):204 print(prompt .format("OK"))205 statistical_analysis.increment_number_test_cases_passed()206 else:207 print(prompt .format("FAIL!!!"))208 ## =========================================================209 # Method to test method that determines if the date/day of210 # a 31-day month is valid.211 # @return - Nothing.212 # O(1) method.213 @staticmethod214 def test_is_valid_31_day_month():215 print(" Testing date_time_operations.is_valid_31_day_month() method.")216 prompt = " ... Test: not 31-day month, mm = 4 {}"217 statistical_analysis.increment_number_test_cases_used()218 if date_time_operations.is_valid_31_day_month(17,4):219 print(prompt .format("OK"))220 statistical_analysis.increment_number_test_cases_passed()221 else:222 print(prompt .format("FAIL!!!"))223 prompt = " ... Test: not 31-day month, mm = 2 {}"224 statistical_analysis.increment_number_test_cases_used()225 if date_time_operations.is_valid_31_day_month(17,4):226 print(prompt .format("OK"))227 statistical_analysis.increment_number_test_cases_passed()228 else:229 print(prompt .format("FAIL!!!"))230 prompt = " ... Test: 31-day month, dd < 0 {}"231 statistical_analysis.increment_number_test_cases_used()232 if not date_time_operations.is_valid_31_day_month(-8,7):233 print(prompt .format("OK"))234 statistical_analysis.increment_number_test_cases_passed()235 else:236 print(prompt .format("FAIL!!!"))237 prompt = " ... Test: 31-day month, dd = 0 {}"238 statistical_analysis.increment_number_test_cases_used()239 if not date_time_operations.is_valid_31_day_month(0,7):240 print(prompt .format("OK"))241 statistical_analysis.increment_number_test_cases_passed()242 else:243 print(prompt .format("FAIL!!!"))244 prompt = " ... Test: 31-day month, dd = 27 {}"245 statistical_analysis.increment_number_test_cases_used()246 if date_time_operations.is_valid_31_day_month(27,10):247 print(prompt .format("OK"))248 statistical_analysis.increment_number_test_cases_passed()249 else:250 print(prompt .format("FAIL!!!"))251 ## =========================================================252 # Method to test method that determines if the date/day of253 # a 30-day month is valid.254 # @return - Nothing.255 # O(1) method.256 @staticmethod257 def test_is_valid_30_day_month():258 print(" Testing date_time_operations.is_valid_30_day_month() method.")259 prompt = " ... Test: not 30-day month, mm = 2 {}"260 statistical_analysis.increment_number_test_cases_used()261 if date_time_operations.is_valid_30_day_month(17,2):262 print(prompt .format("OK"))263 statistical_analysis.increment_number_test_cases_passed()264 else:265 print(prompt .format("FAIL!!!"))266 prompt = " ... Test: not 30-day month, mm = 12 {}"267 statistical_analysis.increment_number_test_cases_used()268 if date_time_operations.is_valid_30_day_month(17,12):269 print(prompt .format("OK"))270 statistical_analysis.increment_number_test_cases_passed()271 else:272 print(prompt .format("FAIL!!!"))273 prompt = " ... Test: 30-day month, dd < 0 {}"274 statistical_analysis.increment_number_test_cases_used()275 if not date_time_operations.is_valid_30_day_month(-8,6):276 print(prompt .format("OK"))277 statistical_analysis.increment_number_test_cases_passed()278 else:279 print(prompt .format("FAIL!!!"))280 prompt = " ... Test: 30-day month, dd = 0 {}"281 statistical_analysis.increment_number_test_cases_used()282 if not date_time_operations.is_valid_30_day_month(0,4):283 print(prompt .format("OK"))284 statistical_analysis.increment_number_test_cases_passed()285 else:286 print(prompt .format("FAIL!!!"))287 prompt = " ... Test: 30-day month, dd = 27 {}"288 statistical_analysis.increment_number_test_cases_used()289 if date_time_operations.is_valid_30_day_month(27,11):290 print(prompt .format("OK"))291 statistical_analysis.increment_number_test_cases_passed()292 else:293 print(prompt .format("FAIL!!!"))294 ## =========================================================295 # Method to test method that determines if the date/day of296 # February is valid.297 # @return - Nothing.298 # O(1) method.299 @staticmethod300 def test_is_valid_date_in_Feb():301 print(" Testing date_time_operations.is_valid_date_in_Feb() method.")302 prompt = " ... Test: not February, mm = 12 {}"303 statistical_analysis.increment_number_test_cases_used()304 if date_time_operations.is_valid_date_in_Feb(17,12,2016):305 print(prompt .format("OK"))306 statistical_analysis.increment_number_test_cases_passed()307 else:308 print(prompt .format("FAIL!!!"))309 prompt = " ... Test: not February, mm = -2 {}"310 statistical_analysis.increment_number_test_cases_used()311 if not date_time_operations.is_valid_date_in_Feb(17,-2,2016):312 print(prompt .format("OK"))313 statistical_analysis.increment_number_test_cases_passed()314 else:315 print(prompt .format("FAIL!!!"))316 prompt = " ... Test: not February, mm = 14 {}"317 statistical_analysis.increment_number_test_cases_used()318 if not date_time_operations.is_valid_date_in_Feb(17,14,2016):319 print(prompt .format("OK"))320 statistical_analysis.increment_number_test_cases_passed()321 else:322 print(prompt .format("FAIL!!!"))323 ## =========================================================324 # Method to test the methods that perform date operations.325 # @return - Nothing.326 # O(1) method.327 @staticmethod328 def test_date_operations():329 print(" Testing date_time_operations.is_valid_date() method.")330 prompt = " ... Test: single error, dd {}"331 statistical_analysis.increment_number_test_cases_used()332 if not date_time_operations.is_valid_date(34,5,2017):333 print(prompt .format("OK"))334 statistical_analysis.increment_number_test_cases_passed()335 else:336 print(prompt .format("FAIL!!!"))337 prompt = " ... Test: single error, -dd {}"338 statistical_analysis.increment_number_test_cases_used()339 if not date_time_operations.is_valid_date(-6701,5,2017):340 print(prompt .format("OK"))341 statistical_analysis.increment_number_test_cases_passed()342 else:343 print(prompt .format("FAIL!!!"))344 prompt = " ... Test: single error, mm {}"345 statistical_analysis.increment_number_test_cases_used()346 if not date_time_operations.is_valid_date(24,15,2017):347 print(prompt .format("OK"))348 statistical_analysis.increment_number_test_cases_passed()349 else:350 print(prompt .format("FAIL!!!"))351 prompt = " ... Test: single error, mm {}"352 statistical_analysis.increment_number_test_cases_used()353 if not date_time_operations.is_valid_date(6,0,2017):354 print(prompt .format("OK"))355 statistical_analysis.increment_number_test_cases_passed()356 else:357 print(prompt .format("FAIL!!!"))358 prompt = " ... Test: single error, -mm {}"359 statistical_analysis.increment_number_test_cases_used()360 if not date_time_operations.is_valid_date(6,-20,2017):361 print(prompt .format("OK"))362 statistical_analysis.increment_number_test_cases_passed()363 else:364 print(prompt .format("FAIL!!!"))365 prompt = " ... Test: single error, yy {}"366 statistical_analysis.increment_number_test_cases_used()367 if not date_time_operations.is_valid_date(6,2,6017):368 print(prompt .format("OK"))369 statistical_analysis.increment_number_test_cases_passed()370 else:371 print(prompt .format("FAIL!!!"))372 prompt = " ... Test: single error, yy {}"373 statistical_analysis.increment_number_test_cases_used()374 if not date_time_operations.is_valid_date(6,2,1017):375 print(prompt .format("OK"))376 statistical_analysis.increment_number_test_cases_passed()377 else:378 print(prompt .format("FAIL!!!"))379 prompt = " ... Test: double errors, dd and yy {}"380 statistical_analysis.increment_number_test_cases_used()381 if not date_time_operations.is_valid_date(29,2,2018):382 print(prompt .format("OK"))383 statistical_analysis.increment_number_test_cases_passed()384 else:385 print(prompt .format("FAIL!!!"))386 prompt = " ... Test: double errors, dd and yy {}"387 statistical_analysis.increment_number_test_cases_used()388 if not date_time_operations.is_valid_date(30,2,1980):389 print(prompt .format("OK"))390 statistical_analysis.increment_number_test_cases_passed()391 else:392 print(prompt .format("FAIL!!!"))393 prompt = " ... Test: double errors, dd and mm {}"394 statistical_analysis.increment_number_test_cases_used()395 if not date_time_operations.is_valid_date(31,4,2018):396 print(prompt .format("OK"))397 statistical_analysis.increment_number_test_cases_passed()398 else:399 print(prompt .format("FAIL!!!"))400 prompt = " ... Test: multiple errors, dd, mm, and yy {}"401 statistical_analysis.increment_number_test_cases_used()402 if not date_time_operations.is_valid_date(32,-4,1988):403 print(prompt .format("OK"))404 statistical_analysis.increment_number_test_cases_passed()405 else:406 print(prompt .format("FAIL!!!"))407 prompt = " ... Test: no error {}"408 statistical_analysis.increment_number_test_cases_used()409 if date_time_operations.is_valid_date(31,7,2015):410 print(prompt .format("OK"))411 statistical_analysis.increment_number_test_cases_passed()412 else:413 print(prompt .format("FAIL!!!"))414 prompt = " ... Test: no error {}"415 statistical_analysis.increment_number_test_cases_used()416 if date_time_operations.is_valid_date(30,6,2017):417 print(prompt .format("OK"))418 statistical_analysis.increment_number_test_cases_passed()419 else:420 print(prompt .format("FAIL!!!"))421 # -----------------------------------------------------------------422 print(" Testing date_time_operations.check_filename_date_time_format() method.")423 prompt = " ... Test: single error, dd {}"424 statistical_analysis.increment_number_test_cases_used()425 if not date_time_operations.check_filename_date_time_format("54-9-2018-13-58-59-734507.txt"):426 print(prompt .format("OK"))427 statistical_analysis.increment_number_test_cases_passed()428 else:429 print(prompt .format("FAIL!!!"))430 prompt = " ... Test: single error, yy {}"431 statistical_analysis.increment_number_test_cases_used()432 if not date_time_operations.check_filename_date_time_format("54-9-3018-13-58-59-734507.txt"):433 print(prompt .format("OK"))434 statistical_analysis.increment_number_test_cases_passed()435 else:436 print(prompt .format("FAIL!!!"))437 prompt = " ... Test: single error, mm {}"438 statistical_analysis.increment_number_test_cases_used()439 if not date_time_operations.check_filename_date_time_format("29-82-2018-13-58-59-734507.txt"):440 print(prompt .format("OK"))441 statistical_analysis.increment_number_test_cases_passed()442 else:443 print(prompt .format("FAIL!!!"))444 prompt = " ... Test: multiple errors, dd, mm, yy {}"445 statistical_analysis.increment_number_test_cases_used()446 if not date_time_operations.check_filename_date_time_format("29-2-2018-13-58-59-734507.txt"):447 print(prompt .format("OK"))448 statistical_analysis.increment_number_test_cases_passed()449 else:450 print(prompt .format("FAIL!!!"))451 prompt = " ... Test: multiple errors, dd, mm, yy {}"452 statistical_analysis.increment_number_test_cases_used()453 if not date_time_operations.check_filename_date_time_format("30-2-2016-13-58-59-734507.txt"):454 print(prompt .format("OK"))455 statistical_analysis.increment_number_test_cases_passed()456 else:457 print(prompt .format("FAIL!!!"))458 prompt = " ... Test: valid date & time - leap year {}"459 statistical_analysis.increment_number_test_cases_used()460 if date_time_operations.check_filename_date_time_format("29-2-2016-21-58-59-734507.txt"):461 print(prompt .format("OK"))462 statistical_analysis.increment_number_test_cases_passed()463 else:464 print(prompt .format("FAIL!!!"))465 prompt = " ... Test: valid date & time {}"466 statistical_analysis.increment_number_test_cases_used()467 if date_time_operations.check_filename_date_time_format("28-2-2018-13-58-59-734507.txt"):468 print(prompt .format("OK"))469 statistical_analysis.increment_number_test_cases_passed()470 else:471 print(prompt .format("FAIL!!!"))472 prompt = " ... Test: valid date & time {}"473 statistical_analysis.increment_number_test_cases_used()474 if date_time_operations.check_filename_date_time_format("31-5-2018-13-58-59-734507.txt"):475 print(prompt .format("OK"))476 statistical_analysis.increment_number_test_cases_passed()477 else:478 print(prompt .format("FAIL!!!"))479 ## =========================================================480 # Method to test the method that tokenizes a filename in481 # the DD-MM-YY-HR-MN-SS-US format.482 # @return - Nothing.483 # O(1) method.484 @staticmethod485 def test_date_time_tokenization():486 print(" Testing date & time tokenization method.")487 # Number of tokens in the DD-MM-YY-HR-MN-SS-US format.488 number_of_tokens = 7489 prompt = " ... Test: invalid DD-MM-YY-HR-MN-SS-US format {}"490 statistical_analysis.increment_number_test_cases_used()491 tokens = date_time_operations.get_date_time_tokens_of_filename("12-2018-14-11-50-912982.invalid")492 if (None != tokens) and (number_of_tokens == len(tokens)):493 print(prompt .format("FAIL!!!"))494 else:495 print(prompt .format("OK"))496 statistical_analysis.increment_number_test_cases_passed()497 prompt = " ... Test: with None object {}"498 statistical_analysis.increment_number_test_cases_used()499 tokens = None500 if (None != tokens) and (number_of_tokens == len(tokens)):501 print(prompt .format("FAIL!!!"))502 else:503 print(prompt .format("OK"))504 statistical_analysis.increment_number_test_cases_passed()505 prompt = " ... Test: valid DD-MM-YY-HR-MN-SS-US format {}"506 statistical_analysis.increment_number_test_cases_used()507 tokens = date_time_operations.get_date_time_tokens_of_filename(generate_filename.create_filename())508 if (None != tokens) and (number_of_tokens == len(tokens)):509 print(prompt .format("OK"))510 statistical_analysis.increment_number_test_cases_passed()511 else:512 print(prompt .format("FAIL!!!"))513 ## =========================================================514 # Method to test the methods that perform date and time515 # operations.516 # @return - Nothing.517 # O(1) method.518 @staticmethod519 def test_date_time_operations():520 date_time_operations_tester.test_time_operations()521 date_time_operations_tester.test_is_valid_year()522 date_time_operations_tester.test_is_valid_month()523 date_time_operations_tester.test_is_valid_31_day_month()524 date_time_operations_tester.test_is_valid_30_day_month()525 date_time_operations_tester.test_is_valid_date_in_Feb()526 date_time_operations_tester.test_date_operations()...
FindMeshBoundary.py
Source:FindMeshBoundary.py
1import math2import matplotlib.pyplot as plt # For displaying array as image3import numpy as np4def euclidean_distance(a, b):5 dx = a[0] - b[0]6 dy = a[1] - b[1]7 return math.sqrt(dx * dx + dy * dy)8def findTopY(x, maxDimension, trifinder, incrementX, incrementY):9 actualY = -110 actualX = -111 currentX = x12 yValues = []13 i = 014 while i < maxDimension:15 yValues.append(i)16 i += incrementY17 print(yValues)18 for y in yValues:19 tri = trifinder(currentX, y) # If the return value is -1, then no triangle was found.20 if tri != -1:21 actualY = y22 actualX = currentX23 break24 currentX += incrementX25 return actualX, actualY26def findBottomY(x, maxDimension, trifinder, incrementX, incrementY):27 actualY = -128 actualX = -129 currentX = x30 yValues = []31 i = 032 while i < maxDimension:33 yValues.append(i)34 i += incrementY35 for y in yValues:36 tri = trifinder(x, y) # If the return value is -1, then no triangle was found.37 if tri != -1:38 actualY = y39 actualX = currentX40 break41 currentX += incrementX42 return actualX, actualY43def findBottom(startPoint, endPoint, incrementX, incrementY, distance, trifinder):44 actualY = -145 actualX = -146 points = []47 currentPoint = startPoint48 singleIncrementX = incrementX / abs(incrementX)49 ratio = incrementY / incrementX50 singleIncrementY = incrementY / abs(incrementX) * abs(ratio)51 while euclidean_distance(currentPoint, startPoint) <= distance:52 tri = trifinder(currentPoint[0], currentPoint[1]) # If the return value is -1, then no triangle was found.53 if tri != -1:54 actualY = currentPoint[1]55 actualX = currentPoint[0]56 break57 # currentPoint = (currentPoint[0] + incrementX, currentPoint[1] + incrementY)58 currentPoint = (currentPoint[0] + singleIncrementX, currentPoint[1] + singleIncrementY)59 return actualX, actualY60def findTop(startPoint, endPoint, incrementX, incrementY, distance, trifinder):61 actualY = -162 actualX = -163 points = []64 currentPoint = startPoint[:]65 singleIncrementX = incrementX / abs(incrementX)66 ratio = incrementY / incrementX67 singleIncrementY = incrementY / abs(incrementX) * abs(ratio)68 ADAPTIVE = False69 if ADAPTIVE:70 highPoint = endPoint[:]71 lowPoint = startPoint[:]72 print("Increments:", incrementX, incrementY, ratio, singleIncrementX, singleIncrementY)73 print('Distance:', distance)74 print("Start:", startPoint)75 print("End:", endPoint)76 while euclidean_distance(lowPoint, highPoint) > distance / 5:77 print('Euclidean: ', euclidean_distance(lowPoint, highPoint), currentPoint)78 tri = trifinder(currentPoint[0], currentPoint[1]) # If the return value is -1, then no triangle was found.79 print('Tri: ', tri)80 if tri != -1:81 # CurrentPoint is in the mesh. CurrentPoint becomes the high point.82 highPoint = currentPoint83 midPoint = [ (currentPoint[0] + lowPoint[0]) / 2, (currentPoint[1] + lowPoint[1]) / 2 ]84 currentPoint = midPoint85 else:86 # CurrentPoint is not in the mesh. CurrentPoint becomes the low point.87 lowPoint = currentPoint88 midPoint = [ (currentPoint[0] + highPoint[0]) / 2, (currentPoint[1] + highPoint[1] ) / 2]89 currentPoint = midPoint90 # actualY = currentPoint[1]91 # actualX = currentPoint[0]92 currentPoint = lowPoint[:]93 tri = trifinder(currentPoint[0], currentPoint[1])94 while tri != 1 and euclidean_distance(currentPoint, startPoint) < distance:95 print(currentPoint)96 currentPoint = [currentPoint[0] + singleIncrementX, currentPoint[1] + singleIncrementY]97 tri = trifinder(currentPoint[0], currentPoint[1])98 if euclidean_distance(currentPoint, startPoint) < distance:99 actualY = currentPoint[1]100 actualX = currentPoint[0]101 else:102 # Fill in the rest of the line.103 while euclidean_distance(currentPoint, startPoint) <= distance:104 tri = trifinder(currentPoint[0], currentPoint[1]) # If the return value is -1, then no triangle was found.105 if tri != -1:106 actualY = currentPoint[1]107 actualX = currentPoint[0]108 break109 # currentPoint = (currentPoint[0] + incrementX, currentPoint[1] + incrementY)110 currentPoint = (currentPoint[0] + singleIncrementX, currentPoint[1] + singleIncrementY)111 return actualX, actualY112def findTopBottom(startPoint, endPoint, incrementX, incrementY, distance, trifinder):113 # print("findTopBottom - Increments: ", incrementX, incrementY)114 topX, topY = findTop(startPoint, endPoint, incrementX, incrementY, distance, trifinder)115 bottomX, bottomY = findBottom(endPoint, startPoint, -incrementX, -incrementY, distance, trifinder)116 return [[topX,topY], [bottomX,bottomY]]117def findLeftX(y, maxDimension, trifinder):118 actualX = -1119 for x in range(maxDimension):120 tri = trifinder(x, y) # If the return value is -1, then no triangle was found.121 if tri != -1:122 actualX = x123 break124 return actualX125def findRightX(y, maxDimension, trifinder):126 actualX = -1127 for x in range(maxDimension, 0, -1):128 tri = trifinder(x, y) # If the return value is -1, then no triangle was found.129 if tri != -1:130 actualX = x131 break132 return actualX133def findLeftRight(y, maxDimension, trifinder, spacing):134 leftX = findLeftX(y, maxDimension, trifinder)135 rightX = findRightX(y, maxDimension, trifinder)136 return [(leftX, y), (rightX, y)]137def generateBoundaryPoints(angle, dimension, spacing):138 angle = angle % 360139 # Generate all the points around the boundary.140 # Find x values along the y = 0 axis.141 print ('starting angle: ', angle)142 xaxis = False143 if angle == 180:144 angle = angle - 180145 xaxis = True146 elif angle == 270:147 angle = angle - 180148 xaxis = False149 elif angle == 90:150 xaxis = False151 elif angle == 0:152 xaxis = True153 elif angle > 45 and angle <= 135:154 # section b and c.155 xaxis = False156 elif (angle > 180 and angle <= 225) or (angle > 315 and angle <= 360) :157 # section e and h158 angle = angle - 180159 xaxis = True160 elif (angle > 225 and angle <= 315):161 # section f and g162 angle = angle - 180163 xaxis = False164 else:165 # section a and d.166 xaxis = True167 print('Actual angle: ', angle)168 print('XAxis: ', xaxis)169 if xaxis:170 xAxisValues = generateXAxisPoints(angle, dimension, spacing)171 yAxisValues = []172 else:173 xAxisValues = []174 yAxisValues = generateYAxisPoints(angle, dimension, spacing)175 return xAxisValues, yAxisValues176def generateYAxisPoints(angle, dimension, spacing):177 AxisValues = []178 extension = int(dimension * 0.8) # At most we need extension for 45 degrees: sin(45) = 0.707179 print('Extension: ', extension)180 for i in range(-extension, dimension + extension, spacing):181 singleLine = []182 startPoint = [0, i]183 singleLine.append(startPoint)184 singleLine.append(generateYAxisLimitPoint(angle, dimension, spacing, startPoint))185 AxisValues.append(singleLine)186 # print(AxisValues)187 return np.array(AxisValues)188def generateXAxisPoints(angle, dimension, spacing):189 AxisValues = []190 # extension = int(math.sin(math.radians(angle)) * dimension *1.5 ) # int(dimension * 0.75) # At most we need extension for 45 degrees: sin(45) = 0.707191 extension = int(dimension * 0.8) # At most we need extension for 45 degrees: sin(45) = 0.707192 print('Extension: ', extension)193 for i in range(-extension, dimension + extension, spacing):194 singleLine = []195 startPoint = [i,0]196 singleLine.append(startPoint)197 singleLine.append(generateXAxisLimitPoint(angle, dimension, spacing, startPoint))198 AxisValues.append(singleLine)199 # print(AxisValues)200 return np.array(AxisValues)201def generateXAxisLimitPoint(angle, dimension, spacing, startPoint):202 # section a, d, and angle 0.203 if angle == 0:204 incrementX = 0205 incrementY = dimension206 elif angle > 0 and angle <= 45:207 incrementX = math.sin(math.radians(angle))208 incrementY = math.cos(math.radians(angle))209 adjustToDimension = dimension / abs(incrementY)210 incrementX *= adjustToDimension211 incrementY *= adjustToDimension212 elif angle > 135 and angle < 180:213 incrementX = -math.sin(math.radians(angle)) # Flip the direction to stay in positive grid.214 incrementY = -math.cos(math.radians(angle)) # Flip the direction to stay in positive grid.215 adjustToDimension = dimension / abs(incrementY)216 incrementX *= adjustToDimension217 incrementY *= adjustToDimension218 return [startPoint[0]+incrementX, startPoint[1]+incrementY]219def generateYAxisLimitPoint(angle, dimension, spacing, startPoint):220 # section a, d, and angle 0.221 if angle == 90:222 incrementX = dimension223 incrementY = 0224 elif angle > 45 and angle < 90:225 incrementX = math.sin(math.radians(angle))226 incrementY = math.cos(math.radians(angle))227 adjustToDimension = dimension / abs(incrementX)228 incrementX *= adjustToDimension229 incrementY *= adjustToDimension230 elif angle > 90 and angle <= 135:231 incrementX = math.sin(math.radians(angle))232 incrementY = math.cos(math.radians(angle)) # Flip the direction to stay in positive grid.233 adjustToDimension = dimension / abs(incrementX)234 incrementX *= adjustToDimension235 incrementY *= adjustToDimension236 return [startPoint[0]+incrementX, startPoint[1]+incrementY]237if __name__ == '__main__':238 angle = 4239 spacing = 20240 gridsize = (3, 2)241 dimension = 100242 lim = 200243 fig = plt.figure(figsize=(12, 8))244 ax1 = plt.subplot2grid(gridsize, (1, 0), rowspan=2 )245 # ax1.set_xticks(np.arange(0, dimension, spacing))246 # ax1.set_yticks(np.arange(0, dimension, spacing))247 ax1.grid()248 ax2 = plt.subplot2grid(gridsize, (1, 1), rowspan=2 )249 # ax1.set_xlim([-lim, lim])250 # ax1.set_ylim([-lim, lim])251 xAxisValues, yAxisValues = generateBoundaryPoints(angle, dimension, spacing)252 for line in xAxisValues:253 # print(line)254 ax1.plot(line[:,0], line[:,1], marker='.')255 for line in yAxisValues:256 ax1.plot(line[:, 0], line[:, 1], marker='.')257 # ax1.plot((45,45), marker='o')258 plt.grid()...
firebase.js
Source:firebase.js
1// @flow2import admin from 'firebase-admin';3import type { Stats, DailyStats } from 'shared/types/state';4export async function getStats(): Promise<Stats> {5 const db = getDb();6 if (!db) {7 return {8 actionAcc: 0,9 actionLeft: 0,10 actionRight: 0,11 actionRotate: 0,12 games: 0,13 lines: 0,14 seconds: 015 };16 } else {17 const ref = db.ref('counts');18 const res = await ref.once('value');19 return prepareStats(res.val());20 }21}22export async function getDailyStats(): Promise<DailyStats> {23 const db = getDb();24 if (!db) {25 return {};26 } else {27 const gameRef = db.ref('dailyGameCounts');28 const gameRes = await gameRef.once('value');29 const turnRef = db.ref('dailyTurnCounts');30 const turnRes = await turnRef.once('value');31 return prepareDailyStats(gameRes.val(), turnRes.val());32 }33}34export function onStatsChange(changeHandler: (stats: Stats) => void) {35 const db = getDb();36 if (db) {37 const ref = db.ref('counts');38 ref.on('value', snapshot => {39 changeHandler(prepareStats(snapshot.val()));40 });41 }42}43export function incrementUserCount() {44 incrementCount('users');45}46export function incrementGameCount() {47 incrementCount('games');48 incrementDailyGameCount();49}50export function incrementTurnCount() {51 incrementCount('turns');52 incrementDailyTurnCount();53}54export function incrementLineCount(lines: number) {55 incrementCount('lines', lines);56}57export function incrementActionLeft(times: number) {58 incrementCount('actionLeft', times);59}60export function incrementActionRight(times: number) {61 incrementCount('actionRight', times);62}63export function incrementActionAcc(times: number) {64 incrementCount('actionAcc', times);65}66export function incrementActionRotate(times: number) {67 incrementCount('actionRotate', times);68}69export function incrementGameTime(seconds: number) {70 incrementCount('seconds', seconds);71}72const { FIREBASE_SERVICE_ACCOUNT } = process.env;73const cert = FIREBASE_SERVICE_ACCOUNT74 ? JSON.parse(FIREBASE_SERVICE_ACCOUNT)75 : null;76if (!cert) {77 console.warn('Firebase not configured');78} else {79 // https://stackoverflow.com/a/5037609280 cert.private_key = cert.private_key.replace(/\\n/g, '\n');81}82let db;83// This function receives a callback to gracefully ignore these calls in84// development, where credentials are missing85function getDb() {86 if (!cert) {87 return null;88 }89 if (!db) {90 admin.initializeApp({91 credential: admin.credential.cert(cert),92 databaseURL: 'https://flatris-forever.firebaseio.com'93 });94 db = admin.database();95 }96 return db;97}98function incrementCount(collection: string, by = 1) {99 const db = getDb();100 if (db) {101 const ref = db.ref('counts').child(collection);102 // If it has never been set it returns null103 ref.transaction(curCount => (curCount === null ? by : curCount + by));104 }105}106function incrementDailyGameCount() {107 const db = getDb();108 if (db) {109 const ref = db.ref('dailyGameCounts').child(getTodaysDate());110 ref.transaction(curCount => (curCount === null ? 1 : curCount + 1));111 }112}113function incrementDailyTurnCount() {114 const db = getDb();115 if (db) {116 const ref = db.ref('dailyTurnCounts').child(getTodaysDate());117 ref.transaction(curCount => (curCount === null ? 1 : curCount + 1));118 }119}120function prepareStats(rawStats) {121 const {122 actionAcc,123 actionLeft,124 actionRight,125 actionRotate,126 games,127 lines,128 seconds,129 turns130 } = rawStats;131 return {132 actionAcc,133 actionLeft,134 actionRight,135 actionRotate,136 games: games + turns,137 lines,138 seconds139 };140}141function prepareDailyStats(gameCounts, turnCounts) {142 const days = Object.keys(gameCounts);143 const totalCounts = {};144 days.forEach(day => {145 totalCounts[day] = gameCounts[day] + (turnCounts[day] || 0);146 });147 return totalCounts;148}149function getTodaysDate() {150 return new Date().toISOString().slice(0, 10);...
Day22_Prob1_10006_Deck.py
Source:Day22_Prob1_10006_Deck.py
...20 else:21 new_deck += deck[n:]22 new_deck += deck[:n]23 return new_deck24def deal_with_increment(deck, n):25 new_deck = []26 pos = 027 take_from = 028 for time in range(0, len(deck)):29 new_deck += [0]30 for time in range(0, len(deck)):31 if pos > len(new_deck)-1:32 pos -= len(new_deck)33 new_deck[pos] = deck[take_from]34 pos += n35 take_from += 136 return new_deck37deck_10 = []38for c in range(0, 10007):39 deck_10 += [c]40string = '''cut 937441deal with increment 4842cut -235443deal with increment 1244cut -703945deal with increment 1446cut -232547deal with increment 4048deal into new stack49cut 421950deal with increment 1551cut -339352deal with increment 4853cut 122154deal with increment 6655cut 133656deal with increment 5357deal into new stack58cut -500859deal into new stack60deal with increment 3461cut 850962deal with increment 2463cut -129264deal into new stack65cut 840466deal with increment 1767cut -10568deal with increment 5169cut 297470deal with increment 571deal into new stack72deal with increment 5373cut 15574deal with increment 3175cut 283176deal with increment 6177cut -419378deal into new stack79cut 994280deal with increment 1381cut -53282deal with increment 4183cut 284784deal into new stack85cut -260986deal with increment 7287cut 909888deal with increment 6489deal into new stack90cut 429291deal into new stack92cut -442793deal with increment 2494cut -471395deal into new stack96cut 589897deal with increment 5698cut -251599deal with increment 2100cut -5502101deal with increment 66102cut 8414103deal with increment 7104deal into new stack105deal with increment 35106deal into new stack107deal with increment 29108cut -2176109deal with increment 14110cut 7773111deal with increment 36112cut 2903113deal into new stack114deal with increment 75115cut 239116deal with increment 45117cut 5450118deal with increment 10119cut 6661120deal with increment 64121cut -6842122deal with increment 40123deal into new stack124deal with increment 31125deal into new stack126deal with increment 46127cut 6462128deal into new stack129cut -8752130deal with increment 28131deal into new stack132deal with increment 43133deal into new stack134deal with increment 54135cut 9645136deal with increment 44137cut 5342138deal with increment 66139cut 3785'''140string = string.split('\n')141for item in string:142 command = item.split()143 if command[0] == 'cut':144 deck_10 = cut(deck_10, int(command[-1]))145 else:146 if command[1] == 'into':147 deck_10 = deal_into_new_stack(deck_10)148 else:149 deck_10 = deal_with_increment(deck_10, int(command[-1]))...
use-latest-ref.js
Source:use-latest-ref.js
1/**2 * External dependencies3 */4import { render, screen, fireEvent, waitFor } from '@testing-library/react';5/**6 * WordPress dependencies7 */8import { useState } from '@wordpress/element';9/**10 * Internal dependencies11 */12import { useLatestRef } from '..';13function debounce( callback, timeout = 0 ) {14 let timeoutId = 0;15 return ( ...args ) => {16 window.clearTimeout( timeoutId );17 timeoutId = window.setTimeout( () => callback( ...args ), timeout );18 };19}20function useDebounce( callback, timeout = 0 ) {21 const callbackRef = useLatestRef( callback );22 return debounce( ( ...args ) => callbackRef.current( ...args ), timeout );23}24function Example() {25 const [ count, setCount ] = useState( 0 );26 const increment = () => setCount( count + 1 );27 const incrementDebounced = debounce( increment, 50 );28 const incrementDebouncedWithLatestRef = useDebounce( increment, 50 );29 return (30 <>31 <div>Count: { count }</div>32 <button onClick={ incrementDebounced }>Increment debounced</button>33 <button onClick={ increment }>Increment immediately</button>34 <br />35 <button onClick={ incrementDebouncedWithLatestRef }>36 Increment debounced with latest ref37 </button>38 </>39 );40}41function sleep( milliseconds ) {42 return new Promise( ( resolve ) =>43 window.setTimeout( resolve, milliseconds )44 );45}46function getCount() {47 return screen.getByText( /Count:/ ).innerHTML;48}49function incrementCount() {50 fireEvent.click( screen.getByText( 'Increment immediately' ) );51}52function incrementCountDebounced() {53 fireEvent.click( screen.getByText( 'Increment debounced' ) );54}55function incrementCountDebouncedRef() {56 fireEvent.click(57 screen.getByText( 'Increment debounced with latest ref' )58 );59}60describe( 'useLatestRef', () => {61 describe( 'Example', () => {62 // prove the example works as expected63 it( 'should start at 0', () => {64 render( <Example /> );65 expect( getCount() ).toEqual( 'Count: 0' );66 } );67 it( 'should increment immediately', () => {68 render( <Example /> );69 incrementCount();70 expect( getCount() ).toEqual( 'Count: 1' );71 } );72 it( 'should increment after debouncing', async () => {73 render( <Example /> );74 incrementCountDebounced();75 expect( getCount() ).toEqual( 'Count: 0' );76 await waitFor( () => sleep( 0 ) );77 expect( getCount() ).toEqual( 'Count: 1' );78 } );79 it( 'should increment after debouncing with latest ref', async () => {80 render( <Example /> );81 incrementCountDebouncedRef();82 expect( getCount() ).toEqual( 'Count: 0' );83 await waitFor( () => sleep( 0 ) );84 expect( getCount() ).toEqual( 'Count: 1' );85 } );86 } );87 it( 'should increment to one', async () => {88 render( <Example /> );89 incrementCountDebounced();90 incrementCount();91 await waitFor( () => sleep( 0 ) );92 expect( getCount() ).toEqual( 'Count: 1' );93 } );94 it( 'should increment to two', async () => {95 render( <Example /> );96 incrementCountDebouncedRef();97 incrementCount();98 await waitFor( () => sleep( 0 ) );99 expect( getCount() ).toEqual( 'Count: 2' );100 } );...
Day22_Prob2_Tracking_One_Position.py
Source:Day22_Prob2_Tracking_One_Position.py
...13 pos += deck_len - abs(n)14 else:15 pos -= abs(n)16 return pos17def deal_with_increment(pos, n):18 x = 019 while True:20 new_pos = (pos + x * deck_len) / n21 if new_pos.is_integer():22 return int(new_pos)23 else:24 x += 125real_string = '''cut 937426deal with increment 4827cut -235428deal with increment 1229cut -703930deal with increment 1431cut -232532deal with increment 4033deal into new stack34cut 421935deal with increment 1536cut -339337deal with increment 4838cut 122139deal with increment 6640cut 133641deal with increment 5342deal into new stack43cut -500844deal into new stack45deal with increment 3446cut 850947deal with increment 2448cut -129249deal into new stack50cut 840451deal with increment 1752cut -10553deal with increment 5154cut 297455deal with increment 556deal into new stack57deal with increment 5358cut 15559deal with increment 3160cut 283161deal with increment 6162cut -419363deal into new stack64cut 994265deal with increment 1366cut -53267deal with increment 4168cut 284769deal into new stack70cut -260971deal with increment 7272cut 909873deal with increment 6474deal into new stack75cut 429276deal into new stack77cut -442778deal with increment 2479cut -471380deal into new stack81cut 589882deal with increment 5683cut -251584deal with increment 285cut -550286deal with increment 6687cut 841488deal with increment 789deal into new stack90deal with increment 3591deal into new stack92deal with increment 2993cut -217694deal with increment 1495cut 777396deal with increment 3697cut 290398deal into new stack99deal with increment 75100cut 239101deal with increment 45102cut 5450103deal with increment 10104cut 6661105deal with increment 64106cut -6842107deal with increment 40108deal into new stack109deal with increment 31110deal into new stack111deal with increment 46112cut 6462113deal into new stack114cut -8752115deal with increment 28116deal into new stack117deal with increment 43118deal into new stack119deal with increment 54120cut 9645121deal with increment 44122cut 5342123deal with increment 66124cut 3785'''125string = real_string126string = string.split('\n')127string.reverse()128position = 2020129for time in range(0, shuffle_times):130 for item in string:131 command = item.split()132 if command[0] == 'cut':133 position = cut(position, int(command[-1]))134 else:135 if command[1] == 'into':136 position = deal_into_new_stack(position)137 else:138 position = deal_with_increment(position, int(command[-1]))139 if position >= deck_len:140 position -= deck_len * (position // deck_len)141 elif position < 0:142 position += deck_len * (position // deck_len)143 print(position)...
Counter.js
Source:Counter.js
...27 <span className={styles.value}>{count}</span>28 <button29 className={styles.button}30 aria-label="Increment value"31 onClick={() => dispatch(increment())}32 >33 +34 </button>35 </div>36 <div className={styles.row}>37 <input38 className={styles.textbox}39 aria-label="Set increment amount"40 value={incrementAmount}41 onChange={(e) => setIncrementAmount(e.target.value)}42 />43 <button44 className={styles.button}45 onClick={() => dispatch(incrementByAmount(incrementValue))}...
Using AI Code Generation
1var expect = require('unexpected').clone();2expect.output.preferredWidth = 80;3expect.addAssertion('<any> to be a number', function (expect, subject) {4 expect(subject, 'to be a', 'number');5});6expect.addAssertion('<any> to be a string', function (expect, subject) {7 expect(subject, 'to be a', 'string');8});9describe("Test Suite", function () {10 it("Test Case", function () {11 expect(1, 'to be a number');12 });13});14var expect = require('unexpected').clone();15expect.output.preferredWidth = 80;16expect.addAssertion('<any> to be a number', function (expect, subject) {17 expect(subject, 'to be a', 'number');18});19expect.addAssertion('<any> to be a string', function (expect, subject) {20 expect(subject, 'to be a', 'string');21});22describe("Test Suite", function () {23 it("Test Case", function () {24 expect(1, 'to be a number');25 });26});27var expect = require('unexpected').clone();28expect.output.preferredWidth = 80;29expect.addAssertion('<any> to be a number', function (expect, subject) {30 expect(subject, 'to be a', 'number');31});32expect.addAssertion('<any> to be a string', function (expect, subject) {33 expect(subject, 'to be a', 'string');34});35describe("Test Suite", function () {36 it("Test Case", function () {37 expect(1, 'to be a number');38 });39});40var expect = require('unexpected').clone();41expect.output.preferredWidth = 80;42expect.addAssertion('<any> to be a number', function (expect, subject) {43 expect(subject, 'to be a', 'number');44});45expect.addAssertion('<any> to be a string', function (expect, subject)
Using AI Code Generation
1const expect = require('unexpected').clone();2expect.output.preferredWidth = 80;3function increment(x) {4 return x + 1;5}6expect(increment(3), 'to equal', 4);7The [Unexpected CLI](
Using AI Code Generation
1const mitm = require('unexpected-mitm');2const expect = require('unexpected')3 .clone()4 .use(mitm);5const request = require('request-promise-native');6const http = require('http');7const server = http.createServer((req, res) => {8 res.statusCode = 200;9 res.end();10});11describe('test', () => {12 before(() => {13 server.listen(8080);14 });15 after(() => {16 server.close();17 });18 it('should make a request', () => {19 });20});21#### `expect.mitm.mockResponse(options)`22const mitm = require('unexpected-mitm');23const expect = require('unexpected')24 .clone()25 .use(mitm);26const request = require('request-promise-native');27const http = require('http');28const server = http.createServer((req, res) => {29 res.statusCode = 200;30 res.end();31});32describe('test', () => {33 before(() => {34 server.listen(8080);35 });36 after(() => {37 server.close();38 });39 it('should mock a response', () => {40 expect.mitm.mockResponse({
Using AI Code Generation
1const expect = require('unexpected');2const unexpectedMongo = require('unexpected-mongodb');3expect.installPlugin(unexpectedMongo);4const collection = 'testCollection';5const database = 'testDatabase';6const client = new MongoClient(mongoUrl);7const db = client.db(database);8before(() => {9 return client.connect();10});11after(() => {12 return client.close();13});14describe('test', () => {15 beforeEach(() => {16 return db.collection(collection).deleteMany({});17 });18 it('should increment field', async () => {19 await db.collection(collection).insertOne({ a: 1 });20 await expect(21 {22 query: { a: 1 },23 update: { $inc: { a: 1 } }24 },25 [{ a: 2 }]26 );27 });28});29const expect = require('unexpected');30const unexpectedMongo = require('unexpected-mongodb');31expect.installPlugin(unexpectedMongo);32const collection = 'testCollection';
Using AI Code Generation
1const { expect } = require('unexpected');2const { expect, increment } = require('unexpected');3const { expect, increment } = require('unexpected');4const { expect, increment } = require('unexpected');5const { expect, increment } = require('unexpected');6const { expect, increment } = require('unexpected');7const { expect, increment } =
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!!