Beispiel #1
0
  def test_get_population(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    self.assertTrue(my_graph.get_biggest_city().code == 'MEX')
    self.assertTrue(my_graph.get_smallest_city().code == 'SCL')
Beispiel #2
0
 def __init__(self, file, lang='pl'):
     Controller.__init__(self, file=file)
     self.language = lang
     self.special_characters = [
         '.', '!', '?', ',', '"', '\'', ')', '(', '-', '–', ':', ';'
     ]
     self.end_of_sentence_characters = ['.', '!', '?']
     self.resList = None  # List without dots and etc. and without stopWords
     self.stopWordsList = None  # StopWord list
     self.resListSplit = None  # List with dots and etc. and with stopWords
     self.sentenceList = []  # Sentence list
     self.termList = []  # Term list
     self.ret30percent = None  # Dictionary G
     self.resListSplitWithDots = None  # List with dots and etc.
     self.Dw = None  # Dw = ['konczy', 'sie', 'zdanie'] from D = [('konczy', 2), ('sie', 2), ('zdanie', 2)]
     self.Gw = None  # Thesame like Dw
     self.wordTermDict = {}  # dictionary [word:(term1, term2, ...)]
     self.coocurenceMatrix = None  # Matrix
     self.termSentencesTotalSize = [
     ]  # counts all terms in sentence where a term occurs
     self.chi2Values = []  # list of tuples (word, values of chi squared)
     if self.language == 'pl':
         self.morfeuszProcess = subprocess.Popen(
             ['morfeusz_bin\morfeusz_analyzer.exe', '-c', 'UTF8'],
             stdin=subprocess.PIPE,
             stdout=subprocess.PIPE,
             bufsize=1)
     else:
         self.porterStemmer = PorterStemmer()  # stemmer for english
Beispiel #3
0
  def test_get_average_distances_of_flight(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    #print(my_graph.list_metros())
    self.assertTrue(my_graph.get_average_distances_of_flight() == (4231+2453)/2.0 )
Beispiel #4
0
  def test_list_metros(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    #print(my_graph.list_metros())
    self.assertTrue(len(my_graph.list_metros()) == 3 )
Beispiel #5
0
def start_workers(num_agents: int = 1,
                  env_name: str = '',
                  state_builder: StateBuilder = None,
                  num_epochs: int = 2001,
                  update_frequency: int = 10):

    State.num_agents = num_agents

    for agent in range(num_agents):
        controller = Controller(learner=None,
                                env_id=env_name,
                                state_builder=state_builder,
                                update_freq=update_frequency,
                                id=agent)

        learner = QLearner(controller.get_action_space(),
                           epsilon=0.1,
                           init_alpha=.5,
                           gamma=.9,
                           decay_rate=.999)

        controller.set_learner(learner)

        agent_thread = threading.Thread(target=controller.train,
                                        kwargs={
                                            "number_epochs":
                                            num_epochs,
                                            "save_location":
                                            '../models/{}-{}.model'.format(
                                                env_name, agent)
                                        })
        agent_thread.start()

    return
Beispiel #6
0
 def start(self):
     from data import menu_list
     try:
         while self.loop:
             choice = Controller.make_choice(menu_list[self.__menu].keys(), self.__menu)
             Controller.considering_choice(self, choice, list(menu_list[self.__menu].values()))
     except Exception as e:
         ViewHelper.show_error(str(e))
    def test_cell_click(self):
        """when a cell is clicked, its text should appear 
			in the top_text"""

        controller = Controller(self.grid)

        controller.clickAt((0, 0))
        self.assertEqual("cell content", controller.getTopText())
Beispiel #8
0
	def test_cell_click(self):
		"""when a cell is clicked, its text should appear 
			in the top_text"""

		controller = Controller(self.grid)

		controller.clickAt((0,0))
		self.assertEqual("cell content",controller.getTopText())
Beispiel #9
0
  def test_get_single_flight(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    #print(my_graph.list_metros())
    self.assertTrue(my_graph.get_longest_single_flight().distance == 4231 )
    self.assertTrue(my_graph.get_shortest_single_flight().distance == 2453)
Beispiel #10
0
  def test_add_edges(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")

    self.assertTrue(len(my_graph.routes) == 2*2)
    self.assertTrue('BOG' not in my_graph.metros)
Beispiel #11
0
  def test_get_city_info(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")

    self.assertTrue(my_graph.get_city_info('LIM') is not None)
    self.assertTrue(my_graph.get_city_info('LIMM') is None)
    self.assertTrue(my_graph.get_city_info("Lima") is not None)
 def test_create_tours_1(self):
     Controller.recreate_tables()
     print("all needed attributes")
     expected_response = {
         'extendedDocs': [],
         'name': 'First tour',
         'id': 1,
         'description': 'This is the first guided tour'
     }
     assert expected_response == TourController.create_tour(
         "First tour", "This is the first guided tour")
Beispiel #13
0
def main():
    BorrowRepo = BorrowRepository("borrow.txt")
    DvdRepo = DvdRepository("dvd.txt")
    
    ctrl = Controller(BorrowRepo,DvdRepo) 
    ui = UI(ctrl)
    ui.run()
Beispiel #14
0
    def config(self):
        self.readSettings()
        clientRepo = None
        bookRepo = None
        rentalRepo = None
        if self.__settings['repository'] == "in-memory":
            clientRepo = ClientRepo()
            bookRepo = BookRepo()
            rentalRepo = RentalRepo()

            clientRepo.initialiseclients()
            bookRepo.initialisebooks()
            rentalRepo.initialiserentals()

        if self.__settings['repository'] == "text-file":
            clientRepo = FileClientRepo2(self.__settings["clients"])
            bookRepo = FileBookRepo(self.__settings["books"])
            rentalRepo = FileRentalRepo(self.__settings["rentals"])

        if self.__settings['repository'] == "binary":
            clientRepo = BinaryClientRepo(self.__settings["clients"])
            bookRepo = BinaryBookRepo(self.__settings["books"])
            rentalRepo = BinaryRentalRepo(self.__settings["rentals"])

        undo = UndoController()
        ctrl = Controller(bookRepo, clientRepo, rentalRepo, undo)
        ui = None
        if self.__settings['ui'] == "console":
            ui = UI(ctrl)

        if self.__settings['ui'] == 'gui':
            ui = GUI(ctrl)

        return ui
Beispiel #15
0
    def main(self):
        filename = "sudoku.txt"
        problem = Problem()
        problem.readFromFile(filename)

        contr = Controller(problem)

        cons = Console(contr)
        cons.mainMenu()
Beispiel #16
0
    async def test_controller(self):
        _ctl = Controller()
        _ctlSpace = ControllableSpace(name='test', maxPopulation=50)
        _ctl.addControllableSpace(_ctlSpace)
        _ctlTask = asyncio.ensure_future(_ctl.start())
        _stopCtlTask = asyncio.ensure_future(
            ControllerTestCase.stop_controller(controller=_ctl))
        _watchCtl = asyncio.ensure_future(
            ControllerWatcher(sleepInterval=1.0, controller=_ctl).start())

        await _ctlTask
        await _stopCtlTask
        try:
            await _watchCtl
        except Exception as e:
            logging.exception(e)
        logging.info('Test completed')

        self.assertEqual(_ctl.controllerStop, True)
Beispiel #17
0
    def main():
        init()

        banner = '''
        _____ _____         _____            
       |_   _|  __ \\       / ____|           
         | | | |__) |_____| |  __  ___  ___  
         | | |  ___/______| | |_ |/ _ \\/ _ \\ 
        _| |_| |          | |__| |  __/ (_) |
       |_____|_|           \\_____|\\___|\\___/ 
       ---------------------------------------
        Created by : Homeless
        Version : 1.0.0
       ---------------------------------------
        '''
        print(Fore.RED + banner)
        ctrl = Controller()

        try:

            while True:
                try:
                    print(Fore.GREEN + "[1] INGRESAR API-KEY MAXMIND.")
                    print(Fore.GREEN + "[2] CONSULTAR IP.")
                    print(Fore.GREEN + "[3] SALIR", end='\n\n')

                    option = int(input("INGRESAR OPCION > "))

                    if option == 1:
                        ctrl.add_api_key()
                        continue

                    elif option == 2:
                        try:
                            ctrl.query_ip()
                            continue
                        except ValueError as ex:
                            print(Fore.RED + "[X] " + ex.__str__(), end="\n\n")
                    elif option == 3:
                        ctrl.exit_program()
                        continue
                    else:
                        print(Fore.RED + "[X] Opcion no valida", end="\n\n")
                except ValueError:
                    print(Fore.RED + "[X] Opcion no valida", end="\n\n")
                    continue
                except requests.HTTPError as ex:
                    print(Fore.RED + "[X] API-KEY Maxmind: " + ex.__str__(),
                          end="\n\n")
                    continue
        except KeyboardInterrupt:
            exit(0)
 def test_create_document(self):
     Controller.recreate_tables()
     print("Create a valid document")
     expected_response = {
         'id': 1,
         'comments': [],
         'user_id': 1,
         'publicationDate': None,
         'subject': 'Subject1',
         'title': 'title',
         'refDate': None,
         'file': '1.gif',
         'originalName': None,
         'description': 'a description',
         'type': 'type',
         'validationStatus': {
             'status': Status.Validated,
             'doc_id': 1
         },
         'visualization': {
             'quaternionZ': None,
             'positionZ': None,
             'positionX': None,
             'id': 1,
             'quaternionY': None,
             'quaternionW': None,
             'positionY': None,
             'quaternionX': None
         }
     }
     assert expected_response == DocController.create_document(
         {
             'title': 'title',
             'subject': 'Subject1',
             'type': 'type',
             'description': 'a description',
             'file': '1.gif',
             'user_id': 1,
             "role": {
                 'label': 'admin'
             }
         }, {'user_id': 1})
Beispiel #19
0
    async def test_controller_remove_population(self):
        _ctl = Controller()
        _ctlSpace = ControllableSpace(name='test', maxPopulation=50)
        _ctl.addControllableSpace(_ctlSpace)
        _ctlTask = asyncio.ensure_future(_ctl.start())
        _stopCtlTask = asyncio.ensure_future(
            ControllerTestCase.stop_controller(controller=_ctl))
        _watchCtl = asyncio.ensure_future(
            ControllerWatcher(sleepInterval=1.0, controller=_ctl).start())

        async def addControllableItems(howMany: int = 10):
            tries = 0
            while True:
                logging.info(f'Adding {howMany} items')
                for _i in range(howMany):
                    _ctl.addControllableItem(ControllableItem(
                        objectLocation=self._nyc,
                        controllable=True,
                        name=f'name_{_i}_{tries}',
                        parentController=_ctl),
                                             ctlSpace=_ctlSpace.name)
                    await asyncio.sleep(0.2)
                tries += 1
                await asyncio.sleep(1.0)

        async def removeControllableItems(howMany: int = 10):
            tries = 0

            await asyncio.sleep(5.0)
            logging.info(f'Removing {howMany} items')
            for _i in range(howMany):
                _ctl.removeControllableItem(name=f'name_{_i}_{tries}',
                                            ctlSpace='test')
            await asyncio.sleep(3.0)

        _addCtlTask = asyncio.ensure_future(addControllableItems())
        _delCtlTask = asyncio.ensure_future(removeControllableItems())

        await _ctlTask
        await _stopCtlTask
        try:
            await _watchCtl
        except Exception as e:
            logging.exception(e)

        try:
            await _addCtlTask
        except MaxControllableSpacePopulationException as e:
            logging.exception(e)

        try:
            _delCtlTask.cancel()
        except Exception as e:
            logging.exception(e)

        logging.info('Test completed')

        self.assertEqual(50, _ctl.getControllablePopulation('test'))
        self.assertEqual(_ctl.controllerStop, True)
Beispiel #20
0
 def menu():
     opmenu = 0  #variable que controla el menu principal de las operaciones
     while (opmenu != 6):
         print('▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼'.center(80, '▼'))
         print()
         print("::::::::::::::::::::::::::::::::::::::".center(80, " "))
         print(": ╔══════════════════════════════════════╗ :".center(
             80, ' '))
         print(": ║ SISTEMA SISTEMA AUTOMATIZADO PARA LA ║ :".center(
             80, ' '))
         print(": ║ ADMINISTRACIÓN Y GESTIÓN DEPRODUCTOS ║ :".center(
             80, ' '))
         print(": ╚══════════════════════════════════════╝ :".center(
             80, ' '))
         print("::::::::::::::::::::::::::::::::::::::".center(80, " "))
         print(
             "\n\t\t\t[1]  ► AGREGAR CLIENTE\n\t\t\t[2]  ► CONSULTAR CLIENTE"
             "\n\t\t\t[3]  ► LISTAR CLIENTES\n\t\t\t[4]  ► VENDER MUEBLE\n\t\t\t[5]  ► INGRESAR NUEVO MUEBLE\n"
             "\n\t\t\t[6]  ► SALIR\n")
         print('▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲'.center(80, '▲'))
         opmenu = input_rango("UD. PUEDE ELEGIR", 1, 6)
         print("▬▬▬▬▬▬▬▬".center(32, "▬"))
         if opmenu == 1:
             Controller.agregar_cliente()
         if opmenu == 2:
             View.leer_cedula()
         if opmenu == 3:
             Controller.listar_clientes()
         if opmenu == 4:
             Controller.vender()
         if opmenu == 5:
             Controller.agregar_mueble()
         if opmenu == 6:
             os.system('cls')
             print(
                 '..............------------... \n.............(   Adios!   ).. \n..............`--, ,-----´... \n.......@@@.......)/.......... '
             )
             print(
                 '.....@.....@.........,....... \n.....@[email protected]...... \n.......@@@.........o@@....... \n........@..........@......... \n.......@@@........@.......... '
             )
             print(
                 '......@.@..@.....@........... \n.....@..@.....@@............. \n....@...@.................... \n...@....@.................... \n..@.....@......... made ..... '
             )
             print(
                 '........@.........  by  ..... \n........@...... Ronaldo ..... \n.......@.@................... \n......@....@................. \n.....@......@................ '
             )
             print(
                 '....@........@............... \n...@..........@.............. \n.@@@..........@@@............ '
             )
Beispiel #21
0
def start_reference_aggregated_learner(env_name: str = ''):
    state_builder = StateBuilderCache.builders.get(env_name, None)

    controller = Controller(learner=None,
                            env_id=env_name,
                            state_builder=state_builder)

    learner = QLearner(controller.get_action_space(),
                       epsilon=0.1,
                       init_alpha=.5,
                       gamma=.9,
                       decay_rate=.999)

    # SET MODEL with copy of Server Model
    learner.set_model(copy.deepcopy(QServer.Q))

    controller.set_learner(learner)

    agent_thread = threading.Thread(target=controller.run)
    agent_thread.start()
    print('Started Reference Learner')

    return
Beispiel #22
0
 def __init__(self):
     Observer.__init__(self)
     self.window = tk.Tk()
     self.config = json.load(open("algorithms_config.json"))
     self.controller = Controller(self.config)
     self.window.protocol("WM_DELETE_WINDOW", self.on_closing)
     self.observe("ReloadConfigEvent", self.__on_reload_config)
     ###Utilities###
     self.maxwidth = self.window.winfo_screenwidth()
     self.maxheight = self.window.winfo_screenheight()
     self.width = int(self.maxwidth * 0.9)
     self.height = int(self.maxheight * 0.62)
     self.f1 = WorkingArea(self.width, self.height, Location.SUBTYPE, self.controller, self.window, self.config)
     self.f2 = WorkingArea(self.width, self.height, Location.SUPERTYPE, self.controller, self.window, self.config)
     self.custommenu = MenuView(self.window, self.config)
Beispiel #23
0
def use_model():
    cart_pole_ctrl = Controller(None,
                                'CartPole-v1',
                                StateBuilderCartPole(),
                                communicate=False)
    # cart_pole_ctrl = Controller(None, 'Taxi-v2', None)
    # cart_pole_ctrl = Controller(None, 'LunarLander-v2', state_builder=StateBuilderLunarLander(), communicate=False)

    learner = QLearner(cart_pole_ctrl.get_action_space(),
                       epsilon=0.0,
                       init_alpha=.5,
                       gamma=.9)

    cart_pole_ctrl.set_learner(learner)
    cart_pole_ctrl.load("models/CartPole-v1-7.model")

    count = 0
    while True:
        cart_pole_ctrl.run(render=True)
        count += 1
        print("Epoch {}".format(count))
Beispiel #24
0
def main():
    # Taxi-v2
    cart_pole_ctrl = Controller(None,
                                'CartPole-v1',
                                StateBuilderCartPole(),
                                communicate=False)
    # cart_pole_ctrl = Controller(None, 'Taxi-v2', None, communicate=False)
    # cart_pole_ctrl = Controller(None, 'LunarLander-v2', state_builder=StateBuilderLunarLander(), communicate=False)
    # cart_pole_ctrl = Controller(None, 'FrozenLake-v0', None, communicate=False)

    running_cumulative_reward = []
    for _ in range(3):
        learner = QLearner(cart_pole_ctrl.get_action_space(),
                           epsilon=0.1,
                           init_alpha=.5,
                           gamma=.9,
                           decay_rate=.999)
        cart_pole_ctrl.set_learner(learner)

        cumulative_reward, num_steps = cart_pole_ctrl.train(number_epochs=2001)
        running_cumulative_reward.append(cumulative_reward)

    ar = np.array(running_cumulative_reward)
    means = np.mean(ar, axis=0)

    standard_errors = scipy.stats.sem(ar, axis=0)
    uperconf = means + standard_errors
    lowerconf = means - standard_errors
    # avg_cumulative = ar.sum(axis=0)
    # avg_cumulative = avg_cumulative/len(running_cumulative_reward)

    x = np.arange(0, len(means))
    # plt.plot(x, means, 'o')

    z = np.polyfit(x, means, 5)
    p = np.poly1d(z)
    plt.plot(x, p(x))

    plt.fill_between(x, uperconf, lowerconf, alpha=0.3, antialiased=True)

    # plt.ylim(ymax=50, ymin=-800)

    plt.show()
    plt.close()

    # z = np.arange(0, len(num_steps))
    # plt.plot(z, num_steps)
    # plt.show()
    # plt.close()

    cart_pole_ctrl.env.close()
 def testSwap(self):        
     repo = Repository()
     
     controller = Controller(repo)
     
     controller._guess = controller.getAll()[0]
     
     assert controller._guess[1] == 'c'
     assert controller._guess[2] == 'r'
     
     controller.swap(0, 1, 0, 2)
     
     assert controller._guess[1] == 'r'
     assert controller._guess[2] == 'c'
Beispiel #26
0
def set_up_env(args):
    # Initialize agent and environment

    controller = Neurosmash.Agent()  # This is an example agent.
    if args.use_controller:
        controller = Controller(args)

    # This is the main environment.
    try:
        environment = Neurosmash.Environment(args)
    except:
        print(
            "Connecting to environment failed. Please make sure Neurosmash is running and check your settings."
        )
        print(
            f"Settings from world model: ip={args.ip}, port={args.port}, size={args.size}, timescale={args.timescale}"
        )
    else:
        print("Successfully connected to Neurosmash!")
        return controller, environment
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._ctl = Controller()
Beispiel #28
0
  def test_add_nodes(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    self.assertTrue(len(my_graph.metros) == 3)
Beispiel #29
0
  def test_get_hub(self):
    my_graph = Graph()
    my_controller = Controller(my_graph)

    my_controller.parse_file("F:/rshan3/Airline/content/map_test_data.json")
    self.assertTrue(my_graph.get_hub()[0] == 'Lima')
"""
Created on 29/01/2017
@author Stefan
"""
from console.console import Console
from controller.Controller import Controller
from controller.UndoController import UndoController
from repository.SentenceRepository import SentenceRepository

if __name__ == '__main__':
    sentence_repo = SentenceRepository()
    controller = Controller(sentence_repo)
    undo_controller = UndoController()
    console = Console(controller, undo_controller)
    console.run()

Beispiel #31
0
	def test_top_text_edit(self):
		controller = Controller(self.grid)
		controller.clickAt((1,1))
		controller.writeTopText("A new hope")

		self.assertEqual("A new hope", controller.getCurrentCellContent())
Beispiel #32
0
'''
Created on Jan 23, 2017

@author: Madalina
'''
from repository.Repository import Repository
from controller.Controller import Controller
from ui.UI import UI

repo = Repository()
controller = Controller(repo)
ui = UI(controller)

ui.mainMenu()
Beispiel #33
0
'''
Created on Mar 14, 2017

@author: Utilizator
'''
from ui.Console import Console
from controller.Controller import Controller
from domain.Graph import Graph

graph = Graph(
    "C:\\Users\\Utilizator\\Desktop\\University\\Semester 2\\Graph Algorithms\\Lab1\\graph"
)
ui = Console(Controller(graph))
ui.runApp()
    def test_top_text_edit(self):
        controller = Controller(self.grid)
        controller.clickAt((1, 1))
        controller.writeTopText("A new hope")

        self.assertEqual("A new hope", controller.getCurrentCellContent())
Beispiel #35
0
from controller.Controller import Controller
from model.Graph import Graph

__author__ = 'Ruihan'


my_graph = Graph()
my_controller = Controller(my_graph)

my_controller.parse_file("content/map_data.json")
my_controller.start()

Beispiel #36
0
    doc_id = flask.request.args.get('doctorID')
    date = flask.request.args.get('date')

    return json.dumps(controller.getDocApps(int(doc_id), date))


@app.route("/deleteAppointment", methods=['DELETE'])
def deleteAppointment():
    doc_id = flask.request.args.get('doctorID')
    app_id = flask.request.args.get('appointmentID')

    return controller.deleteDocAppointment(int(doc_id), int(app_id))


@app.route("/addAppointment", methods=['POST'])
def addAppointment():
    doc_id = int(flask.request.args.get('doctorID'))
    f_name = flask.request.args.get('fName')
    l_name = flask.request.args.get('lName')
    date = flask.request.args.get('date')
    time = flask.request.args.get('time')
    kind = flask.request.args.get('kind')

    return json.dumps(
        controller.addAppointment(doc_id, f_name, l_name, date, time, kind))


if __name__ == '__main__':
    controller = Controller()
    app.run(host='0.0.0.0', debug=True)
Beispiel #37
0
    users = [
        fake.profile(fields=['username'], sex=None)['username']
        for u in range(users_count)
    ]
    threads = []
    try:

        for i in range(users_count):
            threads.append(
                EmulationController(users[i], users, users_count,
                                    random.randint(1, 2)))
        for thread in threads:
            thread.start()

    except Exception as e:
        View.show_error(str(e))
    finally:
        for thread in threads:
            if thread.is_alive():
                thread.stop()


if __name__ == "__main__":
    choice = Controller.make_choice(
        ["Neo4j", "Emulation(use one time with worker for generate db)"],
        "Program mode")
    if choice == 0:
        Neo4jController()
    elif choice == 1:
        emulation()
Beispiel #38
0
            'password': '******'
        }))(UserTest, 'Login with wrong username', True)

        make_test(lambda: UserController.login({
            'username': '******',
            'password': '******'
        }))(UserTest, 'Login with inexisting username', True)

        make_test(lambda: UserController.login({
            'username': '',
            'password': '******'
        }))(UserTest, 'Login with empty username', True)

        make_test(lambda: UserController.login({
            'password': '******'
        }))(UserTest, 'Login with missing username', True)

        make_test(lambda: UserController.login({
        }))(UserTest, 'Login with all missing fields', True)

        make_test(lambda: UserController.login({
        }))(UserTest, 'Login with all missing fields', True)

if __name__ == '__main__':
    Controller.recreate_tables()
    UserTest.create_user()
    UserTest.login()
    print('\n\n\033[04mSuccessTest\033[01m: ',
          UserTest.nb_tests_succeed, '/',
          UserTest.nb_tests, sep='')
Beispiel #39
0
def main():
    controller = Controller()
    controller.start_app()
Beispiel #40
0
def emulation():
    fake = Faker()
    users_count = 10
    users = [
        fake.profile(fields=['username'], sex=None)['username']
        for u in range(users_count)
    ]
    threads = []
    try:
        for i in range(users_count):
            threads.append(
                EmulationController(users[i], users, users_count,
                                    random.randint(1, 2)))
        for thread in threads:
            thread.start()
    except Exception as e:
        View.show_error(str(e))
    finally:
        for thread in threads:
            if thread.is_alive():
                thread.stop()


if __name__ == "__main__":
    choice = Controller.make_choice(["Neo4j menu", "Emulation"],
                                    "Program mode")
    if choice == 0:
        Neo4jController()
    elif choice == 1:
        emulation()
Beispiel #41
0
def create_app():
    app = Flask(__name__)
    app.config.from_object("settings")
    #app.config.from_object("settings")
    Controller(app).initialRouter()
    return app
Beispiel #42
0
 def decode_handler(self):
     if self.readFromClipboard.isChecked():
         self.outputBox.setText(Controller.handle_decoding(self.clipboard.text(), self.options.get_matrix_building_rule()))
     else:
         self.outputBox.setText(Controller.handle_decoding(self.inputBox.toPlainText(), self.options.get_matrix_building_rule()))