class TestController(unittest.TestCase): def setUp(self): TestCase.setUp(self) self.repository = Repository() self.controller = Controller(self.repository) holy1 = Holiday("1", "London", "seaside", 260) holy2 = Holiday("2", "Constanta", "seaside", 160) holy3 = Holiday("3", "Chisinau", "city-break", 260) self.repository.addItem(holy1) self.repository.addItem(holy2) self.repository.addItem(holy3) def test_type(self): self.assertEqual(len(self.controller.filterByType("seaside")), 2) def test_resort(self): self.controller.filterByResort("London") self.assertEqual(len(self.controller.filterByResort("London")), 1)
def setUp(self): TestCase.setUp(self) self.repository = Repository() self.controller = Controller(self.repository) holy1 = Holiday("1", "London", "seaside", 260) holy2 = Holiday("2", "Constanta", "seaside", 160) holy3 = Holiday("3", "Chisinau", "city-break", 260) self.repository.addItem(holy1) self.repository.addItem(holy2) self.repository.addItem(holy3)
def openProject(self): dialog = QtGui.QFileDialog() dialog.setFileMode(QtGui.QFileDialog.Directory) dialog.setOption(QtGui.QFileDialog.ShowDirsOnly, True) path = dialog.getExistingDirectory(self, "Select Directory") if path != '': projectName = path.split(os.pathsep)[-1] controller = Controller(projectName) controller.setProjectVcs(path) controller.configureProject() self.controller = controller commits = controller.getCommits() lastCommit = commits[0] firstCommit = commits[0] for x in commits: if x.timestamp < firstCommit.timestamp: firstCommit = x if x.timestamp > lastCommit.timestamp: lastCommit = x minDate = QtCore.QDateTime.fromTime_t(int(firstCommit.timestamp)) maxDate = QtCore.QDateTime.fromTime_t(int(lastCommit.timestamp)) self.startDateEdit.setDateTimeRange(minDate, maxDate) self.startDateEdit.setDateTime(minDate) self.endDateEdit.setDateTimeRange(minDate, maxDate) self.endDateEdit.setDateTime(maxDate) self.brComboBox.addItems(["all"] + self.controller.getBranches()) self.devComboBox.addItems(["all"] + [x.email for x in self.controller.getAuthors()]) self.outCommitFiles(commits) self.drawLines(commits)
def main(): contro = Controller() contro.run()
# coding=utf-8 from Controller.Controller import Controller from Swarm.Swarm import Swarm if __name__ == "__main__": # number of particles noParticles = 50 noIterations = 100 vxmin = -1.5 vxmax = 4 vymin = -3 vymax = 4 # specific parameters for PSO w = 1.0 c1 = 1.0 c2 = 2.5 sizeOfNeighborhood = 20 population = Swarm(noParticles, vxmax, vxmin, vymax, vymin, sizeOfNeighborhood) ctrl = Controller(population, c1, c2, w, noIterations) fitnessOptim, individualOptim = ctrl.runAlg() print('Result: The detectet minimum point is (%3.2f %3.2f) \n with function\'s value %3.2f' % \ (individualOptim[0], individualOptim[1], fitnessOptim))
''' Description of the module: - this is the starting point of the application ''' from Repository.Repository import ShoppingListRepository from Controller.Controller import Controller from User_Interface.User_Interface import UserInterface from Test.Test_All import runTests repository = ShoppingListRepository() controller = Controller(repository) userInterface = UserInterface(controller) runTests() '''userInterface.runApplication()'''
def __init__(self): states = FileManager.read_puzzle() free_x,free_y = Puzzle.get_empty_spaces_indices(states[0]) self.__controller = Controller(Puzzle(states[0], states[1], free_x, free_y))
def __init__(self): self.__initialConfiguration = SudokuBoard() self.__problem = Problem(self.__initialConfiguration) self.__controller = Controller(self.__problem) self.__hasReadFile = False
async def main(): m = Model() v = View() c = Controller(m, v) await run_tk(v, c)
class Problem: def __init__(self): self.loadProblem() self.controller = Controller(self.noAnts, self.antSize) def loadProblem(self): f = open("input.txt", "r") self.antSize = int(f.readline()) self.noEpoch = int(f.readline()) self.noAnts = int(f.readline()) self.alpha = float(f.readline()) # trail importance self.beta = float(f.readline()) # visibility importance self.rho = float(f.readline()) # pheromone degradation coefficient self.q0 = float(f.readline()) # initial value of pheromone def run(self): bestAnt = Ant(self.antSize) bestAnt.setSolution([]) for i in range(self.noEpoch): ant = self.controller.iteration(self.q0, self.alpha, self.beta, self.rho) if ant.fitness() < bestAnt.fitness(): bestAnt.setSolution(ant.solution) if bestAnt.fitness() == 0: break print("Best found path: " + str(bestAnt.solution)) n = bestAnt.solution count = 0 matrix = [] for i in range(self.antSize): row = [] for j in range(self.antSize): x = 1 if count < len(n): if n[count] >= self.antSize: x = int(n[count] / self.antSize) y = int(n[count] % self.antSize) + 1 else: x = 0 y = 0 row.append([x, y]) count += 1 matrix.append(row) print("Best found solution: ") for i in range(len(matrix)): print(matrix[i]) print("Fitness: " + str(bestAnt.fitness())) def test(self): fitness = [] for j in range(0, 30): bestAnt = Ant(self.antSize) bestAnt.setSolution([]) for i in range(self.noEpoch): ant = self.controller.iteration(self.q0, self.alpha, self.beta, self.rho) fitness.append(ant.fitness()) if ant.fitness() < bestAnt.fitness(): bestAnt.setSolution(ant.solution) if bestAnt.fitness() == 0: break # fitness.append(bestAnt.fitness()) result = "Average: " + str( numpy.average(fitness)) + "\n" + "Standard deviation: " + str( numpy.std(fitness)) print(result) plt.plot(fitness) plt.show()
from Controller.Controller import Controller c = Controller() for winning_ticket in c.get_Betting_Tickets(): print(winning_ticket)
from Controller.Controller import Controller from View.Console import Console if __name__ == '__main__': controller = Controller("") view = Console(controller) view.run()
''' Created on Mar 24, 2017 @author: God ''' # ia aprox 16 secunde sa citeasca fisieru de 1m from Repository.Repository import Repository from Controller.Controller import Controller from Ui.Ui import Ui repo = Repository("graph10k.txt") ctrl = Controller(repo) ui = Ui(ctrl) ui.start()
from Controller.Controller import Controller if __name__ == "__main__": #core = model.PropSpecReaderModel() #ctrl = controller.controller(core) controller = Controller() controller.run()
def test_initiate(self): screen_size = (1200, 600) screen = pygame.display.set_mode(screen_size) Controller(screen)
def main(): model = Model() controller = Controller(model, 'dataset') root = tk.Tk() ui = UI(root, "Aggressivity Detection - A Security Tool", controller)
from Controller.Controller import Controller from View.View import View from View.UserInterface import UserInterface from ServiceLayer.ServiceLayer import ServiceLayer from Dao.Dao import Dao """ Hardcoding DI for now experimenting """ sl = ServiceLayer(Dao()) view = View() userInterface = UserInterface(view) controller = Controller(userInterface, sl) controller.run()
def main(): try: ctrl = Controller() ctrl.controller() except KeyboardInterrupt: exit(0)
# !/usr/bin/python2.7 # -*- coding: utf-8 -*- from Controller.Controller import Controller import Tkinter as tk if __name__ == '__main__': root = tk.Tk() root.withdraw() app = Controller(root) root.mainloop()
from Controller.Controller import Controller m = Controller() m.start() # from Model.Model import Model # model = Model() # a = model.create_contacto('eber','a','b','c,','d','f','g','h','i','j','k') # a = model.create_detalles_cita1('2','3','hola','nada') # a = model.read_contactos_cita(2) # a =model.read_detalles_cita(2) # a = model.update_detalles_cita(['nombre = %s', 'descripcion = %s'],('hola', 'ya me enfade', '2')) # print(a)
class Test(unittest.TestCase): def setUp(self): self.validator = SquareValidator() self.repository = Repository() self.controller = Controller(self.validator, self.repository) def tearDown(self): del self def test(self): self.assertRaises(SquareValidatorError, self.controller.round, "abc", "yz") self.assertRaises(SquareValidatorError, self.controller.round, "-1", "15") self.controller.round("8", "8") self.assertEqual(self.repository.board.matrix[8][8], "B") self.assertEqual(self.repository.board.matrix[8][7], "W") self.controller.round("7", "8") self.assertEqual(self.repository.board.matrix[7][8], "B") self.assertEqual(self.repository.board.matrix[8][6], "W") self.controller.round("6", "8") self.assertEqual(self.repository.board.matrix[6][8], "B") self.assertEqual(self.repository.board.matrix[5][8], "W") self.controller.round("9", "9") self.assertEqual(self.repository.board.matrix[9][9], "B") self.assertEqual(self.repository.board.matrix[5][7], "W") self.controller.round("7", "7") self.assertEqual(self.repository.board.matrix[7][7], "B") self.assertEqual(self.repository.board.matrix[6][6], "W") self.controller.round("7", "9") self.assertEqual(self.repository.board.matrix[7][9], "B") self.assertEqual(self.repository.board.matrix[7][6], "W") self.controller.round("6", "10") self.assertEqual(self.repository.board.matrix[6][10], "B") self.assertEqual(self.repository.board.matrix[5][11], "W") self.controller.round("10", "6") self.assertEqual(self.repository.board.matrix[10][6], "B") self.assertEqual(self.repository.board.matrix[9][7], "W") self.controller.round("8", "12") self.assertEqual(self.repository.board.matrix[8][12], "B") self.assertEqual(self.repository.board.matrix[12][7], "W") self.controller.round("7", "11") self.assertEqual(self.repository.board.matrix[7][11], "B") self.assertEqual(self.repository.board.matrix[7][10], "W") self.controller.round("5", "9") self.assertEqual(self.repository.board.matrix[5][9], "B") self.assertEqual(self.repository.board.matrix[4][8], "W") self.assertRaises(RepositoryError, self.controller.round, "8", "8") self.assertRaises(GameOver, self.controller.round, "9", "13") self.assertEqual(self.repository.board.matrix[9][13], "B")
def start(): repo1 = PassengersRepo() repo2 = PlaneRepo() ctrl = Controller(repo2, repo1) ui = PlanesMenu(ctrl) ui.menu()
def setUp(self): self.validator = SquareValidator() self.repository = Repository() self.controller = Controller(self.validator, self.repository)
from Controller.Controller import Controller controller = Controller() controller.invoke()
''' Created on 31 ian. 2018 @author: Catalin ''' from Controller.Controller import Controller from Repo.sentenceRepo import sentenceRepo from UI.menu import UI r=sentenceRepo() r.addSentence("Anna has apples") r.addSentence("John eats strawberries") c=Controller(r) u=UI(c) u.main()
class MainView(QMainWindow): file_path = os.path.dirname(os.path.abspath(__file__)) ui_path = os.path.join(file_path, "studier.ui") def __init__(self): try: super(MainView, self).__init__() uic.loadUi(self.ui_path, self) # initializing controller self.controller = Controller() # creating database and database tables if they don't exist self.controller.create_tables() # populating the TermCategoriesListWidget self.load_term_categories_list_widget() ''' LINKING SIGNALS TO FUNCTIONS ''' # upon an item being changed in the TermCategoriesListWidget repopulate the TermTableView self.TermCategoriesListWidget.currentItemChanged.connect( self.term_categories_list_widget_item_changed) # Opens a quiz dialog for the currently selected category self.TestButton.clicked.connect(self.test_button_clicked) # upon the click of the help option in the top-left menu # a dialog with information on the application is shown self.actionGet_Help.triggered.connect(self.action_help_clicked) # upon the click of the EditTermButton the EditAndAddTermsView dialog is opened self.EditTermButton.clicked.connect(self.edit_term_button_clicked) self.EditCategoriesButton.clicked.connect( self.edit_categories_button_clicked) # setting table layout self.TermTableView.setSelectionBehavior(QTableView.SelectRows) self.TermTableView.setSelectionMode( QAbstractItemView.SingleSelection) self.TermTableView.horizontalHeader().setStretchLastSection(True) self.TermTableView.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.TermTableView.setColumnHidden(0, True) except Exception as e: print(str(e)) # a dialog with information on the application is shown def action_help_clicked(self): helpView = HelpView() helpView.exec_() # opens the dialog for editing terms def edit_term_button_clicked(self): try: # if there is a category selected pass it # if not, default category, All Terms, will be used. if self.TermCategoriesListWidget.currentItem() is not None: category = self.TermCategoriesListWidget.currentItem().text() edit_and_add_terms = EditAndAddTermsView(category) else: edit_and_add_terms = EditAndAddTermsView() edit_and_add_terms.exec_() # update terms in view so new ones and edited ones are shown properly self.term_categories_list_widget_item_changed() except Exception as e: print(str(e)) # brings up the test dialog and starts test on terms in # the category selected def test_button_clicked(self): try: # getting selected category selected_category = self.controller.get_current_category() # if the category is not None check if category holds terms if selected_category is not None: # if category holds terms begin quiz if self.controller.get_number_of_terms_in_category() != 0: self.controller.begin_quiz(selected_category) else: # if category doesn't hold terms show an error message error_dialog = QErrorMessage(self) error_dialog.showMessage( "There are no terms in the selected category") else: # if there is no selected category show an error message error_dialog = QErrorMessage(self) error_dialog.showMessage("There is not a category selected") except Exception as e: print("here " + str(e)) # load the current categories in the database def load_term_categories_list_widget(self): try: # clear the categories that are currently being displayed self.TermCategoriesListWidget.clear() # get all categories from database categories = self.controller.get_all_categories() # create list widget items for each category # align each list widget item center # add the list widget item to the database for category in categories: category_list_widget_item = QListWidgetItem(category) category_list_widget_item.setTextAlignment(Qt.AlignCenter) self.TermCategoriesListWidget.addItem( category_list_widget_item) except Exception as e: print(str(e)) # loads the terms for the current category selected def term_categories_list_widget_item_changed(self): try: selected_item = self.TermCategoriesListWidget.currentItem() if selected_item is not None: selected_item_text = selected_item.text() self.controller.set_category(selected_item_text) # using the set category a new model is created for the table # that holds the set categories terms terms_names_and_ids_in_category = self.controller.get_term_names_in_category_and_ids( ) # if the category is not None update term table view if terms_names_and_ids_in_category is not None: self.TermTableView.setModel( terms_names_and_ids_in_category) # hiding term ids in the term table view self.TermTableView.setColumnHidden(0, True) else: self.TermTableView.setModel( self.controller.get_empty_term_table_view_model()) except Exception as e: print(str(e)) def edit_categories_button_clicked(self): edit_category_view = EditCategoryView() edit_category_view.exec_() self.load_term_categories_list_widget()
class View: # Construtor def __init__(self): # Criando objeto de janela self.view = tkinter.Tk() self.view.title("Criptografia De Curvas Elípticas") self.view.resizable(0, 0) self.view.pack_propagate(0) #Estilos de fonte self.fonteLabel = ("Century Gothic", 14) fonteEntry = ("Century Gothic", 12) fonteChave = ("Century Gothic", 10) self.fonteButton = ("Century Gothic", 14, "bold") # Criando labels self.lblKa = Label(self.view, text="Informe o Valor de Ka:", font=self.fonteLabel) self.lblKb = Label(self.view, text="Informe o Valor de Kb:", font=self.fonteLabel) self.lblK = Label(self.view, text="Informe o Valor de K:", font=self.fonteLabel) self.lblArquivo = Label(self.view, text="Selecione o Arquivo Com o Texto Claro:", font=self.fonteLabel, wraplength=500) self.lblChave = Label( self.view, text="Selecione o Arquivo Com As Chaves Públicas:", font=self.fonteLabel, wraplength=500) self.lblKa.grid(row=3, column=0, ipady=5) self.lblKb.grid(row=4, column=0, ipady=5) self.lblK.grid(row=11, column=0, ipady=5) self.lblArquivo.grid(row=9, column=0, columnspan=2) self.lblChave.grid(row=7, column=0, columnspan=2) # Criando entrada de texto self.txtKa = Entry(self.view, font=fonteEntry) self.txtKb = Entry(self.view, font=fonteEntry) self.txtK = Entry(self.view, font=fonteEntry) self.txtKa.grid(row=3, column=1, padx=5) self.txtKb.grid(row=4, column=1, padx=5) self.txtK.grid(row=11, column=1, padx=5) Separator(self.view).grid(row=6, column=0, columnspan=2, padx=10, pady=10, sticky="ew") Separator(self.view).grid(row=12, column=0, columnspan=2, padx=10, pady=10, sticky="ew") # Criando botões Button(self.view, text="Gerar Chaves", font=self.fonteButton, command=self.gerarChaves).grid(row=5, column=0, columnspan=2, sticky="ew", padx=15, pady=(15, 0)) Button(self.view, text="Abrir Tela de Seleção Para Texto Claro", font=self.fonteButton, command=self.abrirFileDialogTextoClaro).grid(row=10, column=0, columnspan=2, sticky="ew", padx=15, pady=5) Button(self.view, text="Abrir Tela de Seleção Para Chave", font=self.fonteButton, command=self.abrirFileDialogChavePublica).grid(row=8, column=0, columnspan=2, sticky="ew", padx=15, pady=5) Button(self.view, text="Cifrar/Decifrar", font=self.fonteButton, command=self.cifrar).grid(row=13, column=0, columnspan=2, sticky="ew", padx=15, pady=(0, 15)) # Configura posição da tela após inserir itens self.view.update_idletasks() tela_w = self.view.winfo_screenwidth() tela_h = self.view.winfo_screenheight() janela_w = self.view.winfo_reqwidth() janela_h = self.view.winfo_reqheight() self.view.geometry("+{}+{}".format(int(tela_w / 2 - janela_w / 2), int(tela_h / 2 - janela_h / 2))) self.view.columnconfigure(0, weight=1) # Instancia controller self.controller = Controller(self) # Inicia view def iniciar(self): self.view.mainloop() # Abre tela para escolher arquivo com texto claro def abrirFileDialogTextoClaro(self): user_dir = str(Path.home()) self.view.caminhoTextoClaro = filedialog.askopenfilename( initialdir=user_dir, title="Selecione O Texto", filetypes=[("Arquivos txt", "*.txt")]) if len(self.view.caminhoTextoClaro) != 0: self.lblArquivo["text"] = self.view.caminhoTextoClaro self.controller.cifra.caminho = self.view.caminhoTextoClaro # Abre tela para escolher arquivo com chave pública def abrirFileDialogChavePublica(self): user_dir = str(Path.home()) self.view.caminhoChavePublica = filedialog.askopenfilename( initialdir=user_dir, title="Selecione A Chave Pública", filetypes=[("Arquivos txt", "*.txt")]) if len(self.view.caminhoChavePublica) != 0: self.lblChave["text"] = self.view.caminhoChavePublica self.controller.cifra.caminhoChavePublica = self.view.caminhoChavePublica # Chama função que gera as chaves públicas e privadas def gerarChaves(self): ka = self.txtKa.get() kb = self.txtKb.get() try: result = self.controller.gerarChaves(ka, kb) if result == True: messageBox = MessageBox( "Chaves Geradas Com Sucesso", "Chave Pública Salva Em " + str(Path.home()), None) except ValueError as ve: messageBox = MessageBox("Erro ao Gerar Chaves", ve.args[0], None) print(ve.args) # Função executada ao apertar botão de cifrar def cifrar(self): try: k = self.txtK.get() self.controller.carregarTextoClaro() self.controller.carregarChaves() self.controller.cifrar(k) self.controller.decifrar(k) self.controller.salvarCifrado() self.controller.salvarDecifrado() messageBox = MessageBox( "Cifragem Executada com Sucesso", "Texto Cifrado e Decifrado Salvo em {}".format( self.controller.cifra.getDiretorio()), self.reset) except ValueError as ve: messageBox = MessageBox("Erro ao Executar Cifragem", ve.args[0], None) print(ve.args) except FileNotFoundError as fnfe: messageBox = MessageBox("Erro ao Executar Cifragem", "Arquivo Não Encontrado", None) print(fnfe.args) # Reseta os campos da view e o modelo no controle def reset(self): self.lblArquivo["text"] = "Selecione o Arquivo Com o Texto Claro:" self.lblChave["text"] = "Selecione o Arquivo Com A Chave Pública:" self.txtKa.delete(0, "end") self.txtKb.delete(0, "end") self.txtK.delete(0, "end") self.controller.reset()
def __init__(self): self.loadProblem() self.controller = Controller(self.noAnts, self.antSize)
def __init__(self): # Criando objeto de janela self.view = tkinter.Tk() self.view.title("Criptografia De Curvas Elípticas") self.view.resizable(0, 0) self.view.pack_propagate(0) #Estilos de fonte self.fonteLabel = ("Century Gothic", 14) fonteEntry = ("Century Gothic", 12) fonteChave = ("Century Gothic", 10) self.fonteButton = ("Century Gothic", 14, "bold") # Criando labels self.lblKa = Label(self.view, text="Informe o Valor de Ka:", font=self.fonteLabel) self.lblKb = Label(self.view, text="Informe o Valor de Kb:", font=self.fonteLabel) self.lblK = Label(self.view, text="Informe o Valor de K:", font=self.fonteLabel) self.lblArquivo = Label(self.view, text="Selecione o Arquivo Com o Texto Claro:", font=self.fonteLabel, wraplength=500) self.lblChave = Label( self.view, text="Selecione o Arquivo Com As Chaves Públicas:", font=self.fonteLabel, wraplength=500) self.lblKa.grid(row=3, column=0, ipady=5) self.lblKb.grid(row=4, column=0, ipady=5) self.lblK.grid(row=11, column=0, ipady=5) self.lblArquivo.grid(row=9, column=0, columnspan=2) self.lblChave.grid(row=7, column=0, columnspan=2) # Criando entrada de texto self.txtKa = Entry(self.view, font=fonteEntry) self.txtKb = Entry(self.view, font=fonteEntry) self.txtK = Entry(self.view, font=fonteEntry) self.txtKa.grid(row=3, column=1, padx=5) self.txtKb.grid(row=4, column=1, padx=5) self.txtK.grid(row=11, column=1, padx=5) Separator(self.view).grid(row=6, column=0, columnspan=2, padx=10, pady=10, sticky="ew") Separator(self.view).grid(row=12, column=0, columnspan=2, padx=10, pady=10, sticky="ew") # Criando botões Button(self.view, text="Gerar Chaves", font=self.fonteButton, command=self.gerarChaves).grid(row=5, column=0, columnspan=2, sticky="ew", padx=15, pady=(15, 0)) Button(self.view, text="Abrir Tela de Seleção Para Texto Claro", font=self.fonteButton, command=self.abrirFileDialogTextoClaro).grid(row=10, column=0, columnspan=2, sticky="ew", padx=15, pady=5) Button(self.view, text="Abrir Tela de Seleção Para Chave", font=self.fonteButton, command=self.abrirFileDialogChavePublica).grid(row=8, column=0, columnspan=2, sticky="ew", padx=15, pady=5) Button(self.view, text="Cifrar/Decifrar", font=self.fonteButton, command=self.cifrar).grid(row=13, column=0, columnspan=2, sticky="ew", padx=15, pady=(0, 15)) # Configura posição da tela após inserir itens self.view.update_idletasks() tela_w = self.view.winfo_screenwidth() tela_h = self.view.winfo_screenheight() janela_w = self.view.winfo_reqwidth() janela_h = self.view.winfo_reqheight() self.view.geometry("+{}+{}".format(int(tela_w / 2 - janela_w / 2), int(tela_h / 2 - janela_h / 2))) self.view.columnconfigure(0, weight=1) # Instancia controller self.controller = Controller(self)
class UserInterface: # TODO - change the menu someway def __init__(self): self.__initialConfiguration = SudokuBoard() self.__problem = Problem(self.__initialConfiguration) self.__controller = Controller(self.__problem) self.__hasReadFile = False def printMainMenu(self): s = '' s += "0 - exit \n" s += "1 - read the text file \n" if self.__hasReadFile: s += "2 - find a solution with BFS \n" s += "3 - find a solution with GBFS\n" print(s) def readTextFile(self): print("Input the name of the text file. ") name = input("Enter the text file: ") try: self.__initialConfiguration.readFromFile(name) except ReadFromFileException: print(sys.exc_info()[0]) return except IncorrectInputFileException: print("File does not contain a correct game!") return except: print("File not found!") return self.__problem = Problem(self.__initialConfiguration) self.__controller = Controller(self.__problem) self.__hasReadFile = True def findPathBFS(self): time = perf_counter() answer = str(self.__controller.BFS(self.__problem.getRoot())) if answer is None: print("This Sudoku has no solution.") else: print(answer) print("Elapsed time: " + str(perf_counter() - time)) def findPathGBFS(self): time = perf_counter() answer = str(self.__controller.GBFS(self.__problem.getRoot())) if answer is None: print("This Sudoku has no solution.") else: print(answer) print("Elapsed time: " + str(perf_counter() - time)) def run(self): runM=True while runM: self.printMainMenu() command = int(input(">> ")) if command == 0: runM = False elif command == 1 and not self.__hasReadFile: self.readTextFile() elif command == 2 and self.__hasReadFile: self.findPathBFS() elif command == 3 and self.__hasReadFile: self.findPathGBFS() else: print("Command not available") def testSquare(self): print(self.__initialConfiguration.getAvailableDigitsForCell(2,2))
# -*- coding: utf-8 -*- from Controller.Controller import Controller from PyQt5 import QtWidgets if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) myapp = Controller() myapp.show() sys.exit(app.exec_()) pass
def testBT2(self): pr1 = PassengersRepo() pr2 = PlaneRepo() ctrl = Controller(pr2, pr1) p1 = Passengers('Ion', 'C', 'abc') p2 = Passengers('Ioana', 'B', 'abc2') p3 = Planes('Nume1', 'A201', 'Wizair', 60, 'Cairo', [p1, p2]) ctrl.addPlane(p3) p4 = Passengers('Ion', 'A', 'abc22') p5 = Passengers('Andrei', 'B', 'adc44') p6 = Planes('Nume2', 'A202', 'Wizair', 60, 'Cairo', [p4, p5]) ctrl.addPlane(p6) p7 = Planes('Nume3', 'A203', 'Wair', 60, 'Cairo', [p4, p5]) ctrl.addPlane(p7) p8 = Planes('Nume4', 'A204', 'Wizair', 60, 'Cairo', [p4, p5]) ctrl.addPlane(p8) l1 = ctrl.form2(2)
class Ui: def __init__(self, m, d): self._controller = Controller(m, d) @staticmethod def display_with_path(image, path1, path2): mark_a = pygame.Surface((20, 20)) mark_c = pygame.Surface((20, 20)) mark_g = pygame.Surface((20, 20)) mark_a.fill(GREEN) mark_c.fill(YELLOW) mark_g.fill(RED) for move in path1: if move in path2: mark = mark_c else: mark = mark_a image.blit(mark, (move[1] * 20, move[0] * 20)) list_pos = [] for pos in path2: if pos not in path1: list_pos.append(pos) for move in list_pos: image.blit(mark_g, (move[1] * 20, move[0] * 20)) return image def run(self): # initialize the pygame module pygame.init() # load and set the logo logo = pygame.image.load("logo32x32.png") pygame.display.set_icon(logo) pygame.display.set_caption("Path in simple environment") # we position the drone somewhere in the area # create a surface on screen that has the size of 400 x 480 screen = pygame.display.set_mode((400, 400)) screen.fill(WHITE) # define a variable to control the main loop running = True # main loop while running: # event handling, gets all event from the event queue for event in pygame.event.get(): # only do something if the event is of type QUIT if event.type == pygame.QUIT: # change the value to False, to exit the main loop running = False screen.blit( self._controller.d.map_with_drone(self._controller.m.image()), (0, 0)) pygame.display.flip() fx = randint(0, 19) fy = randint(0, 19) while fx == self._controller.d.x and fy == self._controller.d.y: fx = randint(0, 19) fy = randint(0, 19) start1 = time.time() path1 = self._controller.a_star_search(self._controller.d.x, self._controller.d.y, fx, fy) end1 = time.time() print(end1 - start1) start2 = time.time() path2 = self._controller.greedy_search(self._controller.d.x, self._controller.d.y, fx, fy) end2 = time.time() print(end2 - start2) screen.blit( self.display_with_path(self._controller.m.image(), path1, path2), (0, 0)) pygame.display.flip() time.sleep(15) pygame.quit()