Esempio n. 1
0
class MainWindow(QtWidgets.QMainWindow):
	def __init__(self):
		super().__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.connectSignals()
		self.dock_widget = None


	def connectSignals(self):
		self.ui.botao.clicked.connect(lambda: self.add_widget("cadastro"))


	def add_widget(self, text):
		if not self.dock_widget:
			self.dock_widget = QtWidgets.QDockWidget(self)
			self.dock_widget.setMinimumWidth(400)
			self.dock_widget.setFeatures(QtWidgets.QDockWidget.DockWidgetClosable)
			self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock_widget)
			self.dock_widget.show()
		else:
			self.dock_widget.show()

		if text == "cadastro":
			self.widget = tela_form1.form1(self.dock_widget.widget())
		self.dock_widget.setWidget(self.widget)
Esempio n. 2
0
class MyMainwindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.scan.clicked.connect(self.start)

        # Gui objects
        self.scene = []
        for i in range(0, 3):
            print i
            self.scene.append(QtGui.QGraphicsScene())
        self.view = []
        self.view.append(self.ui.hegraph)
        self.view.append(self.ui.phapgraph)
        self.view.append(self.ui.dpgraph)
        self.box = self.ui.log_text
        self.cursor = self.ui.log_text.textCursor()

    def start(self):
        # clear text box
        self.box.clear()
        # creates and starts threads to run scan
        self.mpthread = Thread("mp")
        self.connect(self.mpthread, QtCore.SIGNAL("mp"), self.append)
        self.mpthread.start()
        self.chthread = Thread("ch")
        self.connect(self.chthread, QtCore.SIGNAL("ch"), self.append)
        self.chthread.start()

        scan.plot(scan.get_data('data.csv', 12), "DP")
        scan.plot(scan.get_data('data.csv', 7), "PHAP")
        scan.plot_he(scan.get_data('data.csv', 2),
                     scan.get_data('data.csv', 3))
        self.display_image('images/he.png', 0)
        self.display_image('images/DP.png', 2)
        self.display_image('images/PHAP.png', 1)

    # append data on the text box
    def append(self, text):
        self.cursor.movePosition(self.cursor.End)
        self.cursor.insertText(text)
        self.box.ensureCursorVisible()

    def display_image(self, img, item):
        self.scene[item].clear()
        #w, h = img.size
        self.imgQ = ImageQt.ImageQt(
            img)  # we need to hold reference to imgQ, or it will crash
        pixMap = QtGui.QPixmap.fromImage(self.imgQ)
        myScaledPixmap = pixMap.scaled(
            self.view[item].size(),
            QtCore.Qt.KeepAspectRatio)  #, KeepAspectRatio)
        self.scene[item].addPixmap(myScaledPixmap)
        self.scene[item].update()
        self.view[item].setScene(self.scene[item])
Esempio n. 3
0
class StartQT4(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.ui_main_window = Ui_MainWindow()
        self.ui_main_window.setupUi(self)

        self.connect_slots()

        self.ui_main_window.cancel_button.setEnabled(False)
        self.ui_main_window.start_button.setEnabled(False)

    def connect_slots(self):
        # Signals and Slots
        self.ui_main_window.actionOpenFile.triggered.connect(self.file_dialog)
        self.ui_main_window.actionAbout_AnaText.triggered.connect(
            self.about_dialog)
        self.ui_main_window.AddSettings.triggered.connect(
            self.tools_dialog)

    def file_dialog(self):
        # fd = QtGui.QFileDialog(self)
        # self.files = fd.getOpenFileNames(
        #     self, 'Open file', '', "Excel Files (*.xls *.xlsx)")
        # print self.files
        files = []
        for path in QtGui.QFileDialog.getOpenFileNames(self, 'Open Files', '', "Excel Files (*.xls *.xlsx)"):
            print path
            if path not in files:
                files.append(path)
        print files

    def about_dialog(self):
        about_box = StartAbout(self)
        about_box.show()

    def tools_dialog(self):
        tools_box = StartTools(self)
        tools_box.show()

    def enable_button(self, ui, button):
        self.ui.button.setEnabled(True)

    # Asks if user really wants to exit.
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
                                           "Are you sure to quit?", QtGui.QMessageBox.Yes |
                                           QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
Esempio n. 4
0
class MyMainwindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.scan.clicked.connect(self.start)
        
        # Gui objects
        self.scene = []
        for i in range(0,3):
            print i
            self.scene.append(QtGui.QGraphicsScene())
        self.view = []
        self.view.append(self.ui.hegraph)
        self.view.append(self.ui.phapgraph)
        self.view.append(self.ui.dpgraph)
        self.box =self.ui.log_text
        self.cursor = self.ui.log_text.textCursor()
        
    def start(self):
        # clear text box
        self.box.clear()
        # creates and starts threads to run scan
        self.mpthread = Thread("mp")
        self.connect(self.mpthread, QtCore.SIGNAL("mp"), self.append)
        self.mpthread.start()
        self.chthread = Thread("ch")
        self.connect(self.chthread, QtCore.SIGNAL("ch"), self.append)
        self.chthread.start()
        
        scan.plot(scan.get_data('data.csv', 12), "DP")
        scan.plot(scan.get_data('data.csv', 7), "PHAP")
        scan.plot_he(scan.get_data('data.csv', 2),scan.get_data('data.csv', 3))
        self.display_image('images/he.png',0)
        self.display_image('images/DP.png',2)
        self.display_image('images/PHAP.png',1)
        
    # append data on the text box        
    def append(self, text):
        self.cursor.movePosition(self.cursor.End)
        self.cursor.insertText(text)
        self.box.ensureCursorVisible()
        
    def display_image(self, img, item):
        self.scene[item].clear()
        #w, h = img.size
        self.imgQ = ImageQt.ImageQt(img)  # we need to hold reference to imgQ, or it will crash
        pixMap = QtGui.QPixmap.fromImage(self.imgQ)
        myScaledPixmap = pixMap.scaled(self.view[item].size(), QtCore.Qt.KeepAspectRatio)#, KeepAspectRatio)
        self.scene[item].addPixmap(myScaledPixmap)
        self.scene[item].update()
        self.view[item].setScene(self.scene[item])
Esempio n. 5
0
File: my.py Progetto: perldev/ErlIde
class MyForm(QtGui.QMainWindow):
    def showOpenFileDialog(self):
        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
        open_tab(self.ui.tabWidget, str(fname))

    def fill_events(self):
        self.ui.actionOpen.triggered.connect(self.showOpenFileDialog)

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        # This is always the same
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.fill_events()
Esempio n. 6
0
class MzAlarmy(QtWidgets.QMainWindow):
    """Main application class"""

    def __init__(self):
        """Initializing main class"""
        super(MzAlarmy, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Removing any numbers from lcd's for enhanced user experience at starting of application
        self.ui.hrsLabel.display('')
        self.ui.minsLabel.display('')
        self.ui.secsLabel.display('')

        self.clock = Clock(self.ui.hrsLabel, self.ui.minsLabel, self.ui.secsLabel)
        self.clock.start()
        self.background_changer = BackgroundChanger(self, 'offline', 'backgrounds/*.jpg')
        self.background_changer.sleep(5) # Making sleep to fix bugs during assigning background
        self.background_changer.start()

        # Setting events
        self.set_events()

        self.alarm_manager = AlarmManager('alarms.txt')
        self.alarm_manager.load_alarms()

        # Setting alarms
        #self.initialize_alarms()

        # Setting alarm mp3
        #self.p = vlc.MediaPlayer("ring.mp3")



    def set_events(self):
        # Menu events
        self.ui.actionSet_Alarms.triggered.connect(self.open_set_alarms)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Space:
            self.alarm_manager.stop_alarm()

    def open_set_alarms(self):
        from set_alarms import SetAlarms

        dialog = SetAlarms()
        self.alarm_manager.load_alarms()
class main_menu(QtGui.QMainWindow):

    def __init__(self):
        super(main_menu, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()         
        
    def keyPressEvent(self, event1):
      verbose = {"FB":"", "LR":""}
      if event1.key() == QtCore.Qt.Key_W: 
        #print "Up pressed"
        verbose["FB"] = "F"
      if event1.key() == QtCore.Qt.Key_S:
        #print "D pressed"
        verbose["FB"] = "B"
      
      if event1.key() == QtCore.Qt.Key_A:
        #print "L pressed"
        verbose["LR"] = "L"
      if event1.key() == QtCore.Qt.Key_D:
        #print "R pressed"
        verbose["LR"] = "R"
        
      print verbose
      json_data=json.dumps(verbose)
      s.sendto((json_data), (IP, PORT))
      
    def keyReleaseEvent(self, event):
      verbose = {"FB":"", "LR":""}
      if event.key() == QtCore.Qt.Key_W: 
        #print "Up rel"
        verbose["FB"] = "S"
      if event.key() == QtCore.Qt.Key_S: 
        #print "D rel"
        verbose["FB"] = "S"
      
      if event.key() == QtCore.Qt.Key_A:
        #print "L pressed"
        verbose["LR"] = "S"
      if event.key() == QtCore.Qt.Key_D: 
        #print "R pressed"
        verbose["LR"] = "S"
        
      print verbose
      json_data=json.dumps(verbose)
      s.sendto((json_data), (IP, PORT))      
Esempio n. 8
0
class App(QtGui.QDialog):
      def __init__(self, parent=None):
          self.__mainWindow = QtGui.QMainWindow()
          self.__mainWindowDesignContext = Ui_MainWindow()
          self.__mainWindowDesignContext.setupUi(self.__mainWindow, self)
          self.__mainWindow.show()
      def menuActionProcess(self):
          self.processThread = BatchProcesser()
          self.progressBar = QtGui.QProgressBar()
          statusBar.addWidget(self.progressBar)
          self.progressBar.show()
          self.progressBar.setMinimum(0)
          self.progressBar.setMaximum(100)
          QtCore.QObject.connect(self.processThread, QtCore.SIGNAL("progress(int)"),self.progressBar, QtCore.SLOT("setValue(int)"), QtCore.Qt.QueuedConnection)
          if not self.processThread.isRunning():
              self.processThread.exiting = False
              self.processThread.start()
Esempio n. 9
0
class main_menu(QtGui.QMainWindow):
    def __init__(self):
        super(main_menu, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()

    def keyPressEvent(self, event1):
        verbose = {"FB": "", "LR": ""}
        if event1.key() == QtCore.Qt.Key_W:
            #print "Up pressed"
            verbose["FB"] = "F"
        if event1.key() == QtCore.Qt.Key_S:
            #print "D pressed"
            verbose["FB"] = "B"

        if event1.key() == QtCore.Qt.Key_A:
            #print "L pressed"
            verbose["LR"] = "L"
        if event1.key() == QtCore.Qt.Key_D:
            #print "R pressed"
            verbose["LR"] = "R"

        print verbose
        json_data = json.dumps(verbose)
        s.sendto((json_data), (IP, PORT))

    def keyReleaseEvent(self, event):
        verbose = {"FB": "", "LR": ""}
        if event.key() == QtCore.Qt.Key_W:
            #print "Up rel"
            verbose["FB"] = "S"
        if event.key() == QtCore.Qt.Key_S:
            #print "D rel"
            verbose["FB"] = "S"

        if event.key() == QtCore.Qt.Key_A:
            #print "L pressed"
            verbose["LR"] = "S"
        if event.key() == QtCore.Qt.Key_D:
            #print "R pressed"
            verbose["LR"] = "S"

        print verbose
        json_data = json.dumps(verbose)
        s.sendto((json_data), (IP, PORT))
Esempio n. 10
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.create_convert_options()
        self.ui.pushButton.clicked.connect(self.file_dialog)
        self.ui.pushButton_2.clicked.connect(self.convert)

    def create_convert_options(self):
        self.ui.comboBox.insertItem(0, 'Select')
        self.ui.comboBox_2.insertItem(0, 'Select')
        for e in enumerate(sorted(encodings.aliases.aliases)):
            index = e[0]
            s = e[1]
            self.ui.comboBox.insertItem(index+1, s)
            self.ui.comboBox_2.insertItem(index+1, s)

    def file_dialog(self):
        d = QFileDialog(self)
        d.setFileMode(QFileDialog.ExistingFiles)
        if d.exec():
            s = d.selectedFiles()
            for ss in s:
                self.ui.lineEdit.setText(self.ui.lineEdit.text()+ss+',')

    def convert(self):
        e_from = self.ui.comboBox.currentText()
        e_to = self.ui.comboBox_2.currentText()
        if e_from != e_to:
            for path in self.ui.lineEdit.text().split(','):
                if path != '':
                    f_path, f_name = os.path.split(path)
                    new_f_name = 'redecoded'+f_name
                    new_f_path = os.path.join(f_path, new_f_name)
                    open(new_f_path, 'wb').write(open(path, 'rb').read().decode(e_from).encode(e_to))
        else:
            print('No jednak sobie rowne')
            c_icon = QMessageBox.Icon(QMessageBox.Critical)
            ok_button = QMessageBox.StandardButton(QMessageBox.Ok)
            m = QMessageBox(self)
            m.addButton(ok_button)
            m.setIcon(c_icon)
            m.setText("'From' and 'to' are equal!")
            m.show()
Esempio n. 11
0
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.event_widgets = []
        
        for i in range(0,5):
            self.ui.eventGrid.setRowMinimumHeight(i,30)
            self.ui.eventGrid.setColumnMinimumWidth(i,30)
            
        for i in range(0,5):
            for j in range(0,5):
                tmp_btn = QtGui.QPushButton(self.ui.centralwidget)
                tmp_btn.setObjectName("eventWidget"+str(len(self.event_widgets)))
                QtCore.QObject.connect(tmp_btn, QtCore.SIGNAL("clicked()"), tmp_btn.hide)
                self.ui.eventGrid.addWidget(tmp_btn, i,j)
                self.event_widgets.append(tmp_btn)
Esempio n. 12
0
class MyForm(QtGui.QMainWindow):
     def showOpenFileDialog(self):
        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file','/home')
        open_tab(self.ui.tabWidget, str(fname))
            
       
      
     def fill_events(self):
            self.ui.actionOpen.triggered.connect(self.showOpenFileDialog)
            

  
     def __init__(self):
         QtGui.QMainWindow.__init__(self)
          # This is always the same
         self.ui=Ui_MainWindow()
         self.ui.setupUi(self)
         self.fill_events()
Esempio n. 13
0
class Main(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        QObject.connect(self.ui.pushButton,SIGNAL('clicked()'),self.setB)
        QObject.connect(self.ui.pushButton_2,SIGNAL('clicked()'),self.search)
        QObject.connect(self.ui.pushButton_3,SIGNAL('clicked()'),self.visualisation)
        self.buts = []
    def testCells(self):
        self.ui.tableWidget.setRowCount(self.ui.tableWidget.rowCount()+1)
        self.ui.tableWidget.setCellWidget(0,1,QPushButton("OPEN"))
    def visualisation(self):
        
        w = Graph(self.ui.lineEdit.text())
        w.show()
    def setB(self):
        self.ui.lineEdit.setText(QFileDialog.getExistingDirectory())
    def search(self):
        Func.compileRegex(self.ui.lineEdit_2.text())
        for root,dirs,files in os.walk(self.ui.lineEdit.text()):
            for file in files:
                if Func.reg.match(file):
                    counter = self.ui.tableWidget.rowCount()-1
                    text = os.path.splitext(root+'/'+file)
                    name = text[0].split('/')
                    name = name[len(name)-1]
                    ext = text[1]
                    print(text)
                    self.ui.tableWidget.setRowCount(self.ui.tableWidget.rowCount()+1)
                    self.ui.tableWidget.setItem(counter,0,QTableWidgetItem(ext))
                    self.ui.tableWidget.setItem(counter,1,QTableWidgetItem(name))
                    baton = MyButton("Open",text[0]+text[1])
                    self.buts.append(baton)
                    which = len(self.buts)-1
                    QObject.connect(self.buts[which],SIGNAL('clicked()'),self.buts[which].openMe)
                    
                    self.ui.tableWidget.setCellWidget(counter,2,self.buts[which])
Esempio n. 14
0
File: run.py Progetto: side2/deter
class Main(QtGui.QMainWindow):
    
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)        
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.actionExit.triggered.connect(QtGui.qApp.quit) 
        self.ui.pushButton_2.clicked.connect(QtGui.qApp.quit) 
        self.ui.pushButton.clicked.connect(self.actionsh)
        self.ui.actionOpen_2.triggered.connect(self.actionsh)        
        self.ui.actionHelp.triggered.connect(self.actionh)
        self.ui.actionDPD.triggered.connect(self.actiond)       
        self.ui.actionIntrodu_in_DB.triggered.connect(self.actioni)           
        self.ui.action_sterge_din_DB.triggered.connect(self.actions)
       
    def txt(self,v):
        self.ui.lineEdit.setText(v)  
    def actiond(self):
           self.window2=Det()
    def actionh(self):       
           self.window2=Helpos()           
    def actionsh(self):
        
        self.ui.lineEdit.setText("")
        if self.ui.lineEdit.text()!="": 
           self.deter()
        else:
             self.w=Sha()
             self.w.h.connect(self.deter)
            

    def deter(self,v):
           f1 = str(v)
           f=f1.split('\n',1)           
           self.ui.lineEdit.setText(f1.replace('\n'+f[-1],' '))            
           con = mdb.connect( path+'/plant.db')
           fileName=f[-1]
           if fileName!='':
              		image = QtGui.QImage(fileName)                      
              		if image.isNull() :                 
	         		QtGui.QMessageBox.information(self, "Error", "Cannot load %s." % fileName) # error message
	     		else:
                 		
                 		
                 		rez=get_resolution(fileName)               		
                 		contours, hierarchy = cv2.findContours(segmentLeaf(cv2.imread(str(fileName))),1, 2)
                   		M = cv2.moments(contours[0])
                 		area = cv2.contourArea(contours[0])
                 		x,y,w,h = cv2.boundingRect(contours[0])
                 		cv2.rectangle(np.zeros((900,900,3), np.uint8),(x,y),(x+w,y+h),(0,255,0),2)
                 		aspect_ratio = float(h)/w
                 		perimeter = cv2.arcLength(contours[0],True)						
                 		rect_area = w*h
                 		param=[float('{0:.4f}'.format(perimeter/rez)),float('{0:.4f}'.format(area/rez**2)),float('{0:.4f}'.format(h/rez)),float('{0:.4f}'.format(float(h)/w)),float('{0:.4f}'.format(rect_area/rez**2)),float('{0:.4f}'.format(float(rect_area)/area)),str(self.ui.lineEdit.text())]
                 		with con: 
							
							self.ui.textEdit.setText('')
							cur = con.cursor()
							cur.execute(" SELECT * FROM botanic2 ")
							
							for  i in range( cur.rowcount):						
								row = cur.fetchone()
								li=[x for x in range(2,len(row))]
								li=li[::2]	
								j=0
								for col in range(len(param-1)):									
									if  row[li[col]]<=(param[col]*10000)<=row[li[col]+1] :
										j+=1
								if param[-1]  in str(row[-1]):
									j+=1
								procent=(j*100)/8
								if procent>10:
									self.ui.textEdit.append(" Probabilitatea de a fi specia "+str(row[0])+" este de: "+str((j*100)/8)+"%"+'\n')
							else:
								self.ui.textEdit.append(" Planta nu poate fi deterninata! ")
                 		
                 		
                 		
                 		
                
    def actioni(self):       
           self.window2=ins()        
    def actions(self):       
           self.window2=Del()
Esempio n. 15
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.textEdit.setText("hola!!!")
Esempio n. 16
0
class main_menu(QtGui.QMainWindow):

    def __init__(self):
        super(main_menu, self).__init__()
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        
        self.ui.location1.clicked.connect(self.send_location1)
        self.ui.location2.clicked.connect(self.send_location2)
        
        self.ui.location3.clicked.connect(self.send_location3)

        self.ui.Start.clicked.connect(self.start)
        self.ui.Stop.clicked.connect(self.stop)
        
    def start(self):
        go = {"action":"start"}
        json_data=json.dumps(go)
        s.sendto((json_data), (IP, PORT))
        print "action sent ", go

    def stop(self):
        go = {"action":"stop"}
        json_data=json.dumps(go)
        s.sendto((json_data), (IP, PORT))
        print "action sent ", go
        
    def send_location1(self):
        location = {"lat":locatoin1_lat, "lon":locatoin1_lon, "angle" : angle1}
        json_data=json.dumps(location)
        s.sendto((json_data), (IP, PORT))
        print "location 1 sent"

    def send_location2(self):
        location = {"lat":locatoin2_lat, "lon":locatoin2_lon, "angle" : angle2}
        json_data=json.dumps(location)
        s.sendto((json_data), (IP, PORT))         
        print "location 2 sent" 
        
    def send_location3(self):
        location = {"lat":locatoin3_lat, "lon":locatoin3_lon, "angle" : angle3}
        json_data=json.dumps(location)
        s.sendto((json_data), (IP, PORT))         
        print "location 3 sent"         
        
    def keyPressEvent(self, event1):
      verbose = {"FB":"", "LR":""}
      if event1.key() == QtCore.Qt.Key_W: 
        #print "Up pressed"
        verbose["FB"] = "F"
      if event1.key() == QtCore.Qt.Key_S:
        #print "D pressed"
        verbose["FB"] = "B"
      
      if event1.key() == QtCore.Qt.Key_A:
        #print "L pressed"
        verbose["LR"] = "L"
      if event1.key() == QtCore.Qt.Key_D:
        #print "R pressed"
        verbose["LR"] = "R"
        
      print verbose
      json_data=json.dumps(verbose)
      s.sendto((json_data), (IP, PORT))
      
    def keyReleaseEvent(self, event):
      verbose = {"FB":"", "LR":""}
      if event.key() == QtCore.Qt.Key_W: 
        #print "Up rel"
        verbose["FB"] = "S"
      if event.key() == QtCore.Qt.Key_S: 
        #print "D rel"
        verbose["FB"] = "S"
      
      if event.key() == QtCore.Qt.Key_A:
        #print "L pressed"
        verbose["LR"] = "S"
      if event.key() == QtCore.Qt.Key_D: 
        #print "R pressed"
        verbose["LR"] = "S"
        
      print verbose
      json_data=json.dumps(verbose)
      s.sendto((json_data), (IP, PORT))      
Esempio n. 17
0
class Test(QMainWindow):
    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Esempio n. 18
0
class Main(QMainWindow):
    def __init__(self,  sezlist):
        QMainWindow.__init__(self)
        self.sezlist = sezlist

        # This is always the same
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)

        # populate the list section
        listsect = []
        for s in self.sezlist:
            listsect.append(str(s))
        self.ui.listSections.insertItems(0, listsect)

        self.scene = QGraphicsScene(self)
        green = QColor(0, 150, 0)
        self.ui.sectionGraphics.setScene(self.scene)

        # take line edit from the UI and set data type Validation
        self.edit = self.ui.lineTabEdit
        float_validator = QDoubleValidator(-999999.0, 999999.0, 3, self.edit)
        self.edit.setValidator(float_validator)

        self.ksmin, self.ksmax = self.minmax_ks()
        # define how section line should be draw
        self.kslinestyle = 'color:width:dash' # 'color:width:dash:zigzag'

    def itemChanged(self, index):
        sect = self.sezlist[index]
        coord = sect.data
        self.sectionModel = SectionModel(coord)
        self.ui.tableSectionCoord.setModel(self.sectionModel)

        self.connect(self.sectionModel, SIGNAL("dataChanged(QModelIndex, QModelIndex)"), self.dataModelChanged)
        self.drawSection(coord)

    def dataModelChanged(self, index, index2):
        self.drawSection(self.sectionModel.array)

    def classify(self, ratio, numberOfClass):
        """
        Return classification of a number given the number of class

        >>> classify(1., 5)
        4
        >>> classify(0., 5)
        0
        >>> classify(0.3, 5)
        1
        >>> classify(0.5, 5)
        2
        """
        cl = 0
        pas = 1./numberOfClass
        limit = np.array([i for i in range(numberOfClass)]) * pas
        print '='*40
        print limit
        for i, l in enumerate(limit):
            if ratio >= l:
                print ratio, l, i
                cl = i
        print 'cl is:', cl
        return cl

    def getColorStyle(self, ks, pen):
        # Fraction to choose color and line 'color:width:dash:zigzag'
        r = (ks - self.ksmin)/(self.ksmax - self.ksmin)
        # classification in 5 different class
        cl = self.classify(r, 5)
        print 'r is:%s\nks is:%s\nclass is %s' % (r, ks, str(cl))
        if 'color' in self.kslinestyle:
            pen.setColor(QColor(int(250*(1-r)), 0, 0))
        if 'width' in self.kslinestyle:
            pen.setWidth(4-cl)
        if 'dash' in self.kslinestyle:
            dashstyle = {0 : Qt.SolidLine,
                         1 : Qt.DashLine,
                         2 : Qt.DashDotLine,
                         3 : Qt.DashDotDotLine,
                         4 : Qt.DotLine}
            pen.setStyle(dashstyle[4-cl])
        return pen

    def drawSection(self, array):
        self.scene.clear()
        r = 5
        i = 0
        pen = QPen(QColor(0, 0, 0))
        # initialize first point
        pnt0 = SectionPoint(self, i, array[0])
        # get firs ks
        x, y, z, ks = array[0]
        self.scene.addItem(pnt0)
        for data in array[1:]:
            i += 1
            pnt1 = SectionPoint(self, i, data)
            # change pen property
            pen0 = self.getColorStyle(ks, pen)
            self.scene.addLine(QLineF(pnt0.point, pnt1.point), pen0)
            self.scene.addItem(pnt1)
            pnt0 = pnt1
            x, y, z, ks = data

    def minmax_ks(self):
        """Return min and max of ks looking from all sections"""
        min = 0
        max = 0
        for s in self.sezlist:
            kslist = s.data.T[3]
            min0 = kslist.min()
            max0 = kslist.max()
            min = min if min < min0 else min0
            max = max if max > max0 else max0
        return min, max

    def on_actionOpen_triggered(self,checked=None):
        if checked is None: return
        filename = QFileDialog.getOpenFileName(self, 'Open project', '/home')
        print filename

    def on_actionImport_triggered(self,checked=None):
        if checked is None: return
        sectionsfilename = QFileDialog.getOpenFileName(self, 'Import sections.ori file', '/home')
        pointsfilename = QFileDialog.getOpenFileName(self, 'Import points.ori file', sectionsfilename)
        river = geo.Reach()
        river.importFileORI(sectionsfilename, pointsfilename)

    def on_actionRun_triggered(self,checked=None):
        if checked is None: return
        # TODO:
        #    * add command to compile?
        #    * or make /bin directory and check which system (32/64 bit) is running and which OS? and then run the comand?
        os.system('./../core/fixbed_sw_1D.out')

#-----------
    def getSimulationPoints(self, section):
        data = section.data
        x = float(section.xcoord[0])
        
        talweg = -float(section.min)
        watersurface = talweg
        #watersurface = sect.watersurf[t]
        bank_l = -float(data[0][2])
        bank_r = -float(data[-1][2])
        #points.append([sect.x, talweg, watersurface, bank_l, bank_r])
        p_talweg= QPointF(x, talweg)
        p_watersurface = QPointF(x, watersurface)
        p_bank_l = QPointF(x, bank_l)
        p_bank_r = QPointF(x, bank_r)
        return [p_talweg, p_watersurface, p_bank_l, p_bank_r]

    def drawLines(self):
	    """Generic function to add line to the scene, specify index (for examples, min, banks,)"""
	    #x0, y0, z0, ks0 = sectionlist[0].data[index]
	    #pnt0 = QPointF(x0, z0)
	    #points = []
	    print "djfhvbzvldz"
	    pen = QPen(QColor(0, 0, 0))
	    # TODO differentiate pens
	    sect0 = self.sezlist[0]
	    points0 = self.getSimulationPoints(sect0)
	    for sect in self.sezlist[1:]:
		    points1 = self.getSimulationPoints(sect)
		    for i in range(4):
			    self.scene.addLine(QLineF(points0[i], points1[i]), pen)
		    points0 = points1
	    self.ui.sectionGraphics.setScene(self.scene)
#------

    def on_actionView_triggered(self, checked=None):
        if checked is None: return
        self.scene.clear()
        self.drawLines()
        
        #viewer = ViewSimulation1D(self, self.sezlist)
        #self.ui.sectionGraphics.setScene(viewer.getScene())

    def on_lineTabEdit_returnPressed(self, checked=None):
        # selectedIndexes() returns a list of all selected and non-hidden item indexes in the view
        cellist = self.ui.tableSectionCoord.selectedIndexes()
        newvalue = self.edit.text()
        #print self.sectionModel.array
        for cel in cellist:
            self.sectionModel.setData(cel, newvalue)
        self.edit.clear()
Esempio n. 19
0
class MainWin(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.settings = updater.Settings()
        self.domains  = updater.Domains()
        self.dom_data = []
        self.codes =    {
                            '401' : 'Incorrect user/pass, or no API access.',
                            '404' : 'Could not find domain/record',
                            '500' : 'A server error has occurred',
                        }
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.create_sys_tray()
        self.check_configs()
        self.connect_ctrls()
        self.run_loop()
    
    
    def get_code_text(self, code):
        try:
            txt = self.codes[str(code)]
        except:
            txt = "Unknown error occured. Please Try again later."
        return txt
        
    
    def stub(self):
        print 111
    
    def connect_ctrls(self):
        self.ui.ch_acct.clicked.connect(self.change_acct)
        self.ui.ch_dom.clicked.connect(self.change_dom)
        self.ui.refresh.clicked.connect(self.refresh)
        self.connect(self.ui.actionHide, QtCore.SIGNAL('triggered()'), self.hide)
        self.connect(self.ui.actionQuit_2, QtCore.SIGNAL('triggered()'), sys.exit)
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'), self.about)
        
       
    def about(self):
        x = About(parent=self)
        x.exec_()
                          
    def change_acct(self):
        x = MyLogin(self)
        self.connect(x, QtCore.SIGNAL("userChanged"), self.acct_callback)
        x.exec_()

    
    def change_dom(self):
        self.domains = updater.Domains()
        try:
            del self.domains.config['domain']
            self.domains.config.write()
        except:
            pass
        self.dom_data = self.domains.get_domains()
        if len(self.dom_data) > 0:
            x = myDomains(self.dom_data, parent=self)
            self.connect(x, QtCore.SIGNAL("domChanged"), self.dom_callback)
        else:
            x = NoDoms(parent=self)
        x.exec_()
        
        
    def acct_callback(self):
        self.check_configs()
        self.display_info()        
        
        
    def dom_callback(self):
        self.check_configs()
        self.display_info()   
    
    
    def refresh(self):
        self.domains = updater.Domains()
        if 'cache' in self.domains.config:
            del self.domains.config['cache']
            self.domains.config.write()
        self.emit(QtCore.SIGNAL("RefreshEvent"))
        
        
    def get_cache(self):
        try:
            self.cache = self.domains.config['cache']
        except:
            self.domains.config['cache'] = {}
            self.domains.config.write()
            self.cache = {}
        return self.cache
        

    def check_configs(self):
        self.refresh_configs()
        if self.settings.is_configured() is False:
            x = MyLogin(self)
            x.exec_()
        if self.settings.has_domain() is False:
            self.domains = updater.Domains()
            self.dom_data = self.domains.get_domains()
            if len(self.dom_data) > 0:
                x = myDomains(self.dom_data, parent=self)
            else:
                x = NoDoms(parent=self)
            x.exec_()


    def refresh_configs(self):
        self.settings = updater.Settings()
        self.domains  = updater.Domains()

    def set_staus(self, msg1, msg2=None):
        txt = msg1
        if msg2 != None:
            txt = txt + "\n                 " + str(msg2)
        self.ui.UpStat.setText("Status:     %s" % txt)
        
    def set_record(self, msg1, msg2=None):
        txt = msg1
        if msg2 != None:
            txt = txt + "\n                 " + str(msg2)
        self.ui.DomInfo.setText("Record:   %s" % txt)
     
    def set_acct(self, msg1, msg2=None):
        txt = msg1
        if msg2 != None:
            txt = txt + "\n                 " + str(msg2)
        self.ui.AcctInfo.setText("Account: %s" % txt)

    def display_info(self):
        self.refresh_configs()
        rec_name = self.domains.config['domain']['rec_name']
        if rec_name == '@':
            dsp_rec = self.domains.config['domain']['name']
        else:
            dsp_rec = rec_name + "." + self.domains.config['domain']['name']
            
        self.ui.AcctInfo.setText("Account: %s" % str(self.domains.config['user']['username']))
        self.ui.DomInfo.setText("Record:   %s" % str(dsp_rec))
        

    def run_loop(self):
        self.updateT = updateThread(self)
        self.display_info()
        self.updateT.begin()
        self.connect(self.updateT, QtCore.SIGNAL("notifEvent"), self.treatEvent)
        self.connect(self.updateT, QtCore.SIGNAL("notifIPEvent"), self.treatIPEvent)


    def create_sys_tray(self):
        self.sysTray = QtGui.QSystemTrayIcon(self)
        menu = QtGui.QMenu()
        exit = menu.addAction("Exit")
        self.sysTray.setContextMenu(menu)
        self.connect(exit, QtCore.SIGNAL('triggered()'), sys.exit)
        self.sysTray.setIcon( QtGui.QIcon(':/updater/icon.png') )
        self.sysTray.setVisible(True)
        self.connect(self.sysTray, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.on_sys_tray_activated)

        self.sysTrayMenu = QtGui.QMenu(self)
        act = self.sysTrayMenu.addAction("FOO")

    def on_sys_tray_activated(self, reason):     
        if reason == 3:   
            if self.isVisible ():
                self.setVisible(False)
            else:
                self.setVisible(True)
                

    def treatIPEvent(self, msg):
        print "IP event: " + str(msg)


    def treatEvent(self, msg):
        if str(msg) == '401':
            cache = self.get_cache()
            self.domains.config['cache']['auth_err'] = True
            self.domains.config.write()
            self.change_acct()
        if str(msg) == '404':
            self.change_dom()

    def closeEvent(self, event):
        if self.isVisible():
            self.setVisible(False)
        event.ignore()
Esempio n. 20
0
class MainWindow(QMainWindow):
    """docstring for quote guessing game"""
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.score = 0
        self.pause_round = False
        self.game_state = False

        #button functions
        self.ui.nextButton.clicked.connect(self.next_question)
        self.ui.submitButton.clicked.connect(self.submit_answer)
        self.ui.resetButton.clicked.connect(self.reset_game)
        self.current_text = self.ui.quotesBox.text()

    def make_question(self):
        """generate a game question"""
        whole_quote = str(random.choice(quote_list))
        self.answer = re.search('\(([^)]+)', whole_quote).group(1).lower()
        return whole_quote.split("-")[0][2:]

    def next_question(self):
        """move game state into new round"""
        if self.pause_round == False:
            self.ui.quotesBox.setText(self.make_question())
            self.ui.answerBox.clear()
            print(self.answer)
            self.game_state = True
            self.pause_round = True
            self.ui.submitButton.setEnabled(True)
        else:
            return

    def submit_answer(self):
        """submit and check user answer"""
        current_answer = self.ui.answerBox.text()
        # self.game_state = True
        if self.game_state:
            if current_answer.lower() == self.answer.lower():
                self.ui.quotesBox.setText("Nice Job!")
                self.score += 1
                self.ui.scoreboard.display(self.score)
                self.ui.answerBox.clear()
                self.game_state = False
                self.pause_round = False
            else:
                self.ui.quotesBox.setText(
                    f"Sorry that's incorrect. The correct answer was: {self.answer} (Press Reset to start again.)"
                )
        else:
            return

    def reset_game(self):
        """reset game state"""
        self.ui.quotesBox.setText(
            "Guess the movie based off the villain. Press Next to begin ")
        self.ui.answerBox.clear()
        self.score = 0
        self.ui.scoreboard.display(self.score)
        self.pause_round = False
        self.ui.submitButton.setEnabled(False)
Esempio n. 21
0
class AppWindow(QMainWindow):
    def __init__(self):
        super(AppWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.conf_ui()

    def conf_ui(self):
        self.ui.btn_gen.clicked.connect(self.pic_gen)
        self.ui.btn_gendataset.clicked.connect(self.gen_dataset)
        self.ui.btn_train.clicked.connect(self.train)
        self.tools = gui_tools.utils(self)
        self.config = {}
        self.update_config()
        self.config.update({'image_counter': 0})

    def train(self):
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        self.tools.logging("The model is set.")
        self.tools.logging("The {} device is selected.".format(device))
        self.model = learning.AliNet()
        self.model = self.model.to(device)
        self.dataloaders = self.dataloaders.to(device)
        summary(self.model, input_size=(3, 25, 25))
        self.optimizer_ft = optim.Adam(self.model.parameters(), lr=1e-4)
        self.exp_lr_scheduler = lr_scheduler.StepLR(self.optimizer_ft,
                                                    step_size=25,
                                                    gamma=0.1)
        self.model = learning.train_model(self.model,
                                          self.dataloaders,
                                          self.optimizer_ft,
                                          self.exp_lr_scheduler,
                                          num_epochs=10)

    def gen_dataset(self):
        self.update_config()

        dataset_train = learning.generated_data(self.config, 'train')
        dataset_test = learning.generated_data(self.config, 'test')
        # dataset_train = learning.generated_data(self.config,'train')
        # dataset_test =  learning.generated_data(self.config,'test')

        # print(len(self.dataset_train) ,len(self.dataset_test))

        self.datasets = {'train': dataset_train, 'test': dataset_test}
        # print(len(self.datasets['train']))
        batch_size = 50
        self.dataloaders = {
            'train':
            DataLoader(dataset_train,
                       batch_size=batch_size,
                       shuffle=True,
                       num_workers=0),
            'test':
            DataLoader(dataset_test,
                       batch_size=batch_size,
                       shuffle=True,
                       num_workers=0)
        }

        dataset_sizes = {
            x: len(self.datasets[x])
            for x in self.datasets.keys()
        }
        # print(dataset_sizes)

        self.tools.logging(
            "Datasets are generated \nTrain_data size:{}\nTest_data size:{}".
            format(dataset_sizes['train'], dataset_sizes['test']))

        def reverse_transform(inp):
            inp = inp.numpy().transpose((1, 2, 0))
            inp = np.clip(inp, 0, 1)
            inp = (inp * 255).astype(np.uint8)

            return inp

        # Get a batch of training data
        inputs, masks = next(iter(self.dataloaders['train']))

        # print(inputs.shape, masks.shape)
        for x in [inputs.numpy(), masks.numpy()]:
            # print(x.min(), x.max(), x.mean(), x.std())
            self.tools.logging(
                "[Train Statistics and Assosiated Masks]: \nMin={} \nMax={} \nMean={} \nSTD={}"
                .format(x.min(), x.max(), x.mean(), x.std()), 'red')

        # plt.imshow(reverse_transform(inputs[3]))
        # plt.show()

    def center_points(self, plt, anntation):
        # objes={}
        # objes=anntation
        # objes.values()
        for obj in anntation:
            print(anntation[obj][1])
            plt.plot(anntation[obj][1],
                     anntation[obj][0],
                     'ro--',
                     linewidth=1,
                     markersize=2)

    def pic_gen(self):

        self.update_config()

        H_, W_, N_ = self.config['image_size_H'], self.config[
            'image_size_W'], self.config['objecs_num']
        F_ = self.config['objecs_Fill']
        C_, S_, T_ = self.config['objecs_circle'], self.config[
            'objecs_squre'], self.config['objecs_triangle']

        if C_ or S_ or T_:

            img, masks, annot = gen_pic.generate_img_and_mask(H_,
                                                              W_,
                                                              num_each_obj=N_,
                                                              fill=F_,
                                                              circle=C_,
                                                              squre=S_,
                                                              triangle=T_)
            masks = masks.transpose(1, 2, 0)
            # img = img.transpose(2, 0, 1)
            img = np.reshape(img, (H_, W_))

            self.config['image_counter'] += 1
            self.tools.logging("Generated image:" +
                               str(self.config['image_counter']))
            # print("Genrated_image", self.config['image_counter'])

            # print(img.shape)
            fig = plt.figure(figsize=(9, 15))
            gs = gridspec.GridSpec(nrows=2, ncols=masks.shape[2])
            title = ["Circle Mask", "Squre Mask", "Tria angle Mask"]
            #
            for i in range(masks.shape[2]):
                ax = fig.add_subplot(gs[0, i])
                ax.imshow(masks[:, :, i])
                ax.set_title(title[i])
            #
            ax = fig.add_subplot(gs[1, :])
            self.center_points(ax, annot)
            ax.imshow(img)
            ax.set_title("Generated Image")
            # # plt.tight_layout()
            plt.show()

    def update_config(self):
        self.config.update({'image_size_H': int(self.ui.in_img_size_H.text())})
        self.config.update({'image_size_W': int(self.ui.in_img_size_W.text())})
        self.config.update({'objecs_num': int(self.ui.in_num_objs.text())})
        self.config.update({'objecs_Fill': int(self.ui.in_objs_fill.text())})
        self.config.update(
            {'objecs_circle': (self.ui.chk_box_circle.isChecked())})
        self.config.update(
            {'objecs_squre': (self.ui.chk_box_squre.isChecked())})
        self.config.update(
            {'objecs_triangle': (self.ui.chk_box_triangle.isChecked())})
        self.config.update(
            {'dataset_size_test': int(self.ui.btn_test_size.text())})
        self.config.update(
            {'dataset_size_train': int(self.ui.btn_train_size.text())})
        if self.ui.chbox_show_configuration.isChecked():
            self.tools.logging("[Configuration]: \n" + (str(self.config)),
                               "red")
Esempio n. 22
0
class MyMainWindow(QtWidgets.QMainWindow):
    N_UNITS = 2

    def __init__(self, io):
        QtWidgets.QWidget.__init__(self, None)
        self.io = io
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.unit_filenames = [""] * self.N_UNITS
        self.unit_file = self.instances_to_list("file")
        self.unit_load = self.instances_to_list("load")
        for n in range(self.N_UNITS):
            f = (lambda n: lambda: self.load_image(n))(n)
            self.unit_load[n].clicked.connect(f)
        self.unit_loaded = [False] * self.N_UNITS
        self.unit_readonly = self.instances_to_list("readonly")
        for n in range(self.N_UNITS):
            f = (lambda n: lambda state: self.set_read_only(n, state))(n)
            self.unit_readonly[n].clicked.connect(f)
        self.rd_counter = [0] * self.N_UNITS
        self.wr_counter = [0] * self.N_UNITS
        self.unit_read = self.instances_to_list("read")
        self.unit_write = self.instances_to_list("write")
        self.unit_lba = self.instances_to_list("lba")
        self.unit_cyl = self.instances_to_list("cyl")
        self.unit_head = self.instances_to_list("head")
        self.unit_sec = self.instances_to_list("sec")
        for model in hp_disk_protocol.DRIVE_MODELS:
            self.ui.drive_model.addItem(model.name)
        self.set_connected_state(False)
        self.io.status_connect.connect(self.conn_status)
        self.io.rd_counter.connect(self.inc_rd_counter)
        self.io.wr_counter.connect(self.inc_wr_counter)
        self.io.curr_pos.connect(self.set_current_pos)
        self.io.active.connect(self.active)
        for n in range(self.N_UNITS):
            self.clear_status(n)
        self.io.set_address(0)
        self.addr_timer = QtCore.QTimer()
        self.addr_timer.timeout.connect(self.addr_timer_to)
        self.addr_timer.setSingleShot(True)
        self.load_settings()

    def instances_to_list(self, suffix):
        l = [
            self.ui.__dict__["unit{}_{}".format(n, suffix)]
            for n in range(self.N_UNITS)
        ]
        return l

    # SLOT
    def set_model(self, model_idx):
        model = hp_disk_protocol.DRIVE_MODELS[model_idx]
        self.ui.drive_protocol.setText(model.protocol)
        g = model.geometry
        self.ui.drive_geometry.setText("{}x{}x{}".format(g[0], g[1], g[2]))
        size = model.max_lba * 256
        self.ui.drive_capacity.setText("{} k".format((size + 1023) // 1024))
        self.ui.unit1.setEnabled(model.units > 1)
        for n in range(self.N_UNITS):
            self.clear_status(n)
        self.io.set_model(model_idx)

    # SLOT
    def active(self):
        self.addr_timer.start(100)
        self.ui.drive_active.setStyleSheet("background-color: red")

    # SLOT
    def addr_timer_to(self):
        self.ui.drive_active.setStyleSheet("")
        self.io.clear_active()

    # SLOT
    def set_address(self, addr):
        if not self.connected:
            self.io.set_address(addr)

    # SLOT
    def conn_status(self, status, msg):
        if status == rem488.CONNECTION_OK:
            self.ui.statusbar.showMessage("Connected {}".format(msg))
            self.set_connected_state(True)
        elif status == rem488.CONNECTION_CLOSED:
            self.ui.statusbar.showMessage("Disconnected")
            self.set_connected_state(False)
        else:
            self.ui.statusbar.showMessage("Connection failure")
            self.set_connected_state(False)

    def load_file(self, unit, filename):
        status = self.io.load_image(unit, filename)
        if status == 0:
            self.unit_filenames[unit] = filename
            self.unit_file[unit].setText(os.path.basename(filename))
            self.unit_load[unit].setText("Unload")
            self.unit_loaded[unit] = True
            self.unit_readonly[unit].setEnabled(False)
        else:
            self.clear_image_file(unit)
        return status

    def load_image(self, unit):
        if self.unit_loaded[unit]:
            self.io.load_image(unit, None)
            self.clear_image_file(unit)
        else:
            f = QtWidgets.QFileDialog.getOpenFileName(
                self, "Select image file for unit {}".format(unit))
            if f[0]:
                status = self.load_file(unit, f[0])
                if status != 0:
                    QtWidgets.QMessageBox.critical(
                        self, "Error",
                        "Can't open file {} (err={})".format(f[0], status))
        self.clear_counters(unit)
        self.clear_pos(unit)

    def clear_status(self, unit):
        self.clear_image_file(unit)
        self.clear_counters(unit)
        self.clear_pos(unit)

    def clear_image_file(self, unit):
        self.unit_filenames[unit] = ""
        self.unit_file[unit].setText("")
        self.unit_load[unit].setText("Load")
        self.unit_loaded[unit] = False
        self.unit_readonly[unit].setEnabled(True)

    def set_read_only(self, unit, state):
        self.io.set_read_only(unit, state)

    def set_connected_state(self, connected):
        self.connected = connected
        self.ui.drive_model.setEnabled(not connected)
        self.ui.drive_addr.setEnabled(not connected)

    def clear_counters(self, unit):
        self.rd_counter[unit] = 0
        self.wr_counter[unit] = 0
        self.unit_read[unit].setNum(0)
        self.unit_write[unit].setNum(0)

    # SLOT
    def inc_rd_counter(self, unit, delta):
        self.rd_counter[unit] += delta
        self.unit_read[unit].setNum(self.rd_counter[unit])

    # SLOT
    def inc_wr_counter(self, unit, delta):
        self.wr_counter[unit] += delta
        self.unit_write[unit].setNum(self.wr_counter[unit])

    def clear_pos(self, unit):
        self.unit_lba[unit].setNum(0)
        self.unit_cyl[unit].setNum(0)
        self.unit_head[unit].setNum(0)
        self.unit_sec[unit].setNum(0)

    # SLOT
    def set_current_pos(self, unit, lba, cyl, head, sec):
        self.unit_lba[unit].setNum(lba)
        self.unit_cyl[unit].setNum(cyl)
        self.unit_head[unit].setNum(head)
        self.unit_sec[unit].setNum(sec)

    def load_settings(self):
        settings = QtCore.QSettings("hp_disk")
        settings.beginGroup("MainWindow")
        geo = settings.value("geometry")
        if geo:
            self.restoreGeometry(geo)
        settings.endGroup()
        settings.beginGroup("Drive")
        x = settings.value("model", 0, int)
        self.ui.drive_model.setCurrentIndex(x)
        x = settings.value("address", 0, int)
        self.ui.drive_addr.setValue(x)
        settings.endGroup()
        n = min(settings.beginReadArray("Unit"), self.N_UNITS,
                self.io.get_unit_count())
        read_only = self.instances_to_list("readonly")
        for i in range(n):
            settings.setArrayIndex(i)
            ro = settings.value("readonly", False, bool)
            read_only[i].setChecked(ro)
            self.set_read_only(i, ro)
            filename = settings.value("file")
            if filename:
                self.load_file(i, filename)
        settings.endArray()

    def save_settings(self):
        settings = QtCore.QSettings("hp_disk")
        settings.beginGroup("MainWindow")
        settings.setValue("geometry", self.saveGeometry())
        settings.endGroup()
        settings.beginGroup("Drive")
        settings.setValue("model", self.ui.drive_model.currentIndex())
        settings.setValue("address", self.ui.drive_addr.value())
        settings.endGroup()
        settings.beginWriteArray("Unit", self.N_UNITS)
        read_only = self.instances_to_list("readonly")
        read_only_values = [ro.isChecked() for ro in read_only]
        for i in range(self.N_UNITS):
            settings.setArrayIndex(i)
            settings.setValue("file", self.unit_filenames[i])
            settings.setValue("readonly", read_only_values[i])
        settings.endArray()

    def closeEvent(self, event):
        self.save_settings()
        event.accept()
Esempio n. 23
0
class MainView(QtGui.QMainWindow):
	def __init__(self, parent=None):
		super(MainView, self).__init__(parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.about=None
		self.objects=None
		self._FIfilter=u'All Files (*.*);;Database files (*.dat *.db);;SQL files (*.sql *.sqlite);;Text files (*.txt);;Binary files (*.bin)'
		self.ui.tabPanel.removeTab(0)
	def injectAbout(self,a):
		if self.about!=None:
			raise ValueError("Immutable property already injected!")
		self.about=a
		
	def labelUi(self, labels):
		if self.objects!=None:
			raise ValueError("Immutable property already injected!")
		self.objects={}
		for page in (self.ui.tableToolPage,self.ui.viewToolPage,self.ui.indexToolPage,self.ui.triggerToolPage):
			page.setModel(QtGui.QStandardItemModel())
		for code in labels.keys():
			l=labels[code]
			lab=QtGui.QTreeWidgetItem(self.ui.treeBox,[l])
			self.ui.treeBox.addTopLevelItem(lab)
			self.objects[code]=lab
			self.makeTree(lab,["-- No %s Yet!" % l])
	
	def makeTree(self,parent,text):
		return QtGui.QTreeWidgetItem(parent,[text])
	def makeScroll(self,text):
		return QtGui.QStandardItem(text)

	def confirmExit(self):
		YES=QtGui.QMessageBox.Yes
		NO=QtGui.QMessageBox.No
		msg=u'You have made unsaved changes to the database.\nAre you sure you want to exit?'
		return YES==QtGui.QMessageBox.question(self, u'Confirm Exit', msg,YES|NO,NO)
		
	def aboutDialog(self):
		self.about.open()
		
	def	openDialog(self,path):
		fn,_ = QtGui.QFileDialog.getOpenFileName(self, self.ui.menuFile_Open.toolTip(),path,self._FIfilter,u'All Files (*.*)')
		if not fn=="":
			return fn

	def	newDialog(self,path):
		fn,_ = QtGui.QFileDialog.getSaveFileName(self, self.ui.menuFile_New.toolTip(),path,self._FIfilter,u'Database files (*.dat *.db)')
		if not fn=="":
			return fn
	
	def putTab(self,tabWidget,icon,name):
		self.ui.tabPanel.setUpdatesEnabled(False)
		self.ui.workStack.setCurrentIndex(1)
		self.ui.tabPanel.setVisible(True)
		if icon is None:
			index=self.ui.tabPanel.addTab(tabWidget,name)
		else:
			index=self.ui.tabPanel.addTab(tabWidget,icon,name)
		self.ui.tabPanel.setUpdatesEnabled(True)
		return index

	def refresh(self, DBloaded):
		self.ui.treeBox.setEnabled(DBloaded)
		self.ui.toolBox.setEnabled(DBloaded)
	
	def notify(self,msg,ex):
		QtGui.QMessageBox.question(self, u'Error Handler', msg,QtGui.QMessageBox.Ok,QtGui.QMessageBox.Ok)
		raise ex
class MainWindows(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindows, self).__init__(parent)
        self.Ui = Ui_MainWindow()
        self.Ui.setupUi(self)
        self.setFixedSize(self.width(), self.height())  ##设置宽高不可变
        self.timer = QTimer()  #设定一个定时器用来显示时间
        self.setWindowIcon(QtGui.QIcon('./main.png'))
        self.timer.timeout.connect(self.showtime)
        self.timer.start()
        self.Ui.encode_Button.clicked.connect(self.encode)  # 编码按钮
        self.Ui.decode_Button.clicked.connect(self.decode)  # 解码按钮
        self.Ui.clear_Button.clicked.connect(self.clear)  # clear
        self.Ui.Copy_Source_Button.clicked.connect(
            lambda: self.Copy_text('Source'))  # copy_source
        self.Ui.Copy_ResultButton.clicked.connect(
            lambda: self.Copy_text('result'))  # copy_result
        self.Ui.tihuan.clicked.connect(self.tihuan)  # tihuan
        self.readfile()
        self.Ui.panduan.clicked.connect(lambda: self.Ui.Source_text.setText(
            str(json_data[self.Ui.sql_type.currentText()]['public']['panduan'])
        ))  # panduan
        self.Ui.chaxunliehshu.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['public'][
                    'chaxunliehshu'])))  # chaxunliehshu
        self.Ui.user.clicked.connect(lambda: self.Ui.Source_text.setText(
            str(json_data[self.Ui.sql_type.currentText()]['public']['user']))
                                     )  # user
        self.Ui.version.clicked.connect(lambda: self.Ui.Source_text.setText(
            str(json_data[self.Ui.sql_type.currentText()]['public']['version'])
        ))  # version
        self.Ui.path.clicked.connect(lambda: self.Ui.Source_text.setText(
            str(json_data[self.Ui.sql_type.currentText()]['public']['path']))
                                     )  # path
        self.Ui.single_databases.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Order'][
                    'single_databases'])))  # single_databases
        self.Ui.current_databases.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Order'][
                    'current_databases'])))  # current_databases
        self.Ui.all_databases.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Order'][
                    'all_databases'])))  # all_databases
        self.Ui.single_tables.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Order'][
                    'single_tables'])))  # single_tables
        self.Ui.all_tables.clicked.connect(lambda: self.Ui.Source_text.setText(
            str(json_data[self.Ui.sql_type.currentText()]['Order'][
                'all_tables'])))  # all_tables
        self.Ui.single_columns.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Order'][
                    'single_columns'])))  # single_columns
        self.Ui.all_columns.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Order'][
                    'all_columns'])))  # all_columns
        self.Ui.mangzhu_databases.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Blinds'][
                    'mangzhu_databases'])))  # mangzhu_databases
        self.Ui.mangzhu_tables.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Blinds'][
                    'mangzhu_tables'])))  # mangzhu_tables
        self.Ui.mangzhu_lumns.clicked.connect(
            lambda: self.Ui.Source_text.setText(
                str(json_data[self.Ui.sql_type.currentText()]['Blinds'][
                    'mangzhu_columns'])))  # mangzhu_lumns
        self.Ui.data.clicked.connect(lambda: self.Ui.Source_text.setText(
            str(json_data[self.Ui.sql_type.currentText()]['others']['data']))
                                     )  # data
        self.Ui.others.clicked.connect(lambda: self.Ui.Source_text.setText(
            str(json_data[self.Ui.sql_type.currentText()]['others']['others']))
                                       )  # others

    def readfile(self):
        global json_data
        f = open('data.json', 'r', encoding='utf-8')
        json_data = json.load(f)
        f.close()

    def showtime(self):  #显示时间
        datetime = QDateTime.currentDateTime()
        text = datetime.toString("yyyy-MM-dd hh:mm:ss")
        self.Ui.time.setText(text)

    #编码
    def encode(self):
        if __name__ == '__main__':
            text = self.Ui.Source_text.toPlainText()
            code_type = self.Ui.encode_type.currentText()
            if code_type == 'URL-UTF8':
                self.URLencode(text, 'utf8')
            if code_type == 'URL-GB2312':
                self.URLencode(text, 'gb2312')
            if code_type == 'Unicode':
                self.Unicodeencode(text)
            if code_type == 'Escape(%U)':
                self.Escapeencode(text)
            if code_type == 'HtmlEncode':
                self.Htmlencode(text)
            if code_type == 'ASCII':
                self.ASCIIencode(text)
            if code_type == 'Base64':
                self.base64encode(text)
            if code_type == 'Str<->Hex':
                self.Strtohexencode(text)
            if code_type == 'SQL-Char':
                self.Charencode(text)
            if code_type == 'SQL-Hex':
                self.Hexencode(text)

    def URLencode(self, text, type):
        # 先进行gb2312编码
        if type == 'utf8':
            text = text.encode('utf-8')
            text = urllib.parse.quote(text)
        if type == 'gb2312':
            text = text.encode('gb2312')
            text = urllib.parse.quote(text)
        self.Ui.Result_text.setText(text)

    def Unicodeencode(self, text):
        text = text.encode('unicode_escape')
        self.Ui.Result_text.setText(str(text, encoding='utf-8'))

    def Escapeencode(self, text):
        text = text.encode('unicode_escape')
        self.Ui.Result_text.setText(
            str(text, encoding='utf-8').replace('\\u', '%u'))

    def Htmlencode(self, text):
        text = html.escape(text)
        self.Ui.Result_text.setText(str(text))

    def ASCIIencode(self, text):
        result = ''
        for i in text:
            result = str(result) + str(ord(str(i))) + ' '
        self.Ui.Result_text.setText(str(result)[:-1])

    def base64encode(self, text):
        text = base64.b64encode(text.encode("utf-8"))
        self.Ui.Result_text.setText(str(text, encoding='utf-8'))

    def Strtohexencode(self, text):
        result = ''
        for i in text:
            single = str(hex(ord(str(i))))
            result = result + single
        self.Ui.Result_text.setText('0x' + (str(result)).replace('0x', ''))

    def Charencode(self, text):
        result = ''
        for i in text:
            single = str(ord(str(i)))
            result = result + 'char(%s)+' % single
        self.Ui.Result_text.setText(str(result)[:-1])

    def Hexencode(self, text):
        result = ''
        for i in text:
            single = str(hex(ord(str(i))))
            result = result + 'hex(%s)+' % single
        self.Ui.Result_text.setText((str(result)[:-1]).replace('0x', ''))

    #解码
    def decode(self):
        if __name__ == '__main__':
            text = self.Ui.Source_text.toPlainText()
            code_type = self.Ui.encode_type.currentText()
            if code_type == 'URL-UTF8':
                self.URLdecode(text, 'utf8')
            if code_type == 'URL-GB2312':
                self.URLdecode(text, 'gb2312')
            if code_type == 'Unicode':
                self.Unicodedecode(text)
            if code_type == 'Escape(%U)':
                self.Escapedecode(text)
            if code_type == 'HtmlEncode':
                self.Htmldecode(text)
            if code_type == 'ASCII':
                self.ASCIIdecode(text)
            if code_type == 'Base64':
                self.base64decode(text)
            if code_type == 'Str<->Hex':
                self.Strtohexedecode(text)
            if code_type == 'SQL-Char':
                self.Chardecode(text)
            if code_type == 'SQL-Hex':
                self.Hexdecode(text)

    def URLdecode(self, text, type):
        if type == 'utf8':
            text = urllib.parse.unquote(text)
        if type == 'gb2312':
            text = urllib.parse.unquote(text, 'gb2312')
        self.Ui.Result_text.setText(str(text))

    def Unicodedecode(self, text):
        text = bytes(text, encoding="utf8").decode('unicode_escape')
        # print(text)
        self.Ui.Result_text.setText(text)

    def Escapedecode(self, text):
        text = text.replace('%u', '\\u').replace('%U', '\\u')
        text = bytes(text, encoding="utf8").decode('unicode_escape')
        # print(text)
        self.Ui.Result_text.setText(text)

    def Htmldecode(self, text):
        # h=HTMLParser()
        self.Ui.Result_text.setText(html.unescape(text))

    def ASCIIdecode(self, text):
        if ':' in text:
            text = text.split(":")
        if ' ' in text:
            text = text.split(" ")
        if ';' in text:
            text = text.split(";")
        if ',' in text:
            text = text.split(",")
        result = ''
        for i in text:
            if i != '':
                # print(chr(int(i)))
                result = result + chr(int(i))
        # print(result)
        self.Ui.Result_text.setText(str(result))

    def base64decode(self, text):
        text = base64.b64decode(text.encode("utf-8"))
        self.Ui.Result_text.setText(str(text, encoding='utf-8'))

    def Strtohexedecode(self, text):
        text = text.replace('0x', '').replace('0X', '')
        text = str(bytes.fromhex(text), encoding="utf-8")
        self.Ui.Result_text.setText(str(text))

    def Chardecode(self, text):
        text = text.replace('char(', '').replace(')', '').split("+")
        result = ''
        for i in text:
            if i != '':
                # print(chr(int(i)))
                result = result + chr(int(i))
        self.Ui.Result_text.setText(str(result))

    def Hexdecode(self, text):
        text = text.replace('hex(', '').replace(')', '').split("+")
        result = ''
        for i in text:
            if i != '':
                result = result + chr(int(str(i), 16))
        self.Ui.Result_text.setText(str(result))

    def clear(self):
        self.Ui.Source_text.clear()
        self.Ui.Result_text.clear()

    def Copy_text(self, text):
        if text == 'Source':
            data = self.Ui.Source_text.toPlainText()
        if text == 'result':
            data = self.Ui.Result_text.toPlainText()
        # 访问剪切板,存入值
        wincld.OpenClipboard()
        wincld.EmptyClipboard()
        wincld.SetClipboardData(win32con.CF_UNICODETEXT, data)
        wincld.CloseClipboard()

    def tihuan(self):
        source_text = self.Ui.tihuan_source.text()
        result_text = self.Ui.tihuan_result.text()
        text = self.Ui.Source_text.toPlainText()
        text = text.replace(source_text, result_text)
        self.Ui.Source_text.setText(str(text))
Esempio n. 25
0
class EventHandler(object):
    def openMainWindow(self):
        app = QtWidgets.QApplication(sys.argv)
        self.MainWindow = QtWidgets.QMainWindow()
        self.ui_main = Ui_MainWindow()
        self.ui_main.setupUi(self.MainWindow)
        self.ui_main.actionLog_in.triggered.connect(self.MainWindow.hide)
        self.ui_main.btn_fileUpload.clicked.connect(self.selectUploadFile)
        self.ui_main.btn_filesUpload.clicked.connect(self.selectUploadFiles)
        self.ui_main.btn_dirUpload.clicked.connect(self.selectUploadDir)
        self.ui_main.btn_fileDownload.clicked.connect(self.selectFileDownload)
        self.MainWindow.show()
        self.configLoginDialog()
        sys.exit(app.exec_())
        
    def configLoginDialog(self):
        self.Dialog = QtWidgets.QDialog()
        self.ui_login = Ui_Dialog()
        self.ui_login.setupUi(self.Dialog)
        self.ui_login.btn_register.clicked.connect(self.registerUser)
        self.ui_login.btn_login.clicked.connect(self.login)
        self.ui_main.actionLog_in.triggered.connect(self.Dialog.show)
        
        if not hasattr(self, "user"):
            self.MainWindow.hide()
            self.Dialog.show()
        
    def registerUser(self):
        name = self.ui_login.txt_name.text()
        password = self.ui_login.txt_password.text()
        TCPClient().send(("addUser", (name, password)))
         
    def login(self):
        name = self.ui_login.txt_name.text()
        password = self.ui_login.txt_password.text()
        user = TCPClient().send(("getUserByName", (name,)))
        if user != None and user[2] == password:
            self.user = user
            self.MainWindow.show()
            self.Dialog.close()
            self.showUserListTable()
            return True
        else:
            return False
        
    def showUserListTable(self):
        users = TCPClient().send(("getUsers",()))
        print(users)
        try:
            if users != None:
                index = 0
                for user in users:
                    self.createUserListTableRow(index, user)
                    index += 1
        except Exception as e:
            print("Show user list table failed.", e)
    
    def createUserListTableRow(self, index, user):
#         set table row count
        _translate = QtCore.QCoreApplication.translate
        self.ui_main.userList_table.setRowCount(index + 1)
        
#         set vertical item
#         item = QtWidgets.QTableWidgetItem()
#         self.ui_main.userList_table.setVerticalHeaderItem(index, item)
#         item = self.ui_main.userList_table.verticalHeaderItem(index)
#         item.setText(_translate("MainWindow", str(index)))

#         set row item
        item = QtWidgets.QTableWidgetItem()
        self.ui_main.userList_table.setItem(index, 0, item)
#         item = self.ui_main.userList_table.item(index, 0)
        item.setText(_translate("MainWindow", user[1]))
        
#         set row item
        item = QtWidgets.QTableWidgetItem()
        self.ui_main.userList_table.setItem(index, 1, item)
#         item = self.ui_main.userList_table.item(index, 1)
        item.setText(_translate("MainWindow", user[2]))
        
    def analysisFile(self, lines):
        client = TCPClient()
        for line in lines:
            client.send(("analysisFile", (line,)), self.analysisFileCallBack)
            
    def analysisFileCallBack(self, params):
        print(params)
    
    def selectUploadFile(self):
        try:
            fileName1, filetype = QFileDialog.getOpenFileName(self.MainWindow, "选取文件", os.path.realpath("/"), "Log Files (*.log)")    #设置文件扩展名过滤,注意用双分号间隔  
            print(fileName1, filetype)  
            file = open(fileName1)
            lines = file.readlines()
#             self.analysisFile(lines)
            Thread(target=self.analysisFile, args=(lines,)).start()
        except Exception as e:
            print(e)
            
    def selectUploadFiles(self):
        try:
            files, ok1 = QFileDialog.getOpenFileNames(self.MainWindow, "多文件选择", os.path.realpath("/"), "All Files (*);;Text Files (*.log);;Text Files (*.txt)")  
            print(files, ok1)  
        except Exception as e:
            print(e)
            
    def selectUploadDir(self):
        try:
            directory1 = QFileDialog.getExistingDirectory(self.MainWindow, "选取文件夹", os.path.realpath("/")) #起始路径  
            print(directory1)  
        except Exception as e:
            print(e)
    
    def selectFileDownload(self):
        try:
            fileName2, ok2 = QFileDialog.getSaveFileName(self.MainWindow, "文件保存", os.path.realpath("/"), "All Files (*);;Text Files (*.log);;Text Files (*.txt)")
            print(fileName2, ok2)
        except Exception as e:
            print(e)
Esempio n. 26
0
class qboproxMainWindow(QtGui.QMainWindow):
    '''
    Subclass of QMainWindow, main window of qboprox application
    '''
    def loadSettings(self):
        self.sett = QtCore.QSettings('boprox','qboprox')
        
    def displayAbout(self):
        DialogAbout = QtGui.QDialog(self)
        ui = Ui_About()
        ui.setupUi(DialogAbout)
        DialogAbout.show()
    
    def displayRepoList(self):
        DialogRepoList = QtGui.QDialog(self)
        ui = Ui_repoListDialog()
        ui.setupUi(DialogRepoList)
        
        def updateList():
            # first delete all rows
            for i in reversed(xrange(0, ui.repoList.rowCount())):
                ui.repoList.removeRow(i)
            self.sett.beginGroup('repositories')
            for repo in self.sett.childGroups():
                self.sett.beginGroup(repo)
                ui.repoList.insertRow(0)
                ui.repoList.setItem(0,0, 
                    QtGui.QTableWidgetItem(repo) )
                localpath = self.sett.value('localpath').toPyObject()
                if localpath: 
                    ui.repoList.setItem(0,1, 
                        QtGui.QTableWidgetItem(localpath) )
                host = self.sett.value('host').toPyObject()
                ui.repoList.setItem(0,2, 
                    QtGui.QTableWidgetItem(host) )
                if self.sett.value('enabled').toPyObject():
                    val = QtGui.QTableWidgetItem('yes')
                else:
                    val = QtGui.QTableWidgetItem('no')
                ui.repoList.setItem(0,3, val)
                self.sett.endGroup()
            self.sett.endGroup()
            ui.repoList.setCurrentCell(0, 0)
        
        def displayRepoConfigAdd ():
            DialogRepoConfig.addRepo()
            updateList()
            
        def displayRepoConfigEdit ():
            # set all the information
            # TODO
            DialogRepoConfig.editRepo(str(ui.repoList.item(
                ui.repoList.currentRow(), 0 ).data(0).toPyObject() ))
            updateList()
        
        def delRepo():
            name = ui.repoList.item(
                ui.repoList.currentRow(),0 ).data(0).toPyObject()
            if name: 
                self.sett.beginGroup('repositories')
                self.sett.remove(name)
                self.sett.endGroup()
            updateList()
            
        # prepare this, just in case
        DialogRepoConfig = QRepoConfig(DialogRepoList)        
        ui.addButton.clicked.connect(displayRepoConfigAdd)
        ui.editButton.clicked.connect(displayRepoConfigEdit)
        ui.delButton.clicked.connect(delRepo)
        updateList()
        DialogRepoList.exec_()
        self.updateRepos()
        
    def triggerRefresh(self):
        pass
    
    def triggerQuit(self):
        QtCore.QCoreApplication.exit()
        
    def toggleVisible(self, reason):
        if reason == QtGui.QSystemTrayIcon.Trigger:
            if self.isVisible():
                self.hide()
            else:
                self.show()
    
    def changedRepo (self, newRepo):
        name = str(newRepo)
        for i in xrange( self.mainUi.repoComboBox.count() ):
            s = str(self.mainUi.repoComboBox.itemText(i))
            if s != name:
                self._reposWatchers[s].treeViewLock()
        self._reposWatchers[name].treeViewUpdate()
    
    def closeEvent(self, event):
        self.setVisible(False)
        event.ignore()
        
    def connectMySlots(self):
        self.mainUi.actionRefresh.activated.connect(self.triggerRefresh)
        self.mainUi.actionRepositoryList.activated.connect(self.displayRepoList)
        self.mainUi.trayRefresh.activated.connect(self.triggerRefresh)
        self.mainUi.trayShow.activated.connect(self.show)
        self.mainUi.actionAbout.activated.connect(self.displayAbout)
        self.mainUi.actionQuit.activated.connect(self.triggerQuit)
        self.mainUi.trayQuit.activated.connect(self.triggerQuit)
        self.mainUi.trayIcon.activated.connect(self.toggleVisible)
        self.mainUi.repoComboBox.currentIndexChanged[QtCore.QString].connect(
            self.changedRepo)
        
    def createTray(self):
        # "De-attach" de MenuTray menu
        self.mainUi.menubar.removeAction(
            self.mainUi.menuTrayIcon.menuAction()) 
        if not QtGui.QSystemTrayIcon.isSystemTrayAvailable:
            # We don't have a tray icon
            self.mainUi.actionClose.setDisabled(True)
        else:
            self.mainUi.trayIcon = QtGui.QSystemTrayIcon(self);
            ic = QtGui.QIcon(":/icons/tray.svg")
            self.mainUi.trayIcon.setContextMenu(self.mainUi.menuTrayIcon);
            self.mainUi.trayIcon.setIcon(ic)
            self.mainUi.trayIcon.setToolTip('qboprox')
            self.mainUi.trayIcon.show()
    
    def updateRepos(self):
        self.sett.beginGroup('repositories')
        for qi in self.sett.childGroups():
            i = str(qi)
            if i not in self._reposWatchers:
                newrepo = QRepoManager(i, self.mainUi.fileTree)
                self._reposWatchers[i] = newrepo
                self.mainUi.repoComboBox.addItem(qi)
        self.sett.endGroup()

    def __init__(self, *args):
        apply(QtGui.QMainWindow.__init__, (self,) + args)
        self.mainUi = Ui_MainWindow()
        self.mainUi.setupUi(self)
        self.loadSettings()
        self.createTray()
        self.connectMySlots()
        self._reposWatchers = dict() 
        self.updateRepos()
        self.show()
Esempio n. 27
0
import sys
from PyQt5 import QtWidgets

from main import Ui_MainWindow

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    start_window = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()

    ui.setupUi(start_window)
    start_window.show()
    sys.exit(app.exec_())
Esempio n. 28
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.load_program()

        #self.ui.keyid.setText(KEY_ID)

        #self.ui.identicon.setPixmap(KEY_IDENTICON_24)

        self.colection_tree_update()
        self.friend_list_update()

        ##FRIEND_MENU
        ##ACTIONS
        #self.ui.actionFriendShare = QtGui.QAction(self)
        #self.ui.actionFriendShare.setIcon(QtGui.QIcon.fromTheme('document-share'))
        #self.ui.actionFriendShare.setObjectName('actionFriendShare')
        #self.ui.actionFriendShare.setText(QtGui.QApplication.translate('MainWindow', 'Share', None, QtGui.QApplication.UnicodeUTF8))

        #self.ui.actionFriendAdd = QtGui.QAction(self)
        #self.ui.actionFriendAdd.setIcon(QtGui.QIcon.fromTheme('list-add-user'))
        #self.ui.actionFriendAdd.setObjectName('actionFriendAdd')
        #self.ui.actionFriendAdd.setText(QtGui.QApplication.translate('MainWindow', 'Add', None, QtGui.QApplication.UnicodeUTF8))

        #self.ui.actionFriendRemove = QtGui.QAction(self)
        #self.ui.actionFriendRemove.setIcon(QtGui.QIcon.fromTheme('list-remove-user'))
        #self.ui.actionFriendRemove.setObjectName('actionFriendRemove')
        #self.ui.actionFriendRemove.setText(QtGui.QApplication.translate('MainWindow', 'Remove', None, QtGui.QApplication.UnicodeUTF8))

        ##ACTIONS
        #self.ui.friendMenu = QtGui.QMenu(self.ui.friendsList)
        #self.ui.friendMenu.setObjectName(_fromUtf8('friendMenu'))

        #self.ui.friendMenu.addAction(self.ui.actionFriendShare)
        #self.ui.friendMenu.addSeparator()
        #self.ui.friendMenu.addAction(self.ui.actionFriendAdd)
        #self.ui.friendMenu.addAction(self.ui.actionFriendRemove)

        #self.connect(self.ui.colectionTree,
        #QtCore.SIGNAL('itemClicked()'),
        #self.show_item
        #)

        #self.ui.model = QStandardItemModel()

        #self.ui.colectionTree..setModel(self.model)

        #self.treeView.setModel(self.model)
        #self.model.appendRow(QStandardItem('<bHello</b'))
        #self.model.appendRow(QStandardItem('World'))

        self.ui.colection.addItems(FILES.keys())
        self.update_file(self.ui.colection.currentText())

        self.ui.action_file_read.setIcon(
            QtGui.QIcon.fromTheme('document-open'))
        self.ui.action_file_import.setIcon(
            QtGui.QIcon.fromTheme('document-import'))
        self.ui.action_file_export.setIcon(
            QtGui.QIcon.fromTheme('document-export'))

        self.ui.action_colection_newcolection.setIcon(
            QtGui.QIcon.fromTheme('list-add'))
        self.ui.action_collection_removecollection.setIcon(
            QtGui.QIcon.fromTheme('list-remove'))

        self.ui.action_friends_add.setIcon(
            QtGui.QIcon.fromTheme('list-add-user'))

        self.ui.action_view_panels_colections.setIcon(
            QtGui.QIcon.fromTheme('folder'))
        self.ui.action_view_panels_friends.setIcon(
            QtGui.QIcon.fromTheme('user-identity'))

        self.ui.action_contextualfriend_add.setIcon(
            QtGui.QIcon.fromTheme('list-add-user'))
        self.ui.action_contextualfriend_remove.setIcon(
            QtGui.QIcon.fromTheme('list-remove-user'))
        self.ui.action_contextualfriend_share_external.setIcon(
            QtGui.QIcon.fromTheme('document-import'))
        self.ui.action_contextualfriend_show.setIcon(
            QtGui.QIcon.fromTheme('view-form'))
        self.ui.action_contextualfriend_setalias.setIcon(
            QtGui.QIcon.fromTheme('user-properties'))

        self.ui.alias_button.setIcon(QtGui.QIcon.fromTheme('document-save'))
        #self.ui..setIcon(QtGui.QIcon.fromTheme(''))
        #self.ui..setIcon(QtGui.QIcon.fromTheme(''))
        #self.ui..setIcon(QtGui.QIcon.fromTheme(''))
        #self.ui..setIcon(QtGui.QIcon.fromTheme(''))
        #self.ui..setIcon(QtGui.QIcon.fromTheme(''))
        #self.ui..setIcon(QtGui.QIcon.fromTheme(''))
        #self.ui..setIcon(QtGui.QIcon.fromTheme(''))

        self.show_friend_from_item(self.ui.friendsList.item(0), None)

        self.connect(
            self.ui.colectionTree,
            QtCore.SIGNAL('customContextMenuRequested(const QPoint &)'),
            self.showColectionTreeMenu)

        self.connect(
            self.ui.friendsList,
            QtCore.SIGNAL('customContextMenuRequested(const QPoint &)'),
            self.show_friends_list_menu)

        self.connect(
            self.ui.colectionTree,
            QtCore.SIGNAL(
                'currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)'),
            self.show_item)

        self.connect(
            self.ui.friendsList,
            QtCore.SIGNAL(
                'currentItemChanged(QListWidgetItem *,QListWidgetItem *)'),
            self.show_friend_from_item)

        self.connect(self.ui.alias_button, QtCore.SIGNAL('clicked()'),
                     self.set_alias)

        self.connect(self.ui.author_identicon, QtCore.SIGNAL('clicked()'),
                     self.show_friend_from_id)

        #self.connect(self.ui.friendsList,
        #QtCore.SIGNAL('itemDoubleClicked(QListWidgetItem*,int)'),
        #self.show_friend_from_item)

        self.connect(self.ui.action_file_read, QtCore.SIGNAL('triggered()'),
                     self.read_file)
        self.connect(self.ui.action_file_import, QtCore.SIGNAL('triggered()'),
                     self.import_file)
        self.connect(self.ui.action_file_export, QtCore.SIGNAL('triggered()'),
                     self.export_file)
        self.connect(self.ui.actionLock_panels, QtCore.SIGNAL('toggled(bool)'),
                     self.lock_dock)

        self.connect(self.ui.action_contextualfriend_share_external,
                     QtCore.SIGNAL('triggered()'), self.friend_share)
        self.connect(self.ui.action_contextualfriend_add,
                     QtCore.SIGNAL('triggered()'), self.friend_add)
        self.connect(self.ui.action_contextualfriend_remove,
                     QtCore.SIGNAL('triggered()'), self.friend_remove)
        self.connect(self.ui.action_contextualfriend_show,
                     QtCore.SIGNAL('triggered()'), self.show_friend_from_none)

        self.connect(self.ui.colection,
                     QtCore.SIGNAL('currentIndexChanged(QString)'),
                     self.update_file)

        self.show()

    def update_file(self, colection):
        self.ui.file.clear()
        self.ui.file.addItems(FILES[str(colection)])

    def friend_share(self):
        item = self.ui.friendsList.currentItem()
        print('share with ' + item.text())

    def friend_add(self):
        item = self.ui.friendsList.currentItem()
        print('share with ' + item.text())

    def friend_remove(self):
        item = self.ui.friendsList.currentItem()
        print(os.path.join(FRIENDS_PATH, str(item.text())))
        os.remove(os.path.join(FRIENDS_PATH, str(item.text())))
        load_global_friends()
        self.friend_list_update()

    def colection_tree_update(self):
        self.ui.colectionTree.clear()
        for colection in FILES.keys():
            colection_item = QtGui.QTreeWidgetItem()
            colection_item.setText(0, colection)
            colection_item.setIcon(0, QtGui.QIcon.fromTheme('folder'))
            for file in FILES[colection]:
                file_item = QtGui.QTreeWidgetItem()
                file_item.setText(0, file)
                file_item.setIcon(
                    0,
                    QtGui.QIcon(os.path.join(COLECTION_PATH, colection, file)))
                colection_item.addChild(file_item)

            self.ui.colectionTree.addTopLevelItem(colection_item)

    def friend_list_update(self):
        #self.ui.friendsList.clear()
        self.ui.friendsList.clear()
        for friend in FRIENDS:
            friend_item = QtGui.QListWidgetItem()
            friend_item.setText(get_friend_displayname(friend))
            friend_item.setIcon(QtGui.QIcon(get_identicon_24_pixmap(friend)))
            friend_item.setStatusTip(str(friend))

            self.ui.friendsList.addItem(friend_item)

    def show_friends_list_menu(self, pos):
        self.ui.friend_menu.popup(QtGui.QCursor(pos).pos())

    def show_friend_from_item(self, current_item, previous_item):
        if current_item:
            self.user_id = str(current_item.statusTip())
            self.user_alias = FRIENDS[self.user_id][0]
            self.show_friend()

    def show_friend_from_none(self):
        self.user_id = str(self.ui.friendsList.currentItem().statusTip())
        self.user_alias = FRIENDS[self.user_id][0]
        self.show_friend()

    def show_friend_from_id(self):
        self.user_id = str(self.ui.author.text())
        try:
            self.user_alias = FRIENDS[self.user_id]
            self.show_friend()
        except KeyError:
            print(self.user_id + ' is not in your friends')

    def show_friend(self):
        self.ui.friend_name.setText(get_friend_displayname(self.user_id))
        self.ui.user_id.setText(self.user_id)
        self.ui.alias.setText(self.user_alias)
        self.ui.identicon.setPixmap(get_identicon_pixmap(self.user_id))
        self.ui.main_stacked.setCurrentIndex(1)

    def set_alias(self):
        print('Launched set_alias')
        friend_file_name = self.user_id + self.user_alias
        new_friend_file_name = self.user_id + str(self.ui.alias.text())
        print((os.path.join(FRIENDS_PATH, friend_file_name),
               os.path.join(FRIENDS_PATH, new_friend_file_name)))
        os.rename(os.path.join(FRIENDS_PATH, friend_file_name),
                  os.path.join(FRIENDS_PATH, new_friend_file_name))

        update_global_friend_alias(self.user_id, str(self.ui.alias.text()))

        self.user_alias = str(self.ui.alias.text())
        if self.user_alias == '':
            self.user_alias = self.user_id

        self.ui.friendsList.currentItem().setText(self.user_alias)

    def showColectionTreeMenu(self, pos):

        index = self.ui.colectionTree.indexAt(pos)

        if index.parent().isValid():
            self.ui.file_menu.popup(QtGui.QCursor(pos).pos())
        else:
            self.ui.colection_menu.popup(QtGui.QCursor(pos).pos())

    def show_item(self, current_item, previous_item):
        parent = current_item.parent()
        if parent:
            self.ui.main_stacked.setCurrentIndex(0)
            self.ui.colection.setCurrentIndex(FILES.keys().index(
                parent.text(0)))
            self.ui.file.setCurrentIndex(FILES[str(parent.text(0))].index(
                current_item.text(0)))

            file_handler = open(
                os.path.join(COLECTION_PATH, str(parent.text(0)),
                             str(current_item.text(0))))
            file_header = extract_file_header(file_handler)
            self.ui.keylength.setValue(file_header['aes_key_length'])
            self.ui.author.setText(file_header['author'])
            self.ui.author_identicon.setIcon(
                QtGui.QIcon(get_identicon_24_pixmap(file_header['author'])))

            if file_header['input_date']:
                self.ui.systemimputdate.setDateTime(
                    QtCore.QDateTime(1970, 1, 1, 1,
                                     0).addSecs(file_header['input_date']))
                #self.ui.systemimputdate.setDisplayFormat('d MMM yyyy HH:mm:ss')
            else:
                self.ui.systemimputdate.clear()
                self.ui.systemimputdate.setEnabled(False)
                #self.ui.systemimputdate.setDisplayFormat('z')

            if file_header['share_date']:
                #self.ui.sharedate.setDisplayFormat('d MMM yyyy HH:mm:ss::')
                self.ui.sharedate.setDateTime(
                    QtCore.QDateTime(1970, 1, 1, 1,
                                     0).addSecs(file_header['share_date']))
            else:
                self.ui.sharedate.clear()
                self.ui.sharedate.setEnabled(False)
                #self.ui.sharedate.setDisplayFormat('z')

            if file_header['import_date']:
                #self.ui.importdate.setDisplayFormat('d MMM yyyy HH:mm:ss')
                self.ui.importdate.setDateTime(
                    QtCore.QDateTime(1970, 1, 1, 1,
                                     0).addSecs(file_header['import_date']))
            else:
                self.ui.importdate.clear()
                self.ui.importdate.setEnabled(False)

    def lock_dock(self, locked):
        if locked:
            self.ui.colectionsDock.setFeatures(
                QtGui.QDockWidget.DockWidgetFeatures(0))
            self.ui.friendsDock.setFeatures(
                QtGui.QDockWidget.DockWidgetFeatures(0))
        else:
            self.ui.colectionsDock.setFeatures(
                QtGui.QDockWidget.DockWidgetFeatures(7))
            self.ui.friendsDock.setFeatures(
                QtGui.QDockWidget.DockWidgetFeatures(7))

    def read_file(self):
        input_file = open(self.choose_file('Open file', ''), 'r')

    def import_file(self):
        import_dialog = ImportDialog(self)
        import_dialog.exec_()
        load_global_files()
        self.colection_tree_update()

    def export_file(self):
        export_dialog = ExportDialog(self)
        export_dialog.show()

    def choose_colection(self, dialogTitle, inputText):
        dialog = QtGui.QInputDialog
        colection, ok = dialog.getItem(self, dialogTitle, inputText,
                                       FILES.keys(), 0, False)

        if ok:
            return os.path.join(COLECTION_PATH, str(colection))

    def choose_colection_file(self, dialogTitleC, inputTextC, dialogTitleF,
                              inputTextF):
        colection = self.choose_colection(dialogTitleC, inputTextC)

        if colection:
            files = []
            for file in os.listdir(os.path.join(colection)):
                if not os.path.isdir(os.path.join(colection, file)):
                    files.append(file)

        dialog = QtGui.QInputDialog
        file, ok = dialog.getItem(self, dialogTitleF, inputTextF, files, 0,
                                  False)

        if ok:
            return os.path.join(colection, str(file))

    #def load_rsakey(self):
    #while not os.path.exists(RSAKEY_PATH):
    #new_rsa_dialog = NewRsaDialog(self)
    #new_rsa_dialog.exec_()

    #key_file = open(RSAKEY_PATH, 'r')

    #rsakey = RSA.importKey(key_file.read())

    #key_id = get_rsakey_id(rsakey)

    #key_identicon = get_identicon_pixmap(key_id)

    #key_identicon_24 = key_identicon.scaled(24, 24, 1, 1)

    #load_global_rsakey_data(rsakey, key_id, key_identicon, key_identicon_24)

    #def load_rsakey(self):
    ##self.get_rsakey()
    #self.get_rsakey()

    def load_program(self):
        pixmap = QtGui.QPixmap(IMAGES_PATH + '/flashscreen.png')

        splash = QtGui.QSplashScreen(pixmap)
        progressBar = QtGui.QProgressBar(splash)
        progressBar.setGeometry(splash.width() / 10, 8 * splash.height() / 10,
                                8 * splash.width() / 10,
                                splash.height() / 10)
        splash.show()

        progressBar.setValue(0)

        progressBar.setFormat('Loading global files')
        print('Loading global files')
        load_global_files()
        progressBar.setValue(20)

        progressBar.setFormat('Loading global friends')
        print('Loading global friends')
        load_global_friends()
        progressBar.setValue(40)

        progressBar.setFormat('Getting RSA key')
        print('Getting RSA key')
        load_rsakey(self)
        progressBar.setValue(60)

        progressBar.setFormat('Loading GUI (Colection tree)')
        self.colection_tree_update()
        progressBar.setValue(80)

        progressBar.setFormat('Loading GUI (Friends list)')
        self.friend_list_update()
        progressBar.setValue(100)
Esempio n. 29
0
class MainWindow_Exec():
    def __init__(self):
        app = QtWidgets.QApplication(sys.argv)
        self.Main = QtWidgets.QMainWindow()
        self.MainUI = MainScreen()
        self.MainUI.setupUi(self.Main)
        # SECTION Configuration
        # ? IP Validator
        # Part of the regular expression
        ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"
        # Regulare expression
        ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange +
                          "\\." + ipRange + "$")
        ipValidator = QRegExpValidator(ipRegex, self.MainUI.lineEdit)
        self.MainUI.lineEdit.setValidator(ipValidator)
        # ? Port Validator
        rx = QRegExp('^[1-9]\d{3}$')
        validator = QRegExpValidator(rx)
        self.MainUI.lineEditPort.setValidator(validator)
        # ? Button Def Config
        self.MainUI.pushButton.setStyleSheet(
            """QPushButton{background-color: #00aaff;color: rgb(255, 255, 255); border-radius: 2px; font: 12pt \"B Nazanin\"; padding: 5px;}\n
                 QPushButton:hover{background-color: #9ee35d; border: 1px solid rgb(255, 85, 127);}\n
                 QPushButton:pressed{outline: none;}\n
                 QPushButton:focus{outline: none;}""")
        self.MainUI.clearLog.setStyleSheet(
            """QPushButton{background-color: #FF5733;color: rgb(255, 255, 255); border-radius: 2px; font: 12pt \"Arial\"; padding: 5px;}\n
                 QPushButton:hover{background-color: #CE4212; border: 1px solid rgb(255, 255, 255);}\n
                 QPushButton:pressed{outline: none;}\n
                 QPushButton:focus{outline: none;}""")
        global Connection_Close, Fan_Off, Lamp_Off
        self.MainUI.connection.setScaledContents(True)
        self.MainUI.connection.setPixmap(QPixmap(Connection_Close))
        self.MainUI.lamp.setScaledContents(True)
        self.MainUI.lamp.setPixmap(QPixmap(Lamp_Off))
        self.MainUI.fan.setScaledContents(True)
        self.MainUI.fan.setPixmap(QPixmap(Fan_Off))
        # SECTION Set Connections
        self.MainUI.pushButton.clicked.connect(self.ButtonClicked)
        self.MainUI.clearLog.clicked.connect(
            lambda: self.MainUI.textBrowser.clear())
        # SECTION Show the Screen
        self.Main.show()
        sys.exit(app.exec_())

    def ButtonClicked(self):
        global Connected, Connectino_Open, Connection_Close, Voice, TCP_IP, TCP_PORT
        if Connected == 0:
            TCP_IP = self.MainUI.lineEdit.text()
            print(type(self.MainUI.lineEdit.text()),
                  self.MainUI.lineEdit.text())
            TCP_PORT = int(self.MainUI.lineEditPort.text())
            print(type(self.MainUI.lineEditPort.text()),
                  self.MainUI.lineEditPort.text())
            self.MainUI.pushButton.setText('قطع اتصال')
            self.MainUI.pushButton.setStyleSheet(
                """QPushButton{background-color: #00aaff;color: rgb(255, 255, 255); border-radius: 2px; font: 12pt \"B Nazanin\"; padding: 5px;}\n
                 QPushButton:hover{background-color: #C70039; border: 1px solid #DAF7A6;}\n
                 QPushButton:pressed{outline: none;}\n
                 QPushButton:focus{outline: none;}""")
            # ? Start Voice Thread
            self.VoiceDetectionThread_Start()
            # ? Start Connection Thread
            self.ConnectionThread_Start()
            # ? Set Icons & gif
            movie = QMovie(Voice)
            self.MainUI.voice.setMovie(movie)
            self.MainUI.voice.setScaledContents(True)
            movie.setCacheMode(QMovie.CacheAll)
            movie.start()
            movie.loopCount()
            self.setConsumer(Fan_Off, Lamp_Off)
            Connected = 1
        else:
            self.MainUI.pushButton.setText('اتصال')
            self.MainUI.pushButton.setStyleSheet(
                """QPushButton{background-color: #00aaff;color: rgb(255, 255, 255); border-radius: 2px; font: 12pt \"B Nazanin\"; padding: 5px;}\n
                 QPushButton:hover{background-color: #9ee35d; border: 1px solid rgb(255, 85, 127);}\n
                 QPushButton:pressed{outline: none;}\n
                 QPushButton:focus{outline: none;}""")
            # ? Start Voice Thread
            self.mVoiceDetectionThread.stop()
            # ? Start Connection Thread
            self.mConnectionThread.stop()
            # ? Set Icons & gif
            self.MainUI.voice.setScaledContents(True)
            self.MainUI.voice.setPixmap(QPixmap())
            self.setConsumer(Fan_Off, Lamp_Off)
            Connected = 0

    def txtAdd(self, text):
        self.MainUI.textBrowser.append(
            '<p align="right" style="margin-right:5px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; color:#ffffff;">$ '
            + text + '</span></p>')

    def txtFailerAdd(self, text):
        self.MainUI.textBrowser.append(
            '<p align="right" style="margin-right:5px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; color:#DE401D;">$ '
            + text + '</span></p>')

    def txtSuccessAdd(self, text):
        self.MainUI.textBrowser.append(
            '<p align="right" style="margin-right:5px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:12pt; color:#12CE42 ;">$ '
            + text + '</span></p>')

    def setConsumer(self, fan, lamp):
        self.MainUI.lamp.setPixmap(QPixmap(lamp))
        self.MainUI.fan.setPixmap(QPixmap(fan))

    def VoiceDetectionThread_Start(self):
        self.mVoiceDetectionThread = VoiceDetectionThread(parent=None)
        self.mVoiceDetectionThread.start()
        self.mVoiceDetectionThread.voiceData.connect(
            self.VoiceThreadDataInitilizer)  # REVIEW Recieve the signal

    def ConnectionThread_Start(self):
        self.mConnectionThread = ConnectionThread(parent=None)
        self.mConnectionThread.start()
        self.mConnectionThread.connectionData.connect(
            self.ConnectionThreadDataInitilizer)  # REVIEW Recieve the signal

    def VoiceThreadDataInitilizer(self, data):
        global Lamp_VoiceCommands, Lamp_On_VoiceCommands, Lamp_Off_VoiceCommands, Fan_VoiceCommands, Fan_On_VoiceCommands, Fan_VoiceCommands, SendList
        if data == 'VER':
            self.txtFailerAdd("نمی تونم تشخیص بدم چی گفتید")
        elif data == 'GER':
            self.txtFailerAdd('در تشخیص صدای شما مشکلی به وجود آمده است')
        else:
            self.txtAdd('فکر می کنم گفتید:' + data)
            # SECTION Command Detection
            if any(x in data for x in Lamp_VoiceCommands) and any(
                    x in data for x in Lamp_On_VoiceCommands):
                self.txtSuccessAdd('درخواست شما ارسال شد')
                SendList.append('VCLOVC')
            elif any(x in data for x in Lamp_VoiceCommands) and any(
                    x in data for x in Lamp_Off_VoiceCommands):
                self.txtSuccessAdd('درخواست شما ارسال شد')
                SendList.append('VCLFVC')
            if any(x in data for x in Fan_VoiceCommands) and any(
                    x in data for x in Fan_On_VoiceCommands):
                self.txtSuccessAdd('درخواست شما ارسال شد')
                SendList.append('VCFOVC')
            elif any(x in data for x in Fan_VoiceCommands) and any(
                    x in data for x in Fan_Off_VoiceCommands):
                self.txtSuccessAdd('درخواست شما ارسال شد')
                SendList.append('VCFFVC')

    def ConnectionThreadDataInitilizer(self, data):
        if data == 'connecting':
            self.txtAdd('در حال اتصال به سرور ...')
        elif data == 'connected':
            self.MainUI.connection.setScaledContents(True)
            self.MainUI.connection.setPixmap(QPixmap(Connectino_Open))
            self.txtSuccessAdd('ارتباط برقرار شد')
        elif data == 'disconnected':
            self.MainUI.connection.setScaledContents(True)
            self.MainUI.connection.setPixmap(QPixmap(Connection_Close))
            self.txtFailerAdd('ارتباط قطع شد')
        elif data == 'responceok':
            self.txtSuccessAdd('درخواست شما با موفقیت انجام شد')
        elif data == 'responcefl':
            self.txtFailerAdd('درخواست شما با خطا مواجه شد')
        # TODO State
        elif 'state' in data:
            res = data.find('state')
            if res != -1:
                state = data[res:]
                _lamp = ''
                _fan = ''
                if state[5] == 'O':
                    _lamp = Lamp_On
                # elif state[5] == 'F':
                else:
                    _lamp = Lamp_Off
                if state[6] == 'O':
                    _fan = Fan_On
                # elif state[6] == 'F':
                else:
                    _fan = Fan_Off
                self.setConsumer(_fan, _lamp)
Esempio n. 30
0
class LabelView(QtGui.QMainWindow):
    def __init__(self, fileName, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        QtCore.QObject.connect(self.ui.sentenceList, QtCore.SIGNAL("clicked(QModelIndex)"), self.updateSentence)
        QtCore.QObject.connect(self.ui.browseResultPath, QtCore.SIGNAL("clicked()"), partial(self.setFilePath, 'RESULT'))
        QtCore.QObject.connect(self.ui.browseTrainingSetPath, QtCore.SIGNAL("clicked()"), partial(self.setFilePath, 'TRAIN'))
        QtCore.QObject.connect(self.ui.browseCorrectSetPath, QtCore.SIGNAL("clicked()"), partial(self.setFilePath, 'CORRECT'))
        QtCore.QObject.connect(self.ui.browseWrongSetPath, QtCore.SIGNAL("clicked()"), partial(self.setFilePath, 'WRONG'))
        QtCore.QObject.connect(self.ui.startButton, QtCore.SIGNAL("clicked()"), self.loadFiles)
        QtCore.QObject.connect(self.ui.saveButton, QtCore.SIGNAL("clicked()"), self.saveFiles)

        QtCore.QObject.connect(self.ui.goodButton, QtCore.SIGNAL("clicked()"), partial(self.resolveSentence, 'GOOD'))
        QtCore.QObject.connect(self.ui.correctButton, QtCore.SIGNAL("clicked()"), partial(self.resolveSentence, 'CORRECT'))
        QtCore.QObject.connect(self.ui.badButton, QtCore.SIGNAL("clicked()"), partial(self.resolveSentence, 'BAD'))


    def setFilePath(self, type):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        filePath = dialog.getOpenFileName()
        if type == 'RESULT':
            self.ui.testResultPath.setText(filePath)
            if len(self.ui.trainingSetPath.text()) == 0:
                self.ui.trainingSetPath.setText(filePath + '_train')
            if len(self.ui.correctSetPath.text()) == 0:
                self.ui.correctSetPath.setText(filePath + '_correct')
            if len(self.ui.wrongSetPath.text()) == 0:
                self.ui.wrongSetPath.setText(filePath + '_wrong')
        elif type == 'TRAIN':
            self.ui.trainingSetPath.setText(filePath)
        elif type == 'CORRECT':
            self.ui.correctSetPath.setText(filePath)
        elif type == 'WRONG':
            self.ui.wrongSetPath.setText(filePath)

    def loadFiles(self):
        testResultPath = self.ui.testResultPath.text()
        correctSetPath = self.ui.correctSetPath.text()
        wrongSetPath = self.ui.wrongSetPath.text()

        #Start only if all 3 are specified
        if testResultPath and correctSetPath and wrongSetPath:
            #load results set
            entries = loadData(testResultPath)
            self.packedSentences = splitSentences(entries)

            #load correct set
            correctEntries = loadData(correctSetPath)
            self.packedCorrectSentences = splitSentences(correctEntries)

            #load wrong set
            wrongEntries = loadData(wrongSetPath)
            self.packedWrongSentences = splitSentences(wrongEntries)

            self.overrideFromPackedSentences(self.packedSentences, self.packedCorrectSentences)
            self.updateSentences()
            self.smartUpdateSentence()

            return

    def saveFiles(self):
        testResultPath = self.ui.testResultPath.text()
        trainSetPath = self.ui.trainingSetPath.text()
        correctSetPath = self.ui.correctSetPath.text()
        wrongSetPath = self.ui.wrongSetPath.text()

        #Start only if all 3 are specified
        if testResultPath and trainSetPath and correctSetPath and wrongSetPath:
            saveData(testResultPath, concatenateSentences(self.packedSentences))
            saveTrainingData(trainSetPath, concatenateSentences(self.packedSentences))

            saveData(correctSetPath, concatenateSentences(self.packedCorrectSentences))
            saveData(wrongSetPath, concatenateSentences(self.packedWrongSentences))
            pass

    def containsPackedSentence(self, packedSentences, packedSentence):
        for sentence in packedSentences:
            if sentence.rawSentence() == packedSentence.rawSentence():
                return True
        return False

    def overrideFromPackedSentence(self, slaveSet, masterSentence):
        for slaveSentence in slaveSet:
            if masterSentence.rawSentence() == slaveSentence.rawSentence():
                masterSentence.override(slaveSentence)

    def overrideFromPackedSentences(self, slaveSet, masterSet):
            for masterSentence in masterSet:
                self.overrideFromPackedSentence(slaveSet, masterSentence)

    #Update sentence sets regarding the action taken
    #Update sentence set view
    def resolveSentence(self, action):
        if action == 'GOOD':
            self.sentenceInCorrection.unify('LEFT')

            self.updateSentence(self.sentenceInCorrectionIndex)

        elif action == 'CORRECT':
            self.sentenceInCorrection.unify('RIGHT')
            if not self.containsPackedSentence(self.packedCorrectSentences, self.sentenceInCorrection):
                self.packedCorrectSentences.append(self.sentenceInCorrection)
            else:
                self.overrideFromPackedSentence(self.packedCorrectSentences, self.sentenceInCorrection)

            self.updateSentence(self.sentenceInCorrectionIndex)

        elif action == 'BAD':
            if not self.containsPackedSentence(self.packedWrongSentences, self.sentenceInCorrection):
                self.packedWrongSentences.append(self.sentenceInCorrection)

        #print 'Correct: %d' % len(self.packedCorrectSentences)
        #print 'Wrong: %d'% len(self.packedWrongSentences)

        if action == 'GOOD' or action == 'CORRECT':
            #Update if already in set
            #Append otherwise
            if not self.containsPackedSentence(self.packedCorrectSentences, self.sentenceInCorrection):
                self.packedCorrectSentences.append(self.sentenceInCorrection)
            else:
                self.overrideFromPackedSentence(self.packedCorrectSentences, self.sentenceInCorrection)

            #Refresh sentenceList
            self.updateSentences()

        self.smartUpdateSentence(self.sentenceInCorrectionIndex.row() + 1)

    def smartUpdateSentence(self, startingRow = 0):
        for rowNum in range(startingRow, self.sentenceModel.rowCount()):
            #print rowNum
            #print self.sentenceModel.sentences[rowNum][sentenceModel.COLUMN_CONFLICT]
            if self.sentenceModel.sentences[rowNum][sentenceModel.COLUMN_CONFLICT]:
                index = self.sentenceModel.index(rowNum, 0)
                self.updateSentence(index)
                return

    def updateSentences(self):
        sentenceList = [(sentence.rawSentence(), sentence.hasConflict(), self.containsPackedSentence(self.packedCorrectSentences, sentence)) for sentence in self.packedSentences]
        self.sentenceModel = sentenceModel(sentenceList)
        self.ui.sentenceList.setModel(self.sentenceModel)

    #Update the correction view with a sentence
    def updateSentence(self, QModelIndex):
        self.sentenceInCorrectionIndex = QModelIndex
        self.sentenceInCorrection = self.packedSentences[QModelIndex.row()]
        sentenceModel = sentenceCorrectionModel(self.sentenceInCorrection.getTokens())
        self.ui.sentenceCorrectionView.setModel(sentenceModel)

        self.ui.sentenceList.scrollTo(QModelIndex)
        self.ui.sentenceIndex.setText(QString(str(QModelIndex.row())))
Esempio n. 31
0
class MainForm(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainForm, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.__ver = '0.5'

        self.exit = QtWidgets.QAction('Exit', self)
        self.exit.setShortcut('Ctrl+Q')
        self.exit.triggered.connect(QtWidgets.qApp.quit)

        self.configFile = GIDEConfig('config.ini')
        self.configuration = {}
        self.wasCalled = False
        self.fname = ''

        self.open = QtWidgets.QAction('Open', self)
        self.open.setShortcut('Ctrl+O')
        self.open.triggered.connect(self.__open)
        self.ui.menuFile.addAction(self.open)
        self.ui.menuFile.addAction(self.exit)
        self.run = QtWidgets.QAction('Run', self)
        self.run.setShortcut('Ctrl+R')
        self.run.triggered.connect(self.__run)
        self.ui.menuRun.addAction(self.run)
        self.__extractConfig()
        self.fileIsEdited = False
        self.fileName = ''
        print(self.configuration)
        self.about = QtWidgets.QAction('About Gide', self)
        self.about.triggered.connect(self.__about)
        self.ui.menuHelp.addAction(self.about)
        self.config = QtWidgets.QAction('Setup GIDE...', self)
        self.config.triggered.connect(self.__launchConfig)
        self.ui.menuAbout.addAction(self.config)
        self.setWindowTitle(f'GIDE version {self.__ver}')
        self.setWindowIcon(QtGui.QIcon(CWD + '/util/gide_res/gide.png'))

    def __bonk(self, msg):
        QtWidgets.QMessageBox.critical(self, 'Error!', msg)

    def __about(self):
        QtWidgets.QMessageBox.information(
            self, 'About GIDE',
            f'GIDE version {self.__ver}.\nGIDE - It just works!\nA IDE for writing Gervi scripts\nBy TheSwagVader. github.com/TheSwagVader'
        )

    def __open(self):
        fname = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Open file',
            self.configuration['INTERPRETER']['progsdir'])[0]
        if fname != '':
            with open(fname, 'r') as fin:
                fileData = fin.read()
                self.ui.textEdit.setText(fileData)
                self.fname = fname
                self.wasCalled = True

    def __extractConfig(self):
        self.configuration = self.configFile.extract()

    def __launchConfig(self):
        setupWin = ConfigDialog()
        res = setupWin.setupGide()
        if res:
            sections, parameters, values = res
            self.configFile.setOptions(sections, parameters, values)
            self.configFile.update()
            self.__extractConfig()

    def __run(self):
        self.fname = QtWidgets.QFileDialog.getSaveFileName(
            self, 'Save file',
            self.configuration['INTERPRETER']['progsdir'])[0]
        if self.fname != '':
            if self.fname == 'i_want_to_be_boss_of_this_gym' and self.ui.textEdit.toPlainText(
            ) == 'JABRONI':
                QtWidgets.QMessageBox.information(
                    self, 'You picked wrong door!',
                    ' Leatherclub two blocks down!')
            else:
                #prog = os.path.expanduser('%s/%s' % (self.configuration['INTERPRETER']['progsdir'], self.fname))
                try:
                    with open(self.fname, 'w+', encoding='utf8') as fout:
                        fout.write(self.ui.textEdit.toPlainText())
                except Exception as e:
                    self.__bonk(traceback.format_exc())
                    return
                if self.configuration['INTERPRETER']['vmpath'] != '':
                    try:
                        with open(self.configuration['INTERPRETER']['vmpath'],
                                  'rb') as vmf:
                            vm = pickle.load(vmf)
                            vm.runFile(self.fname)
                            self.ui.textBrowser_2.setText(vm.getOutputStream())
                            self.ui.textBrowser.setText(vm.getState())
                    except Exception as e:
                        self.__bonk(traceback.format_exc())
                        return
                else:
                    pass
Esempio n. 32
0
class MainWindow(QMainWindow):
    """docstring for Music App"""
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #Set up variables
        self.seventh_flag = False
        self.current_song = []
        self.current_playable = []
        self.abortFlag = False

        self.combo = self.ui.comboBox.currentText()
        self.ui.seventh_chord.setCheckable(True)

        self.ui.one_chord.clicked.connect(self.play_sound_one)
        self.ui.two_chord.clicked.connect(self.play_sound_two)
        self.ui.three_chord.clicked.connect(self.play_sound_three)
        self.ui.four_chrod.clicked.connect(self.play_sound_four)
        self.ui.five_chord.clicked.connect(self.play_sound_five)
        self.ui.six_chord.clicked.connect(self.play_sound_six)
        self.ui.seven_chord.clicked.connect(self.play_sound_seven)
        self.ui.viewChords.clicked.connect(self.open_table)
        self.ui.comboBox.currentTextChanged.connect(self.on_combobox_changed)
        self.ui.seventh_chord.toggled.connect(
            self.on_pushButtonSetBase_toggled)
        self.ui.recButton.clicked.connect(self.record)
        self.ui.playButton.clicked.connect(self.playback)
        self.ui.stopButton.clicked.connect(self.stop_music)
        self.ui.actionOpen.triggered.connect(self.file_open)
        self.ui.actionSave.triggered.connect(self.save_file)
        #initialize combo comboBox
        self.on_combobox_changed()

        self.key_dlg = QtWidgets.QDialog()
        self.table = Ui_Dialog()
        self.table.setupUi(self.key_dlg)
        self.table.btnClose.clicked.connect(self.key_dlg.close)

        self.model = None

    def open_table(self):
        """open database table"""
        self.sql_tableview_model()
        self.key_dlg.show()
        self.key_dlg.exec_()

    @QtCore.pyqtSlot(bool)
    def on_pushButtonSetBase_toggled(self, checked):
        if checked:
            self.seventh_flag = True
            print(self.seventh_flag)
            self.change_seven()
        else:
            self.seventh_flag = False
            self.change_chord()
            print(self.seventh_flag)

    def on_combobox_changed(self):
        """get sounds of current selected key"""
        current_selection = []
        self.combo = self.ui.comboBox.currentIndex()
        if self.seventh_flag == True:
            self.change_seven()
        else:
            self.change_chord()

#get sounds

    def change_chord(self):

        self.ui.label_1.setText(keys_name[self.combo][0])
        self.ui.label_2.setText(keys_name[self.combo][1])
        self.ui.label_3.setText(keys_name[self.combo][2])
        self.ui.label_4.setText(keys_name[self.combo][3])
        self.ui.label_5.setText(keys_name[self.combo][4])
        self.ui.label_6.setText(keys_name[self.combo][5])
        self.ui.label_7.setText(keys_name[self.combo][6])

    def change_seven(self):
        self.ui.label_1.setText(keys_seventh_name[self.combo][0])
        self.ui.label_2.setText(keys_seventh_name[self.combo][1])
        self.ui.label_3.setText(keys_seventh_name[self.combo][2])
        self.ui.label_4.setText(keys_seventh_name[self.combo][3])
        self.ui.label_5.setText(keys_seventh_name[self.combo][4])
        self.ui.label_6.setText(keys_seventh_name[self.combo][5])
        self.ui.label_7.setText(keys_seventh_name[self.combo][6])

#Play sounds

    def play_sound_one(self):
        self.current_song.append((time(), 0))
        if self.seventh_flag == False:
            play_chord = keys_chords[self.combo][0] + ".play()"
            exec(play_chord)
        else:
            play_chord = keys_chords_seventh[self.combo][0] + ".play()"
            exec(play_chord)

    def play_sound_two(self):
        self.current_song.append((time(), 1))
        if self.seventh_flag == False:
            play_chord = keys_chords[self.combo][1] + ".play()"
            exec(play_chord)
        else:
            play_chord = keys_chords_seventh[self.combo][1] + ".play()"
            exec(play_chord)

    def play_sound_three(self):
        self.current_song.append((time(), 2))
        if self.seventh_flag == False:
            play_chord = keys_chords[self.combo][2] + ".play()"
            exec(play_chord)
        else:
            play_chord = keys_chords_seventh[self.combo][2] + ".play()"
            exec(play_chord)

    def play_sound_four(self):
        self.current_song.append((time(), 3))
        if self.seventh_flag == False:
            play_chord = keys_chords[self.combo][3] + ".play()"
            exec(play_chord)
        else:
            play_chord = keys_chords_seventh[self.combo][3] + ".play()"
            exec(play_chord)

    def play_sound_five(self):
        self.current_song.append((time(), 4))
        if self.seventh_flag == False:
            play_chord = keys_chords[self.combo][4] + ".play()"
            exec(play_chord)
        else:
            play_chord = keys_chords_seventh[self.combo][4] + ".play()"
            exec(play_chord)

    def play_sound_six(self):
        self.current_song.append((time(), 5))
        if self.seventh_flag == False:
            play_chord = keys_chords[self.combo][5] + ".play()"
            exec(play_chord)
        else:
            play_chord = keys_chords_seventh[self.combo][5] + ".play()"
            exec(play_chord)

    def play_sound_seven(self):
        self.current_song.append((time(), 6))
        if self.seventh_flag == False:
            play_chord = keys_chords[self.combo][6] + ".play()"
            exec(play_chord)
        else:
            play_chord = keys_chords_seventh[self.combo][6] + ".play()"
            exec(play_chord)


#***** Recording Code ******#

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_R:
            self.record()
        elif e.key() == Qt.Key_P:
            self.playback()
        elif e.key() == Qt.Key_X:
            self.abortFlag = True
        elif e.key() == Qt.Key_O:
            self.file_open()
        elif e.key() == Qt.Key_1:
            self.save_file()
        e.accept()

    def stop_music(self):
        self.abortFlag = True

    def record(self):
        self.current_song = []
        self.current_playable = []
        self.abortFlag = False

    def convert_time(self):
        """convert time for recording"""
        prev = self.current_song[0][0]
        for event in self.current_song:
            self.current_playable.append((event[0] - prev, event[1]))
            prev = event[0]
        print("converting", self.current_playable)
        sleep(1)

    def playback(self):
        if not self.current_playable:
            self.convert_time()
        self.abortFlag = False
        while not self.abortFlag:
            for item in self.current_playable:
                if self.abortFlag:
                    break
                sleep(item[0])

                if self.seventh_flag:
                    play_chord = keys_chords_seventh[self.combo][
                        item[1]] + ".play()"
                else:
                    play_chord = keys_chords[self.combo][item[1]] + ".play()"
                exec(play_chord)
                app.processEvents()
                print(item[1], keys_name[self.combo][item[1]])
            sleep(2)

    def save_file(self):
        """get name to save as"""
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog

        file_name, _ = QFileDialog.getSaveFileName(self,
                                                   directory="sample_music",
                                                   options=options)
        if file_name:
            self.save(file_name)

    def save(self, file_name):
        """write to disk"""
        file_out = open(file_name, "wb")
        dump(self.current_playable, file_out)

    def file_open(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog

        file_name, _ = QFileDialog.getOpenFileName(self,
                                                   directory="sample_music",
                                                   options=options)
        if file_name:
            print(file_name)
            file_in = open(file_name, "rb")
            self.current_playable = load(file_in)
            print(self.current_playable)

        #*** Database Code ***

    def sql_tableview_model(self):
        db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName('KEYS.db')

        tableview = self.table.tableView
        tableview.columnWidth(4)

        self.model = QtSql.QSqlTableModel()
        tableview.setModel(self.model)

        self.model.setTable('KEYS')
        self.model.setEditStrategy(QtSql.QSqlTableModel.OnFieldChange)
        self.model.select()
        self.model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
        self.model.setHeaderData(1, QtCore.Qt.Horizontal, 'I')
        self.model.setHeaderData(3, QtCore.Qt.Horizontal, "II")
        self.model.setHeaderData(4, QtCore.Qt.Horizontal, "III")
        self.model.setHeaderData(5, QtCore.Qt.Horizontal, "IV")
        self.model.setHeaderData(6, QtCore.Qt.Horizontal, "V")
        self.model.setHeaderData(7, QtCore.Qt.Horizontal, "VI")
        self.model.setHeaderData(8, QtCore.Qt.Horizontal, "VII")
        tableview.hideColumn(0)
Esempio n. 33
0
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from main import Ui_MainWindow
import math

app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
trigger = True  #to check if you start a new calculation ad to avoid writing in the same space


#_______________________________buttons_______________________________
def zero():
    global trigger
    if trigger:
        ui.lineEdit.setText(ui.lineEdit.text() + "0")
    if not trigger:
        ui.lineEdit.setText("0")
    trigger = True


def one():
    global trigger
    if trigger:
        ui.lineEdit.setText(ui.lineEdit.text() + "1")
    if not trigger:
        ui.lineEdit.setText("1")
    trigger = True
Esempio n. 34
0
class MainWin(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.settings = updater.Settings()
        self.domains = updater.Domains()
        self.dom_data = []
        self.codes = {
            '401': 'Incorrect user/pass, or no API access.',
            '404': 'Could not find domain/record',
            '500': 'A server error has occurred',
        }
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.create_sys_tray()
        self.check_configs()
        self.connect_ctrls()
        self.run_loop()

    def get_code_text(self, code):
        try:
            txt = self.codes[str(code)]
        except:
            txt = "Unknown error occured. Please Try again later."
        return txt

    def stub(self):
        print 111

    def connect_ctrls(self):
        self.ui.ch_acct.clicked.connect(self.change_acct)
        self.ui.ch_dom.clicked.connect(self.change_dom)
        self.ui.refresh.clicked.connect(self.refresh)
        self.connect(self.ui.actionHide, QtCore.SIGNAL('triggered()'),
                     self.hide)
        self.connect(self.ui.actionQuit_2, QtCore.SIGNAL('triggered()'),
                     sys.exit)
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'),
                     self.about)

    def about(self):
        x = About(parent=self)
        x.exec_()

    def change_acct(self):
        x = MyLogin(self)
        self.connect(x, QtCore.SIGNAL("userChanged"), self.acct_callback)
        x.exec_()

    def change_dom(self):
        self.domains = updater.Domains()
        try:
            del self.domains.config['domain']
            self.domains.config.write()
        except:
            pass
        self.dom_data = self.domains.get_domains()
        if len(self.dom_data) > 0:
            x = myDomains(self.dom_data, parent=self)
            self.connect(x, QtCore.SIGNAL("domChanged"), self.dom_callback)
        else:
            x = NoDoms(parent=self)
        x.exec_()

    def acct_callback(self):
        self.check_configs()
        self.display_info()

    def dom_callback(self):
        self.check_configs()
        self.display_info()

    def refresh(self):
        self.domains = updater.Domains()
        if 'cache' in self.domains.config:
            del self.domains.config['cache']
            self.domains.config.write()
        self.emit(QtCore.SIGNAL("RefreshEvent"))

    def get_cache(self):
        try:
            self.cache = self.domains.config['cache']
        except:
            self.domains.config['cache'] = {}
            self.domains.config.write()
            self.cache = {}
        return self.cache

    def check_configs(self):
        self.refresh_configs()
        if self.settings.is_configured() is False:
            x = MyLogin(self)
            x.exec_()
        if self.settings.has_domain() is False:
            self.domains = updater.Domains()
            self.dom_data = self.domains.get_domains()
            if len(self.dom_data) > 0:
                x = myDomains(self.dom_data, parent=self)
            else:
                x = NoDoms(parent=self)
            x.exec_()

    def refresh_configs(self):
        self.settings = updater.Settings()
        self.domains = updater.Domains()

    def set_staus(self, msg1, msg2=None):
        txt = msg1
        if msg2 != None:
            txt = txt + "\n                 " + str(msg2)
        self.ui.UpStat.setText("Status:     %s" % txt)

    def set_record(self, msg1, msg2=None):
        txt = msg1
        if msg2 != None:
            txt = txt + "\n                 " + str(msg2)
        self.ui.DomInfo.setText("Record:   %s" % txt)

    def set_acct(self, msg1, msg2=None):
        txt = msg1
        if msg2 != None:
            txt = txt + "\n                 " + str(msg2)
        self.ui.AcctInfo.setText("Account: %s" % txt)

    def display_info(self):
        self.refresh_configs()
        rec_name = self.domains.config['domain']['rec_name']
        if rec_name == '@':
            dsp_rec = self.domains.config['domain']['name']
        else:
            dsp_rec = rec_name + "." + self.domains.config['domain']['name']

        self.ui.AcctInfo.setText("Account: %s" %
                                 str(self.domains.config['user']['username']))
        self.ui.DomInfo.setText("Record:   %s" % str(dsp_rec))

    def run_loop(self):
        self.updateT = updateThread(self)
        self.display_info()
        self.updateT.begin()
        self.connect(self.updateT, QtCore.SIGNAL("notifEvent"),
                     self.treatEvent)
        self.connect(self.updateT, QtCore.SIGNAL("notifIPEvent"),
                     self.treatIPEvent)

    def create_sys_tray(self):
        self.sysTray = QtGui.QSystemTrayIcon(self)
        menu = QtGui.QMenu()
        exit = menu.addAction("Exit")
        self.sysTray.setContextMenu(menu)
        self.connect(exit, QtCore.SIGNAL('triggered()'), sys.exit)
        self.sysTray.setIcon(QtGui.QIcon(':/updater/icon.png'))
        self.sysTray.setVisible(True)
        self.connect(
            self.sysTray,
            QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"),
            self.on_sys_tray_activated)

        self.sysTrayMenu = QtGui.QMenu(self)
        act = self.sysTrayMenu.addAction("FOO")

    def on_sys_tray_activated(self, reason):
        if reason == 3:
            if self.isVisible():
                self.setVisible(False)
            else:
                self.setVisible(True)

    def treatIPEvent(self, msg):
        print "IP event: " + str(msg)

    def treatEvent(self, msg):
        if str(msg) == '401':
            cache = self.get_cache()
            self.domains.config['cache']['auth_err'] = True
            self.domains.config.write()
            self.change_acct()
        if str(msg) == '404':
            self.change_dom()

    def closeEvent(self, event):
        if self.isVisible():
            self.setVisible(False)
        event.ignore()
Esempio n. 35
0
class MyMainwindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(lambda:self.execute_python('esp'))
        self.ui.pushButton_2.clicked.connect(self.getInfo)
        self.ui.pushButton_3.clicked.connect(lambda:self.execute_python('msp'))
        self.ui.fwupdate.clicked.connect(lambda:self.execute_python('fw'))
        self.ui.actionExit.triggered.connect(self.close)
        self.ui.actionHardware_Test.triggered.connect(self.init_test)
        self.prog = QtCore.QProcess(self)
        global child_pid
        prog = subprocess.Popen("python %s/socket/sckt.py &" %prog_dir,shell=True ) 
        child_pid = prog.pid
        print child_pid 

    def init_test(self):
        # opens test interface 
        ID = self.ui.lineEdit.text()
        subprocess.Popen("python %s/gui_2.py %s " %(prog_dir,ID),shell=True )
    
    def execute_python(self,command):
        # calls esp or msp programming process 
        self.ui.textEdit.clear()
        self.ui.textEdit_2.clear()
        print 'Connecting process'
        self.process = QtCore.QProcess(self)
        self.process.readyReadStandardOutput.connect(self.stdoutReady)
        self.process.readyReadStandardError.connect(self.stderrReady)
        self.process.started.connect(lambda: p('Started!'))
        self.process.finished.connect(lambda: p('Finished!'))
        print 'Starting process'
        if command == 'esp':
            self.process.start("sh %s/firmware/program.sh" %prog_dir)
        elif command == 'msp':
            self.process.start("sh %s/firmware/call_mspdebug.sh" %prog_dir)
        elif command == 'fw':
            self.process.start("mspdebug tilib --allow-fw-update exit")

    def getInfo(self):
        # opens the file with the device info and puts it on the needed outputs
        f = open("%s/socket/id.txt" %prog_dir, 'r')
        line = f.readline()
        line_split = line.split(']')
        part1=line_split[0].split('[')
        part2=line_split[1].split('[')
        part3=line_split[2].split('[')
        devID=part1[1]
        macadd=part2[1]
        unity=part3[1]
        arg = "%s %s %s" %(devID, macadd, unity)
        print arg
        f.close()
        self.process1 = QtCore.QProcess(self)
        self.process2 = QtCore.QProcess(self)
        self.write_ID(devID)
        self.write_MAC(macadd)
        self.process1.start("sh %s/printer/ptag-config.sh %s %s %s" %(prog_dir, devID, macadd, unity))
        self.process2.start("sh %s/printer/print.sh" %prog_dir)


    def append(self, text):
        frag = text.split(' ')
        msg = 'Programmed'
        color = 'green'
        global count
        if len(frag) >= 5:
            if frag[4] == '(100':
                count = count +1
                if count == 2:
                    # programmed message to ESP process 
                    subprocess.Popen("python %s/call_info.py %s %s" %(prog_dir,msg, color) ,shell=True )
                    count = 0
        if frag[0] == 'Done,': 
            #programmed message to MSP process
            subprocess.Popen("python %s/call_info.py %s %s" %(prog_dir,msg, color) ,shell=True )
        box =self.ui.textEdit
        cursor = self.ui.textEdit.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(text)
        box.ensureCursorVisible()

    def append_error(self, text):
        global count 
        count = 0
        box =self.ui.textEdit_2
        msg="ERROR"
        # If there is an error during the process call a popup window 
        subprocess.Popen("python %s/call_info.py %s red" %(prog_dir,msg),shell=True ) 
        cursor = self.ui.textEdit_2.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(text)
        box.ensureCursorVisible()
    
    # writes on the devices field  
    def write_ID(self,text):
        dev_id = self.ui.lineEdit
        dev_id.clear()
        dev_id.insert(text)
    
    def write_MAC(self,text):
        dev_MAC = self.ui.lineEdit_2
        dev_MAC.clear()
        dev_MAC.insert(text)
        
    def stdoutReady(self):
        # writes on the output text box 
        text = str(self.process.readAllStandardOutput())
        print text
        self.append(text)

    def stderrReady(self):
        # writes on the error text box 
        text = str(self.process.readAllStandardError())
        print text
        self.append_error(text)
Esempio n. 36
0
class MyApp(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.button_0.clicked.connect(self.put0)
        self.ui.button_1.clicked.connect(self.put1)
        self.ui.button_2.clicked.connect(self.put2)
        self.ui.button_3.clicked.connect(self.put3)
        self.ui.button_4.clicked.connect(self.put4)
        self.ui.button_5.clicked.connect(self.put5)
        self.ui.button_6.clicked.connect(self.put6)
        self.ui.button_7.clicked.connect(self.put7)
        self.ui.button_8.clicked.connect(self.put8)
        self.ui.button_9.clicked.connect(self.put9)
        self.ui.decimal.clicked.connect(self.put_dot)
        self.ui.clear_button.clicked.connect(self.clear)
        self.ui.reset_button.clicked.connect(self.reset)
        self.ui.add.clicked.connect(self.put_add)
        self.ui.minus.clicked.connect(self.put_sub)
        self.ui.divide.clicked.connect(self.put_divide)
        self.ui.multiply.clicked.connect(self.put_mul)
        self.ui.remainder.clicked.connect(self.put_mod)
        self.ui.square_root.clicked.connect(self.put_root)
        self.ui.parenthesis_close.clicked.connect(self.parenthesis_close)
        self.ui.parenthesis_open.clicked.connect(self.parenthesis_open)
        self.ui.equals.clicked.connect(self.render_answer)

    def put_add(self):
        self.put_text('+')

    def put_sub(self):
        self.put_text('-')

    def put_mul(self):
        self.put_text('*')

    def put_divide(self):
        self.put_text('/')

    def put_mod(self):
        self.put_text('%')

    def put_root(self):
        self.put_text('√')

    def parenthesis_open(self):
        self.put_text('(')

    def parenthesis_close(self):
        self.put_text(')')

    def reset(self):
        self.ui.lineEdit.clear()
        self.ui.output_window.clear()

    def clear(self):
        self.ui.lineEdit.clear()

    def put0(self):
        self.put_text('0')

    def put1(self):
        self.put_text('1')

    def put2(self):
        self.put_text('2')

    def put3(self):
        self.put_text('3')

    def put4(self):
        self.put_text('4')

    def put5(self):
        self.put_text('5')

    def put6(self):
        self.put_text('6')

    def put7(self):
        self.put_text('7')

    def put8(self):
        self.put_text('8')

    def put9(self):
        self.put_text('9')

    def put_dot(self):
        self.put_text('.')

    def put_text(self, txt):
        original = self.ui.lineEdit.text()
        new = original + txt
        self.ui.lineEdit.setText(new)

    def clicked(self):
        self.statusBar().showMessage('Hello there !')

    def keyPressEvent(self, e):
        key = e.key()
        print(key)
        if key in range(37, 62):
            original = self.ui.lineEdit.text()
            self.ui.lineEdit.setText(str(original + chr(key)))
        elif key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter:
            self.render_answer()
        elif key == QtCore.Qt.Key_Escape:
            self.reset()
        elif key == QtCore.Qt.Key_Backspace:
            self.backspace_line_edit()

    def backspace_line_edit(self):
        init = self.ui.lineEdit.text()
        self.ui.lineEdit.setText(init[:-1])

    def render_answer(self):
        input_equation = self.ui.lineEdit.text()
        init_output = self.ui.output_window.toPlainText()

        try:
            answer = eval(input_equation)
            self.ui.output_window.setText(input_equation + " = " +
                                          str(answer) + "\n" + init_output)

        except Exception:
            self.ui.statusbar.showMessage("Math Error!")

        self.clear()
Esempio n. 37
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.btn_exit.clicked.connect(self.salir)
        self.ui.btn_extraer_info.clicked.connect(self.activar_extraer_info)
        self.ui.btn_elegir_archivo_access.clicked.connect(self.elegir_access)
        self.ui.btn_funcionamiento.clicked.connect(self.show_funcionamiento)

    @Slot()
    def show_funcionamiento(self):
        dialog.show()

    @Slot()
    def activar_extraer_info(self):
        thread = threading.Thread(target=self.extraer_info, daemon=True)
        self.ui.btn_extraer_info.setDisabled(True)
        thread.start()

    @Slot()
    def elegir_access(self):
        root = tkinter.Tk()
        root.withdraw()  #use to hide tkinter window

        try:
            global DB_PATH
            DB_PATH = search_for_file_path(root)
            global conn
            conn = pyodbc.connect("Driver={%s};DBQ=%s;" %
                                  (DRIVER_NAME, DB_PATH))
            global cursor
            cursor = conn.cursor()
            cursor.execute('select * from Inquilinos')
            self.ui.btn_extraer_info.setDisabled(False)
            self.ui.lineEdit.setDisabled(False)
        except:
            self.ui.btn_extraer_info.setDisabled(True)
            self.ui.lineEdit.setDisabled(True)

    def extraer_info(self):
        if self.ui.lineEdit.text() != "":
            periodo_deseado = int(self.ui.lineEdit.text())
            driver = webdriver.Chrome(
                executable_path=
                'C:/Users/manue/Desktop/Programas/Aguas_Cordobesas/chromedriver.exe'
            )

            for row in cursor.fetchall():

                if row[11] != None and row[32] != None:
                    url = row[32]

                    try:
                        print(row[11])
                        driver.get(url)

                        WebDriverWait(driver, 10).until(
                            EC.presence_of_element_located(
                                (By.XPATH, '//*[@id="sUf"]'))
                        )  # Espera hasta que se cargue almenos un boton de copiar aviso en la pagina.
                        WebDriverWait(driver, 10).until(
                            EC.presence_of_element_located(
                                (By.XPATH,
                                 '//*[@id="tbl-detalleDeuda"]/tbody[2]')))
                        text = driver.find_element_by_xpath(
                            '//*[@id="tbl-detalleDeuda"]/tbody[2]').text
                        codigo = driver.find_element_by_xpath(
                            '//*[@id="sUf"]').text

                        text = text.split()

                        while len(text) > 10:
                            comprobacion = text[1].split('/')
                            if int(comprobacion[0]) == periodo_deseado:
                                break
                            del text[0:10]

                        text[8] = text[8].replace(",", ".")

                        print(text)

                        periodo = text[1].split('/')
                        cursor.execute(
                            "UPDATE [Inquilinos] SET [Aguas_Importe] = ?, [Aguas_cuota] = ? WHERE [URL_Aguas_Cbesas] = ?",
                            text[8], periodo[0], url)
                        print("Modificado")
                        conn.commit()

                    except:
                        print('Error con el cliente')
                        cursor.execute(
                            "UPDATE [Inquilinos] SET [Aguas_Importe] = ?, [Aguas_cuota] = ? WHERE [URL_Aguas_Cbesas] = ?",
                            "0", periodo_deseado, url)

            driver.close()
            print("Se ha completado la actualizacion")

            self.ui.btn_extraer_info.setDisabled(False)

    @Slot()
    def look_for_url(self):
        if self.ui.lineEdit_2.text() != "":
            self.ui.lineEdit_2.setText("")

            urls = []

            with open('urls.txt') as json_file:
                urls = json.load(json_file)

            driver = webdriver.Chrome()
            codigo = self.ui.lineEdit_2.text()

            driver.get('https://www.aguascordobesas.com.ar/espacioClientes/')

            sleep(2)

            driver.find_element_by_xpath(
                '//*[@id="modal-impactoEspacioClientes"]/div/div/div/button'
            ).click()
            driver.find_element_by_xpath('//*[@id="consulta-deuda"]').click()

            sleep(2)

            pyautogui.click(221, 636)  # Unidad de facturacion
            pyautogui.typewrite(codigo, interval=0.1)

            element = WebDriverWait(driver, 300).until(
                EC.presence_of_element_located(
                    (By.XPATH, '//*[@id="frmInitConsultaDeuda"]/div')))

            urls.append(driver.current_url)
            print(driver.current_url)

            with open('urls.txt', 'w') as f:
                json.dump(urls, f)

            driver.close()

    @Slot()
    def actualizar_clientes(self):
        new_inquilinos = []
        inquilinos2 = []

        FILE_PATH = 'inquilinos2.xlsx'
        SHEET = 'consulta BD'

        workbook = load_workbook(FILE_PATH, read_only=True)
        sheet = workbook[SHEET]

        for row in sheet.iter_rows(min_row=2):
            if row[13].value != None:
                inquilinos2.append(row[1].value)

        inquilinos1 = []

        FILE_PATH2 = 'inquilinos.xlsx'
        SHEET2 = 'Copia_de_Inquilinos'

        workbook2 = load_workbook(FILE_PATH2, read_only=False)
        sheet2 = workbook2[SHEET2]

        for row in sheet.iter_rows(min_row=2):
            if row[13].value != None:
                inquilinos1.append(row[1].value)

        for i in range(len(inquilinos2)):
            if not inquilinos2[i] in inquilinos1:
                new_inquilinos.append(inquilinos2[i])

        print(new_inquilinos)

    @Slot()
    def salir(self):
        sys.exit(app.exec_())
Esempio n. 38
0
class AppWindow(QMainWindow):
    biblioteca = None
    predefinido = False

    def __init__(self):
        super(AppWindow, self).__init__()

        # Set up the user interface from Designer.
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        self.inicializa_botoes()

        # Abre a página inicial
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_Inicial)

        self.biblioteca = Biblioteca()

    def inicializa_botoes(self):
        # Menu
        self.ui.actionIn_cio.triggered.connect(self.click_inicio)
        self.ui.actionAjuda.triggered.connect(self.click_ajuda)
        self.ui.actionCr_ditos.triggered.connect(self.click_creditos)
        self.ui.actionInserir_Informa_es.triggered.connect(self.click_inserir)
        self.ui.actionCarregar_Pre_Defini_es.triggered.connect(
            self.click_predefinir)
        self.ui.actionRodar_Execu_o.triggered.connect(self.click_MRP)
        self.ui.actionItens_cadastrados.triggered.connect(self.click_itens)

        # Início
        self.ui.btn_automatico.clicked.connect(self.click_automatico)

        # Cadastrar
        self.ui.btn_cadastrar.clicked.connect(self.click_cadastrar)

        # Item
        self.ui.btn_novoitem.clicked.connect(self.click_inserir)

        # MRP
        self.ui.btn_executar.clicked.connect(self.executarMRP)

    # ############ Declaração de Ações dos Botões

    # ###### Menu

    # Exibe Inicio
    def click_inicio(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_Inicial)

    def click_automatico(self):
        self.click_predefinir()
        self.click_MRP()

    # Exibe página de Ajuda
    def click_ajuda(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_Ajuda)

    # Exibe créditos
    def click_creditos(self):
        QMessageBox.about(
            self.ui.stackedWidget, "Créditos",
            "Sistema desenvolvido por: Yago Pessoa, Gustavo Moura, Thais Nobre e Alef Segura no âmbito da disciplina de Modelagem da Produção - ICMC - USP - julho de 2018"
        )

    # Abre a janela de cadastro de item
    def click_inserir(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_Cadastro)
        self.ui.comboBox.addItems(self.biblioteca.getItems())

    # Insere itens no sistema
    def click_predefinir(self):

        # ao inves de ter que cadastrar todos os itens, já pré-inserir uma quantidade legal suficiente para
        # realizar os testes  (inserir tudo de obj.py).

        # Item(codigo, nome, tr_leadtime, lote_mínimo, emin, eatual)
        if (self.predefinido == False):
            # item 1
            i_bk2 = Item("BK-2", "Bicicleta Padrão", 2, 10, 0, 2)
            self.biblioteca.addItem(i_bk2)

            # item 2
            i_sa1 = Item("Sa-1", "Selim", 3, 20, 10, 0)
            self.biblioteca.addItem(i_sa1)

            # item 3
            i_wh1 = Item("WH-1", "Roda", 2, 40, 20, 5)
            self.biblioteca.addItem(i_wh1)

            # item 4
            i_fr2 = Item("FR-2", "Quadro", 7, 20, 30, 10)
            self.biblioteca.addItem(i_fr2)

            # item 5
            i_tr1 = Item("TR-1", "Pneu", 3, 100, 20, 30)
            self.biblioteca.addItem(i_tr1)

            # item 6
            i_rm1 = Item("RM-1", "Aro", 1, 80, 100, 20)
            self.biblioteca.addItem(i_rm1)

            # item 7
            i_hb1 = Item("HB-1", "Cubo", 1, 80, 100, 20)
            self.biblioteca.addItem(i_hb1)

            # item 8
            i_sp1 = Item("SP-1", "Raio", 3, 500, 500, 600)
            self.biblioteca.addItem(i_sp1)

            # item 9
            i_tu1 = Item("TU-1", "Tubo Metálico", 3, 60, 30, 30)
            self.biblioteca.addItem(i_tu1)

            # item 10
            i_ms1 = Item("MS-1", "Tira Metálica", 3, 100, 2, 40)
            self.biblioteca.addItem(i_ms1)

            # item 11
            i_bb1 = Item("BB-1", "Rolamentos", 3, 50, 30, 5)
            self.biblioteca.addItem(i_bb1)

            # item 12
            i_bo1 = Item("BO-1", "Eixo de Roda", 3, 100, 100, 40)
            self.biblioteca.addItem(i_bo1)

            # item 13
            i_ho1 = Item("HO-1", "Cubo Externo", 3, 100, 100, 0)
            self.biblioteca.addItem(i_ho1)

            # dependencias
            i_bk2.addDependencia(i_fr2, 1)
            i_bk2.addDependencia(i_sa1, 1)
            i_bk2.addDependencia(i_wh1, 2)

            i_fr2.addDependencia(i_tu1, 6)

            i_wh1.addDependencia(i_tr1, 1)
            i_wh1.addDependencia(i_rm1, 1)
            i_wh1.addDependencia(i_hb1, 1)
            i_wh1.addDependencia(i_sp1, 32)

            i_rm1.addDependencia(i_ms1, 1.5)

            i_hb1.addDependencia(i_bb1, 1)
            i_hb1.addDependencia(i_bo1, 1)
            i_hb1.addDependencia(i_ho1, 1)

        # Mensagem de informação de sucesso
        QMessageBox.about(self.ui.stackedWidget, "Pré-definido",
                          "Estado do sistema pronto para rodar o MRP.")
        self.predefinido = True

    # Roda o MRP
    def click_MRP(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_MRP)
        self.ui.combo_MRP.addItems(self.biblioteca.getItems())

    # Exibe relatório de itens já inseridos no sistema
    def click_itens(self):
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_Itens)

        self.ui.tree_itens.clear()

        # Inclusão dos itens cadastrados na árvore
        if (self.biblioteca.estaVazia()):
            l = QTreeWidgetItem(["Não há itens cadastrados"])
            self.ui.tree_itens.addTopLevelItem(l)

        else:
            for i in range(self.biblioteca.lenght()):
                item = self.biblioteca.getItem_index(i)
                l = QTreeWidgetItem([item.codigo + " - " + item.nome])

                for dp in item.dependencias:
                    c = QTreeWidgetItem(
                        [dp.item.codigo + " - " + dp.item.nome])

                    l.addChild(c)

                self.ui.tree_itens.addTopLevelItem(l)

    # ###### Cadastrar
    def click_cadastrar(self):
        # realizar a verificação: se o item já foi cadastrado, perguntar se quer substituir as informações dele
        # com as informações inseridas agora
        # self, codigo, nome, nivel, tr, lote, emin, eatual

        # Só cadastra um item novo se ele ainda não estiver no banco
        if (self.biblioteca.naoTem(self.ui.in_cad_codigo.text())):
            itm = Item(self.ui.in_cad_codigo.text(),
                       self.ui.in_cad_nome.text(), self.ui.in_cad_tr.text(),
                       self.ui.in_cad_lote.text(), self.ui.in_cad_emin.text(),
                       self.ui.in_cad_eatual.text())

            self.biblioteca.addItem(itm)

        else:
            QMessageBox.about(self.ui.stackedWidget, "Erro",
                              "Código de item já cadastrado")

    # ###### Executar o MRP
    def executarMRP(self):
        item = self.biblioteca.getItem_index(self.ui.combo_MRP.currentIndex())
        self.ui.lb_item_MRP.setText(self.ui.combo_MRP.currentText())
        mrp = Item_MRP.find(item)
        for nb in range(1, mrp.n):
            # carregar qtd de nb do grid
            mrp.set_nb(nb, 1)
        #exibir mrp atualizado em page_MRP (grid 14x5 como a tabela do relatório)

        self.ui.tableWidget.setRowCount(5)
        self.ui.tableWidget.setColumnCount(14)
        self.ui.tableWidget.verticalHeader().hide()
        self.ui.tableWidget.horizontalHeader().hide()

        # linha 0
        self.ui.tableWidget.setItem(0, 0, QTableWidgetItem("Período"))
        for i in range(13):
            self.ui.tableWidget.setItem(0, i + 1, QTableWidgetItem(str(i)))

        # linha 1
        self.ui.tableWidget.setItem(1, 0, QTableWidgetItem("NB"))
        for i in range(13):
            self.ui.tableWidget.setItem(1, i + 1,
                                        QTableWidgetItem(str(mrp.nb[i])))

        # linha 2
        self.ui.tableWidget.setItem(2, 0, QTableWidgetItem("RP"))
        for i in range(13):
            self.ui.tableWidget.setItem(2, i + 1,
                                        QTableWidgetItem(str(mrp.rp[i])))

        # linha 3
        self.ui.tableWidget.setItem(3, 0, QTableWidgetItem("Disp."))
        for i in range(13):
            self.ui.tableWidget.setItem(3, i + 1,
                                        QTableWidgetItem(str(mrp.ed[i])))

        # linha 4
        self.ui.tableWidget.setItem(4, 0, QTableWidgetItem("LP"))
        for i in range(13):
            self.ui.tableWidget.setItem(4, i + 1,
                                        QTableWidgetItem(str(mrp.lp[i])))

        self.ui.tableWidget.resizeColumnsToContents()
Esempio n. 39
0
class LoginWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("Loginwindow")
        MainWindow.resize(468, 545)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.loginbutton = QtWidgets.QPushButton(self.centralwidget)
        self.loginbutton.setGeometry(QtCore.QRect(170, 340, 111, 31))
        self.loginbutton.setObjectName("loginbutton")
        self.loginbutton.clicked.connect(self.tomainmenu)
        # self.loginbutton.clicked.connect(MainWindow.close) this does work...

        self.closebutton = QtWidgets.QPushButton(self.centralwidget)
        self.closebutton.setGeometry(QtCore.QRect(170, 380, 111, 31))
        self.closebutton.setObjectName("closebutton")
        self.closebutton.clicked.connect(self.closeconfirm)

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(150, 60, 171, 51))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setWordWrap(True)
        self.label.setObjectName("label")

        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(150, 180, 171, 51))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setWordWrap(True)
        self.label_2.setObjectName("label_2")

        self.passwordbox = QtWidgets.QLineEdit(self.centralwidget)
        self.passwordbox.setGeometry(QtCore.QRect(130, 230, 201, 31))
        self.passwordbox.setObjectName("passwordbox")
        self.passwordbox.setEchoMode(QtWidgets.QLineEdit.Password)

        MainWindow.setCentralWidget(self.centralwidget)

        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 468, 21))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QtWidgets.QMenu(self.menubar)
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)

        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.actionLock = QtWidgets.QAction(MainWindow)
        self.actionLock.setObjectName("actionLock")
        self.actionDarkSky_Weather = QtWidgets.QAction(MainWindow)
        self.actionDarkSky_Weather.setObjectName("actionDarkSky_Weather")

        self.actionLocal_Facilities = QtWidgets.QAction(MainWindow)
        self.actionLocal_Facilities.setObjectName("actionLocal_Facilities")

        self.actionNews_Scanner = QtWidgets.QAction(MainWindow)
        self.actionNews_Scanner.setObjectName("actionNews_Scanner")

        self.actionProperty_Datascraper = QtWidgets.QAction(MainWindow)
        self.actionProperty_Datascraper.setObjectName(
            "actionProperty_Datascraper")

        self.actionPolscraper = QtWidgets.QAction(MainWindow)
        self.actionPolscraper.setObjectName("actionPolscraper")

        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.menuMenu.addAction(self.actionExit)

        self.menubar.addAction(self.menuMenu.menuAction())
        self.label_2.setBuddy(self.passwordbox)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Security Check"))

        self.loginbutton.setText(_translate("MainWindow", "OPEN"))
        self.closebutton.setText(_translate("MainWindow", "CLOSE"))
        self.label.setText(_translate("MainWindow", "PYTHON CONTROL PANEL"))
        self.label_2.setText(_translate("MainWindow", "ENTER PASSWORD"))
        self.menuMenu.setTitle(_translate("MainWindow", "Menu"))

        self.actionLock.setText(_translate("MainWindow", "Lock"))
        self.actionLock.setStatusTip(
            _translate("MainWindow", "Lock this computer"))
        self.actionLock.setShortcut(_translate("MainWindow", "Ctrl+L"))

        self.actionDarkSky_Weather.setText(
            _translate("MainWindow", "DarkSky Weather"))
        self.actionLocal_Facilities.setText(
            _translate("MainWindow", "Local Facilities"))
        self.actionNews_Scanner.setText(
            _translate("MainWindow", "News Scanner"))
        self.actionProperty_Datascraper.setText(
            _translate("MainWindow", "Property Datascraper"))
        self.actionPolscraper.setText(_translate("MainWindow", "Polscraper"))

        self.actionExit.setText(_translate("MainWindow", "Exit"))
        self.actionExit.setStatusTip(
            _translate("MainWindow", "Close the application"))

    def tomainmenu(self):
        # if self.passwordbox.text() == "correct":
        self.main_menu = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.main_menu)
        self.main_menu.show()
        MainWindow.close()

    def closeconfirm(self):
        cfm = QMessageBox()
        cfm.setWindowTitle("Close PCP?")
        cfm.setText("Confirm if you want to close the Python Control Panel")
        cfm.setIcon(QMessageBox.Information)
        cfm.setStandardButtons(QMessageBox.Close | QMessageBox.Cancel)
        cfm.setDefaultButton(QMessageBox.Cancel)

        cfm.buttonClicked.connect(self.closeprogram)
        x = cfm.exec_()

    def closeprogram(self, i):
        order = i.text()
        if order == 'Close':
            exit()
        else:
            print(i.text())
Esempio n. 40
0
class Start_Window(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(466, 361)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.ipEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.ipEdit.setGeometry(QtCore.QRect(120, 110, 331, 31))
        self.ipEdit.setObjectName("ipEdit")
        self.portEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.portEdit.setGeometry(QtCore.QRect(120, 180, 331, 31))
        self.portEdit.setObjectName("portEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 112, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(20, 180, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(160, 40, 131, 21))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(120, 240, 91, 31))
        font = QtGui.QFont()
        font.setPointSize(8)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 466, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.ip = None
        self.port = None

        self.ipEdit.setText("127.0.0.1")
        self.portEdit.setText("65432")

        self.ipEdit.returnPressed.connect(self.connect)
        self.portEdit.returnPressed.connect(self.connect)
        self.pushButton.clicked.connect(self.connect)

    def connect(self):
        ip = self.ipEdit.text()
        port = self.portEdit.text()

        if ip and port:
            work = False
            try:
                port = int(port)
                work = True

            except:
                print("Port is not a number")

            if work:
                self.ip = ip
                self.port = port

                try:
                    self.open()

                except:
                    pass

    def open(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()

        self.ui.setupUi(self.window, self)
        MainWindow.hide()
        self.window.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "IP:"))
        self.label_2.setText(_translate("MainWindow", "Port:"))
        self.label_3.setText(_translate("MainWindow", "Pls Connect"))
        self.pushButton.setText(_translate("MainWindow", "Connect"))
Esempio n. 41
0
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.list = []
        self.prog = []
        self.news = []
        self.n = 0
        self.len = 0
        self.ui.setupUi(self)
        self.url = 'http://europaplustv.com/api/v1.0/api.php?r='  # основная ссылка для API
        self.ui.search.hide()
        self.ui.btn.hide()
        self.ui.web.hide()
        self.ui.next.hide()
        self.ui.back.hide()
        self.ui.home.hide()
        self.ui.p1.hide()
        self.ui.p1.name = '1'
        self.ui.p2.hide()
        self.ui.p2.name = '2'
        self.ui.p3.hide()
        self.ui.p3.name = '3'
        self.ui.p4.hide()
        self.ui.p4.name = '4'
        self.ui.p5.hide()
        self.ui.p5.name = '5'
        self.ui.descrip.hide()
        self.ui.prg_name.hide()
        self.ui.news.name = 'news'
        self.ui.prg.name = 'prg'
        self.ui.artists.name = 'artists'
        self.artists = False
        self.ui.news.toggled.connect(self.onClicked)
        self.ui.prg.toggled.connect(self.onClicked)
        self.ui.artists.toggled.connect(self.onClicked)
        # подключаем/создаем базу
        self.conn = sqlite3.connect("base.db")
        self.cursor = self.conn.cursor()
        self.createbd()

    def center(self):  # окно появится в центре экрана
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def createbd(self):
        # удаляем таблицу с разделами программ для перезаписи
        self.cursor.execute("DROP TABLE IF EXISTS type;")
        # Создание таблицы для рубрик
        self.cursor.execute("""CREATE TABLE IF NOT EXISTS type(
           id INT PRIMARY KEY,
           name TEXT,
           description TEXT);
                       """)
        self.conn.commit()

        # создаем таблицу для программ
        self.cursor.execute("""CREATE TABLE IF NOT EXISTS prog(
           id INT PRIMARY KEY,
           title TEXT,
           link TEXT,
           type INT);
                       """)
        self.conn.commit()

        # Создание таблицы для новостей
        self.cursor.execute("""CREATE TABLE IF NOT EXISTS news(
                   id INT PRIMARY KEY,
                   title TEXT,
                   link TEXT,
                   UNIQUE(id));
                               """)
        self.conn.commit()

        # Создание таблицы для артистов
        self.cursor.execute("""CREATE TABLE IF NOT EXISTS artists(
                           id INT PRIMARY KEY,
                           name TEXT,
                           link TEXT);
                                       """)
        self.conn.commit()

    def onClicked(self):
        check = self.sender()
        if check.isChecked():
            if check.name == 'prg':
                self.prg()
            if check.name == 'news':
                self.onnews()
            if check.name == 'artists':
                self.onartist()

    def onnews(self):
        self.n = 0
        self.ui.search.hide()
        self.ui.btn.hide()
        self.ui.web.show()
        self.ui.next.show()
        self.ui.back.show()
        self.ui.home.show()
        self.ui.prg_name.show()
        self.ui.p1.hide()
        self.ui.p2.hide()
        self.ui.p3.hide()
        self.ui.p4.hide()
        self.ui.p5.hide()
        self.ui.im.hide()
        self.ui.descrip.hide()
        self.news = self.get_news()

        self.ui.web.setUrl(QUrl(self.news[self.n][2]))
        self.ui.prg_name.setText(self.news[self.n][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
        self.ui.prg_name.move(140, 100)
        self.ui.back.clicked.connect(self.back_n)
        self.ui.next.clicked.connect(self.next_n)
        self.ui.home.clicked.connect(self.home_n)

    def onartist(self):
        self.n = 0
        self.ui.web.hide()
        self.ui.search.show()
        self.ui.btn.show()
        self.ui.next.show()
        self.ui.back.show()
        self.ui.home.show()
        self.ui.prg_name.hide()
        self.ui.p1.hide()
        self.ui.p2.hide()
        self.ui.p3.hide()
        self.ui.p4.hide()
        self.ui.p5.hide()
        self.ui.im.hide()
        self.ui.descrip.hide()
        try:
            self.cursor.execute("SELECT * FROM artists;")
            self.artists = self.cursor.fetchall()
            self.len = len(self.artists) - 1
            self.ui.web.setUrl(QUrl(self.artists[0][2]))
        except:
            self.artists = False

        self.ui.btn.clicked.connect(self.get_artid)
        self.ui.back.clicked.connect(self.back_a)
        self.ui.next.clicked.connect(self.next_a)
        self.ui.home.clicked.connect(self.home_a)

    def get_artid(self):
        text = self.ui.search.toPlainText()
        if text != '':
            try:
                req_id = API.url + f'search/get&model=artists&tbls=artists&msg={text}'
                data = requests.post(req_id).json()['data']['items']
                id = data[0]['id']
                name = data[0]['name']
                url = API.url + f'content/get&model=artists&id={id}'
                art = (id, name, url)
                self.cursor.execute("INSERT OR IGNORE INTO artists VALUES(?, ?, ?);", art)
                self.conn.commit()
                self.cursor.execute("SELECT * FROM artists;")
                self.artists = self.cursor.fetchall()
                self.len = len(self.artists) - 1
                n = 0
                for i in self.artists:
                    if name in i:
                        self.n = n
                        break
                    else:
                        self.n = self.len
                    n += 1
                self.ui.web.setUrl(QUrl(self.artists[self.n][2]))
                self.ui.web.show()
            except:
                pass

    def prg(self):
        self.ui.search.hide()
        self.ui.btn.hide()
        self.ui.web.hide()
        self.ui.p1.isChecked()
        self.ui.im.show()
        self.list = self.get_lst()
        self.prog = self.get_prg(str(self.list[0][0]))
        self.n = 0
        self.len = len(self.prog) - 1
        self.image()
        self.ui.next.show()
        self.ui.back.show()
        self.ui.home.show()
        self.ui.p1.show()
        self.ui.p1.setText(self.list[0][1])
        self.ui.p2.show()
        self.ui.p2.setText(self.list[1][1])
        self.ui.p3.show()
        self.ui.p3.setText(self.list[2][1])
        self.ui.p4.show()
        self.ui.p4.setText(self.list[3][1])
        self.ui.p5.show()
        self.ui.p5.setText(self.list[4][1])
        self.ui.descrip.show()
        self.ui.descrip.setText(self.list[0][2])
        self.ui.descrip.setReadOnly(True)
        self.ui.prg_name.show()
        self.ui.prg_name.setText(self.prog[0][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
        self.ui.prg_name.move(280, 100)
        self.ui.p1.toggled.connect(self.onprg)
        self.ui.p2.toggled.connect(self.onprg)
        self.ui.p3.toggled.connect(self.onprg)
        self.ui.p4.toggled.connect(self.onprg)
        self.ui.p5.toggled.connect(self.onprg)
        self.ui.back.clicked.connect(self.back_p)
        self.ui.next.clicked.connect(self.next_p)
        self.ui.home.clicked.connect(self.home_p)

    def onprg(self):
        check = self.sender()
        if check.isChecked():
            if check.name == '1':
                self.n = 0
                self.prog = self.get_prg(self.list[0][0])
                self.ui.descrip.setText(self.list[0][2])
                self.ui.prg_name.setText(self.prog[self.n][1])
                self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
                self.image()
            elif check.name == '2':
                self.n = 0
                self.prog = self.get_prg(self.list[1][0])
                self.ui.descrip.setText(self.list[1][2])
                self.ui.prg_name.setText(self.prog[self.n][1])
                self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
                self.image()
            elif check.name == '3':
                self.n = 0
                self.prog = self.get_prg(self.list[2][0])
                self.ui.descrip.setText(self.list[2][2])
                self.ui.prg_name.setText(self.prog[self.n][1])
                self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
                self.image()
            elif check.name == '4':
                self.n = 0
                self.prog = self.get_prg(self.list[3][0])
                self.ui.descrip.setText(self.list[3][2])
                self.ui.prg_name.setText(self.prog[self.n][1])
                self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
                self.image()
            elif check.name == '5':
                self.n = 0
                self.prog = self.get_prg(self.list[4][0])
                self.ui.descrip.setText(self.list[4][2])
                self.ui.prg_name.setText(self.prog[self.n][1])
                self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
                self.image()

    def image(self):
        data = request.urlopen(self.prog[self.n][2]).read()
        self.pix1 = QPixmap()
        self.pix1.loadFromData(data)
        self.ui.im.setPixmap(self.pix1)
        self.ui.im.setScaledContents(True)

    def home_p(self):
        self.n = 0
        self.ui.prg_name.setText(self.prog[self.n][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
        self.image()

    def back_p(self):
        self.n -= 1
        if self.n < 0:
            self.n = self.len
        self.ui.prg_name.setText(self.prog[self.n][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
        self.image()

    def next_p(self):
        self.n += 1
        if self.n > self.len:
            self.n = 0
        self.ui.prg_name.setText(self.prog[self.n][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")
        self.image()

    def home_n(self):
        self.n = 0
        site = self.news[self.n][2]
        c = request.urlopen(site).read()
        with open('templates/page_n.html', 'w+', encoding="cp1251") as f:
            f.write(str(c))
        f.close()

        self.ui.web.setUrl(QUrl('http://127.0.0.1:5000/'))
        self.ui.prg_name.setText(self.news[self.n][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")




    def back_n(self):
        self.n -= 1
        if self.n < 0:
            self.n = self.len
        site = self.news[self.n][2]
        c = request.urlopen(site).read()
        with open('templates/page_n.html', 'w+', encoding="cp1251") as f:
            f.write(str(c))
        f.close()
        self.ui.web.setUrl(QUrl('http://127.0.0.1:5000/'))
        self.ui.prg_name.setText(self.news[self.n][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")

    def next_n(self):
        self.n += 1
        if self.n > self.len:
            self.n = 0

        site = self.news[self.n][2]
        c = request.urlopen(site).read()
        with open('templates/page_n.html', 'w+', encoding="cp1251") as f:
            f.write(str(c))
        f.close()
        self.ui.web.setUrl(QUrl('http://127.0.0.1:5000/'))
        self.ui.prg_name.setText(self.news[self.n][1])
        self.ui.prg_name.setStyleSheet("font: 87 10pt 'Arial Black'; color: rgb(255, 0, 0);")

    def back_a(self):
        if self.artists != False:
            self.n -= 1
            if self.n < 0:
                self.n = self.len
            site = self.artists[self.n][2]
            c = request.urlopen(site).read()
            with open('templates/page_n.html', 'w+', encoding="cp1251") as f:
                f.write(str(c))
            f.close()

            self.ui.web.setUrl(QUrl('http://127.0.0.1:5000/'))


    def next_a(self):
        if self.artists != False:
            self.n += 1
            if self.n > self.len:
                self.n = 0
            site = self.artists[self.n][2]
            c = request.urlopen(site).read()
            with open('templates/page_n.html', 'w+', encoding="cp1251") as f:
                f.write(str(c))
            f.close()
            self.ui.web.setUrl(QUrl('http://127.0.0.1:5000/'))

    def home_a(self):
        if self.artists != False:
            self.n = 0
            site = self.artists[self.n][2]
            c = request.urlopen(site).read()
            with open('templates/page_n.html', 'w+', encoding="cp1251") as f:
                f.write(str(c))
            f.close()

            self.ui.web.setUrl(QUrl('http://127.0.0.1:5000/'))

    def get_lst(self):  # запрашиваем список разделов видео с сайта europaplustv.com
        req = API.url + 'cliptype/get&'
        answer = requests.post(req).json()['data']  # получаем данные
        programms = []
        for i in answer:
            # исключаем лишние разделы
            if i['id'] != 111 and i['id'] != 1 and i['id'] != 71 and i['id'] != 2 and i['id'] != 141:
                try:
                    des = bs4.BeautifulSoup(i['description'], "html.parser").text
                except:
                    des = ''
                dic = (i['id'], i['name'], des)
                programms.append(dic)
            # записываем информацию о разделах с программами
        self.cursor.executemany("INSERT OR IGNORE INTO type VALUES (?,?,?)", programms)
        self.cursor.execute("SELECT * FROM type;")
        getlst = self.cursor.fetchall()
        return getlst

    def get_prg(self, id):  # запрашиваем содержание раздела нужной программы
        req = API.url + 'clip/findallbytypeid&type_id=' + str(id)
        answer = requests.post(req).json()['data']['clips']['items']
        list = []
        for i in answer:
            dic = (i['id'], i['performer'], i['path_poster'], id)
            list.append(dic)
        # записываем выпуски программ в базу
        self.cursor.executemany("INSERT OR IGNORE INTO prog VALUES(?, ?, ?, ?);", list)
        self.conn.commit()
        # получаем из базы полное содержимое выпусков программы нужного раздела
        self.cursor.execute(f"SELECT * FROM prog WHERE type = {id};")
        prog = self.cursor.fetchall()
        self.len = len(prog) - 1
        return prog

    def get_news(self):  # запрашиваем ID последних 20 новостей с сайта europaplustv.com и сохраняем в базу
        req_id = API.url + 'news/get&model=news&search_data[limit][start]=0&search_data[limit][count]=20'
        data = requests.post(req_id).json()['data']['items']
        news = []
        # сайт europaplustv через API отдает новости в виде html.
        # Поэтому сразу формируем ссылки на API запрос на страницы с новостями
        for i in data:
            new = (i['id'], i['title'], f"{API.url}content/get&model=news&id={str(i['id'])}")
            news.append(new)
        # записываем информацию о новых новостях в базу
        self.cursor.executemany("INSERT OR IGNORE INTO news VALUES(?, ?, ?);", news)
        self.conn.commit()
        # получаем из базы полный список новостей
        self.cursor.execute("SELECT * FROM news;")
        news = self.cursor.fetchall()
        self.len = len(news) - 1
        return news
Esempio n. 42
0
 def __init__(self):
     super().__init__()
     self.c = 0
     ui = Ui_MainWindow()
     ui.setupUi(self)
     ui.pushButton.clicked.connect(self.up)
Esempio n. 43
0
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 04 20:38:29 2015

@author: Administrator
"""

import sys
from  PyQt4 import QtGui
from main import Ui_MainWindow


app = QtGui.QApplication(sys.argv)
widget = QtGui.QMainWindow();
win = Ui_MainWindow()
win.setupUi(widget)
#win.pushButton.event = 

widget.show()
#
#widget = QtGui.QWidget();
#
#widget.resize(250,250)
#widget.setWindowTitle("smple")
#widget.show()
#

sys.exit(app.exec_())


class Ui_Fantasy(object):
    #open new
    def mainscr(self):
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.window)
        Fantasy.hide()
        self.window.show()

    def setupUi(self, Fantasy):
        Fantasy.setObjectName("Fantasy")
        Fantasy.resize(800, 600)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(Fantasy.sizePolicy().hasHeightForWidth())
        Fantasy.setSizePolicy(sizePolicy)
        Fantasy.setMinimumSize(QtCore.QSize(800, 600))
        Fantasy.setMaximumSize(QtCore.QSize(800, 600))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("Image/cricket.png"), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        Fantasy.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(Fantasy)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(210, 0, 371, 341))
        self.label.setText("")
        self.label.setPixmap(
            QtGui.QPixmap(
                "Image/218293_cricket-logo-png-removebg-preview.png"))
        self.label.setScaledContents(True)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(240, 300, 271, 91))
        font = QtGui.QFont()
        font.setFamily("Chiller")
        font.setPointSize(25)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(
            310, 400, 131, 81))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(
            self.horizontalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.start = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.start.setFont(font)
        self.start.setObjectName("start")
        self.verticalLayout.addWidget(self.start)
        self.exit = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.exit.setFont(font)
        self.exit.setObjectName("exit")
        self.verticalLayout.addWidget(self.exit)
        Fantasy.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(Fantasy)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
        self.menubar.setObjectName("menubar")
        Fantasy.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(Fantasy)
        self.statusbar.setObjectName("statusbar")
        Fantasy.setStatusBar(self.statusbar)

        self.retranslateUi(Fantasy)
        self.exit.clicked.connect(Fantasy.close)
        QtCore.QMetaObject.connectSlotsByName(Fantasy)

        #START
        self.start.clicked.connect(self.mainscr)

    def retranslateUi(self, Fantasy):
        _translate = QtCore.QCoreApplication.translate
        Fantasy.setWindowTitle(_translate("Fantasy", "Fantasy Cricket"))
        self.label_2.setText(_translate("Fantasy", "Fantasy Cricket"))
        self.start.setText(_translate("Fantasy", "START"))
        self.exit.setText(_translate("Fantasy", "EXIT"))