Пример #1
0
class ProgessBar(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.resize(310, 140)
        self.lbl_info = QLabel('Info:', self) 
        self.lbl_info.move(40, 25) # label with Info
        self.edit_info = QLineEdit(self)
        self.edit_info.resize(170, 20)
        self.edit_info.move(100, 20) # Show changing messages
        self.prog = QProgressBar(self)
        self.prog.resize(230, 30)
        self.prog.move(40, 55) 
        self.newTask(QCoreApplication.translate('Task message','Weighted Multi-Criteria Analysis - WMCA'))
        btn_close = QPushButton(QCoreApplication.translate('Task message','Close'),self)
        btn_close.move(190, 100)
        btn_close.clicked.connect(self.close_win)
        # ProgessBar.btn_cancel = QPushButton('Cancel Task', self)
        # ProgessBar.btn_cancel.move(40, 100)
        # ProgessBar.btn_cancel.clicked.connect(self.cancelTask)


    def newTask(self, message_task_description):
        """Create a task and add it to the Task Manager"""
        self.task = HeavyTask(message_task_description)
        #connect to signals from the background threads to perform gui operations
        #such as updating the progress bar
        self.task.begun.connect(lambda: self.edit_info.setText(QCoreApplication.translate("Task message","Calculating...")))
        self.task.progressChanged.connect(lambda: self.prog.setValue(self.task.progress()))
        self.task.progressChanged.connect(lambda: self.setProgressBarMessages(self.task.progress()))
        self.task.taskCompleted.connect(lambda: self.edit_info.setText(QCoreApplication.translate('Task message','Complete')))
        self.task.taskTerminated.connect(self.TaskCancelled)
        QgsApplication.taskManager().addTask(self.task)


    def TaskCancelled(self):
        self.prog.setValue(0)
        self.edit_info.setText(QCoreApplication.translate('Task message','Task Cancelled'))


    def close_win(self):
        self.close()


    def setProgressBarMessages(self, val):
    # --- Progress bar in the QGIS user messages (top)
        if val <= 15:
            message = QCoreApplication.translate("Task message","Starting...")
            iface.messageBar().pushMessage(message)
        elif val < 50:
            message = QCoreApplication.translate("Task message","Calculating according to grades and weights...")
            iface.messageBar().pushMessage(message)
        elif val < 100:
            message = QCoreApplication.translate("Task message","Preparing final raster...")
            iface.messageBar().pushMessage(message)
        elif val == 100:
            iface.messageBar().clearWidgets()


    # def cancelTask(self):
    #     self.task.cancel()
Пример #2
0
    def run_model_trainingbtnclicked(self):

        checkbox_list = []
        if self.checkBox_svm.isChecked():
            checkbox_list.append(self.checkBox_svm.text())
        if self.checkBox_decisionTree.isChecked():
            checkbox_list.append(self.checkBox_decisionTree.text())
        if self.checkBox_randomForest.isChecked():
            checkbox_list.append(self.checkBox_randomForest.text())
        if self.checkBox_extraTrees.isChecked():
            checkbox_list.append(self.checkBox_extraTrees.text())
        if self.checkBox_xgboost.isChecked():
            checkbox_list.append(self.checkBox_xgboost.text())
        if self.checkBox_mlp.isChecked():
            checkbox_list.append(self.checkBox_mlp.text())

        #print(checkbox_list)

        if "LGM-PolygonClassification-master" in str(os.getcwd()):
            pass
        else:
            #os.chdir()
            os.chdir(os.getcwd() + "\\LGM-PolygonClassification-master")

        #os.chdir(".\\LGM-PolygonClassification-master")
        fpath = self.train_data_chosen_file.text()

        temp11 = str(checkbox_list).replace("[", "").replace("]", "").replace(
            "'", '').replace(" ", "")

        while len(temp11) > 3:
            #print(temp11)
            command = f'python -m polygon_classification.cli train --dataset {fpath} --classifiers {temp11}'
            print(command)
            progress = QProgressBar()
            progress.setGeometry(200, 80, 250, 20)
            progress.move(600, 600)
            progress.setWindowTitle('Processing..')
            progress.setAlignment(QtCore.Qt.AlignCenter)
            progress.show()

            try:
                output = subprocess.check_output(command,
                                                 shell=True,
                                                 stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError:
                QMessageBox.warning(self, "WARNING",
                                    "Execution of command failed")

            QMessageBox.information(self, "INFO", str(output))
            print(output)
            break

        while len(temp11) < 4:
            QMessageBox.warning(self, "WARNING",
                                "Please choose training dataset to proceed")
            break

        #print(subprocess.STDOUT)
        print()
Пример #3
0
class window(QWidget):
    def __init__(self):
        super().__init__()
        self.init()

    def init(self):
        self.timer = QBasicTimer()
        self.pbr = QProgressBar(self)
        self.pbr.resize(200, 25)
        self.step = 0
        self.btn = QPushButton('start', self)
        self.btn.clicked.connect(self.doaction)
        self.btn.move(10, 10)
        self.pbr.move(10, 50)
        self.setGeometry(100, 100, 300, 300)

    def timerEvent(self, e):

        if self.step > 100:
            self.timer.stop()
            self.btn.setText('finshed')
            return
        else:
            self.step += 1
            self.pbr.setValue(self.step)

    def doaction(self):

        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('start')
        else:
            self.timer.start(100, self)
            self.btn.setText('stop')
Пример #4
0
    def run_btn_clicked(
        self
    ):  # asks the user to execute the lgm library, shows some info with info button
        msgBox = QMessageBox.question(self, "EXECUTION",
                                      " Execute classification?",
                                      QMessageBox.Yes | QMessageBox.No,
                                      QMessageBox.Yes)
        if msgBox == QMessageBox.Yes:
            if "LGM-POI-master" in str(os.getcwd()):
                pass
            else:
                os.chdir('.\\LGM-POI-master')

            if len(str(self.chosen_file.text())) < 4:
                QMessageBox.warning(self, "WARNING", "No input data specified")
                QgsMessageLog.logMessage(
                    "No input data specified. To proceed, plesase select an input file (csv) ",
                    MESSAGE_CATEGORY, Qgis.Warning)
                self.update()
            else:
                progress = QProgressBar()
                progress.setGeometry(200, 80, 250, 20)
                progress.move(600, 600)
                progress.setWindowTitle('Processing..')
                progress.setAlignment(QtCore.Qt.AlignCenter)
                progress.show()
                self.fpath = (self.chosen_file.text())
                command = f'python -m poi.cli eval --dataset {self.fpath}'

                try:
                    output = subprocess.run(command,
                                            shell=True,
                                            stderr=subprocess.STDOUT)
                    iface.messageBar().pushMessage(
                        "Success",
                        "Execution of process completed",
                        level=Qgis.Success,
                        duration=25)
                    QgsMessageLog.logMessage("Execution of process completed",
                                             MESSAGE_CATEGORY, Qgis.Success)
                except Exception:  #subprocess.CalledProcessError:
                    iface.messageBar().pushMessage(
                        "Failure",
                        "Execution of command failed {Exception}",
                        level=Qgis.Critical,
                        duration=25)
                    QgsMessageLog.logMessage(
                        "Execution of command '{}' failed".format(
                            self.Exception), MESSAGE_CATEGORY, Qgis.Warning)
                    QMessageBox.warning(self, "Failure",
                                        "Execution of command failed")

        if msgBox == QMessageBox.No:
            iface.messageBar().pushMessage("CAUTION",
                                           "Execution of process cancelled",
                                           level=Qgis.Warning,
                                           duration=15)
            QgsMessageLog.logMessage("Execution of process cancelled",
                                     MESSAGE_CATEGORY, Qgis.Warning)
Пример #5
0
 def extractBar(self):
     pb = QProgressBar(self)
     pb.resize(self.width() - self.barLabel.width(), self.height_)
     pb.move(self.barLabel.width(), 0)
     pb.setStyleSheet(
         "QProgressBar::chunk{background:qlineargradient(spread:pad,x1:0,y1:0,x2:1,y2:0,stop:0 #F8C63D,"
         "stop:1 #CC66E7);}")
     return pb
Пример #6
0
	def model_deploymentbtn_clicked(self):
		experiment_path=QFileDialog()
		exp_path = (experiment_path.getExistingDirectory(self,"Please choose experiment path file",str(os.getcwd()),QFileDialog.ShowDirsOnly)) + "\\"
		
		while exp_path=='':
			QMessageBox.warning(self,"CAUTION","No experiment path selected")
			break
		
		fpath = self.choosepoifilefilechoosenfile.text()
		
		progress = QProgressBar()
		progress.setGeometry(200, 80, 250, 20)
		progress.move(600,600)
		progress.setWindowTitle('Processing..')
		progress.setAlignment(QtCore.Qt.AlignCenter)
		progress.show()
		#time.sleep(1)		
		
		command = f'python .\\LGM-Geocoding-master\\model_deployment.py -experiment_path {exp_path} -fpath {fpath}'
		print(exp_path)
		print(fpath)
		print()
		
		#output = subprocess.check_output(command,shell=True,stderr=subprocess.STDOUT)
		try:
			output = subprocess.check_output(command,shell=True,stderr=subprocess.STDOUT)
		except subprocess.CalledProcessError:
			QMessageBox.warning(self,"WARNING","Execution of command failed")
		#print(subprocess.STDOUT)
		out_put = str(output)
		
		
		QMessageBox.information(self,'INFO',out_put)
		
		#exppath = exp_path + "model_deployment_results"
		csv_filepath = exp_path + "model_deployment_results\\predictions.csv"
		#csvmyfile = exppath + "\\predictionsrplconverted.csv"
		csvmyfile = exp_path + "model_deployment_results" +"\\predictionsrplconverted.csv"
		
		with open(csv_filepath, newline='', encoding='UTF-8') as csv_file:
			with open(csvmyfile,"w",newline='') as myfile: 
				#print('-------')
				csv_data = csv.reader(csv_file,quoting=csv.QUOTE_MINIMAL,skipinitialspace='True') ###
				count = 0
				wr=csv.writer(myfile)
				for row in csv_data:
					if count < 1: #skip csv header
						count=1
						continue
					if len(str(row))>2:
						a=count # id
						count+=1
						b=row[0] # address
						c=row[1] # predictions
						c=c.replace('"',"").replace("[","").replace("]","").replace("(","").replace(")","").replace(",","")
						if any(row): #remove empty lines in csv file
							wr.writerow([a,b,c])
		count=count-1  # remove header from csv
Пример #7
0
class WordCard(QWidget):
    def __init__(self, i, j, s):
        super().__init__()
        self.setWindowIcon(QtGui.QIcon('sources/word_icon.png'))
        s = int(float(s))
        self.i = i
        self.setGeometry(700, 500, 720, 150)
        self.setWindowTitle(i)

        self.coords = QLabel(self)
        self.coords.setText("Word: " + i)
        self.coords.move(30, 30)

        self.coords1 = QLabel(self)
        self.coords1.setText("Translation: " + j)
        self.coords1.move(30, 60)

        self.progressBar = QProgressBar(self)
        self.progressBar.setValue(int((s / 30) * 100))
        self.progressBar.move(30, 90)
        self.progressBar.resize(150, 20)

        self.deleter = QPushButton(self)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("sources/trash.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.deleter.setIcon(icon2)
        self.deleter.setIconSize(QtCore.QSize(86, 86))
        self.deleter.resize(100, 100)
        self.deleter.move(500, 20)
        self.deleter.clicked.connect(self.delete_button)

        self.speaker = QPushButton(self)
        icon = QtGui.QIcon()
        with open('sources/settings.txt', 'r') as f:
            r = json.loads(f.read())
            if r['main_sound'] == 'True':
                icon.addPixmap(QtGui.QPixmap("sources/sound.png"),
                               QtGui.QIcon.Normal, QtGui.QIcon.Off)
            if r['main_sound'] == 'False':
                icon.addPixmap(QtGui.QPixmap("sources/sound_off.png"),
                               QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.speaker.setIcon(icon)
        self.speaker.setIconSize(QtCore.QSize(86, 86))
        self.speaker.resize(100, 100)
        self.speaker.move(610, 20)
        self.speaker.clicked.connect(self.speak)

    def delete_button(self):
        with open('sources/marked.txt', 'w+', encoding="utf8") as f:
            f.write(self.i + '\n')
        sys.exit()

    def speak(self):
        with open('sources/word_to_tell.txt', 'w') as f:
            f.write(self.coords.text())
        os.system("python3 scripts/speaker.py")
Пример #8
0
	def createTable(self,count):    
        self.tableWidget.setRowCount(count) 
		self.tableWidget.setColumnCount(5)  # defore self.tableWidget.setColumnCount(4)
		rownum=0
        #-----------------------------------------------------------------
		#due to the fact that model deployment will always be the last step
		#the function last_exp_file() finds the last modified folder in experiments path (which is model_deployment_results)
		#and then selects the predictionsrplconverted.csv file in model_deployment_results is chosen
		
		
		csv_filepath = self.last_exp_file() + "\\model_deployment_results\\predictionsrplconverted.csv"
		print(csv_filepath)
		
		#----------------------------------------------------------------
		progress = QProgressBar()
		progress.setGeometry(200, 80, 250, 20)
		progress.move(600,600)
		progress.setWindowTitle('Loading Result Table')
		progress.setAlignment(QtCore.Qt.AlignCenter)
		progress.show()
		
		with open(csv_filepath, newline='', encoding='utf-8') as csv_file:  #encoding changed 'utf-8' --> 'ISO-8859-7'
			csv_data = csv.reader(csv_file)
			rownum = 0
				
			for row in csv_data:
				
				j=row[2] #row[2] -> category
				k=row[2]
				l=row[2]
				
				j=j.split(' ',2)[:2] 
				k=k.split(' ',4)[2:4]
				l=l.split(' ',6)[4:6]
				
				if len(str(row))>2:     
					item1=QTableWidgetItem(str(row[1])) #address doesn't need checkbox
					item2=QTableWidgetItem(str(row[0])) #id doesn't need checkbox
					checkbox3=QCheckBox(str(j))
					checkbox4=QCheckBox(str(k))	
					checkbox5=QCheckBox(str(l))
					checkbox3.setCheckState(Qt.Unchecked)
					checkbox4.setCheckState(Qt.Unchecked)
					checkbox5.setCheckState(Qt.Unchecked)
					self.tableWidget.setHorizontalHeaderLabels("poi_id address Category1 Category2 Category3".split())
					self.tableWidget.setItem(rownum,0, item2)
					self.tableWidget.setItem(rownum,1, item1) 
					self.tableWidget.setCellWidget(rownum,2,checkbox3)
					self.tableWidget.setCellWidget(rownum,3,checkbox4)
					self.tableWidget.setCellWidget(rownum,4,checkbox5)
					
				self.tableWidget.resizeColumnsToContents()
				rownum=rownum+1	
					
			self.tableWidget.cellClicked.connect(self.cell_was_clicked)
			self.tableWidget.setRowCount(rownum)
class myClass(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("进度条QProgressBar")
        self.setGeometry(700, 300, 500, 400)
        self.lab = QLabel("进度条", self)
        self.lab.move(45, 50)
        # 进度条控件
        self.qgb = QProgressBar(self)
        self.qgb.move(100, 50)
        # 控件的大小
        self.qgb.resize(300, 20)
        # 配置一个值,控制进度条时钟,表示当前进度
        self.pv = 0
        # 声明一个时钟控件
        self.timerl = QBasicTimer()

        # 设置最大值和最小值
        self.qgb.setMinimum(0)
        self.qgb.setMaximum(100)
        # 设置当前进度
        self.qgb.setValue(self.pv)

        # 载入按钮
        self.btn = QPushButton("开始", self)
        self.btn.move(100, 80)
        self.btn.clicked.connect(self.myTimeChange)  # 信号

        self.show()

    # 时钟控件切换的核心代码
    def myTimeChange(self):
        # 判断控件是否已经开启
        if self.timerl.isActive():
            self.timerl.stop()
            self.btn.setText("开始")
        else:
            self.timerl.start(100, self)  # 每隔一秒
            self.btn.setText("停止")

    # 重写时间控件的方法
    def timerEvent(self, e):
        if self.pv == 100:
            self.timerl.stop()
            self.btn.setText("完成")
            self.btn.clicked.connect(self.close)  # 点击完成后退出
            print("完成")
        else:
            self.pv = self.pv + 1
            self.qgb.setValue(self.pv)
            print(self.pv)
class ProBar(QDialog):
    def __init__(self):
        super(ProBar, self).__init__()
        self.setFixedWidth(200)
        # self.setWindowFlags(Qt.FramelessWindowHint)
        # self.backgroundRole()
        self.progressbar = QProgressBar(self)  # 1
        # self.progressbar.setOrientation(Qt.AlignCenter)
        self.progressbar.setMinimum(0)  # 2
        self.progressbar.setMaximum(100)
        self.progressbar.setRange(0, 100)
        self.progressbar.setFixedWidth(195)

        self.progressbar.move(10, 5)

        self.status = QLabel("正在加载词库...", self)
        self.status.move(55, 30)

        # self.setCentralWidget(self.progressbar)

        self.step = 0  # 3

        self.timer = QTimer(self)  # 4
        self.timer.timeout.connect(self.update_func)

        self.start_stop_func()
        self.update_func()

    def start_stop_func(self):
        self.timer.start(35)
        # if self.ss_button.text() == 'Start':
        #     self.ss_button.setText('Stop')
        #     self.timer.start(100)
        # else:
        #     self.ss_button.setText('Start')
        #     self.timer.stop()

    def update_func(self):
        self.step += 1
        self.progressbar.setValue(self.step)

        if self.step > 85:
            self.status.setText("正在加载主界面...")

        if self.step >= 100:
            self.close()

    @staticmethod
    def start(parent=None):
        dialog = ProBar()
        result = dialog.exec_()
        return result
Пример #11
0
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Soundcloud Downloader'
        self.left = 250
        self.top = 250
        self.width = 600
        self.height = 150
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create textbox
        self.textbox = QLineEdit(self)
        self.textbox.move(20, 20)
        self.textbox.resize(500, 20)
        self.textbox.setPlaceholderText("Past url of track here")

        # Create a button in the window
        self.button = QPushButton('Download', self)
        self.button.move(20, 70)
        self.button.resize(120, 30)

        #BAR
        self.pbar = QProgressBar(self)
        # self.pbar.setGeometry(80, 140, 200, 25)
        self.pbar.move(180, 70)
        self.pbar.resize(200, 30)

        # self.btn = QPushButton('Start', self)
        # self.btn.move(40, 140)
        # self.btn.clicked.connect(self.progress)

        self.button.clicked.connect(self.on_start)
        self.show()

    @pyqtSlot()
    def on_start(self):
        textboxValue = self.textbox.text()
        Handler().getMp3Track(textboxValue, self.pbar, QApplication)
        # handler.getMp3Track("https://soundcloud.com/revealed-recordings/dj-st3v3-washint-free-download")

    def progress(self):
        for i in range(101):
            time.sleep(0.05)
            self.pbar.setValue(i)
Пример #12
0
class MyClass(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("刘金玉编程")
        self.setGeometry(400, 100, 400, 300)
        # 载入进度条
        self.pgb = QProgressBar(self)  # 类对象的初始化
        self.pgb.move(50, 50)  # 将进度条移动到指定的位置
        self.pgb.resize(300, 20)  # 设置进度条宽高

        # 配置一个值表示进度条的当前进度
        self.pv = 0

        # 声明一个时钟控件
        self.timer1 = QBasicTimer()

        # 设置进度条的范围
        self.pgb.setMinimum(0)  # 设置最小值
        self.pgb.setMaximum(100)  # 设置最大值
        self.pgb.setValue(0)  # 设置当前进度

        # 载入按钮
        self.btn = QPushButton("开始", self)
        self.btn.move(50, 100)
        self.btn.clicked.connect(self.myTimerState)

        self.show()

    def myTimerState(self):
        if self.timer1.isActive():  # 检测是否开启
            self.timer1.stop(50, self)
            self.btn.setText("开始")  # 这里的按钮的状态显示的是按钮下次的行为
        else:
            self.timer1.start(50, self)
            self.btn.setText("停止")

    def timerEvent(self, e):
        if self.pv == 100:
            self.tiemr1.stop()
            self.btn.setText("完成")
        else:
            self.pv += 1
            self.pgb.setValue(self.pv)  # 设置当前进度
Пример #13
0
 def featureextractionbtnbtncliked(self):
     progress = QProgressBar()
     progress.setGeometry(200, 80, 250, 20)
     progress.move(600, 600)
     progress.setWindowTitle('Processing..')
     progress.setAlignment(QtCore.Qt.AlignCenter)
     progress.show()
     command = f'python .\\LGM-Classification-master\\src\\features_extraction.py -poi_fpath {self.chosen_train_data.text()}'
     try:
         print(command)
         output = subprocess.check_output(
             command, shell=True, universal_newlines=True
         )  #stderr=subprocess.STDOUT,universal_newlines=True)
     except subprocess.CalledProcessError:
         QMessageBox.warning(self, "WARNING", "Execution of command failed")
         QMessageBox.warning(self, "WARNING", str(subprocess.STDOUT))
     QMessageBox.information(self, 'INFO', str(output))
Пример #14
0
    def proBar(self):
        pb = QProgressBar(self)
        pb.resize(self.width(), self.barHeight)
        # pb.setMaximum(99)
        # pb.setValue(0)
        pb.move(0, self.height() - pb.height() - self.btnHeight)

        pb.setStyleSheet(
            "QProgressBar::chunk{background:qlineargradient(spread:pad,x1:0,y1:0,x2:1,y2:0,stop:0 #F8C63D,"
            "stop:1 #CC66E7);}")

        def pbFunc(int_):
            if int_ == 100:
                self.endBtn.setText("完成")
                self.endBtn.setFocus()

        pb.valueChanged.connect(pbFunc)
        return pb
Пример #15
0
	def feature_extractionbtn_clicked(self):
		progress = QProgressBar()
		progress.setGeometry(200, 80, 250, 20)
		progress.move(600,600)
		progress.setWindowTitle('Processing..')
		progress.setAlignment(QtCore.Qt.AlignCenter)
		progress.show()
		fpath = self.train_data_chosenfile.text()
		fpath = fpath.replace("//","\\")
		pythonexepath= os.environ['PYTHONHOME'] + '\\python.exe'
		os.chdir('.\\LGM-Geocoding-master')
		command = f'python features_extraction.py -fpath {fpath}'
		try:
			output = subprocess.check_output(command,shell=True,stderr=subprocess.STDOUT)
		except subprocess.CalledProcessError:
			print(stderr)
			QMessageBox.warning(self,"WARNING",str(stderr))		
		QMessageBox.information(self,"INFO",str(output))
Пример #16
0
	def model_trainingbtn_clicked(self):
		progress = QProgressBar()
		progress.setGeometry(200, 80, 250, 20)
		progress.move(600,600)
		progress.setWindowTitle('Processing..')
		progress.setAlignment(QtCore.Qt.AlignCenter)
		progress.show()
		exp_path = self.experiment_path_file.text() + "\\"
		command = f'python model_training.py  -experiment_path {exp_path}'
		if "LGM-Geocoding-master" in str(os.getcwd()):
			pass
		else:
			os.chdir('.\\LGM-Geocoding-master')		
		try:
			output = subprocess.check_output(command,shell=True,stderr=subprocess.STDOUT)
		except subprocess.CalledProcessError:
			QMessageBox.warning(self,"WARNING",str(output))
		QMessageBox.information(self,"INFO",str(output))
Пример #17
0
 def algorithmselectionbtncliked(self):
     progress = QProgressBar()
     progress.setGeometry(200, 80, 250, 20)
     progress.move(600, 600)
     progress.setWindowTitle('Processing..')
     progress.setAlignment(QtCore.Qt.AlignCenter)
     progress.show()
     exp_path = self.exppahchoosenfile.text()
     command = f'python .\\LGM-Classification-master\\src\\algorithm_selection.py -experiment_path {exp_path}'
     try:
         output = subprocess.check_output(command,
                                          shell=True,
                                          stderr=subprocess.STDOUT,
                                          universal_newlines=True)
     except subprocess.CalledProcessError:
         QMessageBox.warning(self, "WARNING", "Execution of command failed")
         QMessageBox.warning(self, "WARNING", str(subprocess.STDOUT))
     out_put = str(output)
     QMessageBox.information(self, 'INFO', 'Command executed successfully')
Пример #18
0
Файл: GUI.py Проект: eJNIK/adist
class ProcessingWindow(QWidget):
    def __init__(self, parent=None):
        super(ProcessingWindow, self).__init__(parent)

        self.progress = QProgressBar(self)
        self.progress.setGeometry(200, 80, 280, 20)
        self.progress.move(50, 45)

        self.new_btn = QPushButton('New inputs', self)
        self.new_btn.resize(90, 40)
        self.new_btn.move(10, 100)

        self.run_btn = QPushButton('Run!', self)
        self.run_btn.resize(90, 40)
        self.run_btn.move(150, 100)

        self.back_btn = QPushButton('Back', self)
        self.back_btn.resize(90, 40)
        self.back_btn.move(280, 100)
Пример #19
0
class ProgressBar(QDialog):
    def __init__(self, parent=None):
        super(ProgressBar, self).__init__(parent)
        self.init_ui()

        self.in_progress = False

    def change_text(self, text):
        self.label.setText(text)
        self.label.resize(self.label.sizeHint())

    def change_percent(self, value):
        self.bar.setValue(int(value))

    def init_ui(self):
        self.label = QLabel("Gathering file data...", self)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.move(50, 50)
        self.label.resize(self.label.sizeHint())

        self.bar = QProgressBar(self)
        self.bar.move(50, 100)
        self.bar.resize(400, 25)

        self.setFixedSize(500, 200)
        self.setWindowTitle('Update Progress')
        self.setWindowIcon(
            QIcon(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             "launcher_files/aotr.ico")))
        self.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint)

    def closeEvent(self, evnt):
        if not self.in_progress:
            super(ProgressBar, self).closeEvent(evnt)
        else:
            evnt.ignore()

    def keyPressEvent(self, evnt):
        if not evnt.key() == Qt.Key_Escape:
            super(ProgressBar, self).keyPressEvent(evnt)
Пример #20
0
    def algorithm_selectionbtn_clicked(self):

        progress = QProgressBar()
        progress.setGeometry(200, 80, 250, 20)
        progress.move(600, 600)
        progress.setWindowTitle('Processing..')
        progress.setAlignment(QtCore.Qt.AlignCenter)
        progress.show()
        time.sleep(1)

        exp_path = self.experiment_path_file.text()

        os.chdir('.\\LGM-Geocoding-master')
        command = f'python algorithm_selection.py -experiment_path {exp_path}'

        try:
            output = subprocess.call(command, shell=True)
        except subprocess.CalledProcessError:
            QMessageBox.warning(self, "WARNING", output)
        QMessageBox.information(self, "OUTPUT", output)
        print(output)
Пример #21
0
class MainWindow(QWidget):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi()
        self.tutorial_thread = TutorialThread()
        self.tutorial_thread.set_max.connect(self.set_max)
        self.tutorial_thread.update.connect(self.set_value)
        self.show()

    def setupUi(self):
        self.setGeometry(300, 300, 250, 250)
        self.setWindowTitle("ProgressBar")

        self.button_start = QPushButton('Start', self)
        self.button_start.resize(150, 40)
        self.button_start.move(50, 50)
        self.button_stop = QPushButton(self)
        self.button_stop.setText("End")
        self.button_stop.resize(150, 40)
        self.button_stop.move(50, 90)

        self.progress_bar = QProgressBar(self)
        self.progress_bar.resize(150, 5)
        self.progress_bar.move(50, 130)

        self.button_start.clicked.connect(self.start)
        self.button_stop.clicked.connect(self.stop)
        self.show()

    def start(self):
        self.tutorial_thread.start()

    def stop(self):
        self.tutorial_thread.terminate()

    def set_max(self, data):
        self.progress_bar.setMaximum(data)

    def set_value(self, data):
        self.progress_bar.setValue(data)
Пример #22
0
class Nexo_grafico(QObject):
    dano = pyqtSignal(int)
    def __init__(self, pos, child, parent, thr):
        super().__init__()
        self.nexo = child
        self.nexo.comunicador = self.comunicador
        self.nexo.elcomunicador()
        self.dano.connect(thr.recibir_dano)
        self.nexo.setPixmap(QPixmap("tower"))
        self.nexo.move(pos[0], pos[1])
        self.nexo.setScaledContents(True)
        self.nexo.resize(80, 80)
        self.life = QProgressBar(parent)
        self.life.resize(self.nexo.geometry().width(), 5)
        self.life.setMinimum(0)
        self.life.setMaximum(thr.vida)
        self.life.setValue(thr.vida)
        self.life.move(self.nexo.x(), self.nexo.y() - 7)
        self.nexo.show()

    def comunicador(self, hit):
        self.dano.emit(hit)
Пример #23
0
class MyClass(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('编程')
        self.resize(600,600)

        self.progress=0
        self.timer=QBasicTimer()
        self.progressbar=QProgressBar(self)
        self.progressbar.move(50,50)
        self.progressbar.setMaximum(100)
        self.progressbar.setMinimum(0)

        self.progressbar.setValue(self.progress)

        self.btn=QPushButton("bigin",self)
        self.btn.move(100,100)
        self.btn.clicked.connect(self.changeProgress)

        self.show()

    def changeProgress(self):
        if self.timer.isActive():
            # self.timer.start(100)
            self.timer.stop()
            self.btn.setText('开始')

        else:
            self.timer.start(100, self)
            self.btn.setText('停止')
    def timerEvent(self, a0: 'QTimerEvent'):
        self.progress+=1
        self.progressbar.setValue(self.progress)
        if self.progress==100:
            self.changeProgress()
Пример #24
0
class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__()
        self.set_settings()
        self.create_widgets()

    def set_settings(self):
        self.resize(400, 200)

    def create_widgets(self):
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setFixedWidth(300)
        self.progress_bar.move(50, 80)
        # Timer creating:
        self.timer = QBasicTimer()
        self.step = 0
        self.timer.start(100, self)

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
        self.step += 1
        self.progress_bar.setValue(self.step)
Пример #25
0
    def model_selectionbtn_clicked(self):
        progress = QProgressBar()
        progress.setGeometry(200, 80, 250, 20)
        progress.move(600, 600)
        progress.setWindowTitle('Processing..')
        progress.setAlignment(QtCore.Qt.AlignCenter)
        progress.show()
        time.sleep(1)
        os.chdir('.\\LGM-Geocoding-master')
        exp_path = self.experiment_path_file.text() + "\\"

        print(os.getcwd())
        print(exp_path)
        theclassifierstr = self.clasifiercomboBox.itemText(
            self.clasifiercomboBox.currentIndex())

        command = f'python model_selection.py -classifier {theclassifierstr} -experiment_path {exp_path}'
        output = subprocess.run(command,
                                shell=True,
                                check=True,
                                capture_output=True)

        QMessageBox.information(self, "INFO", str(output))
Пример #26
0
class NowTransformClass(QWidget):
    # イニシャライズ
    def __init__(self, parent=None, json_name=""):
        print(json_name)
        print("NowTransformClass")
        # すぱー
        super(NowTransformClass, self).__init__()

        # フォルダ内のjsonすべて取る
        self.json_name = json_name

        # UI初期化
        self.initUI()

    # UI設定
    def initUI(self):
        # 実行中の経過を表示
        # 大きさとタイトル
        self.resize(1000, 500)
        self.setWindowTitle("変換してるよ")
        # プログレスばー
        self.progress_bar = QProgressBar(self)
        self.progress_bar.move(10, 10)

        # 見せるぜ
        self.show()

        # 実行とか
        self.thread = TransformThread(self.json_name)
        self.progress_bar.setMaximum(100)
        self.progress_bar.setValue(0)
        self.thread.change_value.connect(self.set_progress_bar_value)
        self.thread.start()

    # プログレスバーデータセット
    def set_progress_bar_value(self, val):
        self.progress_bar.setValue(val)
Пример #27
0
class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.set_settings()
        self.create_widgets()

    def set_settings(self):
        self.resize(350, 200)
        self.setWindowIcon(QIcon(f"{BASE_DIR}/static/logo.png"))

    def create_widgets(self):
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setFixedWidth(300)
        self.progress_bar.move(20, 80)
        # timer creating
        self.timer = QBasicTimer()
        self.step = 0
        self.timer.start(100, self)

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
        self.step += 1
        self.progress_bar.setValue(self.step)
Пример #28
0
class Actions(QDialog):
    """진행률 표시 줄과 버튼으로 구성된 다이얼로그 박스."""
    def __init__(self):
        super().__init__()
        self.progress = None
        self.calc = None
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Defect Classification in progress')
        self.progress = QProgressBar(self)
        self.progress.setGeometry(0, 0, 300, 25)
        self.progress.setMaximum(100)
        self.progress.move(10, 10)
        self.progress.setStyleSheet("QProgressBar { text-align: center; } ")
        self.show()
        self.calc = External()
        self.calc.countChanged.connect(self.onCountChanged)
        self.calc.start()

    def onCountChanged(self, value):
        self.progress.setValue(value)
        if value == 100:
            self.close()
Пример #29
0
class App(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('The Seeker of fire')
        self.showFullScreen()

        self.Text = QLabel(self)
        self.book = QLabel(self)
        self.location = QLabel(self)
        self.changed = False

        self.action_targ = QLabel(self)
        self.action_targ.resize(self.width() / 12, 10)
        self.action_targ.move(0, 0)
        self.action_targ.setStyleSheet('QLabel {background-color: Red;'
                                       'border-radius: 5px }')
        self.targ_pos = [(self.width() / 2.17, self.height() / 2.5 - 20),
                         (self.width() / 2.9, self.height() / 2.5 - 20),
                         (self.width() / 1.75, self.height() / 2.5 - 20)]

        self.the_right_answer = [False, False, False]

        self.ur_damage = 10
        self.e_damage = 0
        self.HP_points = 100
        self.eHP_points = 100
        self.result = False

        self.cursor = QCursor(QPixmap('cursor_3.png'))
        self.cursor.pixmap()
        self.setCursor(self.cursor)

        self.skip = QPushButton(self)
        self.skip.resize(100, 20)
        self.skip.move(self.width() / 2 + 180,
                       self.height() / 4 + self.height() / 16 + 20)
        self.skip.setText('SKIP')
        self.skip.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2)}'
            'QPushButton:hover {background-color: Red}')
        self.read = True
        self.skip.clicked.connect(self.next)

        melody = 'DS2.wav'
        self.playable = QSound(melody)
        self.playable.play()

        melody2 = 'in_battle.wav'
        self.playable2 = QSound(melody2)
        self.next_melody = False

        self.movie = QMovie("fire_3.gif")
        self.movie.setScaledSize(QSize(self.width(), self.height()))
        self.movie.frameChanged.connect(self.repaint)
        self.movie.start()

        self.NPC_enemy = QLabel(self)
        self.NPC_enemy.resize(self.height() / 5, self.height() / 5)
        self.NPC_enemy.move(self.width() / 2.3, self.height() / 16)
        self.NPC_enemy.setStyleSheet(
            "QLabel {color: rgb(0, 0, 51);"
            'background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgba(100, 100, 100, 0.5);'
            'border-style: solid;'
            'border-width: 2px;'
            '}'
            'QLabel:hover {background-color: rgba(100, 0, 0, 0.7)}')

        self.book.resize(self.width() / 3, self.height() / 16)
        self.book.move(self.width() / 3, self.height() / 4 + 40)
        self.book.setStyleSheet(
            "QLabel {background-color: rgba(100, 40, 51, 0.5);"
            "text-align: center }")
        self.book.setFont(QFont('Times New Roman', 12))

        self.attack = QPushButton(self)
        self.defend = QPushButton(self)
        self.dodge = QPushButton(self)

        self.change_size('attack_proj.png',
                         (int(self.width() / 12), int(self.height() / 4)))
        self.change_size('shield.png',
                         (int(self.width() / 12), int(self.height() / 4)))
        self.change_size('dodging.png',
                         (int(self.width() / 12), int(self.height() / 4)))

        self.attack.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px;'
            'border-radius: 40px;'
            'background-image: url(attack_proj.png)'
            '}'
            'QPushButton:pressed {background-image: url(DS3.jpg)}')
        self.attack.resize(self.width() / 12, self.height() / 4)
        self.attack.move(self.width() / 2.17, self.height() / 2.5)
        self.attack.clicked.connect(self.attack_fnc)

        self.defend.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px;'
            'border-radius: 40px;'
            'background-image: url(shield.png)'
            '}'
            'QPushButton:pressed {background-image: url(DS3.jpg)}')
        self.defend.resize(self.width() / 12, self.height() / 4)
        self.defend.move(self.width() / 2.9, self.height() / 2.5)
        self.defend.clicked.connect(self.defend_fnc)

        self.dodge.setStyleSheet(
            'QPushButton {background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px;'
            'border-radius: 40px;'
            'background-image: url(dodging.png)'
            '}'
            'QPushButton:pressed {background-image: url(DS3.jpg)}')
        self.dodge.resize(self.width() / 12, self.height() / 4)
        self.dodge.move(self.width() / 1.75, self.height() / 2.5)
        self.dodge.clicked.connect(self.dodge_fnc)

        self.Text.move(self.width() / 3, 0)
        self.Text.resize(self.width() / 3, self.height())
        self.Text.move(self.width() / 3, 0)

        self.Text.setStyleSheet(
            "QLabel {color: rgb(0, 0, 51);"
            'font-family: "Times New Roman", Georgia, Serif;'
            'font-size: 25px;'
            'background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgb(10, 20, 100,);'
            'border-style: solid;'
            'border-width: 5px'
            '}')
        self.HP = QProgressBar(self)
        self.HP.resize(self.width() / 3, 30)
        self.HP.move(self.width() / 3, self.height() * 0)
        self.HP.setStyleSheet(
            "QProgressBar{border: 1px solid transparent;text-align: center;"
            "color:rgba(255,255,250,0);"
            "border-radius: 10px;"
            "border-width: 8px;"
            "border-image: 9,2,5,2; "
            "background-color: Grey;"
            "}"
            "QProgressBar::chunk {background-color: qlineargradient(x1: 0, "
            "y1: 0, x2: 0, y2: 1, stop: 0 rgba(100,80,50,1), stop: 1 rgba(255,0,0,1));"
            "border-radius: 5px}")
        self.HP.setValue(self.HP_points)

        self.eHP = QProgressBar(self)
        self.eHP.resize(self.width() / 6, 10)
        self.eHP.setStyleSheet(
            "QProgressBar{border: 1px solid transparent;text-align: center;"
            "color:rgba(255,255,250,0);"
            "border-radius: 10px;"
            "border-width: 8px;"
            "border-image: 9,2,5,2; "
            "background-color: Grey"
            "}"
            "QProgressBar::chunk {background-color: qlineargradient(x1: 0, "
            "y1: 0, x2: 0, y2: 1, stop: 0 rgba(100,80,50,100), stop: 1 rgba(255,0,0,255));"
            "border-radius: 5px}")
        self.eHP.move(self.width() / 2.45, self.width() / 6.5)

        self.close_button = QPushButton(self)
        self.close_button.resize(self.width() / 4, self.height() / 20)
        self.close_button.move(self.width() / 3 + self.width() / 24,
                               self.height() / 1.07)
        self.close_button.setStyleSheet(
            'QPushButton {border: 3px solid;'
            'border-radius: 10px;'
            'background-color: Khaki'
            '}'
            'QPushButton:pressed{border: 1px solid;'
            'border-radius: 40px;'
            'background-color: Red'
            '}'
            'QPushButton:hover{background-color: rgba(255, 0, 0, 40)}')
        self.close_button.clicked.connect(self.close_event)
        self.close_button.setFont(QFont('Times New Roman', 20))
        self.close_button.setText('Выход')

        self.location.resize(self.width() / 3, self.height() / 8)
        self.location.move(self.width() / 3, self.height() / 4)
        self.location.setFont(QFont('Times New Roman', 20))
        self.location.setText('ЗАБРОШЕННЫЕ МОГИЛЫ')
        self.location.setStyleSheet(
            "QLabel {background-color: rgba(250, 40, 51, 0.5);"
            "}")
        self.location.setAlignment(Qt.AlignCenter)

        self.game()

    def next(self):
        self.read = False

    def paintEvent(self, event):
        currentframe = self.movie.currentPixmap()
        framerect = currentframe.rect()
        framerect.moveCenter(self.rect().center())
        if framerect.intersects(event.rect()):
            painter = QPainter(self)
            painter.drawPixmap(framerect.left(), framerect.top(), currentframe)

    def close_event(self):
        self.close()

    def game(self):
        dont_stop = threading.Thread(target=self.always_on)
        screen = threading.Thread(target=self.on_screen)
        screen.start()
        dont_stop.start()

    def on_screen(self):
        self.HP.show()
        self.close_button.show()
        self.Text.show()
        self.book.show()
        self.NPC_enemy.show()
        self.skip.show()
        self.attack.show()
        self.defend.show()
        self.dodge.show()
        self.eHP.show()

        self.write('И в самом деле. Замок, что зовётся Лотриком, ')
        self.write('стоит там, где сходятся земли Повелителей пепла. ')
        self.write(
            'Покоряя север, пилигримы убеждаются, что старые сказания не лгут')
        self.write('Огонь затухает, и повелители пепла покидают свои троны')
        self.write('Когда огонь под угрозой, когда звонит колокол,')
        self.write(' Повелители пепла поднимаются из своих могил.')
        self.write('Олдрик, святой покровитель глубин.')
        self.write('Легион нежити Фаррона, Хранители Бездны')
        self.write(
            'И мрачный правитель из осквернённой столицы - гигант Йорм.')
        self.write(
            'Но в действительности... Повелители оставят свои троны, и негорящие восстанут.'
        )
        self.write('Безымянная, проклятая нежить, недостойная стать пеплом.')
        self.write('И стало так. Негорящие всегда ищут угли.')

        self.location.show()
        time.sleep(2)
        self.location.close()

        self.write('Вы поднимаетесь из могилы. В руках у вас ваш меч. ')
        self.write('Вы чётко знате, что будуте делать дальше')
        self.write('Вам предстоит вернуть повелителей на свои троны и спасти ')
        self.write('угасающий мир от погружения во тьму')
        self.write('Перед вами тропа')
        self.write('Пути назад больше нет')
        self.write('...')
        self.write('Вы идете по тропе')

        self.write(
            'Перед вами Полый, нежить, потерявшая рассудок и навеки лишившаяся '
        )
        self.write('возможности прикоснуться к Огню')
        self.write('Полый достает меч')
        self.write('Приготовьтесь к битве')
        self.write(' ')

        self.NPC_enemy.close()
        self.NPC_enemy.setStyleSheet(
            'QLabel { background-image: url(hollow.jpg)}')
        time.sleep(0.3)
        self.NPC_enemy.show()
        self.next_melody = True
        self.playable.stop()
        # self.eHP.setValue(100)

        self.book.setStyleSheet('QLabel {color: Red }')

        self.the_right_answer = [False, False, True]
        self.write_in_battle('Усиленная атака сверху')
        time.sleep(2)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Вы успешно уклонились')
            self.result = False

        self.the_right_answer = [False, True, False]
        self.write_in_battle('Противник потерял равновесие')
        time.sleep(2)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Вы успешно атаковали')
            self.result = False

        self.the_right_answer = [False, False, True]
        self.write_in_battle('Выпад вперед!')
        time.sleep(1)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Ваш противник в ярости!')
            self.result = False

        self.the_right_answer = [True, False, False]
        self.write_in_battle('Полый нансосит слабый удар')
        time.sleep(1.5)

        if self.result is not True:
            self.write_in_battle('Вы погибли')
            time.sleep(2)
            self.close()
        else:
            self.eHP_points -= 10
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Щит сломан')
            self.result = False

        self.the_right_answer = [False, True, False]
        self.write_in_battle('Полый выронил меч. Это ваш шанс!')
        victory = False
        time.sleep(0.8)

        if self.result is not True:
            self.write_in_battle('Полый увернулся')
            self.write_in_battle('Вы подбираете его щит')
        else:
            self.eHP_points -= 60
            self.eHP.close()
            self.eHP.setValue(self.eHP_points)
            self.eHP.show()
            self.write_in_battle('Полый побежден!')
            self.result = False
            victory = True

        if victory is False:
            self.the_right_answer = [False, False, True]
            self.write_in_battle('Полый нансосит слабый удар')
            time.sleep(1.5)

            if self.result is not True:
                self.write_in_battle('Вы погибли')
                time.sleep(2)
                self.close()
            else:
                self.eHP_points -= 30
                self.eHP.close()
                self.eHP.setValue(self.eHP_points)
                self.eHP.show()
                self.write_in_battle('Парирование')
                self.result = False

            self.the_right_answer = [False, True, False]
            self.write_in_battle('Полый медленно замахнулся')
            time.sleep(1.5)

            if self.result is not True:
                self.write_in_battle('Вы погибли')
                time.sleep(2)
                self.close()
            else:
                self.eHP_points -= 30
                self.eHP.close()
                self.eHP.setValue(self.eHP_points)
                self.eHP.show()
                self.write_in_battle('Полый сделал шаг назад')
                self.result = False

            self.the_right_answer = [False, True, False]
            self.write_in_battle('Полый поднимает меч')
            time.sleep(1.5)

            if self.result is not True:
                self.write_in_battle('Вы погибли')
                time.sleep(2)
                self.close()
            else:
                self.eHP_points -= 10
                self.eHP.close()
                self.eHP.setValue(self.eHP_points)
                self.eHP.show()
                self.write_in_battle('Полый падает')
                self.result = False

        self.next_melody = False
        self.NPC_enemy.close()
        self.NPC_enemy.setStyleSheet(
            "QLabel {color: rgb(0, 0, 51);"
            'background-color: rgba(10, 20, 100, 0.2);'
            'border-color: rgba(100, 100, 100, 0.5);'
            'border-style: solid;'
            'border-width: 2px;'
            '}'
            'QLabel:hover {background-color: rgba(100, 0, 0, 0.7)}')
        time.sleep(0.3)
        self.NPC_enemy.show()
        self.write('Полый побежден')
        if victory is True:
            self.NPC_enemy.close()
            self.NPC_enemy.setStyleSheet(
                'QLabel { background-image: url(letter.jpg)}')
            time.sleep(0.3)
            self.NPC_enemy.show()
            self.write('Вы получили новый щит: урон противников снижен')
            self.write('Ваш щит сломан: урон противников повышен')
            self.write('Вы продолжаете идти по тропе')
            self.write('Справа от вас труп')
            self.write('В его карамане что-то есть')
            self.write('Найдена записка')
            self.write('С тех времен, как Гвин впервые ')
            self.write(
                'разжег <не разобрать>, минуло много веков и много циклов <не разобрать>'
            )
            self.write('пламени. После того, как он разжег огонь,')
            self.write('этот путь повторили многие великие герои, ')
            self.write('известные как <не разобрать>')

    def always_on(self):
        while True:
            time.sleep(0.5)
            if self.playable.isFinished() is True:
                if self.next_melody is False:
                    self.playable2.stop()
                    self.playable.play()
            if self.playable2.isFinished() is True:
                if self.next_melody is True:
                    self.playable2.play()

    def change_size(self, input_image_path, size=(0, 0)):
        original_image = Image.open(input_image_path)
        resized_image = original_image.resize(size)
        resized_image.save(input_image_path)
        self.changed = True

    def write(self, text):
        your_text = ' '

        for letter in text:
            if self.read is True:
                time.sleep(0.1)
                your_text += letter
                self.book.setText(your_text)
            else:
                self.read = True
                break
        time.sleep(0.2)

    def write_in_battle(self, text):
        your_text = ' '

        for letter in text:
            time.sleep(0.05)
            your_text += letter
            self.book.setText(your_text)

    def defend_fnc(self):
        if self.the_right_answer[0] is True:
            self.result = True
        else:
            self.result = False

        self.action_targ.close()
        self.action_targ.move(self.targ_pos[1][0], self.targ_pos[1][1])
        self.action_targ.show()

    def attack_fnc(self):
        if self.the_right_answer[1] is True:
            self.result = True
        else:
            self.result = False
        self.action_targ.close()
        self.action_targ.move(self.targ_pos[0][0], self.targ_pos[0][1])
        self.action_targ.show()

    def dodge_fnc(self):
        if self.the_right_answer[2] is True:
            self.result = True
        else:
            self.result = False
        self.action_targ.close()
        self.action_targ.move(self.targ_pos[2][0], self.targ_pos[2][1])
        self.action_targ.show()
    def model_evaluationbtn_clicked(self):
        if "LGM-PolygonClassification-master" in str(os.getcwd()):
            pass
        else:
            #os.chdir()
            os.chdir(os.getcwd() + "\\LGM-PolygonClassification-master")
        #choose test dataset file
        file_path = self.test_data_chosen_file.text()
        temp12 = str(file_path).replace("[", "").replace("]", "").replace(
            "'", '').replace(" ", "")

        #choose classifier
        theclassifierstr = self.classifier_comboBox.itemText(
            self.classifier_comboBox.currentIndex())
        theclassifierstr = theclassifierstr.replace('"', "")

        evaluation_cmd = f'python -m polygon_classification.cli evaluate --dataset {temp12} --classifier {theclassifierstr}'
        #need to check if the selected classifier-model exists inside models folder
        if theclassifierstr == "SVM":

            if os.path.exists(os.getcwd() + "\\models\\SVM_model.joblib"):
                QMessageBox.information(
                    self, "INFO", "The selected model exists. You may proceed")
                try:
                    progress = QProgressBar()
                    progress.setGeometry(200, 80, 250, 20)
                    progress.move(600, 600)
                    progress.setWindowTitle('Processing..')
                    progress.setAlignment(QtCore.Qt.AlignCenter)
                    progress.show()

                    output = subprocess.check_output(evaluation_cmd,
                                                     shell=True,
                                                     stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(self, "WARNING", str(output))
                #print(output)
                QMessageBox.information(self, "OUTPUT", str(output))
            else:
                QMessageBox.information(
                    self, "INFO",
                    "The selected classifier does not exist. Choose again")

        if theclassifierstr == "DecisionTree":
            if os.path.exists(os.getcwd() +
                              "\\models\\DecisionTree_model.joblib"):
                QMessageBox.information(
                    self, "INFO", "The selected model exists. You may proceed")
                try:
                    progress = QProgressBar()
                    progress.setGeometry(200, 80, 250, 20)
                    progress.move(600, 600)
                    progress.setWindowTitle('Processing..')
                    progress.setAlignment(QtCore.Qt.AlignCenter)
                    progress.show()

                    output = subprocess.check_output(evaluation_cmd,
                                                     shell=True,
                                                     stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(self, "WARNING", str(output))
                #print(output)
                QMessageBox.information(self, "OUTPUT", str(output))
            else:
                QMessageBox.information(
                    self, "INFO",
                    "The selected classifier does not exist. Choose again")

        if theclassifierstr == "RandomForest":

            if os.path.exists(os.getcwd() +
                              "\\models\\RandomForest_model.joblib"):
                QMessageBox.information(
                    self, "INFO", "The selected model exists. You may proceed")
                try:
                    progress = QProgressBar()
                    progress.setGeometry(200, 80, 250, 20)
                    progress.move(600, 600)
                    progress.setWindowTitle('Processing..')
                    progress.setAlignment(QtCore.Qt.AlignCenter)
                    progress.show()

                    output = subprocess.check_output(evaluation_cmd,
                                                     shell=True,
                                                     stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(self, "WARNING", str(output))
                #print(output)
                QMessageBox.information(self, "OUTPUT", str(output))
            else:
                QMessageBox.information(
                    self, "INFO",
                    "The selected classifier does not exist. Choose again")

        if theclassifierstr == "ExtraTrees":
            if os.path.exists(os.getcwd() +
                              "\\models\\ExtraTrees_model.joblib"):
                QMessageBox.information(
                    self, "INFO", "The selected model exists. You may proceed")
                try:
                    progress = QProgressBar()
                    progress.setGeometry(200, 80, 250, 20)
                    progress.move(600, 600)
                    progress.setWindowTitle('Processing..')
                    progress.setAlignment(QtCore.Qt.AlignCenter)
                    progress.show()

                    output = subprocess.check_output(evaluation_cmd,
                                                     shell=True,
                                                     stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(self, "WARNING", str(output))
                print(output)
                QMessageBox.information(self, "OUTPUT", str(output))
            else:
                QMessageBox.information(
                    self, "INFO",
                    "The selected classifier does not exist. Choose again")

        if theclassifierstr == "XGBoost":
            if os.path.exists(os.getcwd() + "\\models\\XGBoost_model.joblib"):
                QMessageBox.information(
                    self, "INFO", "The selected model exists. You may proceed")
                try:
                    progress = QProgressBar()
                    progress.setGeometry(200, 80, 250, 20)
                    progress.move(600, 600)
                    progress.setWindowTitle('Processing..')
                    progress.setAlignment(QtCore.Qt.AlignCenter)
                    progress.show()

                    output = subprocess.check_output(evaluation_cmd,
                                                     shell=True,
                                                     stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(self, "WARNING", str(output))
                #print(output)
                QMessageBox.information(self, "OUTPUT", str(output))
            else:
                QMessageBox.information(
                    self, "INFO",
                    "The selected classifier does not exist. Choose again")

        if theclassifierstr == "MLP":
            if os.path.exists(os.getcwd() + "\\models\\MLP_model.joblib"):
                QMessageBox.information(
                    self, "INFO", "The selected model exists. You may proceed")
                try:
                    progress = QProgressBar()
                    progress.setGeometry(200, 80, 250, 20)
                    progress.move(600, 600)
                    progress.setWindowTitle('Processing..')
                    progress.setAlignment(QtCore.Qt.AlignCenter)
                    progress.show()

                    output = subprocess.check_output(evaluation_cmd,
                                                     shell=True,
                                                     stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError:
                    QMessageBox.warning(self, "WARNING", str(output))
                #print(output)
                QMessageBox.information(self, "OUTPUT", str(output))
            else:
                QMessageBox.information(
                    self, "INFO",
                    "The selected classifier does not exist. Choose again")
        QWidget.update(self)
Пример #31
0
class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.instr = QLabel("Choose an extension and the link to download from", self)
        self.instr.move(20, 15)

        self.ext_label = QLabel("Extension: ", self)
        self.ext_label.move(20, 50)


        self.ext_input = QLineEdit(self)
        self.ext_input.move(115, 45)
        self.ext_input.returnPressed.connect(self.download)

        self.dom_label = QLabel("Link: ", self)
        self.dom_label.move(20, 90)

        self.dom_input = QLineEdit(self)
        self.dom_input.move(115, 85)
        self.dom_input.returnPressed.connect(self.download)

        self.dwl_but = QPushButton("Download", self)
        self.dwl_but.move(280,45)
        self.dwl_but.resize(100, 75)
        self.dwl_but.clicked.connect(self.download)

        self.dwl_bar = QProgressBar(self)
        self.dwl_bar.move(20, 125)
        self.dwl_bar.resize(360, 25)

        self.results = QTextEdit(self)
        self.results.move(20, 150)
        self.results.resize(360, 100)
        self.results.setReadOnly(True)



        self.setGeometry(300, 300, 400, 300)
        self.setFixedSize(400, 300)
        self.setWindowTitle("File Crawler")
        self.show()

    def download(self):
        self.results.setText("")
        file = str(QFileDialog.getExistingDirectory(self, "Onde salvar?"))
        if (file != ""):
            domain = self.dom_input.text()
            extension = self.ext_input.text()
            try:
                web_text = urlopen(domain, timeout=1.5).read().decode('utf-8', 'ignore')
            except ValueError:
                try:
                    domain = "http://"+domain
                    web_text = urlopen(domain, timeout=1.5).read().decode('utf-8', 'ignore')
                except Exception as e:
                    self.results.append(str(e))
                    web_text = None
            except Exception as e:
                self.results.append(str(e))
                web_text = None

            if web_text != None:
                double_b_file_pattern = re.compile("=\"([^(\'|\")]*\."+extension+")")
                simple_b_file_pattern = re.compile("=\'([^(\'|\")]*\."+extension+")")
                matches = double_b_file_pattern.findall(web_text)
                matches.extend(simple_b_file_pattern.findall(web_text))
            else:
                matches = []
            if len(matches) > 0:
                self.dwl_bar.setValue(0)
                self.results.append("Saving to " + file)
                self.results.append("%d files were found." % len(matches))
                for index, item in enumerate(matches, 1):
                    self.dwl_bar.setValue(int(100 * index / len(matches)))
                    try:
                        download(urljoin(domain, item), file + "/" + split(item)[-1])
                    except Exception as e:
                        # Document links may be broken, in this case, nothing to do.
                        self.results.append("Could not download {}, {}".format(split(item)[-1], e))
                self.results.append("Finished downloading.")
            else:
                self.results.append("Could not find any file.")