Beispiel #1
0
 def __init__(self, agent, temp_it=CFG.temp_thresh + 1, player_name=None):
     self.agent = agent
     self.game = self.agent.game
     self.logger = Logger()
     self.temp_it = temp_it
     self.player_name = player_name
     self.tree = State(None, 1, self.game(), prior=1.0)
Beispiel #2
0
    def __init__(self, host, user, password="", database="zbd_project"):
        """Initialize database object"""
        # Initialize logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug("Database logger has started.")
        self.connection = None
        # Initialize database connection
        try:
            self.logger.debug("Trying to attempt connection with database.")
            self.connection = pymysql.connect(host=host, user=user, passwd=password, database=database)
        except Exception as e:
            self.logger.critical(f"Could not connect to database! Error = {e}")
            raise ConnectionRefusedError(f"Could not connect to database! Error = {e}")
        self.logger.info("Database connection is stable.")

        self.config = dict()
        try:
            with open("config.json") as f:
                self.config = {**self.config, **json.load(f)}
        except IOError as e:
            self.logger.error(f"Error occured while reading config from .json file!. Error = {e}")
            exit(-1)
        self.logger.debug("Config has been read.")

        # Initialize global cursor
        self.logger.debug("Creating global cursor.")
        self.cursor = self.connection.cursor()
        self.logger.debug("Global cursor created.")
Beispiel #3
0
    def __init__(self, argv):
        QtGui.QMainWindow.__init__(self)
        self.MainWindow = Ui_MainWindow
        self.ui = Ui_MainWindow
        self.MainWindow.__init__(self.window)
        self.setupUi(self)
        self.show()

        self.logger = Logger(self.logPanel)
        self.device = EthernetDevice(self.logger)

        self.device.disconState = QtGui.QPixmap(
            _fromUtf8('../res/disconnected'))
        self.device.conState = QtGui.QPixmap(_fromUtf8('../res/connected'))
        self.device.currentState = 0

        self.device.power = 0
        self.device.direction = 0

        self.addWidgets()

        self.updater = DataUpdateThread(self)  # create a thread
        self.updater.trigger.connect(
            self.updateState)  # connect to it's signal
        self.updater.start()

        self.cam = Camera(self)
Beispiel #4
0
 def __init__(self, auction_id, test=False):
     self.auction_id = auction_id
     self.highest_bid = 0
     self.highest_bidder = None
     self.bid_time = 0
     self.no_bids = 0
     self.test = test  # suppress logging in tests
     self.log = Logger(id=auction_id, test=self.test)
     self.log.init_logfile()
    def takeoff(self):
        try:
            print("takeoff")
            self.toggleButtonEnabled()
            self.drone.takeoff()
        except:
            print('Not connected to a drone')
            return
        if self.drone.navdata:
            self.toggleButtonEnabled()
            self.logger = Logger()
            self.begin_log()

        print("taking off")
Beispiel #6
0
    def setup(self):
        self.log = Logger('./%s.log')
        # import the two players
        from src.Players.Dave2Player import Dave2Player
        from src.Players.Dave2Player_old import Dave2Player_old
        self.bot1 = Dave2Player()  # your player!
        self.bot2 = Dave2Player_old()
        test_map = 'M 1 0 0 0\n'\
                     + 'P 10 10 1 1 119 4\n'\
                     + 'P 10 20 2 0 100 5\n'\
                     + 'P 20 10 3 0 100 5\n'\
                     + 'P 20 20 4 2 119 4\n'

        self.pw = PlanetWars(test_map, logger=self.log.turn)
Beispiel #7
0
 def __init__(self):
     super().__init__()
     self.title = 'GameOfDrones Test GUI'
     self.left = 100
     self.top = 100
     self.width = 1024
     self.height = 768
     self.initUI()
     self.logger = Logger()
     self.drone = ARDrone(connect=True)
     self.drone.send(at.CONFIG('general:navdata_demo', True))
     font = QFont()
     font.setBold(True)
     font.setPixelSize(18)
     self.setFont(font)
Beispiel #8
0
def flow_handler(args):
    if len(args) == 1:
        print("1 positional argument missing!")
        print("\tuse_captured_video: detection on captured video\n\tuse_onboard_camera: detection on real-time video "
              "from tx2 camera\n\tuse_local_rtsp: detection on captured video with rtsp server")
        return

    father_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    log = Logger(father_dir + '/results/log/smart_parking.log', 'info')

    if args[1] == 'use_captured_video' or args[1] == 'use_onboard_camera' or args[1] == 'use_local_rtsp':
        detection_pipeline(log, args=args)
    else:
        print("\tuse_captured_video: detection on captured video\n\tuse_onboard_camera: detection on real-time video "
              "from tx2 camera\n\tuse_local_rtsp: detection on captured video with rtsp server")
        return
Beispiel #9
0
    def __init__(self, rootWindow, database, backEvent, year):
        self.rootWindow = rootWindow
        self.backEvent = backEvent
        self.database = database
        self.year = year
        # Start logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug("FunctionController logger has started.")

        self.functionWindow = Toplevel(self.rootWindow)
        self.functionWindow.title("Check a book.")
        self.functionWindow.protocol('WM_DELETE_WINDOW', self.goBack)
        self.functionWindow.bind("<<back>>", lambda _: self.backEvent())

        self.data = self.database.findBestBook(self.year)
        values = self.database.executeStatement(
            f"SELECT * FROM `ksiazki` WHERE `tytul` = '{self.data[0][0][0]}'")
        self.finalData = dict()
        self.finalData["Title"] = values[0][1]
        self.finalData["Date"] = str(values[0][2])
        self.finalData["Genre"] = values[0][3]
        self.finalData["Amount"] = self.data[1][0][0]

        self.mainFrame = Frame(self.functionWindow,
                               bd=4,
                               relief=RAISED,
                               width=self.functionWindow.winfo_width(),
                               height=self.functionWindow.winfo_height())
        self.mainFrame.pack(fill='both', side=TOP)

        titleLabel = Label(self.mainFrame,
                           text=f"Most hired book in year {year} is..",
                           font=("Arial Bold", 18))
        titleLabel.grid(row=0, column=0, columnspan=3, padx=40, pady=20)

        rowNo = 1
        for no, val in self.finalData.items():
            l1 = Label(self.mainFrame,
                       text=f"{no}: {val}",
                       font=("Arial Bold", 14))
            l1.grid(row=rowNo, column=0, columnspan=3, padx=10, pady=10)
            rowNo += 1
Beispiel #10
0
    def __init__(self, configPath, width=640, height=480):
        # Initialize logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug(
            "==================================================================="
        )
        self.logger.debug("Application logger has started.")

        self.config = dict()
        try:
            with open(configPath) as f:
                self.config = {**self.config, **json.load(f)}
        except IOError as e:
            self.logger.error(
                f"Error occured while reading config from .json file!. Error = {e}"
            )
            exit(-1)
        self.logger.debug("Config has been read.")

        # Initialize app window
        self.logger.debug("Initializing application window.")
        self.window = Tk()
        self.window.title("Database Application.")
        self.logger.debug("Application window has been initialized.")

        self.window.geometry(f"{int(width)}x{int(height)}+0+0")
        self.window.resizable(0, 0)
        self.window.attributes("-topmost", True)

        # Setting a theme picture
        self.theme = Canvas(width=width, height=height, bg='black')
        self.theme.grid(column=0, row=0)
        self.imagesDict = dict()
        self.imagesDict["themeC"] = PhotoImage(file="theme.gif")
        self.imagesDict["themeG"] = PhotoImage(file="grayscale_theme.gif")
        self.logger.debug("Images has been loaded.")
        self.imageOnCanvas = self.theme.create_image(
            0, 0, image=self.imagesDict["themeG"], anchor=NW)
        self.logger.debug("Setting grayscale theme.")
Beispiel #11
0
 def __init__(self, opt={}):
     opt = self.__initializeOptions(opt)
     print opt['browser']
     self.browser = Browser(opt['browser'])
     self.backend = Backend(opt['backend'])
     self.logger = Logger(opt['logger'])
Beispiel #12
0
    def __init__(self, tableName, database, themeWindow, returnEvent):
        self.tableName = tableName
        self.database = database
        self.themeWindow = themeWindow
        # Start logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug("TableController logger has started.")

        self.addWindow = None
        self.modifyWindow = None

        self.columnNames = self.database.getColumns(tableName)
        self.tableData = self.database.getRawData(tableName)
        self.data = self.database.getData(tableName)
        self.model = TableModel()

        if len(self.data) == 0:
            messagebox.showwarning("Empty table", "This table has no records!")
            self.data["_"] = dict()
            self.data["_"]["_"] = "Empty table"
        else:
            for key, records in self.data.items():
                for col, value in records.items():
                    if isinstance(value, datetime.date):
                        self.data[key][col] = str(value)
        self.model.importDict(self.data)

        # Widgets
        self.content = Frame(self.themeWindow,
                             bg="#B7B9B8",
                             bd=4,
                             relief=RAISED,
                             width=self.themeWindow.winfo_width() - 80,
                             height=self.themeWindow.winfo_height() - 80)
        self.content.place(x=40, y=40)
        self.content.grid(row=0, column=0)
        self.content.bind("<<goback>>", lambda _: returnEvent(None))
        self.content.update()

        # Canvas with options menu
        self.topCanvas = Canvas(self.content,
                                bg="white",
                                bd=1,
                                relief=RAISED,
                                width=int(self.content.winfo_width()),
                                height=int(self.content.winfo_height() / 12))
        self.topCanvas.pack(fill='both', side=TOP)

        self.backButton = Button(self.topCanvas,
                                 text=" < ",
                                 command=self.back,
                                 width=9)
        self.backButton.pack(fill='both', side=LEFT)
        self.showButton = Button(self.topCanvas,
                                 text="Refresh table",
                                 command=self.refreshTable,
                                 width=22)
        self.showButton.pack(fill='both', side=LEFT)

        # Canvas with data
        self.middleFrame = Frame(self.content)
        self.middleFrame.pack(fill='both', side=TOP)
        self.table = CustomTable(self.middleFrame, model=self.model)
        self.table.show()

        # Canvas with DML buttons
        self.bottomCanvas = Canvas(self.content,
                                   bg="white",
                                   bd=1,
                                   relief=FLAT,
                                   width=int(self.content.winfo_width()),
                                   height=int(self.content.winfo_height() / 5))
        self.bottomCanvas.pack(fill='both', side=TOP)
        self.buttonAdd = Button(self.bottomCanvas,
                                text=" ADD ",
                                command=self.add,
                                width=24,
                                height=3,
                                bd=5)
        self.buttonAdd.pack(side=LEFT)
        self.buttonModify = Button(self.bottomCanvas,
                                   text=" MODIFY ",
                                   command=self.modify,
                                   width=25,
                                   height=3,
                                   bd=5)
        self.buttonModify.pack(side=LEFT)
        self.buttonDelete = Button(self.bottomCanvas,
                                   text=" DELETE ",
                                   command=lambda: self.delete(self.tableName),
                                   width=25,
                                   height=3,
                                   bd=5)
        self.buttonDelete.pack(side=LEFT)
    def __init__(self):
        self.logger = Logger()
        self.drone = ARDrone(connect=True)

        self.drone.send(at.CONFIG('general:navdata_demo', True))
Beispiel #14
0
 def takeoff(self):
     self.logger = Logger()
     self.begin_log()
     while not self.drone.state.fly_mask:
         self.drone.takeoff()
     print("taking off")
Beispiel #15
0
    def __init__(self, themeWindow, tableName, database, selectedRecord, data,
                 backEvent):
        self.themeWindow = themeWindow
        self.tableName = tableName
        self.database = database
        self.selectedRecord = selectedRecord
        self.data = data
        self.backEvent = backEvent
        # Start logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug("ModifyController logger has started.")

        self.modifyWindow = Toplevel(self.themeWindow)
        self.modifyWindow.title("Modify an existing record.")
        self.modifyWindow.protocol('WM_DELETE_WINDOW', self.goBack)
        self.modifyWindow.bind("<<back>>", lambda _: self.backEvent(None))

        self.helpWindow = None

        self.newRecord = list()
        self.emptyCols = 0
        self.emptyButton = IntVar()

        self.colNames = self.database.getColumns(self.tableName)
        self.colTypes = self.database.getColumnTypes(self.tableName)
        self.colKeys = self.database.getColumnKeys(self.tableName)
        self.colNulls = self.database.getColumnNullable(self.tableName)
        self.colConstraints = self.database.getTableCheckConstraint(
            self.tableName)
        print(f"DEBUG = {self.colConstraints}")
        self.colFrame = Frame(self.modifyWindow,
                              bd=4,
                              relief=RAISED,
                              width=self.themeWindow.winfo_width(),
                              height=self.themeWindow.winfo_height() - 40)
        self.colFrame.pack(fill='both', side=TOP)

        self.entries = list()

        if self.tableName in ["wlasciciel_biblioteka"]:
            for no, col in enumerate(self.colNames):
                Label(self.colFrame, text=col,
                      font=("Arial Bold", 12)).grid(row=no, column=0)
                combo = ttk.Combobox(self.colFrame,
                                     values=self.initComboValues(
                                         self.tableName, col[0]))
                combo.grid(row=no, column=1, columnspan=2, padx=20, pady=10)
                if data[self.selectedRecord][col[0]] is not None:
                    combo.set(data[self.selectedRecord][col[0]])
                self.entries.append(combo)

        elif self.tableName in ["autor_ksiazka"]:
            for no, col in enumerate(self.colNames):
                Label(self.colFrame, text=col,
                      font=("Arial Bold", 12)).grid(row=no, column=0)
                vals = self.initComboValues(self.tableName, col[0])
                combo = ttk.Combobox(self.colFrame, values=vals)
                combo.grid(row=no, column=1, columnspan=2, padx=20, pady=10)
                valueHelper = Button(
                    self.colFrame,
                    text="?",
                    command=lambda b=col[0], c=combo: self.showHelp(b, c))
                valueHelper.grid(row=no, column=3)
                if data[self.selectedRecord][col[0]] is not None:
                    combo.set(data[self.selectedRecord][col[0]])
                self.entries.append(combo)

        else:
            for no, col in enumerate(self.colNames):
                if col[0][-2:] == "id" and self.colKeys[col[0]][0] == 'PRI':
                    self.emptyCols += 1
                    continue
                if self.colKeys[col[0]][0] == 'PRI':
                    _text = self.colNames[no][0] + "*"
                else:
                    _text = self.colNames[no][0]
                Label(self.colFrame, text=_text,
                      font=("Arial Bold", 12)).grid(row=no, column=0)
                if self.colTypes[col[0]] == 'date':
                    entry = DateEntry(self.colFrame, date_pattern='y/mm/dd')
                    entry.grid(row=no,
                               column=1,
                               columnspan=2,
                               padx=20,
                               pady=10)
                    if self.colNulls[col[0]] == 'YES':
                        emptyButton = Checkbutton(self.colFrame,
                                                  text="Empty",
                                                  variable=self.emptyButton,
                                                  command=self.clicked)
                        emptyButton.grid(row=no, column=3)
                        self.emptyDate = entry
                else:
                    if self.colKeys[col[0]][0] == 'MUL':
                        vals = self.database.executeStatement(
                            f"SELECT {self.colKeys[col[0]][2]} FROM {self.colKeys[col[0]][1]}"
                        )
                        entry = ttk.Combobox(self.colFrame, values=vals)
                        entry.grid(row=no,
                                   column=1,
                                   columnspan=2,
                                   padx=20,
                                   pady=10)
                    else:
                        if col[0] in self.colConstraints.keys():
                            entry = ttk.Combobox(
                                self.colFrame,
                                values=self.colConstraints[col[0]])
                        else:
                            entry = Entry(self.colFrame, width=20)
                        entry.grid(row=no,
                                   column=1,
                                   columnspan=2,
                                   padx=20,
                                   pady=10)

                if data[self.selectedRecord][col[0]] is not None:
                    if self.colTypes[col[0]] == 'date':
                        entry.set_date(data[self.selectedRecord][col[0]])
                    else:
                        entry.insert(END, data[self.selectedRecord][col[0]])
                self.entries.append(entry)

        self.oldRecord = list()
        for entry in self.entries:
            self.oldRecord.append(entry.get())

        if self.emptyCols > 0:
            if self.tableName == "pracownicy":
                self.oldRecord.insert(
                    0,
                    self.database.executeStatement(
                        f"SELECT `{self.colNames[0][0]}` FROM `{self.tableName}`"
                        +
                        f"WHERE `{self.colNames[2][0]}` = \"{self.oldRecord[1]}\" AND"
                        + f"`{self.colNames[3][0]}` = \"{self.oldRecord[2]}\"")
                    [0][0])

            else:
                self.oldRecord.insert(
                    0,
                    self.database.executeStatement(
                        f"SELECT `{self.colNames[0][0]}` FROM `{self.tableName}`"
                        +
                        f"WHERE `{self.colNames[1][0]}` = \"{self.oldRecord[0]}\" AND"
                        + f"`{self.colNames[2][0]}` = \"{self.oldRecord[1]}\"")
                    [0][0])

        self.buttonFrame = Frame(self.modifyWindow,
                                 bd=4,
                                 relief=RAISED,
                                 width=self.themeWindow.winfo_width(),
                                 height=40)
        self.buttonFrame.pack(fill='both', side=TOP)
        self.addButton = Button(self.buttonFrame,
                                text="Modify",
                                command=self.checkEntry)
        self.addButton.pack(side=LEFT)
        self.cancelButton = Button(self.buttonFrame,
                                   text="Cancel",
                                   command=self.goBack)
        self.cancelButton.pack(side=LEFT)
import sys
from multiprocessing import Process, Queue

from flask import Flask, request, make_response, jsonify, render_template
from flask_restx import Api, Resource

sys.path.append(os.path.dirname(os.path.abspath("./app")))
import config.config as cfg
from src.setup.setup import logger_setup
from src.setup.flask_app import run_flask_app
from src.MotionDetector import MotionDetector
from src.SingleShotDetector import SingleShotDetector
from src.Logger import Logger

motion_detector = MotionDetector()
logger_instance = Logger()
ssd = SingleShotDetector()
motion_vector_queue = Queue()
detection_vector_queue = Queue()

logger = logging.getLogger(__name__)

app = Flask(__name__)
API = Api(
    app,
    title="Inter-process communication",
    description=
    "Documentation of the API of the inter-process communication module",
    doc="/doc",
    prefix="/test_upciti/api/v1",
)
Beispiel #17
0
    def __init__(self, mainWindow, eventF, width=300, height=200):
        # Initialize logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug("LogonController logger has started.")

        # Create sub window with signing info
        self.tlLogon = Toplevel(mainWindow)
        self.tlLogon.title("Sign In")
        mainWindow.update()
        # Calculate offset of sub window
        xOffset = (mainWindow.winfo_width() / 2) - (width / 2)
        yOffset = (mainWindow.winfo_height() / 2) - (height / 2)

        self.tlLogon.geometry(
            f"{width}x{height}+{int(xOffset)}+{int(yOffset)}")
        self.tlLogon.lift()
        self.tlLogon.resizable(0, 0)
        self.tlLogon.attributes("-topmost", True)
        self.tlLogon.bind("<FocusIn>", self.eventHandleFocus)
        self.tlLogon.protocol('WM_DELETE_WINDOW', self.doNothing)
        self.tlLogon.bind('<<signed>>', lambda database: eventF(self.dataBase))

        # Other widgets
        self.content = Frame(self.tlLogon)
        self.content.place(x=self.tlLogon.winfo_width() / 12,
                           y=self.tlLogon.winfo_height() / 6)

        self.labelAddress = Label(self.content,
                                  text="Adress:",
                                  font=("Arial Bold", 12))
        self.labelAddress.grid(row=0, column=0)

        self.textAddress = Entry(self.content, width=20)
        self.textAddress.grid(row=0, column=1)
        self.textAddress.insert(END, "localhost")  # TODO: REMOVE IT LATER

        self.labelUser = Label(self.content,
                               text="Username:"******"Arial Bold", 12))
        self.labelUser.grid(row=1, column=0)

        self.textUser = Entry(self.content, width=20)
        self.textUser.grid(row=1, column=1)
        self.textUser.insert(END, "root")  # TODO: REMOVE IT LATER

        self.labelPassword = Label(self.content,
                                   text="Password:"******"Arial Bold", 12))
        self.labelPassword.grid(row=2, column=0)

        self.textPassword = Entry(self.content, show='*', width=20)
        self.textPassword.grid(row=2, column=1)

        self.labelDatabase = Label(self.content,
                                   text="Database Name:",
                                   font=("Arial Bold", 12))
        self.labelDatabase.grid(row=3, column=0)

        self.textDatabase = Entry(self.content, width=20)
        self.textDatabase.grid(row=3, column=1)
        self.textDatabase.insert(END, "ZBD_project")

        self.buttonLogin = Button(self.content,
                                  text="Sign in",
                                  command=self.clickLogin)
        self.buttonLogin.grid(row=4, column=1)

        self.labelDatabase = Label(self.content,
                                   text="Incorrect login input!",
                                   font=("Arial Bold", 8),
                                   fg="red")
        self.labelDatabase.grid(row=5, column=1)
        self.labelDatabase.grid_remove()
Beispiel #18
0
"""
Written by
Noam Solan - 204484703
Yarin Kimhi - 308337641
"""

from options.ClientOptions import logging_level
from src.Logger import Logger
from src.Server import Server
from options.ServerOptions import server_params

Server(Logger(logging_level), **server_params).await_game_requests()
Beispiel #19
0
"""
Written by
Noam Solan - 204484703
Yarin Kimhi - 308337641
"""

from options.ClientOptions import client_params, logging_level
from src.Client import Client
from src.Logger import Logger

Client(Logger(logging_level), **client_params).init_game()
Beispiel #20
0
    def __init__(self, rootWindow, database, backEvent):
        self.rootWindow = rootWindow
        self.backEvent = backEvent
        self.database = database
        # Start logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug("ProcedureController logger has started.")

        self.mainLabels = ["Library", "Book title", "Genre", "Publishing date"]
        self.personalLabels = [
            "Reader's surname", "Reader's name", "Employee's surname",
            "Employee's name", "Comment(optional)"
        ]

        self.procedureWindow = Toplevel(self.rootWindow)
        self.procedureWindow.title("Check a book.")
        self.procedureWindow.protocol('WM_DELETE_WINDOW', self.goBack)
        self.procedureWindow.bind("<<back>>", lambda _: self.backEvent())

        self.mainFrame = Frame(self.procedureWindow,
                               bd=4,
                               relief=RAISED,
                               width=self.procedureWindow.winfo_width() - 40,
                               height=self.procedureWindow.winfo_height() - 40)
        self.mainFrame.pack(fill='both', side=TOP)

        self.comboBoxes = list()
        self.frames = list()
        for lab in self.mainLabels:
            self.frames.append(Frame(self.mainFrame))
            if len(self.comboBoxes) == 0:
                self.comboBoxes.append(
                    extendedComboBox(self.database, self.frames[-1], lab))
                self.comboBoxes[-1].combo.configure(state='readonly')
            else:
                self.comboBoxes.append(
                    extendedComboBox(self.database, self.frames[-1], lab))
                self.comboBoxes[-2].setChild(self.comboBoxes[-1])
                self.comboBoxes[-1].disable()
            self.frames[-1].pack(fill='both', side=TOP)
            # self.frames.append(Frame(self.mainFrame,
            #                          width=self.procedureWindow.winfo_width() - 40,
            #                          height=20 * 4
            #                          ))
            # Label(self.frames[no], text=lab, font=("Arial Bold", 12)).grid(row=0, column=0, columnspan=3)
            # entry = Entry(self.frames[no], width=20)
            # entry.grid(row=0, column=3, columnspan=2)
            # self.entries.append(entry)
            # self.frames[no].pack(fill='both', side=TOP)

        self.restFrame = Frame(self.mainFrame,
                               width=self.procedureWindow.winfo_width() - 40,
                               height=20 * 6)
        self.entries = dict()
        for no, lab in enumerate(self.personalLabels):
            #print(no, lab)
            l = Label(self.restFrame, text=lab, font=("Arial Bold", 12))
            l.grid(row=no, column=0, columnspan=3)
            if lab == "Comment(optional)":
                # self.commentEntry = Entry(self.restFrame, width=20)
                # self.commentEntry.grid(row=no, column=3, columnspan=2)
                self.commentEntry = scrolledtext.ScrolledText(self.restFrame,
                                                              width=40,
                                                              height=10)
                self.commentEntry.grid(row=no, column=3, columnspan=2)
                continue
            if lab == "Reader's surname":
                val = database.executeStatement(
                    "SELECT `nazwisko` FROM `pracownicy`")
            elif lab == "Reader's name":
                val = database.executeStatement(
                    "SELECT `imie` FROM `pracownicy`")
            elif lab == "Employee's surname":
                val = database.executeStatement(
                    "SELECT `nazwisko` FROM `pracownicy`")
            elif lab == "Employee's name":
                val = database.executeStatement(
                    "SELECT `imie` FROM `pracownicy`")
            entry = ttk.Combobox(self.restFrame, values=([""] + list(val)))
            entry.configure(state='readonly')
            entry.grid(row=no, column=3, columnspan=2, padx=5, pady=10)
            entry.bind("<<ComboboxSelected>>", lambda _: self.refreshValues())
            self.entries[l.cget("text")] = entry

        self.restFrame.pack(fill='both', side=BOTTOM)

        self.buttonFrame = Frame(self.procedureWindow,
                                 bd=4,
                                 relief=RAISED,
                                 width=self.procedureWindow.winfo_width() - 40,
                                 height=40)
        self.buttonFrame.pack(fill='both', side=TOP)

        self.hireButton = Button(self.buttonFrame,
                                 text="Hire",
                                 command=self.applyProcedure)
        self.hireButton.pack(side=LEFT)
        self.cancelButton = Button(self.buttonFrame,
                                   text="Cancel",
                                   command=self.goBack)
        self.cancelButton.pack(side=LEFT)
Beispiel #21
0
    def __init__(self, themeWindow, database, logoutEvent):
        self.database = database
        self.themeWindow = themeWindow
        # Start logger
        self.logger = Logger(__name__, loggingLevel="debug")
        self.logger.debug("MainController logger has started.")
        # Read table names from database object
        self.tableNames = self.database.getTableNames()
        if len(self.tableNames) != 0:
            self.logger.debug("Table names are loaded")
        else:
            self.logger.warning("No table names has been loaded!")

        self.procedureController = None
        self.functionController = None
        self.choiceWindow = None

        # Widgets
        # Main frame of this window
        self.content = Frame(self.themeWindow,
                             bg="#B7B9B8",
                             bd=4,
                             relief=RAISED,
                             width=self.themeWindow.winfo_width() - 80,
                             height=self.themeWindow.winfo_height() - 80)
        self.content.place(x=40, y=40)
        self.content.grid(row=0, column=0)
        self.content.bind("<<signout>>", lambda _: logoutEvent(None))
        self.content.update()

        self.listFrame = Frame(self.content,
                               bg="white",
                               bd=1,
                               relief=FLAT,
                               width=int(self.content.winfo_width() / 2 + 20),
                               height=int(self.content.winfo_height() - 60))
        self.listFrame.place(x=20, y=20)

        # Canvas which contains whole list of table names with their buttons
        self.tablesCanvas = Canvas(self.listFrame,
                                   bg="white",
                                   bd=1,
                                   relief=FLAT,
                                   width=int(self.content.winfo_width() / 2),
                                   height=int(self.content.winfo_height() -
                                              60))
        self.tablesCanvas.update()
        self.tablesScrollY = Scrollbar(self.listFrame,
                                       orient="vertical",
                                       command=self.tablesCanvas.yview)

        self.tablesFrame = Frame(self.tablesCanvas,
                                 bg="white",
                                 bd=0,
                                 relief=FLAT,
                                 width=self.tablesCanvas.winfo_width(),
                                 height=self.tablesCanvas.winfo_height())

        self.selectionVar = IntVar(
        )  # Int variable which contains current selection
        for no, table in enumerate(self.tableNames):
            Radiobutton(self.tablesFrame,
                        bg="white",
                        text=f"{table}",
                        variable=self.selectionVar,
                        value=no,
                        command=lambda: self.selection(self.tableNames[
                            self.selectionVar.get()])).pack(anchor=W)

        self.tablesCanvas.place(x=40, y=30)
        self.tablesCanvas.create_window(0,
                                        0,
                                        anchor='nw',
                                        window=self.tablesFrame)
        self.tablesCanvas.configure(scrollregion=self.tablesCanvas.bbox('all'),
                                    yscrollcommand=self.tablesScrollY.set)
        self.tablesCanvas.pack(fill='both', expand=True, side='left')
        self.tablesScrollY.pack(fill='y', side='left')

        # Frame which contain buttons
        self.buttonsFrame = Frame(self.content,
                                  bg="#B7B9B8",
                                  relief=RAISED,
                                  width=int(self.content.winfo_width() / 4),
                                  height=int(self.content.winfo_height() - 60))

        self.buttonsFrame.place(x=380, y=20)

        # Button to view selected table
        self.buttonViewTable = Button(self.buttonsFrame,
                                      text="View Table",
                                      command=self.viewTable,
                                      width=20,
                                      height=5)
        self.buttonViewTable.grid(row=0, column=0)
        # Button with SQL defined procedure
        self.buttonViewTable = Button(self.buttonsFrame,
                                      text="Hire a book",
                                      command=self.customProcedure,
                                      width=20,
                                      height=5)
        self.buttonViewTable.grid(row=1, column=0)
        # Button with SQL defined function
        self.buttonViewTable = Button(self.buttonsFrame,
                                      text="Top book",
                                      command=self.functionEntry,
                                      width=20,
                                      height=5)
        self.buttonViewTable.grid(row=2, column=0)
        # Button to log out
        self.buttonViewTable = Button(self.buttonsFrame,
                                      text="Log out",
                                      command=self.logout,
                                      width=20,
                                      height=5)
        self.buttonViewTable.grid(row=3, column=0)
Beispiel #22
0
# @date      : 17/02/12
# @author    : mi-na

# my module
from src.init import initialize
import src.params as params
import src.operate as ope
from src.Logger import Logger

# public module
# nothing

##! main process
if __name__ == '__main__':
    ## @brief initialize
    g_map, g_players = initialize()
    g_map.printMap()
    print("turn 0")
    for p in g_players:
        p.printPlayer()
    g_logger = Logger(g_players)

    ## @brief routine
    status_code = "NEXT"
    for i in range(params.max_turn()):
        status_code, g_players, g_logger = ope.routine(i + 1, g_players, g_map,
                                                       g_logger)
        if not status_code == "NEXT":
            break
    print(status_code)
Beispiel #23
0
import socket

from src.config import WIFI_IP
from src.config import WIFI_PORT
from src.config import LOCALE
from src.Logger import Logger
from src.communicator.utils import pcMsgParser

log = Logger()

'''
PC will need an accompanying (reference available in playgrounds pc_client.py
PC.connect() will wait for PC to connect before proceeding

pc = PC()
pc.connect()
while True:
    msg = pc.read()
    print(msg)
'''

class PC:
    def __init__(self, host=WIFI_IP, port=WIFI_PORT):
        self.host = host
        self.port = port
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_sock = None
        self.address = None

    def connect(self):
        log.info('Establishing connection with PC')
Beispiel #24
0
            old_state = current_state
            current_state = game.result(old_state, next_move)
            print_current_move(game, old_state, current_state, next_move,
                               iteration, [])
            iteration += 1

            print("Siamo ancora in fase " + str(phase))

    return current_state


# BODY TEST

millsGame = MillsGame()
logger = Logger()
# mode = 2
mode = int(
    input(
        "Scegli in quale modalità giocare: \n"
        "- mode = 1 -> AI vs Random Advanced (Select random move from filtered actions) \n"
        "- mode = 2 -> AI vs AI \n"
        "- mode = 3 -> AI vs Human \n"
        "- mode = 4 -> Human vs AI\n"))

use_start_state = input("Vuoi partire da una vecchia partita? (s/n)\n")
if use_start_state.lower() == 's':
    starter_state_name = input(
        "Inserisci il nome del file (comprensivo di estensione) \n")
    start_state = logger.read_state(starter_state_name)
else:
Beispiel #25
0
from src.ParentParser import ParentParser
from src.ChildParser import ChildParser
from src.Logger import Logger
from src.utils.tools import random_sleep
import random

from css_selectors.example import features, url, subpage, selectors, url_changer

if url[-1] is not '/':
    url += '/'
site_name = url.split('/')[-2]

log = Logger(site_name)

parent = ParentParser(url, subpage, selectors['parent'], log)

for child_url in parent.url_list:
    child_url = url_changer(child_url)
    # If site uses extent link as hyperlink format
    if features['extent_link']:
        if child_url[0] is '/':  # Modify url format
            child_url = child_url[1:]
        child_url = url + child_url
    # Check if duplicated
    if log.check_url(child_url, child=True):
        print('skipped one')
        continue
    # Parse summary if have
    ChildParser(child_url, selectors['child'], 'output/{}/'.format(site_name),
                features['summary_exist'])
    def start_simulation(self,
                         order_list,
                         num_robots,
                         render_=True,
                         log_=True,
                         print_=True):

        # Define simulation environment
        env = simpy.Environment()

        # Define knowledge base (SQL database)
        kb = self.define_knowledge_base(env)

        # Define communication channel between FleetManager and AGVs (These are just the virtual IP adresses)
        fm_to_agv_comm = dict()
        [
            fm_to_agv_comm.update({i + 1: simpy.FilterStore(env)})
            for i in range(num_robots)
        ]

        # Define communication channel between AGVs and fleet manager (These are just the virtual IP adresses)
        agv_to_fm_comm = simpy.FilterStore(env)

        # Define MES
        mes = MES(env, kb, order_list, print_)

        # Define Fleet Manger / Central Auctioneer
        FleetManager(env, kb, fm_to_agv_comm, agv_to_fm_comm, print_)

        # Define AGVs
        for ID in range(num_robots):
            agv_params = {
                'ID': ID + 1,
                'robot_speed': self.robot_speed,
                'task_execution_time': self.task_execution_time,
                'start_location': self.start_locations[ID % 3],
                'depot_locations': self.depot_locations,
                'battery_threshold': self.battery_threshold,
                'collision_threshold': self.collision_threshold,
                'max_charging_time': self.max_charging_time,
                'max_tasks_in_task_list': self.max_tasks_in_task_list,
                'epsilon': self.epsilon,
                'initial_resources': self.initial_resources
            }
            AGV(env, agv_params, kb, fm_to_agv_comm[ID + 1], agv_to_fm_comm,
                print_)

        # Define logger
        if log_:
            Logger(env, kb, print_)

        # Define online renderer
        if render_:
            RendererOnline(env, kb, self.depot_locations,
                           self.charge_locations, print_)

        # Run environment untill all tasks are executed
        env.run(until=mes.main)
        simulation_time = env.now - 1  # Correction for last time step

        # Print simulation duration
        with open("../logfiles/simulation_information.txt", "w") as file:
            file.write(str(num_robots) + '\n')
            file.write(str(simulation_time) + '\n')

        # Get simulation summary
        travel_cost = sum(get_travel_cost_per_robot())
        charging_cost = sum(get_charging_cost_per_robot())
        congestions = sum(get_congestions_per_robot()) / 2

        return simulation_time, travel_cost, charging_cost, congestions