Пример #1
0
class MainWindow:
    def __init__(self):
        self.main_win = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_win)
        #self.setupUi(self)

        self.ui.stackedWidget.setCurrentWidget(self.ui.tasksPage)

        self.ui.tasksButton.clicked.connect(self.showTasksPage)
        self.ui.profilesButton.clicked.connect(self.showProfilesPage)
        self.ui.accountsButton.clicked.connect(self.showAccountsPage)
        self.ui.settingsButton.clicked.connect(self.showSettingsPage)

    def show(self):
        self.main_win.show()

    def showTasksPage(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.tasksPage)

    def showProfilesPage(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.profilesPage)

    def showAccountsPage(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.accountsPage)

    def showSettingsPage(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.settingsPage)
Пример #2
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # CREATE TWO INSTANCES OF DIOD SETTINGS
        self.diod16w = DiodSettings("980 nm", 16.0)
        self.diod40w = DiodSettings("1470 nm", 40.0)
        # ADD THEM TO THE SETTINGS LAYOUT
        self.ui.SettingsLayout.addWidget(self.diod16w)
        self.ui.SettingsLayout.addWidget(self.diod40w)
        # SET MENU BUTTONS SWITCH BETWEEN SETTINGS CALIBRATION AND DIAGNOSTICS
        self.ui.btn_page_1.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.Diagnostics
                                                           ))
        self.ui.btn_page_2.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.Settings))
        self.ui.btn_page_3.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.Calibration
                                                           ))

        # SET ENABLE/DISABLE OPTIONS FOR BOTH 16 AND 40 W DIOD
        # self.ui.EnableButton.clicked.connect(lambda: print("Enable Button"))

        # SET AIMING BEAM CONTROL
        self.ui.IncrementBeamButton.clicked.connect(self.incrementAimingBeam)
        self.ui.DecrementBeamButton.clicked.connect(self.decrementAimingBeam)
Пример #3
0
    def __init__(self, dialog):
        Ui_MainWindow.__init__(self)

        self.setupUi(dialog)

        # Article scroll area init
        self.articleList = []
        self.articleGBox, self.articleGLayout = self.InitArticleScrollarea()

        # Sources scroll area init
        self.sourceList = []
        self.sourceGBox, self.sourceGLayout = self.InitSourceScrollarea()
        self.currentSourceId = ""

        # Following scroll area init
        self.followingList = []
        self.followingGBox, self.followingGLayout = self.InitFollowScrollarea()
        self.LoadFollowed()

        # Get the all avaliable sources
        self.InsertSources(jsonRes=self.LoadSources(
            sourcesUrl="https://newsapi.org/v1/sources?language=en").json())

        # Get apikey

        self.apiKey = self.GetApiKey('api.txt')

        # Event handler init
        self.MainPage()
        self.InputManager()
Пример #4
0
    def __init__(self, dialog):
        Ui_MainWindow.__init__(self)
        # try:
        #     requests.get('https://www.google.com')
        #     print('google')
        # except:
        #     self.DisplayMessagebox(title='Cant Connect',text='please check your internet connection')
        #     exit()
        self.setupUi(dialog)

        # Article scroll area init
        self.articleList = []
        self.articleGBox, self.articleGLayout = self.InitArticleScrollarea()

        # Sources scroll area init
        self.sourceList = []
        self.sourceGBox, self.sourceGLayout = self.InitSourceScrollarea()
        self.currentSourceId = ""

        # Following scroll area init
        self.followingList = []
        self.followingGBox, self.followingGLayout = self.InitFollowScrollarea()
        self.LoadFollowed()

        # Get the all avaliable sources
        self.InsertSources(jsonRes=self.LoadSources(
            sourcesUrl="https://newsapi.org/v1/sources?language=en").json())

        # Get apikey

        self.apiKey = self.GetApiKey('api.txt')

        # Event handler init
        self.MainPage()
        self.InputManager()
Пример #5
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.generate)
        self.ui.actionOpenFIle.triggered.connect(self.openFileNameDialog)

        self.task = Task()
        self.task.start_thread()
Пример #6
0
    def __init__(self):

        super(UI, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.audioMenu.clicked.connect(self.run_audio)
        self.ui.citraMenu.clicked.connect(self.run_citra)
        self.ui.videoMenu.clicked.connect(self.run_video)
Пример #7
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.btnLoadDb.clicked.connect(self.do_LoadDb)
        self.ui.btnQuery.clicked.connect(self.do_Query)
        self.ui.btnQueryModify.clicked.connect(self.do_QueryModify)
        self.ui.btnQueryDelete.clicked.connect(self.do_QueryDelete)

        self.ui.btnSelectFile.clicked.connect(self.do_Select)
Пример #8
0
class MainWindow(QMainWindow):
    def __init__(self, op):
        super(MainWindow, self).__init__()
        #uic.loadUi("openithm.ui", self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.op = op

        self.ui.tapply.clicked.connect(self.touchboardApply)
        self.ui.irapply.clicked.connect(self.irApply)
        self.ui.tcalibrate.clicked.connect(self.op.calibrateTouchboard)
        self.ui.ircalibrate.clicked.connect(self.op.calibrateIR)
        self.ui.pause.clicked.connect(self.op.pause)
        self.ui.resume.clicked.connect(self.op.resume)
        self.show()

    def updateValues(self):
        self.ui.thres_current.setText(
            QApplication.translate(
                "MainWindow",
                "Current: " + str(self.op.getTouchboard('threshold')), None,
                -1))
        self.ui.dead_current.setText(
            QApplication.translate(
                "MainWindow",
                "Current: " + str(self.op.getTouchboard('deadzone')), None,
                -1))
        self.ui.alpha_current.setText(
            QApplication.translate(
                "MainWindow",
                "Current: " + str(self.op.getTouchboard('alpha')), None, -1))

        self.ui.irdead_current.setText(
            QApplication.translate(
                "MainWindow", "Current: " + str(self.op.getIR('deadzone')),
                None, -1))
        self.ui.iralpha_current.setText(
            QApplication.translate("MainWindow",
                                   "Current: " + str(self.op.getIR('alpha')),
                                   None, -1))

        self.ui.status.setText(
            QApplication.translate("MainWindow",
                                   "Status: " + self.op.getState(), None, -1))

    def touchboardApply(self):
        self.op.setTouchboard('threshold', self.ui.thres_val.value())
        self.op.setTouchboard('deadzone', self.ui.dead_val.value())
        self.op.setTouchboard('alpha', self.ui.alpha_val.value())

    def irApply(self):
        self.op.setIR('deadzone', self.ui.irdead_val.value())
        self.op.setIR('alpha', self.ui.iralpha_val.value())
Пример #9
0
    def __init__(self, op):
        super(MainWindow, self).__init__()
        #uic.loadUi("openithm.ui", self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.op = op

        self.ui.tapply.clicked.connect(self.touchboardApply)
        self.ui.irapply.clicked.connect(self.irApply)
        self.ui.tcalibrate.clicked.connect(self.op.calibrateTouchboard)
        self.ui.ircalibrate.clicked.connect(self.op.calibrateIR)
        self.ui.pause.clicked.connect(self.op.pause)
        self.ui.resume.clicked.connect(self.op.resume)
        self.show()
Пример #10
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.generate)
        self.ui.actionOpenFIle.triggered.connect(self.openFileNameDialog)

        self.task = Task()
        self.task.start_thread()

    def keyPressEvent(self, event):
        key = event.key()

        if key == Qt.Key_Escape:
            QCoreApplication.quit()
        elif key == Qt.Key_Delete:
            self.ui.listWidget.takeItem(self.ui.listWidget.currentRow())

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileNames, _ = QFileDialog.getOpenFileNames(self,"Abrir Excel", "","Excel (*.xlsx)", options=options)
        if fileNames:
            #self.ui.listWidget.addItems([ntpath.basename(i) for i in fileNames])
            for i in fileNames:
                self.ui.listWidget.addItem(Qfile(i))


    def generate(self):

        if self.task.status and not self.task.task:
            file_paths = []
            for i in range(self.ui.listWidget.count()):
                file_paths.append(self.ui.listWidget.item(i).path)

            self.task.start_task(file_paths)

        if not self.task.status:
            self.task = Task()
            self.task.start_thread()
Пример #11
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.index = None
        print(self.index)
        self.image_names = []

        # Populating combobox values.
        self.ui.elitismComboBox.addItem('Y')
        self.ui.elitismComboBox.addItem('N')
        self.ui.crossoverTypeComboBox.addItem('SP')
        self.ui.crossoverTypeComboBox.addItem('TP')
        self.ui.parentSelectComboBox.addItem('RS')
        self.ui.parentSelectComboBox.addItem('RWS')

        self.ga_thread = None
        self.a_star_thread = None

        self.ui.autoTrace.clicked.connect(self.run_auto_trace)
        self.ui.stopAutotrace.clicked.connect(self.stop_auto_trace)

        self.ui.nextButton.clicked.connect(self.show_next_image)
        self.ui.prevButton.clicked.connect(self.show_prev_image)

        self.ui.runAStarButton.clicked.connect(self.run_a_star)
        self.ui.stopastarButton.clicked.connect(self.stop_a_star_thread)

        self.ui.runGaButton.clicked.connect(self.run_genetic_algorithm)
        self.ui.stopgaButton.clicked.connect(self.stop_ga_thread)

        self.ui.resetButton.clicked.connect(self.reset)

        self.ui.nextButton.setDisabled(True)
        self.ui.prevButton.setDisabled(True)
        self.ui.autoTrace.setDisabled(True)
        self.ui.stopAutotrace.setDisabled(True)

        os.makedirs(folder, exist_ok=True
                    )  # Creating folder to store images if it does not exist.
Пример #12
0
class UI(QtWidgets.QMainWindow):

    to_audio = QtCore.pyqtSignal(str)
    to_video = QtCore.pyqtSignal(str)
    to_citra = QtCore.pyqtSignal(str)

    def __init__(self):

        super(UI, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.audioMenu.clicked.connect(self.run_audio)
        self.ui.citraMenu.clicked.connect(self.run_citra)
        self.ui.videoMenu.clicked.connect(self.run_video)

    def run_audio(self):
        self.to_audio.emit("audio")

    def run_citra(self):
        self.to_citra.emit("citra")

    def run_video(self):
        self.to_video.emit("video")
Пример #13
0
	def __init__(self, parent=None, zoom=None, lat=None, lon=None):
		QtGui.QMainWindow.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		self.points = []
		self.tracks = []

		if (zoom):
			self.ui.mapZoom.setValue(zoom)
		if (lat):
			self.ui.mapLat.setValue(lat)
		if (lon):
			self.ui.mapLon.setValue(lon)
		
		# managing upper right UI section (map initialization parameters)
		QtCore.QObject.connect(self.ui.button_rebuild, QtCore.SIGNAL("clicked()"), self.createMapButton)
		QtCore.QObject.connect(self.ui.button_center, QtCore.SIGNAL("clicked()"), self.center)
		QtCore.QObject.connect(self.ui.saveFileButton, QtCore.SIGNAL("clicked()"), self.saveToFile)
		
		# manage points list
		QtCore.QObject.connect(self.ui.button_delete_point, QtCore.SIGNAL("clicked()"), self.deleteSelectedPoint)
		QtCore.QObject.connect(self.ui.button_new_point, QtCore.SIGNAL("clicked()"), self.openNewPointWindow)
		QtCore.QObject.connect(self.ui.button_new_track, QtCore.SIGNAL("clicked()"), self.openNewTrackWindow)
		QtCore.QObject.connect(self.ui.pointsList, QtCore.SIGNAL("itemSelectionChanged()"), self.centerOnSelectedPoint)	
		QtCore.QObject.connect(self.ui.pointsList, QtCore.SIGNAL("itemClicked(QTreeWidgetItem*,int)"), self.itemChangedOnPointsList)	

		self.ui.pointsList.setColumnWidth(0, 100)
		self.ui.pointsList.setColumnWidth(1, 80)
		self.ui.pointsList.setColumnWidth(2, 80)
		self.ui.pointsList.setColumnWidth(3, 30)
		
		# manage zoom buttons
		QtCore.QObject.connect(self.ui.map_zoom_down, QtCore.SIGNAL("clicked()"), self.zoomDown)
		QtCore.QObject.connect(self.ui.map_zoom_up, QtCore.SIGNAL("clicked()"), self.zoomUp)
		
		QtCore.QObject.connect(self, QtCore.SIGNAL("centerUI()"), self.center)
		
		# triggers first map redraw (with default 
		# position and zoom, as set by UI)
		self.createMapButton()
		self.updatePointsList()
Пример #14
0
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.addCarriers()
        
        self.thread = Sender()
        
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'), self.showAbout)
        self.connect(self.ui.actionQuit, QtCore.SIGNAL('triggered()'), exit)
        self.connect(self.ui.button, QtCore.SIGNAL('clicked()'), self.toggle)
        self.connect(self.thread, QtCore.SIGNAL("finished()"), self.done)
        self.connect(self.thread, QtCore.SIGNAL("terminated()"), self.done)
        self.connect(self.thread, QtCore.SIGNAL("plusOne()"), self.plusOne)
        self.connect(self.thread, QtCore.SIGNAL("sendingError()"), self.stop)

        self.ui.server.setText('127.0.0.1:25') #set default
        self.ui.message.setPlainText('SPAM!')
        self.ui.statusBar().showMessage('Ready') #broken
Пример #15
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, preferences, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.preferences = preferences

        # initialize GUI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.lastDirectory = ''

        # load plot plugins
        self.exploratoryPlots = PlotsManager(self.ui.cboExploratoryPlots,
                                             self.ui.plotExploratoryScrollArea,
                                             'Profile scatter plot')
        self.exploratoryPlots.loadPlots(self.preferences,
                                        'plugins/exploratoryPlots/')

        self.statPlots = PlotsManager(self.ui.cboStatPlots,
                                      self.ui.plotStatScrollArea,
                                      'Extended error bar')
        self.statPlots.loadPlots(self.preferences, 'plugins/statPlots/')

        # load statistical technique plugins
        pluginManager = PluginManager(self.preferences)
        self.effectSizeDict = pluginManager.loadPlugins(
            'plugins/effectSizeFilters/')
        pluginManager.populateComboBox(self.effectSizeDict,
                                       self.ui.cboEffectSizeMeasure1,
                                       'Difference between proportions')
        pluginManager.populateComboBox(self.effectSizeDict,
                                       self.ui.cboEffectSizeMeasure2,
                                       'Ratio of proportions')

        self.statTestDict = pluginManager.loadPlugins(
            'plugins/statisticalTests/')
        pluginManager.populateComboBox(self.statTestDict, self.ui.cboStatTests,
                                       'Fisher\'s exact test')

        self.multCompDict = pluginManager.loadPlugins(
            'plugins/multipleComparisonCorrections/')
        pluginManager.populateComboBox(self.multCompDict,
                                       self.ui.cboMultCompMethod,
                                       'No correction')

        self.confIntervMethodDict = pluginManager.loadPlugins(
            'plugins/confidenceIntervalMethods/')
        pluginManager.populateComboBox(self.confIntervMethodDict,
                                       self.ui.cboConfIntervMethods,
                                       'DP: Newcombe-Wilson')

        # initialize class variables
        self.profileTree = ProfileTree()
        self.profile = Profile()
        self.statsTest = StatsTests()
        self.plotWindows = []

        # initialize tables
        self.summaryTable = GenericTable([], [], self)
        self.coverageTable = GenericTable([], [], self)
        self.powerTable = GenericTable([], [], self)

        # connect menu items signals to slots
        self.connect(self.ui.mnuFileOpenProfile, QtCore.SIGNAL('triggered()'),
                     self.loadProfile)
        self.connect(self.ui.mnuFileCreateProfile,
                     QtCore.SIGNAL('triggered()'), self.createProfile)
        self.connect(self.ui.mnuFileAppendCategoryCOG,
                     QtCore.SIGNAL('triggered()'), self.appendCategoriesCOG)
        self.connect(self.ui.mnuFileSavePlot, QtCore.SIGNAL('triggered()'),
                     self.saveImageDlg)
        self.connect(self.ui.mnuFileSaveTable, QtCore.SIGNAL('triggered()'),
                     self.saveTableDlg)
        self.connect(self.ui.mnuFileExit, QtCore.SIGNAL('triggered()'),
                     QtCore.SLOT('close()'))

        self.connect(self.ui.mnuViewSendPlotToWindow,
                     QtCore.SIGNAL('triggered()'), self.sendPlotToWindow)

        self.connect(self.ui.mnuSettingsPreferences,
                     QtCore.SIGNAL('triggered()'), self.prefrencesDlg)

        self.connect(self.ui.mnuHelpAbout, QtCore.SIGNAL('triggered()'),
                     self.openAboutDlg)

        # widget controls in sidebar
        self.connect(self.ui.btnProfileTab, QtCore.SIGNAL('clicked()'),
                     self.profileTabClicked)
        self.connect(self.ui.btnProfileArrow, QtCore.SIGNAL('clicked()'),
                     self.profileTabClicked)
        self.connect(self.ui.btnStatisticsTab, QtCore.SIGNAL('clicked()'),
                     self.statPropTabClicked)
        self.connect(self.ui.btnStatisticsArrow, QtCore.SIGNAL('clicked()'),
                     self.statPropTabClicked)
        self.connect(self.ui.btnFilteringTab, QtCore.SIGNAL('clicked()'),
                     self.filteringTabClicked)
        self.connect(self.ui.btnFilteringArrow, QtCore.SIGNAL('clicked()'),
                     self.filteringTabClicked)

        # connect profile widget signals to slots
        self.connect(self.ui.cboSample1, QtCore.SIGNAL('activated(QString)'),
                     self.hierarchicalLevelsChanged)
        self.connect(self.ui.cboSample2, QtCore.SIGNAL('activated(QString)'),
                     self.hierarchicalLevelsChanged)
        self.connect(self.ui.btnSample1Colour, QtCore.SIGNAL('clicked()'),
                     self.sample1ColourDlg)
        self.connect(self.ui.btnSample2Colour, QtCore.SIGNAL('clicked()'),
                     self.sample2ColourDlg)
        self.connect(self.ui.cboProfileLevel,
                     QtCore.SIGNAL('activated(QString)'),
                     self.profileLevelChanged)
        self.connect(self.ui.cboParentalLevel,
                     QtCore.SIGNAL('activated(QString)'),
                     self.parentLevelChanged)

        # connect statistical test widget signals to slots
        self.connect(self.ui.cboStatTests, QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.cboSignTestType,
                     QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.cboConfIntervMethods,
                     QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.cboNominalCoverage,
                     QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.btnRunTest, QtCore.SIGNAL('clicked()'),
                     self.runTest)
        self.connect(self.ui.cboMultCompMethod,
                     QtCore.SIGNAL('activated(QString)'),
                     self.multCompCorrectionChanged)
        self.connect(self.ui.btnMultCompCorrectionInfo,
                     QtCore.SIGNAL('clicked()'), self.multCompCorrectionInfo)

        # connect filtering test widget signals to slots
        self.connect(self.ui.chkSelectFeatures, QtCore.SIGNAL('toggled(bool)'),
                     self.selectFeaturesCheckbox)
        self.connect(self.ui.btnSelectFeatures, QtCore.SIGNAL('clicked()'),
                     self.selectFeaturesDlg)

        self.connect(self.ui.chkEnableSignLevelFilter,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.spinSignLevelFilter,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)

        self.connect(self.ui.cboSeqFilter, QtCore.SIGNAL('activated(QString)'),
                     self.seqFilterChanged)
        self.connect(self.ui.chkEnableSeqFilter,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.spinFilterSample1,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.spinFilterSample2,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)

        self.connect(self.ui.cboParentSeqFilter,
                     QtCore.SIGNAL('activated(QString)'),
                     self.parentSeqFilterChanged)
        self.connect(self.ui.chkEnableParentSeqFilter,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.spinParentFilterSample1,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.spinParentFilterSample2,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)

        self.connect(self.ui.radioOR, QtCore.SIGNAL('clicked()'),
                     self.filteringPropChanged)
        self.connect(self.ui.radioAND, QtCore.SIGNAL('clicked()'),
                     self.filteringPropChanged)

        self.connect(self.ui.cboEffectSizeMeasure1,
                     QtCore.SIGNAL('activated(QString)'),
                     self.changeEffectSizeMeasure)
        self.connect(self.ui.cboEffectSizeMeasure2,
                     QtCore.SIGNAL('activated(QString)'),
                     self.changeEffectSizeMeasure)
        self.connect(self.ui.spinMinEffectSize1,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.spinMinEffectSize2,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.chkEnableEffectSizeFilter1,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.chkEnableEffectSizeFilter2,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)

        self.connect(self.ui.btnApplyFilters, QtCore.SIGNAL('clicked()'),
                     self.applyFilters)

        # connect exploratory plot page widget signals to slots
        self.connect(self.ui.cboExploratoryPlots,
                     QtCore.SIGNAL('activated(QString)'),
                     self.exploratoryPlotUpdate)
        self.connect(self.ui.btnExploratoryConfigurePlot,
                     QtCore.SIGNAL('clicked()'), self.exploratoryPlotConfigure)

        # connect statistical plot page widget signals to slots
        self.connect(self.ui.cboStatPlots, QtCore.SIGNAL('activated(QString)'),
                     self.statPlotUpdate)
        self.connect(self.ui.btnStatConfigurePlot, QtCore.SIGNAL('clicked()'),
                     self.statPlotConfigure)
        self.connect(self.ui.cboHighlightHierarchyExploratory,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightHierarchyExploratoryChanged)
        self.connect(self.ui.cboHighlightFeatureExploratory,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightFeatureExploratoryChanged)
        self.connect(self.ui.cboHighlightHierarchyStats,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightHierarchyStatsChanged)
        self.connect(self.ui.cboHighlightFeatureStats,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightFeatureStatsChanged)

        # connect paired profile page widget signals to slots
        self.connect(self.ui.chkShowActiveFeatures,
                     QtCore.SIGNAL('toggled(bool)'), self.populateSummaryTable)

        # connect CI coverage page widget signals to slots
        self.connect(self.ui.btnConfIntervCoverage, QtCore.SIGNAL('clicked()'),
                     self.confIntervCoverage)

        # connect CI coverage page widget signals to slots
        self.connect(self.ui.btnPowerTest, QtCore.SIGNAL('clicked()'),
                     self.powerTest)

        # initialize dynamic GUI elements
        self.seqFilterChanged()
        self.parentSeqFilterChanged()
        self.setSample1Colour(self.preferences['Sample 1 colour'])
        self.setSample2Colour(self.preferences['Sample 2 colour'])

        # show window maximized
        self.resize(1100, 700)
        self.showMaximized()

    def appendCategoriesCOG(self):
        assignCOGsDlg = AssignCOGsDlg(self)
        assignCOGsDlg.exec_()

    def profileTabClicked(self):
        self.ui.widgetProfile.setVisible(not self.ui.widgetProfile.isVisible())
        self.updateSideBarTabIcon(self.ui.widgetProfile,
                                  self.ui.btnProfileArrow)

    def statPropTabClicked(self):
        self.ui.widgetStatisticalProp.setVisible(
            not self.ui.widgetStatisticalProp.isVisible())
        self.updateSideBarTabIcon(self.ui.widgetStatisticalProp,
                                  self.ui.btnStatisticsArrow)

    def filteringTabClicked(self):
        self.ui.widgetFilter.setVisible(not self.ui.widgetFilter.isVisible())
        self.updateSideBarTabIcon(self.ui.widgetFilter,
                                  self.ui.btnFilteringArrow)

    def updateSideBarTabIcon(self, tab, arrowButton):
        icon = QtGui.QIcon()
        if tab.isVisible():
            icon.addPixmap(QtGui.QPixmap("icons/downArrow.png"),
                           QtGui.QIcon.Normal, QtGui.QIcon.Off)
        else:
            icon.addPixmap(QtGui.QPixmap("icons/rightArrow.png"),
                           QtGui.QIcon.Normal, QtGui.QIcon.Off)
        arrowButton.setIcon(icon)

    def prefrencesDlg(self):
        preferencesDlg = PreferencesDlg(self)

        preferencesDlg.ui.spinPseudoCount.setValue(
            self.preferences['Pseudocount'])
        preferencesDlg.ui.chkTruncateFeatureNames.setChecked(
            self.preferences['Truncate feature names'])
        preferencesDlg.ui.spinFeatureNameLength.setValue(
            self.preferences['Length of truncated feature names'])

        if preferencesDlg.exec_() == QtGui.QDialog.Accepted:
            self.preferences[
                'Pseudocount'] = preferencesDlg.ui.spinPseudoCount.value()
            self.preferences[
                'Truncate feature names'] = preferencesDlg.ui.chkTruncateFeatureNames.isChecked(
                )
            self.preferences[
                'Length of truncated feature names'] = preferencesDlg.ui.spinFeatureNameLength.value(
                )

        self.exploratoryPlotUpdate()
        self.statPlotUpdate()

    def exploratoryPlotUpdate(self):
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))
        self.exploratoryPlots.update(self.profile)
        QtGui.QApplication.instance().restoreOverrideCursor()

    def exploratoryPlotConfigure(self):
        if self.profile.getNumFeatures() != 0:
            self.exploratoryPlots.configure(self.profile)
        else:
            QtGui.QMessageBox.information(
                self, 'Invalid profile',
                'A profile must be loaded before plots can be configured.',
                QtGui.QMessageBox.Warning)

    def statPlotUpdate(self):
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))
        self.statPlots.update(self.statsTest.results)
        QtGui.QApplication.instance().restoreOverrideCursor()

    def statPlotConfigure(self):
        if self.statsTest.results.profile != None:
            self.statPlots.configure(self.statsTest.results)
        else:
            QtGui.QMessageBox.information(
                self, 'Invalid profile',
                'Statistical test must be run before plots can be configured.',
                QtGui.QMessageBox.Warning)

    def sample1ColourDlg(self):
        colour = QtGui.QColorDialog.getColor(
            self.preferences['Sample 1 colour'], self, 'Colour for sample 1')

        if colour.isValid():
            self.preferences['Sample 1 colour'] = colour
            self.setSample1Colour(colour)

    def setSample1Colour(self, colour):
        colourStr = str(colour.red()) + ',' + str(colour.green()) + ',' + str(
            colour.blue())
        self.ui.btnSample1Colour.setStyleSheet('* { background-color: rgb(' +
                                               colourStr + ') }')
        self.exploratoryPlotUpdate()
        self.statPlotUpdate()

    def sample2ColourDlg(self):
        colour = QtGui.QColorDialog.getColor(
            self.preferences['Sample 2 colour'], self, 'Colour for sample 2')

        if colour.isValid():
            self.preferences['Sample 2 colour'] = colour
            self.setSample2Colour(colour)

    def setSample2Colour(self, colour):
        colourStr = str(colour.red()) + ',' + str(colour.green()) + ',' + str(
            colour.blue())
        self.ui.btnSample2Colour.setStyleSheet('* { background-color: rgb(' +
                                               colourStr + ') }')
        self.exploratoryPlotUpdate()
        self.statPlotUpdate()

    def createProfile(self):
        createProfileDlg = CreateProfileDlg(self)
        createProfileDlg.exec_()

    def loadProfile(self):
        # open file dialog
        file = QtGui.QFileDialog.getOpenFileName(
            self, 'Open profile', self.lastDirectory,
            'STAMP profile file (*.spf *.txt);;All files (*.*)')
        if file == '':
            return

        self.lastDirectory = file[0:file.lastIndexOf('/')]

        # read profiles from file
        try:
            stampIO = StampIO(self.preferences)
            self.profileTree, errMsg = stampIO.read(file)

            if errMsg != None:
                QtGui.QMessageBox.information(self, 'Error reading input file',
                                              errMsg,
                                              QtGui.QMessageBox.Warning)
                return

        except:
            QtGui.QMessageBox.information(self, 'Error reading input file',
                                          'Unknown parsing error.',
                                          QtGui.QMessageBox.Warning)
            return

        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))

        # populate sample combo boxes
        self.ui.cboSample1.clear()
        self.ui.cboSample2.clear()
        for name in self.profileTree.sampleNames:
            self.ui.cboSample1.addItem(name)
            self.ui.cboSample2.addItem(name)
        self.ui.cboSample1.setCurrentIndex(
            self.ui.cboSample1.findText(self.profileTree.sampleNames[0]))
        self.ui.cboSample2.setCurrentIndex(
            self.ui.cboSample2.findText(self.profileTree.sampleNames[1]))

        # populate hierarchy combo boxes
        self.ui.cboParentalLevel.clear()
        self.ui.cboParentalLevel.addItem('Entire sample')
        for header in self.profileTree.hierarchyHeadings[0:-1]:
            self.ui.cboParentalLevel.addItem(header)
        self.ui.cboParentalLevel.setCurrentIndex(0)

        self.ui.cboProfileLevel.clear()
        for header in self.profileTree.hierarchyHeadings:
            self.ui.cboProfileLevel.addItem(header)
        self.ui.cboProfileLevel.setCurrentIndex(0)

        # indicate the hierarchical level of interest have changed
        self.hierarchicalLevelsChanged()

        QtGui.QApplication.instance().restoreOverrideCursor()

    def parentLevelChanged(self):
        parentDepth = self.profileTree.getHierarchicalLevelDepth(
            str(self.ui.cboParentalLevel.currentText()))
        profileDepth = self.profileTree.getHierarchicalLevelDepth(
            str(self.ui.cboProfileLevel.currentText()))

        if parentDepth >= profileDepth:
            QtGui.QMessageBox.information(
                self, 'Invalid profile',
                'The parent level must be higher in the hierarchy than the profile level.',
                QtGui.QMessageBox.Warning)
            self.ui.cboParentalLevel.setCurrentIndex(0)
            return

        self.hierarchicalLevelsChanged()

    def profileLevelChanged(self):
        parentDepth = self.profileTree.getHierarchicalLevelDepth(
            str(self.ui.cboParentalLevel.currentText()))
        profileDepth = self.profileTree.getHierarchicalLevelDepth(
            str(self.ui.cboProfileLevel.currentText()))

        if profileDepth <= parentDepth:
            QtGui.QMessageBox.information(
                self, 'Invalid profile',
                'The profile level must be deeper in the hierarchy than the parent level.',
                QtGui.QMessageBox.Warning)
            self.ui.cboProfileLevel.setCurrentIndex(
                len(self.profileTree.hierarchyHeadings) - 1)
            return

        self.hierarchicalLevelsChanged()

    def hierarchicalLevelsChanged(self):
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))

        # indicate that profile information has changed
        refreshIcon = QtGui.QIcon()
        refreshIcon.addPixmap(QtGui.QPixmap("icons/refresh.png"),
                              QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.btnRunTest.setIcon(refreshIcon)

        # create new profile
        sampleName1 = str(self.ui.cboSample1.currentText())
        sampleName2 = str(self.ui.cboSample2.currentText())

        parentHeading = str(self.ui.cboParentalLevel.currentText())
        profileHeading = str(self.ui.cboProfileLevel.currentText())

        self.profile = self.profileTree.createProfile(sampleName1, sampleName2,
                                                      parentHeading,
                                                      profileHeading)

        # update GUI to reflect new profile
        self.ui.txtTotalSeqs1.setText(
            str(self.profileTree.numSequencesInSample(sampleName1)))
        self.ui.txtTotalSeqs2.setText(
            str(self.profileTree.numSequencesInSample(sampleName2)))

        self.ui.txtNumParentCategories.setText(
            str(self.profile.getNumParentCategories()))
        self.ui.txtNumFeatures.setText(str(self.profile.getNumFeatures()))

        self.ui.cboHighlightHierarchyStats.setCurrentIndex(0)
        self.ui.cboHighlightHierarchyExploratory.setCurrentIndex(0)

        # populate highlight hierarchy combo box
        profileIndex = self.profileTree.hierarchyHeadings.index(profileHeading)
        self.ui.cboHighlightHierarchyStats.clear()
        self.ui.cboHighlightHierarchyExploratory.clear()
        self.ui.cboHighlightHierarchyStats.addItem('None')
        self.ui.cboHighlightHierarchyExploratory.addItem('None')
        for header in self.profileTree.hierarchyHeadings[0:profileIndex + 1]:
            self.ui.cboHighlightHierarchyStats.addItem(header)
            self.ui.cboHighlightHierarchyExploratory.addItem(header)
        self.ui.cboHighlightHierarchyStats.setCurrentIndex(0)
        self.ui.cboHighlightHierarchyExploratory.setCurrentIndex(0)

        self.ui.cboHighlightFeatureStats.clear()
        self.ui.cboHighlightFeatureExploratory.clear()

        # indicate that any previously calculated results, plots, or tables are now invalid
        self.exploratoryPlots.reset(self.preferences)
        self.statPlots.reset(self.preferences)

        selectedFeatures = self.statsTest.results.getSelectedFeatures()
        self.statsTest = StatsTests()
        self.statsTest.results.setSelectedFeatures(selectedFeatures)

        self.statPlotUpdate()
        self.updateFilterInfo()
        self.populateSummaryTable()

        self.exploratoryPlotUpdate()

        QtGui.QApplication.instance().restoreOverrideCursor()

    def runTest(self):
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))

        # indicate data is up-to-date
        noIcon = QtGui.QIcon()
        self.ui.btnRunTest.setIcon(noIcon)

        # show progress of test
        progress = QtGui.QProgressDialog("Running statistical test...",
                                         QtCore.QString(), 0,
                                         len(self.profile.getFeatures()), self)
        progress.setWindowTitle('Progress')
        progress.setWindowModality(QtCore.Qt.WindowModal)

        # run significance test
        test = self.statTestDict[str(self.ui.cboStatTests.currentText())]
        testType = str(self.ui.cboSignTestType.currentText())
        confIntervMethod = self.confIntervMethodDict[str(
            self.ui.cboConfIntervMethods.currentText())]
        coverage = float(self.ui.cboNominalCoverage.currentText())
        self.statsTest.run(test, testType, confIntervMethod, coverage,
                           self.profile, progress)

        # apply multiple test correction
        multCompClass = self.multCompDict[str(
            self.ui.cboMultCompMethod.currentText())]
        self.statsTest.results.performMultCompCorrection(multCompClass)

        # apply filters
        self.applyFilters()

        QtGui.QApplication.instance().restoreOverrideCursor()

    def statTestPropChanged(self):
        refreshIcon = QtGui.QIcon()
        refreshIcon.addPixmap(QtGui.QPixmap("icons/refresh.png"),
                              QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.btnRunTest.setIcon(refreshIcon)

    def multCompCorrectionChanged(self):
        multCompClass = self.multCompDict[str(
            self.ui.cboMultCompMethod.currentText())]
        if multCompClass.method == 'False discovery rate':
            self.ui.lblSignLevelFilter.setText('q-value filter (>):')
        else:
            self.ui.lblSignLevelFilter.setText('p-value filter (>):')
        self.statTestPropChanged()

    def multCompCorrectionInfo(self):
        if self.statsTest.results.multCompCorrection != None:
            multCompDlg = MultCompCorrectionInfoDlg(
                self,
                self.statsTest.results.multCompCorrection.additionalInfo())
            multCompDlg.exec_()
        else:
            QtGui.QMessageBox.information(self, 'Run test',
                                          'Run hypothesis test first.',
                                          QtGui.QMessageBox.Ok)

    def seqFilterChanged(self):
        if self.ui.cboSeqFilter.currentText() == 'maximum':
            self.ui.lblSeqFilterSample1.setText('Maximum (<):')

        elif self.ui.cboSeqFilter.currentText() == 'minimum':
            self.ui.lblSeqFilterSample1.setText('Minimum (<):')

        elif self.ui.cboSeqFilter.currentText() == 'independent':
            self.ui.lblSeqFilterSample1.setText('Sample 1 (<):')

        self.filteringPropChanged()

    def parentSeqFilterChanged(self):
        if self.ui.cboParentSeqFilter.currentText() == 'maximum':
            self.ui.lblParentSeqFilterSample1.setText('Maximum (<):')

        elif self.ui.cboParentSeqFilter.currentText() == 'minimum':
            self.ui.lblParentSeqFilterSample1.setText('Minimum (<):')

        elif self.ui.cboParentSeqFilter.currentText() == 'independent':
            self.ui.lblParentSeqFilterSample1.setText('Sample 1 (<):')

        self.filteringPropChanged()

    def changeEffectSizeMeasure(self):
        self.filteringPropChanged()

    def filteringPropChanged(self):
        # indicate that profile information has changed
        refreshIcon = QtGui.QIcon()
        refreshIcon.addPixmap(QtGui.QPixmap("icons/refresh.png"),
                              QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.btnApplyFilters.setIcon(refreshIcon)

        self.ui.btnSelectFeatures.setEnabled(
            self.ui.chkSelectFeatures.isChecked())

        self.ui.spinSignLevelFilter.setEnabled(
            self.ui.chkEnableSignLevelFilter.isChecked())

        self.ui.cboSeqFilter.setEnabled(self.ui.chkEnableSeqFilter.isChecked())
        self.ui.spinFilterSample1.setEnabled(
            self.ui.chkEnableSeqFilter.isChecked())
        self.ui.spinFilterSample2.setEnabled(
            self.ui.chkEnableSeqFilter.isChecked()
            and self.ui.cboSeqFilter.currentText() == 'independent')
        self.ui.lblSeqFilterSample2.setEnabled(
            self.ui.cboSeqFilter.currentText() == 'independent')

        self.ui.cboParentSeqFilter.setEnabled(
            self.ui.chkEnableParentSeqFilter.isChecked())
        self.ui.spinParentFilterSample1.setEnabled(
            self.ui.chkEnableParentSeqFilter.isChecked())
        self.ui.spinParentFilterSample2.setEnabled(
            self.ui.chkEnableParentSeqFilter.isChecked()
            and self.ui.cboParentSeqFilter.currentText() == 'independent')
        self.ui.lblParentSeqFilterSample2.setEnabled(
            self.ui.cboParentSeqFilter.currentText() == 'independent')

        self.ui.cboEffectSizeMeasure1.setEnabled(
            self.ui.chkEnableEffectSizeFilter1.isChecked())
        self.ui.spinMinEffectSize1.setEnabled(
            self.ui.chkEnableEffectSizeFilter1.isChecked())

        self.ui.cboEffectSizeMeasure2.setEnabled(
            self.ui.chkEnableEffectSizeFilter2.isChecked())
        self.ui.spinMinEffectSize2.setEnabled(
            self.ui.chkEnableEffectSizeFilter2.isChecked())

    def selectFeaturesCheckbox(self):
        self.filteringPropChanged()

    def selectFeaturesDlg(self):
        selectFeatureDialog = SelectFeaturesDlg(self.statsTest.results, self)

        if selectFeatureDialog.exec_() == QtGui.QDialog.Accepted:
            selectedFeatures = selectFeatureDialog.getSelectedFeatures()
            self.statsTest.results.setSelectedFeatures(selectedFeatures)
            self.filteringPropChanged()

    def applyFilters(self):
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))
        icon = QtGui.QIcon()
        self.ui.btnApplyFilters.setIcon(icon)

        if not self.ui.chkSelectFeatures.isChecked():
            self.statsTest.results.selectAllFeautres()

        # perform filtering
        signLevelFilter = self.ui.spinSignLevelFilter.value()
        if not self.ui.chkEnableSignLevelFilter.isChecked():
            signLevelFilter = None

        # sequence filtering
        seqFilter = str(self.ui.cboSeqFilter.currentText())
        sample1Filter = int(self.ui.spinFilterSample1.value())
        sample2Filter = int(self.ui.spinFilterSample2.value())
        if not self.ui.chkEnableSeqFilter.isChecked():
            seqFilter = None
            sample1Filter = None
            sample2Filter = None

        parentSeqFilter = str(self.ui.cboParentSeqFilter.currentText())
        parentSample1Filter = int(self.ui.spinParentFilterSample1.value())
        parentSample2Filter = int(self.ui.spinParentFilterSample2.value())
        if not self.ui.chkEnableParentSeqFilter.isChecked():
            parentSeqFilter = None
            parentSample1Filter = None
            parentSample2Filter = None

        # effect size filters
        if self.ui.chkEnableEffectSizeFilter1.isChecked():
            effectSizeMeasure1 = self.effectSizeDict[str(
                self.ui.cboEffectSizeMeasure1.currentText())]
            minEffectSize1 = float(self.ui.spinMinEffectSize1.value())
        else:
            effectSizeMeasure1 = None
            minEffectSize1 = None

        if self.ui.chkEnableEffectSizeFilter2.isChecked():
            effectSizeMeasure2 = self.effectSizeDict[str(
                self.ui.cboEffectSizeMeasure2.currentText())]
            minEffectSize2 = float(self.ui.spinMinEffectSize2.value())
        else:
            effectSizeMeasure2 = None
            minEffectSize2 = None

        if self.ui.radioOR.isChecked():
            effectSizeOperator = 'OR'
        else:
            effectSizeOperator = 'AND'

        self.statsTest.results.filterFeatures(
            signLevelFilter, seqFilter, sample1Filter, sample2Filter,
            parentSeqFilter, parentSample1Filter, parentSample2Filter,
            effectSizeMeasure1, minEffectSize1, effectSizeOperator,
            effectSizeMeasure2, minEffectSize2)

        self.updateFilterInfo()

        # update table summarizing statistical results
        self.populateSummaryTable()

        # update plots
        self.statPlots.update(self.statsTest.results)

        QtGui.QApplication.instance().restoreOverrideCursor()

    def updateFilterInfo(self):
        self.ui.txtNumActiveFeatures.setText(
            str(len(self.statsTest.results.getActiveFeatures())))

    def populateSummaryTable(self):
        tableData = self.statsTest.results.tableData(
            self.ui.chkShowActiveFeatures.isChecked())

        oneMinAlphaStr = str(self.statsTest.results.oneMinusAlpha() * 100)
        tableHeadings = list(self.profile.hierarchyHeadings)
        tableHeadings += [
            str(self.ui.cboSample1.currentText()),
            str(self.ui.cboSample2.currentText())
        ]
        tableHeadings += ['Parent seq. 1', 'Parent seq. 2']
        tableHeadings += ['Rel. freq. 1 (%)', 'Rel. freq. 2 (%)']
        tableHeadings += ['p-values', 'p-values (corrected)']
        tableHeadings += ['Effect size']
        tableHeadings += [oneMinAlphaStr + '% lower CI']
        tableHeadings += [oneMinAlphaStr + '% upper CI']
        tableHeadings += [
            'Power (alpha = ' + str(self.statsTest.results.alpha) + ')'
        ]
        tableHeadings += [
            'Equal sample size (alpha = ' + str(self.statsTest.results.alpha) +
            '; power = ' + str(self.statsTest.results.oneMinusBeta()) + ')'
        ]

        self.summaryTable = GenericTable(tableData, tableHeadings, self)
        self.summaryTable.sort(0, QtCore.Qt.AscendingOrder
                               )  # start with features in alphabetical order
        self.ui.tableSummary.setModel(self.summaryTable)
        self.ui.tableSummary.verticalHeader().setVisible(False)
        self.ui.tableSummary.resizeColumnsToContents()

    def highlightHierarchyExploratoryChanged(self):
        index = self.ui.cboHighlightHierarchyExploratory.currentIndex() - 1
        if index == -1:
            self.preferences['Selected exploratory features'] = []
            self.ui.cboHighlightFeatureExploratory.clear()
            self.exploratoryPlotUpdate()
            return

        features = set([])
        for feature in self.profile.profileDict.keys():
            hierarchy = self.profile.getHierarchy(feature)
            features.add(hierarchy[index])

        features = list(features)
        features.sort(key=string.lower)

        featureStrList = QtCore.QStringList()
        for feature in features:
            featureStrList.append(feature)

        self.ui.cboHighlightFeatureExploratory.clear()
        self.ui.cboHighlightFeatureExploratory.insertItems(
            len(featureStrList), featureStrList)
        self.ui.cboHighlightFeatureExploratory.setCurrentIndex(0)

        self.ui.cboHighlightFeatureExploratory.adjustSize()

        self.highlightFeatureExploratoryChanged()

    def highlightFeatureExploratoryChanged(self):
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))

        index = self.ui.cboHighlightHierarchyExploratory.currentIndex() - 1
        selectedFeature = self.ui.cboHighlightFeatureExploratory.currentText()

        self.preferences['Selected exploratory features'] = []
        for feature in self.profile.profileDict.keys():
            hierarchy = self.profile.getHierarchy(feature)
            if hierarchy[index] == selectedFeature:
                self.preferences['Selected exploratory features'].append(
                    feature)

        self.exploratoryPlotUpdate()

        QtGui.QApplication.instance().restoreOverrideCursor()

    def highlightHierarchyStatsChanged(self):
        index = self.ui.cboHighlightHierarchyStats.currentIndex() - 1
        if index == -1:
            self.preferences['Selected statistical features'] = []
            self.ui.cboHighlightFeatureStats.clear()
            self.statPlots.update(self.statsTest.results)
            return

        features = set([])
        for feature in self.statsTest.results.getActiveFeatures():
            hierarchy = self.statsTest.results.profile.getHierarchy(feature)
            features.add(hierarchy[index])

        features = list(features)
        features.sort(key=string.lower)

        featureStrList = QtCore.QStringList()
        for feature in features:
            featureStrList.append(feature)

        self.ui.cboHighlightFeatureStats.clear()
        self.ui.cboHighlightFeatureStats.insertItems(len(featureStrList),
                                                     featureStrList)
        self.ui.cboHighlightFeatureStats.setCurrentIndex(0)

        self.ui.cboHighlightFeatureStats.adjustSize()

        self.highlightFeatureStatsChanged()

    def highlightFeatureStatsChanged(self):
        QtGui.QApplication.instance().setOverrideCursor(
            QtGui.QCursor(QtCore.Qt.WaitCursor))

        index = self.ui.cboHighlightHierarchyStats.currentIndex() - 1
        selectedFeature = self.ui.cboHighlightFeatureStats.currentText()

        self.preferences['Selected statistical features'] = []
        for feature in self.statsTest.results.getActiveFeatures():
            hierarchy = self.statsTest.results.profile.getHierarchy(feature)
            if hierarchy[index] == selectedFeature:
                self.preferences['Selected statistical features'].append(
                    feature)

        self.statPlots.update(self.statsTest.results)

        QtGui.QApplication.instance().restoreOverrideCursor()

    def saveImageDlg(self):
        tabWidget = self.ui.tabWidget
        if tabWidget.tabText(tabWidget.currentIndex()) == 'Exploratory plots':
            plotToSave = self.exploratoryPlots
        elif tabWidget.tabText(
                tabWidget.currentIndex()) == 'Statistical plots':
            plotToSave = self.statPlots
        else:
            QtGui.QMessageBox.information(
                self, 'Select plot',
                'A plot tab must be active to save a plot.',
                QtGui.QMessageBox.Ok)
            return

        file = QtGui.QFileDialog.getSaveFileName(
            self, 'Save plot...', self.lastDirectory,
            'Portable Network Graphics (*.png);;' +
            'Portable Document Format (*.pdf);;' + 'PostScript (*.ps);;' +
            'Encapsulated PostScript (*.eps);;' +
            'Scalable Vector Graphics (*.svg)')

        if file != '':
            self.lastDirectory = file[0:file.lastIndexOf('/')]
            try:
                if file[len(file) -
                        3:len(file)] == 'png' or file[len(file) -
                                                      3:len(file)] == 'PNG':
                    dpi, ok = QtGui.QInputDialog.getInteger(
                        self, 'Desired resolution',
                        'Enter desired resolution (DPI) of image:', 300)
                    if ok:
                        plotToSave.save(str(file), dpi)
                else:
                    plotToSave.save(str(file))
            except IOError:
                QtGui.QMessageBox.information(
                    self, 'Failed to save image',
                    'Write permission for file denied.', QtGui.QMessageBox.Ok)

    def sendPlotToWindow(self):
        tabWidget = self.ui.tabWidget
        if tabWidget.tabText(tabWidget.currentIndex()) == 'Exploratory plots':
            newWindow = self.exploratoryPlots.sendToNewWindow(self.profile)
        elif tabWidget.tabText(
                tabWidget.currentIndex()) == 'Statistical plots':
            newWindow = self.statPlots.sendToNewWindow(self.statsTest.results)
        else:
            QtGui.QMessageBox.information(
                self, 'Send plot to window',
                'A plot tab must be active before it can be sent to a new window.',
                QtGui.QMessageBox.Ok)
            return

        self.plotWindows.append(newWindow)

    def saveTableDlg(self):
        tabWidget = self.ui.tabWidget
        if tabWidget.tabText(
                tabWidget.currentIndex()) == 'Statistical results table':
            tableToSave = self.summaryTable
        elif tabWidget.tabText(tabWidget.currentIndex()) == 'CI coverage':
            tableToSave = self.coverageTable
        elif tabWidget.tabText(tabWidget.currentIndex()) == 'Power test':
            tableToSave = self.powerTable
        else:
            QtGui.QMessageBox.information(
                self, 'Select table',
                'A table tab must be active to save a table.',
                QtGui.QMessageBox.Ok)
            return

        filename = QtGui.QFileDialog.getSaveFileName(
            self, 'Save table...', self.lastDirectory,
            'Tab-separated values (*.tsv);;' + 'Text file (*.txt);;' +
            'All files (*.*)')
        if filename != '':
            self.lastDirectory = filename[0:filename.lastIndexOf('/')]
            try:
                tableToSave.save(filename)
            except IOError:
                QtGui.QMessageBox.information(
                    self, 'Failed to save table',
                    'Write permission for file denied.', QtGui.QMessageBox.Ok)

    def confIntervCoverage(self):
        if self.statsTest.results.profile == None:
            return

        confIntervMethod = self.confIntervMethodDict[str(
            self.ui.cboConfIntervMethods.currentText())]
        coverage = float(self.ui.cboCoverage.currentText()) / 100.0
        trials = int(self.ui.spinConfIntervTrials.value())
        bootstrapRep = int(self.ui.spinConfIntervReplicates.value())

        data = self.statsTest.results.contingencyTable(
            self.ui.chkConfInterActiveFeature.isChecked())

        progress = QtGui.QProgressDialog("", QtCore.QString(), 0,
                                         len(data) * trials, self)
        progress.setWindowTitle('Estimating CI coverage')
        progress.setWindowModality(QtCore.Qt.WindowModal)

        confIntervCoverage = ConfIntervCoverage()
        tableData = confIntervCoverage.run(confIntervMethod, coverage, data,
                                           trials, bootstrapRep, progress)

        self.populateConfIntervCoverageTable(tableData)

    def populateConfIntervCoverageTable(self, tableData):
        confIntervMethodStr = str(self.ui.cboConfIntervMethods.currentText())
        coverageStr = str(self.ui.cboCoverage.currentText()) + '%'
        self.ui.lblCoverageTableTitle.setText('Method = ' +
                                              confIntervMethodStr +
                                              '; Nominal coverage = ' +
                                              coverageStr)

        tableHeadings = [str(self.ui.cboProfileLevel.currentText())]
        tableHeadings += [
            str(self.ui.cboSample1.currentText()),
            str(self.ui.cboSample2.currentText())
        ]
        tableHeadings += ['Parent seq. 1', 'Parent seq. 2']
        tableHeadings += ['Rel. freq. 1 (%)', 'Rel. freq. 2 (%)']
        tableHeadings += ['Mean coverage', 'Std. dev. coverage']
        tableHeadings += [
            'Mean coverage (features <= 5 seq.)',
            'Std. dev. (features <= 5 seq.)'
        ]
        tableHeadings += [
            'Mean coverage (features > 5 seq.)',
            'Std. dev. (features > 5 seq.)'
        ]

        self.coverageTable = GenericTable(tableData, tableHeadings, self)

        self.coverageTable.sort(0, QtCore.Qt.AscendingOrder
                                )  # start with features in alphabetical order
        self.ui.tableConfInterCoverage.setModel(self.coverageTable)
        self.ui.tableConfInterCoverage.verticalHeader().setVisible(False)
        self.ui.tableConfInterCoverage.resizeColumnsToContents()

    def powerTest(self):
        if self.statsTest.results.profile == None:
            return

        test = self.statTestDict[str(self.ui.cboStatTests.currentText())]
        signLevel = float(self.ui.cboPowerSignLevel.currentText())
        trials = int(self.ui.spinPowerTrials.value())
        bootstrapRep = int(self.ui.spinPowerReplicates.value())

        data = self.statsTest.results.contingencyTable(
            self.ui.chkPowerActiveFeature.isChecked())

        progress = QtGui.QProgressDialog("", QtCore.QString(), 0,
                                         len(data) * trials, self)
        progress.setWindowTitle('Estimating power')
        progress.setWindowModality(QtCore.Qt.WindowModal)

        power = Power()
        tableData = power.run(test, signLevel, data, trials, bootstrapRep,
                              progress)

        self.populatePowerTestTable(tableData)

    def populatePowerTestTable(self, tableData):
        testStr = str(self.ui.cboStatTests.currentText())
        signLevel = float(self.ui.cboPowerSignLevel.currentText())
        self.ui.lblPowerTestTitle.setText('Test = ' + testStr +
                                          '; Significance level = ' +
                                          str(signLevel))

        tableHeadings = [str(self.ui.cboProfileLevel.currentText())]
        tableHeadings += [
            str(self.ui.cboSample1.currentText()),
            str(self.ui.cboSample2.currentText())
        ]
        tableHeadings += ['Parent seq. 1', 'Parent seq. 2']
        tableHeadings += ['Rel. freq. 1 (%)', 'Rel. freq. 2 (%)']
        tableHeadings += ['Mean power', 'Std. dev. power']
        tableHeadings += [
            'Mean power (features <= 5 seq.)', 'Std. dev. (features <= 5 seq.)'
        ]
        tableHeadings += [
            'Mean power (features > 5 seq.)', 'Std. dev. (features > 5 seq.)'
        ]

        self.powerTable = GenericTable(tableData, tableHeadings, self)

        self.powerTable.sort(0, QtCore.Qt.AscendingOrder
                             )  # start with features in alphabetical order
        self.ui.tablePower.setModel(self.powerTable)
        self.ui.tablePower.verticalHeader().setVisible(False)
        self.ui.tablePower.resizeColumnsToContents()

    def openAboutDlg(self):
        QtGui.QMessageBox.about(
            self, 'About...',
            'STAMP: STatistical Analysis of Metagenomic Profiles\n\n'
            '%s\n'
            '%s\n'
            '%s\n\n'
            '%s' %
            ('Donovan Parks and Robert Beiko', 'v1.08', 'March 13, 2011',
             'Program icon by Caihua (http://commons.wikimedia.org/wiki/File:Fairytale_colors.png)'
             ))
Пример #16
0
    def __init__(self, args, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        if len(args) > 1:
            # self.resize(480, 640)
            self.showFullScreen()
            # self.setWindowFlags(QtCore.Qt.WindowStaysOnBottomHint)
        # self.showFullScreen()

        self.BASE_PATH = BASE_PATH

        self.log_formatter = logging.Formatter(
            '%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
        self.my_handler = RotatingFileHandler('{}'.format(
            os.path.join(self.BASE_PATH, 'logs/photo_to_cloud.log')),
                                              mode='a',
                                              maxBytes=5 * 1024 * 1024,
                                              backupCount=1,
                                              encoding=None,
                                              delay=0)
        self.my_handler.setFormatter(self.log_formatter)
        self.my_handler.setLevel(logging.INFO)
        self.app_log = logging.getLogger('root')
        self.app_log.setLevel(logging.INFO)
        self.app_log.addHandler(self.my_handler)

        # page set up
        self.main_page = 0
        self.menu_page = 1
        self.setting_page = 2
        self.Led_sequence = 3
        self.brightness = 4
        self.screen_brightness = 5
        self.Network_status = 6
        self.password_input = 7
        self.get_update = 8
        self.shutdown_page = 9
        self.camerastatus_page = 10
        self.shutdowntatus_page = 11
        self.step = 0

        self.process_started = False
        self.pinThread = pin_status(self.app_log)
        self.pinThread.signal_rx.connect(self.pinDataEvent)
        self.pinThread.start()

        self.photo_thread = PhotoCloudThread(self.BASE_PATH, self.app_log)
        self.photo_thread.signal_rx.connect(self.photo_event)
        self.photo_thread.start()

        self.wifilist = []
        self.wifiselected = ""
        self.sequence_list = []
        self.sequence_id = []

        self.sequence_selected = ""
        # self.phototocloud = PhotoToCloud()
        self.ui.menuButton.clicked.connect(self.menubuttonClicked)
        self.ui.menuNextbutton.clicked.connect(self.selectClicked)
        self.ui.settingsNextbutton.clicked.connect(self.settins_selectClicked)
        self.ui.nextWiFiButton.clicked.connect(self.wifi_selectClicked)
        self.ui.nextLedSeqButton.clicked.connect(self.sequence_selectClicked)
        self.ui.exitWifipassButton.clicked.connect(
            self.select_exitwifi_password)
        self.ui.menuExitButton.clicked.connect(self.backtomain)
        self.ui.exitImageBrightnessButton.clicked.connect(
            self.brightness_increase)
        self.ui.brightnessLessButton.clicked.connect(self.brightness_decrease)
        self.ui.selectImageBrightnessButton.clicked.connect(
            self.chage_image_brightness)
        self.ui.exitScreenBrightnessButton.clicked.connect(
            self.screen_brightness_increase)
        self.ui.lessScreenBrightnessButton.clicked.connect(
            self.screen_brightness_decrease)
        self.ui.selectScreenBrightnessButton.clicked.connect(
            self.chage_screen_brightness)
        # self.ui.getUpdateButton.clicked.connect(self.update_database)
        self.ui.lightSourcepushbutton.clicked.connect(self.light_source_update)
        self.ui.takePhotoButton.clicked.connect(self.process_light)
        self.ui.shutdownButton.clicked.connect(self.shutdownsystem)
        self.ui.restartButton.clicked.connect(self.restartsystem)
        # self.ui.lineEdit.clicked.connect(self.open_keyboard)
        # self.ui.lineEdit.installEventFilter(self)
        # self.ui.lineEdit.focusOutEvent()
        # self.ui.lineEdit.focusInEvent = MatchBoxLineEdit()
        # self.ui.lineEdit.setFocusPolicy(QtCore.Qt.StrongFocus)
        # self.ui.lineEdit.setFocus(True)
        self.ui.menuSelectButton.clicked.connect(self.nextClicked)
        self.ui.settingsSelectbutton.clicked.connect(self.nextClicked_settings)
        self.ui.selectWiFiButton.clicked.connect(self.nextClicked_wifi)
        self.ui.selectLedSeqButton.clicked.connect(self.nextClicked_sequence)
        self.ui.pushButton_6.clicked.connect(self.rescanNetwork)
        self.ui.exitAppButton.clicked.connect(self.exitApp)

        self.ui.settingsExitbutton.clicked.connect(self.backtomenu)
        self.ui.exitLedSeqButton.clicked.connect(self.backtomenu)
        self.ui.exitWiFiButton.clicked.connect(self.backtomenu)
        self.ui.exitUpdateButton.clicked.connect(self.backtomenu)
        self.ui.exitShutdownButton.clicked.connect(self.backtomenu)

        self.ui.saveWifipassButton.clicked.connect(self.save_wifi)
        self.ui.exitWiFiButton.clicked.connect(self.backtomenu)
        self.ui.cancelShutdownButton.clicked.connect(
            self.cancelActionShutDownOrRestart)
        self.ui.stopshutdown.clicked.connect(
            self.cancelActionShutDownOrRestart)
        self.ui.showKeyboardButton.clicked.connect(self.showKeyboard)
        self.ui.menuList.clicked.connect(self.menulistclicked)
        self.ui.settingsList.clicked.connect(self.settingslistclicked)
        self.ui.sequenceList.clicked.connect(self.sequencelistclicked)
        self.ui.wifiavailableList.clicked.connect(self.wifilistclicked)
        self.ui.updateSequenceButton.clicked.connect(self.update_database)

        # Database access
        self.processing = False
        self.start_time = datetime.now()

        # initiate the database
        self.settings_database = ptc_database.SettingsDatabase(self.app_log)
        self.sequence_step_database = ptc_database.SequenceStepsDatabase(
            self.app_log)
        self.led_groups_database = ptc_database.LEDGroupsDatabase(self.app_log)
        self.sequences_database = ptc_database.SequencesDatabase(self.app_log)
        self.ui.stackedWidget.setCurrentIndex(0)

        self.sequences = []
        # self.ui.wifiavailableList.itemSelectionChanged.connect(self.selectionChanged)
        self.ui.statusInfo.setText("Waiting")
        self.set_sequnce_main_page()
        self.status_light_source = True
        self.light_source_update()
        time.sleep(1)
        self.startUploadFileThread()
Пример #17
0
class MyMainWindow(QMainWindow):
    def __init__(self, args, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        if len(args) > 1:
            # self.resize(480, 640)
            self.showFullScreen()
            # self.setWindowFlags(QtCore.Qt.WindowStaysOnBottomHint)
        # self.showFullScreen()

        self.BASE_PATH = BASE_PATH

        self.log_formatter = logging.Formatter(
            '%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
        self.my_handler = RotatingFileHandler('{}'.format(
            os.path.join(self.BASE_PATH, 'logs/photo_to_cloud.log')),
                                              mode='a',
                                              maxBytes=5 * 1024 * 1024,
                                              backupCount=1,
                                              encoding=None,
                                              delay=0)
        self.my_handler.setFormatter(self.log_formatter)
        self.my_handler.setLevel(logging.INFO)
        self.app_log = logging.getLogger('root')
        self.app_log.setLevel(logging.INFO)
        self.app_log.addHandler(self.my_handler)

        # page set up
        self.main_page = 0
        self.menu_page = 1
        self.setting_page = 2
        self.Led_sequence = 3
        self.brightness = 4
        self.screen_brightness = 5
        self.Network_status = 6
        self.password_input = 7
        self.get_update = 8
        self.shutdown_page = 9
        self.camerastatus_page = 10
        self.shutdowntatus_page = 11
        self.step = 0

        self.process_started = False
        self.pinThread = pin_status(self.app_log)
        self.pinThread.signal_rx.connect(self.pinDataEvent)
        self.pinThread.start()

        self.photo_thread = PhotoCloudThread(self.BASE_PATH, self.app_log)
        self.photo_thread.signal_rx.connect(self.photo_event)
        self.photo_thread.start()

        self.wifilist = []
        self.wifiselected = ""
        self.sequence_list = []
        self.sequence_id = []

        self.sequence_selected = ""
        # self.phototocloud = PhotoToCloud()
        self.ui.menuButton.clicked.connect(self.menubuttonClicked)
        self.ui.menuNextbutton.clicked.connect(self.selectClicked)
        self.ui.settingsNextbutton.clicked.connect(self.settins_selectClicked)
        self.ui.nextWiFiButton.clicked.connect(self.wifi_selectClicked)
        self.ui.nextLedSeqButton.clicked.connect(self.sequence_selectClicked)
        self.ui.exitWifipassButton.clicked.connect(
            self.select_exitwifi_password)
        self.ui.menuExitButton.clicked.connect(self.backtomain)
        self.ui.exitImageBrightnessButton.clicked.connect(
            self.brightness_increase)
        self.ui.brightnessLessButton.clicked.connect(self.brightness_decrease)
        self.ui.selectImageBrightnessButton.clicked.connect(
            self.chage_image_brightness)
        self.ui.exitScreenBrightnessButton.clicked.connect(
            self.screen_brightness_increase)
        self.ui.lessScreenBrightnessButton.clicked.connect(
            self.screen_brightness_decrease)
        self.ui.selectScreenBrightnessButton.clicked.connect(
            self.chage_screen_brightness)
        # self.ui.getUpdateButton.clicked.connect(self.update_database)
        self.ui.lightSourcepushbutton.clicked.connect(self.light_source_update)
        self.ui.takePhotoButton.clicked.connect(self.process_light)
        self.ui.shutdownButton.clicked.connect(self.shutdownsystem)
        self.ui.restartButton.clicked.connect(self.restartsystem)
        # self.ui.lineEdit.clicked.connect(self.open_keyboard)
        # self.ui.lineEdit.installEventFilter(self)
        # self.ui.lineEdit.focusOutEvent()
        # self.ui.lineEdit.focusInEvent = MatchBoxLineEdit()
        # self.ui.lineEdit.setFocusPolicy(QtCore.Qt.StrongFocus)
        # self.ui.lineEdit.setFocus(True)
        self.ui.menuSelectButton.clicked.connect(self.nextClicked)
        self.ui.settingsSelectbutton.clicked.connect(self.nextClicked_settings)
        self.ui.selectWiFiButton.clicked.connect(self.nextClicked_wifi)
        self.ui.selectLedSeqButton.clicked.connect(self.nextClicked_sequence)
        self.ui.pushButton_6.clicked.connect(self.rescanNetwork)
        self.ui.exitAppButton.clicked.connect(self.exitApp)

        self.ui.settingsExitbutton.clicked.connect(self.backtomenu)
        self.ui.exitLedSeqButton.clicked.connect(self.backtomenu)
        self.ui.exitWiFiButton.clicked.connect(self.backtomenu)
        self.ui.exitUpdateButton.clicked.connect(self.backtomenu)
        self.ui.exitShutdownButton.clicked.connect(self.backtomenu)

        self.ui.saveWifipassButton.clicked.connect(self.save_wifi)
        self.ui.exitWiFiButton.clicked.connect(self.backtomenu)
        self.ui.cancelShutdownButton.clicked.connect(
            self.cancelActionShutDownOrRestart)
        self.ui.stopshutdown.clicked.connect(
            self.cancelActionShutDownOrRestart)
        self.ui.showKeyboardButton.clicked.connect(self.showKeyboard)
        self.ui.menuList.clicked.connect(self.menulistclicked)
        self.ui.settingsList.clicked.connect(self.settingslistclicked)
        self.ui.sequenceList.clicked.connect(self.sequencelistclicked)
        self.ui.wifiavailableList.clicked.connect(self.wifilistclicked)
        self.ui.updateSequenceButton.clicked.connect(self.update_database)

        # Database access
        self.processing = False
        self.start_time = datetime.now()

        # initiate the database
        self.settings_database = ptc_database.SettingsDatabase(self.app_log)
        self.sequence_step_database = ptc_database.SequenceStepsDatabase(
            self.app_log)
        self.led_groups_database = ptc_database.LEDGroupsDatabase(self.app_log)
        self.sequences_database = ptc_database.SequencesDatabase(self.app_log)
        self.ui.stackedWidget.setCurrentIndex(0)

        self.sequences = []
        # self.ui.wifiavailableList.itemSelectionChanged.connect(self.selectionChanged)
        self.ui.statusInfo.setText("Waiting")
        self.set_sequnce_main_page()
        self.status_light_source = True
        self.light_source_update()
        time.sleep(1)
        self.startUploadFileThread()

        # self.status_wifi = False
        # time.sleep(10)
        # self.app_log.info("main, updating the database")
        # self.update_database()
        # self.app_log.info("main, updated the database")

    def startUploadFileThread(self):
        print("starting the upload qthred")
        self.file_upload_thread = UploadFileQThread(self.BASE_PATH)
        self.file_upload_thread.start()

        # self.update_database()

        # self.update_database()

    # def selectionChanged(self):
    #     print("Selected items: ")
    #     x = self.ui.wifiavailableList.selectedIndexes()
    #     index = x[0].row()
    #     print(index)

    # def focusInEvent(self, e):
    #     print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    #
    # def focusOutEvent(self, e):
    #     print("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")

    # def eventFilter(self, obj, event):
    #     if event.type() == QEvent.FocusIn:
    #         if obj == self.ui.lineEdit:
    #             try:
    #                 subprocess.Popen(["matchbox-keyboard"])
    #             except FileNotFoundError:
    #                 pass
    #         if event.type() == QEvent.FocusOut:
    #             if obj == self.ui.lineEdit:
    #                 subprocess.Popen(["killall", "matchbox-keyboard"])
    #     return False

    def showKeyboard(self):
        self.app_log.info("main, showKeyboard clicked")
        self.setWifiPasswordFocus()
        password = self.ui.lineEdit.text()
        print("pass", password)
        print("len ", len(password))
        self.ui.lineEdit.setCursorPosition(len(password))
        try:
            # os.system("sh /home/pi/Desktop/code_1/keyboard_open.sh")
            os.system("sh {}".format(
                os.path.join(self.BASE_PATH, 'keyboard_open.sh')))
        except FileNotFoundError:
            pass

    def exitApp(self):
        self.photo_thread.signal_tx.emit("exitfromapp")
        # sys.exit(1)

    def cancelActionShutDownOrRestart(self):
        self.app_log.info("main, cancelActionShutDownOrRestart clicked")
        print("cancelActionShutDownOrRestart signal emiting")
        self.photo_thread.signal_tx.emit("cancel")
        print("cancelActionShutDownOrRestart signal emitted")

    def mouseDoubleClickEvent(self, e):
        current_page = self.ui.stackedWidget.currentIndex()
        if current_page == self.password_input:
            self.showKeyboard()

    def menulistclicked(self, item):
        self.app_log.info("main, menuList clicked")
        print("clicked menuuuuuuuuu list", item.row())
        selected = item.row()
        if selected >= 0:
            self.selection_logic(selected)

    def settingslistclicked(self, item):
        self.app_log.info("main, settingsList clicked")
        print("clicked menuuuuuuuuu list", item.row())
        selected = item.row()
        if selected >= 0:
            self.settings_list_selected(selected)

    def sequencelistclicked(self, item):
        self.app_log.info("main, sequenceList clicked")
        print("clicked menuuuuuuuuu list", item.row())
        selected = item.row()
        if selected >= 0:
            self.led_sequnce_selected(selected)

    def wifilistclicked(self, item):
        self.app_log.info("main, wifiavailableList clicked")
        print("clicked menuuuuuuuuu list", item.row())
        selected = item.row()
        if selected >= 0:
            self.wifi_next_clicked(selected)

    def backtomenu(self):
        self.app_log.info("main, back to menu")
        self.ui.stackedWidget.setCurrentIndex(1)
        self.ui.label_32.setText(" ")
        print("Button click")

    def backtomain(self):
        self.app_log.info("main, back to main")
        # self.app_log.info("main, menuExitButton clicked")
        self.ui.stackedWidget.setCurrentIndex(0)
        self.pinThread.signal_tx.emit("start")
        self.step = 0
        self.set_sequnce_main_page()
        self.light_source_update()

        # self.ui.lightSourceInfo.setText("Light Source Info")
        # print("Button click")

    def rescanNetwork(self):
        self.scan_network()

    def set_sequnce_main_page(self):
        try:
            f = open("{}".format(os.path.join(self.BASE_PATH, 'active_seq')),
                     "r")
            sequence_id = int(f.read())
            f.close()
            name_seq = self.sequences_database.get_active_sequence_name(
                sequence_id)
            if name_seq is not None:
                self.set_led_group_name(self.step, sequence_id)
                # self.ui.lightSourceInfo.setText(self.sequence_selected + " " + str(self.step))
                self.sequence_selected = name_seq
            else:
                self.ui.lightSourceInfo.setText("No sequence available")
                try:
                    os.remove("{}".format(
                        os.path.join(self.BASE_PATH, 'active_seq')))
                except Exception as e:
                    print("Exception update_database ", e)
                    pass

        except Exception as e:
            self.app_log.info("main, updateSequenceButton clicked " + str(e))
            print("Exception set_sequnce_main_page", e)
            # select default sequence
            self.sequences = self.sequences_database.get_all_sequences()
            print("sequences: ", self.sequences)
            sequence_set = False
            for sequence in self.sequences:
                sequence_set = True
                sequence_step_count = self.sequence_step_database.get_sequence_step_count_seq(
                    sequence['id'])
                print(sequence_step_count)
                if sequence_step_count - 1 < self.step:
                    self.step = 0
                self.sequence_selected = sequence['name']
                self.filesave_sequence(sequence['id'])
                sequence_id = sequence['id']
                self.set_led_group_name(self.step, sequence_id)
                # self.ui.lightSourceInfo.setText(self.sequence_selected + " " + str(self.step))
                break
            if not sequence_set:
                self.ui.lightSourceInfo.setText("No sequence available")
                try:
                    os.remove("{}".format(
                        os.path.join(self.BASE_PATH, 'active_seq')))
                except Exception as e:
                    print("Exception update_database ", e)
                    pass

    def set_sequnce_main_page_first(self):
        try:
            self.app_log.info("main, set_sequence_main_page_first started")
            f = open("{}".format(os.path.join(self.BASE_PATH, 'active_seq')),
                     "r")
            sequence_id = int(f.read())
            f.close()
            self.app_log.info("main, file read done")
            self.sequences = self.sequences_database.get_all_sequences()
            sequence_set = False
            for sequence in self.sequences:
                print("xxxxxxxxxxx", sequence['id'])
                if int(sequence['id']) == sequence_id:
                    sequence_set = True
                    break
            if sequence_set == True:
                self.app_log.info("main, sequence same before")
                print("set_sequnce_main_page_first", sequence_set)
                name_seq = self.sequences_database.get_active_sequence_name(
                    sequence_id)
                self.set_led_group_name(self.step, sequence_id)
                # self.ui.lightSourceInfo.setText(self.sequence_selected + " " + str(self.step))
                self.sequence_selected = name_seq
            else:
                self.app_log.info("main, new sequence")
                print("set_sequence_main_page_first", sequence_set)
                self.sequences = self.sequences_database.get_all_sequences()
                print("sequences: ", self.sequences)
                sequence_set1 = False
                for sequence in self.sequences:
                    sequence_set1 = True
                    sequence_step_count = self.sequence_step_database.get_sequence_step_count_seq(
                        sequence['id'])
                    print(sequence_step_count)
                    if sequence_step_count - 1 < self.step:
                        self.step = 0
                    self.sequence_selected = sequence['name']
                    self.filesave_sequence(sequence['id'])
                    sequence_id = sequence['id']
                    self.set_led_group_name(self.step, sequence_id)
                    # self.ui.lightSourceInfo.setText(self.sequence_selected + " " + str(self.step))
                    break
                if not sequence_set1:
                    self.app_log.info("main, No sequence available")
                    self.ui.lightSourceInfo.setText("No sequence available")
                    try:
                        os.remove("{}".format(
                            os.path.join(self.BASE_PATH, 'active_seq')))
                    except Exception as e:
                        print("Exception update_database ", e)
                        pass
        except Exception as e:
            self.app_log.info("main, set_sequence_main_page_first " + str(e))
            print("Exception set_sequnce_main_page", e)
            # select default sequence
            self.sequences = self.sequences_database.get_all_sequences()
            print("sequences: ", self.sequences)
            sequence_set = False
            for sequence in self.sequences:
                sequence_set = True
                sequence_step_count = self.sequence_step_database.get_sequence_step_count_seq(
                    sequence['id'])
                print(sequence_step_count)
                if sequence_step_count - 1 < self.step:
                    self.step = 0
                self.sequence_selected = sequence['name']
                self.filesave_sequence(sequence['id'])
                sequence_id = sequence['id']
                self.set_led_group_name(self.step, sequence_id)
                # self.ui.lightSourceInfo.setText(self.sequence_selected + " " + str(self.step))
                break
            if not sequence_set:
                self.app_log.info("main, No sequence available")
                self.ui.lightSourceInfo.setText("No sequence available")
                try:
                    os.remove("{}".format(
                        os.path.join(self.BASE_PATH, 'active_seq')))
                except Exception as e:
                    print("Exception update_database ", e)
                    pass

    def menubuttonClicked(self):
        # print("stacked widget: ")
        self.app_log.info("main, menubuttonClicked")
        self.pinThread.signal_tx.emit("stop")
        print(self.ui.stackedWidget.currentIndex())
        self.ui.stackedWidget.setCurrentIndex(1)
        self.ui.menuList.setCurrentRow(0)
        self.photo_thread.signal_tx.emit("turnofflight")
        self.ui.label_32.setText(" ")
        print("Button click")

    def open_keyboard(self, e):
        try:
            subprocess.Popen(["matchbox-keyboard"])
        except FileNotFoundError:
            pass

    def close_keyboard(self, e):
        subprocess.Popen(["killall", "matchbox-keyboard"])

    def brightness_increase(self):
        # print("stacked widget: ")
        cu = self.ui.imageBrightnessbox.value()
        self.ui.imageBrightnessbox.setValue(cu + 1)

    def shutdownsystem(self):
        self.app_log.info("main, shutdownButton clicked")
        self.ui.stackedWidget.setCurrentIndex(self.shutdowntatus_page)
        # os.system("sudo poweroff")
        # for i in range(10,0,-1):
        #     self.ui.shudownTimer.setText("Timer in " + str(10))
        self.photo_thread.signal_tx.emit("poweroff")

    def restartsystem(self):
        self.app_log.info("main, restartbutton clicked")
        self.ui.stackedWidget.setCurrentIndex(self.shutdowntatus_page)
        # os.system("sudo poweroff")
        # for i in range(10,0,-1):
        #     self.ui.shudownTimer.setText("Timer in " + str(10))
        self.photo_thread.signal_tx.emit("restart")

    def update_database(self):
        self.app_log.info("main, updateSequenceButton clicked")
        self.photo_thread.signal_tx.emit("download")
        # try:
        #     os.remove("active_seq")
        # except Exception as e:
        #     print("Exception update_database ", e)
        #     pass
        # self.download_database()
        # self.set_sequnce_main_page()

    def brightness_decrease(self):
        # print("stacked widget: ")
        cu = self.ui.imageBrightnessbox.value()
        if cu - 1 >= 0:
            self.ui.imageBrightnessbox.setValue(cu - 1)

    def read_sequence_id(self):
        sequence_id = None
        try:
            f = open("{}".format(os.path.join(self.BASE_PATH, 'active_seq')),
                     "r")
            sequence_id = int(f.read())
            f.close()
            self.app_log.info("read_sequence_id from the file")
        except Exception as e:
            self.app_log.info("read_sequence_id" + str(e))
            pass
        return sequence_id

    def process_light(self):
        self.app_log.info("main, take photo clicked")
        self.sequence_id = self.read_sequence_id()
        if self.sequence_id is None:
            self.app_log.info("main, sequnce id is None")
            return
        if self.process_started:
            return
        self.process_started = True
        self.app_log.info("main, take photo started")
        self.ui.lightSourceInfo.setText("Processing started")
        self.pinThread.signal_tx.emit("stop")
        self.ui.stackedWidget.setCurrentIndex(self.camerastatus_page)
        self.ui.pushButton.setIcon(
            QtGui.QIcon("{}".format(
                os.path.join(self.BASE_PATH,
                             'image_resources/update_icon.png'))))
        self.ui.cameraCapturinginfo.setText("Image Capturing in Progress.....")
        self.app_log.info("main, take photo stopeed")
        # self.phototocloud.process_loop()

    def get_led_gruop_name(self, step, sequencd_id):
        try:
            led_id = self.sequence_step_database.get_led_group_id(
                step, sequencd_id)
            group_name = self.led_groups_database.get_led_group_name(led_id)
            return group_name
        except Exception as exception:
            print(exception)
            return None

    def chage_image_brightness(self):
        cu = self.ui.imageBrightnessbox.value()
        self.photo_thread.signal_tx.emit("brightness=" + str(cu))
        self.ui.stackedWidget.setCurrentIndex(1)

    def chage_screen_brightness(self):
        cu = self.ui.spinBox_2.value()
        # self.pinThread.signal_tx.emit("brightness=" + str(cu))
        self.ui.stackedWidget.setCurrentIndex(1)

    def read_ssid_ipconfig(self):
        ssid = ""
        ipaddress = ""
        try:
            testIP = "8.8.8.8"
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect((testIP, 0))
            ipaddress = s.getsockname()[0]
            ssid = os.popen("iwconfig wlan0 \
                            | grep 'ESSID' \
                            | awk '{print $4}' \
                        | awk -F\\\" '{print $2}'").read()
        except:
            pass
        return [ssid, ipaddress]

    def screen_brightness_increase(self):
        # print("stacked widget: ")
        cu = self.ui.spinBox_2.value()
        self.ui.spinBox_2.setValue(cu + 1)

    def screen_brightness_decrease(self):
        # print("stacked widget: ")
        cu = self.ui.spinBox_2.value()
        if cu - 1 >= 0:
            self.ui.spinBox_2.setValue(cu - 1)

    def set_led_group_name(self, step, sequence_id):
        group_name = self.get_led_gruop_name(step, sequence_id)
        self.ui.lightSourceInfo.setText(self.sequence_selected + " " +
                                        group_name)

    def light_source_update(self):
        self.app_log.info("main, source clicked")
        self.app_log.info("main, light_source_update")
        sequence_id = None
        try:
            f = open("{}".format(os.path.join(self.BASE_PATH, 'active_seq')),
                     "r")
            sequence_id = int(f.read())
            f.close()
            self.app_log.info("main, sequence id saved in the file ")
        except Exception as e:
            self.app_log.info("main, read file exception " + str(e))
            pass

        if sequence_id is not None and self.sequence_selected is not None:
            self.app_log.info("sequence_id and sequence_selected is not None")
            sequence_step_count = self.sequence_step_database.get_sequence_step_count_seq(
                sequence_id)
            print(sequence_step_count)
            if sequence_step_count - 1 < self.step:
                self.step = 0
            # self.ui.lightSourceInfo.setText(self.sequence_selected + " " + str(self.step))
            self.set_led_group_name(self.step, sequence_id)
            # self.phototocloud.process_step(self.step)
            self.app_log.info("main, step started")
            self.photo_thread.signal_tx.emit(self.step)
            self.app_log.info("main, step stopped")
            # self.ph
            self.step += 1
        self.app_log.info(
            "main, source clicked sequence id None or sequence_selected is not None"
        )

    def scan_network(self):
        self.ui.wifiavailableList.clear()
        self.wifilist = self.wifilistarray()
        # self.wifilist = ["Item 1","Item 2"]
        self.ui.wifiavailableList.setFont(QFont("Fixed", 20))
        self.ui.wifiavailableList.addItems(self.wifilist)
        self.ui.wifiavailableList.setCurrentRow(0)

    def select_exitwifi_password(self):
        try:
            # os.system("sh /home/pi/Desktop/code_1/keyboard_on_off.sh")
            os.system("sh {}".format(
                os.path.join(self.BASE_PATH, 'keyboard_on_off.sh')))
        except FileNotFoundError:
            pass
        self.showFullScreen()
        self.ui.stackedWidget.setCurrentIndex(self.Network_status)
        self.scan_network()

    def settins_selectClicked(self):
        self.app_log.info("main, settingsNextbutton clicked")
        x = self.ui.settingsList.selectedIndexes()
        print("row_selected", x)
        if len(x) > 0:
            index = x[0].row()
            print(index)
            if index != -1 and index <= 0:
                self.ui.settingsList.setCurrentRow(index + 1)
                # del self.ui.menuList[index]
            else:
                self.ui.settingsList.setCurrentRow(0)

    def wifi_selectClicked(self):
        self.app_log.info("main, nextWiFiButton clicked")
        x = self.ui.wifiavailableList.selectedIndexes()
        index = x[0].row()
        print(index)
        wif_connected = len(self.wifilist)
        if index != -1 and index <= wif_connected - 2:
            self.ui.wifiavailableList.setCurrentRow(index + 1)
            # del self.ui.menuList[index]
        else:
            self.ui.wifiavailableList.setCurrentRow(0)

    def sequence_selectClicked(self):
        self.app_log.info("main, nextLedSeqButton clicked")
        x = self.ui.sequenceList.selectedIndexes()
        index = x[0].row()
        print(index)
        seq_connected = len(self.sequence_list)
        if index != -1 and index <= seq_connected - 2:
            self.ui.sequenceList.setCurrentRow(index + 1)
            # del self.ui.menuList[index]
        else:
            self.ui.sequenceList.setCurrentRow(0)

    def selectClicked(self):
        self.app_log.info("main, menuNextbutton clicked")
        x = self.ui.menuList.selectedIndexes()
        index = x[0].row()
        print(index)
        if index != -1 and index <= 2:
            self.ui.menuList.setCurrentRow(index + 1)
            # del self.ui.menuList[index]
        else:
            self.ui.menuList.setCurrentRow(0)

    def preview_back(self):
        self.ui.lightSourceInfo.setText("Light Source Info")

    def filesave_sequence(self, seq_val):
        try:
            f = open("{}".format(os.path.join(self.BASE_PATH, 'active_seq')),
                     "w")
            f.write(str(seq_val))
            # perform file operations
        finally:
            f.close()

    def populate_sequence(self):
        self.ui.sequenceList.clear()
        self.sequence_list = []
        self.sequence_id = []
        self.sequences = (self.sequences_database.get_all_sequences())
        # self.sequence_list = ["Item _seq_1", "Item seq_2"]
        for sequence in self.sequences:
            self.sequence_list.append(sequence['name'])
            self.sequence_id.append(sequence['id'])
        self.ui.sequenceList.setFont(QFont("Fixed", 20))
        self.ui.sequenceList.addItems(self.sequence_list)
        self.ui.sequenceList.setCurrentRow(0)

    def selection_logic(self, selected):
        self.sequence_list = []
        self.sequence_id = []
        # Page - Sequence selection page
        if (selected == 0):
            self.ui.stackedWidget.setCurrentIndex(self.Led_sequence)
            self.ui.updateStatusLabel.setText(" ")
            self.populate_sequence()

        # if (selected == 1):
        #     # print("stacked widget: ")
        #     # print(self.ui.stackedWidget.currentIndex())
        #     self.ui.stackedWidget.setCurrentIndex(self.brightness)
        # if (selected == 2):
        #     # print("stacked widget: ")
        #     # print(self.ui.stackedWidget.currentIndex())
        #     self.ui.stackedWidget.setCurrentIndex(self.screen_brightness)

        if (selected == 1):
            self.ui.stackedWidget.setCurrentIndex(self.setting_page)
            [ssid, ipconfig] = self.read_ssid_ipconfig()
            self.ui.label_30.setText(ipconfig)
            self.ui.label_31.setText(ssid)
            self.ui.settingsList.setCurrentRow(0)

        if (selected == 2):
            self.ui.stackedWidget.setCurrentIndex(self.shutdown_page)
            self.ui.shudownTimer.setText(" ")

        if (selected == 3):
            os.system(settings.runServerCommand)
            restartbutton = QMessageBox()
            self.ui.label_32.setText("Server started")

    def nextClicked(self):
        self.app_log.info("main, menuSelectButton clicked")
        # ss = self.ui.menuList.selectedItems()
        # print(ss)
        x = self.ui.menuList.selectedIndexes()
        selected = x[0].row()
        self.selection_logic(selected)

    def wifilistarray(self):
        wifi_list = []
        try:
            os.remove("/home/pi/wifilist")
        except:
            pass
        try:
            os.system("iwlist scan >> /home/pi/wifilist")
            time.sleep(1)
            with open('/home/pi/wifilist') as openfileobject:
                for line in openfileobject:
                    if "ESSID" in line:
                        ssid = line.split(":")[1].replace('"', '').replace(
                            "\n", "")
                        wifi_list.append(ssid)
            print(wifi_list)
            return wifi_list
        except:
            return wifi_list

    def download_database(self):
        print("Downloading settings...")
        self.ui.updateStatusLabel.setText("Downloading settings...")
        self.settings_database.download()
        print("Downloading sequences...")
        self.ui.updateStatusLabel.setText("Downloading sequences...")
        self.sequences_database.download()
        print("Downloading sequence steps...")
        self.ui.updateStatusLabel.setText("Downloading sequence steps...")
        self.sequence_step_database.download()
        print("Downloading LED groups...")
        self.ui.updateStatusLabel.setText("Downloading LED groups...")
        self.led_groups_database.download()
        print("Downloading completed, please check log for full details.")
        self.ui.updateStatusLabel.setText("Downloading completed")

    def settings_list_selected(self, selected):
        if (selected == 0):
            self.ui.stackedWidget.setCurrentIndex(self.Network_status)
            self.ui.wifiavailableList.clear()
            self.wifilist = self.wifilistarray()
            # self.wifilist = ["Item 1","Item 2"]
            self.ui.wifiavailableList.setFont(QFont("Fixed", 20))
            self.ui.wifiavailableList.addItems(self.wifilist)
            self.ui.wifiavailableList.setCurrentRow(0)

    def nextClicked_settings(self):
        # ss = self.ui.menuList.selectedItems()
        # print(ss)
        self.app_log.info("main, settingsSelectbutton clicked")
        x = self.ui.settingsList.selectedIndexes()
        selected = x[0].row()
        self.settings_list_selected(selected)

    def wifi_next_clicked(self, selected):
        self.wifiselected = self.wifilist[selected]
        self.ui.stackedWidget.setCurrentIndex(self.password_input)
        self.showNormal()
        self.resize(322, 480)
        self.setGeometry(0, 0, 322, 479)
        self.ui.lineEdit.clear()
        self.ui.lineEdit.setCursorPosition(0)
        try:
            # os.system("sh /home/pi/Desktop/code_1/keyboard_on_off.sh")
            os.system("sh {}".format(
                format(os.path.join(self.BASE_PATH, 'keyboard_on_off.sh'))))
        except FileNotFoundError:
            # subprocess.Popen(["killall", "matchbox-keyboard"])
            pass
        self.setWifiPasswordFocus()

    def setWifiPasswordFocus(self):
        self.ui.lineEdit.setFocus()

    def nextClicked_wifi(self):
        self.app_log.info("main, selectWiFiButton clicked")
        # ss = self.ui.menuList.selectedItems()
        # print(ss)
        # self.setGeometry(0, 0, 300, 460)
        x = self.ui.wifiavailableList.selectedIndexes()
        selected = x[0].row()
        print(self.wifilist[selected])
        self.wifi_next_clicked(selected)

    def led_sequnce_selected(self, selected):
        self.sequence_selected = self.sequence_list[selected]
        print(self.sequence_selected)
        sequence_id_active = self.sequence_id[selected]
        self.filesave_sequence(sequence_id_active)
        self.backtomain()
        # self.ui.stackedWidget.setCurrentIndex(self.menu_page)
        # self.ui.lightSourceInfo.setText(self.sequence_selected)

    def nextClicked_sequence(self):
        self.app_log.info("main, selectLedSeqButton clicked")
        # ss = self.ui.menuList.selectedItems()
        # print(ss)
        x = self.ui.sequenceList.selectedIndexes()
        selected = x[0].row()
        self.led_sequnce_selected(selected)

    def save_wifi(self):
        self.app_log.info("main, saveWifipassButton clicked")
        password = self.ui.lineEdit.text()
        print(password)
        ssid = self.wifiselected
        try:
            os.system("sh {}".format(
                format(os.path.join(self.BASE_PATH, 'keyboard_on_off.sh'))))
        except FileNotFoundError:
            pass
        # os.system("sudo sh /home/pi/Desktop/code_1/add_wifilist.sh " + ssid + " " + password)
        os.system("sudo sh {} ".format(
            format(os.path.join(self.BASE_PATH, 'add_wifilist.sh'))) + ssid +
                  " " + password)
        self.showFullScreen()
        self.restartsystem()

        # restartbutton = QMessageBox()
        # sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        # restartbutton.setSizePolicy(sizePolicy)
        # buttonReply = restartbutton.question(self, 'Session', "Reboot your system now?",
        #                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        # if buttonReply == QMessageBox.Yes:
        #     print('Yes clicked.')
        #     print("sudo reboot")
        # else:
        #     print('No clicked.')
        #     self.showFullScreen()
        #     self.ui.stackedWidget.setCurrentIndex(self.menu_page)
        # os.system("sudo reboot")

    def pinDataEvent(self, Rxdata):
        print('event test')
        print(Rxdata)
        print("stacked widget: ")
        current_page = self.ui.stackedWidget.currentIndex()
        if current_page == self.main_page:
            if Rxdata == '1':
                self.menubuttonClicked()
            if Rxdata == '2':
                self.process_light()
            if Rxdata == '3':
                self.light_source_update()
        elif current_page == self.menu_page:
            if Rxdata == '1':
                self.backtomain()
            if Rxdata == '2':
                self.nextClicked()
            if Rxdata == '3':
                self.selectClicked()
        elif current_page == self.setting_page:
            if Rxdata == '1':
                self.backtomenu()
            if Rxdata == '2':
                self.nextClicked_settings()
            if Rxdata == '3':
                self.settins_selectClicked()
        elif current_page == self.Led_sequence:
            if Rxdata == '1':
                self.backtomenu()
            if Rxdata == '2':
                self.nextClicked_sequence()
            if Rxdata == '3':
                self.sequence_selectClicked()
        elif current_page == self.brightness:
            if Rxdata == '1':
                self.brightness_increase()
            if Rxdata == '2':
                self.chage_image_brightness()
            if Rxdata == '3':
                self.brightness_decrease()
        elif current_page == self.screen_brightness:
            if Rxdata == '1':
                self.screen_brightness_increase()
            if Rxdata == '2':
                self.chage_screen_brightness()
            if Rxdata == '3':
                self.screen_brightness_decrease()
        elif current_page == self.Network_status:
            if Rxdata == '1':
                self.backtomenu()
            if Rxdata == '2':
                self.nextClicked_wifi()
            if Rxdata == '3':
                self.wifi_selectClicked()
        elif current_page == self.password_input:
            if Rxdata == '1':
                self.select_exitwifi_password()
            if Rxdata == '3':
                self.save_wifi()
        elif current_page == self.get_update:
            if Rxdata == '1':
                self.backtomenu()
            if Rxdata == '3':
                pass
        elif current_page == self.shutdown_page:
            if Rxdata == '1':
                self.backtomenu()
            if Rxdata == '3':
                self.cancelActionShutDownOrRestart()

        # if Rxdata == '4':
        #     self.ui.statusInfo.setText("Connected")
        #     self.ui.wifiStatus.setIcon(QtGui.QIcon('image_resources/wifiON_icon.ico'))
        #     self.ui.wifiStatus.setIconSize(QtCore.QSize(44, 40))
        # elif Rxdata == '5':
        #     self.ui.statusInfo.setText("Not Connected")
        #     self.ui.wifiStatus.setIcon(QtGui.QIcon('image_resources/wifiOFF_icon.png'))
        #     self.ui.wifiStatus.setIconSize(QtCore.QSize(44, 40))

        if Rxdata == 'stopped' and self.process_started:
            print("camera stopped")
            # self.phototocloud.process()
            self.photo_thread.signal_tx.emit("start")

    def photo_event(self, Rxdata):
        if (Rxdata == "finished"):
            # self.ui.lightSourceInfo.setText("processing {} ".format(Rxdata))
            self.ui.lightSourceInfo.setText("Ready")
            self.ui.cameraCapturinginfo.setText("Success!")
            # self.ui.pushButton.setIcon(QtGui.QIcon('/home/pi/Desktop/code_1/image_resources/tick_icon.png'))
            self.ui.pushButton.setIcon(
                QtGui.QIcon('{}'.format(
                    os.path.join(self.BASE_PATH,
                                 'image_resources/tick_icon.png'))))

        elif (Rxdata == "backtomaainpage"):
            self.pinThread.signal_tx.emit("start")
            self.ui.stackedWidget.setCurrentIndex(self.main_page)
            self.process_started = False
            self.step = 0

        elif (Rxdata == "connected"):
            self.ui.statusInfo.setText("Ready")
            # self.ui.wifiStatus.setIcon(QtGui.QIcon('/home/pi/Desktop/code_1/image_resources/wifiON_icon.png'))
            self.ui.wifiStatus.setIcon(
                QtGui.QIcon('{}'.format(
                    os.path.join(self.BASE_PATH,
                                 'image_resources/wifiON_icon.png'))))
            self.ui.wifiStatus.setIconSize(QtCore.QSize(44, 40))

        elif (Rxdata == "disconnected"):
            self.ui.statusInfo.setText("No WiFi connection")
            # self.ui.wifiStatus.setIcon(QtGui.QIcon('/home/pi/Desktop/code_1/image_resources/wifiOFF_icon.png'))
            self.ui.wifiStatus.setIcon(
                QtGui.QIcon('{}'.format(
                    os.path.join(self.BASE_PATH,
                                 'image_resources/wifiOFF_icon.png'))))
            self.ui.wifiStatus.setIconSize(QtCore.QSize(44, 40))

        elif "Downloading completed" in Rxdata:
            self.populate_sequence()
            self.ui.updateStatusLabel.setText(Rxdata)

        elif "Downloading failed" in Rxdata:
            self.populate_sequence()
            self.ui.updateStatusLabel.setText(Rxdata)

        elif "Downloading" in Rxdata:
            self.ui.updateStatusLabel.setText(Rxdata)

        elif "Low Battery" in Rxdata:
            self.ui.statusInfo.setText(Rxdata)

        elif "full mode" in Rxdata:
            print("Ready")
            pass
            # self.ui.statusInfo.setText("Ready")

        elif "Shutting down in" in Rxdata:
            # self.ui.shudownTimer.setText(Rxdata)
            Rxdata = Rxdata + " seconds"
            self.ui.shutdownstatus.setText(Rxdata)

        elif "Restart in " in Rxdata:
            # self.ui.shudownTimer.setText(Rxdata)
            Rxdata = Rxdata + " seconds"
            self.ui.shutdownstatus.setText(Rxdata)
        elif "Action Cancelled" in Rxdata:
            # self.ui.shudownTimer.setText(Rxdata)
            self.ui.shutdownstatus.setText(Rxdata)
            self.ui.stackedWidget.setCurrentIndex(self.shutdown_page)

        else:
            print("RX dataAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", Rxdata)
Пример #18
0
from PyQt4 import QtCore, QtGui
from mainUI import Ui_MainWindow, MyWindow

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)



    
if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = MyWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    
    sys.exit(app.exec_())

Пример #19
0
class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.btnLoadDb.clicked.connect(self.do_LoadDb)
        self.ui.btnQuery.clicked.connect(self.do_Query)
        self.ui.btnQueryModify.clicked.connect(self.do_QueryModify)
        self.ui.btnQueryDelete.clicked.connect(self.do_QueryDelete)

        self.ui.btnSelectFile.clicked.connect(self.do_Select)
        self.ui.btnAddtoDb.clicked.connect(self.do_Add)





    ###########自定义槽函数#################################################
    #---加载函数-------------------------------------------------------------------
    def do_LoadDb(self):
        #链接数据库
        self.db = MySQLdb.connect(host='localhost' , user='******' , password ='******' , db='db_test',charset='utf8')
        self.cur = self.db.cursor()
        print('Good job!')
        #更新/加载条件选择的comBOX
        self.cur.execute("SELECT DISTINCT data_location FROM clutter_table;")
        name_location = self.cur.fetchall()
        self.ui.cmbDataLocation.clear()
        self.ui.cmbDataLocation.addItem('不限')
        for category in name_location:
            self.ui.cmbDataLocation.addItem(category[0])
        self.cur.execute("SELECT DISTINCT data_model FROM clutter_table;")
        name_model = self.cur.fetchall()
        self.ui.cmbDataModel.clear()
        self.ui.cmbDataModel.addItem('不限')
        for category in name_model:
            self.ui.cmbDataModel.addItem(category[0])
        self.cur.execute("SELECT DISTINCT data_mode FROM clutter_table;")
        name_mode = self.cur.fetchall()
        self.ui.cmbDataMode.clear()
        self.ui.cmbDataMode.addItem('不限')
        for category in name_mode:
            self.ui.cmbDataMode.addItem(category[0])
        self.cur.execute("SELECT DISTINCT data_env FROM clutter_table;")
        name_env = self.cur.fetchall()
        self.ui.cmbDataEnv.clear()
        self.ui.cmbDataEnv.addItem('不限')
        for category in name_env:
            self.ui.cmbDataEnv.addItem(category[0])
        #显示加载数据
        self.ui.tableView1.clearContents()
        self.cur.execute("SELECT * FROM clutter_table ORDER BY data_id DESC")
        data = self.cur.fetchall()
        print(data)
        self.ui.tableView1.setRowCount(0)
        self.ui.tableView1.insertRow(0)
        for row,form in enumerate(data):
            for column, item in enumerate(form):
                self.ui.tableView1.setItem(row, column, QTableWidgetItem(str(item)))
                column += 1
            row_position = self.ui.tableView1.rowCount()
            self.ui.tableView1.insertRow(row_position)
        #打印操作记录
        item_num = len(data)
        print(str(item_num))
        text_history = "------------------------------------\n"
        text_history += "杂波数据库共保存" + str(item_num) + "条数据..."
        self.ui.textHistory.append(text_history)
        self.db.close()
    #---查询函数-------------------------------------------------------------------
    def do_Query(self):
        #链接数据库
        self.db = MySQLdb.connect(host='localhost' , user='******' , password ='******' , db='db_test',charset='utf8')
        self.cur = self.db.cursor()
        condition_id = self.ui.textDataId.text()
        condition_name = self.ui.textDataFileName.text()
        condition_date1 = self.ui.dateDataDate1.text()
        #condition_date1.toString(dtStr, "MM-dd-yyyy")
        condition_date2 = self.ui.dateDataDate2.text()
       # condition_date2.toString(dtStr, "MM-dd-yyyy")
        condition_location = self.ui.cmbDataLocation.currentText()
        condition_model = self.ui.cmbDataModel.currentText()
        condition_mode = self.ui.cmbDataMode.currentText()
        condition_env = self.ui.cmbDataEnv.currentText()
        condition_remarks = self.ui.textDataRemarks.toPlainText()
        #开始查询
        query_sql = "SELECT * FROM clutter_table WHERE 1=1 "
        if condition_id != '':
           # query_sql += "AND data_id like \%%d\% " %int(condition_id)
           query_sql += "AND data_id like '%" + condition_id + "%' "
        if condition_name != '':
            query_sql += " AND data_filename LIKE '%" + condition_name + "%' "
        if condition_location != '不限':
            query_sql += " AND data_location ='" + condition_location + "' "
        if condition_model != '不限':
            query_sql += " AND data_model ='" + condition_model + "' "
        if condition_mode != '不限':
            query_sql += " AND data_mode ='" + condition_mode + "' "
        if condition_env != '不限':
            query_sql += " AND data_env ='" + condition_env + "' "
        if condition_remarks != '':
            query_sql += " AND data_remarks like '%" + condition_remarks + "%' "
        query_sql += ";"
        self.cur.execute(query_sql)
        data = self.cur.fetchall()
        #在tableView1中显示
        self.ui.tableView1.clearContents()
        self.ui.tableView1.setRowCount(0)
        self.ui.tableView1.insertRow(0)
        for row,form in enumerate(data):
            for column, item in enumerate(form):
                self.ui.tableView1.setItem(row, column, QTableWidgetItem(str(item)))
                column += 1
            row_position = self.ui.tableView1.rowCount()
            self.ui.tableView1.insertRow(row_position)
        #打印操作记录
        item_num = len(data)
        print(str(item_num))
        text_history = "------------------------------------\n"
        text_history += "共检索到" + str(item_num) + "条数据..."
        self.ui.textHistory.append(text_history)
        self.db.close()
    #---批量更改-------------------------------------------------------------------
    def do_QueryModify(self):
        reply = QMessageBox.question(self, 'Message', '确认修改数据?',
                           QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
        if reply == QMessageBox.Yes:
            print("Good!")
            #链接数据库
            self.db = MySQLdb.connect(host='localhost' , user='******' , password ='******' , db='db_test',charset='utf8')
            self.cur = self.db.cursor()
            rowCount = self.ui.tableView1.rowCount()
            columnCount = self.ui.tableView1.columnCount()
            for i in range(rowCount - 1):
                value_lst = []
                for j in range(columnCount):
                    #item_data = QTableWidgetItem(None)
                    #self.ui.tableView1.setItem(i,j,item_data)
                    tmp_data = self.ui.tableView1.item(i,j).text()
                    value_lst.append(tmp_data)
                sql = "UPDATE clutter_table SET data_filename = '" + value_lst[1] + "',data_date = '" + value_lst[2] + "',"
                sql += "data_location = '" + value_lst[3] + "',data_model ='" + value_lst[4] + "',"
                sql += "data_mode = '" + value_lst[5] + "',data_env = '" + value_lst[6] + "',data_remarks = '" + value_lst[7] + "',"
                sql += "data_path = '" + value_lst[8] + "'"
                sql += " WHERE data_id = " + value_lst[0] + ";"
                #sql =
                #sql%(value_lst[1],value_lst[2],value_lst[3],value_lst[4],value_lst[5],value_lst[6],value_lst[7],value_lst[8],int(value_lst[0]))
                self.cur.execute(sql)
                self.db.commit() #必须显示提交才行
            text_history = "------------------------------------\n"
            text_history += "数据库更新完毕..."
            self.ui.textHistory.append(text_history)
            self.db.close()  # 这里必须关掉,否则数据实际无更改
            self.ui.tableView1.clearContents()
            
    #---单个删除-------------------------------------------------------------------
    def do_QueryDelete(self):
        reply = QMessageBox.question(self, 'Message', '确认删除该条数据?',
                           QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
        if reply == QMessageBox.Yes:
            print("Delete it !")
            #链接数据库
            self.db = MySQLdb.connect(host='localhost' , user='******' , password ='******' , db='db_test',charset='utf8')
            self.cur = self.db.cursor()
            #提取当前行
            row_del = self.ui.tableView1.currentRow()
            id_del = self.ui.tableView1.item(row_del,0).text()
            #从数据中删除该行数据
            sql = "DELETE FROM clutter_table WHERE data_id =" + id_del
            self.cur.execute(sql)
            self.db.commit()
            #删除表格中该行数据
            self.ui.tableView1.removeRow(row_del)
            text_history = "------------------------------------\n"
            text_history += "该数据已删除..."
            self.ui.textHistory.append(text_history)
            self.db.close()  # 这里必须关掉,否则数据实际无更改
    #---添加多个文件-------------------------------------------------------------------
    def do_Select(self):
        files, filetype = QFileDialog.getOpenFileNames(self,"请选择:","E:/my_python/gui/test_data",
                                                       "All Files(*);;Text Files(*.txt)")
        files_name = []
        files_date = []
        files_location = []
        files_model = []
        files_mode = []
        files_env = []
        files_path = []
        #遍历files,获取信息 格式:7s2020062501_上海_1x_SAR_湿地.txt
        for file in files:
            files_path.append(file)
            file = QFileInfo(file)
            name = file.fileName()
            p1 = name.find('_',0)
            p2 = name.find('_',p1 + 1)
            p3 = name.find('_',p2 + 1)
            p4 = name.find('_',p3 + 1)
            p5 = name.find('.',p4 + 1)
            files_name.append(name)
            date = name[2:p1 - 2]
            date = date[:4] + '-' + date[4:6] + '-' + date[6:]
            files_date.append(date)
            files_location.append(name[p1 + 1:p2])
            files_model.append(name[p2 + 1:p3])
            files_mode.append(name[p3 + 1:p4])
            files_env.append(name[p4 + 1:p5])
        num_files = len(files_name)
        self.ui.tableView2.clearContents()
        self.ui.tableView2.setRowCount(0)
        self.ui.tableView2.insertRow(0)
        for i in range(num_files):
            self.ui.tableView2.setItem(i,1,QTableWidgetItem(str(files_name[i])))
            self.ui.tableView2.setItem(i,2,QTableWidgetItem(str(files_date[i])))
            self.ui.tableView2.setItem(i,3,QTableWidgetItem(str(files_location[i])))
            self.ui.tableView2.setItem(i,4,QTableWidgetItem(str(files_model[i])))
            self.ui.tableView2.setItem(i,5,QTableWidgetItem(str(files_mode[i])))
            self.ui.tableView2.setItem(i,6,QTableWidgetItem(str(files_env[i])))
            self.ui.tableView2.setItem(i,8,QTableWidgetItem(str(files_path[i])))
            row_position = self.ui.tableView2.rowCount()
            self.ui.tableView2.insertRow(row_position)
        text_history = "------------------------------------\n"
        text_history += "打开" + str(num_files) + "条数据, 点击 添加至数据库 完成导入..."
        self.ui.textHistory.append(text_history)
    #---从表格导入数据库----------------------------------------------------------------
    def Add(self):
        reply = QMessageBox.question(self, 'Message', '确认导入数据?',
                           QMessageBox.Yes | QMessageBox.No,QMessageBox.No)
        if reply == QMessageBox.Yes:
            #链接数据库
            self.db = MySQLdb.connect(host='localhost' , user='******' , password ='******' , db='db_test',charset='utf8')
            self.cur = self.db.cursor()
            rowCount = self.ui.tableView2.rowCount()
            colCount = self.ui.tableView2.columnCount()
            for i in range(rowCount - 1):
                value_lst = []
                for j in range(colCount):
                    #item_data = QTableWidgetItem(None)
                    #self.ui.tableView1.setItem(i,j,item_data)
                    tmp_data = self.ui.tableView2.item(i,j).text()
                    value_lst.append(tmp_data)
                sql = "INSERT INTO clutter_table (data_filename, data_date, data_location, data_model,"
                sql += " data_mode, data_env, data_remarks, data_path)"
                sql += " VALUES('") data_id = " + value_lst[0] + ";"
                #sql =
                #sql%(value_lst[1],value_lst[2],value_lst[3],value_lst[4],value_lst[5],value_lst[6],value_lst[7],value_lst[8],int(value_lst[0]))
                self.cur.execute(sql)
Пример #20
0
class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.btnLoadDb.clicked.connect(self.do_LoadDb)
        self.ui.btnQuery.clicked.connect(self.do_Query)
        self.ui.btnQueryModify.clicked.connect(self.do_QueryModify)
        self.ui.btnQueryDelete.clicked.connect(self.do_QueryDelete)

        self.ui.btnSelectFile.clicked.connect(self.do_Select)

    ###########自定义槽函数#################################################
    #---加载函数-------------------------------------------------------------------
    def do_LoadDb(self):
        #链接数据库
        self.db = MySQLdb.connect(host='localhost',
                                  user='******',
                                  password='******',
                                  db='db_test',
                                  charset='utf8')
        self.cur = self.db.cursor()
        print('Good job!')
        #更新/加载条件选择的comBOX
        self.cur.execute("SELECT DISTINCT data_location FROM clutter_table;")
        name_location = self.cur.fetchall()
        self.ui.cmbDataLocation.clear()
        self.ui.cmbDataLocation.addItem('不限')
        for category in name_location:
            self.ui.cmbDataLocation.addItem(category[0])
        self.cur.execute("SELECT DISTINCT data_model FROM clutter_table;")
        name_model = self.cur.fetchall()
        self.ui.cmbDataModel.clear()
        self.ui.cmbDataModel.addItem('不限')
        for category in name_model:
            self.ui.cmbDataModel.addItem(category[0])
        self.cur.execute("SELECT DISTINCT data_mode FROM clutter_table;")
        name_mode = self.cur.fetchall()
        self.ui.cmbDataMode.clear()
        self.ui.cmbDataMode.addItem('不限')
        for category in name_mode:
            self.ui.cmbDataMode.addItem(category[0])
        self.cur.execute("SELECT DISTINCT data_env FROM clutter_table;")
        name_env = self.cur.fetchall()
        self.ui.cmbDataEnv.clear()
        self.ui.cmbDataEnv.addItem('不限')
        for category in name_env:
            self.ui.cmbDataEnv.addItem(category[0])
        #显示加载数据
        self.ui.tableView1.clearContents()
        self.cur.execute("SELECT * FROM clutter_table ORDER BY data_id DESC")
        data = self.cur.fetchall()
        print(data)
        self.ui.tableView1.setRowCount(0)
        self.ui.tableView1.insertRow(0)
        for row, form in enumerate(data):
            for column, item in enumerate(form):
                self.ui.tableView1.setItem(row, column,
                                           QTableWidgetItem(str(item)))
                column += 1
            row_position = self.ui.tableView1.rowCount()
            self.ui.tableView1.insertRow(row_position)
        #打印操作记录
        item_num = len(data)
        print(str(item_num))
        text_history = "------------------------------------\n"
        text_history += "杂波数据库共保存" + str(item_num) + "条数据..."
        self.ui.textHistory.append(text_history)
        self.db.close()

    #---查询函数-------------------------------------------------------------------
    def do_Query(self):
        #链接数据库
        self.db = MySQLdb.connect(host='localhost',
                                  user='******',
                                  password='******',
                                  db='db_test',
                                  charset='utf8')
        self.cur = self.db.cursor()
        condition_id = self.ui.textDataId.text()
        condition_name = self.ui.textDataFileName.text()
        condition_date1 = self.ui.dateDataDate1.text()
        #condition_date1.toString(dtStr, "MM-dd-yyyy")
        condition_date2 = self.ui.dateDataDate2.text()
        # condition_date2.toString(dtStr, "MM-dd-yyyy")
        condition_location = self.ui.cmbDataLocation.currentText()
        condition_model = self.ui.cmbDataModel.currentText()
        condition_mode = self.ui.cmbDataMode.currentText()
        condition_env = self.ui.cmbDataEnv.currentText()
        condition_remarks = self.ui.textDataRemarks.toPlainText()
        #开始查询
        query_sql = "SELECT * FROM clutter_table WHERE 1=1 "
        if condition_id != '':
            # query_sql += "AND data_id like \%%d\% " %int(condition_id)
            query_sql += "AND data_id like '%" + condition_id + "%' "
        if condition_name != '':
            query_sql += " AND data_filename LIKE '%" + condition_name + "%' "
        if condition_location != '不限':
            query_sql += " AND data_location ='" + condition_location + "' "
        if condition_model != '不限':
            query_sql += " AND data_model ='" + condition_model + "' "
        if condition_mode != '不限':
            query_sql += " AND data_mode ='" + condition_mode + "' "
        if condition_env != '不限':
            query_sql += " AND data_env ='" + condition_env + "' "
        if condition_remarks != '':
            query_sql += " AND data_remarks like '%" + condition_remarks + "%' "
        query_sql += ";"
        self.cur.execute(query_sql)
        data = self.cur.fetchall()
        #在tableView1中显示
        self.ui.tableView1.clearContents()
        self.ui.tableView1.setRowCount(0)
        self.ui.tableView1.insertRow(0)
        for row, form in enumerate(data):
            for column, item in enumerate(form):
                self.ui.tableView1.setItem(row, column,
                                           QTableWidgetItem(str(item)))
                column += 1
            row_position = self.ui.tableView1.rowCount()
            self.ui.tableView1.insertRow(row_position)
        #打印操作记录
        item_num = len(data)
        print(str(item_num))
        text_history = "------------------------------------\n"
        text_history += "共检索到" + str(item_num) + "条数据..."
        self.ui.textHistory.append(text_history)
        self.db.close()

    #---批量更改-------------------------------------------------------------------
    def do_QueryModify(self):
        reply = QMessageBox.question(self, 'Message', '确认修改数据?',
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            print("Good!")
            #链接数据库
            self.db = MySQLdb.connect(host='localhost',
                                      user='******',
                                      password='******',
                                      db='db_test',
                                      charset='utf8')
            self.cur = self.db.cursor()
            rowCount = self.ui.tableView1.rowCount()
            columnCount = self.ui.tableView1.columnCount()
            for i in range(rowCount - 1):
                value_lst = []
                for j in range(columnCount):
                    #item_data = QTableWidgetItem(None)
                    #self.ui.tableView1.setItem(i,j,item_data)
                    tmp_data = self.ui.tableView1.item(i, j).text()
                    value_lst.append(tmp_data)
                sql = "UPDATE clutter_table SET data_filename = '" + value_lst[
                    1] + "',data_date = '" + value_lst[2] + "',"
                sql += "data_location = '" + value_lst[
                    3] + "',data_model ='" + value_lst[4] + "',"
                sql += "data_mode = '" + value_lst[
                    5] + "',data_env = '" + value_lst[
                        6] + "',data_remarks = '" + value_lst[7] + "',"
                sql += "data_path = '" + value_lst[8] + "'"
                sql += " WHERE data_id = " + value_lst[0] + ";"
                #sql = sql%(value_lst[1],value_lst[2],value_lst[3],value_lst[4],value_lst[5],value_lst[6],value_lst[7],value_lst[8],int(value_lst[0]))
                self.cur.execute(sql)
                self.db.commit()  #必须显示提交才行
            text_history = "------------------------------------\n"
            text_history += "数据库更新完毕..."
            self.ui.textHistory.append(text_history)
            self.db.close()  # 这里必须关掉,否则数据实际无更改
            self.ui.tableView1.clearContents()

    #---单个删除-------------------------------------------------------------------
    def do_QueryDelete(self):
        reply = QMessageBox.question(self, 'Message', '确认删除该条数据?',
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            print("Delete it !")
            #链接数据库
            self.db = MySQLdb.connect(host='localhost',
                                      user='******',
                                      password='******',
                                      db='db_test',
                                      charset='utf8')
            self.cur = self.db.cursor()
            #提取当前行
            row_del = self.ui.tableView1.currentRow()
            id_del = self.ui.tableView1.item(row_del, 0).text()
            #从数据中删除该行数据
            sql = "DELETE FROM clutter_table WHERE data_id =" + id_del
            self.cur.execute(sql)
            self.db.commit()
            #删除表格中该行数据
            self.ui.tableView1.removeRow(row_del)
            text_history = "------------------------------------\n"
            text_history += "该数据已删除..."
            self.ui.textHistory.append(text_history)
            self.db.close()  # 这里必须关掉,否则数据实际无更改

    #---添加多个文件-------------------------------------------------------------------
    def do_Select(self):
        print("hah")
Пример #21
0
'''
This is the main entry point
Author: Shawn
Date: 2018.8.11
Version: 0.1
'''

import sys
from mainUI import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    UI = QtWidgets.QMainWindow()
    MainUI = Ui_MainWindow()
    MainUI.setupUi(UI)
    UI.show()
    sys.exit(app.exec_())


Пример #22
0
class MainWindow(qtw.QMainWindow):
    """Class that handles all the backend of the UI."""
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.index = None
        print(self.index)
        self.image_names = []

        # Populating combobox values.
        self.ui.elitismComboBox.addItem('Y')
        self.ui.elitismComboBox.addItem('N')
        self.ui.crossoverTypeComboBox.addItem('SP')
        self.ui.crossoverTypeComboBox.addItem('TP')
        self.ui.parentSelectComboBox.addItem('RS')
        self.ui.parentSelectComboBox.addItem('RWS')

        self.ga_thread = None
        self.a_star_thread = None

        self.ui.autoTrace.clicked.connect(self.run_auto_trace)
        self.ui.stopAutotrace.clicked.connect(self.stop_auto_trace)

        self.ui.nextButton.clicked.connect(self.show_next_image)
        self.ui.prevButton.clicked.connect(self.show_prev_image)

        self.ui.runAStarButton.clicked.connect(self.run_a_star)
        self.ui.stopastarButton.clicked.connect(self.stop_a_star_thread)

        self.ui.runGaButton.clicked.connect(self.run_genetic_algorithm)
        self.ui.stopgaButton.clicked.connect(self.stop_ga_thread)

        self.ui.resetButton.clicked.connect(self.reset)

        self.ui.nextButton.setDisabled(True)
        self.ui.prevButton.setDisabled(True)
        self.ui.autoTrace.setDisabled(True)
        self.ui.stopAutotrace.setDisabled(True)

        os.makedirs(folder, exist_ok=True
                    )  # Creating folder to store images if it does not exist.

    def run_a_star(self):
        """Function to run the A* algorithm. It uses a thread to run the algorithm in the background."""

        N_queens = self.ui.nQueenSpinBox.value()

        self.a_star_thread = AStarAlgorithmThread(N_queens=N_queens)

        self.ui.outputLabel.setText("A Star Algorithm Running...")
        self.a_star_thread.start()
        self.a_star_thread.finished.connect(self.show_a_star_results)

    def stop_a_star_thread(self):
        """Function to stop the algorithm's thread and enable some buttons."""

        self.ui.outputLabel.setText('Searching Stopped!')
        self.a_star_thread.terminate()

        self.ui.nextButton.setDisabled(False)
        self.ui.prevButton.setDisabled(False)
        self.ui.autoTrace.setDisabled(False)
        self.ui.stopAutotrace.setDisabled(False)
        win.close(
        )  # Closing window as stopping on large inputs can sometimes freeze the window.

    def show_a_star_results(self):
        """Function to display the output of the algorithm."""

        global a_star_output
        if len(a_star_output) != 0:
            output = f'Steps = {a_star_output[0]} | Time = {a_star_output[1] :.4} secs | Solution Found = {a_star_output[2]}'
            self.ui.outputLabel.setText(output)
            self.load_images_directory()
        else:
            print('Output List is Empty!')

    def run_genetic_algorithm(self):
        """Function to run the Genetic algorithm. It uses a thread to run the algorithm in the background."""

        N_queens = self.ui.nQueenSpinBox.value()
        init_pop_size = self.ui.initpopSpinBox.value()
        mutation_prob = self.ui.mutprobDoubleSpinBox.value()
        max_gen = self.ui.maxgenSpinBox.value()
        crossover_rate = self.ui.crossoverRateDoubleSpinBox.value()
        elitism = self.ui.elitismComboBox.currentText()
        crossover_method = self.ui.crossoverTypeComboBox.currentText()
        parent_selection_algo = self.ui.parentSelectComboBox.currentText()

        self.ga_thread = GeneticAlgorithmThread(
            N_queens=N_queens,
            init_pop_size=init_pop_size,
            mutation_prob=mutation_prob,
            max_gen=max_gen,
            crossover_method=crossover_method,
            crossover_rate=crossover_rate,
            parent_selection_algo=parent_selection_algo,
            elitism=elitism)

        self.ui.outputLabel.setText("Genetic Algorithm Running...")
        self.ga_thread.start()
        self.ga_thread.finished.connect(self.show_ga_results)

    def stop_ga_thread(self):
        """Function to stop the algorithm's thread and enable some buttons."""

        self.ui.outputLabel.setText('Searching Stopped!')
        self.ga_thread.terminate()

        self.ui.nextButton.setDisabled(False)
        self.ui.prevButton.setDisabled(False)
        self.ui.autoTrace.setDisabled(False)
        self.ui.stopAutotrace.setDisabled(False)
        win.close(
        )  # Closing window as stopping on large inputs can sometimes freeze the window.

    def show_ga_results(self):
        """Function to display the output of the algorithm."""

        global ga_output
        if len(ga_output) != 0:
            output = f'Steps = {ga_output[0]} | Time = {ga_output[1] :.4} secs | Solution Found = {ga_output[2]}'
            self.ui.outputLabel.setText(output)
            self.load_images_directory()
        else:
            print('Output List is Empty!')

    def run_auto_trace(self):
        """Function to run auto trace feature."""

        self.image_names.clear()

        self.load_images_directory()

        self.file_it = iter(self.image_names)

        self._timer = QtCore.QTimer(self, interval=300)
        self._timer.timeout.connect(self._on_timeout)
        self._timer.start()

    def _on_timeout(self):
        """Utility timeout function for auto tracing."""

        try:
            img = next(self.file_it)

            self.ui.imagecountLabel.setText(img)
            self.ui.imageLabel.setPixmap(QtGui.QPixmap(folder + '\\' + img))
        except StopIteration:
            self._timer.stop()

    def stop_auto_trace(self):
        """Function to stop the auto tracer."""

        self._timer.stop()

    def load_images_directory(self):
        """Function that loads the image names from the 'states_images' directory."""

        for filename in sorted(os.listdir(folder), key=lambda f: int(f[5:-4])):
            self.image_names.append(filename)
        print(self.image_names)

        self.ui.nextButton.setDisabled(False)
        self.ui.prevButton.setDisabled(False)
        self.ui.autoTrace.setDisabled(False)
        self.ui.stopAutotrace.setDisabled(False)

    def show_next_image(self):
        """Function to show next image in line."""

        if self.index is None:
            self.index = 0

        img = self.image_names[self.index]
        self.ui.imageLabel.setPixmap(QtGui.QPixmap(folder + '\\' + img))
        self.ui.imagecountLabel.setText(img)
        self.index += 1
        self.index = self.index % len(self.image_names)

    def show_prev_image(self):
        """Function to show previous image in line."""

        self.index -= 1
        self.index = self.index % len(
            self.image_names)  # Using the property og -ve modulo in python.
        img = self.image_names[self.index]
        self.ui.imageLabel.setPixmap(QtGui.QPixmap(folder + '\\' + img))
        self.ui.imagecountLabel.setText(img)

    def reset(self):
        self.ui.outputLabel.setText("Steps/Time")
        self._clear_states_images_folder()
        self._display_initial_text()
        self.index = None
        self.image_names = []
        self.ui.imagecountLabel.setText('Image Count')
        self.ui.nextButton.setDisabled(True)
        self.ui.prevButton.setDisabled(True)
        self.ui.autoTrace.setDisabled(True)
        self.ui.stopAutotrace.setDisabled(True)

    def _clear_states_images_folder(self):
        """Function to clear image folder and reset the instructions on the main screen."""

        files = glob.glob('states_images/**/*.png', recursive=True)
        for f in files:
            try:
                os.remove(f)
            except OSError as e:
                print(f"Error: {f} : {e.strerror}")
        self._display_initial_text()

    def _display_initial_text(self):
        """Function to display initial instructions again."""

        _translate = QtCore.QCoreApplication.translate
        text = '''
        <html><head/><body><p align="justify"><span style=" font-size:12pt; font-weight:600; text-decoration: underline;">Instructions</span>
        <span style=" font-size:12pt; font-weight:600;">:</span>
        </p><p align="justify">1. Choose to run A* or Genetic algorithm at a time.</p>
        <p align="justify">2. When output appears on the top label, then click &lt;Next&gt; button </p>
        <p align="justify">to view the images (for visual tracing) or use &lt;Auto Trace&gt;.</p>
        <p align="justify">NOTE: Check if the folder &lt;states_images&gt; is created or not.</p>
        <p align="justify">3. Click on &lt;RESET&gt; button to clear &lt;states_images&gt; folder.</p>
        <p align="justify">Then run any algorithm again.</p>
        <p align="justify"><span style=" font-weight:600; text-decoration: underline;">Dictionary:</span></p>
        <p align="justify">1. Crossover type - SP (Single point), TP (Two point)</p>
        <p align="justify">2. Parent selection - RS (Rank selection), RWS (Roulette wheel selection)</p>
        <p align="justify">3. Elitism - Y (Yes), N (No)</p><p align="justify">ENJOY THE APP!</p></body></html>
        '''
        self.ui.imageLabel.setText(_translate("MainWindow", text))
Пример #23
0
class GUI(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.addCarriers()
        
        self.thread = Sender()
        
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'), self.showAbout)
        self.connect(self.ui.actionQuit, QtCore.SIGNAL('triggered()'), exit)
        self.connect(self.ui.button, QtCore.SIGNAL('clicked()'), self.toggle)
        self.connect(self.thread, QtCore.SIGNAL("finished()"), self.done)
        self.connect(self.thread, QtCore.SIGNAL("terminated()"), self.done)
        self.connect(self.thread, QtCore.SIGNAL("plusOne()"), self.plusOne)
        self.connect(self.thread, QtCore.SIGNAL("sendingError()"), self.stop)

        self.ui.server.setText('127.0.0.1:25') #set default
        self.ui.message.setPlainText('SPAM!')
        self.ui.statusBar().showMessage('Ready') #broken
        
    
    def toggle(self):
        self.state = self.ui.button.text()
        if self.state == 'Start':
            self.start()
        if self.state == 'Stop':
            self.stop()
            
    def stop(self):
        self.thread.terminate()
        print('stoping')
        self.done()
        
    def done(self):
        self.ui.button.setText('Start')
        self.ui.phone.setEnabled(True)
        self.ui.provider.setEnabled(True)
        self.ui.server.setEnabled(True)
        self.ui.tls.setEnabled(True)
        self.ui.user.setEnabled(True)
        self.ui.password.setEnabled(True)
        self.ui.message.setEnabled(True)
        
    def start(self):
        if self.ui.phone.text() != '' and self.thread.connect(
                            self.ui.server.text(),
                            self.ui.user.text(), 
                            self.ui.password.text(),
                            self.ui.tls.isChecked()
                              ):
            self.ui.button.setText('Stop')
            self.ui.phone.setEnabled(False)
            self.ui.provider.setEnabled(False)
            self.ui.server.setEnabled(False)
            self.ui.tls.setEnabled(False)
            self.ui.user.setEnabled(False)
            self.ui.password.setEnabled(False)
            self.ui.message.setEnabled(False)
            self.ui.lcd.display('0')
            
            print('starting')
            
            
            self.thread.toaddr = self.ui.phone.text() + self.providers[self.ui.provider.currentText()]
            self.thread.msg = self.ui.message.toPlainText()
            
            print('sending to:', self.thread.toaddr)
            
        
        
    def plusOne(self):
        self.ui.lcd.display(str(self.ui.lcd.intValue() + 1))

    def showAbout(self):
        self.about = QtGui.QWidget()
        ui = Ui_About()
        ui.setupUi(self.about)
        ui.Version.setText(str(version))
        self.connect(ui.pushButton, QtCore.SIGNAL('clicked()'),self.about.close)
        self.about.show()
    
    def addCarriers(self):
        '''can get more from
        http://www.emailtextmessages.com/
        '''
        self.providers = {
                          'Alltel':'@message.alltel.com',
                          'AT&T':'@txt.att.net',
                          'Boost Mobile':'@myboostmobile.com',
                          'Metro PCS':'@mymetropcs.com',
                          'Sprint':'@messaging.sprintpcs.com',
                          'T-Mobile':'@tmomail.net',
                          'US Cellular':'@email.uscc.net',
                          'Verizon':'@vtext.com',
                          'Virgin Mobile':'@vmobl.com',
                          'Gmail':'@gmail.com',
                          'Other':''
                          }
        self.ui.provider.addItems(sorted(list(self.providers.keys())))
Пример #24
0
    def __init__(self, preferences, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.preferences = preferences

        # initialize GUI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.lastDirectory = ''

        # load plot plugins
        self.exploratoryPlots = PlotsManager(self.ui.cboExploratoryPlots,
                                             self.ui.plotExploratoryScrollArea,
                                             'Profile scatter plot')
        self.exploratoryPlots.loadPlots(self.preferences,
                                        'plugins/exploratoryPlots/')

        self.statPlots = PlotsManager(self.ui.cboStatPlots,
                                      self.ui.plotStatScrollArea,
                                      'Extended error bar')
        self.statPlots.loadPlots(self.preferences, 'plugins/statPlots/')

        # load statistical technique plugins
        pluginManager = PluginManager(self.preferences)
        self.effectSizeDict = pluginManager.loadPlugins(
            'plugins/effectSizeFilters/')
        pluginManager.populateComboBox(self.effectSizeDict,
                                       self.ui.cboEffectSizeMeasure1,
                                       'Difference between proportions')
        pluginManager.populateComboBox(self.effectSizeDict,
                                       self.ui.cboEffectSizeMeasure2,
                                       'Ratio of proportions')

        self.statTestDict = pluginManager.loadPlugins(
            'plugins/statisticalTests/')
        pluginManager.populateComboBox(self.statTestDict, self.ui.cboStatTests,
                                       'Fisher\'s exact test')

        self.multCompDict = pluginManager.loadPlugins(
            'plugins/multipleComparisonCorrections/')
        pluginManager.populateComboBox(self.multCompDict,
                                       self.ui.cboMultCompMethod,
                                       'No correction')

        self.confIntervMethodDict = pluginManager.loadPlugins(
            'plugins/confidenceIntervalMethods/')
        pluginManager.populateComboBox(self.confIntervMethodDict,
                                       self.ui.cboConfIntervMethods,
                                       'DP: Newcombe-Wilson')

        # initialize class variables
        self.profileTree = ProfileTree()
        self.profile = Profile()
        self.statsTest = StatsTests()
        self.plotWindows = []

        # initialize tables
        self.summaryTable = GenericTable([], [], self)
        self.coverageTable = GenericTable([], [], self)
        self.powerTable = GenericTable([], [], self)

        # connect menu items signals to slots
        self.connect(self.ui.mnuFileOpenProfile, QtCore.SIGNAL('triggered()'),
                     self.loadProfile)
        self.connect(self.ui.mnuFileCreateProfile,
                     QtCore.SIGNAL('triggered()'), self.createProfile)
        self.connect(self.ui.mnuFileAppendCategoryCOG,
                     QtCore.SIGNAL('triggered()'), self.appendCategoriesCOG)
        self.connect(self.ui.mnuFileSavePlot, QtCore.SIGNAL('triggered()'),
                     self.saveImageDlg)
        self.connect(self.ui.mnuFileSaveTable, QtCore.SIGNAL('triggered()'),
                     self.saveTableDlg)
        self.connect(self.ui.mnuFileExit, QtCore.SIGNAL('triggered()'),
                     QtCore.SLOT('close()'))

        self.connect(self.ui.mnuViewSendPlotToWindow,
                     QtCore.SIGNAL('triggered()'), self.sendPlotToWindow)

        self.connect(self.ui.mnuSettingsPreferences,
                     QtCore.SIGNAL('triggered()'), self.prefrencesDlg)

        self.connect(self.ui.mnuHelpAbout, QtCore.SIGNAL('triggered()'),
                     self.openAboutDlg)

        # widget controls in sidebar
        self.connect(self.ui.btnProfileTab, QtCore.SIGNAL('clicked()'),
                     self.profileTabClicked)
        self.connect(self.ui.btnProfileArrow, QtCore.SIGNAL('clicked()'),
                     self.profileTabClicked)
        self.connect(self.ui.btnStatisticsTab, QtCore.SIGNAL('clicked()'),
                     self.statPropTabClicked)
        self.connect(self.ui.btnStatisticsArrow, QtCore.SIGNAL('clicked()'),
                     self.statPropTabClicked)
        self.connect(self.ui.btnFilteringTab, QtCore.SIGNAL('clicked()'),
                     self.filteringTabClicked)
        self.connect(self.ui.btnFilteringArrow, QtCore.SIGNAL('clicked()'),
                     self.filteringTabClicked)

        # connect profile widget signals to slots
        self.connect(self.ui.cboSample1, QtCore.SIGNAL('activated(QString)'),
                     self.hierarchicalLevelsChanged)
        self.connect(self.ui.cboSample2, QtCore.SIGNAL('activated(QString)'),
                     self.hierarchicalLevelsChanged)
        self.connect(self.ui.btnSample1Colour, QtCore.SIGNAL('clicked()'),
                     self.sample1ColourDlg)
        self.connect(self.ui.btnSample2Colour, QtCore.SIGNAL('clicked()'),
                     self.sample2ColourDlg)
        self.connect(self.ui.cboProfileLevel,
                     QtCore.SIGNAL('activated(QString)'),
                     self.profileLevelChanged)
        self.connect(self.ui.cboParentalLevel,
                     QtCore.SIGNAL('activated(QString)'),
                     self.parentLevelChanged)

        # connect statistical test widget signals to slots
        self.connect(self.ui.cboStatTests, QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.cboSignTestType,
                     QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.cboConfIntervMethods,
                     QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.cboNominalCoverage,
                     QtCore.SIGNAL('activated(QString)'),
                     self.statTestPropChanged)
        self.connect(self.ui.btnRunTest, QtCore.SIGNAL('clicked()'),
                     self.runTest)
        self.connect(self.ui.cboMultCompMethod,
                     QtCore.SIGNAL('activated(QString)'),
                     self.multCompCorrectionChanged)
        self.connect(self.ui.btnMultCompCorrectionInfo,
                     QtCore.SIGNAL('clicked()'), self.multCompCorrectionInfo)

        # connect filtering test widget signals to slots
        self.connect(self.ui.chkSelectFeatures, QtCore.SIGNAL('toggled(bool)'),
                     self.selectFeaturesCheckbox)
        self.connect(self.ui.btnSelectFeatures, QtCore.SIGNAL('clicked()'),
                     self.selectFeaturesDlg)

        self.connect(self.ui.chkEnableSignLevelFilter,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.spinSignLevelFilter,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)

        self.connect(self.ui.cboSeqFilter, QtCore.SIGNAL('activated(QString)'),
                     self.seqFilterChanged)
        self.connect(self.ui.chkEnableSeqFilter,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.spinFilterSample1,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.spinFilterSample2,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)

        self.connect(self.ui.cboParentSeqFilter,
                     QtCore.SIGNAL('activated(QString)'),
                     self.parentSeqFilterChanged)
        self.connect(self.ui.chkEnableParentSeqFilter,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.spinParentFilterSample1,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.spinParentFilterSample2,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)

        self.connect(self.ui.radioOR, QtCore.SIGNAL('clicked()'),
                     self.filteringPropChanged)
        self.connect(self.ui.radioAND, QtCore.SIGNAL('clicked()'),
                     self.filteringPropChanged)

        self.connect(self.ui.cboEffectSizeMeasure1,
                     QtCore.SIGNAL('activated(QString)'),
                     self.changeEffectSizeMeasure)
        self.connect(self.ui.cboEffectSizeMeasure2,
                     QtCore.SIGNAL('activated(QString)'),
                     self.changeEffectSizeMeasure)
        self.connect(self.ui.spinMinEffectSize1,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.spinMinEffectSize2,
                     QtCore.SIGNAL('valueChanged(QString)'),
                     self.filteringPropChanged)
        self.connect(self.ui.chkEnableEffectSizeFilter1,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)
        self.connect(self.ui.chkEnableEffectSizeFilter2,
                     QtCore.SIGNAL('toggled(bool)'), self.filteringPropChanged)

        self.connect(self.ui.btnApplyFilters, QtCore.SIGNAL('clicked()'),
                     self.applyFilters)

        # connect exploratory plot page widget signals to slots
        self.connect(self.ui.cboExploratoryPlots,
                     QtCore.SIGNAL('activated(QString)'),
                     self.exploratoryPlotUpdate)
        self.connect(self.ui.btnExploratoryConfigurePlot,
                     QtCore.SIGNAL('clicked()'), self.exploratoryPlotConfigure)

        # connect statistical plot page widget signals to slots
        self.connect(self.ui.cboStatPlots, QtCore.SIGNAL('activated(QString)'),
                     self.statPlotUpdate)
        self.connect(self.ui.btnStatConfigurePlot, QtCore.SIGNAL('clicked()'),
                     self.statPlotConfigure)
        self.connect(self.ui.cboHighlightHierarchyExploratory,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightHierarchyExploratoryChanged)
        self.connect(self.ui.cboHighlightFeatureExploratory,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightFeatureExploratoryChanged)
        self.connect(self.ui.cboHighlightHierarchyStats,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightHierarchyStatsChanged)
        self.connect(self.ui.cboHighlightFeatureStats,
                     QtCore.SIGNAL('activated(QString)'),
                     self.highlightFeatureStatsChanged)

        # connect paired profile page widget signals to slots
        self.connect(self.ui.chkShowActiveFeatures,
                     QtCore.SIGNAL('toggled(bool)'), self.populateSummaryTable)

        # connect CI coverage page widget signals to slots
        self.connect(self.ui.btnConfIntervCoverage, QtCore.SIGNAL('clicked()'),
                     self.confIntervCoverage)

        # connect CI coverage page widget signals to slots
        self.connect(self.ui.btnPowerTest, QtCore.SIGNAL('clicked()'),
                     self.powerTest)

        # initialize dynamic GUI elements
        self.seqFilterChanged()
        self.parentSeqFilterChanged()
        self.setSample1Colour(self.preferences['Sample 1 colour'])
        self.setSample2Colour(self.preferences['Sample 2 colour'])

        # show window maximized
        self.resize(1100, 700)
        self.showMaximized()
Пример #25
0
#!/usr/bin/env python3
from mainUI import Ui_MainWindow
from adapter import Adapter
from PyQt5 import QtCore, QtGui, QtWidgets
from dataframe import Dataframe
import sys
sys.path.append("...")


class Main:
    def __init__(self):
        self.datalogger_filepath = None


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
Пример #26
0
class Mapper(QtGui.QMainWindow):
	
	# working map objects by createMap
	draw = None			# imageDraw, to draw decorations on
	completeMap = None	# PIL Image
	
	# copy of the map image (by createMap)
	backupMap = None
	
	# map objects for drawing on QGraphicsView (by drawMapOnCanvas)
	imgQ = None		# QtGui.QPixmap
	scene = None	# QtGui.QGraphicsScene
	
	# sizes of map image (by createMap)
	imgHeight = 0
	imgWidth = 0
	mapWidthMeters = 0
	pixelsPerMeter = 0
	#upperLeftLat = upperLeftLon = 0
	#upperRightLat = upperRightLon = 0
	#bottomLeftLat = bottomLeftLon = 0
	mapCenterX = mapCenterY = 0
	
	upperLeftX = 0
	upperleftY = 0
	actualZoom = 0
	
	# points database
	points = []
	tracks = []
	
	pointsListValid = True
	
	selectionRect = None
	selectionLine = None
	selectionText = None

	# Converts a gps coordinate couple into the xy coordinate of
	# the OSM tile it is on.
	def deg2num(self, lat_deg, lon_deg, zoom):
		lat_rad = math.radians(lat_deg)
		n = 2.0 ** zoom
		xtile = float((lon_deg + 180.0) / 360.0 * n)
		ytile = float((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
		return (xtile, ytile)

	# Calculates the NW gps coordinate of an xy OSM tile
	def num2deg(self, xtile, ytile, zoom):
		n = 2.0 ** zoom
		lon_deg = xtile / n * 360.0 - 180.0
		lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
		lat_deg = math.degrees(lat_rad)
		return (lat_deg, lon_deg)

	# Calculates the position in pixel on the current drawn map
	# of the passed coordinates
	def gpsToXY(self, lat, lon):
		xPos, yPos = self.deg2num(lat, lon, self.actualZoom)
		tileWidth = tileHeight = 256.0
		dotX = (xPos - float(self.upperLeftX))*tileWidth
		dotY = (yPos - float(self.upperLeftY))*tileHeight
		return dotX, dotY
	
	# Calculates the gps coordinates of the pixel xy in the 
	# currently drawn map
	def xyToGps(self, x, y):
		xPos = x / 256.0 + self.upperLeftX
		yPos = y / 256.0 + self.upperLeftY	
		lat, lon = self.num2deg(xPos, yPos, self.actualZoom)
		return lat, lon

	# Returns the OSM tile containing the passed gps
	# coordinate
	def getTile(self, lat, lon, zoom, xshift=0, yshift=0):
		(x, y) = self.deg2num(lat, lon, zoom)		
		return self.getTileXY(x, y, zoom, xshift, yshift)
	
	# Returns the OSM tile indicated by the xy coordinates
	# - if the tile was already cached on disk, serve the cached copy
	# - if the tile was not cached, download it
	# - if can't download, return a black square
	def getTileXY(self, x, y, zoom, xshift=0, yshift=0):
		imUrl = "http://tile.openstreetmap.org/%i/%i/%i.png"%(zoom, x+xshift, y+yshift)

		fileName = "%i-%i-%i.png"%(zoom, x+xshift, y+yshift)
		fileName = os.path.join("tmp", fileName)

		if os.path.exists(fileName):
			
			# open existing file
			dataSource = open(fileName, "rb")
			dataSourceContent = dataSource.read()
			imRead = cStringIO.StringIO(dataSourceContent)
			dataSource.close()
			
		else:
			
			try:
				# retrieve tile from tile server
				print "Downloading tile..."
				dataSource = urllib2.urlopen(imUrl)
				dataSourceContent = dataSource.read()
				imRead = cStringIO.StringIO(dataSourceContent)
				dataSource.close()
			except Exception as errorDesc:
				print "Unexpected error while downloading tile from %s: %s"%(imUrl, errorDesc)
				return PIL.Image.new('RGBA', (256, 256), (0, 0, 0, 0)) 
			
			# cache tile for future use
			cacheImage = open(fileName, "wb")
			cacheImage.write(dataSourceContent)
			cacheImage.close()
		
		return PIL.Image.open(imRead)
		

	def __init__(self, parent=None, zoom=None, lat=None, lon=None):
		QtGui.QMainWindow.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		
		self.points = []
		self.tracks = []

		if (zoom):
			self.ui.mapZoom.setValue(zoom)
		if (lat):
			self.ui.mapLat.setValue(lat)
		if (lon):
			self.ui.mapLon.setValue(lon)
		
		# managing upper right UI section (map initialization parameters)
		QtCore.QObject.connect(self.ui.button_rebuild, QtCore.SIGNAL("clicked()"), self.createMapButton)
		QtCore.QObject.connect(self.ui.button_center, QtCore.SIGNAL("clicked()"), self.center)
		QtCore.QObject.connect(self.ui.saveFileButton, QtCore.SIGNAL("clicked()"), self.saveToFile)
		
		# manage points list
		QtCore.QObject.connect(self.ui.button_delete_point, QtCore.SIGNAL("clicked()"), self.deleteSelectedPoint)
		QtCore.QObject.connect(self.ui.button_new_point, QtCore.SIGNAL("clicked()"), self.openNewPointWindow)
		QtCore.QObject.connect(self.ui.button_new_track, QtCore.SIGNAL("clicked()"), self.openNewTrackWindow)
		QtCore.QObject.connect(self.ui.pointsList, QtCore.SIGNAL("itemSelectionChanged()"), self.centerOnSelectedPoint)	
		QtCore.QObject.connect(self.ui.pointsList, QtCore.SIGNAL("itemClicked(QTreeWidgetItem*,int)"), self.itemChangedOnPointsList)	

		self.ui.pointsList.setColumnWidth(0, 100)
		self.ui.pointsList.setColumnWidth(1, 80)
		self.ui.pointsList.setColumnWidth(2, 80)
		self.ui.pointsList.setColumnWidth(3, 30)
		
		# manage zoom buttons
		QtCore.QObject.connect(self.ui.map_zoom_down, QtCore.SIGNAL("clicked()"), self.zoomDown)
		QtCore.QObject.connect(self.ui.map_zoom_up, QtCore.SIGNAL("clicked()"), self.zoomUp)
		
		QtCore.QObject.connect(self, QtCore.SIGNAL("centerUI()"), self.center)
		
		# triggers first map redraw (with default 
		# position and zoom, as set by UI)
		self.createMapButton()
		self.updatePointsList()

	def createMapButton(self):		
		lat = self.ui.mapLat.value()
		lon = self.ui.mapLon.value()
		zoom = self.ui.mapZoom.value()
		
		self.createMap(lat, lon, zoom)
		
		# delete previous "_center_" marker
		self.deletePointByID("_center_")
		# draw "_center_" position
		self.addPoint(Point("_center_", lat, lon, 'red'))
		
		#track = Track("prova")
		#track.addPoint(Point("one", 42.355900, 10.930400, "red"))
		#track.addPoint(Point("two", 42.355800, 10.930700, "red"))
		#track.addPoint(Point("three", 42.355600, 10.920400, "red"))
		#self.addTrack(track)
		
		self.refresh()

	def createMap(self, lat, lon, zoom):
		x, y = self.deg2num(lat, lon, zoom)
		self.createMapXY(x, y, zoom)
		self.mapCenterX, self.mapCenterY = self.gpsToXY(lat, lon)
	
	def createMapXY(self, x, y, zoom):
		# salvataggio parametri mappa
		self.upperLeftX = int(x-1)
		self.upperLeftY = int(y-1)
		self.actualZoom = zoom
		
		#centerLat, centerLon = self.num2deg(x+1, y+0.5, zoom)
		#print "Centro geometrico mappa: %.3f, %.3f"%(centerLat, centerLon)

		# limiti mappa (in radianti) per calcolo larghezza
		upperLeftLat, upperLeftLon = self.num2deg(x-1, y-1, zoom)
		upperLeftLatRad = math.radians(upperLeftLat)
		upperLeftLonRad = math.radians(upperLeftLon)
		
		upperRightLat, upperRightLon = self.num2deg(x+3, y-1, zoom)
		upperRightLatRad = math.radians(upperRightLat)
		upperRightLonRad = math.radians(upperRightLon)
		
		# calcolo larghezza mappa in metri
		e = math.acos(math.sin(upperLeftLatRad)*math.sin(upperRightLatRad) + math.cos(upperLeftLatRad)*math.cos(upperRightLatRad)*math.cos(upperRightLonRad-upperLeftLonRad))
		self.mapWidthMeters =  e*6378.137*1000
		self.ui.map_width.setText("%.2f Km"%(self.mapWidthMeters/1000.0))
	
		# recupero tiles da openstreetmap
		self.ui.statusbar.showMessage("Downloading tiles from OpenStreetMap.org...")
		
		progress = QProgressDialog("Downloading tiles from OpenStreetMap.org...", "Abort", 0, 12, self)
		progress.setWindowModality(Qt.WindowModal)
		progress.setMinimumDuration = 0
		
		i = 0
		tiles = []
		for deltaX in range(-1,3):
			for deltaY in range(-1,2):
			
				progress.setValue(i)
			
				tiles.append(self.getTileXY(x+deltaX, y+deltaY, zoom))
				i = i + 1
		
		progress.setValue(12);
		
		self.ui.statusbar.showMessage("Tiles downloaded from OpenStreetMap.org")
		
		# creazione immagine contenitore
		biggerIm = PIL.Image.new("RGB", (256*4,256*3))
		
		# aggiunta tiles al contenitore
		row = 0
		col = 0
		for tile in tiles:
			biggerIm.paste(tile, (256*col, 256*row))
			row = row + 1
			if (row>2):
				row = 0
				col = col + 1	

		# oggetto su cui disegnare
		self.draw = ImageDraw.Draw(biggerIm)
		self.completeMap = biggerIm
		
		self.backupMap = biggerIm.copy()
	
		# salvataggio informazioni mappa
		self.imgWidth, self.imgHeight = biggerIm.size 
		if (self.mapWidthMeters != 0):
			self.pixelsPerMeter = float(self.imgWidth) / float(self.mapWidthMeters)
			self.ui.map_resolution.setText("%.2f m/px"%(1.0 / self.pixelsPerMeter))

	def recreateDrawings(self):
		self.clear()
		
		rectWidth = 2
		pen = QPen(QtCore.Qt.red, 2, QtCore.Qt.SolidLine)
		
		for point in self.points:
		
			if (point.visible() == False): continue
		
			dotX, dotY = self.gpsToXY(point.lat(), point.lon())
			
			if (dotX >= 4*256 or dotX <= 0 or dotY >= 3*256 or dotY <= 0): continue;
			
			#self.draw.ellipse(
			#	[dotX-rectWidth, dotY-rectWidth, dotX+rectWidth, dotY+rectWidth], 
			#	fill=point.color()
			#)
			
			ellipse = self.scene.addEllipse(dotX-rectWidth, dotY-rectWidth, 2*rectWidth, 2*rectWidth, pen)
			ellipse.setToolTip("%s\n%f - %f"%(point.name(), point.lat(), point.lon()))
	
		for track in self.tracks:
		
			if (track.visible() == False): continue
		
			prevX = -1
			prevY = -1
			
			for point in track.points():
				
				if (point.visible() == False): continue
			
				dotX, dotY = self.gpsToXY(point.lat(), point.lon())
				
				if (dotX >= 4*256 or dotX <= 0 or dotY >= 3*256 or dotY <= 0): continue;
				
				#self.draw.ellipse(
				#	[dotX-rectWidth, dotY-rectWidth, dotX+rectWidth, dotY+rectWidth], 
				#	fill=point.color()
				#)
				
				ellipse = self.scene.addEllipse(dotX-rectWidth, dotY-rectWidth, 2*rectWidth, 2*rectWidth, pen)
				ellipse.setToolTip("Track: %s\nPoint: %s\nLat: %f - Lon: %f"%(track.name(), point.name(), point.lat(), point.lon()))
				
				if (prevX != -1 and prevY != -1):
					self.scene.addLine(prevX, prevY, dotX, dotY)
				
				prevX = dotX
				prevY = dotY
				

		# draw image geometrical center
		# self.draw.ellipse([self.imgWidth/2-3, self.imgHeight/2-3, self.imgWidth/2+3, self.imgHeight/2+3], fill="green")

	def drawMapOnCanvas(self):	
		self.imgQ = ImageQt.ImageQt(self.completeMap)  # we need to hold reference to imgQ, or it will crash
		pixMap = QtGui.QPixmap.fromImage(self.imgQ)
		#pixMap = pixMap.scaled(100, 100, QtCore.Qt.KeepAspectRatio)
	
		self.scene = QScene(self)
		self.scene.addPixmap( pixMap )
		self.ui.graphicsView.setScene(self.scene)

	def refresh(self):
	
		# creates a scene with the downloaded map
		# and draws it on the UI
		self.drawMapOnCanvas()
	
		# recreates points and tracks on the scene
		self.recreateDrawings()
		
		# ir required updates points listing
		if (self.pointsListValid == False):
			self.updatePointsList()
			self.pointsListValid = True

	def itemChangedOnPointsList(self, item, column):
		# checks just status of column 3 (visible flag)
		if (column != 3): return
		if (item):
			nodeName = item.text(0)
			
			# not a track
			if (item.childCount() == 0): 
			
				# a point belonging to a track
				if (item.parent()):
				
					trackItem = item.parent()
					trackName = trackItem.text(0)
					
					track = self.getTrackByID(trackName)
					
					if (track):
						
						point = track.getPointByID(nodeName)
						
						if (point):
							
							actualState = point.visible()
							newState = item.checkState(3)
							if (newState == Qt.Checked):
								newState = True
							else:
								newState = False
							
							if (newState != actualState):
								point.setVisible(newState)
								self.pointsListValid = False
								self.refresh()
					
				# a point not belonging to a track
				else:
					point = self.getPointByID(nodeName)
					
					if (point):
						
						actualState = point.visible()
						newState = item.checkState(3)
						if (newState == Qt.Checked):
							newState = True
						else:
							newState = False
						
						if (newState != actualState):
							point.setVisible(newState)
							self.pointsListValid = False
							self.refresh()
			
			# a track
			else:	
				track = self.getTrackByID(nodeName)
				
				if (track):

						actualState = track.visible()
						newState = item.checkState(3)
						if (newState == Qt.Checked):
							newState = True
						else:
							newState = False
						
						if (newState != actualState):
							track.setVisible(newState)
							self.pointsListValid = False
							self.refresh()				
	
	def zoomDown(self):
		if (self.ui.mapZoom.value() < 17):
			self.ui.mapZoom.setValue(self.ui.mapZoom.value()+1)
			self.createMapButton()
	def zoomUp(self):
		if (self.ui.mapZoom.value() > 1):
			self.ui.mapZoom.setValue(self.ui.mapZoom.value()-1)
			self.createMapButton()
	
	# performed when a point is doubleclicked in the map
	# sets the point coordinates in the upper right fields in the ui, 
	# and rebuilds the map
	def doubleClickOnGraphics(self, event):
		
		newX = event.scenePos().x()
		newY = event.scenePos().y()
		lat, lon = self.xyToGps(newX, newY)
		
		self.ui.mapLat.setValue(lat)
		self.ui.mapLon.setValue(lon)
		self.createMapButton()
		
		self.center()
	
	def center(self):
		self.ui.graphicsView.centerOn(QPointF(self.mapCenterX, self.mapCenterY))
		print "centering on %i x %i"%(self.mapCenterX, self.mapCenterY)
	
	def centerCoords(self, lat, lon):
		dotX, dotY = self.gpsToXY(lat, lon)
		self.ui.graphicsView.centerOn(QPointF(dotX, dotY))
		
		try:
			if (self.selectionRect):
				self.scene.removeItem(self.selectionRect)
		except:
			pass

		try:
			if (self.selectionLine):
				self.scene.removeItem(self.selectionLine)
		except:
			pass

		try:
			if (self.selectionText):
				self.scene.removeItem(self.selectionText)
		except:
			pass
	
		pen = QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
		self.selectionRect = self.scene.addRect(dotX-7, dotY-7, 14, 14, pen)
		self.selectionLine = self.scene.addLine(dotX+7, dotY-7, dotX+5+20, dotY-5-20, pen)
		self.selectionText = self.scene.addSimpleText("%.5f, %.5f"%(lat, lon))
		self.selectionText.setPos(dotX+5+24, dotY-5-20-10)

	def centerOnSelectedPoint(self):
		currentSelectedPoint = self.ui.pointsList.currentItem()
		
		if (currentSelectedPoint):
			if (currentSelectedPoint.childCount() == 0):
				try:
					pointLat = float(currentSelectedPoint.text(1))		
					pointLon = float(currentSelectedPoint.text(2))	

					dotX, dotY = self.gpsToXY(pointLat, pointLon)
					if (dotX >= 4*256 or dotX <= 0 or dotY >= 3*256 or dotY <= 0): 
						pass
					else:
						self.centerCoords(pointLat, pointLon)
				except:
					pass
			
	def deleteSelectedPoint(self):
		currentSelectedPoint = self.ui.pointsList.currentItem()
		if (currentSelectedPoint):
		
			# a point
			if (currentSelectedPoint.childCount() == 0 and currentSelectedPoint.text(1) != None):
				
				pointID = currentSelectedPoint.text(0)
				
				# a point in a track
				if (currentSelectedPoint.parent()):				
					track = self.getTrackByID(currentSelectedPoint.parent().text(0))
					if (track):	
						track.deletePointByID(pointID)						
				
				# a root point
				else:		
					remainingPoints = []
					for point in self.points:
						if (point.name() != pointID):
							remainingPoints.append(point)
					
					self.points = remainingPoints
			
				self.pointsListValid = False
				self.refresh()
			
			# maybe a track?
			else:
				trackID = currentSelectedPoint.text(0)
				
				remainingTracks = []
				for track in self.tracks:
					if (track.name() != trackID):
						remainingTracks.append(track)
				
				self.tracks = remainingTracks
			
				self.pointsListValid = False
				self.refresh()					

	def clear(self):		
		#print "Clearing drawings over image..."
		del self.completeMap
		del self.draw
		self.completeMap = self.backupMap.copy()
		self.draw = ImageDraw.Draw(self.completeMap)	
	
	def saveToFile(self, filename = None):
		if (filename == None):
			filename = QtGui.QFileDialog.getSaveFileName(None, "Nome immagine", "", "Image Files (*.png)")
			filename = filename[0]

		if (len(filename) == 0):
			return
		
		outputimg = QtGui.QPixmap(self.ui.graphicsView.viewport().width(), self.ui.graphicsView.viewport().height())
		painter = QtGui.QPainter(outputimg)
		
		targetrect = sourcerect = self.ui.graphicsView.viewport().rect()
		
		self.ui.graphicsView.render(painter, targetrect, sourcerect)
		outputimg.save(filename, "PNG")

		painter.end()	
	
	
	def updatePointsList(self):	
		self.ui.pointsList.clear()
		
		first = True
		firstElement = None

		for point in self.points:
		
 			newElement = QtGui.QTreeWidgetItem(None)
			newElement.setText(0, point.name())
			newElement.setText(1, "%.8f"%point.lat())
			newElement.setText(2, "%.8f"%point.lon())
			
			if (point.visible()):
				newElement.setCheckState(3, Qt.Checked)
			else:
				newElement.setCheckState(3, Qt.Unchecked)
			
			self.ui.pointsList.addTopLevelItem(newElement)
			
			if (first == True):	
				firstElement = newElement
				first = False
		
		for track in self.tracks:
			
			trackName = track.name()
			trackNode = QtGui.QTreeWidgetItem(None)
			trackNode.setText(0, trackName)
			
			if (track.visible() == False):
				trackNode.setCheckState(3, Qt.Unchecked)
			else:
				trackNode.setCheckState(3, Qt.Checked)
			
			self.ui.pointsList.addTopLevelItem(trackNode)
			trackNode.setToolTip(0, "Points in track: %i"%len(track.points()))
			
			for point in track.points():
			
				newElement = QtGui.QTreeWidgetItem(trackNode)
				newElement.setText(0, point.name())
				newElement.setText(1, "%.8f"%point.lat())
				newElement.setText(2, "%.8f"%point.lon())

				if (point.visible()):
					newElement.setCheckState(3, Qt.Checked)
				else:
					newElement.setCheckState(3, Qt.Unchecked)
				
				self.ui.pointsList.addTopLevelItem(newElement)				
		
		if (firstElement):
			self.ui.pointsList.setCurrentItem(firstElement)	
	

	def openNewPointWindow(self):
	
		track = None

		# if a track is currently selected, add it the new point
		currentSelectedPoint = self.ui.pointsList.currentItem()
		
		if (currentSelectedPoint):
			# a point (not a track)
			if (currentSelectedPoint.childCount() > 0 or currentSelectedPoint.text(1) != None):				
				track = self.getTrackByID(currentSelectedPoint.text(0))

		self.newPointWindow = NewPointDialog(self, track)
		
		self.newPointWindow.exec_()

	def openNewTrackWindow(self):
		self.newTrackWindow = NewTrackDialog(self)
		self.newTrackWindow.exec_()

	def addPoint(self, point):
		if (self.getPointByID(point.name())):
			return 1
		else:
			self.points.append(point)
			self.pointsListValid = False
			return 0

	def addTrack(self, track):
		if (self.getTrackByID(track.name())):
			return 1
		else:
			self.tracks.append(track)
			self.pointsListValid = False
			return 0
	
	def deletePointByID(self, id):
		survivingPoints = []
		
		for point in self.points:
			if (point.name() != id):
				survivingPoints.append(point)

		self.points = survivingPoints
		self.pointsListValid = False
	
	def getTrackByID(self, id):	
		for track in self.tracks:
			if (track.name() == id):
				return track
		
		return None

	def getPointByID(self, id):	
		for point in self.points:
			if (point.name() == id):
				return point
		
		return None