Esempio n. 1
0
File: main1.py Progetto: aisyluG/LR3
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.input = None
        # self.thr = Thread().
        self.timer = QTimer()
        self.reader_Thread = QThread()
        self.reader = ConsoleReader(self.semaphore, self.timer)
        self.reader.moveToThread(self.reader_Thread)

        self.writer_Thread = QThread()
        self.writer = ConsoleWriter(self.semaphore)
        self.writer.moveToThread(self.writer_Thread)

        self.ui.startBt.clicked.connect(self.startProcess)
        self.writer.process_created.connect(self.pp)
        # self.writer.process_created.connect(self.reader.set_pipe)
        self.reader.readed.connect(self.addToConsole)
        self.ui.sendBt.clicked.connect(self.addInput)
        # self.timer.timeout.connect(self.ii)
        # self.timer.timeout.connect(self.timer.stop)

        self.reader_Thread.start()
        self.writer_Thread.start()
Esempio n. 2
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.sem_for_timer = QSemaphore()

        self.reader_Thread = QThread()
        self.reader = ConsoleReader(self.sem_for_timer,
                                    self.semaphore_start_reading)
        self.reader.moveToThread(self.reader_Thread)

        # self.timerThread = QThread()
        # self.timer = Timer(self.sem_for_timer, self.reader_Thread)
        # self.timer.moveToThread(self.timerThread)

        self.writer_Thread = QThread()
        self.writer = ConsoleWriter(self.semaphore_start_reading)
        self.writer.moveToThread(self.writer_Thread)

        self.thr_read = Thread(target=self.ff)
        self.thr_write = Thread(target=self.ww)
        # self.thr_timer = Thread(target=self.gg)

        self.ui.startBt.clicked.connect(self.startProcess)
        # self.writer.process_created.connect(self.pp)
        # self.writer.process_created.connect(self.reader.set_pipe)
        self.ui.sendBt.clicked.connect(self.addInput)
        self.writer.value_entered.connect(self.semaphore_start_reading.release)
        self.reader.readed.connect(self.addToConsole)
        # self.timer.timeout.connect(self.newThread)

        self.writer_Thread.start()
        # self.timerThread.start()
        self.reader_Thread.start()
Esempio n. 3
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # This is always the same
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Esempio n. 4
0
class MainApp:
    def __init__(self):

        self.init_ui()

    def init_ui(self):
        self.app = QtWidgets.QApplication(sys.argv)
        self.MainWindow = QtWidgets.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

    def init_listeners(self):
        self.ui.pushButtonTSNE.clicked.connect(self.tsne)
        self.ui.pushButtonHist.clicked.connect(self.hist)

    def tsne(self):
        path = self.ui.lineEdit.text()
        print(path)
        self.ts = tsne(path)

    def hist(self):
        path = self.ui.lineEdit.text()
        self.pt = starts(path)

    def start(self):
        self.ui.setupUi(self.MainWindow)
        self.init_listeners()
        self.MainWindow.show()
        sys.exit(self.app.exec_())
Esempio n. 5
0
 def __init__(self, parent=None):
     QMainWindow.__init__(self, parent)
     # Load the ui
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     # Set the MainWindow Title
     self.setWindowTitle('Game Genie Good Guy - ' + self.version)
     # When the software are closed on console the software are closed
     signal.signal(signal.SIGINT, signal.SIG_DFL)
     self.ui.system.addItem("Game Boy/Gear/Master System")
     self.ui.system.addItem("Genesis/Mega Drive (no SMD roms)")
     self.ui.system.addItem("Nintendo")
     self.ui.system.addItem("Super Nintendo")
     self.ui.browse.clicked.connect(self.browse)
     self.ui.patch.clicked.connect(self.generateRom)
     self.ui.ips.clicked.connect(self.generateIPS)
     self.ui.log.setReadOnly(True)
     self.process = QProcess()
     self.process.readyReadStandardOutput.connect(self.printLog)
     if self.settings.value("rom"):
         self.ui.rom.setText(self.settings.value("rom"))
     if self.settings.value("system"):
         self.ui.system.setCurrentIndex(int(self.settings.value("system")))
     # Show the form
     self.show()
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(WIDTH, HEIGHT)
        self.ui.submit_Btn.clicked.connect(self.run)

    def run(self):
        try:
            file_name = self.ui.file_path_textEdit.toPlainText()
            iterations = int(self.ui.iterations_textEdit.toPlainText())
            delimiter = self.ui.delimiter_textEdit.toPlainText()
            learning_rate = float(self.ui.learning_rate_textEdit.toPlainText())
            get_gradient_descent(file_name, learning_rate, delimiter,
                                 iterations)
        except Exception as ex:
            self.display_error(str(ex))

    def display_error(self, message):
        msg = QtGui.QMessageBox()
        msg.setIcon(QtGui.QMessageBox.Warning)
        msg.setWindowTitle("Error")
        msg.setInformativeText(message)
        msg.exec_()
Esempio n. 7
0
class Browser(QtWidgets.QMainWindow):
    def __init__(self):
        super(Browser, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.url = self.make_true_url('http://127.0.0.1:5000')
        self.ui.webView.load(self.url)

        self.ui.reloadButton.clicked.connect(self.ui.webView.reload)
        self.ui.backButton.clicked.connect(self.ui.webView.back)
        self.ui.goButton.clicked.connect(self.go_to_page)
        self.ui.urlLine.setText(
            re.findall("('.+')", str(self.ui.webView.url()))[0][1:-1])

        self.ui.webView.urlChanged.connect(self.update_urlbar)
        self.ui.webView.titleChanged.connect(self.update_title)

    @staticmethod
    def make_true_url(url):
        return QUrl(url) if QUrl(url).scheme() else QUrl('http://' + url)

    def go_to_page(self):
        self.url = self.make_true_url(self.ui.urlLine.text())
        self.ui.webView.load(self.url)

    def update_urlbar(self):
        self.ui.urlLine.setText(
            re.findall("('.+')", str(self.ui.webView.url()))[0][1:-1])

    def update_title(self):
        title = self.ui.webView.page().title()
        self.setWindowTitle(f'{title} - MiniBrowser')
Esempio n. 8
0
File: main.py Progetto: aisyluG/LR2
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # буфер для отправленных, но еще не обработанных сообщений
        self.buffer = queue.Queue()
        # потоки для обработки информации
        self.sentThread = QThread()
        self.sentObj = Producer(self.sem, self.buffer)
        self.sentObj.moveToThread(self.sentThread)

        self.n = 1
        self.getThreadsPool = [QThread()]
        self.getObjs = [Consumer(self.sem, self.sem_forBuffer, 1, self.buffer)]
        self.getObjs[0].moveToThread(self.getThreadsPool[0])



        self.ui.sendBt.clicked.connect(self.sentObj.run)
        self.ui.sendBt.clicked.connect(self.check)
        self.sentObj.message_sented.connect(self.getObjs[0].run)
        self.sentObj.message_sented.connect(self.addSendedMessage)
        self.getObjs[0].message_getted.connect(self.addGettedMessage)
        self.ui.okBt.clicked.connect(self.change_threadNumber)


        self.sem_forBuffer.release()
        self.sentThread.start()
        self.getThreadsPool[0].start()
Esempio n. 9
0
class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        global ui
        super(ApplicationWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
Esempio n. 10
0
 def __init__(self):
     super().__init__()
     self.ui = Ui_MainWindow()
     # 初始化界面
     self.ui.setupUi(self)
     self.__actionBlinding__()
     self.udpIp = '192.168.1.3'
     self.udpPort = '5000'
Esempio n. 11
0
 def __init__(self):
     super(DojoShare, self).__init__()
     netList = get_interfaces_addresses()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.comboBox.addItems(netList)
     self.ui.pushButton.clicked.connect(self.buttonClicked)
     self.server_thread = Thread(target=self.start_server)
Esempio n. 12
0
def main():
    app = QApplication(sys.argv)
    main_window = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(main_window)
    main_window.show()

    sys.exit(app.exec_())
Esempio n. 13
0
class MainWin(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWin, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.let_rice_val.setText("800")
        self.ui.let_rice_per_sushi.setText("160")

        self.show_msg = QtWidgets.QMessageBox()
        self.ui.pbn_calc.clicked.connect(self.calc_sushi_vals)
        self.ui.pbn_reset.clicked.connect(self.reset_vals)

    def calc_sushi_vals(self):

        res = self.check_input(self.ui.let_rice_val.text())

        if res == -1:
            return
        res = self.check_input(self.ui.let_rice_per_sushi.text())

        if res == -1:
            return
        rice = float(self.ui.let_rice_val.text())
        rice_per_sushi = float(self.ui.let_rice_per_sushi.text())

        acid_calc = str(round(rice * 11 / 100))
        shugar_calc = str(round(rice * 9 / 100))
        salt_calc = str(round(rice * 1 / 100))
        water_calc = str(round(rice * 111 / 100))

        total_sushi_calc = str(round(
            (rice + int(water_calc)) / rice_per_sushi))
        self.ui.let_acid_val.setText(acid_calc)
        self.ui.let_shugar_val.setText(shugar_calc)
        self.ui.let_salt_val.setText(salt_calc)
        self.ui.let_water_val.setText(water_calc)
        self.ui.let_total_sushu_cnt.setText(total_sushi_calc)

    def check_input(self, string):
        ciphers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        if len(string) == 0:
            self.show_msg.critical(None, "Ошибка ввода", "Пустое поле ввода")
            return -1
        for i, char in enumerate(string):
            if char not in ciphers:
                self.show_msg.critical(None, "Ошибка ввода",
                                       "В поле ввода находится не число!")
                return -1

    def reset_vals(self):
        self.ui.let_rice_val.setText("800")
        self.ui.let_rice_per_sushi.setText("160")
        self.ui.let_salt_val.clear()
        self.ui.let_shugar_val.clear()
        self.ui.let_water_val.clear()
        self.ui.let_acid_val.clear()
        self.ui.let_total_sushu_cnt.clear()
Esempio n. 14
0
    def __init__(self, w):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(w)

        self.filenames = os.listdir(PATH)
        self.groups = ['x' for i in range(len(self.filenames))]
        self.current_i = 0

        self.prepare_ui(w)
Esempio n. 15
0
 def __init__(self):
     super().__init__()
     self.ui = Ui_MainWindow()
     # 初始化界面
     self.ui.setupUi(self)
     self.__actionBlinding__()
     self.__beBeautiful__()
     self.udpIp = '192.168.1.3'
     self.udpPort = '5000'
     self.udpInterface = UdpApplication()
Esempio n. 16
0
File: main.py Progetto: aisyluG/LVM
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.canvas = DrawWidget(self.ui.frame)
        self.ui.canvas.setGeometry(
            QRect(2, 2,
                  self.ui.frame.width() - 165,
                  self.ui.frame.height() - 6))
        palet = QPalette()
        palet.setColor(QPalette.Window, QColor('#ffffff'))
        palet.setColor(QPalette.Button, QColor('#ffffff'))
        self.ui.canvas.setPalette(palet)
        self.ui.canvas.setAutoFillBackground(True)

        ds = DangerousState()
        self.dangStates = [ds]
        self.ui.canvas.setState(ds)
        self.ui.listWidget.addItem('dangerous state 1')
        self.ui.listWidget.setCurrentRow(0)

        # кнопки
        self.ui.andBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.orBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.cursorBt.setStyleSheet('background-color: blue;')
        self.ui.stateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.iniStateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.dangStateBt.setStyleSheet('background-color: #f0f0f0;')
        self.ui.connectBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.cleanBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.delBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.addDSbt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.saveBt.setStyleSheet(('background-color: #f0f0f0;'))
        self.ui.openBt.setStyleSheet(('background-color: #f0f0f0;'))

        # обработчики событий
        self.ui.andBt.clicked.connect(self.change_paintMode)
        self.ui.orBt.clicked.connect(self.change_paintMode)
        self.ui.stateBt.clicked.connect(self.change_paintMode)
        self.ui.cursorBt.clicked.connect(self.change_paintMode)
        self.ui.dangStateBt.clicked.connect(self.change_paintMode)
        self.ui.iniStateBt.clicked.connect(self.change_paintMode)
        self.ui.connectBt.clicked.connect(self.change_paintMode)
        self.ui.canvas.selectedChanged.connect(self.probabEnter)
        self.ui.computeDEPbt.clicked.connect(self.computing)
        self.ui.cleanBt.clicked.connect(self.cleancanvas)
        self.ui.addDSbt.clicked.connect(self.addNewDstate)
        self.ui.listWidget.currentItemChanged.connect(self.stateChanged)
        self.ui.canvas.dang_stateRenamed.connect(self.renameState)
        self.ui.delBt.clicked.connect(self.delCurrent)
        self.ui.openBt.clicked.connect(self.open)
        self.ui.saveBt.clicked.connect(self.save)

        self.selectedState = None
Esempio n. 17
0
File: main1.py Progetto: aisyluG/LR3
class Window(QMainWindow):
    semaphore = QSemaphore()
    input_sended = pyqtSignal()
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.input = None
        # self.thr = Thread().
        self.timer = QTimer()
        self.reader_Thread = QThread()
        self.reader = ConsoleReader(self.semaphore, self.timer)
        self.reader.moveToThread(self.reader_Thread)

        self.writer_Thread = QThread()
        self.writer = ConsoleWriter(self.semaphore)
        self.writer.moveToThread(self.writer_Thread)

        self.ui.startBt.clicked.connect(self.startProcess)
        self.writer.process_created.connect(self.pp)
        # self.writer.process_created.connect(self.reader.set_pipe)
        self.reader.readed.connect(self.addToConsole)
        self.ui.sendBt.clicked.connect(self.addInput)
        # self.timer.timeout.connect(self.ii)
        # self.timer.timeout.connect(self.timer.stop)

        self.reader_Thread.start()
        self.writer_Thread.start()


    def ii(self):
        print('stopped')
        # self.reader_Thread.terminate()
        self.reader.thread().wait()

    def pp(self, process):
        self.reader.set_pipe(process)

    def addToConsole(self, output):
        self.ui.outputText.append(output)

    def startProcess(self):
        path = self.ui.comandLine.text()
        if '\\' in path:
            path = path.replace('\\', '/')
            # print(path)
        self.writer.createProcess(path)
        self.reader.run()

    def addInput(self):
        input = self.ui.inputText.text()
        self.writer.write(input)
        self.ui.outputText.append('>'+input)
Esempio n. 18
0
    def __init__(self):
        super(MainWin, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.let_rice_val.setText("800")
        self.ui.let_rice_per_sushi.setText("160")

        self.show_msg = QtWidgets.QMessageBox()
        self.ui.pbn_calc.clicked.connect(self.calc_sushi_vals)
        self.ui.pbn_reset.clicked.connect(self.reset_vals)
Esempio n. 19
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.executeBtn.clicked.connect(self.executeQuery)
        self.openBtn.clicked.connect(self.openFile)
        self.resultTable.verticalHeader().hide()
        self.queryTextEdit.setText(self.createSql)
        self.connectionStringLineEdit.setText(':memory:')
        self.outputTextView.setReadOnly(True)
Esempio n. 20
0
    def __init__(self):
        super(WindowOperator, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.path_img_lineedit.setReadOnly(True)
        self.ui.predict_button.clicked.connect(self.predict_images)
        self.ui.file_path_button.clicked.connect(self.get_file_path)
        self.ui.model_box.currentIndexChanged.connect(self.get_model_path)
        self.ui.path_model_lable.setText('')
        self.ui.predict_button.setEnabled(False)

        self.images_path = ''
        self.model_path = config.lenet
Esempio n. 21
0
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #Threads
        self.threadclass = ThreadClass()
        self.threadclass.start()
        self.threadclass.sig1.connect(self.graphUpdate)
        #self.connect(self.threadclass, QtCore.SIGNAL("elVal"), self.graphUpdate)
        #Signals:::
        self.ui.pushButton_start.clicked.connect(
            self.Button_Start_Clicked
        )  # connecting the clicked signal with btnClicked slot
        self.ui.Button_In.clicked.connect(self.Button_In_Clicked)
        self.ui.Button_Out.clicked.connect(self.Button_Out_Clicked)
        self.ui.dial_FS.valueChanged.connect(self.dial_FS_moved)
        self.ui.lineEdit_FS.returnPressed.connect(self.lineEdit_FS_change)
        self.ui.Button_getParams.clicked.connect(self.Button_getParams_Clicked)
        self.ui.Button_cmd.clicked.connect(self.Button_cmd_Clicked)
        self.ui.lineEdit_gCommand.returnPressed.connect(
            self.Button_cmd_Clicked)
        self.ui.Button_ParamSend.clicked.connect(self.Button_ParamSend_Clicked)
        self.ui.spinBox_maxTravel.valueChanged.connect(
            self.spinBox_maxTravel_clicked)
        self.ui.spinBox_position.valueChanged.connect(
            self.spinBox_position_clicked)
        self.ui.hSlider.valueChanged.connect(self.hSlider_clicked)
        self.ui.pushButton_go.clicked.connect(self.pushButton_go_clicked)
        self.ui.Button_holdRes.clicked.connect(self.Button_holdRes_Clicked)
        self.ui.Button_home.clicked.connect(self.Button_home_Clicked)

        self.ui.spinBox_maxFS.valueChanged.connect(self.settingChanges)

        self.update_window_signal.connect(self.update_window_routine)
        #self.ui.tableView_Params.itemChanged.connect(self.tableSignal)
        ### Default values
        self.ui.comboBox_temp_ports.setEnabled(False)
        self.ui.comboBox_stepper_ports.setEnabled(False)
        self.ui.Button_cmd.setEnabled(False)
        self.ui.Button_getParams.setEnabled(False)
        self.ui.Button_ParamSend.setEnabled(False)
        self.ui.dial_FS.setValue(200)
        self.ui.lineEdit_FS.setText(str(self.ui.dial_FS.value()))
        self.ui.hSlider.setMaximum(self.ui.spinBox_maxTravel.value() / 10)
        self.ui.spinBox_position.setMaximum(self.ui.spinBox_maxTravel.value())

        #private variables
        self.temp_counter = 0
        self.temp_old = temp_0
        self.block_soak = 0
        self.block_peak = 0
Esempio n. 22
0
    def __init__(self):
        super(Browser, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.url = self.make_true_url('http://127.0.0.1:5000')
        self.ui.webView.load(self.url)

        self.ui.reloadButton.clicked.connect(self.ui.webView.reload)
        self.ui.backButton.clicked.connect(self.ui.webView.back)
        self.ui.goButton.clicked.connect(self.go_to_page)
        self.ui.urlLine.setText(
            re.findall("('.+')", str(self.ui.webView.url()))[0][1:-1])

        self.ui.webView.urlChanged.connect(self.update_urlbar)
        self.ui.webView.titleChanged.connect(self.update_title)
Esempio n. 23
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Exit QAction
        exit_action = QAction("Exit", self)
        exit_action.setShortcut(QKeySequence.Quit)
        exit_action.triggered.connect(self.close)

        self.ui.menuFile.addAction(exit_action)

        # Window dimensions
        geometry = qApp.desktop().availableGeometry(self)
        self.setFixedSize(geometry.width() * 0.8, geometry.height() * 0.7)
Esempio n. 24
0
 def __init__(self, parent=None):
     #Loads of BORING UI setup code!!
     QtGui.QMainWindow.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.loadSettings()
     self.initPD()
     self.initFTD()
     self.ui.listView.setModel(self.peer_container)
     self.peerSelection = self.ui.listView.selectionModel()
     self.ui.tableView.setModel(self.proxy)
     self.fileSelection = self.ui.tableView.selectionModel()
     self.dloadMgr = model.DownloadWidgetManager(self.ui.tableWidget)
     self.tableHeaderResize()
     self.initConnection()
    def __init__(self, app):

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

        self.ui.pushButton.clicked.connect(self.launch)
        self.ui.pushButton_2.clicked.connect(self.makeInput)

        self.ui.pushButton_2.setVisible(False)

        self.outputdim = np.zeros(4)

        # Variables UI
        self.show()
        self.app = app
Esempio n. 26
0
    def __init__(self):
        #Inicio el objeto QMainwindow
        QMainWindow.__init__(self)
        self.formulario = Ui_MainWindow()
        self.formulario.setupUi(self)

        self.iniciarVariables()
        self.vaciarLog()

        self.reporte = Reporte()

        #seteamos los eventos        
        self.formulario.btnSimulacion.clicked.connect(self.simular)
        self.formulario.btnGraficoDePuntos.clicked.connect(self.armarGraficoPuntos)
        self.formulario.btnGraficoDeBarras.clicked.connect(self.armarGraficoBarras)
        self.formulario.btnReporte.clicked.connect(self.armarReporte)
Esempio n. 27
0
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.mixerOutput = ''
        self.imageBoxItem = ''
        self.imageBoxItem_2 = ''
        self.firstComponentValueofImage_1 = ''
        self.secondComponentValueOfImage_1 = ''
        self.firstComponentValueOfImage_2 = ''
        self.secondComponentValueOfImage_2 = ''
        self.componentBoxItem = ''
        self.componentBoxItem_2 = ''
        self.sliderValue = ''
        self.sliderValue2 = ''
        ##########
        self.comboBoxText = ''
        self.ui.mixerBtn.clicked.connect(self.OpenWindow)
        self.ui.browseImage1.clicked.connect(self.browseImage)
        self.ui.browseImage1_2.clicked.connect(self.browseImage2)
        self.ui.browseBtn1.clicked.connect(self.checkComboBox)
        self.ui.browsebtn2.clicked.connect(self.checkComboBox2)

        self.myImage_1 = imageClass()
        self.myImage_2 = imageClass()
Esempio n. 28
0
    def __init__(self):
        # python version calls
        if (sys.version_info > (3, 0)):
            super().__init__()
        else:
            super(AppWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(910, 720)
        self.setMouseTracking(False)
        self.setWindowIcon(QtGui.QIcon("res/icon.png"))
        self.init_Connections()
        self.init_Interface()

        self.hashSelectionChanged()

        self.show()
Esempio n. 29
0
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        highlight = syntax.PythonHighlighter(self.ui.editor.document())
        self.ui.editor.document().setDefaultFont(QFont("Monospace", 10, QFont.Normal))

        self.connect(self.ui.actionRun, SIGNAL("triggered()"), self.on_run_program)
Esempio n. 30
0
File: CC02.py Progetto: rouxinol/Lab
 def __init__(self, parent=None):
     QtGui.QWidget.__init__(self, parent)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     
     
     #connect to run button
     
     QtCore.QObject.connect(self.ui.runButton, QtCore.SIGNAL(("clicked()")), self.handleCalculate)
     QtCore.QObject.connect(self.ui.plotBtn,   QtCore.SIGNAL(("clicked()")), self.plotData)
Esempio n. 31
0
    def __init__(self):

        QtGui.QMainWindow.__init__(self)

        # UI created by QT Designer
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # default value = 5 m
        self.launchAlt = 5

        #Set up option parsing to get connection string
        import argparse
        parser = argparse.ArgumentParser(
            description=
            'Tracks GPS position of your computer (Linux only). Connects to SITL on local PC by default.'
        )
        parser.add_argument('--connect', help="vehicle connection target.")
        args = parser.parse_args()

        self.connection_string = args.connect
        self.sitl = None

        #Start SITL if no connection string specified
        if not self.connection_string:
            import dronekit_sitl
            self.sitl = dronekit_sitl.start_default()
            self.connection_string = self.sitl.connection_string()

        # Connect to the Vehicle
        print 'Connecting to vehicle on: %s' % self.connection_string
        self.vehicle = connect(self.connection_string, wait_ready=True)

        # Display Flight Mode
        self.updateFlightModeGUI(self.vehicle.mode)
        self.addObserverAndInit(
            'mode', lambda vehicle, name, mode: self.updateFlightModeGUI(mode))

        # Display Location Info
        self.updateLocationGUI(self.vehicle.location)
        self.addObserverAndInit(
            'location',
            lambda vehicle, name, location: self.updateLocationGUI(location))
Esempio n. 32
0
File: main.py Progetto: miodeq/swd
	def __init__(self):
		QtGui.QMainWindow.__init__(self)

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

		self.ui.actionAdd_Row.triggered.connect(self.add_row)
		self.ui.actionAdd_Col.triggered.connect(self.add_empty_column)
		self.ui.actionDelete_Col.triggered.connect(self.remove_column_dialog)
		self.ui.actionDelete_Row.triggered.connect(self.remove_row_dialog)

		self.ui.actionClear.triggered.connect(self.clear_tree)
		self.ui.actionPopulate_from_set.triggered.connect(self.populate_from_set)
		self.ui.actionDEBUG.triggered.connect(self.DEBUG)
		self.ui.typesPushButton.clicked.connect(self.edit_types)
		self.ui.namesPushButton.clicked.connect(self.edit_names)
		self.ui.actionSave.triggered.connect(self.save_data)
		self.ui.actionLoad.triggered.connect(self.load_data)

		#zadanie1
		self.ui.actionDyskretyzacjaPRD.triggered.connect(self.dyskretyzacjaPRD)
		self.ui.actionDyskretyzacjaNK.triggered.connect(self.dyskretyzacjaNK)
		self.ui.actionStandaryzacja.triggered.connect(self.standaryzacja)
		self.ui.actionOdstajace3x.triggered.connect(self.odstajace3x)
		self.ui.actionOdstajaceProcent.triggered.connect(self.odstajaceProcent)
		self.ui.actionNormalizacja.triggered.connect(self.normalizacja)
		self.ui.actionWykres2D.triggered.connect(self.Wykres2D)
		self.ui.actionWykres3D.triggered.connect(self.Wykres3D)
		#self.ui.actionSprawdzOcene.triggered.connect(self.SprawdzOceneKlasyfikacji)
		#self.ui.actionSklasyfikujObiekt.triggered.connect(self.SklasyfikujObiekt)
		self.ui.actionMetryk_Euklidesow.triggered.connect(self.SprawdzEuklidesowa)
		self.ui.actionMetryk_Miejsk.triggered.connect(self.SprawdzMiejska)
		self.ui.actionMetryk_Mahalanobisa.triggered.connect(self.SprawdzMahalanobisa)
		self.ui.actionMetryk_Euklidesow_2.triggered.connect(self.KlasyfikujEuklidesowa)
		self.ui.actionMetryk_Miejsk_2.triggered.connect(self.KlasyfikujMiejska)
		self.ui.actionMetryk_Mahalanobisa_2.triggered.connect(self.KlasyfikujMahalanobisa)
		self.ui.actionMetoda_K_Srednich.triggered.connect(self.Metoda_K_Srednich)
		self.ui.actionMetoda_K_Srednich_optymalne_K.triggered.connect(self.Metoda_K_Srednich_search)

		self.TypToS = TypToS
		self.SToTyp = SToTyp
Esempio n. 33
0
 def __init__(self):
     QtGui.QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     
     self.ui.btnInputCellFile.clicked.connect(self.btnInputCellFile_Clicked)
     self.ui.btnInputNeighborFile.clicked.connect(self.btnInputNeighborFile_Clicked)
     self.ui.btnGenerateCellFile.clicked.connect(self.btnGenerateCellFile_Clicked)
     self.ui.actionCellDatabaseFileFormat.triggered.connect(self.actionCellDatabaseFileFormat_Clicked)
     self.ui.actionNeighborFileFormat.triggered.connect(self.actionNeighborFileFormat_Clicked)
     self.ui.actionAbout.triggered.connect(self.actionAbout_Clicked)
Esempio n. 34
0
 def __init__(self):
     super(interface_window, self).__init__()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     #self.ui.pushButton.clicked.connect(self.flashSplash)
     self.ui.pushButton.released.connect(self.ProcessorParsing)
     #self.ui.pushButton_4.clicked.connect(self.flashSplash)
     self.ui.pushButton_4.released.connect(self.VideocardParsing)
     #self.ui.pushButton_3.clicked.connect(self.flashSplash)
     self.ui.pushButton_3.released.connect(self.Ram_DIMMParsing)
     self.ui.ViewModeBtn.clicked.connect(self.View)
     self.list_get_requests = [
         "https://www.dns-shop.ru/catalog/17a89aab16404e77/videokarty/",
         "https://www.dns-shop.ru/catalog/17a899cd16404e77/processory/",
         "https://www.dns-shop.ru/catalog/17a89a3916404e77/operativnaya-pamyat-dimm/"
     ]
     self.ViewMode_ = None
     self.data_about_proc = list()
     self.data_about_gp = list()
     self.data_about_ram = list()
     dir = os.path.abspath(os.curdir)
Esempio n. 35
0
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.ui.startwifi.clicked.connect(self.startwifi_clicked)
		self.ui.stopwifi.clicked.connect(self.stopwifi_clicked)
		self.ui.exitapp.clicked.connect(self.exitapp_clicked)

		self.ui.actionAbout.triggered.connect(self.actionAbout_triggered)
		self.ui.popAboutDailog = aboutDialog()

		self.ui.stopwifi.setEnabled(False)
Esempio n. 36
0
class Main(QtGui.QMainWindow):
	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.ui.startwifi.clicked.connect(self.startwifi_clicked)
		self.ui.stopwifi.clicked.connect(self.stopwifi_clicked)
		self.ui.exitapp.clicked.connect(self.exitapp_clicked)

		self.ui.actionAbout.triggered.connect(self.actionAbout_triggered)
		self.ui.popAboutDailog = aboutDialog()

		self.ui.stopwifi.setEnabled(False)

	def startwifi_clicked(self):
		ssid = str(self.ui.wifiname.text())
		password = str(self.ui.wifipassword.text())

		if ssid == '' or password == '':
			self.ui.status.setText("Invalid Name & Password")
		else:
			os.system('netsh wlan set hostednetwork mode=allow ssid='+ssid+' key='+password+'')
			os.system('netsh wlan start hostednetwork')
			self.ui.status.setText("Hotspot Started")
			self.ui.startwifi.setEnabled(False)
			self.ui.stopwifi.setEnabled(True)


	def stopwifi_clicked(self):
		self.ui.startwifi.setEnabled(True)
		self.ui.stopwifi.setEnabled(False)
		os.system('netsh wlan stop hostednetwork')
		self.ui.status.setText("Hotspot Stopped")

	def exitapp_clicked(self):
		self.close()

	def actionAbout_triggered(self):
		self.ui.popAboutDailog.show()
Esempio n. 37
0
 def __init__(self):
     QtGui.QWidget.__init__(self)
     global dir2, dir3, dir1
     dir1 = "/home/slotlocker/random/"
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.listWidget.setMaximumWidth(80)
     self.ui.listWidget.setMaximumHeight(200)
     self.ui.listWidget.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
     self.setWindowTitle("Browse/Edit Diary")
     
     dir_list = os.listdir(dir1)
     self.ui.listWidget.addItems(dir_list)
     self.ui.listWidget.clicked.connect(self.step2)
Esempio n. 38
0
class Window(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        highlight = syntax.PythonHighlighter(self.ui.editor.document())
        self.ui.editor.document().setDefaultFont(QFont("Monospace", 10, QFont.Normal))

        self.connect(self.ui.actionRun, SIGNAL("triggered()"), self.on_run_program)

    def load(self, fd):
        self.ui.editor.setPlainText(fd.read())

    def currentText(self):
        return self.ui.editor.toPlainText()

    def on_run_program(self):
        out = StringIO()
        runner = PythonRunner(out)
        runner.execute(str(self.currentText()))
        out.seek(0)
        self.ui.console.insertPlainText(out.read())
Esempio n. 39
0
 def __init__(self, parent=None):
     #Loads of BORING UI setup code!!
     QtGui.QMainWindow.__init__(self, parent)
     self.ui=Ui_MainWindow()
     self.ui.setupUi(self)
     self.loadSettings()
     self.initPD()
     self.initFTD()
     self.ui.listView.setModel(self.peer_container)
     self.peerSelection=self.ui.listView.selectionModel()
     self.ui.tableView.setModel(self.proxy)
     self.fileSelection=self.ui.tableView.selectionModel()
     self.dloadMgr=model.DownloadWidgetManager(self.ui.tableWidget)
     self.tableHeaderResize()
     self.initConnection()    
Esempio n. 40
0
class ShipHolderApplication(QMainWindow):
    def __init__(self, parent=None):
        super (ShipHolderApplication,self).__init__(parent)
        self.createWidgets()
        self.connectActions()
        #item to print
        self.printNo = 0
        
        #Stock bibitem a ecrire dans le fichier
        self.towrite = []
        self.lastfile = ""
        
    def createWidgets(self):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
    def connectActions(self):
        self.ui.pushButton.connect(self.ui.pushButton,SIGNAL('clicked()'), self.Searching)
        self.ui.pushButton_2.connect(self.ui.pushButton_2,SIGNAL('clicked()'),app,SLOT('quit()'))
        self.ui.pushButton_3.connect(self.ui.pushButton_3,SIGNAL('clicked()'),app,SLOT('quit()'))
        self.ui.pushButton_4.connect(self.ui.pushButton_4,SIGNAL('clicked()'),app,SLOT('quit()'))
        self.ui.pushButton_5.connect(self.ui.pushButton_5,SIGNAL('clicked()'),app,SLOT('quit()'))

    def Searching(self):
        title = str(self.ui.lineEdit.text())
        author = str(self.ui.lineEdit_2.text())
        print author
        #print str(MyString)
        self.printNo = 0
        mySearch = TheSearch()
        mySearch.ToSearch(title.encode("utf-8"),author.encode("utf-8"))
        self.toprint = mySearch.DoSearch()

        #self.labelVariable.set(self.toprint[0].EntryToString())
        #print self.toprint[0].EntryToString())
        self.totalnumber = len(self.toprint)
Esempio n. 41
0
 def __init__(self):
     QtGui.QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     
     self.connect(self.ui.btnZapis, SIGNAL("clicked()"), self.btnZapis_Clicked)
     self.connect(self.ui.btnSmazat, SIGNAL("clicked()"), self.btnSmazat_Clicked)
     self.connect(self.ui.btnPrepocitat, SIGNAL("clicked()"), self.btnPrepocitat_Clicked)
     #self.connect(self.ui.tblVypis, SIGNAL(""), self.tableWidget_Pressed)
     
     # Define classes of widgets
     self.mysql = Mysql()
     self.vypis = Vypis(self.ui.tblVypis)        
     self.matplot = MatPlot(self.ui.matplot)
     
     # Do start functions
     self.starting()
Esempio n. 42
0
	def __init__(self):
		
		QtGui.QMainWindow.__init__(self)

		# UI created by QT Designer 
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		# default value = 5 m
		self.launchAlt = 5 

		#Set up option parsing to get connection string
		import argparse  
		parser = argparse.ArgumentParser(description='Tracks GPS position of your computer (Linux only). Connects to SITL on local PC by default.')
		parser.add_argument('--connect', help="vehicle connection target.")
		args = parser.parse_args()

		self.connection_string = args.connect
		self.sitl = None

		#Start SITL if no connection string specified
		if not self.connection_string:
			import dronekit_sitl
			self.sitl = dronekit_sitl.start_default()
			self.connection_string = self.sitl.connection_string()

		# Connect to the Vehicle
		print 'Connecting to vehicle on: %s' % self.connection_string
		self.vehicle = connect(self.connection_string, wait_ready=True)

		# Display Flight Mode
		self.updateFlightModeGUI(self.vehicle.mode)
		self.addObserverAndInit(
			'mode'
			,lambda vehicle,name,mode: self.updateFlightModeGUI(mode) ) 

		# Display Location Info
		self.updateLocationGUI(self.vehicle.location)
		self.addObserverAndInit(
			'location'
			,lambda vehicle, name, location: self.updateLocationGUI(location) )
Esempio n. 43
0
 def createWidgets(self):
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
Esempio n. 44
0
File: CC02.py Progetto: rouxinol/Lab
class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        
        #connect to run button
        
        QtCore.QObject.connect(self.ui.runButton, QtCore.SIGNAL(("clicked()")), self.handleCalculate)
        QtCore.QObject.connect(self.ui.plotBtn,   QtCore.SIGNAL(("clicked()")), self.plotData)
      #  QtCore.QObject.connect(self.ui.plotBtn,   QtCore.SIGNAL(("clicked()")), self.handleCalculate)
       
       
#    def plotData(self):
#        x, y = rand(2, 30)
#        self.ui.plotWidget.canvas.ax.plot(x, y, 'o')
#        self.ui.plotWidget.canvas.draw()
 
    def plotData(self):
        self.handleCalculate()
        w   = float(str(self.ui.wEdit.text()))
        s   = float(str(self.ui.sEdit.text()))
        t   = float(str(self.ui.tEdit.text()))
        h   = float(str(self.ui.hEdit.text()))
        l   = float(str(self.ui.lEdit.text()))
        e   = float(str(self.ui.eEdit.text()))
        rho = float(str(self.ui.rhoEdit.text()))
        tc  =  float(str(self.ui.tcEdit.text()))
        ck  = float(str(self.ui.ccEdit.text()))
        Tg  = float(str(self.ui.tgEdit.text()))
        ck = []
        Ql = []
        for n in range(0,len(Ccap)):
           # print 'n = ', n
           # print 'Ccap = ', Ccap[n]
            
            ck.append(Ccap[n])
           # print 'ck=  ', ck[n] eeff,l0,Lk,Ll,Cl,f0,alfa, z0,L,C,R,F0,Qi,Rstar,Cstar,fstar,Qext,
            
            Qload = cal(w,s,t,h,l,e,rho,tc,ck[n],Tg)[17] 
            Ql.append(Qload)
            
        savetxt('Ql.txt',Ql)
            #print 'end'
        
        self.ui.plotWidget.canvas.ax.plot(ck, Ql, marker='o', linestyle='-', color='r')
#            axes[0].plot(ng_vec, energies[:,n])
            #self.ui.plotWidget.canvas.ax.set_ylim(-10, ymax[0])
        self.ui.plotWidget.canvas.ax.set_yscale('log')
        self.ui.plotWidget.canvas.ax.set_xscale('log')
        self.ui.plotWidget.canvas.ax.set_xlabel(r'$C_c$', fontsize=12)
        self.ui.plotWidget.canvas.ax.set_ylabel(r'$Q_l$', fontsize=12)
            
            #self.ui.plotWidget.canvas.ax.plot(x, y, 'o')
       #     self.ui.plotWidget.canvas.draw()
        self.ui.plotWidget.canvas.draw()

### TEst
# #       def newWindow(self):
#        self.myOtherWindow = Plot_Widget()
#        self.myOtherWindow.show()
#        #app = QApplication(sys.argv)
#        #plot = Plot_Widget()#data2plot,  varDict = totaldict)
#        #plot.show()
#         #sys.exit(app.exec_()) 
### TEST


            
    def handleCalculate(self):
        w   = float(str(self.ui.wEdit.text()))
        s   = float(str(self.ui.sEdit.text()))
        t   = float(str(self.ui.tEdit.text()))
        h   = float(str(self.ui.hEdit.text()))
        l   = float(str(self.ui.lEdit.text()))
        e   = float(str(self.ui.eEdit.text()))
        rho = float(str(self.ui.rhoEdit.text()))
        tc  =  float(str(self.ui.tcEdit.text()))
        ck  = float(str(self.ui.ccEdit.text()))
        Tg  = float(str(self.ui.tgEdit.text()))
        #print ck
        
        
        
        
        eeff,l0,Lk,Ll,Cl,f0,alfa, z0,L,C,R,F0,Qi,Rstar,Cstar,fstar,Qext,Qload = cal(w,s,t,h,l,e,rho,tc,ck,Tg)
        #print ans
        self.ui.eeffLabel.setText( str("%.3f" % (eeff)))
        self.ui.lambdaLabel.setText( str("%.3E" % (l0)))
        self.ui.kineticLabel.setText('%.3E H/m' % (Lk)) 
        self.ui.alfaLabel.setText( str("%.3E" % (alfa)))
        
        self.ui.fEdit.setText(str("%.3E" % (f0)))
        self.ui.llEdit.setText(str("%.3E" % ((Ll))))
        self.ui.clEdit.setText(str("%.3E" % ((Cl))))
        self.ui.z0Edit.setText(str("%.2f" % ((z0))))
        
        self.ui.LEdit.setText(str("%.2E" % ((L))))
        self.ui.CEdit.setText(str("%.2E" % ((C))))
        self.ui.REdit.setText(str("%.2E" % ((R))))
        self.ui.f0Edit.setText(str("%.2E" % ((F0))))
        self.ui.qiEdit.setText(str("%.2f" % ((Qi/1e3))))
        self.ui.qeEdit.setText(str("%.2f" % ((Qext/1e3))))
        self.ui.qlEdit.setText(str("%.2f" % ((Qload/1e3))))
        self.ui.frEdit.setText(str("%.3E" % ((fstar))))
Esempio n. 45
0
class Readdialog(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        global dir2, dir3, dir1
        dir1 = "/home/slotlocker/random/"
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.listWidget.setMaximumWidth(80)
        self.ui.listWidget.setMaximumHeight(200)
        self.ui.listWidget.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
        self.setWindowTitle("Browse/Edit Diary")
        
        dir_list = os.listdir(dir1)
        self.ui.listWidget.addItems(dir_list)
        self.ui.listWidget.clicked.connect(self.step2)
    def step2(self):
        selected_item = self.ui.listWidget.selectedItems()
        dir_selected = selected_item[0].text()
        global dir2
        dir2 = dir1 + dir_selected + "/"
        global column2
        column2 = QtGui.QListWidget()
        column2.setAlternatingRowColors(True)
        column2.setMaximumWidth(80)
        column2.setMaximumHeight(200)
        column2.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
        self.ui.gridLayout.addWidget(column2,0,1)
        dir_list = os.listdir(dir2)
        column2.addItems(dir_list)
        column2.clicked.connect(self.step3)
    def step3(self):
        selected_item = column2.selectedItems()
        dir_selected = selected_item[0].text()
        global dir3
        dir3 = dir2 + dir_selected + "/"
        global column3
        column3 = QtGui.QListWidget()
        column3.setAlternatingRowColors(True)
        column3.setMaximumWidth(80)
        column3.setMaximumHeight(200)
        column3.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
        self.ui.gridLayout.addWidget(column3,0,2)
        dir_list = os.listdir(dir3)
        column3.addItems(dir_list)
        column3.clicked.connect(self.step4)
    def step4(self):
        global textarea1, textarea2
        textarea1 = QtGui.QTextEdit()
        textarea2 = QtGui.QTextEdit()
        self.ui.gridLayout.addWidget(textarea1,0,3)
        textarea1.setMinimumWidth(300)
        textarea1.setMinimumHeight(200)
        textarea1.setMaximumHeight(200)
        self.ui.gridLayout.setColumnStretch(3,100)
        self.ui.gridLayout.addWidget(textarea2,1,0,1,4)
        textarea2.setMinimumHeight(320)
        selected_item = column3.selectedItems()
        global file_selected
        file_selected = selected_item[0].text()
        file_path = dir3 + file_selected + "/diary.html"
        file_pointer = open(file_path, 'r')
        file_contents = file_pointer.read()
        textarea2.setText(file_contents)
        file_pointer.close()
        textarea2.setAcceptRichText(True)
        textarea2.setReadOnly(True)
        global title_file
        title_file = dir3 + file_selected + "/title.txt"
        file_pointer = open(title_file, "r")
        title = file_pointer.read()
        file_pointer.close()

        textarea1.setText(title)
        

        
        global button1
        button1 = QtGui.QPushButton("Edit")
        self.ui.gridLayout.addWidget(button1, 2,2)
        button1.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)
        global button2
        button2 = QtGui.QPushButton("Save")
        self.ui.gridLayout.addWidget(button2, 2,3)
        button2.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)
        button2.setEnabled(False)
        button1.pressed.connect(self.edit)

    def edit(self):
            button1.setEnabled(False)
            textarea2.setReadOnly(False)
            textarea2.setAcceptRichText(True)
            button2.setEnabled(True)

            button2.pressed.connect(self.save_exit)

    def save_exit(self):
        file_path = dir3+ file_selected + "/" + "diary.html"
        file_pointer = open(file_path,"w")
        file_contents = textarea2.toHtml()
        file_pointer.write(file_contents)
        file_pointer.close()
        button1.setEnabled(True)
        button2.setEnabled(False)
Esempio n. 46
0
class Main(QtGui.QMainWindow):
    
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.connect(self.ui.btnZapis, SIGNAL("clicked()"), self.btnZapis_Clicked)
        self.connect(self.ui.btnSmazat, SIGNAL("clicked()"), self.btnSmazat_Clicked)
        self.connect(self.ui.btnPrepocitat, SIGNAL("clicked()"), self.btnPrepocitat_Clicked)
        #self.connect(self.ui.tblVypis, SIGNAL(""), self.tableWidget_Pressed)
        
        # Define classes of widgets
        self.mysql = Mysql()
        self.vypis = Vypis(self.ui.tblVypis)        
        self.matplot = MatPlot(self.ui.matplot)
        
        # Do start functions
        self.starting()
        
    def starting(self):
        # Write out data to table widget
        self.vypis.writeOutData()
        
        # Plot the cashflow
        x = self.vypis.get_allCash()
        self.matplot.plot(x)
        
        # Populate database
#         data = self.vypis.get_csvData()
#         self.mysql.populate(data)
           
        
    def reload(func):
        def magic(self):
            func(self)
            self.matplotCashflow2()
        return magic
            
    #@reload
    def btnSmazat_Clicked(self):
        row = self.ui.tblVypis.currentRow()
        self.ui.tblVypis.removeRow(row)
        # is needed to recount all items
        self.vypis.recount()
       
    def btnPrepocitat_Clicked(self):
        self.vypis.recount()
    
    def countCsvFile(self):
        with open('cashflow.csv', 'r') as f:
            rowCount = 0
            for lastrow in csv.reader(f):
                rowCount += 1
            return rowCount
        
    def get_lastRow(self):
        with open('cashflow.csv', 'r') as f:
            lastrow = None
            self.rowCount = 0
            for lastrow in csv.reader(f):
                self.rowCount += 1
                pass
            return lastrow
             
    def btnZapis_Clicked(self):
        with open('cashflow.csv', 'a') as f:
            writer = csv.writer(f, delimiter=';', lineterminator='\n')
            
            date = time.strftime("%d:%m",time.gmtime(CZ_TIME))
            hour = time.strftime("%H:%M",time.gmtime(CZ_TIME))
            # current money
            money = int(self.get_lastRow()[0].split(";")[-2])
            predmet = self.ui.txtPredmet.text()
            pohyb = int(self.ui.spinBoxPohyb.text())
            writer.writerow([CZ_TIME, date, hour, predmet, pohyb, money + pohyb, None])
        self.vypis.writeOutData()
Esempio n. 47
0
class UIController(QtGui.QMainWindow):
    def __init__(self, parent=None):
        #Loads of BORING UI setup code!!
        QtGui.QMainWindow.__init__(self, parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.loadSettings()
        self.initPD()
        self.initFTD()
        self.ui.listView.setModel(self.peer_container)
        self.peerSelection=self.ui.listView.selectionModel()
        self.ui.tableView.setModel(self.proxy)
        self.fileSelection=self.ui.tableView.selectionModel()
        self.dloadMgr=model.DownloadWidgetManager(self.ui.tableWidget)
        self.tableHeaderResize()
        self.initConnection()    

    def listCtxtMenu(self, point):
        if not self.peerSelection.hasSelection():
            return
        menu=QtGui.QMenu(parent=self.ui.listView)
        menu.addAction(self.ui.actionExplore)
        menu.addAction(self.ui.actionBlacklistPeer)
        menu.addAction(self.ui.actionDeleteIP)
        menu.exec_(self.ui.listView.mapToGlobal(point))

    def fileCtxtMenu(self, point):
        if not self.fileSelection.hasSelection():
            return
        menu=QtGui.QMenu(parent=self.ui.tableView)
        menu.addAction(self.ui.actionDownload)
        menu.addAction(self.ui.actionDownloadAs)
        menu.exec_(self.ui.tableView.mapToGlobal(point))
    
    def initConnection(self):
        self.ui.actionDiscover.triggered.connect(self.setDiscover)
        self.ui.actionAddIP.triggered.connect(self.manAddIP)
        self.ui.actionClearBlacklist.triggered.connect(self.resetBan)
        self.ui.actionBlacklistPeer.triggered.connect(self.blacklistPeer)
        self.ui.actionExplore.triggered.connect(self.explorePeer)
        self.peer_container.updated.connect(self.updateHT)
        self.ui.listView.customContextMenuRequested.connect(self.listCtxtMenu)
        self.ui.tableView.customContextMenuRequested.connect(self.fileCtxtMenu)
        self.ui.radioButton.toggled.connect(self.filterIP)
        self.ui.radioButton_2.toggled.connect(self.filterIP)
        self.ui.lineEdit.textChanged.connect(self.proxy.setFilterFixedString)
        self.peerSelection.selectionChanged.connect(self.filterIP)
        self.ui.tableView.doubleClicked.connect(self.downloadAction)
        self.ui.actionDownload.triggered.connect(self.downloadAction)
        self.ui.actionDownloadAs.triggered.connect(self.downloadAsAction)
        self.ui.actionDeleteIP.triggered.connect(self.deletePeer)

    def resetBan(self):
        QtGui.QMessageBox.information(self, 'Blacklist Cleared', 'List of blacklisted peers has been reset')
        self.peer_container.clearBlacklist()

    def filterIP(self):
        if not self.ui.radioButton.isChecked():
            addr=self.getSelectedPeer()
            self.file_model.selectIP(addr)
        else:
            self.file_model.selectIP(None)

    def initPD(self):
        self.busy_peers=[]
        self.peer_container=model.PeerContainer()
        mcast_addr=(self.settings['MULTICAST_IP'], int(self.settings['MULTICAST_PORT']))
        self.pd=PDModule(mcast_addr, self.settings['NAME'], self.peer_container)

    def initFTD(self):
        self.finxr=indexer.FileIndexer(self.settings['INDEXER_PATH'])
        self.dfct=daemon.IFFactory(self.finxr)
        reactor.listenTCP(int(self.settings['DAEMON_PORT']),self.dfct)
        self.file_model=model.FileIndexModel()
        self.proxy = model.TxtMapSortProxyModel(self, model.FILE_LIST_MAP)
        self.proxy.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.proxy.setSourceModel(self.file_model)


    def manAddIP(self):
        ipaddr, ok = QtGui.QInputDialog.getText(self, 'Manual IP Entry', 'IP address')
        if ok:
            ipaddr=str(ipaddr)
            if not is_valid_ip(ipaddr):
                QtGui.QMessageBox.warning(self, 'Input Error', 'Invalid IP address')
                return
            rc=self.peer_container.addAddr(ipaddr)
            if rc == 1:
                QtGui.QMessageBox.information(self, 'Address Exception', 'IP is already present')
            elif rc == 2:
                QtGui.QMessageBox.warning(self, 'Address Exception', 'IP is blacklisted')

    def loadSettings(self):
        re_cd, self.settings=load_settings_from_file(SETTINGS_FILE)
        if re_cd:
            self.firstRun()
        save_settings_to_file(self.settings, SETTINGS_FILE)

    def deletePeer(self):
        addr=self.getSelectedPeer()
        self.peer_container.removeAddr(addr)

    def isValidConfig(self):
        return is_name(self.settings['NAME']) and is_dir_path(self.settings['INDEXER_PATH'])

    def downloadAction(self):
        name, addr, fHash=self.getSelectedFile()
        option=QtGui.QMessageBox.question(self, 'Download file', 'Confirm download {0}'\
            .format(name), QtGui.QMessageBox.No | QtGui.QMessageBox.Yes)
        if option == QtGui.QMessageBox.Yes:
            sv_fObj=self.quickSaveFile(name)
            if sv_fObj:
                self.downloadFile(name, addr, fHash, sv_fObj)

    def downloadFile(self, name, addr, fHash, fObj):
        d=Deferred()
        fFact=probe.FTFactory(fHash, fObj, d)
        d.addCallback(self.makeDL, name)
        d.addErrback(self.logError, addr)
        reactor.connectTCP(addr, 17395, probe.FTFactory(fHash, fObj, d))

    def makeDL(self, FTProt, name):
        idx=self.dloadMgr.addFTProtocol(name, FTProt)
        FTProt.def_obj.addCallback(self.removeDL, idx)
        FTProt.def_obj.addErrback(self.removeDL, idx)

    def removeDL(self, arg, idFT):
        logging.info(arg)
        self.dloadMgr.doneFT(idFT)

    def downloadAsAction(self):
        name, addr, fHash=self.getSelectedFile()
        sv_fObj=self.saveFilePrompt(name)
        if sv_fObj:
            self.downloadFile(name, addr, fHash, sv_fObj)

    def saveFilePrompt(self, name):
        savePath=str(QtGui.QFileDialog.getSaveFileName(self, 'Choose a destination file', \
            os.path.join(self.finxr.path, 'tmp.'+name.split('.')[-1])))
        if savePath:
            return open(savePath, 'wb')
        return None

    def quickSaveFile(self, saveName):
        try:
            sv_fObj=None
            sv_fObj=self.finxr.saveFile(saveName)
        except:
            option=QtGui.QMessageBox.warning(self, 'File overwrite', 'File exits. Overwrite?', \
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.Abort | QtGui.QMessageBox.Save)
            if option == QtGui.QMessageBox.Yes:
                return self.finxr.saveFile(saveName, True)
            elif option == QtGui.QMessageBox.Save:
                return self.saveFilePrompt(saveName)
        return sv_fObj

    def firstRun(self):
        self.settings=DEFAULT_SETTINGS
        frDialog=QtGui.QDialog(parent=self)
        frDialog.ui=first_run.Ui_Dialog()
        frDialog.ui.setupUi(frDialog)
        frDialog.ui.lineEdit.setText(self.settings['NAME'])
        def folderHandler():
            shareFolder=str(QtGui.QFileDialog.getExistingDirectory(frDialog, \
                'Choose a directory to share'))
            frDialog.ui.lineEdit_2.setText(shareFolder)
            self.settings['INDEXER_PATH']=shareFolder
        frDialog.ui.pushButton.clicked.connect(folderHandler)
        frDialog.exec_()
        self.settings['NAME']=str(frDialog.ui.lineEdit.text())
        if not self.isValidConfig():
            QtGui.QMessageBox.critical(self,'Settings Error','Invalid Configuration')
            logging.critical('Invalid Config')
            exit_reactor(1)

    def updateHT(self):
        active_peers=self.peer_container.getAddrList()
        explored_peers=self.file_model.getAddrList()
        for item in explored_peers:
            if not item in active_peers:
                self.file_model.delIndex(item)
        for item in active_peers:
            if not item in explored_peers:
                self.discoverPeer(item)

    def gotHT(self, fileHT, addr):
        self.busy_peers.remove(addr)
        self.file_model.updateIndex(addr, fileHT)

    def discoverPeer(self, addr):
        if addr in self.busy_peers:
            return
        d=Deferred()
        d.addCallback(self.gotHT, addr)
        d.addErrback(self.logError, addr)
        self.busy_peers.append(addr)
        reactor.connectTCP(addr, 17395, probe.FHFactory(d))
    
    def logError(self, reason, addr, role):
        if addr in self.busy_peers:
            self.busy_peers.remove(addr)
        logging.error('Error in role {2} connecting to {0} : {1}'\
            .format(addr, str(reason), str(role)))

    def setDiscover(self):
        self.pd.setEnable(self.ui.actionDiscover.isChecked())

    def getSelectedPeer(self):
        if not self.peerSelection.hasSelection():
            return ''
        sIdx=self.peerSelection.selectedRows()[0]
        return str(self.peer_container.itemFromIndex(sIdx).text())

    def getSelectedFile(self):
        if not self.fileSelection.hasSelection():
            return None
        return [str(self.file_model.itemFromIndex(self.proxy.mapToSource(\
                self.fileSelection.selectedRows(column=idx)[0])).text()) for idx in [0,2,3]]

    def explorePeer(self):
        addr=self.getSelectedPeer()
        self.discoverPeer(addr)

    def blacklistPeer(self):
        addr=self.getSelectedPeer()
        self.peer_container.blacklistAddr(addr)

    def tableHeaderResize(self):
        header_crtl=self.ui.tableView.horizontalHeader()
        header_crtl.setResizeMode(0, QtGui.QHeaderView.Stretch)
        header_crtl.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
        header_crtl.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
        header_crtl=self.ui.tableWidget.horizontalHeader()
        header_crtl.setResizeMode(0, QtGui.QHeaderView.Stretch)
        header_crtl.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
        header_crtl.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
Esempio n. 48
0
 def __init__(self):
     self.cache_window = QtGui.QMainWindow()
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self.cache_window)
     self.cache_window.show()
Esempio n. 49
0
File: main.py Progetto: miodeq/swd
class Main(QtGui.QMainWindow):
	def DEBUG(self):
		self.recast_data()
		#self.print_data()
		#self.refresh_data()
		#self.edit_types()
	def remove_row(self,i):
		self.zb.usun_obserwacja(i)
		self.populate_from_set()
	def remove_col(self,i):
		self.zb.usun_zmienna(int(i))
		self.populate_from_set()
	
	def print_data(self):
		cols = self.ui.treeWidget.columnCount()
		rows = self.ui.treeWidget.topLevelItemCount()
		zb = Zbior()
		root = self.ui.treeWidget.invisibleRootItem()
		child_count = root.childCount()
		lista = []
		for i in range(child_count):
				item = root.child(i)
				lista.append([u'%s'%(item.text(i)) for i in range(cols)])
		for i in lista:
				print i
		#for i in range(cols):
				#print self.ui.treeWidget.
		#print cols,rows

	def recast_data(self):
		for i in range(len(self.zb.typy)):
				self.zb.rzutuj(self.zb.typy[i],i)
		

	def get_translated(self,string):
		return QtGui.QApplication.translate("MainWindow", string, None, QtGui.QApplication.UnicodeUTF8)
	def populate_from_set(self):
		zb = self.zb
		if(not zb):
				print "Zbior not set"
		self.clear_tree()
		for i in zb.kolumny:
				self.add_column(i)
		for i in zb.lista:
				self.add_row(i)
		text = ",".join([self.TypToS[str(x)] for x in zb.typy])
		self.ui.typesLineEdit.setText(text)
		col_num = len(zb.kolumny)
		text = self.get_translated('')
		for i in range(col_num-1):
			text+=self.get_translated(zb.kolumny[i]+',')
		text+=self.get_translated(str(zb.kolumny[col_num-1]))
		
		#text = self.get_translated(',').join([self.get_translated(str(x)) for x in zb.kolumny])
		#text = ",".join(zb.kolumny)
		self.ui.namesLineEdit.setText(text)

	def set_zbior(self,zb):
		self.zb = zb;

	def clear_tree(self):
		#self.ui.treeWidget = QtGui.QTreeWidget(self.ui.centralwidget)
		self.ui.treeWidget.clear()
		self.ui.treeWidget.setColumnCount(0)

	def edit_types(self):
		types = [self.SToTyp[str(x).strip()] for x in self.ui.typesLineEdit.text().split(',')]
		if(len(types) != len(self.zb.typy)):
				print "can't cast! different size of types"
		else:
				self.zb.typy = types
				for i in range(len(types)):
					self.zb.rzutuj(types[i],i)
				#for i in range(len(types)):
					#self.zb.rzutuj(types[i],i)
				self.populate_from_set()

	def edit_names(self):
		names = [unicode(x).strip() for x in self.ui.namesLineEdit.text().split(',')]
		if(len(names) != len(self.zb.kolumny)):
				print "can't cast! different size of types"
		else:
				self.zb.kolumny = names
				self.populate_from_set()


	#def add_row(self):
		#add_row(None)
		
	def add_row(self,row_data):
		item = QtGui.QTreeWidgetItem(self.ui.treeWidget)
		if(row_data):
				for i in xrange(len(row_data)):
					text = QtGui.QApplication.translate("MainWindow", str(row_data[i]), None, QtGui.QApplication.UnicodeUTF8)
					item.setText(i,text)
		item.setFlags(QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEditable|QtCore.Qt.ItemIsDragEnabled|QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)

	def add_empty_column(self):
		text, ok = QtGui.QInputDialog.getText(self, 'Nowa kolumna', 'Podaj nazwe')
		if ok:
				self.add_column(str(text))
	def remove_column_dialog(self):
		text, ok = QtGui.QInputDialog.getText(self, 'Usun kolumne', 'Podaj numer kolumny')
		if ok:
				self.remove_col(int(text))
	def remove_row_dialog(self):
		text, ok = QtGui.QInputDialog.getText(self, 'Usun wiersz', 'Podaj numer wiersza')
		if ok:
				self.remove_row(int(text))
	def add_column(self,nazwa):
		idx = self.ui.treeWidget.columnCount()
		self.ui.treeWidget.headerItem().setText(idx, QtGui.QApplication.translate("MainWindow", nazwa, None, QtGui.QApplication.UnicodeUTF8))
	def save_data(self):
		fname = QtGui.QFileDialog.getSaveFileName(self,'Zapisz plik','.')
		if(not fname):
				return
		separ, ok = QtGui.QInputDialog.getText(self, 'Separator', 'Podaj separator (\\t dla tabulatora)')
		if not ok:
				return
		kol, ok = QtGui.QInputDialog.getText(self, 'Nazwy kolumn', 'Zapisac nazwy kolumn ? [T/N]')
		if not ok:
				return
		if(str(kol).upper()=="T"):
			  kol=True
		else:
			  kol=False
		typy, ok = QtGui.QInputDialog.getText(self, 'Nazwy typow', 'Zapisac nazwy typów ? [T/N]')
		if not ok:
				return
		if(separ=='\\t'):separ='\t'
		if(str(typy).upper()=="T"):
			  typy=True
		else:
			  typy=False
		self.zb.zapisz(fname,separ,kol,typy)
		#pass
	def load_data(self):
		zb = Zbior()
		fname = QtGui.QFileDialog.getOpenFileName(self,'Otworz plik','.')
		if(not fname):
				return
		sep, ok = QtGui.QInputDialog.getText(self, 'Separator', 'Podaj separator (\\t dla tabulatora)')
		if not ok:
				return
		ile, ok = QtGui.QInputDialog.getText(self, 'Pomijanie wierszy', 'Ile wierszy pominac ?')
		if not ok:
				return
		kolumny, ok = QtGui.QInputDialog.getText(self, 'Nazwy kolumn', 'Czu 0 wiersz to nazwy kolumn [T/N] ?')
		if not ok:
				return
		typy, ok = QtGui.QInputDialog.getText(self, 'Nazwy typow', 'Czu 1 wiersz to nazwy typu [T/N] ?')
		if not ok:
				return
		if(sep=='\\t'):sep='\t'
		if(str(kolumny).upper()=='T'):
				kolumny = True
		else:
				kolumny = False
				
		if(str(typy).upper()=='T'):
				typy = True
		else:
				typy = False

		zb.wczytaj(fname,sep,int(ile),kolumny,typy)
		self.zb = zb
		self.populate_from_set()
		if(typy==True):
				print "recasting"
				self.recast_data()
	def dyskretyzacjaPRD(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		n, ok = QtGui.QInputDialog.getText(self, 'N', 'Podaj N:')
		if not ok:
				return
		self.zb.dyskretyzuj(int(kol),int(n))
		self.populate_from_set()
	def dyskretyzacjaNK(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		n, ok = QtGui.QInputDialog.getText(self, 'N', 'Podaj N:')
		if not ok:
				return
		self.zb.dyskretyzuj2(int(kol),int(n))
		self.populate_from_set()
	def standaryzacja(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.standaryzuj(int(kol))
		self.populate_from_set()
	def odstajace3x(self):
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.odchylenie_trzykrotne(int(kol))
		self.populate_from_set()
	def odstajaceProcent(self):
		mi, ok = QtGui.QInputDialog.getText(self, 'Minimum np 0.05', 'Podaj minimum:')
		if not ok:
				return
		mx, ok = QtGui.QInputDialog.getText(self, 'Maksimum np 0.95', 'Podaj maksimum:')
		if not ok:
				return
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.odstajace_procentowo(float(mi),float(mx),int(kol))
		self.populate_from_set()
	def normalizacja(self):
		mi, ok = QtGui.QInputDialog.getText(self, 'Minimum np 0.0', 'Podaj minimum:')
		if not ok:
				return
		mx, ok = QtGui.QInputDialog.getText(self, 'Maksimum np 50.0', 'Podaj maksimum:')
		if not ok:
				return
		kol, ok = QtGui.QInputDialog.getText(self, 'Kolumna', 'Podaj indeks kolumny:')
		if not ok:
				return
		self.zb.normalizuj(float(mi),float(mx),int(kol))
		self.populate_from_set()

	def make_col_list(self,col):
		return [self.zb.lista[i][col] for i in range(len(self.zb.lista))]

	def Wykres2D(self):
		import numpy_demo
		i, ok = QtGui.QInputDialog.getText(self, 'Wektor X', 'Podaj kolumne:')
		if not ok:
				return
		j, ok = QtGui.QInputDialog.getText(self, 'Wektor Y', 'Podaj kolumne:')
		if not ok:
				return
		color, ok = QtGui.QInputDialog.getText(self, 'Kolor', 'Podaj kolumne koloru:')
		if not ok:
				return
		i = int(i)
		j = int(j)
		color = int(color)
		l1 = self.make_col_list(i)
		l2 = self.make_col_list(j)
		l3 = self.make_col_list(color)
		numpy_demo.wykres(l1,l2,l3,self.zb.kolumny[i],self.zb.kolumny[j])
	def Wykres3D(self):
		import numpy_demo
		i, ok = QtGui.QInputDialog.getText(self, 'Wektor X', 'Podaj kolumne:')
		if not ok:
				return
		j, ok = QtGui.QInputDialog.getText(self, 'Wektor Y', 'Podaj kolumne:')
		if not ok:
				return
		k, ok = QtGui.QInputDialog.getText(self, 'Wektor Z', 'Podaj kolumne:')
		if not ok:
				return
		color, ok = QtGui.QInputDialog.getText(self, 'Kolor', 'Podaj kolumne koloru:')
		if not ok:
				return
		i = int(i)
		j = int(j)
		k = int(k)
		color = int(color)
		l1 = self.make_col_list(i)
		l2 = self.make_col_list(j)
		l3 = self.make_col_list(k)
		l4 = self.make_col_list(color)
		numpy_demo.wykres3D(l1,l2,l3,l4,[self.zb.kolumny[i],self.zb.kolumny[j],self.zb.kolumny[k]])
	def SprawdzKlasyfikacje(self, metryka):
		indeksy, ok = QtGui.QInputDialog.getText(self, 'Podaj wektory', 'Podaj kolumny oddzielone przecinkiem np. 4,6,7:')
		if not ok:
				return
		
		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa Decyzyjna', 'Podaj kolumne klasy decyzyjnej:')
		if not ok:
				return

		k, ok = QtGui.QInputDialog.getText(self, 'Sasiedzi', 'Podaj k:')
		if not ok:
				return
		indeksy = [int(i) for i in indeksy.split(',')]
		#metryka = self.zb.metrykaEuklidesowa
		ocena = self.zb.ocenaKlasyfikacji(int(k),metryka,int(klasa), indeksy)
		reply = QtGui.QMessageBox.question(self, 'Podsumowanie',
            "%d z %d Sklasyfikowanych poprawnie (%.2f %%)"%(ocena[0],ocena[1],float(ocena[0])*100./ocena[1]), 
            QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
	def PopupMessage(self,m1,m2):
		QtGui.QMessageBox.question(self, m1, m2, QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok)
		
	def SprawdzEuklidesowa(self):
		self.SprawdzKlasyfikacje(self.zb.metrykaEuklidesowa)
		
	def SprawdzMiejska(self):
		self.SprawdzKlasyfikacje(self.zb.metrykaMiejska)
		
	def SprawdzMahalanobisa(self):
		self.SprawdzKlasyfikacje(self.zb.metrykaMahalanobisa)

	def KlasyfikujEuklidesowa(self):
		self.SklasyfikujObiekt(self.zb.metrykaEuklidesowa)
		
	def KlasyfikujMiejska(self):
		self.SklasyfikujObiekt(self.zb.metrykaMiejska)
		
	def KlasyfikujMahalanobisa(self):
		self.SklasyfikujObiekt(self.zb.metrykaMahalanobisa)

	def SklasyfikujObiekt(self, metryka):
		item_index = self.ui.treeWidget.indexFromItem(self.ui.treeWidget.currentItem()).row()
		if item_index == -1:
			self.PopupMessage("Niepoprawne zaznaczenie", "Prosze najpierw zaznaczyc obiekt z listy.")
		indeksy, ok = QtGui.QInputDialog.getText(self, 'Podaj wektory', 'Podaj kolumny oddzielone przecinkiem np. 4,6,7:')
		if not ok:
				return
		
		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa Decyzyjna', 'Podaj kolumne klasy decyzyjnej:')
		if not ok:
				return

		k, ok = QtGui.QInputDialog.getText(self, 'Sasiedzi', 'Podaj k:')
		if not ok:
				return
		indeksy = [int(i) for i in indeksy.split(',')]

		wynik =  self.zb.klasyfikuj(self.zb.lista[item_index],indeksy, int(klasa), metryka, int(k))
		zapisac, ok = QtGui.QInputDialog.getText(self, 'Zaktualizowac wynik na liscie ?', 'Uzyskano wynik:%s\nCzy chcesz zapisac wynik do obiektu ?[T/N]'%(wynik))
		if not ok:
				return
		if str(zapisac).upper()=="T":
			self.zb.lista[item_index][int(klasa)] = wynik
			self.populate_from_set()

	def Metoda_K_Srednich(self):
		N = None
		k, ok = QtGui.QInputDialog.getText(self, 'K klas', 'Podaj k:')
		if not ok:
			return

		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa decyzyjna', 'Podaj indeks klasy decyzyjnej:')
		if not ok:
			return

		indeksy, ok = QtGui.QInputDialog.getText(self, 'Indeksy Zmiennych', 'Podaj indeksy kolumn oddzielone ",":')
		if not ok:
			return

		indeksy = [int(i) for i in indeksy.split(',')]

		N, ok = QtGui.QInputDialog.getText(self, 'Ilosc iteracji', 'Podaj ilosc iteracji, lub -1 jesli chcesz iterowac az nie bedzie zmian:')
		if not ok:
			return

		N = int(N)

		wynik = self.zb.licz_k_srednich(int(k), self.zb.metrykaEuklidesowa, int(klasa), indeksy, (N if N>0 else None))

		if wynik['result'] == 'OK':
			self.PopupMessage("Podsumowanie klasyfikacji", "Sklasyfikowano %.2f%% osobnikow poprawnie" %(wynik['val']*100))
		else:
			self.PopupMessage("Nie mozna podsumowac klasyfikacji", "Nie mozna bylo podsumowac klasyfikacji, k <> faktycznej ilosci klas")
		self.populate_from_set()

	def Metoda_K_Srednich_search(self):

		indeksy, ok = QtGui.QInputDialog.getText(self, 'Indeksy Zmiennych', 'Podaj indeksy kolumn oddzielone ",":')
		if not ok:
			return

		klasa, ok = QtGui.QInputDialog.getText(self, 'Klasa decyzyjna', 'Podaj indeks klasy decyzyjnej:')
		if not ok:
			return

		indeksy = [int(i) for i in indeksy.split(',')]
		klasa = int(klasa)

		wynik = self.zb.znajdz_k_srednich(self.zb.metrykaEuklidesowa,klasa, indeksy)
		self.populate_from_set()
		self.PopupMessage("Podsumowanie szukania K", "Optymalne K: %d, Suma odchylen: %.3f" %(wynik[1],wynik[0]))

	def __init__(self):
		QtGui.QMainWindow.__init__(self)

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

		self.ui.actionAdd_Row.triggered.connect(self.add_row)
		self.ui.actionAdd_Col.triggered.connect(self.add_empty_column)
		self.ui.actionDelete_Col.triggered.connect(self.remove_column_dialog)
		self.ui.actionDelete_Row.triggered.connect(self.remove_row_dialog)

		self.ui.actionClear.triggered.connect(self.clear_tree)
		self.ui.actionPopulate_from_set.triggered.connect(self.populate_from_set)
		self.ui.actionDEBUG.triggered.connect(self.DEBUG)
		self.ui.typesPushButton.clicked.connect(self.edit_types)
		self.ui.namesPushButton.clicked.connect(self.edit_names)
		self.ui.actionSave.triggered.connect(self.save_data)
		self.ui.actionLoad.triggered.connect(self.load_data)

		#zadanie1
		self.ui.actionDyskretyzacjaPRD.triggered.connect(self.dyskretyzacjaPRD)
		self.ui.actionDyskretyzacjaNK.triggered.connect(self.dyskretyzacjaNK)
		self.ui.actionStandaryzacja.triggered.connect(self.standaryzacja)
		self.ui.actionOdstajace3x.triggered.connect(self.odstajace3x)
		self.ui.actionOdstajaceProcent.triggered.connect(self.odstajaceProcent)
		self.ui.actionNormalizacja.triggered.connect(self.normalizacja)
		self.ui.actionWykres2D.triggered.connect(self.Wykres2D)
		self.ui.actionWykres3D.triggered.connect(self.Wykres3D)
		#self.ui.actionSprawdzOcene.triggered.connect(self.SprawdzOceneKlasyfikacji)
		#self.ui.actionSklasyfikujObiekt.triggered.connect(self.SklasyfikujObiekt)
		self.ui.actionMetryk_Euklidesow.triggered.connect(self.SprawdzEuklidesowa)
		self.ui.actionMetryk_Miejsk.triggered.connect(self.SprawdzMiejska)
		self.ui.actionMetryk_Mahalanobisa.triggered.connect(self.SprawdzMahalanobisa)
		self.ui.actionMetryk_Euklidesow_2.triggered.connect(self.KlasyfikujEuklidesowa)
		self.ui.actionMetryk_Miejsk_2.triggered.connect(self.KlasyfikujMiejska)
		self.ui.actionMetryk_Mahalanobisa_2.triggered.connect(self.KlasyfikujMahalanobisa)
		self.ui.actionMetoda_K_Srednich.triggered.connect(self.Metoda_K_Srednich)
		self.ui.actionMetoda_K_Srednich_optymalne_K.triggered.connect(self.Metoda_K_Srednich_search)

		self.TypToS = TypToS
		self.SToTyp = SToTyp
Esempio n. 50
0
class MapWatchWindow(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        # General Settings
        self.version = '0.3'
        self.appTitle = 'Map Watch (v'+self.version+')'
        self.setWindowIcon(QtGui.QIcon(r'images\\icon.ico'))
        self.firstClose = 1
        self.zana_mods = [ # TODO: maybe load from outside source? settings.ini?
            ['None', 'Free', 0, 0, ''],
            ['Item Quantity', 'Free', 1, 0, '+1% Quantity Per Master Level'],
            ['Rampage', '4x Chaos Orbs', 2, 0, 'Slaying enemies quickly grants Rampage bonuses'],
            ['Bloodlines', '4x Chaos Orb', 2, 15, 'Magic Monster Packs each have a Bloodline Mod'],
            ['Anarchy', '8x Chaos Orb', 3, 16, 'Area is inhabited by 4 additional Rogue Exiles'],
            ['Invasion', '8x Chaos Orb', 3, 16, 'Area is inhabited by 3 additional Invasion Bosses'],
            ['Domination', '10x Chaos Orb', 4, 0, 'Area Contains 5 Extra Shrines'],
            ['Onslaught', '8x Chaos Orb', 4, 30, '40% Increased Monster Cast & Attack Speed'],
            ['Torment', '8x Chaos Orb', 5, 12, 'Area spawns 3 extra Tormented Spirits (Stacks with any that naturally spawned)'],
            ['Beyond', '12x Chaos Orb', 5, 8, 'Slaying enemies close together can attract monsters from Beyond this realm'],
            ['Ambush', '12x Chaos Orb', 6, 0, 'Area contains 4 extra Strongboxes'],
            ['Nemesis', '1x Exalted Orb', 7, 0, 'One Rare Per Pack, Rare Monsters Each Have A Nemesis Mod'],
            ['Tempest', '3x Exalted Orb', 8, 16, 'Powerful Tempests can affect both Monsters and You'],
            ['Warbands', '3x Exalted Orb', 8, 16, 'Area is inhabited by 2 additional Warbands']
        ]
        #Windows hwnd
        self._handle = None
        self.window = None
        # System Tray Icon
        self.sysTrayIcon = QtWidgets.QSystemTrayIcon()
        self.sysTrayIcon.setIcon(QtGui.QIcon(r'images\\icon.ico'))
        self.sysTrayIcon.show()
        self.sysTrayIcon.activated.connect(self.restore)
        # System Tray Context Menu
        menu = QtWidgets.QMenu(parent)
        icon = QtGui.QIcon(r'images\\icon.ico')
        restoreAction = QtWidgets.QAction(icon, '&Show Map Watch', self)
        restoreAction.triggered.connect(self.popup)
        menu.addAction(restoreAction)
        icon = QtGui.QIcon('')
        exitAction = QtWidgets.QAction(icon, '&Exit', self)
        exitAction.triggered.connect(self.closeApplication)
        menu.addAction(exitAction)
        self.sysTrayIcon.setContextMenu(menu)
        # This will do the Map Watching in a different thread
        self.thread = MapWatcher()
        self.thread.runLoop()
        self.thread.trigger.connect(self.newMapFound)  # Triggered when new map found
        # Configure UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setFixedSize(471, 413)
        self.setWindowTitle(self.appTitle)
        self.ui_confirm = ConfirmDialog(self)
        self.ui_prefs = Preferences(self)
        self.setPrefs()
        self.addZanaMods()
        if not int(self.settings['AlwaysOnTop']):
            self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowCloseButtonHint|Qt.X11BypassWindowManagerHint)
        else:
            self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowCloseButtonHint|Qt.WindowStaysOnTopHint|Qt.X11BypassWindowManagerHint)  
        # Button Actions
        self.ui.ms_add_map.clicked.connect(self.addMap)
        self.ui.ms_remove_map.clicked.connect(self.removeMap)
        self.ui.mr_clear_map.clicked.connect(self.clearMap)
        self.ui.mr_run_map.clicked.connect(self.runMap)
        self.ui.mr_add_zana_mod.currentIndexChanged.connect(self.changeZanaMod)
        self.ui.mr_add_bonus_iq.valueChanged.connect(self.changeBonusIQ)
        # Menu Actions
        self.ui.menu_create_new_db.triggered.connect(lambda: self.setDBFile(True))
        self.ui.menu_load_db.triggered.connect(self.setDBFile)
        self.ui.menu_open_stats.triggered.connect(self.openStatFile)
        self.ui.menu_exit_app.triggered.connect(self.closeApplication)
        self.ui.menu_ms_add_map.triggered.connect(self.addMap)
        self.ui.menu_ms_add_unlinked_map.triggered.connect(lambda: self.addMap(True))
        self.ui.menu_ms_remove_map.triggered.connect(self.removeMap)
        self.ui.menu_mr_clear_map.triggered.connect(self.clearMap)
        self.ui.menu_mr_run_map.triggered.connect(self.runMap)
        self.ui.menu_preferences.triggered.connect(self.getPrefs)
        self.ui.menu_about.triggered.connect(self.about)
        # Keyboard Shortcuts
        self.hotkey_add = QtWidgets.QShortcut(QtGui.QKeySequence("A"), self, self.addMap)
        self.hotkey_addu = QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+U"), self, lambda: self.addMap(True))
        QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+D"), self, self.removeMap)
        QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+X"), self, self.clearMap)
        QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+R"), self, self.runMap)
        QtWidgets.QShortcut(QtGui.QKeySequence("Z"), self, lambda: self.giveFocus('ZanaMod'))
        QtWidgets.QShortcut(QtGui.QKeySequence("Q"), self, lambda: self.giveFocus('BonusIQ'))
        QtWidgets.QShortcut(QtGui.QKeySequence("F1"), self, lambda: self.setDBFile(True))
        QtWidgets.QShortcut(QtGui.QKeySequence("F2"), self, self.setDBFile)
        QtWidgets.QShortcut(QtGui.QKeySequence("F3"), self, self.openStatFile)
        QtWidgets.QShortcut(QtGui.QKeySequence("F4"), self, self.getPrefs)
        QtWidgets.QShortcut(QtGui.QKeySequence("F5"), self, self.about)
        QtWidgets.QShortcut(QtGui.QKeySequence("F12"), self, self.closeApplication)
        self.button_access = [False, False, False, False]
        # Setup Map Database
        self.map_data = None
        self.mapDB = MapDatabase(self)
        if int(self.settings['LoadLastOpenedDB']):
            if os.path.exists(self.settings['LastOpenedDB']):
                self.mapDB.setDBFile(self.settings['LastOpenedDB'])
                self.mapDB.setupDB('Checking DB Structure', True)
            else:
                self.mapDB.setupDB(self.settings['LastOpenedDB'])
        else:
            self.buttonAccess(self.button_access)
        self.updateWindowTitle()

    def _window_enum_callback(self, hwnd, wildcard):
        '''Pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None:
            self._handle = hwnd
            print('hwnd: '+str(self._handle))
        #print(str(win32gui.GetWindowText(hwnd)))

    def restore(self, action):
        if action == self.sysTrayIcon.DoubleClick:
            self.popup()

    def popup(self):
        self.showNormal()
        #self.show()
        self.activateWindow()
        if self._handle:
            #win32gui.ShowWindow(self._handle, win32con.SW_RESTORE)
            win32gui.BringWindowToTop(self._handle)
            if int(self.settings['AlwaysOnTop']):
                win32gui.SetWindowPos(self._handle, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
            else:
                win32gui.SetWindowPos(self._handle, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
            self.window.SetFocus() #STEAL FOCUS! HAHA, f**k you Microsoft

    def giveFocus(self, widget):
        if widget is 'ZanaMod':
            self.ui.mr_add_zana_mod.setFocus(Qt.ShortcutFocusReason)
        elif widget is 'BonusIQ':
            self.ui.mr_add_bonus_iq.setFocus(Qt.ShortcutFocusReason)

    def newMapFound(self, map_data):
        self.popup()
        self.map_data = map_data
        self.button_access = [True, True, True, True]
        if self.thread.map_type is MapType.Fragment:
            self.button_access[Button.Add] = False
            self.hotkey_add.setEnabled(False)
            self.hotkey_addu.setEnabled(False)
        else:
            self.hotkey_add.setEnabled(True)
            self.hotkey_addu.setEnabled(True)
        self.buttonAccess(self.button_access)
        self.updateUiMapSelected()

    def updateUiMapSelected(self):
        print('UI Updated')
        # Clear those items that may not be updated with new map
        self.ui.ms_iq.setText('0%')
        self.ui.ms_ir.setText('0%')
        self.ui.ms_pack_size.setText('0%')
        self.ui.ms_mods.setText('None')
        # Get each piece of map info and update UI lables, etc
        if Map.TimeAdded in self.map_data:
            h = '%H'
            ms = ''
            p = ''
            if int(self.settings['ClockHour12']):
                h = '%I'
                p = ' %p'
            if int(self.settings['ShowMilliseconds']):
                ms = '.%f'
            time_added = datetime.datetime.fromtimestamp(self.map_data[Map.TimeAdded]).strftime(h+':%M:%S'+ms+p)
            self.ui.ms_time_stamp.setText(time_added)
        if Map.Name in self.map_data:
            self.ui.ms_name.setText(self.map_data[Map.Name])
        if Map.Tier in self.map_data:
            level = int(self.map_data[Map.Tier]) + 67
            self.ui.ms_tier.setText(self.map_data[Map.Tier] + '  (' + str(level) + ')')
        if Map.IQ in self.map_data:
            self.ui.ms_iq.setText(self.map_data[Map.IQ]+'%')
        if Map.IR in self.map_data:
            self.ui.ms_ir.setText(self.map_data[Map.IR]+'%')
        if Map.PackSize in self.map_data:
            self.ui.ms_pack_size.setText(self.map_data[Map.PackSize]+'%')
        if Map.Rarity in self.map_data:
            rarity = self.map_data[Map.Rarity]
            self.ui.ms_rarity.setText(rarity)
            if rarity == 'Rare':
                self.ui.ms_name.setStyleSheet("color: rgb(170, 170, 0);")
            elif rarity == 'Magic':
                self.ui.ms_name.setStyleSheet("color: rgb(0, 85, 255);")
            elif rarity == 'Unique':
                self.ui.ms_name.setStyleSheet("color: rgb(170, 85, 0);")
            else:
                self.ui.ms_name.setStyleSheet("color: rgb(0, 0, 0);")
        if Map.Mod1 in self.map_data:
            all_mods = self.map_data[Map.Mod1]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod2 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod2]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod3 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod3]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod4 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod4]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod5 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod5]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod6 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod6]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod7 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod7]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod8 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod8]
            self.ui.ms_mods.setText(all_mods)
        if Map.Mod9 in self.map_data:
            all_mods = all_mods + '\r\n' + self.map_data[Map.Mod9]
            self.ui.ms_mods.setText(all_mods)

    def updateUiMapRunning(self, clear=False):
        print('UI Updated')
        if clear:
            self.ui.mr_name.setText('None')
            self.ui.mr_tier.setText('0')
            self.ui.mr_iq.setText('0%')
            self.ui.mr_bonus_iq.setText('')
            self.ui.mr_ir.setText('0%')
            self.ui.mr_pack_size.setText('0%')
            self.ui.mr_rarity.setText('')
            self.ui.mr_mods.setText('')
            self.ui.mr_name.setStyleSheet("color: rgb(0, 0, 0);")
        else:
            self.ui.mr_name.setText(self.ui.ms_name.text())
            self.ui.mr_tier.setText(self.ui.ms_tier.text())
            self.ui.mr_iq.setText(self.ui.ms_iq.text())
            self.ui.mr_ir.setText(self.ui.ms_ir.text())
            self.ui.mr_pack_size.setText(self.ui.ms_pack_size.text())
            self.ui.mr_rarity.setText(self.ui.ms_rarity.text())
            self.ui.mr_mods.setText(self.ui.ms_mods.toPlainText())
            self.map_mod_text = self.ui.ms_mods.toHtml() # orginal copy for bonus IQ add/remove
            rarity = self.ui.ms_rarity.text()
            if rarity == 'Rare':
                self.ui.mr_name.setStyleSheet("color: rgb(170, 170, 0);")
            elif rarity == 'Magic':
                self.ui.mr_name.setStyleSheet("color: rgb(0, 85, 255);")
            elif rarity == 'Unique':
                self.ui.mr_name.setStyleSheet("color: rgb(170, 85, 0);")
            else:
                self.ui.mr_name.setStyleSheet("color: rgb(0, 0, 0);")

    def updateUiMapRunningBonuses(self):
        print('UI Updated')
        if Map.BonusIQ in self.mapDB.map_running and self.mapDB.map_running[Map.BonusIQ] != 0:
            self.ui.mr_bonus_iq.setText('+'+str(self.mapDB.map_running[Map.BonusIQ])+'%')
        else:
            self.ui.mr_bonus_iq.setText('')
        if Map.Mod9 in self.mapDB.map_running:
            if self.mapDB.map_running[Map.Mod9] and self.map_mod_text:
                all_mods = self.map_mod_text + '\r\n<br><b>' +self.mapDB.map_running[Map.Mod9]+ '</b>'
                self.ui.mr_mods.setText(all_mods)
            else:
                self.ui.mr_mods.setText(self.map_mod_text)

    def removeMap(self):
        print('Removing Last Map')
        self.ui_confirm.boxType('confirm')
        del_map = None
        if self.ui_confirm.exec_('Remove Map?', 'Are you sure you want to delete the last map saved to database?'):
            del_map = self.mapDB.deleteLastMap(Maps.Dropped)
            self.updateWindowTitle()
        if del_map:
            self.sysTrayIcon.showMessage(
                'Last Map Removed',
                del_map+' was removed from the database.',
                1, 1000)

    def addMap(self, unlinked=False):
        print('Adding to Map Drops')
        add_map = self.mapDB.addMap(self.map_data, unlinked)
        if add_map:
            self.minimizeToSysTray()
            self.updateWindowTitle()
            self.sysTrayIcon.showMessage(
                'Map Added',
                add_map+' was added to the database.',
                1, 1000)

    def clearMap(self):
        if self.mapDB.map_running:
            self.ui_confirm.boxType('confirm')
            if self.ui_confirm.exec_('Map Cleared?', 'Is the current running map cleared?  No more map drops will be linked to this map.'):
                self.mapDB.clearMap()
                self.updateUiMapRunning(True)
                return True
            else:
                return False
        else:
            return True

    def runMap(self):
        print('Running Selected Map')
        if self.mapDB.runMap(self.map_data):
            self.updateUiMapRunning()
            self.resetBonuses()

    def setDBFile(self, new=False):
        if self.clearMap():
            abs_path = os.path.abspath(os.path.dirname('__file__'))
            if new:
                file_name = QFileDialog.getSaveFileName(self, 'Create New Database File', abs_path+'/data', 'SQLite Files (*.sqlite)')
                if file_name[0]:
                    self.mapDB.setupDB(file_name[0])
            else:
                file_name = QFileDialog.getOpenFileName(self, 'Load Database File', abs_path+'/data', 'SQLite Files (*.sqlite)')
            # Update settings
            if file_name[0]:
                self.mapDB.setDBFile(file_name[0])
                if not new:
                    self.mapDB.setupDB('Checking DB Structure', True)
                self.updateWindowTitle()
                self.buttonAccess([True, True, True, True])
                self.settings['LastOpenedDB'] = file_name[0]
                writeSettings(self.settings)

    def addZanaMods(self):
        print('Adding Zana Mods to Combo Box')
        self.ui.mr_add_zana_mod.clear()
        for i, zana_mod in enumerate(self.zana_mods):
            self.ui.mr_add_zana_mod.addItem(zana_mod[ZanaMod.Name] + ' (' + zana_mod[ZanaMod.Cost] + ')')
            if int(self.settings['ZanaDefaultModIndex']) == i:
                self.ui.mr_add_zana_mod.setCurrentIndex(i)
            if int(self.settings['ZanaLevel']) < zana_mod[ZanaMod.Level]:
                break # Stop adding mod options if Zana level is to low to run them

    def changeZanaLevel(self):
        self.zana_mods[1][ZanaMod.IQ] = int(self.settings['ZanaLevel'])
        self.addZanaMods()

    def changeZanaMod(self):
        print('New Zana Mod Selected')
        if self.mapDB.map_running:
            self.mapDB.map_running[Map.BonusIQ] = self.calcBonusIQ()
            zana_mod_str = self.zana_mods[self.ui.mr_add_zana_mod.currentIndex()][ZanaMod.Desc]
            self.mapDB.map_running[Map.Mod9] = zana_mod_str
            self.updateUiMapRunningBonuses()
            self.ui.mr_mods.moveCursor(QtGui.QTextCursor.End)

    def changeBonusIQ(self):
        print('Bonus IQ Changed')
        if self.mapDB.map_running:
            self.mapDB.map_running[Map.BonusIQ] = self.calcBonusIQ()
            self.updateUiMapRunningBonuses()

    def calcBonusIQ(self):
        zana_iq = self.zana_mods[self.ui.mr_add_zana_mod.currentIndex()][ZanaMod.IQ]
        bonus_iq = self.ui.mr_add_bonus_iq.property('value') + zana_iq
        return bonus_iq

    def resetBonuses(self):
        self.ui.mr_add_zana_mod.setCurrentIndex(-1) # force change event
        self.ui.mr_add_zana_mod.setCurrentIndex(int(self.settings['ZanaDefaultModIndex']))
        self.ui.mr_add_bonus_iq.setProperty('value', 0)

    def openStatFile(self):
        stat_file = self.settings['SelectedStatisticsFile']
        webbrowser.open('file://' + stat_file)

    def getPrefs(self):
        if self.ui_prefs.exec_():
            self.setPrefs()

    def setPrefs(self):
        self.settings = readSettings()
        self.popup()
        self.thread.setMapCheckInterval(float(self.settings['MapCheckInterval']))
        self.changeZanaLevel()
        hour12 = self.settings['ClockHour12']
        milliseconds = self.settings['ShowMilliseconds']
        hour12 = False if hour12 == '0' else True
        milliseconds = False if milliseconds == '0' else True
        settings = {'hour12': hour12, 'milliseconds': milliseconds}
        writeSettingsJS(settings)
        print("Preferences Updated")

    def about(self):
        self.ui_confirm.boxType('about')
        self.ui_confirm.exec_('About', 'Map Watch\nVersion '+self.version+'\n\nCreated by\[email protected]\nIGN: Grahf_Azura')

    def updateWindowTitle(self):
        if self.mapDB.db_file:
            map_count = self.mapDB.countMapsAdded()
            self.setWindowTitle(self.appTitle + ' ---> ' + str(map_count) + ' map drops in database (' + os.path.basename(self.mapDB.db_file) + ')')
        else:
            self.setWindowTitle(self.appTitle + ' ---> Map Database Not Loaded')

    def buttonAccess(self, button):
        self.ui.ms_add_map.setEnabled(button[Button.Add])
        self.ui.ms_remove_map.setEnabled(button[Button.Remove])
        self.ui.mr_clear_map.setEnabled(button[Button.Clear])
        self.ui.mr_run_map.setEnabled(button[Button.Run])
        self.ui.menu_ms_add_map.setEnabled(button[Button.Add])
        self.ui.menu_ms_add_unlinked_map.setEnabled(button[Button.Add])
        self.ui.menu_ms_remove_map.setEnabled(button[Button.Remove])
        self.ui.menu_mr_clear_map.setEnabled(button[Button.Clear])
        self.ui.menu_mr_run_map.setEnabled(button[Button.Run])

    def error(self, err_msg, errors=None):
        err_msg += '\n'
        if errors is not None:
            for err in errors:
                err_msg += '\n'+str(err)
                #print(err)
        self.ui_confirm.boxType('error')
        self.ui_confirm.exec_('Error', err_msg)

    def closeApplication(self):
        print('Map Watch Closing')
        self.mapDB.clearMap() # In-case user forgot to clear thier map before closing app
        self.sysTrayIcon.hide()
        sys.exit()

    def closeEvent(self, event):
        # Changes the close button (X) behavior to minimize instead
        event.ignore()
        if self.firstClose:
            self.sysTrayIcon.showMessage(
                'Minimized To System Tray',
                'Map Watch will still continue to run in the background. Right click and select exit to shut down application.',
                1, 1000)
            self.firstClose = 0
        self.minimizeToSysTray()
        #self.closeApplication()

    def minimizeToSysTray(self):
        self.showMinimized()
        self.hide()
Esempio n. 51
0
class QDCWindow(QtGui.QMainWindow):

	def __init__(self):
		
		QtGui.QMainWindow.__init__(self)

		# UI created by QT Designer 
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		# default value = 5 m
		self.launchAlt = 5 

		#Set up option parsing to get connection string
		import argparse  
		parser = argparse.ArgumentParser(description='Tracks GPS position of your computer (Linux only). Connects to SITL on local PC by default.')
		parser.add_argument('--connect', help="vehicle connection target.")
		args = parser.parse_args()

		self.connection_string = args.connect
		self.sitl = None

		#Start SITL if no connection string specified
		if not self.connection_string:
			import dronekit_sitl
			self.sitl = dronekit_sitl.start_default()
			self.connection_string = self.sitl.connection_string()

		# Connect to the Vehicle
		print 'Connecting to vehicle on: %s' % self.connection_string
		self.vehicle = connect(self.connection_string, wait_ready=True)

		# Display Flight Mode
		self.updateFlightModeGUI(self.vehicle.mode)
		self.addObserverAndInit(
			'mode'
			,lambda vehicle,name,mode: self.updateFlightModeGUI(mode) ) 

		# Display Location Info
		self.updateLocationGUI(self.vehicle.location)
		self.addObserverAndInit(
			'location'
			,lambda vehicle, name, location: self.updateLocationGUI(location) )


	def send_ned_velocity(self, velocity_x, velocity_y, velocity_z, duration):
		msg = self.vehicle.message_factory.set_position_target_local_ned_encode(
			0,       # time_boot_ms (not used)
			0, 0,    # target system, target component
			mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame
			0b0000111111000111, # type_mask (only speeds enabled)
			0, 0, 0, # x, y, z positions (not used)
			velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s
			0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)
			0, 0)    # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) 

		#send command to vehicle on 1 Hz cycle
		for x in range(0,duration):
			self.vehicle.send_mavlink(msg)
			time.sleep(1)

	# set yaw from 0 to 359 / 0-north, 90-east, 180-south, 270-west
	def condition_yaw(heading, relative=False):
		if relative:
			is_relative = 1 #yaw relative to direction of travel
		else:
			is_relative = 0 #yaw is an absolute angle
		# create the CONDITION_YAW command using command_long_encode()
		msg = vehicle.message_factory.command_long_encode(
			0, 0,    # target system, target component
			mavutil.mavlink.MAV_CMD_CONDITION_YAW, #command
			0, #confirmation
			heading,    # param 1, yaw in degrees
			0,          # param 2, yaw speed deg/s
			1,          # param 3, direction -1 ccw, 1 cw
			is_relative, # param 4, relative offset 1, absolute angle 0
			0, 0, 0)    # param 5 ~ 7 not used
		# send command to vehicle
		vehicle.send_mavlink(msg)
 	
	def updateLocationGUI(self, location):
		self.ui.lblLongValue.setText(str(location.global_frame.lon))
		self.ui.lblLatValue.setText(str(location.global_frame.lat))
		self.ui.lblAltValue.setText(str(location.global_relative_frame.alt))
	
	def updateFlightModeGUI(self, value):
		index,mode = str(value).split(':')
		self.ui.lblFlightModeValue.setText(mode)
		
	def addObserverAndInit(self, name, cb):
		"""We go ahead and call our observer once at startup to get an initial value"""
		self.vehicle.add_attribute_listener(name, cb)


	def vehicle_validation(self, function):
		if self.vehicle.mode == "GUIDED":
			function()

	def west_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(0,-1,0,1)
			self.send_ned_velocity(0,0,0,1)

	def east_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(0,1,0,1)
			self.send_ned_velocity(0,0,0,1)

	def north_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(1,0,0,1)
			self.send_ned_velocity(0,0,0,1)

	def south_click(self):
		@self.vehicle_validation
		def wrapped():
			self.send_ned_velocity(-1,0,0,1)
   			self.send_ned_velocity(0,0,0,1)

	def rtl_click(self):
		@self.vehicle_validation
		def wrapped():
			self.vehicle.mode = VehicleMode("RTL")

	def up_click(self):
		@self.vehicle_validation
		def wrapped():
			alt = self.vehicle.location.global_relative_frame.alt
			if  alt < 20:
				self.send_ned_velocity(0,0,-0.5,1)
	 	  		self.send_ned_velocity(0,0,0,1)

	def down_click(self):
		@self.vehicle_validation
		def wrapped():
			alt = self.vehicle.location.global_relative_frame.alt
			if alt > 3:
				self.send_ned_velocity(0,0,0.5,1)
	 	  		self.send_ned_velocity(0,0,0,1)

	def launch_click(self):
		"""
		Arms vehicle and fly to self.alt
		"""
		print "Basic pre-arm checks"
		# Don't let the user try to arm until autopilot is ready
		while not self.vehicle.is_armable:
			print " Waiting for vehicle to initialise..."
			time.sleep(1)

		print "Arming motors"
		# Copter should arm in GUIDED mode
		self.vehicle.mode = VehicleMode("GUIDED")
		self.vehicle.armed = True

		while not self.vehicle.armed:      
			print " Waiting for arming..."
			time.sleep(1)

		print "Taking off!"
		self.vehicle.simple_takeoff(self.launchAlt) # Take off to target altitude

		# Wait until the vehicle reaches a safe height before processing the goto (otherwise the command 
		#  after Vehicle.simple_takeoff will execute immediately).
		while True:
			print " Altitude: ", self.vehicle.location.global_relative_frame.alt      
			if self.vehicle.location.global_relative_frame.alt>=self.launchAlt*0.95: #Trigger just below target alt.
				print "Reached target altitude"
				break
			time.sleep(1)
Esempio n. 52
0
class Main(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.btnInputCellFile.clicked.connect(self.btnInputCellFile_Clicked)
        self.ui.btnInputNeighborFile.clicked.connect(self.btnInputNeighborFile_Clicked)
        self.ui.btnGenerateCellFile.clicked.connect(self.btnGenerateCellFile_Clicked)
        self.ui.actionCellDatabaseFileFormat.triggered.connect(self.actionCellDatabaseFileFormat_Clicked)
        self.ui.actionNeighborFileFormat.triggered.connect(self.actionNeighborFileFormat_Clicked)
        self.ui.actionAbout.triggered.connect(self.actionAbout_Clicked)
        
    def btnInputCellFile_Clicked(self):
        self.ui.txtInputCellFile.setText(QtGui.QFileDialog.getOpenFileName(filter='CSV (*.csv);;All files (*.*)'))
              
    def btnInputNeighborFile_Clicked(self):
        self.ui.txtInputNeighborFile.setText(QtGui.QFileDialog.getOpenFileName(filter='CSV (*.csv);;All files (*.*)'))
            
    def actionCellDatabaseFileFormat_Clicked(self):
        QtGui.QMessageBox.information(None, 'Cell Database file Format', "CELL,CI,LAT,LON,ANT_DIRECTION,ANT_BEAM_WIDTH,ARFCN,BSIC,MCC,MNC,LAC")
        
    def actionNeighborFileFormat_Clicked(self):
        QtGui.QMessageBox.information(None, 'Neighbor file Format', "cell,neighbor")
        
    def actionAbout_Clicked(self):
        QtGui.QMessageBox.information(None, 'About', "Source code for this software can be found at:\nhttps://github.com/imtiaznizami/PyTemsCellFileGenerator")
        
    def btnGenerateCellFile_Clicked(self):
        fn_cel = self.ui.txtInputCellFile.text()
        fn_nbr = self.ui.txtInputNeighborFile.text()
        
        # check if file / folder names are valid
        if not os.path.isfile(fn_cel):
            QtGui.QMessageBox.information(None, 'Warning', "Cell file name is invalid. Aborting execution.")
            return
            
        if not os.path.isfile(fn_nbr):
            QtGui.QMessageBox.information(None, 'Warning', "Neighbor file name is invalid. Aborting execution.")
            return

        # read neighbor file into a dictionary
        # key: cell id
        # value: list of neighbors 
        dict_nbr = {}
        
        with open(fn_nbr, 'rt') as csvfile:
            reader_nbr = csv.reader(csvfile, delimiter=',', quotechar='"')
            for row in reader_nbr:
                if len(row) > 1:
                    if row[0] not in dict_nbr:
                        dict_nbr[row[0]] = []
                    
                    dict_nbr[ row[0].strip() ].append( row[1].strip() )   
        
        # read cell file and write to file like string
        output = io.StringIO()
        writer = csv.writer(output, delimiter = '\t', lineterminator='\n')
        writer.writerow(["2 TEMS_-_Cell_names"])
        lst_header = []
        flag = 1
        
        with open(fn_cel, 'rt') as f:
            reader = csv.DictReader(f) # read rows into a dictionary format
            for row in reader: # read a row as {column1: value1, column2: value2,...}                
                lst = list(row.values())
                for (k,v) in row.items(): # go over each column name and value  
                    if flag:
                        lst_header.append(k)                  
                    if k == 'CI':
                        if v in dict_nbr:
                            lst = lst + dict_nbr[v][:32]
                               
                if flag:
                    for n in range(1, 33):
                        lst_header.append("CI_N_%s" % (n,))
                    writer.writerow( lst_header )
                    flag = 0
                
                writer.writerow( lst )
        
        # write output file
        fn_out = QtGui.QFileDialog.getSaveFileName(filter='CEL (*.cel);;All files (*.*)')
        if not os.path.isdir(os.path.dirname(fn_out)):
            QtGui.QMessageBox.information(None, 'Warning', "Output file directory is invalid. Aborting execution.")
            return
        
        file_out = open(fn_out, "w")
        file_out.write(output.getvalue())
        file_out.close()
Esempio n. 53
0
 def __init__(self, parent=None):
     super().__init__(parent)
     # General Settings
     self.version = '0.3'
     self.appTitle = 'Map Watch (v'+self.version+')'
     self.setWindowIcon(QtGui.QIcon(r'images\\icon.ico'))
     self.firstClose = 1
     self.zana_mods = [ # TODO: maybe load from outside source? settings.ini?
         ['None', 'Free', 0, 0, ''],
         ['Item Quantity', 'Free', 1, 0, '+1% Quantity Per Master Level'],
         ['Rampage', '4x Chaos Orbs', 2, 0, 'Slaying enemies quickly grants Rampage bonuses'],
         ['Bloodlines', '4x Chaos Orb', 2, 15, 'Magic Monster Packs each have a Bloodline Mod'],
         ['Anarchy', '8x Chaos Orb', 3, 16, 'Area is inhabited by 4 additional Rogue Exiles'],
         ['Invasion', '8x Chaos Orb', 3, 16, 'Area is inhabited by 3 additional Invasion Bosses'],
         ['Domination', '10x Chaos Orb', 4, 0, 'Area Contains 5 Extra Shrines'],
         ['Onslaught', '8x Chaos Orb', 4, 30, '40% Increased Monster Cast & Attack Speed'],
         ['Torment', '8x Chaos Orb', 5, 12, 'Area spawns 3 extra Tormented Spirits (Stacks with any that naturally spawned)'],
         ['Beyond', '12x Chaos Orb', 5, 8, 'Slaying enemies close together can attract monsters from Beyond this realm'],
         ['Ambush', '12x Chaos Orb', 6, 0, 'Area contains 4 extra Strongboxes'],
         ['Nemesis', '1x Exalted Orb', 7, 0, 'One Rare Per Pack, Rare Monsters Each Have A Nemesis Mod'],
         ['Tempest', '3x Exalted Orb', 8, 16, 'Powerful Tempests can affect both Monsters and You'],
         ['Warbands', '3x Exalted Orb', 8, 16, 'Area is inhabited by 2 additional Warbands']
     ]
     #Windows hwnd
     self._handle = None
     self.window = None
     # System Tray Icon
     self.sysTrayIcon = QtWidgets.QSystemTrayIcon()
     self.sysTrayIcon.setIcon(QtGui.QIcon(r'images\\icon.ico'))
     self.sysTrayIcon.show()
     self.sysTrayIcon.activated.connect(self.restore)
     # System Tray Context Menu
     menu = QtWidgets.QMenu(parent)
     icon = QtGui.QIcon(r'images\\icon.ico')
     restoreAction = QtWidgets.QAction(icon, '&Show Map Watch', self)
     restoreAction.triggered.connect(self.popup)
     menu.addAction(restoreAction)
     icon = QtGui.QIcon('')
     exitAction = QtWidgets.QAction(icon, '&Exit', self)
     exitAction.triggered.connect(self.closeApplication)
     menu.addAction(exitAction)
     self.sysTrayIcon.setContextMenu(menu)
     # This will do the Map Watching in a different thread
     self.thread = MapWatcher()
     self.thread.runLoop()
     self.thread.trigger.connect(self.newMapFound)  # Triggered when new map found
     # Configure UI
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.setFixedSize(471, 413)
     self.setWindowTitle(self.appTitle)
     self.ui_confirm = ConfirmDialog(self)
     self.ui_prefs = Preferences(self)
     self.setPrefs()
     self.addZanaMods()
     if not int(self.settings['AlwaysOnTop']):
         self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowCloseButtonHint|Qt.X11BypassWindowManagerHint)
     else:
         self.setWindowFlags(Qt.CustomizeWindowHint|Qt.WindowCloseButtonHint|Qt.WindowStaysOnTopHint|Qt.X11BypassWindowManagerHint)  
     # Button Actions
     self.ui.ms_add_map.clicked.connect(self.addMap)
     self.ui.ms_remove_map.clicked.connect(self.removeMap)
     self.ui.mr_clear_map.clicked.connect(self.clearMap)
     self.ui.mr_run_map.clicked.connect(self.runMap)
     self.ui.mr_add_zana_mod.currentIndexChanged.connect(self.changeZanaMod)
     self.ui.mr_add_bonus_iq.valueChanged.connect(self.changeBonusIQ)
     # Menu Actions
     self.ui.menu_create_new_db.triggered.connect(lambda: self.setDBFile(True))
     self.ui.menu_load_db.triggered.connect(self.setDBFile)
     self.ui.menu_open_stats.triggered.connect(self.openStatFile)
     self.ui.menu_exit_app.triggered.connect(self.closeApplication)
     self.ui.menu_ms_add_map.triggered.connect(self.addMap)
     self.ui.menu_ms_add_unlinked_map.triggered.connect(lambda: self.addMap(True))
     self.ui.menu_ms_remove_map.triggered.connect(self.removeMap)
     self.ui.menu_mr_clear_map.triggered.connect(self.clearMap)
     self.ui.menu_mr_run_map.triggered.connect(self.runMap)
     self.ui.menu_preferences.triggered.connect(self.getPrefs)
     self.ui.menu_about.triggered.connect(self.about)
     # Keyboard Shortcuts
     self.hotkey_add = QtWidgets.QShortcut(QtGui.QKeySequence("A"), self, self.addMap)
     self.hotkey_addu = QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+U"), self, lambda: self.addMap(True))
     QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+D"), self, self.removeMap)
     QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+X"), self, self.clearMap)
     QtWidgets.QShortcut(QtGui.QKeySequence("Ctrl+R"), self, self.runMap)
     QtWidgets.QShortcut(QtGui.QKeySequence("Z"), self, lambda: self.giveFocus('ZanaMod'))
     QtWidgets.QShortcut(QtGui.QKeySequence("Q"), self, lambda: self.giveFocus('BonusIQ'))
     QtWidgets.QShortcut(QtGui.QKeySequence("F1"), self, lambda: self.setDBFile(True))
     QtWidgets.QShortcut(QtGui.QKeySequence("F2"), self, self.setDBFile)
     QtWidgets.QShortcut(QtGui.QKeySequence("F3"), self, self.openStatFile)
     QtWidgets.QShortcut(QtGui.QKeySequence("F4"), self, self.getPrefs)
     QtWidgets.QShortcut(QtGui.QKeySequence("F5"), self, self.about)
     QtWidgets.QShortcut(QtGui.QKeySequence("F12"), self, self.closeApplication)
     self.button_access = [False, False, False, False]
     # Setup Map Database
     self.map_data = None
     self.mapDB = MapDatabase(self)
     if int(self.settings['LoadLastOpenedDB']):
         if os.path.exists(self.settings['LastOpenedDB']):
             self.mapDB.setDBFile(self.settings['LastOpenedDB'])
             self.mapDB.setupDB('Checking DB Structure', True)
         else:
             self.mapDB.setupDB(self.settings['LastOpenedDB'])
     else:
         self.buttonAccess(self.button_access)
     self.updateWindowTitle()