Beispiel #1
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton_2, QtCore.SIGNAL("clicked()"), self.on_first_clicked )
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.on_second_clicked)
        QtCore.QObject.connect(self.ui.pushButton_3, QtCore.SIGNAL("clicked()"), self.on_merge_clicked)
     
    def on_first_clicked(self):
        File1 = QtGui.QFileDialog.getOpenFileName();
        self.ui.lineEdit_2.setText(File1)

    def on_second_clicked(self):
        File2 = QtGui.QFileDialog.getOpenFileName();
        self.ui.lineEdit.setText(File2)

    def on_merge_clicked(self):
        File1 = self.ui.lineEdit_2.text()
        File2 = self.ui.lineEdit.text()
        if File1 and File2:
            merge(File1, File2)
        else:
            print('specify a file')

    def add_entry(self):
        self.ui.lineEdit.selectAll()
        self.ui.lineEdit.cut()
        self.ui.textEdit.append("")
        self.ui.textEdit.paste()
Beispiel #2
0
class AppWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(AppWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.initialize_UI()
        self.ui.search_toggle_cbox.currentIndexChanged.connect(
            self.toggle_search)
        self.show()

    def initialize_UI(self):
        """
            Initialze the ui and add basic functionality like:
            hide student reg number spinBox at startup.
            close buttons.
            toggle between stackedWidget pages.
            ...
        """
        self.ui.stdreg_number.hide()
        self.ui.stackedWidget.setCurrentIndex(0)
        self.ui.exit_btn.clicked.connect(self.close)
        self.ui.exit_btn_2.clicked.connect(self.close)
        self.ui.manage_btn.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(1))
        self.ui.main_btn.clicked.connect(
            lambda: self.ui.stackedWidget.setCurrentIndex(0))

    def toggle_search(self):
        if self.ui.search_toggle_cbox.currentIndex() == 1:
            self.ui.fname_edit.hide()
            self.ui.stdreg_number.show()
        else:
            self.ui.fname_edit.show()
            self.ui.stdreg_number.hide()
Beispiel #3
0
class ControlMainWindow(QtGui.QMainWindow):
	def __init__(self, parent=None):
		super(ControlMainWindow, self).__init__(parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
	def customSetUp(self):
		initialize_map()

		table = self.ui.mainboard
		table.setRowCount(upper_limit_x())
		table.setColumnCount(upper_limit_y())
	 	table.setHorizontalHeaderLabels(('0', '1', '2' , '3' , '4' ,'5'))
		table.setVerticalHeaderLabels(('0', '1', '2' , '3' , '4' ,'5'))
		table.cellClicked.connect(handleTableClick)
		#(y,x)
		#table.setItem(origin.y, origin.x, QtGui.QTableWidgetItem())
		#table.item(origin.y, origin.x).setBackground(QtGui.QColor(100,100,150))
		#table.setItem(finish.y, finish.x, QtGui.QTableWidgetItem())
		#table.item(finish.y, finish.x).setBackground(QtGui.QColor(100,100,150))
		self.ui.solveButton.clicked.connect(start_a_star)
		self.ui.cleanButton.clicked.connect(action_clean_board)
		self.ui.randomButton.clicked.connect(create_random_map)
		QtCore.QObject.connect(self.ui.aboutASTAR, QtCore.SIGNAL('triggered()'), action_about_a_star)
		QtCore.QObject.connect(self.ui.actionNewMap, QtCore.SIGNAL('triggered()'), action_new_map)

		clean_board()
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.plot_btn.clicked.connect(self.open_plot)
        self.ui.square_btn.clicked.connect(self.show_square)
        self.dialog = 0

    def open_plot(self):
        self.dialog = PlotWindow(-2, 8.3, original_func,
                                 int(self.ui.num_count.text()) or 100)
        self.dialog.show()

    def show_square(self):
        mont = MonteCarlo(-2, 8.3, original_func,
                          int(self.ui.num_count.text()) or 100)
        monts = [
            MonteCarlo(-2, 8.3, original_func,
                       int(self.ui.num_count.text()) or 100)
            for i in range(int(self.ui.iterations_count.text()))
        ]
        values = []
        for i in monts:
            i.generate_points()
            values.append(i.square())
        square = sum(values) / len(values)
        self.ui.square.setText(f'Sрасч = {square}')
        self.ui.error.setText(
            str(round(abs((square - 38.7925786761) / 38.7925786761) *
                      100, 3)) + '%')
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.run_even.clicked.connect(self.form_even_sequence)
        self.ui.save_to_file.clicked.connect(self.save_to_file)
        self.ui.even_list.setReadOnly(True)

    def form_even_sequence(self):
        self.ui.even_list.clear()
        a = float(self.ui.a_even.text())
        b = float(self.ui.b_even.text())
        accuracy = float(self.ui.accurancy_even.text())
        number_count = int(self.ui.number_count_even.text())

        even = distr.Even(a, b, accuracy, number_count)
        if even.distribute():
            self.ui.even_list.setText('\n'.join(map(to_str, even.sequence)))
            self.ui.m_pract.setText(str(even.get_exp_value()))
            self.ui.m_theor.setText(str(even.exp_value_theor))
            self.ui.m_theor.setText(str(even.exp_value_theor))
            self.ui.dispertion.setText(str(even.dispersion))

        else:
            self.ui.even_list.setText(even.error_message)

    def save_to_file(self):
        file = open('output.txt', 'w')
        file.write(self.ui.even_list.toPlainText())
        file.close()
class Main(QtWidgets.QMainWindow):
    def __init__(self):
        super(Main, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.submit_button.clicked.connect(self.submit_func)
        self.ui.reset_button.clicked.connect(self.reset_func)
        self.ui.show_help_button.clicked.connect(self.show_help_func)
        self.ui.MainWindow.setWindowTitle(last_name)

    def submit_func(self):
        text = self.ui.lineEdit.text()
        config.set("settings", "last_name", text)
        with open("config.ini", 'w') as config_file:
            config.write(config_file)
        self.ui.MainWindow.setWindowTitle(text)

    def reset_func(self):
        self.ui.MainWindow.setWindowTitle('Discord custom game activity')
        self.ui.lineEdit.setText('')

    def show_help_func(self):
        # messageBox = QtWidgets.QMessageBox()
        # ok = messageBox.question(
        #     self, f"How to use.\nEnter custom game name in the text area and click Submit\nThen change game activity in discord to the selected name.\nThat's all!")
        # if ok == QtWidgets.QMessageBox.Yes:
        #     pass
        messageBox = QtWidgets.QMessageBox()
        ok = messageBox.question(self, f'Delete')
        if ok == QtWidgets.QMessageBox.Yes:
            pass
Beispiel #7
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.train)
        self.ui.pushButton_2.clicked.connect(self.choose_file)
        self.ui.plainTextEdit_2.setFont(QtGui.QFont('Arial', 8))
        self.ui.plainTextEdit.setFont(QtGui.QFont('Arial', 14))

    def train(self):
        filename = self.ui.plainTextEdit_2.toPlainText()
        iters = int(self.ui.plainTextEdit.toPlainText())

        X, Y = read_file(filename)
        if len(X) > 1000:
            size = 8
        else:
            size = math.ceil(np.sqrt(5 * np.sqrt(len(X))))

        som = SOM(X, neuron_size=[size, size], iters=iters)

        som.update_weights(X, Y)
        plot_feature_map(som.get_feature_map())

    def choose_file(self):
        options = QtWidgets.QFileDialog.Options()  # 開啟選單
        options |= QtWidgets.QFileDialog.DontUseNativeDialog  # 使用非本機Dialog
        filename, filetype = QtWidgets.QFileDialog.getOpenFileName(
            self,
            "Choosing file...",
            "./",
            "All Files (*);;Python Files (*.py)",
            options=options)  # 參數1:Dialog Title, 參數2:起始路徑 ,參數3:檔案類型
        self.ui.plainTextEdit_2.setPlainText(filename)
Beispiel #8
0
class MyApp(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(486, 433)

        with open('data.txt') as f:
            for row in f:
                self.ui.listWidget.addItems([row.strip()])

        self.ui.pushButton.clicked.connect(self.add)
        self.ui.lineEdit.returnPressed.connect(self.add)
        self.ui.listWidget.itemDoubleClicked.connect(self.remove)

    def add(self):
        print("Neuer Eintrag")
        self.ui.listWidget.addItems([self.ui.lineEdit.text()])
        self.ui.lineEdit.setText("")

        self.update_file()

    def remove(self, item):
        self.ui.listWidget.takeItem(self.ui.listWidget.row(item))
        self.update_file()

    def update_file(self):
        with open('data.txt', "w") as f:
            for x in range(self.ui.listWidget.count()):
                f.write(self.ui.listWidget.item(x).text() + "\n")
Beispiel #9
0
class principal(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.ventana = Ui_MainWindow()
        self.ventana.setupUi(self)

        command = 'systemctl is-active firewalld.service'
        serviceStatus = os.system(command)

        if serviceStatus == 0:
            self.ventana.label_2.setText("<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">Activado</span></p></body></html>")
            self.ventana.pushButton.setText("Desactivar")

        self.connect(self.ventana.pushButton, QtCore.SIGNAL('clicked()'), self.switch)

    def switch(self):

        command = 'systemctl is-active firewalld.service'
        serviceStatus = os.system(command)

        if serviceStatus == 0:
            os.system('beesu systemctl stop firewalld.service')
            self.ventana.label_2.setText("<html><head/><body><p><span style=\" font-size:12pt; font-weight:600; color:#FF0000\">Desactivado</span></p></body></html>")
            self.ventana.pushButton.setText("Activar")
        elif serviceStatus == 768:
            os.system('beesu systemctl start firewalld.service')
            self.ventana.label_2.setText("<html><head/><body><p><span style=\" font-size:12pt; font-weight:600;\">Activado</span></p></body></html>")
            self.ventana.pushButton.setText("Desactivar")
Beispiel #10
0
class Window(QtGui.QMainWindow):
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		# buttons
		self.ui.updateBN.clicked.connect(self.updateValues)
		# self.ui.eStopBN.clicked.connect()
		# scroll bar
		self.ui.speedBar.setMinimum(0)
		self.ui.speedBar.setMaximum(100)
		self.ui.speedBar.sliderMoved.connect(self.updateSpeedLB)
		self.ui.speedBar.sliderReleased.connect(self.updateSpeedLB)
		# rotation
		self.ui.cwBN.setEnabled(False)
		self.ui.cwBN.clicked.connect(self.changeRotation)
		self.ui.ccwBN.clicked.connect(self.changeRotation)
	
	def updateValues(self):
		self.updateSpeedLB()

	def updateSpeedLB(self):
		# updates value to label beside bar on release
		self.ui.label.setText("Motor Speed: " + str(self.ui.speedBar.value())+ "%")

	def changeRotation(self):
		if self.ui.cwBN.isEnabled():
			self.ui.cwBN.setEnabled(False)
			self.ui.ccwBN.setEnabled(True)
		else:
			self.ui.cwBN.setEnabled(True)
			self.ui.ccwBN.setEnabled(False)
Beispiel #11
0
def main():
    global ui
    global MainWindow
    global Ui_MainWindow

    #pid = win32api.GetCurrentProcessId()
    #print(pid,"<----Process ID")
    #handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
    #win32process.SetPriorityClass(handle, win32process.HIGH_PRIORITY_CLASS)

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    dimCameraLiink = "rtsp://*****:*****@10.152.235.180"
    ocrCameraLink = "rtsp://*****:*****@10.152.235.184/ch1-s1?tcp"  #10.152.235.184

    t1 = threading.Thread(target=slabDim, args=(dimCameraLiink, ))
    t2 = threading.Thread(target=ocr, args=(ocrCameraLink, ))

    t1.start()
    t2.start()

    sys.exit(app.exec_())
    t1.join()
    t2.join()

    print("Done with both the Threads................")
Beispiel #12
0
def main():
    import sys

    global app
    global ui

    app = QApplication(sys.argv)
    MainWindow = AppMainWindow()
    if path.exists(
            path.dirname(path.abspath(__file__)).replace(path.sep, "/") +
            "/config.cfg"):
        config = ConfigParser()
        config.read(
            path.dirname(path.abspath(__file__)).replace(path.sep, "/") +
            "/config.cfg")
        ui = Ui_MainWindow(config)
    else:
        ui = Ui_MainWindow()

    ui.setupUi(MainWindow)
    sys.stdout = OutLog(ui.txtConsole)
    app.setWindowIcon(
        QtGui.QIcon(
            path.dirname(path.abspath(__file__)).replace(path.sep, "/") +
            "/icons/mcdl.ico"))
    MainWindow.show()
    sys.exit(app.exec_())
Beispiel #13
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #buttons
        self.ui.browsebutton.clicked.connect(self.set_directory)
        self.ui.clearbutton.clicked.connect(self.clear_directory)
        
    def set_directory(self):
        self.ui.directorybox.clear()
        self.ui.directorybox.setText(QFileDialog.getExistingDirectory())
        self.display_scripts()
	
    def clear_directory(self):
        self.ui.scriptlist.clear()
        self.ui.directorybox.clear()
        
    def display_scripts(self):
        self.ui.scriptlist.clear()
        path = self.ui.directorybox.text()
        os.chdir(path)
        filelist = os.listdir()
        
        for i in filelist:
            if(i.endswith('.py')):
                self.ui.scriptlist.append(i)
Beispiel #14
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        QtCore.QObject.connect(self.ui.goto_channel_0,
            QtCore.SIGNAL("clicked()"), self.move_program_to_channel)  # lint:ok

        QtCore.QObject.connect(self.ui.create_null,
            QtCore.SIGNAL("clicked()"), self.create_null)  # lint:ok
        
        # Create a QTimer
        self.channel_timer = QtCore.QTimer()
        # Connect it to f
        self.channel_timer.timeout.connect(self.update_gui)
        # Call f() every 5 seconds
        self.channel_timer.start(1000)

    def update_sinks(self, sink_inputs):                
        for sink in sink_inputs:
            old_items = self.ui.sinks.findItems(sink['appname'], QtCore.Qt.MatchFixedString)
            
            if not old_items:
                item = QtGui.QListWidgetItem("%s" % sink['appname'])            
                self.ui.sinks.addItem(item)
                
        for index in range(self.ui.sinks.count()):
            item = self.ui.sinks.item(index)
            found = False
            for sink in sink_inputs:
                if sink['appname'] == item.text():
                    found = True
            if not found:
                self.ui.sinks.takeItem(index)                

    def update_channels(self, channels):
        for channel in channels:
            item = QtGui.QListWidgetItem("%s" % channel['name'])
            self.ui.channel1.addItem(item)

            if channel['name'] == 'streamer':
                self.ui.create_null.setEnabled(False)

    def update_gui(self):
        self.update_sinks(get_active_player_programs())
        
    def move_program_to_channel(self):
        return

    def create_null(self):
        cmd = ["pactl"]
        paramter = ["load-module", "module-null-sink", "sink_name=streamer"]

        try:
            sink_number = subprocess.call(cmd + paramter)

        except OSError as e:
            print >>sys.stderr, "Execution failed:", e
Beispiel #15
0
def main():
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    MainWindow.show()
    
    sys.exit(app.exec_())
Beispiel #16
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.vm = VirtualMachine()
        self.ui.console.push_local_ns('vm', self.vm)
        #self.ui.console.setStyleSheet("color:#F8F8F2;")
        self.ui.console.eval_queued()
Beispiel #17
0
class Main(QMainWindow):
    def __init__(self, parent):

        super(Main, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.textEdit.initInterpreter(locals())
        self.ui.textEdit.updateInterpreterLocals(self.ui.dockWidget)
Beispiel #18
0
class Main(QMainWindow):
    def __init__(self, parent):

        super(Main, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.textEdit.initInterpreter(locals())
        self.ui.textEdit.updateInterpreterLocals(self.ui.dockWidget)
Beispiel #19
0
def main():
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    MainWindow.show()

    sys.exit(app.exec_())
Beispiel #20
0
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Force consistent theme and font size
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Plastique"))

        # Disable resizing
        self.setFixedSize(self.size())

        #######################################################
        # Interface Object Connections                        #
        #######################################################
        itemClicked = QtCore.SIGNAL("itemClicked(QListWidgetItem *)")
        clicked = QtCore.SIGNAL("clicked()")

        ## Buttons
        QtCore.QObject.connect(self.ui.pushButton_convert, clicked, self.convertImage)
        QtCore.QObject.connect(self.ui.pushButton_loadImage, clicked, self.loadImage)

    def loadImage(self):
        imageName = str(QtGui.QFileDialog.getOpenFileName())
        self.ui.label_imageFile.setText(imageName)
        
        
    def convertImage(self):
        imageName = str(self.ui.label_imageFile.text())
        imageTitle = self.ui.lineEdit_title.text()
        if not imageTitle == '':
            filename, extension = os.path.splitext(imageName)
            directory, file = os.path.split(filename)
            image = Image.open(imageName)
            #scale image
            imageWidth, imageHeight = image.size
            ratio = min(128/imageWidth, 98/imageHeight)
            newImageHeight = int(imageHeight*ratio)
            newImageWidth = int(imageWidth*ratio)
            size = newImageWidth, newImageHeight
            image = image.resize(size)
            #add white bar to bottom for text
            horizontalImageSpacing = int((128-newImageWidth)/2)
            image = image.crop(( -1*horizontalImageSpacing,0,newImageWidth+horizontalImageSpacing,128))
            draw = ImageDraw.Draw(image)
            myFont = ImageFont.truetype("Arial.ttf", 20, encoding="unic")
            textWidth, textHeight = myFont.getsize(imageTitle)
            textHorizontalPosition = 64 - (textWidth/2)
            textVerticalPosition = 98 + (15 - (textHeight/2))
            draw.text((textHorizontalPosition, textVerticalPosition), imageTitle, fill="white", font=myFont)
            image = image.convert("RGB")
            #convert to png
            validFileName = ''.join(c for c in imageTitle if not c in NonValidChars)
            image.save(os.path.join(directory, validFileName) + ".png", quality=100)
            QtGui.QMessageBox.information(self, "Image Converted", "The image has been converted and is ready for use on the Sifteo Cubes")
Beispiel #21
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        ''' Examples of connecting signals (assumes your form has a pushButton, lineEdit, and textEdit)
        self.ui.pushButton.clicked.connect(self.ui.textEdit.clear)
        self.ui.lineEdit.returnPressed.connect(self.add_entry)
        '''
        ''' Example of signal callback (performed when return is pressed on lineEdit, see above)
Beispiel #22
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.imgWidgets = []
        self.imgWidgets.append([self.ui.img1, self.ui.img1_component_display, self.ui.img1_display_selector])
        self.imgWidgets.append([self.ui.img2, self.ui.img2_component_display, self.ui.img2_display_selector])
        self.component1 = component(img_selector = self.ui.component1_img_selector ,
                               component_selector = self.ui.component1_component_selector,
                               ratio = self.ui.component1_slider_ratio, slotFunction = self.updateOutputDisplay)
        self.component2 = component(img_selector = self.ui.component2_img_selector ,
                        component_selector = self.ui.component2_component_selector,
                        ratio = self.ui.component2_slider_ratio, slotFunction = self.updateOutputDisplay)
        self.outputs = {'output 1': self.ui.output1_display, 'output 2': self.ui.output2_display}
        self.images = {}

        self.ui.output_selector.activated.connect(self.updateOutputDisplay)
        for widget in self.imgWidgets:
            widget[2].activated.connect(self.updateComponentDisplay)
            widget[2].addItems([component for component in imgComponents])
               
        self.ui.output_selector.addItems([output for output in outputs])
        self.ui.actionopen.triggered.connect(self.open)
        self.ui.actionnew_window.triggered.connect(self.child_window)
        self.idx = 0 

    def updateComponentDisplay(self):
        for image in self.images.values():
            image.display()

    def updateOutputDisplay(self):
        self.mixer.display()

    def open(self):
            files_names = QtGui.QFileDialog.getOpenFileName( self, 'Open only jpeg', os.getenv('HOME') ,"jpeg(*.jpeg)" )
            for path in files_names:
                if pathlib.Path(path).suffix == ".jpeg":
                    self.images['image ' + str(self.idx + 1)] = image(self.imgWidgets[0] , path)
                    if self.images['image ' + str(self.idx + 1)] == False:
                        return
                    self.imgWidgets.pop(0)
                    self.idx = self.idx + 1
            if not self.imgWidgets:
                self.mixer = Mixer( outputs = self.outputs,
                                    component1 = self.component1,
                                    component2 = self.component2,
                                    images = self.images,
                                    outputSelector = self.ui.output_selector)

    def child_window(self):
        self.child = ApplicationWindow()
        self.child.show()
Beispiel #23
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #buttonSetup(self.ui)
        #self.createTable()
        #self.show()

    def createObjects(self):
        self.displayButtonSetup()

    '''def createTable(self):
        self.ui.tableWidget_2.setRowCount(10)
        self.ui.tableWidget_2.setColumnCount(10)
        self.ui.tableWidget_2.setItem(0,0, QTableWidgetItem("Cell (1,1)"))
        self.ui.tableWidget_2.setItem(0,1, QTableWidgetItem("Cell (1,2)"))
        self.ui.tableWidget_2.setItem(1,0, QTableWidgetItem("Cell (2,1)"))
        self.ui.tableWidget_2.setItem(1,1, QTableWidgetItem("Cell (2,2)"))
        self.ui.tableWidget_2.setItem(2,0, QTableWidgetItem("Cell (3,1)"))
        self.ui.tableWidget_2.setItem(2,1, QTableWidgetItem("Cell (3,2)"))
        self.ui.tableWidget_2.setItem(3,0, QTableWidgetItem("Cell (4,1)"))
        self.ui.tableWidget_2.setItem(3,1, QTableWidgetItem("Cell (4,2)"))

        self.ui.tableWidget.setRowCount(10)
        self.ui.tableWidget.setColumnCount(10)
        self.ui.tableWidget.setItem(0,0, QTableWidgetItem("Cell (1,1)"))
        self.ui.tableWidget.setItem(0,1, QTableWidgetItem("Cell (1,2)"))
        self.ui.tableWidget.setItem(1,0, QTableWidgetItem("Cell (2,1)"))
        self.ui.tableWidget.setItem(1,1, QTableWidgetItem("Cell (2,2)"))
        self.ui.tableWidget.setItem(2,0, QTableWidgetItem("Cell (3,1)"))
        self.ui.tableWidget.setItem(2,1, QTableWidgetItem("Cell (3,2)"))
        self.ui.tableWidget.setItem(3,0, QTableWidgetItem("Cell (4,1)"))
        self.ui.tableWidget.setItem(3,1, QTableWidgetItem("Cell (4,2)"))'''

    def displayButtonSetup(self):
        self.ui.clearButton.clicked.connect(self.clearTable)
        self.ui.clearButton2.clicked.connect(self.clearTable2)
        #self.ui.testButton9.clicked.connect(self.testButton9)

    def clearTable(self):
        self.ui.tableWidget_2.setRowCount(0)

    def clearTable2(self):
        self.ui.tableWidget.setRowCount(0)
        clearNodeList()

    '''def testButton9(self):
        print (str(nodeList))'''

    def getUI(self):
        return self.ui
Beispiel #24
0
class MainWindow(QtWidgets.QMainWindow):

    cyclist1 = Cyclist()
    cyclist2 = Cyclist()

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.comboBoxC1.addItem("Right")
        self.ui.comboBoxC1.addItem("Left")

        self.ui.comboBoxC2.addItem("Right")
        self.ui.comboBoxC2.addItem("Left")
        #тут инициализируется графическая оболочка
        #и происходит вызов функции загрузки, если фала нет, то выдаст исключение
        #если файл существует или не испорчен, то проиходит парсинг xml файла
        #при испорченности он тоже выдаст исключение и будет считаться, что файл пуст
        try:
            downloadXML.download(self.cyclist1, self.cyclist2)
        except Exception:
            print("Пустота")
        #после загрузки происходит инициализация полей исходя из данных файла
        self.ui.c1_x.setValue(self.cyclist1.getCoordinate())
        self.ui.c1_v.setValue(self.cyclist1.getSpeed())
        self.ui.c2_x.setValue(self.cyclist2.getCoordinate())
        self.ui.c2_v.setValue(self.cyclist2.getSpeed())
        self.ui.pushButtonOk.clicked.connect(self.btnClickOk)


    def btnClickOk(self):
        self.cyclist1.setCoordinate(self.ui.c1_x.value())
        self.cyclist1.setSpeed(self.ui.c1_v.value())
        self.cyclist2.setCoordinate(self.ui.c2_x.value())
        self.cyclist2.setSpeed(self.ui.c2_v.value())
        self.cyclist1.setNewXinTime(self.ui.time.value(), self.ui.comboBoxC1.currentIndex())
        self.cyclist2.setNewXinTime(self.ui.time.value(), self.ui.comboBoxC2.currentIndex())
        self.ui.result.setText("Расстояние между велосипедистами " + str(abs(self.cyclist1.getCoordinate() - self.cyclist2.getCoordinate())))
        self.ui.c1_x.setValue(self.cyclist1.getCoordinate())
        self.ui.c2_x.setValue(self.cyclist2.getCoordinate())

    def closeEvent(self, event):
        #здесь была переопределена функция закрытия интерфейса
        reply = QMessageBox.question(self, "Выход", "вы действительно хотите выйти?",
                QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            create_xml(self.cyclist1, self.cyclist2)
            event.accept()
        else:
            event.ignore()
class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.start_simulation_btn.clicked.connect(self.start)

    def start(self):
        self.simulation(self.timer_func, int(self.ui.request_count.text()))

    def simulation(self, slot, count=1000, interval=117):
        counter = 0
        self.ui.progressBar.minimum = 0
        self.ui.progressBar.maximum = int(self.ui.request_count.text())
        smo = SMO(self.ui.progressBar, int(self.ui.request_count.text()),
                  self.ui.outer_info)
        smo.add_channel(Channel('channel_1', self.ui.state_1, 0.6 / 4))
        smo.add_channel(Channel('channel_2', self.ui.state_2, 0.6 / 4))
        smo.add_channel(Channel('channel_3', self.ui.state_3, 0.6 / 4))
        smo.add_channel(Channel('channel_4', self.ui.state_4, 0.6 / 4))
        requests = [
            Request() for i in range(int(self.ui.request_count.text()))
        ]

        def handler():
            nonlocal counter
            counter += 1
            slot(smo, requests.pop(), counter, count)
            if counter >= count:
                timer.stop()
                timer.deleteLater()

        timer = QtCore.QTimer()
        timer.timeout.connect(handler)
        timer.start(interval)

    def timer_func(self, smo, request, current_count, max_count):
        smo.execute_request(request)
        if (current_count == max_count):
            smo.return_remaining()
            denied = smo.get_dined_count()
            self.ui.outer_info.append('\n' * 3)
            self.ui.outer_info.append(
                f'Обслужено заявок: {max_count - denied}')
            self.ui.outer_info.append(f'Откланено заявок: {denied}')
            self.ui.outer_info.append(
                f'Вероятность обслуживания заявки: {100 - denied/max_count*100}%'
            )
            self.ui.progressBar.setValue(100)
Beispiel #26
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.input_carpeta.clicked.connect(self.cualCarpeta)

    def cualCarpeta(self):
        print("kkkkkkkkkkkk")
        self.ui.facturas_path.setText(u"kkkkkkkkkkkkkk")
        esteFileChooser = QFileDialog()
        esteFileChooser.setFileMode(QFileDialog.Directory)
        if esteFileChooser.exec_():

            self.esteFolder = esteFileChooser.selectedFiles()[0] + "/"
Beispiel #27
0
class Gui(Ui_MainWindow):
    def __init__(self, MainWindow):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(MainWindow)
        self.is_auto = False
        self.p = self.S = self.f = self.betaL = self.betaR = \
            self.betaS = self.z = self.x0 = self.y0 = None
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Ad server"))
        self.ui.checkBox.toggled['bool'].connect(self.betaLInput_handler)
        self.ui.checkBox.toggled['bool'].connect(self.ui.betaRInput.setEnabled)
        self.ui.checkBox.toggled['bool'].connect(self.ui.betaStep.setEnabled)
        self.ui.calculateButton.clicked.connect(self.calculate)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def betaLInput_handler(self, is_enabled):
        if is_enabled:
            self.ui.betaLInput.setPlaceholderText("Left border")
        else:
            self.ui.betaLInput.setPlaceholderText("")
        self.is_auto = is_enabled

    def parse(self):
        self.p, p_corr = gen_function(['w'], self.ui.distInput.text())
        self.S, S_corr = gen_function(['t'], self.ui.planInput.text())
        self.f, f_corr = gen_function(['z', 'x', 'S', 'b'], self.ui.corrInput.text())
        if self.is_auto:
            self.betaL, self.betaR, self.betaS, beta_corr = num_check(self.ui.betaLInput.text(),
                                                                      self.ui.betaRInput.text(),
                                                                      self.ui.betaStep.text())
        else:
            self.betaL, beta_corr = num_check(self.ui.betaLInput.text())
        self.z, z_corr = gen_function(['t'], self.ui.trafInput.text())
        self.x0, self.y0, start_corr = num_check(self.ui.X0Input.text(), self.ui.Y0Input.text())
        print(p_corr, S_corr, f_corr, beta_corr, z_corr, start_corr)
        if not p_corr or not S_corr or not f_corr or not beta_corr or not z_corr or not start_corr:
            return False
        return True

    def calculate(self):
        if not self.parse():
            print('This is so sad, Alexa play despacito')
            return
        print('calculated!')
        graphics.show_results()

    def error(self):
        pass
Beispiel #28
0
class VesselKMRun(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.new_session_btn.clicked.connect(self.check_display)
        self.ui.actionConfigure.triggered.connect(self.show_config)

        self.dialog = ConfigDialog(self.ui.current_km_label)

    def check_display(self):
        index = 100
        self.ui.current_km_label.display(index)

    def show_config(self):
        self.dialog.show()
Beispiel #29
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.PlotButton.clicked.connect(self.btnClicked)
        self.ui.chgEnd.clicked.connect(self.choosePoint)

    def btnClicked(self):
        global endlat, endlon, n

        #locals()['self.ui.Latitude_{}'.format(i+1)]=0
        endlat = [
            float(self.ui.Latitude_1.text()),
            float(self.ui.Latitude_2.text()),
            float(self.ui.Latitude_3.text()),
            float(self.ui.Latitude_4.text()),
            float(self.ui.Latitude_5.text()),
            float(self.ui.Latitude_6.text()),
            float(self.ui.Latitude_7.text()),
            float(self.ui.Latitude_8.text()), 0
        ]
        endlon = [
            float(self.ui.Longitude_1.text()),
            float(self.ui.Longitude_2.text()),
            float(self.ui.Longitude_3.text()),
            float(self.ui.Longitude_4.text()),
            float(self.ui.Longitude_5.text()),
            float(self.ui.Longitude_6.text()),
            float(self.ui.Longitude_7.text()),
            float(self.ui.Longitude_8.text()), 0
        ]
        f = open('endlat.txt', 'w+')
        f.write(str(endlat[n:]))
        f.close()
        f = open('endlon.txt', 'w+')
        f.write(str(endlon[n:]))
        f.close()

    def choosePoint(self):
        global n
        n = n + 1

        if n == 8:
            n = 0
        self.ui.label.setText(str(n))
Beispiel #30
0
 def __init__(self):
     super(MainWindow, self).__init__()
     Ui.setupUi(self, self)
     self.filepath = "Dane.xlsx"
     data_file = Path("Dane.xlsx")
     if data_file.is_file():
         self.flag_file_exists = True
         self.input_data = f.full_import(self.filepath)
         del data_file
     else:
         #tworzenie pliku
         x = f.daj_przykladowe_dane()
         f.exporter(x[0],x[1],x[2],x[3],x[4],x[5])
         self.sample_xl_created_flag = True
         self.flag_file_exists = True
     #for x in self.dane_firm:
     #    print(x)
     self.refresh()
Beispiel #31
0
class MainWindow(QMainWindow):
    def __init__(self, wordList, tkWord, tkLabel):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.wordList = wordList
        self.tkWord = tkWord
        self.tkLabel = tkLabel

        self.ui.lineEdit.returnPressed.connect(self.interact)

    def appendTextToBrowser(self):
        userText = self.ui.lineEdit.text()
        self.ui.textBrowser.append("You:  " + userText)
        self.ui.lineEdit.clear()

    def interact(self):
        # while (True):

        # Get input from the user
        # print("(Press 'bye' to exit.)")
        userInput = self.ui.lineEdit.text()
        self.ui.textBrowser.append("You:  " + userInput)
        self.ui.lineEdit.clear()

        # Transform user input into a boolean list representing their
        # includence (theres a better word here that I cant think of) in the word list
        userInputArr = makeInput([userInput.replace("?", "").replace("!", "")], self.wordList, self.tkWord)

        # The results of out predictions
        results = model.predict(userInputArr)
        print(results)
        print(np.argmax(results))

        # Use the predictions to select the most likely label
        predictedLabelIndex = np.argmax(results) + 1

        for label, key in self.tkLabel.word_index.items():
            if key == predictedLabelIndex:
                for intent in data["intents"]:
                    if intent["tag"] == label:
                        response = random.choice(intent["responses"])
                        self.ui.textBrowser.append("BankBot4444:  " + response + "\n")
Beispiel #32
0
class GStatusSetter(QtGui.QMainWindow):
    def __init__(self):
        super(GStatusSetter, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        self.thread = None
        self.ui.start.clicked.connect(self.start)
        self.ui.stop.clicked.connect(self.stop)

    def start(self):
        self.enabled = True
        self.interval = int(self.ui.interval.text())
        self.index = 0
        self.statuses = self.ui.statuses.toPlainText().split('\n')
        if self.thread == None:
            self.thread = threading.Thread(target=self.run)
            self.thread.start()

    def run(self):
        while self.enabled:
            self.setStatus(self.statuses[self.index])
            self.index = (self.index + 1) % len(self.statuses)
            time.sleep(self.interval)
        self.thread = None

    def stop(self):
        self.enabled = False

    def setStatus(self, statusmsg):
        client = Client(server='gmail.com', debug=[])
        if not client.connect(server=('talk.google.com', 5222)):
            raise IOError('Cannot connect to server')
        if not client.auth(self.ui.username.text(), self.ui.password.text(),
                           'gmail.com'):
            raise IOError('Authentication failed')
        client.send(
            Iq('set',
               'google:shared-status',
               payload=[
                   Node('show', payload=['dnd']),
                   Node('status', payload=[statusmsg])
               ]))
        client.disconnect()
Beispiel #33
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.folder = ''
        self.files = []
        self.ui.selectPDF.clicked.connect(self.select_pdf)
        self.ui.selectSaveFolder.clicked.connect(self.select_save_folder)
        self.ui.runButton.clicked.connect(self.parse_run)
        self.show()

    def select_pdf(self):
        '''get pdf`s file names'''
        caption = 'Open file'
        # use current/working directory
        directory = './'
        filter_mask = "*.pdf"
        self.files, _ = QFileDialog.getOpenFileNames(None,
                                                     caption, directory, filter_mask)

    def select_save_folder(self):
        '''get save folder'''
        self.folder = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
        self.ui.labelPATH.setText("Save dir: " + str(self.folder))

    def parse_run(self):
        if self.files == []:
            return
        files = self.files
        if self.folder != '':
            folder = self.folder
        else:
            folder = os.path.dirname(files[0])

        with Manager() as manager:
            processes = []
            for filename in files:
                p = Process(target=prepare_to_parsing, args=(filename, folder))
                p.start()
                processes.append(p)
            for p in processes:
                p.join()
Beispiel #34
0
class ApplicationWindow(QtWidgets.QMainWindow):

    onNumberGenerated = pyqtSignal(int)

    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.onNumberGenerated.connect(self.updateAll)
        self.ui.pushButton.clicked.connect(self.generateNumber)

    def generateNumber(self):
        number = random.randint(0, 100)
        self.onNumberGenerated.emit(number)

    def updateAll(self, number):
        self.ui.progressBar.setValue(number)
        self.ui.spinBox.setValue(number)
        self.ui.verticalSlider.setValue(number)
Beispiel #35
0
def gui(str_):
    import sys
    from PyQt5 import QtCore, QtGui, QtWidgets

    from gui import Ui_MainWindow

    # create app
    app = QtWidgets.QApplication(sys.argv)

    # init
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    # logic
    ui.Interface_list.setText(str_)

    # main loop
    sys.exit(app.exec_())
Beispiel #36
0
class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_graphics()

        self.show()

    def init_graphics(self):
        self.scene = QGraphicsScene(self.ui.MainImage)
        self.ui.MainImage.setScene(self.scene)

    def simplex_run(self):

        args = {
            'height': self.ui.inputHeight.value(),
            'length': self.ui.inputLength.value(),
            'calc_a': self.ui.inputCalcA.value(),
            'calc_b': self.ui.inputCalcB.value(),
            'calc_c': self.ui.inputCalcC.value(),
            'gradual': self.ui.inputGradual.checkState()
        }

        simplex = sw.SimplexGenerator(args)
        self.ui.creationBar.setMaximum(args.get('height') * args.get('length'))

        counter = 0
        for p in simplex.createelevation():
            counter += 1
            item = QGraphicsRectItem(3 * p.get('x'), 3 * p.get('y'), 3, 3)
            item.setBrush(QColor(*simplex.decidebiome(p.get('elev'))))
            self.scene.addItem(item)
            self.ui.creationBar.setValue(counter)
            if args.get('gradual'):
                # Update for each 100th pixel to keep performance so-and-so
                if counter % 100 == 0:
                    QApplication.processEvents()

    def generateButton(self):
        self.simplex_run()
Beispiel #37
0
def main():
        #dbProcessor('CREATE', 'localhost','root','levon92','MYDATABASE')
        #dbProcessor('DROP', 'localhost','root','levon92','MYDATABASE')		

        #budgetTbProcessor('CREATE', 'localhost','root','levon92','MYDATABASE')
        #budgetTbProcessor('DROP', 'localhost','root','levon92','MYDATABASE')		

	app  =  QApplication(sys.argv)
	window  =  QMainWindow()
	ui =  Ui_MainWindow()
	ui.setupUi(window)
	
	
	window.show()

	ui.ADD_btn.clicked.connect(lambda: add(ui))
	ui.REPORT_ALL_btn.clicked.connect(lambda: report_all(ui))
	ui.REMOVE_btn.clicked.connect(lambda: remove(ui))
	ui.BALANCE_btn.clicked.connect(lambda: balance(ui))
	ui.EXIT_btn.clicked.connect(lambda: ex(ui))
	sys.exit(app.exec_())
Beispiel #38
0
class MainWindow(baseClass):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Your code will go here
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.encode_button.clicked.connect(self.on_click_encode_button)
        self.ui.tableWidget.setColumnCount(3)
        self.ui.tableWidget.setRowCount(3)
        item = qtw.QTableWidgetItem()
        self.ui.tableWidget.setHorizontalHeaderItem(0, item)
        item = qtw.QTableWidgetItem()
        self.ui.tableWidget.setHorizontalHeaderItem(1, item)
        item = qtw.QTableWidgetItem("Trzeci")
        self.ui.tableWidget.setHorizontalHeaderItem(2, item)
        item = qtw.QTableWidgetItem()
        # Your code ends here
        self.show()
    def on_click_encode_button(self):
        self.ui.output_textedit.setPlainText(self.ui.input_textedit.toPlainText())
Beispiel #39
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btnTakePic.clicked.connect(self.takePicClicked)
        self.ui.btnAutofocus.clicked.connect(self.autofocusClicked)
        self.ui.btnMoveUp.clicked.connect(self.moveUpClicked)
        self.ui.btnMoveDown.clicked.connect(self.moveDownClicked)
        self.ui.btnStart.clicked.connect(self.startClicked)
        self.ui.btnStop.clicked.connect(self.stopClicked)

        self.cameraOperator = CameraOperator("/home/pi/robotchem/robotchem/")
        self.autofocus = Autofocus()
        self.platform = Platform()
        self.scheduler = Scheduler(self.autofocus)

    def takePicClicked(self):
        self.ui.txtResult.setText("TakePic")
        pixmap = self.cameraOperator.takePic()
        self.ui.labPic.setScaledContents(True)
        self.ui.labPic.setPixmap(pixmap)

    def autofocusClicked(self):
        self.ui.txtResult.setText("Autofocus")

    def moveUpClicked(self):
        self.ui.txtResult.setText("MoveUp")

    def moveDownClicked(self):
        self.ui.txtResult.setText("MoveDown")

    def startClicked(self):
        self.ui.txtResult.setText("Start")
        self.scheduler.startSerial(self.ui.spinTime.value(),
                                   self.ui.spinInterval.value())

    def stopClicked(self):
        self.ui.txtResult.setText("Stop")
Beispiel #40
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # ------вывод имени--------------------
        self.ui.label.setText(name)
        # ------включение кнопки---------------
        self.ui.sendButton.clicked.connect(self.inputThreadCall)

        # ------вызов потока OUTPUT------------
        self.outputObject = Output()
        self.outputObject.start()

        self.outputObject.mySignal1.connect(self.onOutput, Qt.QueuedConnection)

# ------исполнение GUI для OUTPUT-------------

    def onOutput(self, text):
        # global outputText
        # self.ui.output.clear()
        self.ui.output.setText(text)

# ------вызов потока INPUT-------------

    def inputThreadCall(self):
        global input_text
        input_text = self.ui.input.toPlainText()

        self.inputObject = Input()
        self.inputObject.start()

        self.ui.input.clear()

    def keyPressEvent(self, e):
        global f
        if e.key() == Qt.Key_Escape:
            f.close()
            self.close()
Beispiel #41
0
class GStatusSetter(QtGui.QMainWindow):
	def __init__(self):
		super(GStatusSetter, self).__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.show()
		self.thread = None
		self.ui.start.clicked.connect(self.start)
		self.ui.stop.clicked.connect(self.stop)

	def start(self):
		self.enabled = True
		self.interval = int(self.ui.interval.text())
		self.index = 0
		self.statuses = self.ui.statuses.toPlainText().split('\n')
		if self.thread == None:
			self.thread = threading.Thread(target=self.run)
			self.thread.start()

	def run(self):
		while self.enabled:
			self.setStatus(self.statuses[self.index])
			self.index = (self.index + 1) % len(self.statuses)
			time.sleep(self.interval)
		self.thread = None
	
	def stop(self):
		self.enabled = False

	def setStatus(self, statusmsg):
		client = Client(server='gmail.com', debug=[])
		if not client.connect(server=('talk.google.com', 5222)):
			raise IOError('Cannot connect to server')
		if not client.auth(self.ui.username.text(), self.ui.password.text(), 'gmail.com'):
			raise IOError('Authentication failed')
		client.send(Iq('set', 'google:shared-status', payload=[
					Node('show', payload=['dnd']),
					Node('status', payload=[statusmsg])
					]))
		client.disconnect()
Beispiel #42
0
class MyForm(QtGui.QMainWindow):
    #Constructor
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        #Create Video Object
        cv2.namedWindow('Video')
        device = 0
        self.video = cv2.VideoCapture(device)     
        
        #Set up timer
        self.ctimer = QtCore.QTimer()

        #Slider Bars signal connectors
        QtCore.QObject.connect(self.ui.horizontalSlider, QtCore.SIGNAL("sliderMoved(int)"),self.updateLabels)
        QtCore.QObject.connect(self.ui.horizontalSlider_2, QtCore.SIGNAL("sliderMoved(int)"),self.updateLabels)
        QtCore.QObject.connect(self.ui.horizontalSlider_3, QtCore.SIGNAL("sliderMoved(int)"),self.updateLabels)
        QtCore.QObject.connect(self.ui.horizontalSlider_4, QtCore.SIGNAL("sliderMoved(int)"),self.updateLabels)
        QtCore.QObject.connect(self.ui.horizontalSlider_5, QtCore.SIGNAL("sliderMoved(int)"),self.updateLabels)
        QtCore.QObject.connect(self.ui.horizontalSlider_6, QtCore.SIGNAL("sliderMoved(int)"),self.updateLabels)
        
        #Timer signal
        QtCore.QObject.connect(self.ctimer,QtCore.SIGNAL("timeout()"),self.tick)
        
        #Timer start
        self.ctimer.start(1)

    #Label Updates Signal Callback
    def updateLabels(self):
        self.ui.label.setText(str(self.ui.horizontalSlider.value()))
        self.ui.label_2.setText(str(self.ui.horizontalSlider_2.value()))
        self.ui.label_3.setText(str(self.ui.horizontalSlider_3.value()))
        self.ui.label_4.setText(str(self.ui.horizontalSlider_4.value()))
        self.ui.label_5.setText(str(self.ui.horizontalSlider_5.value()))
        self.ui.label_6.setText(str(self.ui.horizontalSlider_6.value()))
        self.updateThresh()
        
    def updateThresh(self):
        colormin,colormax = self.getColors()
        minStr = "Threshold minimum: " + str(colormin[0]) + ", " + str(colormin[1]) + ", " + str(colormin[2])
        maxStr = "Threshold maximum: " + str(colormax[0]) + ", " + str(colormax[1]) + ", " + str(colormax[2])
        self.ui.label_7.setText(minStr)
        self.ui.label_8.setText(maxStr)
        
    #Timer tick
    def tick(self):
        self.updateLabels()
        _,frame = self.video.read()
        colormin,colormax = self.getColors()
        checked = self.ui.checkBox.checkState()
        if not checked:
            cv2.imshow('Video', frame)
        else:
            image = processImage(frame,colormin,colormax)
            cv2.imshow('Video', image)
        
    #Get Colors from Ui
    def getColors(self):
        #Get values from form
        hmin = np.amax([0,self.ui.horizontalSlider.value()-(self.ui.horizontalSlider_6.value()/2)])
        hmax = np.amin([360,self.ui.horizontalSlider.value()+(self.ui.horizontalSlider_6.value()/2)])
        smin = self.ui.horizontalSlider_2.value()
        smax = self.ui.horizontalSlider_3.value()
        vmin = self.ui.horizontalSlider_4.value()
        vmax = self.ui.horizontalSlider_5.value()
        #Create colors and return them
        cmin = np.array([hmin,smin,vmin],np.uint8)
        cmax = np.array([hmax,smax,vmax],np.uint8)
        return cmin,cmax        
Beispiel #43
0
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle('SmartMM')
        self.initialize()

    def initialize(self):
        first_load()
        self.emovecs = initialize_emotion_recognizer()
        self.initalize_gui()
        self.initialize_triggers()

    def initalize_gui(self):
        self.ui.review1.setStyleSheet("background-color: DarkCyan;color: black")
        self.ui.recommendButton.setStyleSheet("background-color: Tomato;color: black")
        self.ui.review1.setIcon(qta.icon('fa.flag'))
        self.ui.recommendButton.setIcon(qta.icon('fa.bullseye'))
        self.setup_mov_list()
        self.ui.progressInfo.setVisible(False)
        self.ui.progressBar.setVisible(False)
        self.showClickedItem(self.ui.listWidget.item(0))

    def initialize_triggers(self):
        self.ui.actionExit.triggered.connect(QCoreApplication.instance().quit)
        self.ui.actionAdd_Files.triggered.connect(self.addFiles_triggered)
        self.ui.actionAdd_Folders.triggered.connect(self.addFolder_triggered)
        self.ui.listWidget.itemClicked.connect(self.showClickedItem)
        self.ui.actionSync.triggered.connect(self.internet_sync_trigger)
        self.ui.recommendButton.clicked.connect(self.recommendMovies)

    #The list shows movies even if movie is removed from folder
    def recommendMovies(self):
        list = getSeenMovies()
        list = [x[0] for x in list]
        print list
        recommender = Recommender()
        rec_list = recommender.get_n_recommendations(10, list)
        for movie in rec_list:
            self.ui.listWidgetRecommend.addItem(movie['title'])

    def setup_mov_list(self):
        movies = get_mov_names()
        self.ui.listWidget.clear()
        #check if the movie exists in the folder acc. to db entry
        #correct it
        for movie in movies:
            if movie != "":
                print movie
                item = QtWidgets.QListWidgetItem()
                widget = QtWidgets.QWidget()
                widgetText = QtWidgets.QLabel(movie)
                widgetCheckbox = QtWidgets.QCheckBox()
                path = os.getcwd()
                widgetCheckbox.setStyleSheet(
                    "QCheckBox::indicator:unchecked {image: url(%s/images/star_greyed_small.png);}"
                    "QCheckBox::indicator:checked {image: url(%s/images/star_pressed_small.png);}" % (path,path)
                )
                widgetLayout = QtWidgets.QHBoxLayout()
                widgetLayout.addWidget(widgetText)
                widgetLayout.addStretch(1)
                widgetLayout.addWidget(widgetCheckbox)
                widget.setLayout(widgetLayout)
                item.setSizeHint(widget.sizeHint())
                seen = getSeenValue(movie)
                #print movie + " Initial Seen Value: " + str(seen)
                if seen:
                    widgetCheckbox.setCheckState(QtCore.Qt.Checked)
                #print checkbox.isChecked()
                widgetCheckbox.stateChanged.connect(functools.partial(self.checkFunction, movie))
                self.ui.listWidget.addItem(item)
                self.ui.listWidget.setItemWidget(item, widget)

                ####OLD CODE WITHOUT LABEL
                """
                #print movie
                item = QtWidgets.QListWidgetItem(movie)
                self.ui.listWidget.addItem(item)
                checkbox = QtWidgets.QCheckBox()
                seen = getSeenValue(movie)
                #print movie + " Initial Seen Value: " + str(seen)
                if seen:
                    checkbox.setCheckState(QtCore.Qt.Checked)
                #print checkbox.isChecked()
                checkbox.stateChanged.connect(functools.partial(self.checkFunction, movie))
                self.ui.listWidget.setItemWidget(item, checkbox)
                """

    def checkFunction(self, movie):
        #if state == QtCore.Qt.Checked:
        changeSeenValue(movie)

    def addFolder_triggered(self):
        dir = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Directory"))
        add_folder(dir)
        self.setup_mov_list()

    def addFiles_triggered(self):
        filename=QtWidgets.QFileDialog.getOpenFileName(self)
        add_file(filename[0])
        self.setup_mov_list()

    def displayImage(self, imgData):
        qimg = QtGui.QImage.fromData(imgData)
        pixmap = QtGui.QPixmap.fromImage(qimg)
        self.ui.imgLabel.setPixmap(pixmap)

    def showClickedItem(self,item):
        #selected_vid = item.text()
        try:
            selected_vid = self.ui.listWidget.itemWidget(item).findChild(QtWidgets.QLabel).text()
            self.update_gui_with_mov(selected_vid)
        except Exception as e:
            print e.message



    def update_gui_with_mov(self,mov):
        mov_details = prep_mov_details_dict(mov_to_id(mov))
        print mov_details
        #print len(mov_details["review_urls"])
        self.ui.labelMov.setText(mov_details["name"])
        self.ui.labelGenre.setText(mov_details["genres"])
        self.ui.textMovSummary.setText(mov_details["plot"])
        self.ui.textDirector.setText(mov_details["directors"])
        self.ui.textProducer.setText(mov_details["producers"])
        self.ui.textStarCast.setText(mov_details["cast"])
        self.ui.textRTRating.setText(mov_details["rt_rating"])
        self.ui.textIMDBRating.setText(mov_details["imdb_rating"])
        self.ui.textVoteCount.setText(mov_details["votes"])
        self.displayImage(mov_details["img"])
        self.displayWordCloud(mov_details["plot"])
        self.emotionDisplay(mov)
        #self.displayReview(mov_details)
        if (len(mov_details["review"])):
            self.ui.review1.disconnect()
            self.ui.review1.clicked.connect(functools.partial(self.displayReview, mov_details))
        QCoreApplication.processEvents()
        #if(len(mov_details["reviews"])):
        #    self.displayRakeKeywords(mov_details["reviews"][0])
        #    self.displayTextRankKeywords(mov_details["reviews"][0])
        #    self.displayKeywords(mov_details["reviews"][0])

    def emotionDisplay(self,mov):
        path = mov_to_path(mov).split(".")[0]+".srt"
        print path
        try:
            emotions = predictEmo(path,self.emovecs)
        except Exception as e:
            print e.message
        if emotions is None:
            self.ui.pbarAngry.setValue(0)
            self.ui.pbarSurprise.setValue(0)
            self.ui.pbarFear.setValue(0)
            self.ui.pbarSad.setValue(0)
            self.ui.pbarHappy.setValue(0)
        print emotions
        self.ui.pbarAngry.setValue(emotions['anger']*100)
        self.ui.pbarSurprise.setValue(emotions['surprise']*100)
        self.ui.pbarFear.setValue(emotions['fear']*100)
        self.ui.pbarSad.setValue(emotions['sad']*100)
        self.ui.pbarHappy.setValue(emotions['happy']*100)

    def displayWordCloud(self, plot):
        #print plot
        rake = Rake("SmartStoplist.txt")
        keywords = rake.run(str(plot))
        #print keywords
        data = WordCloud(max_words=15).generate_from_frequencies(keywords)
        img = data.to_image()
        #print img
        pix = QtGui.QPixmap.fromImage(ImageQt(img))
        scaledPix = pix.scaled(self.ui.wordCloudLabel.size(), QtCore.Qt.KeepAspectRatio)

        #img.show()
        #data = img.tostring('raw', 'RGBA')
        #image = QtGui.QImage(data, img.size[0], img.size[1], QtGui.QImage.Format_ARGB32)
        #pix = QtGui.QPixmap.fromImage(image)

        self.ui.wordCloudLabel.setPixmap(scaledPix)
        #print "displayed"

    def displayReview(self, mov_details):
        print mov_details["name"]
        class MyWebView(QWebView):
            def __init__(self):
                QWebView.__init__(self)
                self.setWindowTitle(mov_details["name"])
                #print "Hello"

            def _loadFinished(self):
                js1 = """
                var text = "Less impressive are the screenplay and Ron Howard's direction";
                var re = new RegExp(text, "gi");
                document.body.innerHTML = document.body.innerHTML.replace(re,"<span style='color:blue'>" + text + "</span>");
                """

                js2 = """
                var text = {0};
                var re = new RegExp(text, "gi");
                document.body.innerHTML = document.body.innerHTML.replace(re,"<span style='color:{1}'>" + text + "</span>");
                """
                sentences = "Writer Akiva Goldsman (he of the two bad Batman films fame), adapting the script from Sylvia Nasar's biography of Nash, reveals only the warts that aren't too ugly (there is no mention of Nash's bisexuality or of his divorce from Alicia)."
                sentences = sentences.split(".")
                # print repr(sentences[0])
                # sentences[0] = sentences[0].replace("\n","")
                # sentences[0] = "\"%s.\"" % ( sentences[0] )
                # print repr(sentences[0])
                # js2 = js2.format(sentences[0], "red")
                #for sent in sentences:
                #    sent = sent.replace("\n","")
                #    sent = "\"%s.\"" % ( sent )
                #    print repr(sent)
                #    js2 = js2.format(sent, "red")


                #tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
                #tokens = [token.replace("\n", "") for token in tokenizer.tokenize(mov_details["reviews"][0])]
                #print tokens
                #for token in tokens:
                #    #print token
                #    js2 = js2.format(token, "blue")q
                #    self.page().mainFrame().evaluateJavaScript(js2)

                #print js2
                #print js2==js1
                #self.page().mainFrame().evaluateJavaScript(js2)
                #self.page().mainFrame().evaluateJavaScript("""alert("done")""")
                print "load finished"

        print "Review clicked "
        self.webview = MyWebView()
        #self.webview.load(QtCore.QUrl(mov_details["review_urls"][0]))
        html = str(mov_details["review"])
        html = self.sentimentify(html)
        self.webview.setHtml(html)
        path = os.getcwd()
        self.webview.settings().setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile( path + "/review.css"))
        #self.webview.loadFinished.connect(self.webview._loadFinished)
        self.webview.show()

        ##Old Code to replace string
        """//var index = innerHTML.indexOf(text);
                //alert(index);
                //if(index >=0)
                    //innerHTML = innerHTML.substring(0,index) + "<span style='color:blue'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length);"""

        #####Code to add CSS File
        #path = os.getcwd()
        #self.webview.settings().setUserStyleSheetUrl(QtCore.QUrl.fromLocalFile(path + "/highlight.css"))

    def sentimentify(self, review):
        rake = Rake("SmartStoplist.txt")
        keywords = rake.run(review)
        #print keywords
        data = WordCloud(max_words=15).generate_from_frequencies(keywords)
        img = data.to_image()
        output = StringIO.StringIO()
        img.save(output, format = 'PNG')
        output.seek(0)
        output_s = output.read()
        b64 = base64.b64encode(output_s)

        strRev = '<img src="data:image/png;base64,{0}"/>'.format(b64)
        review_sentences = nltk.sent_tokenize(review)
        scores = test(review_sentences)
        # test(reviews[0])
        colors = [ '#FF0000', '#FF9900', '#FFFF66', '#CCFFBB', '#005A04' ]

        for score,review_sentence in zip(scores,review_sentences):
            strRev += "<span style='background-color:{0}'>".format(colors[score]) + review_sentence + " " + "</span>"

        strRev = "<html><body><p>" + strRev + "</p></body></html>"
        print strRev
        return strRev

    def displayRakeKeywords(self, review):
        rake = Rake("SmartStoplist.txt")
        keywords = rake.run(str(review))
        print keywords
        text = ""
        for word in keywords[:10]:
            text += str(word[0])
            text += ";\n"
        #self.ui.keywordLabel.setText(text)
        #self.ui.keywordLabel.setToolTip(text)

    def displayTextRankKeywords(self, review):
        review = review.decode('utf8')
        keywords = extractKeyphrases(review)
        print keywords
        keywords = list(keywords)
        text = ""
        for word in keywords[:10]:
            text += str(word)
            text += ";\n"
        #self.ui.keywordLabel_2.setText(text)
        #self.ui.keywordLabel_2.setToolTip(text)

    def displayKeywords(self, review):
        review = review.decode('utf8')
        wordTokens = nltk.word_tokenize(review)
        tagged = nltk.pos_tag(wordTokens)
        #textlist = [x[0] for x in tagged]
        tags = ['JJ']
        adjectives = [item[0] for item in tagged if item[1] in tags]
        print set(adjectives)


    #it does not overwrite the db, rather inserts duplicate values
    #correct it
    def internet_sync_trigger(self):
        self.syncer = MovieSyncThread(self)
        self.syncer.startSignal.connect(self.init_progressbar)
        self.syncer.updateSignal.connect(self.update_progressbar)
        self.syncer.terminateSignal.connect(self.terminate_progressbar)
        self.syncer.start()

    def terminate_progressbar(self):
        self.ui.progressInfo.setVisible(False)
        self.ui.progressBar.setVisible(False)

    def update_progressbar(self):
        self.ui.progressBar.setValue(self.ui.progressBar.value() + 1)

    def init_progressbar(self, maxProgressBarValue):
        print "Initialize progress bar now"
        # self.ui.progressInfo.setVisible(True)
        self.ui.progressBar.setVisible(True)
        self.ui.progressBar.setMaximum(maxProgressBarValue)
        # self.ui.progressInfo.setText("Fetching info...Please Wait!")
        self.ui.statusbar.showMessage("Fetching info...Please Wait!")
        self.ui.progressBar.setValue(0)

    def recommendMovies(self):
        list = getSeenMovies()
        reco_thread = RecommenderThread(self,15,list)
        reco_thread.startSignal.connect(self.init_progressbar)
        reco_thread.updateSignal.connect(self.update_progressbar)
        reco_thread.terminateSignal.connect(self.terminate_recos)
        reco_thread.start()

    def terminate_recos(self,recos):
        seen_movies = getSeenMovies()
        seen_movie_longnames = [name for id,imdb_id,name in seen_movies]
        for movie in recos:
            if movie["long imdb canonical title"] not in seen_movie_longnames:
                self.ui.listWidgetRecommend.addItem(movie['title'])
        self.terminate_progressbar()	
class blueCat(QtGui.QMainWindow):
    def __init__(self, app, parent=None):
        super(blueCat, self).__init__(parent)
        print("Ala ma kota")
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.bt = Bt()
        self.bt.new_beacon.connect(self.receive_beacon)

        self.blueNode = BlueNode('login', 'password')   # add your login 
        self.blueNode.new_data.connect(self.receive_node)

        self.detected_devices = []
        self.monitored_devices = []

        self.devices_live_time = 10  # after this amount of seconds of inactivity device is lost....
        self.timer_delete_old_devices = QtCore.QTimer()
        QtCore.QObject.connect(self.timer_delete_old_devices, QtCore.SIGNAL('timeout()'), self.delete_old_devices)
        # self.timer_delete_old_devices.start(self.devices_live_time*1000)

        # GUI
        QtCore.QObject.connect(self.ui.pushButton_add, QtCore.SIGNAL('clicked()'), self.button_add)
        QtCore.QObject.connect(self.ui.pushButton_connect, QtCore.SIGNAL('clicked()'), self.button_connect)

        self.ui.lineEdit_name.setText("Beacon1")
        self.ui.lineEdit_location.setText("Reaktor")


    def button_add(self):
        selected = self.ui.list_detected_devices.selectedItems()
        #print(selected)
        #print(len(selected))
        if len(selected) > 0:
            index = self.ui.list_detected_devices.row(selected[0])
            self.detected_devices[index].name = self.ui.lineEdit_name.text()
            self.detected_devices[index].location = self.ui.lineEdit_location.text()
            self.monitored_devices.append(self.detected_devices[index])
            self.ui.list_monitored_devices.addItem(self.detected_devices[index].__str__())
            self.ui.list_detected_devices.takeItem(index)
            del self.detected_devices[index]
            self.blueNode.send_device(self.JSON_create_devices_list())

    def button_connect(self):
        pass

    @QtCore.Slot(object)
    def delete_old_devices(self):
        current_time = time()
        detected_devices_temp = []
        number_of_deleted = 0
        for i in range(0, len(self.detected_devices)):
            if current_time - self.detected_devices[i].time < self.devices_live_time:
                detected_devices_temp.append(self.detected_devices[i])
            else:
                self.ui.list_detected_devices.takeItem(i-number_of_deleted)
                number_of_deleted += 1
        if number_of_deleted > 0:
            self.detected_devices = detected_devices_temp
        # print('Current time: ' + str(current_time) + ' Remove: '  + str(number_of_deleted))

    @QtCore.Slot(object)
    def receive_beacon(self, b):
        if b.UUID[0] == 1:  # Window sensor
            t = WindowDevice(b.UUID, "", "", time(), b.minor, ((b.major & 255)+200)*10, (b.major & 256)/256)
        elif b.UUID[0] == 2:
            t = DoorDevice(b.UUID, "", "", time(), b.minor, ((b.major & 255)+200)*10, (b.major & 256)/256)
        else:
            t = BeaconDevice(b.UUID, "", "", time(), b.minor, b.major, 0)
        # print(t)
        done = False
        for i in range(0, len(self.monitored_devices)):
            if self.monitored_devices[i].compare_UUID(t):
                done = True
                if not self.monitored_devices[i].compare(t):
                    self.monitored_devices[i].update(t)
                    self.ui.list_monitored_devices.item(i).setText(self.monitored_devices[i].__str__())
                    self.blueNode.send_update_device_value({"values": self.monitored_devices[i].json_update_device_value()})
                break
        if not done:
            for i in range(0, len(self.detected_devices)):
                if self.detected_devices[i].compare_UUID(t):
                    done = True
                    if not self.detected_devices[i].compare(t):
                        self.detected_devices[i] = t
                        self.ui.list_detected_devices.item(i).setText(self.detected_devices[i].__str__())
                    break
        if not done:
            self.detected_devices.append(t)
            self.ui.list_detected_devices.addItem(t.__str__())
        self.delete_old_devices()
        #print(self.detected_devices)
        #print(self.monitored_devices)

    @QtCore.Slot(object)
    def receive_node(self, data):
        print(data)

    def sigint_handler(self, *args):
        """
        Stop thread before end
        """
        self.bt.stop()
        self.blueNode.stop()
        QtGui.QApplication.quit()

    def JSON_create_devices_list(self):
        data = {"device_types": []}
        data['device_types'].append(BeaconDevice.json_update_device_type())
        data['device_types'].append(WindowDevice.json_update_device_type())
        data['device_types'].append(DoorDevice.json_update_device_type())
        for device in self.monitored_devices:
            if type(device) is BeaconDevice:
                data['device_types'][0]["devices"].append(device.json_update_devices())
            elif type(device) is WindowDevice:
                data['device_types'][1]["devices"].append(device.json_update_devices())
            elif type(device) is DoorDevice:
                data['device_types'][2]["devices"].append(device.json_update_devices())
        return data
Beispiel #45
0
class ChamiGUI(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.tv1model = QStandardItemModel()
        self.tv2model = QStandardItemModel()

        self.chami = Chami()
        self.db = self.chami.db

        self.setMyCoursesTreeView()
        self.setAllCoursesTreeView()


        # Starts the url consommer/downloader thread/queue
        self.downloader = Downloader()
        self.downloader.updateProgress.connect(self.set_progress)
        self.downloader.start()

        self.ui.downloadButton.setEnabled(False)
        self.ui.downloadButton.clicked.connect(lambda: self.download())
        self.ui.connectButton.clicked.connect(lambda: self.connect())
        self.ui.searchButton.clicked.connect(lambda: self.search())
        
        self.ui.searchLineEdit.returnPressed.connect(lambda: self.search())
        self.ui.passLineEdit.returnPressed.connect(lambda: self.connect())

        self.ui.action_Update_db.triggered.connect(lambda: self.update_db())


    def update_db(self):
        thread = threading.Thread(target=self._update_db)
        thread.daemon = True
        thread.start()


    def _update_db(self):
        chami = Chami()
        chami.connect(self.ui.userLineEdit.text(), self.ui.passLineEdit.text())

        courses = chami.courses_to_be_updated()
        chami.update_db(courses)
        self.ui.statusbar.showMessage('Updating {} courses...'.format(len(courses)), 6000)
        

    def set_progress(self, url, remaining, percent):
        if remaining > 0:
            self.ui.statusbar.showMessage('Remaining files: {0} ({1}% of {2})'.format(remaining, percent, local_path(url)))
        else:
            self.ui.statusbar.showMessage('Download complete!')


    def connect(self):
        username = self.ui.userLineEdit.text()
        # if user enters 12345 or g12345 instead of G12345
        username = username.upper()
        if not 'G' in username:
            username = '******' + username
            self.ui.userLineEdit.setText(username)

        connect = self.chami.connect(username, self.ui.passLineEdit.text())
        print('connected:', connect)
        if not connect:
            self.ui.statusbar.showMessage('Something went wrong when connecting, check user/password', 6000)
            self.ui.userLineEdit.setStyleSheet('QLineEdit { color: red }')
            self.ui.passLineEdit.setStyleSheet('QLineEdit { color: red }')
            self.ui.downloadButton.setEnabled(False)
        else:
            self.ui.statusbar.showMessage('Successfully connected!', 6000)
            self.ui.downloadButton.setEnabled(True)

            self.ui.connectButton.setText('Disconnect')
            self.ui.userLineEdit.setEnabled(False) #setStyleSheet('QLineEdit { color: green }')
            self.ui.passLineEdit.setEnabled(False) #setStyleSheet('QLineEdit { color: green }')
            self.ui.connectButton.clicked.connect(lambda: self.disconnect())

            self.downloader.set_session(self.chami.session)

    def disconnect(self):
        self.chami.disconnect()

        self.ui.statusbar.showMessage('Disconnected.', 6000)
        self.ui.downloadButton.setEnabled(False)

        self.ui.connectButton.setText('Connect')
        self.ui.userLineEdit.setEnabled(True)
        self.ui.passLineEdit.setEnabled(True)
        self.ui.connectButton.clicked.connect(lambda: self.connect())


    def search(self):
        self.setMyCoursesTreeView(self.ui.searchLineEdit.text())
        self.setAllCoursesTreeView(self.ui.searchLineEdit.text())

    def download(self):
        global queue

        for selectedIndex in (self.ui.treeView.selectedIndexes() + self.ui.treeView_2.selectedIndexes()):
            print(selectedIndex.data())
            urls = self.children_folders(selectedIndex.data(), selectedIndex, [])

            if selectedIndex.data() and urls and urls[0]:
                for url in urls:
                    print('Queueing {}'.format(url))
                    queue.put(url)

        # for j in jobs:
        #     print(j.url, j.status)

        # urls = [j.url for j in jobs if j.status == 403]

        # print(urls)

        # if urls:
        #     #msgBox = QMessageBox()
                #QMessageBox.warning(self, 'Download error', 'Some files could not be downloaded.', buttons=QMessageBox.Ok)
        #     #msgBox.setText('Some files could not be downloaded.')
        #     #msgBox.exec_()


    def parent_folder(self, folder, index, liste):
        parent = index.parent()
        liste.append(folder)
        
        if parent.data():
            self.parent_folder(parent.data(), parent, liste)
            return liste


    def children_folders(self, folder, index, liste):
        # XXX: refactoring really needed
        if self.ui.coursesTabWidget.currentIndex() == 0:
            if self.tv2model.itemFromIndex(index) and self.tv2model.itemFromIndex(index).rowCount() == 0:
                # could not find how to access url directly, has to use parent...
                item = self.tv2model.itemFromIndex(index)
                row = item.row()
                url = index.parent().child(row, 2).data()

                return [url]

            for row in range(self.tv2model.itemFromIndex(index).rowCount()):
                folder = index.child(row,0).data()
                
                if self.tv2model.itemFromIndex(index.child(row,0)).rowCount() > 0:
                    #print('recursive', folder)
                    self.children_folders(folder, index.child(row,0), liste)
                else:
                    url = index.child(row,2).data()
                    if url:
                        #print('appending', index.child(row,0).data())
                        liste.append(url)

        else:

            if self.tv1model.itemFromIndex(index) and self.tv1model.itemFromIndex(index).rowCount() == 0:
                # could not find how to access url directly, has to use parent...
                item = self.tv1model.itemFromIndex(index)
                row = item.row()
                url = index.parent().child(row, 2).data()

                return [url]

            for row in range(self.tv1model.itemFromIndex(index).rowCount()):
                folder = index.child(row,0).data()
                
                if self.tv1model.itemFromIndex(index.child(row,0)).rowCount() > 0:
                    #print('recursive', folder)
                    self.children_folders(folder, index.child(row,0), liste)
                else:
                    url = index.child(row,2).data()
                    if url:
                        #print('appending', index.child(row,0).data())
                        liste.append(url)

        return liste

    def setMyCoursesTreeView(self, regex=None):
        self.tv2model.clear()
        self.tv2model = self.setTreeView(self.db.select_my_courses(regex))

        self.ui.treeView_2.setModel(self.tv2model)
        self.ui.treeView_2.setSortingEnabled(True) # enable sorting
        self.ui.treeView_2.sortByColumn(1, Qt.SortOrder(Qt.AscendingOrder)) # sort by course name, A-Z
        self.ui.treeView_2.setSelectionMode(QAbstractItemView.ExtendedSelection) # single selection or Ctrl
        self.ui.treeView_2.header().setResizeMode(QHeaderView.ResizeToContents) # auto resize columns
        self.ui.treeView_2.setEditTriggers(QAbstractItemView.NoEditTriggers) # don't allow to change names
            
    def setAllCoursesTreeView(self, regex=None):
        self.tv1model.clear()
        self.tv1model = self.setTreeView(self.db.select_courses(regex))

        self.ui.treeView.setModel(self.tv1model)
        self.ui.treeView.setSortingEnabled(True) # enable sorting
        self.ui.treeView.sortByColumn(1, Qt.SortOrder(Qt.AscendingOrder)) # sort by course name, A-Z
        self.ui.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection) # single selection or Ctrl
        self.ui.treeView.header().setResizeMode(QHeaderView.ResizeToContents) # auto resize columns
        self.ui.treeView.setEditTriggers(QAbstractItemView.NoEditTriggers) # don't allow to change names

    def setTreeView(self, courses):
        def append_folders(course_id=None, parent_folder=None, parent=None):

            folders = self.db.select_folders(course_id, parent_folder)

            for folder in folders:
                qsi_folder = append_files(course_id, folder[0], QStandardItem(folder[1]))

                parent.appendRow(append_folders(course_id, folder[0], qsi_folder))

            return parent

        def append_files(course_id=None, parent_folder=None, folder=None):

            files = self.db.select_files(course_id, parent_folder)

            for filee in files:
                folder.appendRow([QStandardItem(filee[2]), QStandardItem(filee[3]), QStandardItem(filee[4])])

            return folder


        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(['Course ID', 'Course Name', 'URL'])

        for course in courses:

            course_id = course[0]
            course = self.db.select_course(course_id)[0]

            parent = append_folders(course_id, '/', QStandardItem(course_id))

            model.appendRow([parent, QStandardItem(course[1])])

        return model
Beispiel #46
0
class core:
	def loadConfig(self):
		import ConfigParser
		config = ConfigParser.ConfigParser()
		if os.path.exists('rsaChat.rc'):
			config.read('rsaChat.rc')
			self.xmpp_jid = config.get('Settings', 'jid')
			self.xmpp_pwd = config.get('Settings', 'passwd')
		else:
			print '''
File rsaChat.rc not found.
Example
-------------------------

[Settings]
jid = nick@server
passwd = reallyStrongPass

-------------------------
'''
			exit(0)
		'''
		#пример записи в настройки, на всякий случай
		config.add_section('Settings')
		config.set('Settings', 'jid', '*****@*****.**')
		config.set('Settings', 'passwd', 'e9oojqw534')
		with open('example.cfg', 'wb') as configfile:
			config.write(configfile)
		'''
	def getKey(self,to):
		mesg = "#getkey"
		self.jb.send(to,mesg)
	def messageCB(self,conn,mess):
		#Данный колбек проверяет регулярное выражение, после чего 
		#Либо рабоатет с ключами, либо шифрует сообения
		if ( mess.getBody() == None ):
			return	
		msg = mess.getBody()
		patern = re.compile('^#(getkey|sendkey|mesg|getlastmesg) ?(.*)')
		res = patern.search(msg)
		if res:
			#Проверка
			a = res.groups()[0]
			if a == "getkey":
				self.sendKey(mess.getFrom())
				if  self.crypt.hasKey(mess.getFrom())!=False:
					conn.send(mess.getFrom(),"#getkey")	
			elif a == "sendkey":
				if res.groups()[1]!='':
					a = self.crypt.decodeKey(res.groups()[1].decode("hex"))
					self.crypt.saveKey(mess.getFrom().getStripped(),a)
			elif a == "mesg":
				decryptMess = self.crypt.decryptMesg(res.groups()[1])
				if decryptMess=="#errorDecrypt":
					self.sendKey(mess.getFrom())
					self.print_("Error decrypt sendKey")
				else:
					self.print_(self.to+"--> "+decryptMess)
			elif a == "getlastmesg*":
				print a
	def print_(self,text):
		self.ui.textBrowser.append(text)
	def sendKey(self,to):
		#Берем публичный ключ и прегоняем его в hex и отправляем
		key = '#sendkey '+ self.crypt.pubKey.save_pkcs1(format='DER').encode('hex')
		self.jb.send(to,key)
	def sendMsg(self):
		#Ужастная функция с костылем которая прверяет наличие ключа
		#При наличии отправляет собщение иначе иницирует обмен ключами
		if self.crypt.hasKey(self.to)==False:
			self.getKey(self.to)
			return
		text = unicode(self.ui.lineEdit.text().toUtf8(), "utf-8")	
		if text=="":
			return
		print text
		acam = ""
		#Проблема модуля шифрования в ограничении длины строки, поэтому костыль
		while(len(text)>0):
			if(len(text)>29):
				cutText = text[0:29]
				text = text[29:]
			else:
				cutText = text
				text = ""

			mes = self.crypt.cryptMesg(self.to,cutText)
			self.ui.lineEdit.clear()
			self.jb.send(self.to,"#mesg "+mes)
			acam = acam + cutText
		self.print_(self.to+"<-- "+acam)
	def setToRow(self,alpha):
		#Устанавливаем кому отправлять сообещния, в списке делаем его в фокусе
		self.to = unicode(self.ui.listWidget.item(alpha).text().toUtf8(), "utf-8")
		self.ui.lineEdit.setFocus()
		self.print_("Now mesg to "+self.to)
	def __init__(self):
		#Первым делом загрузим настройки
		self.loadConfig()
		#Создадим объект для шифорования
		self.crypt = Crypt()
		
		#Создадим и подключимся к жабберу
		self.jb = sjabber(self.xmpp_jid,self.xmpp_pwd)
		self.jb.connect()
		
		#Зададим колбек для приходящих сообщений
		self.jb.setCB(self.messageCB)

		#Создадим Qt обработчик событий для графики
		self.app = QApplication(sys.argv)

		self.window = QMainWindow()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self.window)
		#Подключим сигналы нажатия на кнопку отправить и нажатие энтер
		self.ui.pushButton.clicked.connect(self.sendMsg)
		self.ui.lineEdit.returnPressed.connect(self.sendMsg)

		self.window.show()

		#А теперь заполним юзерлист 
		userList = self.jb.userList()
		for i in userList:
			self.ui.listWidget.addItem(i)	
		#Меняем пользователя для отправки собщения
		self.ui.listWidget.currentRowChanged.connect(self.setToRow)
		#Выберем по умолчанию первого пользователя
		self.ui.listWidget.setCurrentRow(0)

		#Создадим рабочего который будет "дергать" обработчик жаббера
		self.workThread = WorkThread()
		self.workThread.setWorker(self.jb)
		self.workThread.start()
		#собственно запускаем обработчик сигналов и ожидаем его завершения
		sys.exit(self.app.exec_())
Beispiel #47
0
class NetworkTest(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.setFixedSize(self.size()) # disable resizing
        
        self.serial = None # serial object with configs
        self.ports = [] # list of open ports
        self.name = NODE_NAME # name of this node
        self.node = None # name of node to send to
        self.input = "" # text input from another device
        self.nodes = [] # nodes in range of this one
        self.oldNodes = []
        self.thread = None # thread for listening to the network
        self.queue = [] # queue of messages to send when possible
        
        self.port = PORT
        self.baud = BAUD_RATE
        self.parity = PARITY
        self.stopBits = STOP_BITS
        self.byteSize = BYTE_SIZE
        
        self.initialize() # initialize the interface
        
        # QT signals used
        clicked = QtCore.SIGNAL("clicked()")
        toggled = QtCore.SIGNAL("toggled(bool)")
        itemClicked = QtCore.SIGNAL("itemClicked(QListWidgetItem *)")
        indexChanged = QtCore.SIGNAL("currentIndexChanged(const QString&)")
        textChanged = QtCore.SIGNAL("textChanged(const QString&)")
        returnPressed = QtCore.SIGNAL("returnPressed()")
        
        # list widget connections
        QtCore.QObject.connect(self.ui.listPorts, itemClicked, self.select_port)
        QtCore.QObject.connect(self.ui.listNodes, itemClicked, self.select_node)
        
        # radio button connections
        QtCore.QObject.connect(self.ui.radioEven, toggled, self.select_parity)
        QtCore.QObject.connect(self.ui.radioOdd, toggled, self.select_parity)
        QtCore.QObject.connect(self.ui.radioMark, toggled, self.select_parity)
        QtCore.QObject.connect(self.ui.radioSpace, toggled, self.select_parity)
        QtCore.QObject.connect(self.ui.radioNone, toggled, self.select_parity)
        
        QtCore.QObject.connect(self.ui.radio1, toggled, self.select_stop_bits)
        QtCore.QObject.connect(self.ui.radio15, toggled, self.select_stop_bits)
        QtCore.QObject.connect(self.ui.radio2, toggled, self.select_stop_bits)
        
        QtCore.QObject.connect(self.ui.radio5, toggled, self.select_byte_size)
        QtCore.QObject.connect(self.ui.radio6, toggled, self.select_byte_size)
        QtCore.QObject.connect(self.ui.radio7, toggled, self.select_byte_size)
        QtCore.QObject.connect(self.ui.radio8, toggled, self.select_byte_size)
        
        # combo box connections
        QtCore.QObject.connect(self.ui.comboBaudRate, indexChanged, self.select_baud)
       
        # line edit connections
        QtCore.QObject.connect(self.ui.textName, textChanged, self.change_name)
        QtCore.QObject.connect(self.ui.textSend, returnPressed, self.send_text)
        
        # button connections
        QtCore.QObject.connect(self.ui.btnSend, clicked, self.send_text)
        QtCore.QObject.connect(self.ui.btnSendImage, clicked, self.send_image)
    
    def refresh(self):
        if self.thread != None:
            self.thread.stop()
        if self.serial != None:
            if self.serial.isOpen():
                self.serial.close()
                self.update_serial()
        self.thread = SerialListen(self)
        self.thread.start()
                
    def initialize(self):
        self.msg("Initializing...")
        
        self.ui.listPorts.clear()
        self.ports = self.list_ports()
        for port in self.ports:
            self.ui.listPorts.addItem(str(port))
        
        # Set default baud rate
        self.select_baud(BAUD_RATE)
        
        # Set default parity
        if PARITY == serial.PARITY_NONE:
            self.ui.radioNone.setChecked(True)
        elif PARITY == serial.PARITY_ODD:
            self.ui.radioOdd.setChecked(True)
        elif PARITY == serial.PARITY_MARK:
            self.ui.radioMark.setChecked(True)
        elif PARITY == serial.PARITY_SPACE:
            self.ui.radioSpace.setChecked(True)
        else:
            self.ui.radioEven.setChecked(True)
            self.parity = serial.PARITY_EVEN
        
        # Set default stop bits
        if float(STOP_BITS) == 1.0:
            self.ui.radio1.setChecked(True)
        elif float(STOP_BITS) == 1.5:
            self.ui.radio15.setChecked(True)
        else:
            self.stopBits = 2
            self.ui.radio2.setChecked(True)
        
        # Set default byte size
        if BYTE_SIZE == 5:
            self.ui.radio5.setChecked(True)
        elif BYTE_SIZE == 6:
            self.ui.radio6.setChecked(True)
        elif BYTE_SIZE == 7:
            self.ui.radio7.setChecked(True)
        else:
            self.ui.radio8.setChecked(True)
            self.byteSize = 8
        
        # Set default name
        self.change_name(self.random_name())
        
        # Clear list widgets
        self.ui.listNodes.clear()
        self.ui.listSentData.clear()
        self.ui.listReceivedData.clear()
        self.ui.listRelayedData.clear()
        
        
        self.msg("Initialized.")
    
    def send_ping(self):
        threading.Timer(5.0, self.send_ping).start()
        self.serial.write("{NAME=" + self.name + "}")
        self.oldNodes = self.nodes
        self.nodes = []
        
    def select_port(self, item):
        self.msg("Selecting new port: " + str(item.text()))
        self.port = int(item.text()[3:])
        self.update_serial()
        self.refresh()
        
    def select_node(self, item):
        self.msg("Selecting new node: " + str(item.text()))
        self.node = str(item.text())
        
    def select_parity(self, button):
        self.msg("Selecting new parity.")
        if self.ui.radioEven.isChecked():
            self.parity = serial.PARITY_EVEN
        elif self.ui.radioOdd.isChecked():
            self.parity = serial.PARITY_ODD
        elif self.ui.radioMark.isChecked():
            self.parity = serial.PARITY_MARK
        elif self.ui.radioSpace.isChecked():
            self.parity = serial.PARITY_SPACE
        else:
            selfparity = serial.PARITY_NONE
        
        
    def select_stop_bits(self, button):
        self.msg("Selecting new stop bits.")
        if self.ui.radio1.isChecked():
            self.stopBits = serial.STOPBITS_ONE
        elif self.ui.radio15.isChecked():
            self.stopBits = serial.STOPBITS_ONE_POINT_FIVE
        else:
            self.stopBits = serial.STOPBITS_TWO
            
        
    def select_byte_size(self, button):
        self.msg("Selecting new byte size.")
        if self.ui.radio5.isChecked():
            self.byteSize = serial.FIVEBITS
        elif self.ui.radio6.isChecked():
            self.byteSize = serial.SIXBITS
        elif self.ui.radio7.isChecked():
            self.byteSize = serial.SEVENBITS
        else:
            self.byteSize = serial.EIGHTBITS
            
        self.refresh()
    
    def select_baud(self, baud):
        self.msg("Selecting new baud rate: " + str(baud))
        index = self.ui.comboBaudRate.findText(str(baud))
        self.baud = self.ui.comboBaudRate.itemText(index)
        self.ui.comboBaudRate.setCurrentIndex(index)
        
        self.refresh()
        
    def change_name(self, name):
        self.msg("Changing this node's name to " + str(name))
        self.ui.textName.setText(name)
        self.name = name
        
    def send_text(self):
        if str(self.ui.textSend.text()) != "" and self.node != None:
            self.msg("Sending text: " + str(self.ui.textSend.text()))
            self.send(self.name, self.node, self.ui.textSend.text())
            self.ui.textSend.clear()
        elif self.node == None:
            self.msg("You must select a node to send this message.")
        else:
            self.msg("No text entered.")
     
    def send_image(self):
        image = str(QtGui.QFileDialog.getOpenFileName())
        imageStr = Image.open(image).tostring()
        self.serial.write(imageStr)
     
    # Sends a message with a specified sender and recipient
    def send(self, sender, recipient, text):
        message = "{FROM=" + sender + "}{TO=" + recipient + "}{TEXT=" + text + "}"
        #self.queue.append(message)
        self.serial.write(message)
        if sender == self.name:
            self.ui.listSentData.addItem("<To: " + recipient + "> " + text)
        
    # Prints a message to the user via the status bar.
    def msg(self, text):
        self.ui.statusbar.showMessage(str(text))

    def list_ports(self):
        ports = None
        if platform.system() == "Windows":
            ports = []
            for i in range(256):
                try:
                    s = serial.Serial(i)
                    ports.append("USB" + str("%03d" % (i,)))
                    s.close()
                except serial.SerialException:
                    pass
        else:
            ports = glob.glob("/dev/ttyS*") + glob.glob("/dev/ttyUSB*")
        return ports
        
    # Generates a random name for this node.
    def random_name(self):
        names = ["Donut", "Penguin", "Stumpy", "Whicker", "Howard",
                 "Wilshire", "Disco", "Jack", "Bear", "Sneak", "Wisp",
                 "Crazy", "Goat", "Pirate", "Hambone", "Walla", "Snake",
                 "Caboose", "Sleepy", "Stompy", "Mopey", "Dopey", "Weasel",
                 "Ghost", "Dasher", "Grumpy", "Hollywood", "Noodle", "Cupid",
                 "Abraham", "Prancer", "Blinky", "Bonobo", "Banana", "Cinnabon"]
                 
        rand = random.randint(0, len(names) - 1)
        return names[rand]
    
    def update_serial(self):
        try:
            #self.serial = serial.Serial(self.port, self.baud, self.byteSize, 
            #                            self.parity, self.stopBits)
            if self.thread != None:
                self.thread.stop()
                self.thread = None
            if self.serial != None:
                if self.serial.isOpen():
                    self.serial.close()
                    self.serial = None
                    
            self.serial = serial.Serial(self.port)
            self.send_ping()
        except Exception as e:
            self.msg("Serial already initialized, " + str(e))
Beispiel #48
0
class Testsuite(QMainWindow):
    
    trigger = QtCore.pyqtSignal(int)
    socket_error = QtCore.pyqtSignal()
    update_status = QtCore.pyqtSignal(str)
    tests_finished = QtCore.pyqtSignal()
    
    demorun = False
    
    if "--demo" in sys.argv:
        demorun = True
        print "Running ft6 in demo mode!"

    def keyPressEvent(self, event):
        if type(event) == QtGui.QKeyEvent:
            if event.key() == QtCore.Qt.Key_Escape:
                self.close()

            event.accept()
        else:
            event.ignore()

    def __init__(self):
        QMainWindow.__init__(self)
        
        self.tm = TestManager.TestManager(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.pushButton_all.hide()
        self.ui.pushButton_logFile.hide()
        
        # add all checkboxes to class variable
        self.checkboxes = []
        self.allthetests = []
        self.add_checkboxes()
        
        # attatch widgets to handlers
        self.ui.pushButton_none.clicked.connect(self.noneButtonHandler)
        self.ui.pushButton_all.clicked.connect(self.allButtonHandler)
        self.ui.pushButton_logFile.clicked.connect(self.logfileButtonHandler)
    
        if Testsuite.demorun:
            self.ui.pushButton_start.clicked.connect(self.demoButtonHandler)
            self.ui.pushButton_start.setText("Simulate")
        else:
            self.ui.pushButton_start.clicked.connect(self.startButtonHandler)
            

        # the list view needs this model
        self.model = QStandardItemModel()

        self.ui.results_listView.setModel(self.model)
        self.ui.results_listView.clicked.connect(self.listViewClickHandler)
        
        self.trigger.connect(self.testFinished)
        self.socket_error.connect(self.socketErrorHandler)
        self.update_status.connect(self.updateStatusHandler)
        self.tests_finished.connect(self.testsFinishedHandler)
        
        self.update_status.emit("Disconnected.")

        # fix the order in which pressing the tab key cycles through the widgets
        # http://stackoverflow.com/questions/9371007/programmatically-edit-tab-order-in-pyqt4-python
        self.setTabOrder(self.ui.lineEdit_target_address, self.ui.lineEdit_open_port)
        self.setTabOrder(self.ui.lineEdit_open_port, self.ui.lineEdit_closed_port)
        self.setTabOrder(self.ui.lineEdit_closed_port, self.ui.pushButton_start)

        self.loadSettings()

        
    """ shows the details for the test """
    def listViewClickHandler(self, index):
        # take into account the mapping between the list of selected test to the list of available tests
        # eg, we've selected tests [1,2,4,6]
        # the index.row() will be the n-th element of that list, eg the value '4' will be at index 2
        # so we have to translate the index (2) to the value (4). 
        # fortunately, these are stored in the allthettests list.
        # we can now ask the testmanager what the id'th test is     
        id = self.allthetests[index.row()]
        if Testsuite.demorun:
            self.demoTests[index.row()].showDetailsWindow()
        else:
            self.tm.getTest(id).showDetailsWindow()
        
    """ handles clicks to the 'None' button: uncheck all checkboxes """
    def noneButtonHandler(self):
        self.ui.pushButton_none.hide()
        self.ui.pushButton_all.show()
        
        for checkbox in self.checkboxes:
            checkbox.setChecked(0)
        
    """ handles clicks to the 'All' button: check all checkboxes """
    def allButtonHandler(self):
        self.ui.pushButton_all.hide()
        self.ui.pushButton_none.show()
        
        for checkbox in self.checkboxes:
            checkbox.setChecked(1)
                
    def saveSettings(self):
        try:
            f = open("ft6.conf", "w")
            f.write("%s\n" % str(self.ui.lineEdit_target_address.text()))
            f.write("%d\n" % int(self.ui.lineEdit_open_port.text()))
            f.write("%d\n" % int(self.ui.lineEdit_closed_port.text()))
            f.close()
        except IOError:
            print "Uh-Oh!"
            raise

    def loadSettings(self):
        settings = []
        try: 
            f = open("ft6.conf", "r")
            for i in range(3):
                settings.append(f.readline().strip())

            f.close()
        except IOError,e:
            if e[0] == errno.ENOENT:
                print "no configuration file ft6.conf found. using defaults"
                self.loadDefaults()
            else:
                raise


        if len(settings) == 3:
            self.ui.lineEdit_target_address.setText(settings[0])
            self.ui.lineEdit_open_port.setText(settings[1])
            self.ui.lineEdit_closed_port.setText(settings[2])
        else:
            print "something wrong with configuration file ft6.conf. using defaults"
            self.loadDefaults()
Beispiel #49
0
class NeuroDaqWindow(QtGui.QMainWindow):
    """ Assembles the main NeuroDAQ user interface.
    
    Data management:
    
    All H5 items that contain data are stored in workingDataTree.dataItems. The property 
    item.listIndex contains the location of the item on the list, so that it can be accessed
    programatically when needed.
    
    To keep track of data plotted in dataPlotsWidget, the items plotted are stored in
    dataPlotsWidget.plotDataItems.
    
    OBSOLETE:    
    Data loaded in the Working Data tree are stored in list workingDataTree.data. Each item in 
    the tree has a property item.dataIndex that is the position of the item's data in the list.
    
    To keep track of data plotted in dataPlotsWidget, the indexes of the plotted data are stored 
    in dataPlotsWidget.plotDataIndex
    """
    
    def __init__(self, parent=None):    
        # Initialise and setup UI
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        
        # Lists for storing data
        self.db = None
        self.wdb = None
        self.ui.dataPlotsWidget.plotDataItems = []
        
        # Current working file and folder for saving
        self.currentSaveFile = []
        self.currentFolder = self.ui.dirTree.homeFolder
        self.saveFolder = self.currentFolder

        # Share instance with other modules by setting global variable browser
        utilsconsole.set_browser(self)

        # Load custom analysis modules
        self.customToolSelector  = toolselector.ToolSelector()        
        for module in dir(moduleLoader):               
            try:  
                sys.modules['analysis.modules.'+module].AnalysisModule(self)
                #print dir(m)
                #if hasattr(m, 'AnalysisModule'): 
                #    m.AnalysisModule(self)   
                #    print 'Loaded module', m
            except KeyError:
                pass
            except:    
                print module, sys.exc_info()


        # Directory browser
        # -----------------------------------------------------------------------------
        self.ui.dirTree.selectionModel().selectionChanged.connect(self.load_h5_OnSelectionChanged)
        self.ui.loadFolderInput.setText(self.currentFolder)
        self.ui.loadFolderButton.clicked.connect(self.select_loadFolder)
        self.ui.saveFolderInput.setText(self.currentFolder)
        self.ui.saveFolderButton.clicked.connect(self.select_saveFolder)

        # File data tree
        # -----------------------------------------------------------------------------
        self.ui.fileDataTree.data = []
        self.ui.fileDataTree.root = self.ui.fileDataTree.invisibleRootItem()
        self.ui.fileDataTree.root.attrs = {}        
        self.ui.fileDataTree.currentItemChanged.connect(self.plot_OnSelectionChanged)
        self.ui.fileDataTree.itemSelectionChanged.connect(lambda: self.store_Selection(1))
        self.ui.workingDataTree.itemSelectionChanged.connect(lambda: self.store_Selection(2))
        self.ui.loadFolderInput.returnPressed.connect(self.update_loadDir)
        self.ui.saveFolderInput.textChanged.connect(self.update_saveDir)
        self.connect(self.ui.dirTree, QtCore.SIGNAL('fileDeletePressed'), self.delete_file)

        # Analysis tab selection
        # -----------------------------------------------------------------------------
        self.ui.selectionTabWidget.currentChanged.connect(self.tab_changed)
      

        # Analysis selection list
        # -----------------------------------------------------------------------------
        self.ui.oneDimToolSelect.selectionModel().selectionChanged.connect(self.select_analysisTool)
        self.ui.customToolSelect.selectionModel().selectionChanged.connect(self.select_analysisTool)
        self.ui.behaviourToolSelect.selectionModel().selectionChanged.connect(self.select_analysisTool)
        self.ui.graphToolSelect.selectionModel().selectionChanged.connect(self.select_analysisTool)
        self.ui.imageToolSelect.selectionModel().selectionChanged.connect(self.select_analysisTool)                
        self.selectionList = []
        self.selectionList.append([self.ui.oneDimToolSelect, self.ui.oneDimToolStackedWidget, '1D Analysis'])
        self.selectionList.append([self.ui.behaviourToolSelect, self.ui.behaviourToolStackedWidget, 'Behaviour Analysis'])
        self.selectionList.append([self.ui.imageToolSelect, self.ui.imageToolStackedWidget, 'Image Analysis'])
        self.selectionList.append([self.ui.graphToolSelect, self.ui.graphToolStackedWidget, 'Graph'])        
        self.selectionList.append([self.ui.customToolSelect, self.ui.customToolStackedWidget, 'Custom Analysis'])

        # Working data tree
        # -----------------------------------------------------------------------------
        self.ui.workingDataTree.data = []
        self.ui.workingDataTree.dataItems = []
        self.ui.workingDataTree.root = self.ui.workingDataTree.invisibleRootItem()
        self.ui.workingDataTree.root.attrs = {}
        self.ui.actionLoadData.triggered.connect(self.load_h5OnLoadPush)
        self.ui.actionNewFile.triggered.connect(self.create_h5OnNewPush)
        self.ui.actionSaveFile.triggered.connect(self.save_h5OnSavePush)
        self.ui.actionSaveFileAs.triggered.connect(self.save_h5OnSaveAsPush)
        self.connect(self.ui.workingDataTree, QtCore.SIGNAL('dropped'), self.move_itemsAcross)
        self.connect(self.ui.workingDataTree, QtCore.SIGNAL('targetPosition'), self.set_targetPosition)
        self.connect(self.ui.workingDataTree, QtCore.SIGNAL('deletePressed'), self.remove_itemOnMenu)
        self.ui.workingDataTree.currentItemChanged.connect(self.browse_OnSelectionChanged)
        self.ui.workingDataTree.propsDt = ''
        self.ui.workingDataTree.propsDescription = ''   

        # Context menu
        self.ui.workingDataTree.customContextMenuRequested.connect(self.open_workingDataTreeMenu)
        self.ui.actionAddRootGroup.triggered.connect(self.add_rootGroupOnMenu)
        self.ui.actionAddChildGroup.triggered.connect(self.add_childGroupOnMenu)
        self.ui.actionRenameTreeItem.triggered.connect(self.rename_itemOnMenu)
        self.ui.actionRemoveTreeItem.triggered.connect(self.remove_itemOnMenu)
        self.ui.actionShowInTable.triggered.connect(self.show_inTableOnMenu)    

        # Data table        
        # -----------------------------------------------------------------------------
        self.connect(self.ui.dataTableWidget, QtCore.SIGNAL('droppedInTable'), self.copy_itemsToTable)
        self.connect(self.ui.dataTableWidget, QtCore.SIGNAL('tableTargetPosition'), self.set_targetTablePosition)

        # Properties table        
        # -----------------------------------------------------------------------------        
        self.ui.propsTableWidget.setRowCount(2)
        self.ui.propsTableWidget.setColumnCount(1)
        self.ui.propsTableWidget.horizontalHeader().setVisible(False)
        self.ui.propsTableWidget.setData({'dt':['']})
        #self.ui.propsTableWidget.setData({'Description':['']})
        
        #self.ui.workingDataTree.propsItemDtLabel = QtGui.QTableWidgetItem('dt')
        #self.ui.workingDataTree.propsItemDt = QtGui.QTableWidgetItem(self.ui.workingDataTree.propsDt)
        #self.ui.workingDataTree.propsItemDescriptionLabel = QtGui.QTableWidgetItem('Description')
        #self.ui.workingDataTree.propsItemDescription = QtGui.QTableWidgetItem(self.ui.workingDataTree.propsDescription)                
        #self.ui.propsTableWidget.setVerticalHeaderItem(0, self.ui.workingDataTree.propsItemDtLabel)
        #self.ui.propsTableWidget.setItem(0,0,self.ui.workingDataTree.propsItemDt)
        #self.ui.propsTableWidget.setVerticalHeaderItem(1, self.ui.workingDataTree.propsItemDescriptionLabel)
        #self.ui.propsTableWidget.setItem(1,0,self.ui.workingDataTree.propsItemDescription)
        #self.connect(self.ui.propsTableWidget, QtCore.SIGNAL('updateAttr'), self.updateItemAttrs)     
        self.ui.propsTableWidget.itemSelectionChanged.connect(self.updateItemAttrs)        

        
        # IPython tab
        # -----------------------------------------------------------------------------        
        self.ui.IPythonWidget.pushVariables({'browser': self, 'aux': auxfuncs, 'dataTree': self.ui.workingDataTree,
                                    'dataPlot': self.ui.dataPlotsWidget, 'ndaq': utilsconsole, 
                                    'canvas': self.ui.mplWidget.canvas, 'ax': self.ui.mplWidget.canvas.ax})

        # Plots tab
        # ----------------------------------------------------------------------------- 
        self.ui.actionPlotData.triggered.connect(self.plot_selected)
        self.ui.actionShowCursors.triggered.connect(self.show_cursors)
        self.ui.actionAnalyseData.triggered.connect(self.analyse_data)

        # Video tab
        # ----------------------------------------------------------------------------- 
        self.ui.actionVideoPlotData.triggered.connect(self.videoPlot_selected)

    # -----------------------------------------------------------------------------
    # HDF5 file Methods
    # -----------------------------------------------------------------------------
    def load_h5_OnSelectionChanged(self, newSelection, oldSelection):
        """ Load hdf5 file
        """
        if self.db: 
            if self.dbType=='hdf5':
                self.db.close()
            self.db = None
        h5.load_h5(self, self.ui.fileDataTree, push=False)

    def load_h5OnLoadPush(self):
        h5.load_h5(self, self.ui.workingDataTree, push=True)
        
    def create_h5OnNewPush(self):
        h5.create_h5(self, self.ui.workingDataTree)

    def save_h5OnSavePush(self):
        if self.currentSaveFile:
            fname = os.path.split(self.currentSaveFile)[1] # update save folder to user selected if necessary
            self.currentSaveFile = str(self.saveFolder) + '/' + fname
            h5.save_h5(self, self.ui.workingDataTree)
        else: 
            fname, ok = QtGui.QInputDialog.getText(self, 'New file', 'Enter file name:')
            if ok:
                self.currentSaveFile = str(self.saveFolder) + '/' + fname + '.hdf5'
                h5.save_h5(self, self.ui.workingDataTree)
        h5.load_h5(self, self.ui.fileDataTree, push=False) # Re-open currently selected file
        
    def save_h5OnSaveAsPush(self):
        fname, ok = QtGui.QInputDialog.getText(self, 'New file', 'Enter file name:')
        if self.ui.saveFolderInput.text()<>'': self.update_saveDir()
        if ok:
            self.currentSaveFile = self.saveFolder + '/' + fname + '.hdf5'      
            h5.save_h5(self, self.ui.workingDataTree)        
        h5.load_h5(self, self.ui.fileDataTree, push=False) # Re-open currently selected file

    def delete_file(self):
        index = self.ui.dirTree.selectedIndexes()[0]
        currentFile = str(index.model().filePath(index))
        try:
            os.remove(currentFile)
        except OSError:
            return

    # -----------------------------------------------------------------------------
    # Tree Methods
    # -----------------------------------------------------------------------------    
    def update_loadDir(self):
        treefun.set_loadFolder(self, self.ui.dirTree, self.ui.loadFolderInput.text())

    def update_saveDir(self):
        self.saveFolder = self.ui.saveFolderInput.text()

    def select_loadFolder(self):
        folder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Folder", self.currentFolder))
        treefun.set_loadFolder(self, self.ui.dirTree, folder)
        self.ui.loadFolderInput.setText(folder)

    def select_saveFolder(self):
        self.saveFolder = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Folder", self.saveFolder))        
        self.ui.saveFolderInput.setText(self.saveFolder)
    
    def store_Selection(self, source):
        """ Store user selected tree items in dragItems list to get them back
        once they have been dropped. Source '1' is fileDataTree and '2' is
        workingDataTree. 
        """
        if source==1:   # Move
            self.dragItems = []
            dataTree = self.ui.fileDataTree
            for originalIndex in dataTree.selectedIndexes():
                item = dataTree.itemFromIndex(QtCore.QModelIndex(originalIndex))
                self.dragItems.append([item.path, item.text(0), item.listIndex, originalIndex, 
                                      item.data, item.attrs])
                #self.dragItems.append([item, originalIndex])
        elif source==2: # Copy
            dataTree = self.ui.workingDataTree
            self.copyItems = []
            for item in self.ui.workingDataTree.selectedItems():          
                self.copyItems.append(item)        

    def move_itemsAcross(self, source, modifiers):
        """ Create new tree items and populate the target tree. Originally made 
        for moving items from fileDataTree to workingDataTree, but then modified
        to copy items when the move is internal in workingDataTree and Ctrl is 
        pressed.
        """
        if (source==self.ui.workingDataTree) and (modifiers==QtCore.Qt.ControlModifier):
          # Copy internally
          #print 'copying'
          targetItems = []
          for item in self.copyItems:
            i = h5Item([str(item.text(0))])
            i.data = item.data
            targetItems.append(i)             
          parentIndex = self.ui.workingDataTree.indexFromItem(self.dragTargetParent)
          for row in np.arange(0, len(self.copyItems)):
            index = self.ui.workingDataTree.model().index(self.dragTargetRow+row, 0, parentIndex)        
            temp_item = self.ui.workingDataTree.itemFromIndex(QtCore.QModelIndex(index))
            sip.delete(temp_item)        
            if parentIndex.isValid():
                self.make_nameUnique(self.dragTargetParent, targetItems[row], targetItems[row].text(0))
                self.dragTargetParent.insertChild(index.row(), targetItems[row])
                originalParentWidget = self.copyItems[row]
                h5.populate_h5copyItems(self, originalParentWidget, targetItems[row])
            else:
                self.make_nameUnique(self.ui.workingDataTree.invisibleRootItem(), targetItems[row], targetItems[row].text(0))
                self.ui.workingDataTree.insertTopLevelItem(index.row(), targetItems[row])     
                originalParentWidget = self.copyItems[row]
                h5.populate_h5copyItems(self, originalParentWidget, targetItems[row])       
        elif source==self.ui.workingDataTree:
          pass
        else:
          # Move across
          #print 'moving'
          targetItems = []
          for item in self.dragItems:
            i = h5Item([str(item[1])])
            i.path = item[0]
            i.listIndex = item[2]
            i.originalIndex = item[3]
            i.data = item[4]
            i.attrs = item[5]
            #item = i[0]
            #item.originalIndex = i[1]
            targetItems.append(i)             
          parentIndex = self.ui.workingDataTree.indexFromItem(self.dragTargetParent)
          for row in np.arange(0, len(self.dragItems)):
            index = self.ui.workingDataTree.model().index(self.dragTargetRow+row, 0, parentIndex)        
            temp_item = self.ui.workingDataTree.itemFromIndex(QtCore.QModelIndex(index))
            sip.delete(temp_item)        
            if parentIndex.isValid():
                self.make_nameUnique(self.dragTargetParent, targetItems[row], targetItems[row].text(0))
                self.dragTargetParent.insertChild(index.row(), targetItems[row])
                originalParentWidget = self.ui.fileDataTree.itemFromIndex(QtCore.QModelIndex(targetItems[row].originalIndex))
                h5.populate_h5dragItems(self, originalParentWidget, targetItems[row])
            else:
                self.make_nameUnique(self.ui.workingDataTree.invisibleRootItem(), targetItems[row], targetItems[row].text(0))
                self.ui.workingDataTree.insertTopLevelItem(index.row(), targetItems[row])     
                originalParentWidget = self.ui.fileDataTree.itemFromIndex(QtCore.QModelIndex(targetItems[row].originalIndex))
                h5.populate_h5dragItems(self, originalParentWidget, targetItems[row])
                
    def set_targetPosition(self, parent, row):
        self.dragTargetParent = parent
        self.dragTargetRow = row

    def make_nameUnique(self, parentWidget, item, originalName):
        """ Check existing names in parentWidget that start with item.text
        and get the next available index, as item.text_index.
        Updates item.text if name is not unique.
        """
        names = []
        name = originalName
        if parentWidget.childCount()>0:
            for c in range(parentWidget.childCount()):
                child = parentWidget.child(c)
                names.append(str(child.text(0)))
            unique = False
            i = 1
            while not unique:
                if name in names:
                    name = originalName + '_' + str(i)
                    i+=1
                else:
                    unique = True
        item.setText(0, name)

    def open_workingDataTreeMenu(self, position):
        """ Context menu for working data tree
        """
        self.workingDataTreeMenu = QtGui.QMenu()
        self.workingDataTreeMenu.addAction(self.ui.actionAddRootGroup)
        self.workingDataTreeMenu.addAction(self.ui.actionAddChildGroup)
        self.workingDataTreeMenu.addAction(self.ui.actionAddDataset)
        self.workingDataTreeMenu.addSeparator()
        self.workingDataTreeMenu.addAction(self.ui.actionRenameTreeItem)
        self.workingDataTreeMenu.addAction(self.ui.actionShowInTable)
        self.workingDataTreeMenu.addAction(self.ui.actionRemoveTreeItem)

        if len(self.ui.workingDataTree.selectedItems())==0: 
            self.ui.actionAddChildGroup.setDisabled(True)
            self.ui.actionRenameTreeItem.setDisabled(True)
        else:
            self.ui.actionAddChildGroup.setDisabled(False)
            self.ui.actionRenameTreeItem.setDisabled(False)            
        self.workingDataTreeMenu.exec_(self.ui.workingDataTree.viewport().mapToGlobal(position))

    def add_rootGroupOnMenu(self):
        text, ok = QtGui.QInputDialog.getText(self, 'New root group', 'Enter name:')
        if ok: treefun.add_treeGroup(self, self.ui.workingDataTree, 'root', str(text))
       
    def add_childGroupOnMenu(self):
        text, ok = QtGui.QInputDialog.getText(self, 'New child group', 'Enter name:')
        if ok: treefun.add_treeGroup(self, self.ui.workingDataTree, 'child', str(text))
    
    def rename_itemOnMenu(self):        
        currentText = self.ui.workingDataTree.currentItem().text(0)
        text, ok = QtGui.QInputDialog.getText(self, 'Rename item', 'Enter new name:', text=currentText)
        if ok: treefun.rename_treeItem(self, self.ui.workingDataTree, str(text))

    def remove_itemOnMenu(self):
        treefun.remove_treeItem(self, self.ui.workingDataTree)

    def show_inTableOnMenu(self):
        table.clear_table(self)
        table.put_dataOnTable(self)

    # -----------------------------------------------------------------------------
    # Analysis Methods
    # -----------------------------------------------------------------------------
    def select_analysisTool(self):
        i = self.ui.selectionTabWidget.currentIndex()
        toolSelectWidget = None
        for item in self.selectionList:
            if item[2]==self.ui.selectionTabWidget.tabText(i):  # get the widgets that belong to the selected tab
                toolSelectWidget = item[0]
                toolStackedWidget = item[1]           
        if toolSelectWidget and len(toolSelectWidget.selectedIndexes())>0:                
            index = toolSelectWidget.selectedIndexes()[0]
            # Display the matching stack in the stacked widget
            selectedItemName = toolSelectWidget.model.itemFromIndex(index).text()
            for w in toolStackedWidget.widgetList:
                if w[0]==selectedItemName: toolStackedWidget.setCurrentIndex(w[1])
        else:
            index = None        
        return index        

    def analyse_data(self):       
        # Get data source 
        i = self.ui.selectionTabWidget.currentIndex()
        for tab in self.ui.dataSource:
            if tab[0]==i: 
                dataSource = tab[1].currentText()
        if dataSource=='Plot':
            self.analysisItems = self.ui.dataPlotsWidget.plotDataItems  # deal with error as below
        else:
            self.analysisItems = self.ui.workingDataTree.selectedItems() # also deal with error

        # if cursors are selected and dataSource is Selection, ask if the cursors positions are  
        # to be applied to the selection, which could be useful

        #if len(self.ui.dataPlotsWidget.plotDataItems)==0: # Check that there is data plotted to analyse
        #    auxfuncs.error_box('There is no data to analyze', infoText='Please plot the data')
        #else:
        index = self.select_analysisTool()
        if index:
            tool = index.data() 
            self.customToolSelector.tool_select(self, tool)
        else:
            auxfuncs.error_box('No analysis function selected')

    def tab_changed(self, index):
        """ Use to set the minimum size of the left splitter depending on
        the tab seleceted. It's a hack, because the in-built automated setting
        of minimumSizeHint gets stuck on the highest value that it sees.
        """   
        self.ui.splitter_leftPane.setMinimumSize(self.ui.leftPaneSizes[index],1)

    # -----------------------------------------------------------------------------
    # Properties Methods
    # -----------------------------------------------------------------------------
    def updateItemAttrs(self):
        itemList = self.ui.workingDataTree.selectedItems()
        for item in itemList:
            attr = str(self.ui.propsTableWidget.verticalHeaderItem(0).text())
            #attrValue = float(self.ui.propsTableWidget.item(self.ui.propsTableWidget.currentItem().row(), 0).text()) # for dt
            attrValue = float(self.ui.propsTableWidget.currentItem().text())
            item.attrs[attr] = attrValue

    def test(self):
        print self.ui.propsTableWidget.currentItem().text()

    # -----------------------------------------------------------------------------
    # Table Methods
    # -----------------------------------------------------------------------------
    def show_inTableOnMenu(self):
        #self.ui.dataTableWidget.setData({'x': [1,2,3], 'y': [4,5,6]})#np.random.random(100))
        table.put_dataOnTable(self) #, self.ui.dataTableWidget)

    def set_targetTablePosition(self, col, row):
        self.dragTableTargetCol = col
        self.dragTableTargetRow = row

    def copy_itemsToTable(self, source, modifiers):
        if (source==self.ui.workingDataTree):
          print "something arrived at the Table"
          copyItems = []
          for item in self.copyItems:
             i = tableItem(str(item.text(0)))
             i.data = item.data
             targetItems.append(i)      
                 
          #parentIndex = self.ui.workingDataTree.indexFromItem(self.dragTargetParent)
          for row in np.arange(0, len(self.copyItems)):
             index = self.ui.dataTable.model().index(self.dragTableTargetCol, self.dragTableTargetRow) #, 0, parentIndex)        
             temp_item = self.ui.dataTable.itemFromIndex(QtCore.QModelIndex(index))
             sip.delete(temp_item)        
          #  if parentIndex.isValid():
          #      self.make_nameUnique(self.dragTargetParent, targetItems[row], targetItems[row].text(0))
          #      self.dragTargetParent.insertChild(index.row(), targetItems[row])
          #      originalParentWidget = self.copyItems[row]
          #      h5.populate_h5copyItems(self, originalParentWidget, targetItems[row])
          #  else:
          #      self.make_nameUnique(self.ui.workingDataTree.invisibleRootItem(), targetItems[row], targetItems[row].text(0))
          #      self.ui.workingDataTree.insertTopLevelItem(index.row(), targetItems[row])     
          #      originalParentWidget = self.copyItems[row]
          #      h5.populate_h5copyItems(self, originalParentWidget, targetItems[row])       


    # -----------------------------------------------------------------------------
    # Plotting Methods
    # -----------------------------------------------------------------------------
    def plot_OnSelectionChanged(self, current, previous):
        if current:
            data = h5.get_dataFromFile(self, current)
            if data is not None:
                pgplot.plot_singleData(self, self.ui.singlePlotWidget, data)    

    def browse_OnSelectionChanged(self, current, previous):
        if ('video' in current.attrs) and (current.attrs['video']=='True'):
            self.ui.dataVideoWidget.filename = str(current.attrs['mrl'])    
            self.ui.dataVideoWidget.OpenFile()  # not ideal, should maybe have a Load button    
        elif hasattr(current, 'data'): 
            # Show data values in status bar
            if current.data is not None:
                dataValue = str(current.data[0])
                self.ui.statusbar.showMessage('First data point value: ' + dataValue)
            else:
                self.ui.statusbar.clearMessage()
            # Plot data if Browse is selected
            if self.ui.actionBrowseData.isChecked():
              if current.data is not None: 
                if len(current.data.shape)==1:
                    pgplot.browse_singleData(self, self.ui.dataPlotsWidget, current)
                elif len(current.data.shape)>1:
                    pgplot.browse_image(self, self.ui.dataImageWidget, current)
            # Show dt
            self.ui.propsTableWidget.setData({'dt':[current.attrs['dt']]})
            #tableItem = QtGui.QTableWidgetItem(current.attrs['dt'])
            #tableItem.itemChanged = ''
            #self.ui.propsTableWidget.setItem(0,0, tableItem)

    def plot_selected(self):
        self.ui.actionBrowseData.setChecked(False)
        itemList = self.ui.workingDataTree.selectedItems()
        if itemList:
            pgplot.plot_multipleData(self, self.ui.dataPlotsWidget, itemList)   
            #print itemList[0].attrs['dt']    

    def videoPlot_selected(self):
        itemList = self.ui.workingDataTree.selectedItems()
        if itemList:
            pgplot.plot_multipleData(self, self.ui.dataVideoWidget.plotsWidget, itemList)   
            self.ui.dataVideoWidget.xmax = self.ui.dataVideoWidget.plotsWidget.viewBox.childrenBounds()[0][1]

    def zoom_out(self):
        pgplot.zoom_out(self, self.ui.dataPlotsWidget)

    def show_cursors(self):
        if self.ui.actionShowCursors.isChecked():
            pgplot.show_cursors(self, self.ui.dataPlotsWidget)
            self.ui.dataPlotsWidget.cursor = True
        else:
            pgplot.hide_cursors(self, self.ui.dataPlotsWidget)
            self.ui.dataPlotsWidget.cursor = False
Beispiel #50
0
class MyMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.master = None
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #Initialize Buttons
        self.ui.push_autostart.clicked.connect(self.buttonAutostart)
        self.ui.push_stop.clicked.connect(self.buttonStop)
        self.ui.push_charge.clicked.connect(self.buttonCharge)
        self.ui.push_discharge.clicked.connect(self.buttonDischarge)
        self.ui.push_catch.clicked.connect(self.buttonCatch)
        self.ui.push_release.clicked.connect(self.buttonRelease)
        #self.ui.push_reboot.clicked.connect(self.buttonReboot)
        #self.ui.push_shutdown.clicked.connect(self.buttonShutdown)
        
        #Rest
        self.set_process()
        self.timer = QtCore.QTimer()
        self.i = 0
        self.timer.timeout.connect(self.update)
        self.timer.start(500)
        
    def set_process(self):
        print('UI has started up.')
        self.color={'RGBwarning':"(255,0,0)",'RGBcaution':"(255,255,0)",'RGBok':"(0,255,0)",'RGBinfo':"(0,255,255)",'RGBwhite':"(255,255,255)",
                    'HEXwarning':"#ff0000",'HEXcaution':"#ffff00",'HEXok':"#00ff00",'HEXinfo':"#00ffff",'HEXwhite':"#ffffff"}
        
    def update(self):
        """Update the interface every so often as defined by self.timer.start(x)"""
        if self.i < 3:
            #self.ui.lineKerberos.setText(QtGui.QApplication.translate("MainWindow", str(""), None, QtGui.QApplication.UnicodeUTF8))
            #main.card()
            STATUS = "BOOTING UP"
        elif self.master.operation != None:
            STATUS = self.master.operation
        else:
            STATUS = "SYSTEM ERROR"
        
        #Acquire values from the subsystems
        HOST=self.master.HOST
        MAC=self.master.MAC
        IP=self.master.IP
        ROSMASTER=str(self.master.ROSMASTER)
        ROSTHREAD=str(self.master.ROSTHREAD)
        if self.master.drone == "None":
            DRONE="Cylon Raider 46F01Z1"
        else:
            DRONE=self.master.drone
        #print(HOST)
        if self.master.charger!=None and self.master.charger.Alive == True:
            CHARGERDEVICEcolor = self.color['RGBok']
            CHARGERDEVICE=str(self.master.charger.status)
            ELAPSEDTIME=self.master.charger.elapsed
            DRONEBATTERY=str('{0:.2f}'.format(self.master.charger.voltage))+"V "+str('{0:.2f}'.format(self.master.charger.current/1000))+"A "+str(self.master.charger.resistance)+"ohm "+str(self.master.charger.percentage)+"%"
            DRONECELL1=str('{0:.2f}'.format(self.master.charger.cell1))
            DRONECELL2=str('{0:.2f}'.format(self.master.charger.cell2))
            DRONECELL3=str('{0:.2f}'.format(self.master.charger.cell3))
            
        else:
            CHARGERDEVICEcolor = self.color['RGBwarning']
            CHARGERDEVICE="Disabled"
            ELAPSEDTIME=0
            DRONEBATTERY=None
            DRONECELL1=0
            DRONECELL2=0
            DRONECELL3=0

        if self.master.mechanism!=None and self.master.mechanism.Alive == True:
            SANDWICHMECHANISMcolor=self.color['RGBok']
            if self.master.mechanism.direction == 1:
                SANDWICHMECHANISM="Catch"
            elif self.master.mechanism.direction ==-1:
                SANDWICHMECHANISM="Release"
            else:
                SANDWICHMECHANISM="Neutral"

            q1fsr = self.master.mechanism.fsr[0]
            q2fsr = self.master.mechanism.fsr[1]
            q3fsr = self.master.mechanism.fsr[2]
            q4fsr = self.master.mechanism.fsr[3]

            q1limit0 = self.master.mechanism.limit[0][0]
            q1limit1 = self.master.mechanism.limit[0][1]
            q2limit0 = self.master.mechanism.limit[1][0]
            q2limit1 = self.master.mechanism.limit[1][1]
            q3limit0 = self.master.mechanism.limit[2][0]
            q3limit1 = self.master.mechanism.limit[2][1]
            q4limit0 = self.master.mechanism.limit[3][0]
            q4limit1 = self.master.mechanism.limit[3][1]

            if q1fsr>=self.master.mechanism.fsrThreshold:
                q1fsr="___ "+str(q1fsr)[:5]
                q1fsr_color=self.color['HEXcaution']
            elif q1fsr>=self.master.mechanism.fsrCritical:
                q1fsr="HIT "+str(q1fsr)[:5]
                q1fsr_color=self.color['HEXok']
            else:
                q1fsr="HIT "+str(q1fsr)[:5]
                q1fsr_color=self.color['HEXwarning']

            if q2fsr>=self.master.mechanism.fsrThreshold:
                q2fsr="___ "+str(q2fsr)[:5]
                q2fsr_color=self.color['HEXcaution']
            elif q2fsr>=self.master.mechanism.fsrCritical:
                q2fsr="HIT "+str(q2fsr)[:5]
                q2fsr_color=self.color['HEXok']
            else:
                q2fsr="HIT "+str(q2fsr)[:5]
                q2fsr_color=self.color['HEXwarning']

            if q3fsr>=self.master.mechanism.fsrThreshold:
                q3fsr="___ "+str(q3fsr)[:5]
                q3fsr_color=self.color['HEXcaution']
            elif q3fsr>=self.master.mechanism.fsrCritical:
                q3fsr="HIT "+str(q3fsr)[:5]
                q3fsr_color=self.color['HEXok']
            else:
                q3fsr="HIT "+str(q3fsr)[:5]
                q3fsr_color=self.color['HEXwarning']

            if q4fsr>=self.master.mechanism.fsrThreshold:
                q4fsr="___ "+str(q4fsr)[:5]
                q4fsr_color=self.color['HEXcaution']
            elif q4fsr>=self.master.mechanism.fsrCritical:
                q4fsr="HIT "+str(q4fsr)[:5]
                q4fsr_color=self.color['HEXok']
            else:
                q4fsr="HIT "+str(q4fsr)[:5]
                q4fsr_color=self.color['HEXwarning']

            if q1limit0==1:
                q1limit0="HIT"
                q1limit0color=self.color['HEXwarning']
            else:
                q1limit0="___"
                q1limit0color=self.color['HEXcaution']

            if q1limit1==1:
                q1limit1="HIT"
                q1limit1color=self.color['HEXwarning']
            else:
                q1limit1="___"
                q1limit1color=self.color['HEXcaution']

            if q2limit0==1:
                q2limit0="HIT"
                q2limit0color=self.color['HEXwarning']
            else:
                q2limit0="___"
                q2limit0color=self.color['HEXcaution']

            if q2limit1==1:
                q2limit1="HIT"
                q2limit1color=self.color['HEXwarning']
            else:
                q2limit1="___"
                q2limit1color=self.color['HEXcaution']

            if q3limit0==1:
                q3limit0="HIT"
                q3limit0color=self.color['HEXwarning']
            else:
                q3limit0="___"
                q3limit0color=self.color['HEXcaution']

            if q3limit1==1:
                q3limit1="HIT"
                q3limit1color=self.color['HEXwarning']
            else:
                q3limit1="___"
                q3limit1color=self.color['HEXcaution']

            if q4limit0==1:
                q4limit0="HIT"
                q4limit0color=self.color['HEXwarning']
            else:
                q4limit0="___"
                q4limit0color=self.color['HEXcaution']

            if q4limit1==1:
                q4limit1="HIT"
                q4limit1color=self.color['HEXwarning']
            else:
                q4limit1="___"
                q4limit1color=self.color['HEXcaution']
            
        else:
            SANDWICHMECHANISMcolor = self.color['RGBwarning']
            SANDWICHMECHANISM="Disabled"
            q1fsr_color=self.color['HEXwarning']
            q2fsr_color=self.color['HEXwarning']
            q3fsr_color=self.color['HEXwarning']
            q4fsr_color=self.color['HEXwarning']
            q1limit0color=self.color['HEXwarning']
            q2limit0color=self.color['HEXwarning']
            q3limit0color=self.color['HEXwarning']
            q4limit0color=self.color['HEXwarning']
            q1limit1color=self.color['HEXwarning']
            q2limit1color=self.color['HEXwarning']
            q3limit1color=self.color['HEXwarning']
            q4limit1color=self.color['HEXwarning']
            q1fsr=""
            q2fsr=""
            q3fsr=""
            q4fsr=""
            q1limit0=""
            q2limit0=""
            q3limit0=""
            q4limit0=""
            q1limit1=""
            q2limit1=""
            q3limit1=""
            q4limit1=""

        UPTIME=int(time.time() - self.master.bootupTime)

        IPcolor = self.color['RGBwarning']
        ROScolor = self.color['RGBwarning']
        DRONEcolor = self.color['RGBinfo']
        DRONEBATTERYcolor = self.color['RGBcaution']
        DRONECELL1color = self.color['RGBcaution']
        DRONECELL2color = self.color['RGBcaution']
        DRONECELL3color = self.color['RGBcaution']
        ELAPSEDTIMEcolor = self.color['RGBinfo']
        UPTIMEcolor = self.color['RGBinfo']
        STATUScolor = self.color['RGBwhite']
        NETWORKcolor = self.color['RGBinfo']
        
        if str(IP)!="None":
            IPcolor = self.color['RGBok']
        else:
            IP="Disconnected"

        if str(ROSMASTER)=="None":
            ROSMASTER="Master:None"
        if str(ROSTHREAD)=="None":
            ROSTHREAD="Topics:None"
        if str(CHARGERDEVICE)=="Enabled":
            CHARGERDEVICEcolor=self.color['RGBok']            

        #Update Color and Style
        self.ui.label_internetO.setStyleSheet("color: rgb"+IPcolor+";")
        self.ui.label_rosO.setStyleSheet("color: rgb"+ROScolor+";")
        self.ui.label_chargerO.setStyleSheet("color: rgb"+CHARGERDEVICEcolor+";")
        self.ui.label_mechanismO.setStyleSheet("color: rgb"+SANDWICHMECHANISMcolor+";")
        self.ui.label_droneO.setStyleSheet("color: rgb"+DRONEcolor+";")
        self.ui.label_dronebatteryO.setStyleSheet("color: rgb"+DRONEBATTERYcolor+";")
        self.ui.label_dronecell1O.setStyleSheet("color: rgb"+DRONECELL1color+";")
        self.ui.label_dronecell2O.setStyleSheet("color: rgb"+DRONECELL2color+";")
        self.ui.label_dronecell3O.setStyleSheet("color: rgb"+DRONECELL3color+";")
        self.ui.label_elapsedO.setStyleSheet("color: rgb"+ELAPSEDTIMEcolor+";")
        self.ui.label_uptimeO.setStyleSheet("color: rgb"+UPTIMEcolor+";")
        self.ui.label_status.setStyleSheet("color: rgb"+STATUScolor+";")
        self.ui.label_network.setStyleSheet("color: rgb"+NETWORKcolor+";")
        #Update Text
        self.ui.label_Q1.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q1</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q1fsr_color+";\">"+str(q1fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">LSO: </span><span style=\" color:"+q1limit0color+";\">"+str(q1limit0)+"  </span><span style=\" font-weight:600;\">LSI: </span><span style=\" color:"+q1limit1color+";\">"+str(q1limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_Q2.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q2</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q2fsr_color+";\">"+str(q2fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">LSO: </span><span style=\" color:"+q2limit0color+";\">"+str(q2limit0)+"  </span><span style=\" font-weight:600;\">LSI: </span><span style=\" color:"+q2limit1color+";\">"+str(q2limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_Q3.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q3</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q3fsr_color+";\">"+str(q3fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">LSO: </span><span style=\" color:"+q3limit0color+";\">"+str(q3limit0)+"  </span><span style=\" font-weight:600;\">LSI: </span><span style=\" color:"+q3limit1color+";\">"+str(q3limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_Q4.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q4</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q4fsr_color+";\">"+str(q4fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">LSO: </span><span style=\" color:"+q4limit0color+";\">"+str(q4limit0)+"  </span><span style=\" font-weight:600;\">LSI: </span><span style=\" color:"+q4limit1color+";\">"+str(q4limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        
        #self.ui.label_Q1.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q1</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q1fsr_color+";\">"+str(q1fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Outside: </span><span style=\" color:"+q1limit0color+";\">"+str(q1limit0)+"</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Inside: </span><span style=\" color:"+q1limit1color+";\">"+str(q1limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        #self.ui.label_Q2.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q2</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q2fsr_color+";\">"+str(q2fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Outside: </span><span style=\" color:"+q2limit0color+";\">"+str(q2limit0)+"</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Inside: </span><span style=\" color:"+q2limit1color+";\">"+str(q2limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        #self.ui.label_Q3.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q3</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q3fsr_color+";\">"+str(q3fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Outside: </span><span style=\" color:"+q3limit0color+";\">"+str(q3limit0)+"</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Inside: </span><span style=\" color:"+q3limit1color+";\">"+str(q3limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        #self.ui.label_Q4.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-weight:600;\">Q4</span></p><p align=\"center\"><span style=\" font-weight:600;\">FSR: </span><span style=\" color:"+q4fsr_color+";\">"+str(q4fsr)+"v</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Outside: </span><span style=\" color:"+q4limit0color+";\">"+str(q4limit0)+"</span></p><p align=\"center\"><span style=\" font-weight:600;\">Limit Switch Inside: </span><span style=\" color:"+q4limit1color+";\">"+str(q4limit1)+"</span></p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_internetO.setText(QtGui.QApplication.translate("MainWindow", str(IP), None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_rosO.setText(QtGui.QApplication.translate("MainWindow", str(ROSMASTER) + " " + str(ROSTHREAD), None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_chargerO.setText(QtGui.QApplication.translate("MainWindow", str(CHARGERDEVICE), None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_mechanismO.setText(QtGui.QApplication.translate("MainWindow", str(SANDWICHMECHANISM), None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_droneO.setText(QtGui.QApplication.translate("MainWindow", str(DRONE), None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_dronebatteryO.setText(QtGui.QApplication.translate("MainWindow", str(DRONEBATTERY), None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_dronecell1O.setText(QtGui.QApplication.translate("MainWindow", "C1: "+str(DRONECELL1)+"v", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_dronecell2O.setText(QtGui.QApplication.translate("MainWindow", "C2: "+str(DRONECELL2)+"v", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_dronecell3O.setText(QtGui.QApplication.translate("MainWindow", "C3: "+str(DRONECELL3)+"v", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_elapsedO.setText(QtGui.QApplication.translate("MainWindow", str(ELAPSEDTIME)+"s", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_uptimeO.setText(QtGui.QApplication.translate("MainWindow", str(UPTIME)+"s", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_status.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\">"+str(STATUS)+"</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.label_network.setText(QtGui.QApplication.translate("MainWindow", "<html><head/><body><p align=\"center\">"+str(HOST)+"</p><p align=\"center\">"+str(MAC)+"</p></body></html>", None, QtGui.QApplication.UnicodeUTF8))

        self.i += 1
         
    def reset(self):
        self.i=-1
        pass

    def buttonAutostart(self):
        """Wrapper for Autostart"""
        thread = threading.Thread(target=self.master.runAutostart, args=())
        thread.daemon = True
        thread.name = "UI-Autostart-"+thread.name
        thread.start()
        
    def buttonStop(self):
        """Wrapper for Stop"""
        thread = threading.Thread(target=self.master.runStop, args=())
        thread.daemon = True
        thread.name = "UI-Stop-"+thread.name
        thread.start()
        
    def buttonCharge(self):
        """Wrapper for Charge"""
        thread = threading.Thread(target=self.master.runCharge, args=())
        thread.daemon = True
        thread.name = "UI-Charge-"+thread.name
        thread.start()

    def buttonDischarge(self):
        """Wrapper for Discharge"""
        #Unimplemented currently. You can use buttonCharge as a template. Check the Instructions dictionary in the battery.py file for implementation.
        #Must create runDischarge() in main.py and discharge() battery.py if implemented.
        pass

    def buttonCatch(self):
        """Wrapper for Catch"""
        thread = threading.Thread(target=self.master.runCatch, args=())
        thread.daemon = True
        thread.name = "UI-Catch-"+thread.name
        thread.start()

    def buttonRelease(self):
        """Wrapper for Release"""
        thread = threading.Thread(target=self.master.runRelease, args=())
        thread.daemon = True
        thread.name = "UI-Release-"+thread.name
        thread.start()

    def buttonReboot(self):
        """Wrapper for Reboot"""
        self.master.reboot()

    def buttonShutdown(self):
        """Wrapper for Shutdown"""
        self.master.shutdown()

    def instance(self):
        """Return the GUI object"""
        return self
Beispiel #51
0
class ControlMainWindow(QtGui.QMainWindow):
    #used to limit how often its updated
    currentFrame = 0
    #attributes:
    #   view: 0=standard, 1=motion, 2=heatmap
    def __init__(self, parent=None):
        super(ControlMainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.view = 0;
        self.ui.setupUi(self)
        
        #SIGNALS
        self.ui.actionStandard.triggered.connect(self.view_standard)
        self.ui.actionMotion.triggered.connect(self.view_motion)
        self.ui.actionHeat_Map.triggered.connect(self.view_heat_map)
        self.ui.actionReset_Heat_Map.triggered.connect(self.reset)
        self.ui.actionClear_Teams.triggered.connect(self.clear_teams)
        self.ui.actionAdd_Teams.triggered.connect(self.add_team)
        
        self._timer = QtCore.QTimer(self)
        self._timer.timeout.connect(self.play)
        self._timer.start(27)
        self.update()
        
    #SLOTS (functions to bind signals to)
    def view_standard(self):
        self.view = 0
     
    def view_motion(self):
        self.view = 1
        
    def view_heat_map(self):
        self.view = 2
        
    def play(self):
        self.currentFrame += 1
        rawHeatmap = CC.getLatestRawHeatmaps()
        if self.view == 0:
            img = CC.getLatestFrames()
        elif self.view == 1:
            img = CC.getLatestThresholds()
        else:
            img = CC.getLatestHeatmaps()
        if len(img) > 0:
            self.ui.label1.setPixmap(convertImg(img[0]))
            self.ui.label1.mousePressEvent = self.getPos
        if len(img) > 1:
            self.ui.label2.setPixmap(convertImg(img[1]))
            self.ui.label2.mousePressEvent = self.getPos
        if len(img) > 2:
            self.ui.label3.setPixmap(convertImg(img[2]))   # QLabels hold images that we update
            self.ui.label3.mousePressEvent = self.getPos
        if len(img) > 3:
            self.ui.label4.setPixmap(convertImg(img[3]))
            self.ui.label4.mousePressEvent = self.getPos

            if ((self.currentFrame % 10) == 0):
                for t in gl.teams:
                    t.update(rawHeatmap[0])   
                gl.sortTeams()                      # sort by intensity
                self.ui.tableWidget.clearContents() # clear widget
                for i in xrange(len(gl.teams)):    # display new order in widget
                    item = QtGui.QTableWidgetItem(gl.teams[i].id) # widget item associated with display
                    intensityString = '%.2f' % gl.teams[i].intensity
                    intensity = QtGui.QTableWidgetItem(intensityString)
                    self.ui.tableWidget.setItem(i, 0, item)
                    self.ui.tableWidget.setItem(i, 1, intensity)

        else:
            pass
            #print "No images to pull!"

    def getPos(self , event):
        x = event.pos().x()
        y = event.pos().y() 
        print "x: ", x, " y:", y

    def clear_teams(self):
        gl.removeAll()

    def add_team(self):
        # d = QtGui.QInputDialog(self)
        # d.show()

        # Get user input: we figure out x,y coords by observing position of mouse click events over the images.
        # label is which box (camera display) its in 1,2, or 3 starting from top-left
        ans, ok = QtGui.QInputDialog.getText(self, "Team Info", "Enter exactly --> label:team_name:x1,y1:x2,y2")

        if (ok and len(ans) > 0):
            insert_team(ans)

    def insert_team(self, ans):
        # OK was clicked with data
        info = ans.split(":")
        label = int(info[0])
        name = info[1]
        x1,y1 = info[2].split(",")
        x2,y2 = info[3].split(",")
        x1 = int(x1)
        x2 = int(x2)
        y1 = int(y1)
        y2 = int(y2)
        gl.addTeam(x1, x2, y1, y2, id = name, label = label )

    def remove_team(self):
        ans, ok = QtGui.QInputDialog.getText(self, "Remove Team", "Enter the team's ID'")
        if ok and len(ans) > 0:
            gl.removeTeam(ans)

    def reset(self):
        self.clear_teams()
        CC = CameraControl()
        CC.connectToAllHosts()       
        CC.startMotionDetection()
Beispiel #52
0
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.q = Queue()
        self.task_list = []

        self.check_status_cmd = 'adb devices'
        self.check_status = False
        self.under_autotesting = False        #switch; lock buttons while under autotesting
        self.under_testing = False    #switch; lock buttons while under testing
        self.bgtimer = QTimer()
        self.bgtimer.setInterval(1000)
        self.bgtimer.timeout.connect(lambda:self.update_ui(self.check_status))
        self.bgtimer.start()

        self.ui.btnFirmwareversion.clicked.connect(lambda: self.on_btn(self.ui.btnFirmwareversion))
        self.ui.btnNand.clicked.connect(lambda: self.on_btn(self.ui.btnNand))
        self.ui.btnFirmwareversion_2.clicked.connect(lambda: self.on_btn(self.ui.btnFirmwareversion_2))
        self.ui.btnNand_2.clicked.connect(lambda: self.on_btn(self.ui.btnNand_2))
        self.ui.btnFirmwareversion_3.clicked.connect(lambda: self.on_btn(self.ui.btnFirmwareversion_3))
        self.ui.btnNand_3.clicked.connect(lambda: self.on_btn(self.ui.btnNand_3))
        self.ui.autotest.clicked.connect(lambda: self.on_btn(self.ui.autotest))


        self.auto_test_task = auto_test.AutoTest(self)
        self.auto_test_task.sig_update_ui.connect(self.update_message)
        self.firmware_version_task = firmware_version.FirmwareVersion(self)
        self.task_list.append(self.firmware_version_task)
        self.nand_task = nand.Nand(self)
        self.task_list.append(self.nand_task)
        self.firmware_version_task2 = firmware_version.FirmwareVersion(self)
        self.task_list.append(self.firmware_version_task2)
        self.nand_task2 = nand.Nand(self)
        self.task_list.append(self.nand_task2)
        self.firmware_version_task3 = firmware_version.FirmwareVersion(self)
        self.task_list.append(self.firmware_version_task3)
        self.nand_task3 = nand.Nand(self)
        self.task_list.append(self.nand_task3)
        for task in self.task_list:
            task.sig_update_ui.connect(self.update_message)


    def on_btn(self,button):
        running_btn_name = button.text()
        if running_btn_name == 'Auto Test':
            if self.q.empty():
                for task in self.task_list:
                    self.q.put(task)
            self.auto_test_task.start()

        if running_btn_name == 'Firmwareversion':
            self.firmware_version_task.start()

        if running_btn_name == 'NAND':
            self.nand_task.start()

        if running_btn_name == 'Firmwareversion2':
            self.firmware_version_task2.start()

        if running_btn_name == 'NAND2':
            self.nand_task2.start()

        if running_btn_name == 'Firmwareversion3':
            self.firmware_version_task3.start()

        if running_btn_name == 'NAND3':
            self.nand_task3.start()


    def update_message(self, data):
        self.ui.listWidget.addItem(data)


    def update_ui(self, data):
        adb_result = subprocess.Popen(self.check_status_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        (output, err) = adb_result.communicate()
        adb_return_code = adb_result.wait()
        check_status = data
        if '2-1' in str(output):
            print('Log: ' + str(adb_return_code) + '; device connected')
            self.check_status = True
            if self.under_autotesting or self.under_testing:
                self.disable_button()
            else:
                self.enable_button()

        else:
            print('Log: ' + str(adb_return_code) + '; decice disconnected')
            self.disable_button()
            self.check_status = False


    def enable_button(self):    #set button enable
        self.ui.autotest.setEnabled(True)
        self.ui.btnFirmwareversion.setEnabled(True)
        self.ui.btnNand.setEnabled(True)
        self.ui.btnFirmwareversion_2.setEnabled(True)
        self.ui.btnNand_2.setEnabled(True)
        self.ui.btnFirmwareversion_3.setEnabled(True)
        self.ui.btnNand_3.setEnabled(True)


    def disable_button(self):    #set button disable to click
        self.ui.autotest.setEnabled(False)
        self.ui.btnFirmwareversion.setEnabled(False)
        self.ui.btnNand.setEnabled(False)
        self.ui.btnFirmwareversion_2.setEnabled(False)
        self.ui.btnNand_2.setEnabled(False)
        self.ui.btnFirmwareversion_3.setEnabled(False)
        self.ui.btnNand_3.setEnabled(False)


    def closeEvent(self, event):
        print('Bye')
Beispiel #53
0
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        # nazwa klasy
        self.source=Source()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        QtCore.QObject.connect(self.ui.Button_LoadMainFilePath,QtCore.SIGNAL("clicked()"), self.Button_LoadMainFilePath)
        QtCore.QObject.connect(self.ui.Button_LoadConfigPath,QtCore.SIGNAL("clicked()"), self.Button_LoadConfigPath)
        QtCore.QObject.connect(self.ui.Button_LoadOutFile,QtCore.SIGNAL("clicked()"), self.Button_LoadOutFileCandidate)      
        QtCore.QObject.connect(self.ui.Button_RemoveOutFile,QtCore.SIGNAL("clicked()"), self.Button_RemoveOutFile)
        QtCore.QObject.connect(self.ui.Button_AddWWW,QtCore.SIGNAL("clicked()"), self.Button_AddWWWClicked)
        QtCore.QObject.connect(self.ui.Button_Przelicz,QtCore.SIGNAL("clicked()"), self.Button_Przelicz)
        QtCore.QObject.connect(self.ui.Button_CloseAddWWW,QtCore.SIGNAL("clicked()"), self.CloseAddWWW)
        QtCore.QObject.connect(self.ui.horizontalSlider_Threshold,QtCore.SIGNAL("valueChanged(int)"), self.horizontalSlider_ThresholdValueChanged)
        QtCore.QObject.connect(self.ui.Button_LoadOutFileCandidateFromWWW,QtCore.SIGNAL("clicked()"), self.Button_LoadOutFileCandidateFromWWW)
        QtCore.QObject.connect(self.ui.listWidget_OutFilesList,QtCore.SIGNAL("doubleClicked(QModelIndex)"), self.listWidget_OutFilesListDClicked)        
        QtCore.QObject.connect(self.ui.listWidget_MainFile,QtCore.SIGNAL("doubleClicked(QModelIndex)"), self.listWidget_MainFileDClicked)
        QtCore.QObject.connect(self.ui.listWidget_ChoosenOutFile,QtCore.SIGNAL("doubleClicked(QModelIndex)"), self.listWidget_ChoosenOutFileDClicked)
        QtCore.QObject.connect(self.ui.comboBox_MethodList,QtCore.SIGNAL("currentIndexChanged(int)"), self.comboBox_MethodListClicked)
        QtCore.QObject.connect(self.ui.listWidget_wwwFromMainFile,QtCore.SIGNAL("doubleClicked(QModelIndex)"), self.listWidget_wwwFromMainFileDClicked)
       
        
        #actions
        QtCore.QObject.connect(self.ui.actionNowy_projekt,QtCore.SIGNAL("triggered()"), self.Button_LoadMainFilePath)
        QtCore.QObject.connect(self.ui.actionOtw_rz_projekt,QtCore.SIGNAL("triggered()"), self.Button_LoadConfigPath)
        QtCore.QObject.connect(self.ui.actionDodaj_plik,QtCore.SIGNAL("triggered()"), self.Button_LoadOutFileCandidate)
        QtCore.QObject.connect(self.ui.actionDodaj_WWW,QtCore.SIGNAL("triggered()"), self.Button_LoadOutFileCandidateFromWWW)
        QtCore.QObject.connect(self.ui.actionUsu_plik,QtCore.SIGNAL("triggered()"), self.Button_RemoveOutFile)
        QtCore.QObject.connect(self.ui.actionDokumentacja,QtCore.SIGNAL("triggered()"), self.Action_Dokumentacja)                

        #init
        self.ui.listWidget_wwwFromMainFile.setVisible(False)    
        self.ui.lineEdit_wwwPath.setVisible(False) 
        self.ui.Button_AddWWW.setVisible(False) 
        self.ui.Button_CloseAddWWW.setVisible(False)

    '''Methods to load propertly 1 site'''

    def CloseAddWWW(self):
        self.ui.listWidget_wwwFromMainFile.setVisible(not self.ui.listWidget_wwwFromMainFile.isVisible())    
        self.ui.lineEdit_wwwPath.setVisible(not self.ui.lineEdit_wwwPath.isVisible()) 
        self.ui.Button_AddWWW.setVisible(not self.ui.Button_AddWWW.isVisible()) 
        self.ui.Button_CloseAddWWW.setVisible(not self.ui.Button_CloseAddWWW.isVisible())
    
    def Action_Dokumentacja(self):
        webbrowser.open_new_tab("https://github.com/Vallher/Plagiat/wiki")
    
    
    def Button_LoadMainFilePath(self): #
        
        path=QtGui.QFileDialog.getOpenFileName(self,'Open','',filter='Text files (*.txt *pdf *html *docx);;All files (*)')
        path=str(path)
        self.source.SetPath(path)
        try:
            self.source.PrepareMainFile()
        except Exception as ex:
            self.ui.listWidget_errorList.addItem("Błąd ładowania pliku glównego / Brak lub błędna ścieżka")

        name="Projekt" #TODOO
        self.source.SetConfigName(name) 
        try:
            self.source.CreateConfig()
        except Exception as ex:
            self.ui.listWidget_errorList.addItem("Bład tworzenia konfiguracji")
        self.RefreshDisplay()
        
    def Button_LoadConfigPath(self):  #
        path=QtGui.QFileDialog.getOpenFileName(self,'Open','',filter='Config files (*.json);;All files (*)')
        path=str(path)
        self.source.SetPath(path)
        
        try:
            self.source.LoadConfig()
        except Exception as ex:
            self.ui.listWidget_errorList.addItem("Błąd ładowania pliku zewnętrznego / Brak lub błędna ścieżka")

        self.RefreshDisplay()
    
    #2
    ''''Methods to load properly 2 site'''    
    def UpdateOutFilesList(self):    
        self.ui.listWidget_OutFilesList.clear()
        for outFile in self.source.OutFiles:
            name=outFile.GetFileName()
            self.ui.listWidget_OutFilesList.addItem(name)
        return True
    
    
    def UpdateWWWlist(self):
        self.ui.listWidget_wwwFromMainFile.clear()
        try:
            list= self.source.GetAdressFromMainFile()
            for adress in list:
                self.ui.listWidget_wwwFromMainFile.addItem(adress)    
        except:
            pass
    
    def RefreshDisplay(self):
        self.UpdateMainFileText()
        self.UpdateWWWlist()
        self.UpdateOutFilesList()
        self.UpdateMainFileText()
        try:
            self.source.GenerateRaport()
        except:
            print("")
        self.LoadOutFilesListInRaport()
        self.UpdateChoosenOutFileText()    
        self.UpdateRaportStats()
        self.ColorMainFile()
        self.ColorOutFilesList()
        threshold=self.ui.horizontalSlider_Threshold.value()
        self.ui.label_numberOfThreshold.setText(str(threshold))
        return True
    
    
    def listWidget_wwwFromMainFileDClicked(self):
        adressList= self.source.GetAdressFromMainFile()
        clickedRow=self.ui.listWidget_wwwFromMainFile.currentRow()
        path=[adressList[clickedRow]]
        self.source.AddOutFileCandidate(path)
        self.AddOutFiles()

    
    def Button_AddWWWClicked(self):
        path=[str(self.ui.lineEdit_wwwPath.text())]
        self.source.AddOutFileCandidate(path)
        try:
            self.AddOutFiles()
        except:
            self.ui.listWidget_errorList.addItem("Nie wybrano pliku")
    
    #button
    def Button_LoadOutFileCandidateFromWWW(self):
        self.ui.listWidget_wwwFromMainFile.setVisible(not self.ui.listWidget_wwwFromMainFile.isVisible())    
        self.ui.lineEdit_wwwPath.setVisible(not self.ui.lineEdit_wwwPath.isVisible()) 
        self.ui.Button_AddWWW.setVisible(not self.ui.Button_AddWWW.isVisible())  
        self.ui.Button_CloseAddWWW.setVisible(not self.ui.Button_CloseAddWWW.isVisible())
        return True
    
    def Button_LoadOutFileCandidate(self):
        #path=self.source.SearchFile()
        path=QtGui.QFileDialog.getOpenFileNames(self,'Open','',filter='Text files (*.txt *pdf *html *docx);;All files (*)')

        newPat=[]
        for p in path:
            newPat.append(str(p))
        path=newPat
        self.source.AddOutFileCandidate(path)
        try:
            self.AddOutFiles()
        except:
            pass
    def Button_RemoveOutFile(self):
        clickedRow=self.ui.listWidget_OutFilesList.currentRow()
        try:
            self.source.RemoveOutFile(clickedRow)
        except:
            self.ui.listWidget_errorList.addItem("Nie wybrano pliku do usunięcia")
        self.UpdateOutFilesList()
        self.RefreshDisplay()
    
    def AddOutFiles(self):
        self.ui.progressBar_GenerateOutFile.setValue(0)
        howMuchOut=len(self.source.OutFilesCandidate)
        valueRaise=100.0/howMuchOut
        done=[]
        for outFile in self.source.OutFilesCandidate:
            self.ui.progressBar_GenerateOutFile.setValue(self.ui.progressBar_GenerateOutFile.value()+valueRaise)
            try:
                self.source.GenerateOutFile([outFile])
            except Exception as ex:
                self.ui.listWidget_errorList.addItem(ex.args[0]+": "+ex.args[1]) 
            done.append(outFile)
            self.UpdateOutFilesList()
        for complete in done:
            self.source.OutFilesCandidate.remove(complete)
        self.UpdateOutFilesList()
        self.RefreshDisplay()
            
    def horizontalSlider_ThresholdValueChanged(self):
        threshold=self.ui.horizontalSlider_Threshold.value()
        self.source.threshold=threshold
        self.RefreshDisplay()

        return True
    def Button_Przelicz(self):
        self.ui.progressBar_GenerateOutFile.setValue(0)
        howMuchOut=len(self.source.OutFiles)+1
        valueRaise=100.0/howMuchOut
        
        
        for OutFile in self.source.OutFiles:
            self.ui.progressBar_GenerateOutFile.setValue(self.ui.progressBar_GenerateOutFile.value()+valueRaise)
            OutFile.repeats.pop()
            self.source.CheckSimilarity(OutFile)
        self.ui.progressBar_GenerateOutFile.setValue(100)
        self.RefreshDisplay()
        return True


        '''Method to properly load 3 site'''
    
    def UpdateRaportStats(self):
        mainFileSentencesNumber=self.source.HowManySentencesInMainFile()
        numberOfRepeatSentences=self.source.HowManySentencesRepeats()
        self.ui.label_numberOfSentences.setText(str(mainFileSentencesNumber))
        self.ui.label_numberOfRepeatSentences.setText(str(numberOfRepeatSentences))
        try:
            percentValue=numberOfRepeatSentences*100/mainFileSentencesNumber
            self.ui.label_repeatSentencesProcent.setText(str(percentValue)+' %')
        except:
            pass


    def UpdateMainFileText(self):
        self.ui.listWidget_MainFile.clear()
        try:
            for sentence in self.source.GetMainFileClearText():  # show MainFile text to left widget 
                self.ui.listWidget_MainFile.addItem(sentence) 
        except:
            self.ui.listWidget_errorList.addItem("Nie wybrano pliku głownego")
    def UpdateChoosenOutFileText(self):
        currentRow=self.ui.listWidget_OutFilesList.currentRow()
        self.ui.listWidget_ChoosenOutFile.clear()
        currentMethodRow=self.ui.comboBox_MethodList.currentIndex()
        try:
            for sentence in self.source.OutFiles[currentRow].clearText:
                self.ui.listWidget_ChoosenOutFile.addItem(sentence)
        except:
           print ""
    def ColorMainFile(self):    
        self.ClearColorOnMainFile()
        currentMethodRow=self.ui.comboBox_MethodList.currentIndex()
        ListOfSentencesToColor=self.source.ListOfMainFileSentenceToColor()
        colors=self.GetColors()
        colorIt=-1
        for outFile in ListOfSentencesToColor:
            outFileCurrentMethod=outFile[currentMethodRow]
            colorIt+=1
            color=colors[colorIt]
            for number in outFileCurrentMethod:
                item=self.ui.listWidget_MainFile.item(number)
                item.setBackgroundColor(color)
    
    def ClearColorOnMainFile(self):
        for number in range(self.source.HowManySentencesInMainFile()):
            item=self.ui.listWidget_MainFile.item(number)
            item.setBackgroundColor(QtGui.QColor(255,255,255))
    
    def ColorOutFilesList(self):    
        numberOfOutFiles=len(self.source.GetOutFiles())
        colors=self.GetColors()
        colorIt=-1
        for outFileNumber in range(numberOfOutFiles):
            colorIt+=1
            color=colors[colorIt]
            item=self.ui.listWidget_OutFilesList.item(outFileNumber)
            item.setBackgroundColor(color)
                       
    def GetColors(self):
        colors=[]
   #     colors.append(QtGui.QColor(176,23,31))
    #    colors.append(QtGui.QColor(65,105,225))
     #   colors.append(QtGui.QColor(93,71,139))
      #  colors.append(QtGui.QColor(238,162,173))
        colors.append(QtGui.QColor(39   , 64  ,  139))
        colors.append(QtGui.QColor(189    ,252   , 201))
        colors.append(QtGui.QColor(139   , 117  ,  0))
        colors.append(QtGui.QColor(61    ,145 ,   64    ))
        colors.append(QtGui.QColor(124  ,  252  ,  0))
        colors.append(QtGui.QColor(255  ,  246  ,  143))
        colors.append(QtGui.QColor(0   , 245 ,   255))
        colors.append(QtGui.QColor(222  ,  184 ,   135))
        colors.append(QtGui.QColor(238  ,  118  ,  0))
        colors.append(QtGui.QColor(238  ,  149  ,  114))
        colors.append(QtGui.QColor(205   , 201  ,  201))
        colors.append(QtGui.QColor(56  ,  142,    142    ))
        colors.append(QtGui.QColor(113  ,  198  ,  113))
        colors.append(QtGui.QColor(198  ,  113   , 113))
        return colors

    def LoadOutFilesListInRaport(self):
        self.ui.listWidget_OutFilesList.clear()
        for outFile in self.source.GetOutFiles():  # make list of outfiles in top widget
            outFileName=outFile.GetFileName()
            self.ui.listWidget_OutFilesList.addItem(outFileName)  
        self.ui.listWidget_OutFilesList.setCurrentRow(0)


    def listWidget_OutFilesListDClicked(self):
        self.UpdateChoosenOutFileText()
    
    
    def comboBox_MethodListClicked(self):
        self.ColorMainFile()
        currentMethodRow=self.ui.comboBox_MethodList.currentIndex()
        
        if(currentMethodRow == 0):
            self.ui.horizontalSlider_Threshold.setEnabled(False)
        else:
            self.ui.horizontalSlider_Threshold.setEnabled(True)
        
    
    def listWidget_MainFileDClicked(self):
        currentRow=self.ui.listWidget_MainFile.currentRow() # number of clicked Sentence
        

        if(len(self.source.raportStructure[currentRow].keys())>0):   # repeat exist
            fileNumber=self.source.raportStructure[currentRow].keys()[0]   # number of file when is repeat
            sentenceNumber=self.source.raportStructure[currentRow].values()[0]   # number of sentence in fileNumber where is repeat
        
            self.ui.listWidget_OutFilesList.setCurrentRow(fileNumber)  #change outFile text to show
            self.UpdateChoosenOutFileText() # update widget
            self.ui.listWidget_ChoosenOutFile.setCurrentRow(sentenceNumber) # make focus on sentence

                 
            
    
    def listWidget_ChoosenOutFileDClicked(self):
        currentMethodRow=self.ui.comboBox_MethodList.currentIndex()
        #self.Change_listWidget_ChoosenOutFileFoucs()
        clickedRow=self.ui.listWidget_ChoosenOutFile.currentRow() # number of clicked sentence
        #self.source.raportStructure=[{0:2}, {}, {}, {}, {}, {}, {}, {}]
        outFileNumber=self.ui.listWidget_OutFilesList.currentRow()  # in what file was that sentence
        #self.source.OutFiles[outFileNumber].repeats=[2,2,2,2,2,2,2]
        mainFileSentenceNumber=self.source.OutFiles[outFileNumber].repeats[currentMethodRow][clickedRow]  # search for repeat number
        self.ui.listWidget_MainFile.setCurrentRow(mainFileSentenceNumber) #change focus on left widget
        return True
Beispiel #54
0
class Pyssenlit(QObject):

    def __init__(self):
        QObject.__init__(self)

        self.m = Model('example.db')

        self.app = QtGui.QApplication(sys.argv)
        self.window = QtGui.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.window)

        self.ui.code.setLexer(QsciLexerPython())


        self.ui.packages.itemSelectionChanged.connect(self.UpdateClasses)
        self.ui.classes.itemClicked.connect(self.ShowImports)
        self.ui.classes.itemSelectionChanged.connect(self.UpdateMethods)
        self.ui.methods.itemSelectionChanged.connect(self.UpdateCode)
        savekey = QtGui.QShortcut(Qt.CTRL + Qt.Key_S, self.ui.code, self.save)
        self.ui.newpackage.clicked.connect(self.newPackage)
        self.ui.newclass.clicked.connect(self.newClass)
        self.ui.newmethod.clicked.connect(self.newMethod)

        #fill packages list
        self.UpdatePackage()

        self.window.show()

        self.app.exec_()


    def __del__(self):
        print 'application closing'
        QObject.__del__(self)
        del self.m

    def UpdatePackage(self):
        self.ui.packages.clear()
        self.ui.classes.clear()
        self.ui.methods.clear()
        self.ui.code.clear()
        res = self.m.getAllPackages()
        itemslist = []
        for row in res:
            item  = QtGui.QTreeWidgetItem()
            item.setText(0,row[2])
            item.setText(1,str(row[0]))
            itemslist.append(item)
            if row[1]==0:
                self.ui.packages.addTopLevelItem(item)
            else:
                itemslist[row[1]-1].addChild(item)
    
    def UpdateClasses(self):
        self.ui.classes.clear()
        self.ui.methods.clear()
        self.ui.code.clear()
        self.currentpackage = self.ui.packages.selectedItems()[0]
        res = self.m.getClassesFromPackage(self.currentpackage.text(0))
        for row in res:
            item = QtGui.QListWidgetItem()
            item.setText(row[2])
            self.ui.classes.addItem(item)

    def ShowImports(self,item):
        name, inherits,imports = self.m.getInfosFromClass(item.text())
        signature = 'class '+name
        if inherits!='':
            signature = signature+'('+inherits+')'
        self.ui.methods.clearSelection()
        self.ui.code.clear()
        self.ui.code.setText(signature)
        self.currentclass = item

    def UpdateMethods(self):
        self.ui.code.clear()
        self.ui.methods.clear()
        
        if len(self.ui.classes.selectedItems()) > 0:
            res = self.m.getMethodsFromClass(self.ui.classes.selectedItems()[0].text())
            for row in res:
                item = QtGui.QListWidgetItem()
                item.setText(row[1])
                self.ui.methods.addItem(item)

    def UpdateCode(self):
        self.ui.code.clear()
        if len(self.ui.methods.selectedItems()) > 0 :
            print self.ui.methods.selectedItems()[0].text()
            code=self.m.getCodeFromMethod(self.ui.methods.selectedItems()[0].text())
            name,args,comments = self.m.getInfosFromMethod(self.ui.methods.selectedItems()[0].text())

            method = ''
            for line in comments.split('\n'):
                method += '#'+line+'\n'
            method += "def "+name+'('
            arguments = args.split(',')
            if len(arguments) > 0:
                if len(arguments)==1:
                    method += arguments[0]
                else:
                    for arg in arguments[0:-1]:
                        method += arg+ ", "
                    method += arguments[-1]
            method += "):\n"

            for line in code.split('\n'):
                method += '\t' + code
            self.ui.code.setText(method)

    def save(self):
        self.m.setCodeOfMethod(self.ui.methods.selectedItems()[0].text(),
                               self.ui.code.text())

    def newPackage(self):
        dialog = QtGui.QDialog()
        packageDialog = Ui_NewPackage()
        packageDialog.setupUi(dialog)
        dialog.show()
        if dialog.exec_():
            self.m.newPackage(packageDialog.packagename.text())
            self.UpdatePackage()

    def newClass(self):
        dialog = QtGui.QDialog()
        classDialog = Ui_NewClass()
        classDialog.setupUi(dialog)
        dialog.show()
        if dialog.exec_():
            self.m.newClass(self.ui.packages.selectedItems()[0].text(0),
                            classDialog.classname.text(),
                            classDialog.classinherits.text(), '')
            self.UpdateClasses()

    def newMethod(self):
        dialog = QtGui.QDialog()
        methodDialog = Ui_NewMethod()
        methodDialog.setupUi(dialog)
        dialog.show()
        if dialog.exec_():
            self.m.newMethod(self.ui.classes.selectedItems()[0].text(),
                             methodDialog.methodname.text(),
                             methodDialog.methodcategory.text(),
                             methodDialog.methodarguments.text(),
                             methodDialog.methodcomments.document().toPlainText()
                             )
            self.UpdateMethods()
Beispiel #55
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Signals/Slots
        QtCore.QObject.connect(self.ui.pushButton_Add1, QtCore.SIGNAL("clicked()"), self.add_songs1)
        QtCore.QObject.connect(self.ui.pushButton_Shuffle1, QtCore.SIGNAL("clicked()"), self.shuffle1)
        QtCore.QObject.connect(self.ui.pushButton_Delete1, QtCore.SIGNAL("clicked()"), self.delete1)
        QtCore.QObject.connect(self.ui.pushButton_Add2, QtCore.SIGNAL("clicked()"), self.add_songs2)
        QtCore.QObject.connect(self.ui.pushButton_Shuffle2, QtCore.SIGNAL("clicked()"), self.shuffle2)
        QtCore.QObject.connect(self.ui.pushButton_Delete2, QtCore.SIGNAL("clicked()"), self.delete2)
        QtCore.QObject.connect(self.ui.pushButton_Save, QtCore.SIGNAL("clicked()"), self.save)
        QtCore.QObject.connect(self.ui.actionAbout, QtCore.SIGNAL("activated()"), self.show_about)
    

    def add_songs1(self):
        self._add_songs("My songs", self.ui.groupMySongs, self.ui.tableWidgetMySongs)

    def add_songs2(self):
        self._add_songs("His/Her songs", self.ui.groupHerSongs, self.ui.tableWidgetHerSongs)

    def _add_songs(self, groupTitle, groupBox, table):
        '''
        Add songs to the table
        '''

        files = QtGui.QFileDialog.getOpenFileNames(self, 'Add songs', 
                                                   os.path.expanduser("~"), 
                                                   "Audio Files (*.mp3)")
        total_size = 0.0
        for filename in files:
            tag = eyeD3.Tag()
            try:
                # Patch for TagException: Multiple UFID frames not allowed 
                # with the same owner ID
                tag.link(unicode(filename))
            except TagException:
                pass
            size = os.path.getsize(unicode(filename)) / (1024.0 * 1024.0)
            total_size += size 
            self._create_table_item({'title': tag.getTitle(),
                                     'artist': tag.getArtist(),
                                     'size': "%.2f MB" % size,
                                     'path': unicode(filename)}, table)
            
        self._update_groupBox_label(table, groupTitle, groupBox)


    def _create_table_item(self, data, table):
        '''
        Create a table item
        
        @param data: dict
        '''
        
        new_rc = table.rowCount()
        table.setRowCount(new_rc + 1)
        table.setItem(new_rc, 0, QTableWidgetItem(data['title']))
        table.setItem(new_rc, 1, QTableWidgetItem(data['artist']))
        table.setItem(new_rc, 2, QTableWidgetItem(data['size']))
        table.setItem(new_rc, 3, QTableWidgetItem(data['path']))


    def shuffle1(self):
        self._shuffle(self.ui.tableWidgetMySongs)
        
    def shuffle2(self):
        self._shuffle(self.ui.tableWidgetHerSongs)

    def _shuffle(self, table):
        '''
        Shuffle rows
        '''
        
        data = [(table.item(i, 0).text(),
                 table.item(i, 1).text(),
                 table.item(i, 2).text(),
                 table.item(i, 3).text()) 
                    for i in xrange(table.rowCount())]
        random.shuffle(data)
        table.setRowCount(0)
        table.setRowCount(len(data))
        for i, row in enumerate(data):
            table.setItem(i, 0, QTableWidgetItem(row[0]))
            table.setItem(i, 1, QTableWidgetItem(row[1]))
            table.setItem(i, 2, QTableWidgetItem(row[2]))
            table.setItem(i, 3, QTableWidgetItem(row[3]))
    
    def _update_groupBox_label(self, table, groupTitle, groupBox):
        '''
        Update the groupBox label to show name, number of items and size
        '''
    
        groupBox.setTitle("%s (%d items, %.2f MB)" % (groupTitle, table.rowCount(), 
                                                      self._count_songs_size(table)))
    
    
    def _count_songs_size(self, table):
        '''
        Counts the size of the songs of a table
        '''
        
        files_size = sum([os.path.getsize(unicode(table.item(i, 3).text())) 
                          for i in xrange(table.rowCount())])
        
        return files_size / (1024.0 * 1024.0)
    
    
    def delete1(self):
        self._delete(self.ui.tableWidgetMySongs, "My songs", self.ui.groupMySongs)
        
    def delete2(self):
        self._delete(self.ui.tableWidgetHerSongs, "His/Her songs", self.ui.groupHerSongs)
    
    def _delete(self, table, groupTitle, groupBox):
        '''
        Shuffle rows
        '''
        
        table.removeRow(table.currentRow())
        self._update_groupBox_label(table, groupTitle, groupBox)
    
    def _get_songs(self, table):
        '''
        Returns list of file paths
        '''
        
        return [table.item(i, 3).text() for i in xrange(table.rowCount())]
        
    
    def save(self):
        '''
        Merge lists and save to disk
        '''
        
        
        mysongs = self._get_songs(self.ui.tableWidgetMySongs)
        hersongs = self._get_songs(self.ui.tableWidgetHerSongs)
        
        if not (mysongs and hersongs):
            QMessageBox.information(self, "Merge lists", "You need to fill up both song lists")
            return None
        
        # First select where to dump the files
        folder = QtGui.QFileDialog.getExistingDirectory(self, 'Select folder to save the files')
        if folder:
            folder_path = os.path.abspath(unicode(folder))
            merged_songs = merge_lists(mysongs, hersongs)
            
            QMessageBox.information(self, "Merge lists", 
                                    "%d files are going to be copied to %s" % (len(merged_songs), 
                                                                               folder_path.encode('utf-8')))
            for i, song_path in enumerate(merged_songs):
                dest_name = (u'%.4d-%s' % (i, os.path.basename(unicode(song_path))))
                shutil.copy(unicode(song_path).encode('utf-8'), os.path.join(folder_path, dest_name).encode('utf-8'))
    
            QMessageBox.information(self, "Merge lists", "Files copied OK!")
            
        
    def show_about(self):
        '''
        Show about dialog
        '''
        
        QMessageBox.about(self, "Music Blender", 
                          "Author: Diego Navarro Mellén\nLicense: GPLv3".decode('utf-8'))
Beispiel #56
0
class Programa(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.modelo = self.generaModelo()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.tabla.setModel(self.modelo)
        self.reajusta()
        

        QtCore.QObject.connect(self.ui.action_Salir,QtCore.SIGNAL("activated()"),QtGui.qApp, QtCore.SLOT("quit()") )
        QtCore.QObject.connect(self.ui.refrescar,QtCore.SIGNAL("clicked()"),self.refrescar )
        QtCore.QObject.connect(self.ui.nuevaLinea,QtCore.SIGNAL("clicked()"),self.nuevaLinea )
        QtCore.QObject.connect(self.ui.eliminarLinea,QtCore.SIGNAL("clicked()"),self.eliminarLinea )


    def generaModelo(self):
        self.conectaDB()
        modelo = QtSql.QSqlTableModel(None, self.db)
        modelo.setTable("inventario")
        modelo.setSort(self.recordPrototipo.indexOf("ean13"),QtCore.Qt.AscendingOrder)
        modelo.select()
        return modelo

    def conectaDB(self):
        self.db = QtSql.QSqlDatabase.addDatabase("QPSQL")
        self.db.setHostName("rufus")
        self.db.setDatabaseName("inventario")
        self.db.setUserName("josemaria")
        self.db.setPassword("")
        name = self.db.open()

        query = QtSql.QSqlQuery("select * from inventario",self.db)
        self.recordPrototipo = query.record()


    def reajusta(self):
        self.ui.tabla.resizeColumnsToContents()


    def nuevaLinea(self):
        fila = self.modelo.rowCount()
        self.modelo.insertRow(fila)
        self.reajusta()

        
    def eliminarLinea(self):
        index = self.ui.tabla.currentIndex()
        fila = index.row()
        ean13 = self.modelo.data(self.modelo.index(fila, self.recordPrototipo.indexOf("ean13"))).toString()
        nombre = self.modelo.data(self.modelo.index(fila, self.recordPrototipo.indexOf("nombre"))).toString()

        if QtGui.QMessageBox.question(self, "Borrar linea",
                                      QtCore.QString("¿Desea borrar el producto #%1, «%2»?").arg(ean13).arg(nombre),
                                      QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
            self.modelo.removeRow(fila)
            self.reajusta()
        
     
        
        
    def refrescar(self):
        self.modelo.select()
Beispiel #57
0
            fileNumber=self.source.raportStructure[currentRow].keys()[0]   # number of file when is repeat
            sentenceNumber=self.source.raportStructure[currentRow].values()[0]   # number of sentence in fileNumber where is repeat
        
            self.ui.listWidget_OutFilesList.setCurrentRow(fileNumber)  #change outFile text to show
            self.UpdateChoosenOutFileText() # update widget
            self.ui.listWidget_ChoosenOutFile.setCurrentRow(sentenceNumber) # make focus on sentence

                 
            
    
    def listWidget_ChoosenOutFileDClicked(self):
        currentMethodRow=self.ui.comboBox_MethodList.currentIndex()
        #self.Change_listWidget_ChoosenOutFileFoucs()
        clickedRow=self.ui.listWidget_ChoosenOutFile.currentRow() # number of clicked sentence
        #self.source.raportStructure=[{0:2}, {}, {}, {}, {}, {}, {}, {}]
        outFileNumber=self.ui.listWidget_OutFilesList.currentRow()  # in what file was that sentence
        #self.source.OutFiles[outFileNumber].repeats=[2,2,2,2,2,2,2]
        mainFileSentenceNumber=self.source.OutFiles[outFileNumber].repeats[currentMethodRow][clickedRow]  # search for repeat number
        self.ui.listWidget_MainFile.setCurrentRow(mainFileSentenceNumber) #change focus on left widget
        return True
        
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    app_holder=app.setActiveWindow(MainWindow)
    ui = Ui_MainWindow()
    ui_holder=ui.setupUi(MainWindow)
    myapp = StartQT4()
    myapp_holder=myapp.show()
    sys_holder=sys.exit(app.exec_())
    myapp_runprogram_hollder=myapp.RunProgram()
Beispiel #58
0
    trezor_warn_and_start("CONFIRM RESTORE ON TREZOR!", client.load_device_by_mnemonic, mnemonic=mnemonic_string, pin="",
                          passphrase_protection=False, label=label, language='en')

#
# UI Execution
#

app = QtGui.QApplication(sys.argv)

class MyWindow(QtGui.QMainWindow):
    pass


main_window = MyWindow()
ui = Ui_MainWindow()
ui.setupUi(main_window)
main_window.show()

general_alert = GeneralAlert()


def setup():
    # update label
    ui.label_tid.setText(client.features.device_id)
    ui.button_t_set_label.clicked.connect(click_set_label)
    update_label()

    # wipe
    ui.button_wipe.clicked.connect(wipe_device)

    # reload from mnemonic or xprv
Beispiel #59
0
class principal(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        
        self.ventana = Ui_MainWindow()
        self.ventana.setupUi(self)
        self.center()
        
        self.connect(self.ventana.btnAcerca, QtCore.SIGNAL('clicked()'), self.acerca)
        self.connect(self.ventana.btnRaices, QtCore.SIGNAL('clicked()'), self.roots)
        self.connect(self.ventana.btnMatriz, QtCore.SIGNAL('clicked()'), self.matrix)
        self.connect(self.ventana.btnIntegral, QtCore.SIGNAL('clicked()'), self.integral)
        self.connect(self.ventana.btnEcuaciones, QtCore.SIGNAL('clicked()'), self.ecuations)
        
        self.connect(self.ventana.metodosRaices, QtCore.SIGNAL('currentIndexChanged(int)'), self.checkRoots)
    
    def center(self):
        screen = QtGui.QDesktopWidget().screenGeometry()
        mysize = self.geometry()
        hpos = ( screen.width() - mysize.width() ) / 2
        vpos = ( screen.height() - mysize.height() ) / 2
        self.move(hpos,vpos)

    def checkRoots(self):

        combo = self.ventana.metodosRaices
                
        if combo.currentIndex() > 1:
            self.ventana.raicesA.setEnabled(False)
            self.ventana.raicesB.setEnabled(False)
            self.ventana.raicesX.setEnabled(True)
        else:
            self.ventana.raicesA.setEnabled(True)
            self.ventana.raicesB.setEnabled(True)
            self.ventana.raicesX.setEnabled(False)
            
    def roots(self):
        ventana = self.ventana
        
        if ventana.metodosRaices.currentIndex() == 0:
            ecuacion = str(ventana.editRaices.text())
            valorA = float(ventana.raicesA.text())
            valorB = float(ventana.raicesB.text())
            iteraciones = ventana.raicesItera.value()
            tolerancia = float(ventana.raicesTolera.currentText())
            
            cadena = Biseccion(ecuacion, valorA, valorB, tolerancia, iteraciones)
            
            if cadena == '0':
                QtGui.QMessageBox.warning(self, u"Método de Bisección", 
                                          u"Al evaluar la función con los valores especificados en los extremos\nA y B no se consiguen valores con signo diferente. Por favor cambia\nel valor de por lo menos un extremo.",
                                          QtGui.QMessageBox.Ok)
            else:
                QtGui.QMessageBox.about(self, u"Método de Bisección",
                                        unicode(cadena))
        elif ventana.metodosRaices.currentIndex() == 1:
            ecuacion = str(ventana.editRaices.text())
            valorA = float(ventana.raicesA.text())
            valorB = float(ventana.raicesB.text())
            iteraciones = ventana.raicesItera.value()
            tolerancia = float(ventana.raicesTolera.currentText())
            
            cadena = ReglaFalsa(ecuacion, valorA, valorB, tolerancia, iteraciones)
            
            if cadena == '0':
                QtGui.QMessageBox.warning(self, u"Método de la Regla Falsa", 
                                          u"Al evaluar la función con los valores especificados en los extremos\nA y B no se consiguen valores con signo diferente. Por favor cambia\nel valor de por lo menos un extremo.",
                                          QtGui.QMessageBox.Ok)
            else:
                QtGui.QMessageBox.about(self, u"Método de la Regla Falsa",
                                        cadena)
        elif ventana.metodosRaices.currentIndex() == 2:
            ecuacion = str(ventana.editRaices.text())
            valorX = float(ventana.raicesX.text())
            iteraciones = ventana.raicesItera.value()
            tolerancia = float(ventana.raicesTolera.currentText())
            
            cadena = NewtonRaphson(ecuacion, valorX, tolerancia, iteraciones)
            
            if cadena == '0':
                QtGui.QMessageBox.warning(self, u"Método de Newton-Raphson", 
                                          u"El valor otorgado a X₀ es uno de los puntos críticos, cambielo por favor.",
                                          QtGui.QMessageBox.Ok)
            else:
                QtGui.QMessageBox.about(self, u"Método de Newton-Raphson",
                                        cadena)
        
    def matrix(self):
        ventana = self.ventana
        
        matriz = [[float(ventana.A11.text()),float(ventana.A12.text()),float(ventana.A13.text()),float(ventana.B1.text())],
                   [float(ventana.A21.text()),float(ventana.A22.text()),float(ventana.A23.text()),float(ventana.B2.text())],
                    [float(ventana.A31.text()),float(ventana.A32.text()),float(ventana.A33.text()),float(ventana.B3.text())]]
                    
        diagonal = diagonalFuerte(matriz)
        if diagonal == '0':
            if ventana.metodosMatriz.currentIndex() == 0:
                iteraciones = ventana.matrizItera.value()
                cadena = Jacobi(matriz, iteraciones)
                QtGui.QMessageBox.about(self, u"Método de Jacobi", unicode(cadena))
            elif ventana.metodosMatriz.currentIndex() == 1:
                iteraciones = ventana.matrizItera.value()
                cadena = GaussSeidel(matriz, iteraciones)
                QtGui.QMessageBox.about(self, u"Método de Gauss-Seidel", unicode(cadena))
        else:
            QtGui.QMessageBox.warning(self, u"Diagonal Fuerte",
                                      u"El sistema de ecuaciones no se encuentra en diagonal fuerte, por favor corrigelo",
                                      QtGui.QMessageBox.Ok)

    def integral(self):
        ventana = self.ventana
        funcion = str(ventana.fxIntegral.text())
        a = float(ventana.aIntegral.text())
        b = float(ventana.bIntegral.text())
        n = ventana.integralItera.value()
        
        if ventana.metodosIntegral.currentIndex() == 0:
            area = Riemann(a,b,n,funcion)
            QtGui.QMessageBox.about(self, u"Sumas de Riemman", unicode(area))
        elif ventana.metodosIntegral.currentIndex() == 1:
            area = Trapecios(a,b,n,funcion)
            QtGui.QMessageBox.about(self, u"Método de Trapecios", unicode(area))
        elif ventana.metodosIntegral.currentIndex() == 2:
            area = Simpson(a,b,n,funcion)
            QtGui.QMessageBox.about(self, u"Simpson ⅓", unicode(area))
            
    def ecuations(self):
        ventana = self.ventana
        eq = str(ventana.yPrima.text())
        x0 = float(ventana.ecuacionesX0.text())
        xn = float(ventana.ecuacionesXn.text())
        y0 = float(ventana.ecuacionesY0.text())
        n = ventana.ecuacionesItera.value()
        
        if ventana.metodosEcuaciones.currentIndex() == 0:
            cadena = Euler(x0,xn,y0,n,eq)
            QtGui.QMessageBox.about(self, u"Método de Euler", unicode(cadena))
        elif ventana.metodosEcuaciones.currentIndex() == 1:
            cadena = RK4(x0,xn,y0,n,eq)
            QtGui.QMessageBox.about(self, u"Método RK-4", unicode(cadena))
        
    def acerca(self):
        self.aboutV = aboutWin()
        self.aboutV.show()
Beispiel #60
0
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.popup = SubForm()
        self._files = None

        #buttons
        self.ui.browsebutton.clicked.connect(self.set_directory)
        self.ui.clearbutton.clicked.connect(self.clear_directory)
        self.ui.define_inout.clicked.connect(self.get_inout)
        self.ui.scriptlist.itemClicked.connect(self.doFile)
        self.ui.exportbutton.clicked.connect(self.writetoFile)

    def writetoFile(self):
        path = QFileDialog.getSaveFileName()
        f = open(path, 'w')
        f.write(str(self))
        f.close()


    def reset(self, listoftuples):
        if (self._files != None):
            self._files.createAlltests(listoftuples)
            self._files.runTests()

    def doFile(self):
        index = self.ui.scriptlist.currentRow()
        b = self._files._files[index]
        self.ui.StatusBox.setText(str(b))
        count = check_comments(b._filename)
        self.ui.linenumbers.setText(str(count._linecount))
        self.ui.commentnumbers.setText(str(count._commentcount))
        self.ui.functionnumbers.setText(str(count._functioncount))
        t = tabulate(b.getResults(), linecount=count._linecount, commentcount=count._commentcount, functioncount=count._functioncount, correctweight= int(self.ui.correctweight.text()), wrongweight = int(self.ui.incorrectweight.text()), errorweight = int(self.ui.errorweight.text()), commentfreq= int(self.ui.comment_freq.text()), functionfreq= int(self.ui.avg_func_len.text()), includeComments= self.ui.commentcheck.checkState(), includeFunctions= self.ui.functioncheck.checkState())
        self.ui.Total_score.setText(str(t.getScore()))
        self.ui.IO_score.setText(str(t.getIOScore()))
        self.ui.correctnum.setText(str(t._correctraw))
        self.ui.errornum.setText(str(t._errorraw))
        self.ui.incorrectnum.setText(str(t._incorrectraw))
        if (self.ui.commentcheck.checkState()):
            self.ui.comment_score.setText(str(t.getCommentScore()))
        else:
            self.ui.comment_score.setText("N/A")
        if (self.ui.functioncheck.checkState()):
            self.ui.Function_score.setText(str(t.getFunctionScore()))
        else:
            self.ui.Function_score.setText("N/A")


    def set_directory(self):
        self.ui.directorybox.clear()
        self.ui.directorybox.setText(QFileDialog.getExistingDirectory())
        path = self.ui.directorybox.text()
        self._files = allFiles(path,timeout = int(self.ui.timeout_box.text()), testcases= self.popup.pairlist)
        self._files.runTests()
        self.display_scripts()
	
    def clear_directory(self):
        self.ui.scriptlist.clear()
        self.ui.directorybox.clear()
        
    def display_scripts(self):
        self.ui.scriptlist.clear()
        path = self.ui.directorybox.text()
        os.chdir(path)
        filelist = os.listdir(path)
        
        for i in self._files._files:
            # if(i.endswith('.py')):
            self.ui.scriptlist.addItem(i._filename)
                

        if self.ui.scriptlist.size() != 0:
            self.startsession(path)
            
    def startsession(self, path):
        timelimit = self.ui.timeout_box.text()

        # print('file path: ' + path)
        # print('timeout: ' + timelimit)
        
    def get_inout(self):
        self.popup.show()

    def __str__(self):
        outs = str()
        for b in self._files._files:
            outs += str(b)
            count = check_comments(b._filename)
            outs +="\n\n    Lines: "+str(count._linecount)
            outs +="\n    Comments: "+str(count._commentcount)
            outs +="\n    Functions: "+str(count._functioncount)
            t = tabulate(b.getResults(), linecount=count._linecount, commentcount=count._commentcount, functioncount=count._functioncount, correctweight= int(self.ui.correctweight.text()), wrongweight = int(self.ui.incorrectweight.text()), errorweight = int(self.ui.errorweight.text()), commentfreq= int(self.ui.comment_freq.text()), functionfreq= int(self.ui.avg_func_len.text()), includeComments= self.ui.commentcheck.checkState(), includeFunctions= self.ui.functioncheck.checkState())
            outs+= "\n    Correct: "+str(t._correctraw)
            outs+= "\n    Errors: "+str(t._errorraw)
            outs+= "\n    Incorrect: "+str(t._incorrectraw)

            outs+= "\n    Total Score: "+str(t.getScore())
            outs +="\n    IO Score: " +str(t.getIOScore())
            outs += "\n    Comment Score: "
            if (self.ui.commentcheck.checkState()):
                outs+= str(t.getCommentScore())
            else:
              outs+= "N/A"
            outs+= "\n    Function Score: "
            if (self.ui.functioncheck.checkState()):
                outs+= str(t.getFunctionScore())
            else:
                outs+= "N/A"
            outs+= "\n\n"
        return outs