Beispiel #1
0
class SelectChoice:
    def __init__(self, cb, container, label, options):
        self.cb = cb
        self.choice = 0
        self.options = options

        self.widget_label = QLabel(label)
        self.widget_options = QComboBox()
        self.widget_options.addItems(options)
        self.widget_options.currentIndexChanged.connect(self.on_selection)

        row = container.rowCount()
        container.addWidget(self.widget_label, row, 0)
        container.addWidget(self.widget_options, row, 1)

    def delete(self):
        self.widget_label.hide()
        self.widget_label.deleteLater()
        self.widget_options.hide()
        self.widget_options.deleteLater()

    def pack(self):
        val = bin(self.choice)[2:]
        val = "0" * ((len(self.options) - 1).bit_length() - len(val)) + val
        return val

    def unpack(self, value):
        self.change(int(value, 2))

    def change(self, value):
        self.choice = value
        self.widget_options.setCurrentIndex(self.choice)

    def on_selection(self):
        self.choice = self.widget_options.currentIndex()
        self.cb()
Beispiel #2
0
class QtDBConsoleWindow(QMainWindow):
    def __init__(self, master):
        super(QtDBConsoleWindow, self).__init__()
        self.master = master
        self.connection = self.master.connection
        self.GroupBoxSeg = [1, 10, 1]
        self.processing = []
        #Fixme: QTimer to be added to update the page automatically

        self.mainWidget = QWidget()
        self.mainLayout = QGridLayout()
        self.mainWidget.setLayout(self.mainLayout)
        self.setCentralWidget(self.mainWidget)

        self.occupied()
        self.setLoginUI()
        self.createHeadLine()
        self.createMain()
        self.createApp()
        if isActive(self.connection):
            self.connectDB()

    def setLoginUI(self):
        self.setGeometry(200, 200, 600, 1200)
        self.setWindowTitle('Database Console')

        self.menubar = self.menuBar()
        self.menubar.setNativeMenuBar(False)

        ###################################################
        ##  Database Menu
        ###################################################
        self.actionDatabase = self.menubar.addMenu("&Database")

        self.ViewerAction = QAction("&View Table")
        self.ViewerAction.triggered.connect(self.viewTable)
        self.actionDatabase.addAction(self.ViewerAction)

        ###################################################
        ##  Image Menu
        ###################################################
        self.actionImage = self.menubar.addMenu("&Image")

        self.InsertImgAction = QAction("&Insert Image")
        self.InsertImgAction.triggered.connect(self.insertImage)
        self.actionImage.addAction(self.InsertImgAction)

        self.ViewImgAction = QAction("&View Image")
        self.ViewImgAction.triggered.connect(self.viewImage)
        self.actionImage.addAction(self.ViewImgAction)

        ###################################################
        ##  Shipment Menu
        ###################################################
        self.actionShipment = self.menubar.addMenu("&Shipment")

        self.sendPackAction = QAction("&Send Package")
        self.sendPackAction.triggered.connect(self.sendPackage)
        self.actionShipment.addAction(self.sendPackAction)

        self.receivePackAction = QAction("&Receive Package")
        self.receivePackAction.triggered.connect(self.receivePackage)
        self.actionShipment.addAction(self.receivePackAction)

        ###################################################
        ##  User Menu
        ###################################################
        self.actionUser = self.menubar.addMenu("&User")

        self.ShowUserAction = QAction("&Show Users", self)
        self.ShowUserAction.triggered.connect(self.displayUsers)
        self.actionUser.addAction(self.ShowUserAction)

        self.AddUserAction = QAction("&Add Users", self)
        self.AddUserAction.triggered.connect(self.addUsers)
        self.actionUser.addAction(self.AddUserAction)

        self.UpdateUserAction = QAction("&Update Profile", self)
        self.UpdateUserAction.triggered.connect(self.updateProfile)
        self.actionUser.addAction(self.UpdateUserAction)

        self.ShowInstAction = QAction("&Show institute", self)
        self.ShowInstAction.triggered.connect(self.displayInstitue)
        self.actionUser.addAction(self.ShowInstAction)

        ###################################################
        ##  Miscellanea Menu
        ###################################################
        self.actionMiscel = self.menubar.addMenu("&Miscellanea")

        self.ComplaintAction = QAction("&Submit Complaint", self)
        self.ComplaintAction.triggered.connect(self.fileComplaint)
        self.actionMiscel.addAction(self.ComplaintAction)

        self.show()

    def activateMenuBar(self):
        self.menubar.setDisabled(False)

    def deactivateMenuBar(self):
        self.menubar.setDisabled(True)

    def enableMenuItem(self, item, enabled):
        item.setEnabled(enabled)

    ##########################################################################
    ##  Functions for Table Viewer
    ##########################################################################

    def viewTable(self):
        viewTableTab = QtViewTableTab(self)
        self.MainTabs.addTab(viewTableTab, "Database Viewer")
        self.MainTabs.setCurrentWidget(viewTableTab)

    ##########################################################################
    ##  Functions for Table Viewer (END)
    ##########################################################################

    ##########################################################################
    ##  Functions for Image
    ##########################################################################

    def insertImage(self):
        insertImageTab = QtImageInsertionTab(self)
        self.InsertImgAction.setDisabled(True)
        self.MainTabs.addTab(insertImageTab, "Insert Image")
        self.MainTabs.setCurrentWidget(insertImageTab)

    def viewImage(self):
        viewImageTab = QtImageViewerTab(self)
        self.MainTabs.addTab(viewImageTab, "Image  Viewer")
        self.MainTabs.setCurrentWidget(viewImageTab)

    ##########################################################################
    ##  Functions for Image (END)
    ##########################################################################

    ##########################################################################
    ##  Functions for Shipment
    ##########################################################################

    def sendPackage(self):
        self.sendPackageTab = QWidget()

        # Add tabs
        self.MainTabs.addTab(self.sendPackageTab, "Send Package")
        self.sendPackAction.setDisabled(True)
        self.sendPackageTab.layout = QGridLayout(self)
        sendPackageLabel = QLabel('<font size="12"> Package Delivery </font>')
        sendPackageLabel.setMaximumHeight(60)

        self.SPSenderLabel = QLabel('Sender:')
        self.SPSenderEdit = QLineEdit('')
        self.SPSenderEdit.setEchoMode(QLineEdit.Normal)
        self.SPSenderEdit.setPlaceholderText('Sender Name')

        self.SPReceiverLabel = QLabel('Receiver:')
        self.SPReceiverEdit = QLineEdit('')
        self.SPReceiverEdit.setEchoMode(QLineEdit.Normal)
        self.SPReceiverEdit.setPlaceholderText('Receiver Name')
        self.SPReceiverEdit.setDisabled(True)

        siteList = getByColumnName("institute",
                                   describeInstitute(self.connection),
                                   retrieveAllInstitute(self.connection))

        self.SPOriginLabel = QLabel('Origin:')
        self.SPOriginCombo = QComboBox()
        self.SPOriginCombo.addItems(["{0}".format(x) for x in siteList])

        self.SPDestinationLabel = QLabel('Destination:')
        self.SPDestinationCombo = QComboBox()
        self.SPDestinationCombo.addItems(["{0}".format(x) for x in siteList])

        self.SPDateSentLabel = QLabel('date sent:')
        self.SPDateSentEdit = QDateTimeEdit()
        self.SPDateSentEdit.setDateTime(QDateTime.currentDateTime())

        self.SPDateReceivedLabel = QLabel('date received:')
        self.SPDateReceivedEdit = QDateTimeEdit()
        self.SPDateReceivedEdit.setDisabled(True)
        #self.SPDateReceivedEdit.setDateTime(QDateTime.currentDateTime())

        self.SPCarrierLabel = QLabel('Carrier:')
        self.SPCarrierEdit = QLineEdit('')
        self.SPCarrierEdit.setEchoMode(QLineEdit.Normal)
        self.SPCarrierEdit.setPlaceholderText('carrier name')

        self.SPTrackingLabel = QLabel('Tracking Number:')
        self.SPTrackingEdit = QLineEdit('')
        self.SPTrackingEdit.setEchoMode(QLineEdit.Normal)
        self.SPTrackingEdit.setPlaceholderText('Tracking Code')

        self.SPCommentLabel = QLabel('Comment:')
        self.SPCommentEdit = QTextEdit('')
        self.SPCommentEdit.setPlaceholderText("Your comment")

        self.SPFeedBackLabel = QLabel()

        self.SPSubmitButton = QPushButton('Submit')
        self.SPSubmitButton.clicked.connect(self.submitSPRequest)

        self.sendPackageTab.layout.addWidget(sendPackageLabel, 0, 0, 1, 4,
                                             Qt.AlignTop)
        self.sendPackageTab.layout.addWidget(self.SPSenderLabel, 1, 0, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPSenderEdit, 1, 1, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPDateSentLabel, 1, 2, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPDateSentEdit, 1, 3, 1, 1)

        self.sendPackageTab.layout.addWidget(self.SPOriginLabel, 2, 0, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPOriginCombo, 2, 1, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPDestinationLabel, 2, 2, 1,
                                             1)
        self.sendPackageTab.layout.addWidget(self.SPDestinationCombo, 2, 3, 1,
                                             1)

        self.sendPackageTab.layout.addWidget(self.SPCarrierLabel, 3, 0, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPCarrierEdit, 3, 1, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPTrackingLabel, 3, 2, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPTrackingEdit, 3, 3, 1, 1)

        self.sendPackageTab.layout.addWidget(self.SPCommentLabel, 4, 0, 1, 4,
                                             Qt.AlignLeft)
        self.sendPackageTab.layout.addWidget(self.SPCommentEdit, 5, 0, 3, 4)
        self.sendPackageTab.layout.addWidget(self.SPFeedBackLabel, 8, 0, 1, 2)
        self.sendPackageTab.layout.addWidget(self.SPSubmitButton, 8, 3, 1, 1)

        self.sendPackageTab.setLayout(self.sendPackageTab.layout)
        self.MainTabs.setCurrentWidget(self.sendPackageTab)

    def submitSPRequest(self):
        if self.SPTrackingEdit.text() == "":
            self.SPFeedBackLabel.setText(
                "Please make sure Tracking Number are filled")
            return
        if self.SPSenderEdit.text() == "":
            self.SPFeedBackLabel.setText("Please make sure sender are filled")
            return
        Args = describeTable(self.connection, "shipment")
        Data = []
        SubmitArgs = []
        for arg in Args:
            if arg == "origin":
                Data.append(self.SPOriginCombo.currentText())
                SubmitArgs.append(arg)
            if arg == "destination":
                Data.append(self.SPDestinationCombo.currentText())
                SubmitArgs.append(arg)
            if arg == "sender":
                Data.append(self.SPSenderEdit.text())
                SubmitArgs.append(arg)
            if arg == "date_sent":
                Data.append(self.SPDateSentEdit.dateTime().toUTC().toString(
                    "yyyy-dd-MM hh:mm:ss.z"))
                SubmitArgs.append(arg)
            if arg == "carrier":
                Data.append(self.SPCarrierEdit.text())
                SubmitArgs.append(arg)
            if arg == "tracking_number":
                Data.append(self.SPTrackingEdit.text())
                SubmitArgs.append(arg)
            if arg == "comment":
                Data.append(self.SPCommentEdit.toPlainText())
                SubmitArgs.append(arg)
        try:
            insertGenericTable(self.connection, "shipment", SubmitArgs, Data)
        except:
            print("Failed to submit the shipment record")
            return

        self.SPSenderLabel.deleteLater()
        self.SPSenderEdit.deleteLater()
        self.SPDateSentLabel.deleteLater()
        self.SPDateSentEdit.deleteLater()

        self.SPOriginLabel.deleteLater()
        self.SPOriginCombo.deleteLater()
        self.SPDestinationLabel.deleteLater()
        self.SPDestinationCombo.deleteLater()

        self.SPCarrierLabel.deleteLater()
        self.SPCarrierEdit.deleteLater()
        self.SPTrackingLabel.deleteLater()
        self.SPTrackingEdit.deleteLater()

        self.SPCommentLabel.deleteLater()
        self.SPCommentEdit.deleteLater()
        self.SPFeedBackLabel.deleteLater()
        self.SPSubmitButton.deleteLater()

        self.sendPackageTab.layout.removeWidget(self.SPSenderLabel)
        self.sendPackageTab.layout.removeWidget(self.SPSenderEdit)
        self.sendPackageTab.layout.removeWidget(self.SPDateSentLabel)
        self.sendPackageTab.layout.removeWidget(self.SPDateSentEdit)

        self.sendPackageTab.layout.removeWidget(self.SPOriginLabel)
        self.sendPackageTab.layout.removeWidget(self.SPOriginCombo)
        #self.sendPackageTab.layout.removeWidget(self.SPDestinationLabel)
        #self.sendPackageTab.layout.removeWidget(self.SPDestinationCombo)

        self.sendPackageTab.layout.removeWidget(self.SPCarrierLabel)
        self.sendPackageTab.layout.removeWidget(self.SPCarrierEdit)
        self.sendPackageTab.layout.removeWidget(self.SPTrackingLabel)
        self.sendPackageTab.layout.removeWidget(self.SPTrackingEdit)

        self.sendPackageTab.layout.removeWidget(self.SPCommentLabel)
        self.sendPackageTab.layout.removeWidget(self.SPCommentEdit)
        self.sendPackageTab.layout.removeWidget(self.SPFeedBackLabel)
        self.sendPackageTab.layout.removeWidget(self.SPSubmitButton)

        self.SPFeedBackLabel = QLabel("Submitted")
        self.SPFeedBackLabel.setStyleSheet("color:green")
        self.SPContinueButton = QPushButton('Continue')
        self.SPContinueButton.clicked.connect(self.recreateSP)
        self.SPCloseButton = QPushButton('Close')
        self.SPCloseButton.clicked.connect(self.closeSP)
        self.sendPackageTab.layout.addWidget(self.SPFeedBackLabel, 1, 0, 1, 2)
        self.sendPackageTab.layout.addWidget(self.SPContinueButton, 1, 3, 1, 1)
        self.sendPackageTab.layout.addWidget(self.SPCloseButton, 1, 4, 1, 1)
        return

    def recreateSP(self):
        self.closeTab(self.MainTabs.currentIndex())
        self.sendPackage()

    def closeSP(self):
        self.closeTab(self.MainTabs.currentIndex())

    def receivePackage(self):
        self.receivePackageTab = QWidget()

        # Add tabs
        self.MainTabs.addTab(self.receivePackageTab, "Receive Package")
        self.receivePackAction.setDisabled(True)
        self.receivePackageTab.layout = QGridLayout(self)
        receivePackageLabel = QLabel(
            '<font size="12"> Package Delivery </font>')
        receivePackageLabel.setMaximumHeight(60)

        self.RPIDLabel = QLabel('ID:')
        self.RPIDEdit = QLineEdit('')
        self.RPIDEdit.setEchoMode(QLineEdit.Normal)
        self.RPIDEdit.setPlaceholderText('Shipment ID')
        self.RPFetchButton = QPushButton("Fetch")
        self.RPFetchButton.clicked.connect(self.fillRPRequest)

        self.RPSenderLabel = QLabel('Sender:')
        self.RPSenderEdit = QLineEdit('')
        self.RPSenderEdit.setEchoMode(QLineEdit.Normal)
        self.RPSenderEdit.setPlaceholderText('Sender Name')
        self.RPSenderEdit.setDisabled(True)

        self.RPReceiverLabel = QLabel('Receiver:')
        self.RPReceiverEdit = QLineEdit('')
        self.RPReceiverEdit.setEchoMode(QLineEdit.Normal)
        self.RPReceiverEdit.setPlaceholderText('Receiver Name')

        siteList = getByColumnName("institute",
                                   describeInstitute(self.connection),
                                   retrieveAllInstitute(self.connection))

        self.RPOriginLabel = QLabel('Origin:')
        self.RPOriginCombo = QComboBox()
        self.RPOriginCombo.addItems(["{0}".format(x) for x in siteList])
        self.RPOriginCombo.setDisabled(True)

        self.RPDestinationLabel = QLabel('Destination:')
        self.RPDestinationCombo = QComboBox()
        self.RPDestinationCombo.addItems(["{0}".format(x) for x in siteList])
        self.RPDestinationCombo.setDisabled(True)

        self.RPDateSentLabel = QLabel('date sent:')
        self.RPDateSentEdit = QDateTimeEdit()
        #self.RPDateSentEdit.setDateTime(QDateTime.currentDateTime())
        self.RPDateSentEdit.setDisabled(True)

        self.RPDateReceivedLabel = QLabel('date received:')
        self.RPDateReceivedEdit = QDateTimeEdit()
        self.RPDateReceivedEdit.setDateTime(QDateTime.currentDateTime())

        self.RPCarrierLabel = QLabel('Carrier:')
        self.RPCarrierEdit = QLineEdit('')
        self.RPCarrierEdit.setEchoMode(QLineEdit.Normal)
        self.RPCarrierEdit.setPlaceholderText('carrier name')
        self.RPCarrierEdit.setDisabled(True)

        self.RPTrackingLabel = QLabel('Tracking Number:')
        self.RPTrackingEdit = QLineEdit('')
        self.RPTrackingEdit.setEchoMode(QLineEdit.Normal)
        self.RPTrackingEdit.setPlaceholderText('Tracking Code')
        self.RPTrackingEdit.setDisabled(True)

        self.RPCommentLabel = QLabel('Comment:')
        self.RPCommentEdit = QTextEdit('')
        self.RPCommentEdit.setPlaceholderText("Your comment")

        self.RPFeedBackLabel = QLabel()

        self.RPSubmitButton = QPushButton('Submit')
        self.RPSubmitButton.clicked.connect(self.submitRPRequest)

        self.receivePackageTab.layout.addWidget(receivePackageLabel, 0, 0, 1,
                                                4, Qt.AlignTop)

        self.receivePackageTab.layout.addWidget(self.RPIDLabel, 1, 0, 1, 1)
        self.receivePackageTab.layout.addWidget(self.RPIDEdit, 1, 1, 1, 1)
        self.receivePackageTab.layout.addWidget(self.RPFetchButton, 1, 2, 1, 1)

        self.receivePackageTab.layout.addWidget(self.RPSenderLabel, 2, 0, 1, 1)
        self.receivePackageTab.layout.addWidget(self.RPSenderEdit, 2, 1, 1, 1)
        self.receivePackageTab.layout.addWidget(self.RPDateSentLabel, 2, 2, 1,
                                                1)
        self.receivePackageTab.layout.addWidget(self.RPDateSentEdit, 2, 3, 1,
                                                1)

        self.receivePackageTab.layout.addWidget(self.RPReceiverLabel, 3, 0, 1,
                                                1)
        self.receivePackageTab.layout.addWidget(self.RPReceiverEdit, 3, 1, 1,
                                                1)
        self.receivePackageTab.layout.addWidget(self.RPDateReceivedLabel, 3, 2,
                                                1, 1)
        self.receivePackageTab.layout.addWidget(self.RPDateReceivedEdit, 3, 3,
                                                1, 1)

        self.receivePackageTab.layout.addWidget(self.RPOriginLabel, 4, 0, 1, 1)
        self.receivePackageTab.layout.addWidget(self.RPOriginCombo, 4, 1, 1, 1)
        self.receivePackageTab.layout.addWidget(self.RPDestinationLabel, 4, 2,
                                                1, 1)
        self.receivePackageTab.layout.addWidget(self.RPDestinationCombo, 4, 3,
                                                1, 1)

        self.receivePackageTab.layout.addWidget(self.RPCarrierLabel, 5, 0, 1,
                                                1)
        self.receivePackageTab.layout.addWidget(self.RPCarrierEdit, 5, 1, 1, 1)
        self.receivePackageTab.layout.addWidget(self.RPTrackingLabel, 5, 2, 1,
                                                1)
        self.receivePackageTab.layout.addWidget(self.RPTrackingEdit, 5, 3, 1,
                                                1)

        self.receivePackageTab.layout.addWidget(self.RPCommentLabel, 6, 0, 1,
                                                4, Qt.AlignLeft)
        self.receivePackageTab.layout.addWidget(self.RPCommentEdit, 7, 0, 3, 4)
        self.receivePackageTab.layout.addWidget(self.RPFeedBackLabel, 10, 0, 1,
                                                3)
        self.receivePackageTab.layout.addWidget(self.RPSubmitButton, 10, 3, 1,
                                                1)

        self.receivePackageTab.setLayout(self.receivePackageTab.layout)
        self.MainTabs.setCurrentWidget(self.receivePackageTab)

    def fillRPRequest(self):
        try:
            header = describeTable(self.connection, "shipment", True)
            shipmentInfo = retrieveWithConstraint(self.connection,
                                                  "shipment",
                                                  id=self.RPIDEdit.text())
        except:
            return
        if len(shipmentInfo) > 0 and len(header) == len(shipmentInfo[0]):
            self.RPFeedBackLabel.setText("Delivery Record found")
            self.RPSenderEdit.setText(
                getByColumnName("sender", header, shipmentInfo)[0])
            origin_index = self.RPOriginCombo.findText(
                getByColumnName("origin", header, shipmentInfo)[0])
            self.RPOriginCombo.setCurrentIndex(origin_index)
            destination_index = self.RPDestinationCombo.findText(
                getByColumnName("destination", header, shipmentInfo)[0])
            self.RPDestinationCombo.setCurrentIndex(destination_index)
            time_string = getByColumnName(
                "date_sent", header,
                shipmentInfo)[0].strftime("%m/%d/%Y, %H:%M:%S")
            print(time_string)
            self.RPDateSentEdit.setDateTime(QDateTime.fromString(time_string))
            self.RPCarrierEdit.setText(
                getByColumnName("carrier", header, shipmentInfo)[0])
            self.RPTrackingEdit.setText(
                getByColumnName("tracking_number", header, shipmentInfo)[0])
            self.RPCommentEdit.setText(
                getByColumnName("comment", header, shipmentInfo)[0])
        else:
            self.RPFeedBackLabel.setText("Shipment ID not found")
            self.RPSenderEdit.setText("")
            origin_index = self.RPOriginCombo.findText("")
            self.RPOriginCombo.setCurrentIndex(origin_index)
            destination_index = self.RPDestinationCombo.findText("")
            self.RPDestinationCombo.setCurrentIndex(destination_index)
            #time_string = datetime.strftime("%m/%d/%Y, %H:%M:%S")
            #self.RPDateSentEdit.setDateTime(QDateTime.fromString(time_string))
            self.RPCarrierEdit.setText("")
            self.RPTrackingEdit.setText("")
            self.RPCommentEdit.setText("")

    def submitRPRequest(self):
        if self.RPTrackingEdit.text() == "":
            self.RPFeedBackLabel.setText(
                "Please make sure Tracking Number are filled")
            return
        if self.RPReceiverEdit.text() == "":
            self.RPFeedBackLabel.setText(
                "Please make sure receiver are filled")
            return
        if self.RPDateReceivedEdit.text() == "":
            self.RPFeedBackLabel.setText(
                "Please make sure received time are filled")
            return
        Args = describeTable(self.connection, "shipment")
        Data = []
        SubmitArgs = []
        for arg in Args:
            if arg == "receiver":
                Data.append(self.RPReceiverEdit.text())
                SubmitArgs.append(arg)
            if arg == "date_received":
                Data.append(
                    self.RPDateReceivedEdit.dateTime().toUTC().toString(
                        "yyyy-dd-MM hh:mm:ss.z"))
                SubmitArgs.append(arg)
            if arg == "comment":
                Data.append(self.RPCommentEdit.toPlainText())
                SubmitArgs.append(arg)
        try:
            updateGenericTable(self.connection,
                               "shipment",
                               SubmitArgs,
                               Data,
                               id=int(self.RPIDEdit.text()))
        except:
            print("Failed to submit the shipment record")
            return

        self.RPIDLabel.deleteLater()
        self.RPIDEdit.deleteLater()
        self.RPFetchButton.deleteLater()

        self.RPSenderLabel.deleteLater()
        self.RPSenderEdit.deleteLater()
        self.RPDateSentLabel.deleteLater()
        self.RPDateSentEdit.deleteLater()

        self.RPReceiverLabel.deleteLater()
        self.RPReceiverEdit.deleteLater()
        self.RPDateReceivedLabel.deleteLater()
        self.RPDateReceivedEdit.deleteLater()

        self.RPOriginLabel.deleteLater()
        self.RPOriginCombo.deleteLater()
        self.RPDestinationLabel.deleteLater()
        self.RPDestinationCombo.deleteLater()

        self.RPCarrierLabel.deleteLater()
        self.RPCarrierEdit.deleteLater()
        self.RPTrackingLabel.deleteLater()
        self.RPTrackingEdit.deleteLater()

        self.RPCommentLabel.deleteLater()
        self.RPCommentEdit.deleteLater()
        self.RPFeedBackLabel.deleteLater()
        self.RPSubmitButton.deleteLater()

        self.receivePackageTab.layout.removeWidget(self.RPIDEdit)
        self.receivePackageTab.layout.removeWidget(self.RPIDLabel)
        self.receivePackageTab.layout.removeWidget(self.RPFetchButton)

        self.receivePackageTab.layout.removeWidget(self.RPSenderLabel)
        self.receivePackageTab.layout.removeWidget(self.RPSenderEdit)
        self.receivePackageTab.layout.removeWidget(self.RPDateSentLabel)
        self.receivePackageTab.layout.removeWidget(self.RPDateSentEdit)

        self.receivePackageTab.layout.removeWidget(self.RPReceiverLabel)
        self.receivePackageTab.layout.removeWidget(self.RPReceiverEdit)
        self.receivePackageTab.layout.removeWidget(self.RPDateReceivedLabel)
        self.receivePackageTab.layout.removeWidget(self.RPDateReceivedEdit)

        self.receivePackageTab.layout.removeWidget(self.RPOriginLabel)
        self.receivePackageTab.layout.removeWidget(self.RPOriginCombo)
        self.receivePackageTab.layout.removeWidget(self.RPDestinationLabel)
        self.receivePackageTab.layout.removeWidget(self.RPDestinationCombo)

        self.receivePackageTab.layout.removeWidget(self.RPCarrierLabel)
        self.receivePackageTab.layout.removeWidget(self.RPCarrierEdit)
        self.receivePackageTab.layout.removeWidget(self.RPTrackingLabel)
        self.receivePackageTab.layout.removeWidget(self.RPTrackingEdit)

        self.receivePackageTab.layout.removeWidget(self.RPCommentLabel)
        self.receivePackageTab.layout.removeWidget(self.RPCommentEdit)
        self.receivePackageTab.layout.removeWidget(self.RPFeedBackLabel)
        self.receivePackageTab.layout.removeWidget(self.RPSubmitButton)

        self.RPFeedBackLabel = QLabel("Submitted")
        self.RPFeedBackLabel.setStyleSheet("color:green")
        self.RPContinueButton = QPushButton('Continue')
        self.RPContinueButton.clicked.connect(self.recreateRP)
        self.RPCloseButton = QPushButton('Close')
        self.RPCloseButton.clicked.connect(self.closeRP)
        self.receivePackageTab.layout.addWidget(self.RPFeedBackLabel, 1, 0, 1,
                                                2)
        self.receivePackageTab.layout.addWidget(self.RPContinueButton, 1, 3, 1,
                                                1)
        self.receivePackageTab.layout.addWidget(self.RPCloseButton, 1, 4, 1, 1)
        return

    def recreateRP(self):
        self.closeTab(self.MainTabs.currentIndex())
        self.receivePackage()

    def closeRP(self):
        self.closeTab(self.MainTabs.currentIndex())

    ##########################################################################
    ##  Functions for Shipment  (END)
    ##########################################################################

    def displayUsers(self):
        self.processing.append("UserDisplay")
        UserDisplayTab = QWidget()

        # Add tabs
        self.MainTabs.addTab(UserDisplayTab, "User List")

        UserDisplayTab.layout = QGridLayout()

        dataList = ([describeTable(self.connection, "people")] +
                    retrieveGenericTable(self.connection, "people"))

        proxy = QtDBTableWidget(dataList, 0)

        lineEdit = QLineEdit()
        lineEdit.textChanged.connect(proxy.on_lineEdit_textChanged)
        view = QTableView()
        view.setSortingEnabled(True)
        comboBox = QComboBox()
        comboBox.addItems(["{0}".format(x) for x in dataList[0]])
        comboBox.currentIndexChanged.connect(
            proxy.on_comboBox_currentIndexChanged)
        label = QLabel()
        label.setText("Regex Filter")

        view.setModel(proxy)
        view.setSelectionBehavior(QAbstractItemView.SelectRows)
        view.setSelectionMode(QAbstractItemView.MultiSelection)
        view.setEditTriggers(QAbstractItemView.NoEditTriggers)

        UserDisplayTab.layout.addWidget(lineEdit, 0, 1, 1, 1)
        UserDisplayTab.layout.addWidget(view, 1, 0, 1, 3)
        UserDisplayTab.layout.addWidget(comboBox, 0, 2, 1, 1)
        UserDisplayTab.layout.addWidget(label, 0, 0, 1, 1)

        UserDisplayTab.setLayout(UserDisplayTab.layout)
        self.MainTabs.setCurrentWidget(UserDisplayTab)

    ##########################################################################
    ##  Functions for Managing Users
    ##########################################################################

    def addUsers(self):
        ## Fixme: disable the menu when tab exists, relieaze the menu when closed.
        self.processing.append("AddUser")
        AddingUserTab = QWidget()

        # Add tabs
        self.MainTabs.addTab(AddingUserTab, "Adding User")
        self.AddUserAction.setDisabled(True)
        AddingUserTab.layout = QGridLayout(self)
        AddUserLabel = QLabel('<font size="12"> Creating new user: </font>')
        AddUserLabel.setMaximumHeight(60)

        self.AUNewUsernameLabel = QLabel('username')
        self.AUNewUsernameEdit = QLineEdit('')
        self.AUNewUsernameEdit.setEchoMode(QLineEdit.Normal)
        self.AUNewUsernameEdit.setPlaceholderText('new username')

        self.AUPasswordLabel = QLabel('password')
        self.AUPasswordEdit = QLineEdit('')
        self.AUPasswordEdit.setEchoMode(QLineEdit.Password)
        self.AUPasswordEdit.setPlaceholderText('new password')

        self.AURePasswordLabel = QLabel('re-password')
        self.AURePasswordEdit = QLineEdit('')
        self.AURePasswordEdit.setEchoMode(QLineEdit.Password)
        self.AURePasswordEdit.setPlaceholderText('verify password')

        self.AUNameLabel = QLabel('*name')
        self.AUNameEdit = QLineEdit('')
        self.AUNameEdit.setEchoMode(QLineEdit.Normal)
        self.AUNameEdit.setPlaceholderText('short name')

        self.AUFullNameLabel = QLabel('*full name')
        self.AUFullNameEdit = QLineEdit('')
        self.AUFullNameEdit.setEchoMode(QLineEdit.Normal)
        self.AUFullNameEdit.setPlaceholderText('full name')

        self.AUEmailLabel = QLabel('e-mail')
        self.AUEmailEdit = QLineEdit('')
        self.AUEmailEdit.setEchoMode(QLineEdit.Normal)
        self.AUEmailEdit.setPlaceholderText('*****@*****.**')

        self.AUInstLabel = QLabel('institute')
        self.AUInstComboBox = QComboBox()
        siteList = getByColumnName("description",
                                   describeInstitute(self.connection),
                                   retrieveAllInstitute(self.connection))
        self.AUInstComboBox.addItems(["{0}".format(x) for x in siteList])

        self.AUFeedBackLabel = QLabel()

        self.AUSubmitButton = QPushButton('Submit')
        self.AUSubmitButton.clicked.connect(self.submitAURequest)

        AddingUserTab.layout.addWidget(AddUserLabel, 0, 0, 1, 4)
        AddingUserTab.layout.addWidget(self.AUNewUsernameLabel, 1, 0, 1, 1)
        AddingUserTab.layout.addWidget(self.AUNewUsernameEdit, 1, 1, 1, 1)
        AddingUserTab.layout.addWidget(self.AUPasswordLabel, 2, 0, 1, 1)
        AddingUserTab.layout.addWidget(self.AUPasswordEdit, 2, 1, 1, 1)
        AddingUserTab.layout.addWidget(self.AURePasswordLabel, 3, 0, 1, 1)
        AddingUserTab.layout.addWidget(self.AURePasswordEdit, 3, 1, 1, 1)
        AddingUserTab.layout.addWidget(self.AUNameLabel, 4, 0, 1, 1)
        AddingUserTab.layout.addWidget(self.AUNameEdit, 4, 1, 1, 1)
        AddingUserTab.layout.addWidget(self.AUFullNameLabel, 4, 2, 1, 1)
        AddingUserTab.layout.addWidget(self.AUFullNameEdit, 4, 3, 1, 1)
        AddingUserTab.layout.addWidget(self.AUEmailLabel, 5, 0, 1, 1)
        AddingUserTab.layout.addWidget(self.AUEmailEdit, 5, 1, 1, 1)
        AddingUserTab.layout.addWidget(self.AUInstLabel, 5, 2, 1, 1)
        AddingUserTab.layout.addWidget(self.AUInstComboBox, 5, 3, 1, 1)
        AddingUserTab.layout.addWidget(self.AUFeedBackLabel, 6, 0, 1, 3)
        AddingUserTab.layout.addWidget(self.AUSubmitButton, 6, 3, 1, 1)

        AddingUserTab.setLayout(AddingUserTab.layout)
        self.MainTabs.setCurrentWidget(AddingUserTab)

        #self.enableMenuItem(self.AddingUserTab, False)

    def submitAURequest(self):
        # check the password consistency
        if self.AUNewUsernameEdit.text() == "" or self.AUNameEdit.text(
        ) == "" or self.AUFullNameEdit.text() == "":
            self.AUFeedBackLabel.setText("key blank is empty")
            return
        if self.AUPasswordEdit.text() != self.AURePasswordEdit.text():
            self.AUFeedBackLabel.setText("passwords are inconsistent")
            self.AUPasswordEdit.setText("")
            self.AURePasswordEdit.setText("")
            return

        try:
            InstituteInfo = retrieveWithConstraint(
                self.connection,
                "institute",
                description=str(self.AUInstComboBox.currentText()))
            InstName = getByColumnName(
                "institute", describeTable(self.connection, "institute"),
                InstituteInfo)
            TimeZone = getByColumnName(
                "timezone", describeTable(self.connection, "institute"),
                InstituteInfo)
        except:
            self.AUFeedBackLabel.setText(
                "Failed to extract institute info, try to reconnect to DB")
        Args = describeTable(self.connection, "people")
        Data = []
        Data.append(self.AUNewUsernameEdit.text())
        Data.append(self.AUNameEdit.text())
        Data.append(self.AUFullNameEdit.text())
        Data.append(self.AUEmailEdit.text())
        Data.append(InstName[0])
        Data.append(self.AUPasswordEdit.text())
        Data.append(TimeZone[0])
        Data.append(0)
        try:
            createNewUser(self.connection, Args, Data)
            self.AUFeedBackLabel.setText("Query submitted")
            self.AUFeedBackLabel.setStyleSheet("color:green")
            return
        except:
            print("submitFailed")
            return

    def updateProfile(self):
        pass

    ##########################################################################
    ##  Functions for Adding Users (END)
    ##########################################################################

    ##########################################################################
    ##  Functions for Institutes display
    ##########################################################################
    def displayInstitue(self):
        self.processing.append("InstituteDisplay")

        displayInstiTab = QWidget()

        # Add tabs
        self.MainTabs.addTab(displayInstiTab, "Institutes")

        displayInstiTab.layout = QGridLayout(self)

        dataList = ([describeInstitute(self.connection)] +
                    retrieveAllInstitute(self.connection))

        proxy = QtDBTableWidget(dataList, 0)

        lineEdit = QLineEdit()
        lineEdit.textChanged.connect(proxy.on_lineEdit_textChanged)
        view = QTableView()
        view.setSortingEnabled(True)
        comboBox = QComboBox()
        comboBox.addItems(["{0}".format(x) for x in dataList[0]])
        comboBox.currentIndexChanged.connect(
            proxy.on_comboBox_currentIndexChanged)
        label = QLabel()
        label.setText("Regex Filter")

        view.setModel(proxy)
        view.setSelectionBehavior(QAbstractItemView.SelectRows)
        view.setSelectionMode(QAbstractItemView.MultiSelection)
        view.setEditTriggers(QAbstractItemView.NoEditTriggers)

        displayInstiTab.layout.addWidget(lineEdit, 0, 1, 1, 1)
        displayInstiTab.layout.addWidget(view, 1, 0, 1, 3)
        displayInstiTab.layout.addWidget(comboBox, 0, 2, 1, 1)
        displayInstiTab.layout.addWidget(label, 0, 0, 1, 1)

        displayInstiTab.setLayout(displayInstiTab.layout)
        self.MainTabs.setCurrentWidget(displayInstiTab)

    ##########################################################################
    ##  Functions for Institutes display (END)
    ##########################################################################

    ##########################################################################
    ##  Functions for Complaint submission
    ##########################################################################
    def fileComplaint(self):
        self.ComplaintTab = QWidget()

        # Add tabs
        self.MainTabs.addTab(self.ComplaintTab, "Complaint")
        self.ComplaintAction.setDisabled(True)
        self.ComplaintTab.layout = QGridLayout(self)
        ComplaintLabel = QLabel(
            '<font size="12"> Submit the complaint </font>')
        ComplaintLabel.setMaximumHeight(60)

        self.FCNameLabel = QLabel('Name:')
        self.FCNameEdit = QLineEdit('')
        self.FCNameEdit.setEchoMode(QLineEdit.Normal)
        TableInfo = describeTable(self.connection, "people")
        UserInfo = retrieveWithConstraint(self.connection,
                                          "people",
                                          username=self.TryUsername)
        ShortName = getByColumnName("name", TableInfo, UserInfo)
        if len(ShortName) > 0:
            self.FCNameEdit.setText(str(ShortName[0]))

        self.FCDateTimeLabel = QLabel('Date(local)')
        self.FCDateTimeEdit = QDateTimeEdit()
        self.FCDateTimeEdit.setDateTime(QDateTime.currentDateTime())

        self.FCCommentLabel = QLabel('Comment:')
        self.FCCommentEdit = QTextEdit('')
        self.FCCommentEdit.setPlaceholderText("Your comment")

        self.FCFeedBackLabel = QLabel()

        self.FCSubmitButton = QPushButton('Submit')
        self.FCSubmitButton.clicked.connect(self.submitFCRequest)

        self.ComplaintTab.layout.addWidget(ComplaintLabel, 0, 0, 1, 4,
                                           Qt.AlignTop)
        self.ComplaintTab.layout.addWidget(self.FCNameLabel, 1, 0, 1, 1)
        self.ComplaintTab.layout.addWidget(self.FCNameEdit, 1, 1, 1, 1)
        self.ComplaintTab.layout.addWidget(self.FCDateTimeLabel, 1, 2, 1, 1)
        self.ComplaintTab.layout.addWidget(self.FCDateTimeEdit, 1, 3, 1, 1)
        self.ComplaintTab.layout.addWidget(self.FCCommentLabel, 2, 0, 1, 4,
                                           Qt.AlignLeft)
        self.ComplaintTab.layout.addWidget(self.FCCommentEdit, 3, 0, 6, 4)
        self.ComplaintTab.layout.addWidget(self.FCFeedBackLabel, 9, 0, 1, 2)
        self.ComplaintTab.layout.addWidget(self.FCSubmitButton, 9, 3, 1, 1)

        self.ComplaintTab.setLayout(self.ComplaintTab.layout)
        self.MainTabs.setCurrentWidget(self.ComplaintTab)

    def submitFCRequest(self):
        if self.FCNameEdit.text() == "" or self.FCCommentEdit.toPlainText(
        ) == "":
            self.FCFeedBackLabel.setText(
                "Please make sure the name/comment are filled")
            return
        Args = describeTable(self.connection, "complaint")
        Data = []
        Data.append(self.FCDateTimeEdit.dateTime().toUTC().toString(
            "yyyy-dd-MM hh:mm:ss.z"))
        Data.append(self.FCCommentEdit.toPlainText())
        Data.append(self.FCNameEdit.text())
        print(Data)
        try:
            insertGenericTable(self.connection, "complaint", Args, Data)
        except:
            print("Failed to submit the text")
            return
        self.FCNameLabel.deleteLater()
        self.FCNameEdit.deleteLater()
        self.FCDateTimeLabel.deleteLater()
        self.FCDateTimeEdit.deleteLater()
        self.FCCommentLabel.deleteLater()
        self.FCCommentEdit.deleteLater()
        self.FCFeedBackLabel.deleteLater()
        self.FCSubmitButton.deleteLater()

        self.ComplaintTab.layout.removeWidget(self.FCNameLabel)
        self.ComplaintTab.layout.removeWidget(self.FCNameEdit)
        self.ComplaintTab.layout.removeWidget(self.FCDateTimeLabel)
        self.ComplaintTab.layout.removeWidget(self.FCDateTimeEdit)
        self.ComplaintTab.layout.removeWidget(self.FCCommentLabel)
        self.ComplaintTab.layout.removeWidget(self.FCCommentEdit)
        self.ComplaintTab.layout.removeWidget(self.FCFeedBackLabel)
        self.ComplaintTab.layout.removeWidget(self.FCSubmitButton)

        self.FCFeedBackLabel = QLabel("Submitted")
        self.FCFeedBackLabel.setStyleSheet("color:green")
        self.FCContinueButton = QPushButton('Continue')
        self.FCContinueButton.clicked.connect(self.recreateFC)
        self.ComplaintTab.layout.addWidget(self.FCFeedBackLabel, 1, 0, 1, 2)
        self.ComplaintTab.layout.addWidget(self.FCContinueButton, 1, 3, 1, 1)
        return

    def recreateFC(self):
        self.closeTab(self.MainTabs.currentIndex())
        self.fileComplaint()

    ##########################################################################
    ##  Functions for Complaint submission (END)
    ##########################################################################

    def createHeadLine(self):
        self.deactivateMenuBar()
        self.HeadBox = QGroupBox()

        self.HeadLayout = QHBoxLayout()

        UsernameLabel = QLabel("Username:"******"Password:"******"Host IP:")
        self.HostEdit = QLineEdit('128.146.38.1')
        self.HostEdit.setEchoMode(QLineEdit.Normal)
        self.HostEdit.setMinimumWidth(150)
        self.HostEdit.setMaximumHeight(30)

        DatabaseLabel = QLabel("Database:")
        self.DatabaseEdit = QLineEdit('SampleDB')
        self.DatabaseEdit.setEchoMode(QLineEdit.Normal)
        self.DatabaseEdit.setMinimumWidth(150)
        self.DatabaseEdit.setMaximumHeight(30)

        self.ConnectButton = QPushButton("&Connect to DB")
        self.ConnectButton.clicked.connect(self.connectDB)

        self.HeadLayout.addWidget(UsernameLabel)
        self.HeadLayout.addWidget(self.UsernameEdit)
        self.HeadLayout.addWidget(PasswordLabel)
        self.HeadLayout.addWidget(self.PasswordEdit)
        self.HeadLayout.addWidget(HostLabel)
        self.HeadLayout.addWidget(self.HostEdit)
        self.HeadLayout.addWidget(DatabaseLabel)
        self.HeadLayout.addWidget(self.DatabaseEdit)
        self.HeadLayout.addWidget(self.ConnectButton)

        self.HeadBox.setLayout(self.HeadLayout)

        self.mainLayout.addWidget(self.HeadBox, 0, 0, self.GroupBoxSeg[0], 1)

    def destroyHeadLine(self):
        self.HeadBox.deleteLater()
        self.mainLayout.removeWidget(self.HeadBox)

    def clearLogInfo(self):
        self.connection = "Offline"

    def connectedHeadLine(self):
        self.activateMenuBar()
        self.HeadBox.deleteLater()
        self.mainLayout.removeWidget(self.HeadBox)

        self.HeadBox = QGroupBox()
        self.HeadLayout = QHBoxLayout()

        WelcomeLabel = QLabel("Hello,{}!".format(self.TryUsername))

        statusString, colorString = checkDBConnection(self.connection)
        DBStatusLabel = QLabel()
        DBStatusLabel.setText("Database:{}/{}".format(self.TryHostAddress,
                                                      self.TryDatabase))
        DBStatusValue = QLabel()
        DBStatusValue.setText(statusString)
        DBStatusValue.setStyleSheet(colorString)

        self.SwitchButton = QPushButton("&Switch DB")
        self.SwitchButton.clicked.connect(self.destroyHeadLine)
        self.SwitchButton.clicked.connect(self.clearLogInfo)
        self.SwitchButton.clicked.connect(self.createHeadLine)

        self.HeadLayout.addWidget(WelcomeLabel)
        self.HeadLayout.addStretch(1)
        self.HeadLayout.addWidget(DBStatusLabel)
        self.HeadLayout.addWidget(DBStatusValue)
        self.HeadLayout.addWidget(self.SwitchButton)

        self.HeadBox.setLayout(self.HeadLayout)

        self.HeadBox.setLayout(self.HeadLayout)
        self.mainLayout.addWidget(self.HeadBox, 0, 0, self.GroupBoxSeg[0], 1)

    def createMain(self):
        self.MainBodyBox = QGroupBox()

        self.mainbodylayout = QHBoxLayout()

        self.MainTabs = QTabWidget()
        self.MainTabs.setTabsClosable(True)
        self.MainTabs.tabCloseRequested.connect(
            lambda index: self.closeTab(index))

        self.mainbodylayout.addWidget(self.MainTabs)

        self.MainBodyBox.setLayout(self.mainbodylayout)
        self.mainLayout.addWidget(self.MainBodyBox, sum(self.GroupBoxSeg[0:1]),
                                  0, self.GroupBoxSeg[1], 1)

    def destroyMain(self):
        self.MainBodyBox.deleteLater()
        self.mainLayout.removeWidget(self.MainBodyBox)

    def createApp(self):
        self.AppOption = QGroupBox()
        self.StartLayout = QHBoxLayout()

        self.ResetButton = QPushButton("&Refresh")

        self.FinishButton = QPushButton("&Finish")
        self.FinishButton.setDefault(True)
        self.FinishButton.clicked.connect(self.closeWindow)

        self.StartLayout.addWidget(self.ResetButton)
        self.StartLayout.addWidget(self.FinishButton)
        self.StartLayout.addStretch(1)
        self.AppOption.setLayout(self.StartLayout)

        self.mainLayout.addWidget(self.AppOption, sum(self.GroupBoxSeg[0:2]),
                                  0, self.GroupBoxSeg[2], 1)

    def destroyApp(self):
        self.AppOption.deleteLater()
        self.mainLayout.removeWidget(self.AppOption)

    def sendBackSignal(self):
        self.backSignal = True

    def connectDB(self):
        try:
            if isActive(self.connection):
                self.TryUsername = self.master.TryUsername
                self.TryHostAddress = self.master.TryHostAddress
                self.TryDatabase = self.master.TryDatabase
                self.connectedHeadLine()
                return
            self.TryUsername = self.UsernameEdit.text()
            self.TryPassword = self.PasswordEdit.text()
            self.TryHostAddress = self.HostEdit.text()
            self.TryDatabase = self.DatabaseEdit.text()

            if self.TryUsername == '':
                msg.information(None, "Error", "Please enter a valid username",
                                QMessageBox.Ok)
                return

            self.connection = QtStartConnection(self.TryUsername,
                                                self.TryPassword,
                                                self.TryHostAddress,
                                                self.TryDatabase)

            if isActive(self.connection):
                self.connectedHeadLine()
        except Exception as err:
            print("Error in connecting to database, {}".format(repr(err)))

    def syncDB(self):
        pass

    def changeDBList(self):
        self.DBNames = DBNames[str(self.HostName.currentText())]
        self.DatabaseCombo.clear()
        self.DatabaseCombo.addItems(self.DBNames)
        self.DatabaseCombo.setCurrentIndex(0)

    def closeTab(self, index):
        self.releaseAction(self.MainTabs.tabText(index))
        self.MainTabs.removeTab(index)

    def releaseAction(self, text):
        if text == "Adding User":
            self.AddUserAction.setDisabled(False)
            return
        if text == "Complaint":
            self.ComplaintAction.setDisabled(False)
            return
        if text == "Send Package":
            self.sendPackAction.setDisabled(False)
            return
        if text == "Receive Package":
            self.receivePackAction.setDisabled(False)
            return
        if text == "Insert Image":
            self.InsertImgAction.setDisabled(False)
            return

    def closeWindow(self):
        self.close()
        self.release()

    def occupied(self):
        self.master.DBConsoleButton.setDisabled(True)

    def release(self):
        self.master.DBConsoleButton.setDisabled(False)

    def closeEvent(self, event):
        #Fixme: strict criterias for process checking  should be added here:
        #if self.ProcessingTest == True:
        #	QMessageBox.critical(self, 'Critical Message', 'There is running process, can not close!')
        #	event.ignore()

        reply = QMessageBox.question(
            self, 'Window Close',
            'Are you sure you want to exit, all unsubmitted content will be lost?',
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            print('DB console terminated')
            event.accept()
        else:
            event.ignore()
Beispiel #3
0
class View(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        """Put the dialog window on top and block all windows."""
        self.setWindowModality(Qt.ApplicationModal)

        self.progressBar = QProgressBar(self)
        self.progressBar.setAlignment(Qt.AlignCenter)
        self.progressBar.setValue(0)

        self.btnOpen = QPushButton(Strings.connect)
        self.btnClose = QPushButton(Strings.disconnect)
        self.btnClose.setDisabled(True)
        self.btnExit = QPushButton(Strings.exitLC)
        self.combo = QComboBox()

        self.textConnected = QLabel(Strings.portConnected)
        self.textConnected.setAlignment(Qt.AlignCenter)
        self.textConnected.setFont(QFont("Times", 8, QFont.Bold))

        self.layout = QVBoxLayout(self)

        self.layout.addWidget(self.progressBar)

        self.resize(300, 200)
        self.centerWindowOnScreen()
        self.setWindowTitle(Strings.sprV2)

    def centerWindowOnScreen(self):
        windowGeometry = self.frameGeometry()
        desktopWidget = QDesktopWidget().availableGeometry().center()
        windowGeometry.moveCenter(desktopWidget)
        self.move(windowGeometry.topLeft())

    def mainWindow(self, connected, byConnectButton):
        if byConnectButton == 0:
            self.layout.removeWidget(self.progressBar)
            self.progressBar.deleteLater()

        elif byConnectButton == 1:
            self.layout.removeWidget(self.btnOpen)
            self.btnOpen.deleteLater()
            self.layout.removeWidget(self.btnClose)
            self.btnClose.deleteLater()
            self.layout.removeWidget(self.btnExit)
            self.btnExit.deleteLater()
            self.layout.removeWidget(self.combo)
            self.combo.deleteLater()

        if connected:
            self.textConnected.setText(Strings.portConnected)
            self.textConnected.setStyleSheet('color: green')
            self.layout.addWidget(self.textConnected)

        else:
            self.textConnected.setText(Strings.messagePortNotFound)
            self.textConnected.setStyleSheet('color: red')
            self.layout.addWidget(self.textConnected)
            self.layout.addWidget(self.btnOpen)
            self.layout.addWidget(self.btnClose)
            self.layout.addWidget(self.btnExit)
            self.layout.addWidget(self.combo)

    def setPorts(self, ports):
        self.combo.addItem(Strings.portsUC)

        for port in ports:
            self.combo.addItem(port['port'])

    def setPortFound(self, numberOfIndex):
        self.btnClose.setDisabled(False)
        self.btnOpen.setDisabled(True)
        self.combo.setCurrentIndex(numberOfIndex)
        self.combo.setDisabled(True)

    def setMessageCritical(self, typeMessage, message):
        QMessageBox.critical(self, typeMessage, message)

    def setMessageExistsFile(self):
        loadFile = QMessageBox.question(self, Strings.question,
                                        Strings.messageLoadConfigurationFile,
                                        QMessageBox.Yes | QMessageBox.No,
                                        QMessageBox.No)
        if loadFile == QMessageBox.Yes:
            fileName, _ = QFileDialog.getOpenFileName(
                self, Strings.openFile,
                'C:/Users/' + getpass.getuser() + '/Documents/', '*.cfg')

            if fileName:
                return [True, fileName]

            else:
                return [False, None]

        else:
            return [False, Strings.no]

    def setMessageExit(self):
        exitApp = QMessageBox.question(self, Strings.question,
                                       Strings.messageExit,
                                       QMessageBox.Yes | QMessageBox.No,
                                       QMessageBox.No)

        if exitApp == QMessageBox.Yes:
            return True

        else:
            return False
Beispiel #4
0
 def morph_from(cls, cmbx: QComboBox):
     ins = cls(cmbx.parent())
     ins.setSizePolicy(cmbx.sizePolicy())
     ins.setObjectName(cmbx.objectName())
     cmbx.deleteLater()
     return ins
Beispiel #5
0
class MacroLine(QObject):

    changed = pyqtSignal()

    types = ["Text", "Down", "Up", "Tap"]
    type_to_cls = [ActionTextUI, ActionDownUI, ActionUpUI, ActionTapUI]

    def __init__(self, parent, action):
        super().__init__()

        self.parent = parent
        self.container = parent.container

        if self.parent.parent.keyboard.vial_protocol >= 2:
            self.types = self.types[:] + ["Delay (ms)"]
            self.type_to_cls = self.type_to_cls[:] + [ActionDelayUI]

        self.arrows = QHBoxLayout()
        self.btn_up = QToolButton()
        self.btn_up.setText("▲")
        self.btn_up.setToolButtonStyle(Qt.ToolButtonTextOnly)
        self.btn_up.clicked.connect(self.on_move_up)
        self.btn_down = QToolButton()
        self.btn_down.setText("▼")
        self.btn_down.clicked.connect(self.on_move_down)
        self.btn_down.setToolButtonStyle(Qt.ToolButtonTextOnly)

        self.arrows.addWidget(self.btn_up)
        self.arrows.addWidget(self.btn_down)
        self.arrows.setSpacing(0)

        self.select_type = QComboBox()
        self.select_type.addItems(self.types)
        self.select_type.setCurrentIndex(self.type_to_cls.index(type(action)))
        self.select_type.currentIndexChanged.connect(self.on_change_type)

        self.action = action
        self.action.changed.connect(self.on_change)
        self.row = -1

        self.btn_remove = QToolButton()
        self.btn_remove.setText("×")
        self.btn_remove.setToolButtonStyle(Qt.ToolButtonTextOnly)
        self.btn_remove.clicked.connect(self.on_remove_clicked)

    def insert(self, row):
        self.row = row
        self.container.addLayout(self.arrows, row, 0)
        self.container.addWidget(self.select_type, row, 1)
        self.container.addWidget(self.btn_remove, row, 3)
        self.action.insert(row)

    def remove(self):
        self.container.removeItem(self.arrows)
        self.container.removeWidget(self.select_type)
        self.container.removeWidget(self.btn_remove)
        self.action.remove()

    def delete(self):
        self.action.delete()
        self.btn_remove.deleteLater()
        self.select_type.deleteLater()
        self.arrows.deleteLater()
        self.btn_up.deleteLater()
        self.btn_down.deleteLater()

    def on_change_type(self):
        self.action.remove()
        self.action.delete()
        self.action = self.type_to_cls[self.select_type.currentIndex()](
            self.container)
        self.action.changed.connect(self.on_change)
        self.action.insert(self.row)
        self.changed.emit()

    def on_remove_clicked(self):
        self.parent.on_remove(self)

    def on_move_up(self):
        self.parent.on_move(self, -1)

    def on_move_down(self):
        self.parent.on_move(self, 1)

    def on_change(self):
        self.changed.emit()
class Window(QDialog):

    def __init__(self):

        super().__init__()
        self.setWindowTitle("Simple English Dictionary")
        self.setWindowIcon(QIcon("dict.png"))
        self.setGeometry(350,150,550,350)
        self.setStyleSheet("background-color:#f2f2f2")

        self.ui_window()

        self.show()

    def ui_window(self):

        # completer
        keys = data.keys()
        comp = QCompleter(keys)

        # label
        word_count = QLabel(f"There is {len(keys)} word!")
        label = QLabel("Enter The Word:")
        label.setFont(QFont("Arial",15))
        self.label2 = QLabel()
        self.label2.setFont(QFont("Arial",13))
        self.label2.setStyleSheet("color:#E84682")

        # line erea
        self.line_edit = QLineEdit()
        self.line_edit.setFont(QFont("Arial",13))
        self.line_edit.returnPressed.connect(self.translate_word)
        self.line_edit.setCompleter(comp)

        # text erea
        self.text_erea = QTextEdit()
        self.text_erea.setFont(QFont("Arial",13))

        # buttons
        translate = QPushButton("Translate")
        translate.setFont(QFont("Arial",13))
        translate.setStyleSheet("background-color:#27FF4F")
        translate.clicked.connect(self.translate_word)

        exit = QPushButton("Exit")
        exit.setFont(QFont("Arial",13))
        exit.setStyleSheet("background-color:#FF0000")
        exit.clicked.connect(sys.exit)

        hbox = QHBoxLayout()
        self.hbox2 = QHBoxLayout()
        vbox = QVBoxLayout()

        hbox.addWidget(label)
        hbox.addWidget(self.line_edit)
        hbox.addWidget(translate)
        vbox.addWidget(word_count)
        vbox.addLayout(hbox)
        vbox.addLayout(self.hbox2)
        vbox.addWidget(self.text_erea)
        vbox.addWidget(exit)

        self.setLayout(vbox)

    def translate_word(self):
        if self.line_edit.text():
            try:
                self.cbox.deleteLater()
            except:
                pass
            try:
                self.set.deleteLater()
            except:
                pass
            self.label2.clear()
            self.text_erea.clear()
            word = self.line_edit.text()
            match = str()
            try:
                for d in data[word]:
                    match += f"{d}\n"+"-"*80+"\n"
                self.label2.setText(word)
                self.text_erea.setText(match)
            except KeyError:
                matches = get_close_matches(word, data.keys())
                self.cbox = QComboBox()
                self.cbox.setGeometry(QRect(40, 40, 491, 31))
                self.cbox.setFont(QFont("Arial",12))
                self.cbox.setObjectName("ComboBox")
                self.set = QPushButton("Apply")
                self.set.setFont(QFont("Arial",11))
                self.set.setStyleSheet("background-color:#00FFFF")
                self.set.clicked.connect(self.set_word)
                if matches:
                    self.label2.setText(f"Did you mean this")
                    for m in matches:
                        self.cbox.addItem(m)
                    self.hbox2.addWidget(self.label2)
                    self.hbox2.addWidget(self.cbox)
                    self.hbox2.addWidget(self.set)
                else:
                    QMessageBox.about(self, "Translate", "Sorry, This word doesn't exist!")

            self.line_edit.clear()

    def set_word(self):

        word = self.cbox.currentText()
        match = str()
        for d in data[word]:
            match += f"{d}\n"+"-"*80+"\n"
        self.label2.setText(word)
        self.text_erea.setText(match)

        self.line_edit.clear()
        self.cbox.deleteLater()
        self.set.deleteLater()
Beispiel #7
0
class Main(QWidget):
    def __init__(self, parent=None):
        super(Main, self).__init__(parent)

        self.funkcje = [
            Polynomial(1, 0, -4, 3, 0),
            Polynomial(2, 0),
            Polynomial(4, 1, -1),
            Polynomial(3, 0, -5, 2, 7),
            Polynomial(-42),
            Polynomial(1, 0, -1, -2),
            Polynomial(1, -1, -1)
        ]

        self.cb = QComboBox()
        for i in self.funkcje:
            self.cb.addItem(str(i))

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(-100, 100)
        self.sliderValue = QLabel('0')
        self.slider.valueChanged.connect(self.updateLabel)
        self.sliderValue.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)

        self.etap = 0
        self.metoda = "brak"
        self.stop = "brak"
        self.funkcja = "brak"
        self.poczatek = 0
        self.koniec = 0
        self.wybor = "Metoda bisekcji"
        self.iteracje = 0
        self.dokladnosc = 0.0

        self.layout = QVBoxLayout()

        self.label = QLabel("Wybierz metodę")
        self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.layout.addWidget(self.label)

        self.b1 = QRadioButton("Metoda bisekcji")
        self.b1.setChecked(True)
        self.b1.toggled.connect(lambda: self.radioButtonZmiana(self.b1))
        self.layout.addWidget(self.b1)

        self.b2 = QRadioButton("Metoda złotego podziału")
        self.b2.toggled.connect(lambda: self.radioButtonZmiana(self.b2))

        self.layout.addWidget(self.b2)
        self.setLayout(self.layout)
        self.setWindowTitle("Wybór metody")

        self.next = QPushButton('OK')
        self.next.clicked.connect(self.zmianaEtapu)
        self.layout.addWidget(self.next)

    def radioButtonZmiana(self, b):

        if b.isChecked():
            self.wybor = b.text()

    def zmianaEtapu(self):

        if self.etap == 0:
            self.etap += 1
            self.metoda = self.wybor
            self.label.setText("Wybierz warunek stopu")
            self.b1.setText("Ilość iteracji")
            self.b1.setChecked(True)
            self.b2.setText("Dokładność")
            self.wybor = "Ilość iteracji"

        elif self.etap == 1:
            self.etap += 1
            self.stop = self.wybor
            self.label.setText("Wybierz funkcję testową")
            self.layout.removeWidget(self.b1)
            self.layout.removeWidget(self.b2)
            self.layout.removeWidget(self.next)
            self.b1.deleteLater()
            self.b2.deleteLater()
            self.layout.addWidget(self.cb)
            self.layout.addWidget(self.next)

        elif self.etap == 2:
            self.etap += 1
            self.funkcja = self.funkcje[self.cb.currentIndex()]
            self.label.setText("Wybierz początek przedziału")
            self.layout.removeWidget(self.cb)
            self.layout.removeWidget(self.next)
            self.cb.deleteLater()
            self.layout.addWidget(self.slider)
            self.layout.addWidget(self.sliderValue)
            self.layout.addWidget(self.next)
        elif self.etap == 3:
            self.etap += 1
            self.poczatek = self.slider.value()
            self.label.setText("Wybierz koniec przedziału")
            self.slider.setRange(self.poczatek + 1, self.poczatek + 100)

        elif self.etap == 4:
            self.etap += 1
            self.koniec = self.slider.value()
            if self.stop == "Ilość iteracji":
                self.slider.setRange(1, 50)
                self.label.setText("Wybierz ilość iteracji")
            else:
                self.label.setText("Wybierz dokładność")
                self.slider.setRange(0, 100)
                self.slider.setValue(50)
                self.sliderValue.setText('0.5')
                self.slider.valueChanged.connect(self.updateLabelFloat)

        elif self.etap == 5:

            temp = 0

            while not self.unimodalnosc():
                print("nope")
                self.poczatek -= 5
                self.poczatek -= 5
                temp += 1

                if temp == 50:
                    print("NO{E")
                    exit(-1)

            if self.stop == "Ilość iteracji":
                self.iteracje = self.slider.value()
            else:
                self.dokladnosc = self.slider.value() / 100.0

            if self.metoda == "Metoda bisekcji":
                self.bisekcja()
                self.next.setDisabled(True)
            else:
                self.zlotyPodzial()
                self.next.setDisabled(True)

    def updateLabel(self, value):
        self.sliderValue.setText(str(value))

    def updateLabelFloat(self, value):
        self.sliderValue.setText(str(value / 100.0))

    def samesign(self, a, b):
        return a * b > 0

    def unimodalnosc(self):

        krok = self.poczatek

        while krok + 2 <= self.koniec:
            y1 = self.funkcja(krok)
            y2 = self.funkcja(krok + 1)
            y3 = self.funkcja(krok + 2)
            if (y1 >= y2) and (y2 <= y3):
                return True
            else:
                krok += 1

        return False

    def bisekcja(self):
        print(str(self.funkcja))
        low = self.poczatek
        high = self.koniec
        yL = self.funkcja(low)
        przedzialy = []
        if self.stop == "Ilość iteracji":
            for i in range(self.iteracje):

                print("Przedział ( " + str(low) + " ; " + str(high) + " )")
                przedzialy.append(low)
                przedzialy.append(high)
                midpoint = (low + high) / 2.0
                yM = self.funkcja(midpoint)

                if yL * yM < 0:
                    high = midpoint
                else:
                    low = midpoint
                    yL = yM

        else:
            while abs(float(low) - float(high)) < self.dokladnosc:
                print("Przedział ( " + str(low) + " ; " + str(high) + " )")

                midpoint = (low + high) / 2.0
                yM = self.funkcja(midpoint)

                if yL * yM < 0:
                    high = midpoint
                else:
                    low = midpoint
                    yL = yM

        X = list(range(self.poczatek, self.koniec))
        Y = []
        for i in X:
            Y.append(self.funkcja(i))

        plt.figure(200)
        plt.plot(X, Y)
        plt.plot(midpoint, self.funkcja(midpoint), 'ro')
        plt.xlim([self.poczatek, self.koniec])
        plt.show()

        plt.figure(300)
        temp = 0
        for i in range(0, len(przedzialy), 2):
            x = [przedzialy[i], przedzialy[i + 1]]
            y = [temp, temp]
            plt.plot(x, y, label="Przedział " + str(temp))
            temp += 1
        plt.show()
        print(midpoint)
        return midpoint

    def zlotyPodzial(self):
        epsilon = self.dokladnosc

        phi = (1 + 5**0.5) / 2  #golden ratio constant
        a = self.poczatek
        b = self.koniec
        c = b - (b - a) / phi
        d = a + (b - a) / phi
        while abs(b - a) > epsilon:
            if self.funkcja(c) < self.funkcja(d):
                b = d
            else:
                a = c
            c = b - (b - a) / phi
            d = a + (b - a) / phi
        x_opt = (b + a) / 2

        X = list(range(self.poczatek, self.koniec))
        Y = []
        for i in X:
            Y.append(self.funkcja(i))
        plt.plot(X, Y)
        plt.plot(x_opt, self.funkcja(x_opt), 'ro')
        plt.xlim([self.poczatek, self.koniec])
        plt.show()
        print(x_opt)
        return x_opt