class MainWindow: def __init__(self): self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ds = DataStore() self.ui.setupUi(self.main_win) self.ui.stackedWidget.setCurrentWidget(self.ui.home) self.ui.bmr_batton.clicked.connect(self.showBMR) self.ui.bmi_button.clicked.connect(self.showBMI) self.ui.bmr_calculate_button.clicked.connect(self.calcBMR) self.ui.bmi_calculate_button.clicked.connect(self.calcBMI) def show(self): self.main_win.show() def showBMR(self): self.ui.stackedWidget.setCurrentWidget(self.ui.bmr) def showBMI(self): self.ui.stackedWidget.setCurrentWidget(self.ui.bmi) def calcBMR(self): if self.ui.bmr_male_radio.isChecked(): gender = "male" else: gender = "female" height = int(self.ui.bmr_height_input.text()) weight = int(self.ui.bmr_weight_input.text()) age = int(self.ui.bmr_age_input.text()) if self.ui.bmr_sedentary.isChecked(): activity = "sedentary" elif self.ui.bmr_lighthy.isChecked(): activity = "lighthy" elif self.ui.bmr_moderately.isChecked(): activity = "moderately" elif self.ui.bmr_very.isChecked(): activity = "very" else: activity = "extremely" result = self.ds.bmr_calc(gender, height, weight, age, activity) output = "The BMR for a {} year old {}, who is {} cm tall and {} kg heavy with a {} activity level is {} calories.".format( age, gender, height, weight, activity, result) self.ui.bmr_output_label.setText(output) def calcBMI(self): height = int(self.ui.bmi_height_input.text()) weight = int(self.ui.bmi_weight_input.text()) result = self.ds.bmi_calc(height, weight) outpuut = "You entered the following information for BMI: Height {} cm & Weight: {} kg. This meansyourBMI is {}".format( height, weight, result) self.ui.bmi_output_label.setText(outpuut)
class Main(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) # This is always the samej self.ui=Ui_MainWindow() self.ui.setupUi(self) self.ui.DownloadFolder.setText(QtCore.QDir.homePath() + "/Downloads") self.ui.statusbar.showMessage("Ready") self.ui.BrowseButton.clicked.connect(self.SetDownloadFolder) self.ui.DownloadButton.clicked.connect(self.Download) def SetDownloadFolder(self): dir = QtGui.QFileDialog.getExistingDirectory(self, "Select Downloads Directory", QtCore.QDir.homePath() + "/Downloads", QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks) if(dir != ''): self.ui.DownloadFolder.setText(dir) def Download(self): if (str(self.ui.NhacSoURL.text()).startswith('http://www.nhacso.net') or str(self.ui.NhacSoURL.text()).startswith('http://nhacso.net')) : NhacSoURLParser(unicode(str(self.ui.NhacSoURL.text()), 'utf-8')) for i in range(len(song_name)): self.ui.statusbar.showMessage("Downloading " + song_name[i]) print "Downloading %s" % (song_name[i]) urlretrieve(song_mp3link[i], unicode(self.ui.DownloadFolder.text()) + "/" + unicode(song_name[i]) + " - " + unicode(song_artist[i]) + ".mp3") print "Done: %s" % (song_name[i]) QtGui.QMessageBox.information(self, "Done", "All files is downloaded!") else: QtGui.QMessageBox.critical(self, "Error", "Please enter vaild URL")
def __init__(self, parent=None): QMainWindow.__init__(self, parent) Ui_MainWindow.setupUi(self, self) self.manager = UserManager() self.users = {} self.lineEdit_appid.setText('wxaafc0692eca7f8d6') self.lineEdit_secret.setText('077b4e1bed2b773c1014efa4512cd652') self.progressBar.setValue(0) self.pushButton_get_openids.setEnabled(False) self.pushButton_dump_all_user.setEnabled(False) self.pushButton_connect.clicked.connect(self.onConnect) self.pushButton_get_openids.clicked.connect(self.onGetOpenids) self.listWidget.currentItemChanged.connect(self.onOpenidFocus) self.manager.connected.connect(self.onConnected) self.manager.openidGot.connect(self.onOpenidGot) self.manager.info.connect(self.onInfo) self.manager.error.connect(self.onError) self.manager.onUser.connect(self.onUserInfo) self.manager.progress.connect(self.onProgressUpdate) self.pushButton_dump_all_user.clicked.connect(self.manager.dump_all_users) self.pushButton_statistics.clicked.connect(self.manager.do_statistic) self.pushButton_gender.clicked.connect(self.manager.show_stat_sex) self.pushButton_language.clicked.connect(self.manager.show_stat_language) self.pushButton_city.clicked.connect(self.manager.show_stat_city) self.pushButton_province.clicked.connect(self.manager.show_stat_province) self.pushButton_country.clicked.connect(self.manager.show_stat_country)
class MainWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) def onBtn1Clicked(self): print("onBtn1Clicked")
class Win(QtGui.QMainWindow): def __init__(self, parent=None): super(Win, self).__init__(parent) self.initUI() def initUI(self): self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show()
def __init__(self): self.app = QtGui.QApplication(sys.argv) jsonpickle.ext.numpy.register_handlers() mw = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(mw) #Obtain DesktopWidget to gain screen sizes dw = QtGui.QDesktopWidget() screen = dw.availableGeometry() #Resize main window to 90% of the screen width/height mw.resize(screen.size() * 0.9) #Recenter main window frame = mw.frameGeometry() frame.moveCenter(screen.center()) mw.move(frame.topLeft()) pw = gl.GLViewWidget(ui.centralwidget) ui.gridLayout.replaceWidget(ui.plotWidget, pw) ui.plotWidget.hide() ui.plotWidget = pw self.ui = ui self.mw = mw self.pw = pw self.tree = None self.paths = None self.seedAmt = None self.state = -1 mw.setWindowTitle("Hierarchical Visualizer") pw.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) axis = gl.GLAxisItem() xText = glt.GLTextItem(GLViewWidget=self.pw, X=1, Y=0, Z=0, text="X") yText = glt.GLTextItem(GLViewWidget=self.pw, X=0, Y=1, Z=0, text="Y") zText = glt.GLTextItem(GLViewWidget=self.pw, X=0, Y=0, Z=1, text="Z") self.pw.addItem(axis) self.pw.addItem(xText) self.pw.addItem(yText) self.pw.addItem(zText) self.connectSlots()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Tarea 5') self.error = QMessageBox() self.listStudents = [] self.ui.add.clicked.connect(self.addF) self.ui.deleteS.clicked.connect(self.delete_student) self.ui.readS.clicked.connect(self.read_student) self.ui.listWidget.currentRowChanged.connect(self.show_details) def show_error(self, message): self.error.setText(message) self.error.setIcon(QMessageBox.Warning) self.error.exec_() @Slot() def addF(self): temp = student(self.ui.name.text(), self.ui.email.text(), self.ui.password.text()) self.listStudents.append(temp) student.saveStudentP(self.listStudents) self.ui.listWidget.addItem(temp.getName()) self.ui.name.setText('') self.ui.email.setText('') self.ui.password.setText('') @Slot() def show_details(self): self.ui.textEdit.clear() temp = self.listStudents[self.ui.listWidget.currentRow()] self.ui.textEdit.append(str(temp)) @Slot() def delete_student(self): try: self.listStudents.pop(self.ui.listWidget.currentRow()) self.ui.listWidget.takeItem(self.ui.listWidget.currentRow()) except: self.show_error("No hay estudiantes por borrar") @Slot() def read_student(self): self.listStudents.append(student.readStudentP('studentsP.db')) for i in student.readStudentP('studentsP.db'): self.ui.textEdit.append(str(i))
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionOpen.triggered.connect(self.open) self.ui.actionGet_User_Info.triggered.connect(self.GetUserInfo) def open(self): print ("Open") def GetUserInfo(self): wd = InfoDialog(self).GetResult() if wd : print (wd) def closeEvent(self,event): print ("CloseEvent")
def __init__(self, c1, c2, parent=None): QMainWindow.__init__(self, parent) ui = Ui_MainWindow() ui.setupUi(self) colKeys = sorted(list(set(c1.keys).intersection(c2.keys))) self._mdl = TableModel(c1, c2, colKeys[0], self) ui.tableView.setModel(self._mdl) self._ui = ui ui.columnCombo.addItems(colKeys) ui.columnCombo.currentTextChanged.connect(self.updateCols) ui.columnCombo.setCurrentText(colKeys[0]) ui.refCombo.addItems(colKeys) ui.refCombo.currentTextChanged.connect(self.updateCols) ui.refCombo.addItems(colKeys) self.updateCols()
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.showFileDialog) def showFileDialog(self): fname = QFileDialog.getOpenFileName(self.ui.centralwidget, 'Open file')[0] if fname: f = open(fname, 'r') self.openDetectWindow(str(f.name)) f.close() def openDetectWindow(self, file_name): dialog = DetectObjectWindow(self, file_name) dialog.show()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self._ui = Ui_MainWindow() self._ui.setupUi(self) self._provider = ReminderApiProvider('http://localhost:8080') self._collections_model = CollectionsModel(self._provider) self._table_model = None self._ui.comboBox.setModel(self._collections_model) self._ui.comboBox.currentTextChanged.connect(self._set_collection) self._collections_model.update_model() self._set_collection(self._ui.comboBox.currentText()) @Slot() def _set_collection(self, collection: str): self._table_model = CollectionTableModel(self._provider, collection) self._table_model.update_model() self._ui.tableView.setModel(self._table_model)
class MainWindow(QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) # set up ui self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Network Analyzer') # connect signals self.ui.portScan.clicked.connect(self._onPortScanClicked) self.ui.launchServer.clicked.connect(self._onLaunchServerClicked) self.ui.networkScan.clicked.connect(self._onNetworkScanClicked) self.ui.getHostNameButton.clicked.connect(self._onGetHostNameClicked) self.ui.quitButton.clicked.connect(self._onQuitClicked) def _onPortScanClicked(self): portScanWindow = PortScanWindow(self) portScanWindow.show() def _onLaunchServerClicked(self): launchWindow = LaunchServer(self) launchWindow.show() def _onNetworkScanClicked(self): networkScanWindow = NetworkScanDisplay(self) networkScanWindow.show() networkScanWindow.scan() def _onGetHostNameClicked(self): getHostNameWindow = GetHostNameWindow(self) getHostNameWindow.show() def _onQuitClicked(self): self.close()
roslib.load_manifest('cob_script_server') import rospy from std_msgs.msg import String import threading from simple_script_server import simple_script_server from cob_srvs.srv import Trigger import sys, os from PyQt4.QtCore import QThread, pyqtSignal from PyQt4.QtGui import QApplication, QMainWindow from Ui_MainWindow import Ui_MainWindow app = QApplication(sys.argv) window = QMainWindow() ui = Ui_MainWindow() ui.setupUi(window) # ROS - Worker Thread class RosThread(QThread): add = pyqtSignal(str) rem = pyqtSignal(str) name_gripper="3-Finger-Hand" name_vacuum ="Vacuum-Cleaner" def __init__(self, ui, parent = None): QThread.__init__(self, parent) self.ui = ui self.mode="linear" self.add[str].connect(self.onAdd) self.rem[str].connect(self.onRem)
class MainWindow(QtGui.QMainWindow): needsThetaInputList = ['Momentum transfer (Q Angstroms^-1)', 'd-Spacing (Angstroms)'] needsThetaOutputList = ['Momentum transfer (Q Angstroms^-1)', 'd-Spacing (Angstroms)'] needsFlightPathInputList = ['Time of flight (microseconds)'] needsFlightPathOutputList = ['Time of flight (microseconds)'] def thetaEnable (self, enabled): self.ui.lineEdit_4.setEnabled(enabled) if enabled == False: self.ui.lineEdit_4.clear() def flightPathEnable (self, enabled): self.ui.lineEdit_3.setEnabled(enabled) if enabled == False: self.ui.lineEdit_3.clear() def setInstrumentInputs (self): #disable both self.thetaEnable(False) self.flightPathEnable(False) #get the values of the two unit strings inOption=self.ui.inputUnits.currentText() outOption=self.ui.outputUnits.currentText() #for theta: enable if input or output unit requires it if inOption in self.needsThetaInputList: self.thetaEnable(True) if outOption in self.needsThetaOutputList: self.thetaEnable(True) #for flightpath: enable if input or output unit requires it if inOption in self.needsFlightPathInputList: self.flightPathEnable(True) if outOption in self.needsFlightPathOutputList: self.flightPathEnable(True) def __init__(self, parent=None): QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) self.setInstrumentInputs() ##defaults self.flightpath=-1.0 self.Theta=-1.0 self.stage1output=0.0 self.stage2output=0.0 def convert(self): if self.ui.InputVal.text() == "": return try: inOption=self.ui.inputUnits.currentText() outOption=self.ui.outputUnits.currentText() if self.ui.lineEdit_3.text() !='': self.flightpath = float(self.ui.lineEdit_3.text()) else: self.flightpath = -1.0 if self.ui.lineEdit_4.text() !='': self.Theta = ((float(self.ui.lineEdit_4.text()) * 3.14159265358979323846264) / 360.0) self.Theta = -1.0 self.stage1output= self.input2energy(float(self.ui.InputVal.text()),inOption) self.stage2output= self.energy2output(self.stage1output,outOption) self.ui.lineEdit_2.clear() self.ui.lineEdit_2.insert(str(self.stage2output)) except Exception, e: QtGui.QMessageBox.warning(self, "TofConverter", str(e)) return
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Our api') self.httpd = HttpServer() self.httpd.request_text_change.connect(self.add_to_request) self.httpd.client_text_change.connect(self.add_to_client) self.httpd.response_text_change.connect(self.add_to_response) self.httpd.start() self.ui.saveSession.clicked.connect(self.save_session) self.ui.resetSession.clicked.connect(self.reset_session) self.ui.testClientGet.clicked.connect(self.run_test_client_get) self.ui.testClientPost.clicked.connect(self.run_test_client_post) self.ui.apiSummary.clicked.connect(self.show_api) self.session_string = '' self.ui.requestText.setReadOnly(True) self.ui.clientText.setReadOnly(True) self.ui.responseText.setReadOnly(True) def add_to_request(self, request_text): request_type, request_string = request_text.split(',') self.ui.requestText.setText(request_string) request_log = f"""\n\n ################### NEW REQUEST ################### \t{request_string}\t ################################################### """ self.session_string += request_log def add_to_client(self, client_text): self.ui.clientText.setText(client_text) request_log = f"Client details\n{client_text}\n" self.session_string += request_log def add_to_response(self, response_text): self.ui.responseText.setText(response_text) request_log = f"\nResponse\n{response_text}\n\n" self.session_string += request_log def save_session(self): file_name, _ = QFileDialog.getSaveFileName(self, "Session File", "", "Text Files (*.txt)") if file_name: with open(file_name, "w") as session_file: session_file.write(self.session_string) def reset_session(self): self.session_string = '' self.ui.requestText.clear() self.ui.clientText.clear() self.ui.responseText.clear() def run_test_client_get(self): get_client = ClientGet(self) get_client.setModal(False) get_client.show() def run_test_client_post(self): post_client = ClientPost(self) post_client.setModal(False) post_client.show() def show_api(self): definitions = Definitions('definitions.ini') definitions.load() api_dialog = ApiDialog(self, definitions.definitions_dict) api_dialog.setWindowTitle('API Functions') api_dialog.setModal(False) api_dialog.show()
class MainWindow(QtGui.QMainWindow): """ Class of Main Window (top) Copy to ui.setupUI # Version 3.0 + Import for Ui_MainWindow.py from MplFigureCanvas import Qt4MplCanvas # Replace 'self.graphicsView = QtGui.QtGraphicsView' with the following self.graphicsView = Qt4MplCanvas(self.centralwidget) self.mainplot = self.graphicsView.getPlot() # Version 2.0 + Import import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from matplotlib.figure import Figure self.figure = Figure((4.0, 3.0), dpi=100) self.mainplot = self.figure.add_subplot(111) self.graphicsView = FigureCanvas(self.figure) self.graphicsView.setParent(self.centralwidget) self.graphicsView.setGeometry(QtCore.QRect(20, 150, 741, 411)) self.graphicsView.setObjectName(_fromUtf8("graphicsView")) # Version 1.0 Replacement is not a valid approach as the UI is setup at the end of self.ui.setupUI self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.figure = Figure((4.0, 3.0), dpi=100) self.mainplot = self.figure.add_subplot(111) self.ui.graphicsView = FigureCanvas(self.figure) self.ui.graphicsView.setParent(self.centralwidget) self.ui.graphicsView.setGeometry(QtCore.QRect(40, 230, 821, 411)) self.ui.graphicsView.setObjectName(_fromUtf8("graphicsView")) """ def __init__(self, parent=None): """ Intialization and set up """ # Base class QtGui.QMainWindow.__init__(self,parent) # Mantid configuration config = ConfigService.Instance() self._instrument = config["default.instrument"] # Central widget self.centralwidget = QtGui.QWidget(self) # UI Window (from Qt Designer) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Do initialize plotting vecx, vecy, xlim, ylim = self.computeMock() self.mainline = self.ui.mainplot.plot(vecx, vecy, 'r-') leftx = [xlim[0], xlim[0]] lefty = [ylim[0], ylim[1]] self.leftslideline = self.ui.mainplot.plot(leftx, lefty, 'b--') rightx = [xlim[1], xlim[1]] righty = [ylim[0], ylim[1]] self.rightslideline = self.ui.mainplot.plot(rightx, righty, 'g--') upperx = [xlim[0], xlim[1]] uppery = [ylim[1], ylim[1]] self.upperslideline = self.ui.mainplot.plot(upperx, uppery, 'b--') lowerx = [xlim[0], xlim[1]] lowery = [ylim[0], ylim[0]] self.lowerslideline = self.ui.mainplot.plot(lowerx, lowery, 'g--') self.ui.graphicsView.mpl_connect('button_press_event', self.on_mouseDownEvent) # Set up horizontal slide (integer) and string value self._leftSlideValue = 0 self._rightSlideValue = 99 self.ui.horizontalSlider.setRange(0, 100) self.ui.horizontalSlider.setValue(self._leftSlideValue) self.ui.horizontalSlider.setTracking(True) self.ui.horizontalSlider.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider, SIGNAL('valueChanged(int)'), self.move_leftSlider) self.ui.horizontalSlider_2.setRange(0, 100) self.ui.horizontalSlider_2.setValue(self._rightSlideValue) self.ui.horizontalSlider_2.setTracking(True) self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider_2, SIGNAL('valueChanged(int)'), self.move_rightSlider) # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), # self.set_startTime) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"), self.set_startTime) # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), # self.set_stopTime) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) self.connect(self.ui.pushButton_setTf, QtCore.SIGNAL("clicked()"), self.set_stopTime) # File loader self.scanEventWorkspaces() self.connect(self.ui.pushButton_refreshWS, SIGNAL('clicked()'), self.scanEventWorkspaces) self.connect(self.ui.pushButton_browse, SIGNAL('clicked()'), self.browse_File) self.connect(self.ui.pushButton_load, SIGNAL('clicked()'), self.load_File) self.connect(self.ui.pushButton_3, SIGNAL('clicked()'), self.use_existWS) # Set up time self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) # Filter by time self.connect(self.ui.pushButton_filterTime, SIGNAL('clicked()'), self.filterByTime) # Filter by log value self.ui.lineEdit_5.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_5)) self.ui.lineEdit_6.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_6)) self.ui.lineEdit_7.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_7)) self.ui.lineEdit_8.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_8)) self.ui.lineEdit_9.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_9)) self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"), self.set_minLogValue) self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"), self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] self.ui.comboBox_4.addItems(dirchangeops) logboundops = ["Centre", "Left"] self.ui.comboBox_5.addItems(logboundops) self.connect(self.ui.pushButton_4, SIGNAL('clicked()'), self.plotLogValue) self.connect(self.ui.pushButton_filterLog, SIGNAL('clicked()'), self.filterByLogValue) # Set up vertical slide self._upperSlideValue = 99 self._lowerSlideValue = 0 self.ui.verticalSlider.setRange(0, 100) self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.verticalSlider.setTracking(True) self.connect(self.ui.verticalSlider, SIGNAL('valueChanged(int)'), self.move_upperSlider) self.ui.verticalSlider_2.setRange(0, 100) self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.verticalSlider_2.setTracking(True) self.connect(self.ui.verticalSlider_2, SIGNAL('valueChanged(int)'), self.move_lowerSlider) # Set up for filtering (advanced setup) self._tofcorrection = False self.ui.checkBox_filterByPulse.setChecked(False) self.ui.checkBox_from1.setChecked(False) self.ui.checkBox_groupWS.setChecked(True) self.connect(self.ui.comboBox_tofCorr, SIGNAL('currentIndexChanged(int)'), self.showHideEi) self.connect(self.ui.pushButton_refreshCorrWSList, SIGNAL('clicked()'), self._searchTableWorkspaces) self.ui.lineEdit_Ei.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_Ei)) self.ui.label_Ei.hide() self.ui.lineEdit_Ei.hide() self.ui.label_Ei_2.hide() self.ui.comboBox_corrWS.hide() self.ui.pushButton_refreshCorrWSList.hide() # Error message # self.connect(self.ui.pushButton_clearerror, SIGNAL('clicked()'), self._clearErrorMsg) # self.ui.plainTextEdit_ErrorMsg.setReadOnly(True) # self.ui.label_error.hide() # Set up for workspaces self._dataWS = None self._sampleLogNames = [] self._sampleLog = None # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() self.ui.label_avg.hide() self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() self.ui.label_logname.hide() self.ui.label_lognamevalue.hide() self.ui.label_logsize.hide() self.ui.label_logsizevalue.hide() # Default self._defaultdir = os.getcwd() # self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) # QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) # QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # self.setInstrumentInputs() ##defaults return def on_mouseDownEvent(self, event): """ Respond to pick up a value with mouse down event """ x = event.xdata y = event.ydata if x is not None and y is not None: msg = "You've clicked on a bar with coords:\n %f, %f" % (x, y) QMessageBox.information(self, "Click!", msg) return def computeMock(self): """ Compute vecx and vecy as mocking """ import random, math x0 = 0. xf = 1. dx = 0.1 vecx = [] vecy = [] x = x0 while x < xf: y = 0.0 vecx.append(x) vecy.append(y) x += dx xlim = [x0, xf] ylim = [-1., 1] return (vecx, vecy, xlim, ylim) def move_leftSlider(self): """ Re-setup left range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ newx = self.ui.horizontalSlider.value() if newx <= self._rightSlideValue and newx != self._leftSlideValue: # Allowed value: move the value bar self._leftSlideValue = newx # Move the vertical line xlim = self.ui.mainplot.get_xlim() newx = xlim[0] + newx*(xlim[1] - xlim[0])*0.01 leftx = [newx, newx] lefty = self.ui.mainplot.get_ylim() setp(self.leftslideline, xdata=leftx, ydata=lefty) self.ui.graphicsView.draw() # Change value self.ui.lineEdit_3.setText(str(newx)) else: # Reset the value to original value self.ui.horizontalSlider.setValue(self._leftSlideValue) return def set_startTime(self): """ Set the starting time and left slide bar """ inps = str(self.ui.lineEdit_3.text()) print "Starting time = %s" % (inps) xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtime0 = xlim[0] else: newtime0 = float(inps) # Convert to integer slide value ileftvalue = int( (newtime0-xlim[0])/(xlim[1] - xlim[0])*100 ) print "iLeftSlide = %d" % (ileftvalue) # Skip if same as origina if ileftvalue == self._leftSlideValue: return # Set the value if out of range resetT = True if ileftvalue < 0: # Minimum value as 0 ileftvalue = 0 elif ileftvalue > self._rightSlideValue: # Maximum value as right slide value ileftvalue = self._rightSlideValue else: resetT = False if resetT is True: newtime0 = xlim[0] + ileftvalue*(xlim[1]-xlim[0])*0.01 print "Corrected iLeftSlide = %d (vs. right = %d)" % (ileftvalue, self._rightSlideValue) # Move the slide bar (left) self._leftSlideValue = ileftvalue # Move the vertical line leftx = [newtime0, newtime0] lefty = self.ui.mainplot.get_ylim() setp(self.leftslideline, xdata=leftx, ydata=lefty) self.ui.graphicsView.draw() # Set the value to left slider self.ui.horizontalSlider.setValue(self._leftSlideValue) # Reset the value of line edit if resetT is True: self.ui.lineEdit_3.setText(str(newtime0)) return def move_rightSlider(self): """ Re-setup left range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ newx = self.ui.horizontalSlider_2.value() if newx >= self._leftSlideValue and newx != self._rightSlideValue: # Allowed value: move the value bar self._rightSlideValue = newx xlim = self.ui.mainplot.get_xlim() newx = xlim[0] + newx*(xlim[1] - xlim[0])*0.01 leftx = [newx, newx] lefty = self.ui.mainplot.get_ylim() setp(self.rightslideline, xdata=leftx, ydata=lefty) self.ui.graphicsView.draw() # Change value self.ui.lineEdit_4.setText(str(newx)) else: # Reset the value self.ui.horizontalSlider_2.setValue(self._rightSlideValue) return def set_stopTime(self): """ Set the starting time and left slide bar """ inps = str(self.ui.lineEdit_4.text()) print "Stopping time = %s" % (inps) xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtimef = xlim[1] else: # Parse newtimef = float(inps) # Convert to integer slide value irightvalue = int( (newtimef-xlim[0])/(xlim[1] - xlim[0])*100 ) print "iRightSlide = %d" % (irightvalue) # Return if no change if irightvalue == self._rightSlideValue: return # Correct value resetT = True if irightvalue >= 100: irightvalue == 100 elif irightvalue < self._leftSlideValue: irightvalue = self._leftSlideValue else: resetT = False if resetT is True: newtimef = xlim[0] + irightvalue*(xlim[1]-xlim[0])*0.01 # Move the slide bar (right) self._rightSlideValue = irightvalue # Move the vertical line rightx = [newtimef, newtimef] righty = self.ui.mainplot.get_ylim() setp(self.rightslideline, xdata=rightx, ydata=righty) self.ui.graphicsView.draw() # Set the value to left slider self.ui.horizontalSlider_2.setValue(self._rightSlideValue) # Reset to line edit if resetT: self.ui.lineEdit_4.setText(str(newtimef)) return def move_lowerSlider(self): """ Re-setup upper range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ inewy = self.ui.verticalSlider_2.value() print "LowerSlider is set with value %d vs. class variable %d" % (inewy, self._lowerSlideValue) # Return with no change if inewy == self._lowerSlideValue: # No change return if inewy >= self._upperSlideValue: # Out of upper range inewy = self._upperSlideValue - 1 if inewy == 0 and self._lowerSlideValue < 0: setLineEdit = False else: setLineEdit = True # Move the lower vertical bar ylim = self.ui.mainplot.get_ylim() newy = ylim[0] + inewy*(ylim[1] - ylim[0])*0.01 lowerx = self.ui.mainplot.get_xlim() lowery = [newy, newy] setp(self.lowerslideline, xdata=lowerx, ydata=lowery) self.ui.graphicsView.draw() # Set line edit input if setLineEdit is True: # Change value to line edit (5) self.ui.lineEdit_5.setText(str(newy)) # Reset the class variable self._lowerSlideValue = inewy return def set_minLogValue(self): """ Set the starting time and left slide bar """ print "Minimum Log Value = %s" %(str(self.ui.lineEdit_5.text())) ylim = self.ui.mainplot.get_ylim() if str(self.ui.lineEdit_5.text()) == "": # Empty. Default to minY newminY = ylim[0] else: # Non empty. Parse newminY = float(self.ui.lineEdit_5.text()) # Convert to integer slide value iminlogval = int( (newminY-ylim[0])/(ylim[1] - ylim[0])*100 ) print "ilowerSlide = %d" % (iminlogval) # Return if no change if iminlogval == self._lowerSlideValue: return # Set value if out of range resetL = True if iminlogval >= self._upperSlideValue: iminlogval = self._upperSlideValue - 1 else: resetL = False if resetL is True: newminY = ylim[0] + iminlogval * (ylim[1]-ylim[0]) * 0.01 # Move the vertical line lowerx = self.ui.mainplot.get_xlim() lowery = [newminY, newminY] setp(self.lowerslideline, xdata=lowerx, ydata=lowery) self.ui.graphicsView.draw() # Move the slide bar (lower) self._lowerSlideValue = iminlogval print "LineEdit5 set slide to %d" % (self._lowerSlideValue) self.ui.verticalSlider_2.setValue(self._lowerSlideValue) # Reset line Edit if using default if resetL is True: self.ui.lineEdit_5.setText(str(newminY)) return def move_upperSlider(self): """ Re-setup upper range line in figure. Triggered by a change in Qt Widget. NO EVENT is required. """ inewy = self.ui.verticalSlider.value() # Return w/o change if inewy == self._upperSlideValue: return # Set to boundary value if inewy <= self._lowerSlideValue: inewy = self._lowerSlideValue + 1 # Reset line editor? if inewy == 100 and self._upperSlideValue > 100: setLineEdit = False else: setLineEdit = True # Move the upper value bar: upperx and uppery are real value (float but not (0,100)) of the figure ylim = self.ui.mainplot.get_ylim() newy = ylim[0] + inewy*(ylim[1] - ylim[0])*0.01 upperx = self.ui.mainplot.get_xlim() uppery = [newy, newy] setp(self.upperslideline, xdata=upperx, ydata=uppery) self.ui.graphicsView.draw() # Change value if setLineEdit is True: self.ui.lineEdit_6.setText(str(newy)) self._upperSlideValue = inewy return def set_maxLogValue(self): """ Set maximum log value from line-edit """ inps = str(self.ui.lineEdit_6.text()) print "Maximum Log Value = %s" %(inps) ylim = self.ui.mainplot.get_ylim() if inps == "": # Empty. Default to minY newmaxY = ylim[1] else: # Parse newmaxY = float(inps) # Convert to integer slide value imaxlogval = int( (newmaxY-ylim[0])/(ylim[1] - ylim[0])*100 ) print "iUpperSlide = %d" % (imaxlogval) # Return if no change if imaxlogval == self._upperSlideValue: return # Set to default if out of range resetL = True # if imaxlogval >= 100: # imaxlogval = 100 if imaxlogval < self._lowerSlideValue: imaxlogval = self._lowerSlideValue + 1 else: resetL = False # Set newmaxY if necessary if resetL is True: newmaxY = ylim[0] + imaxlogval * (ylim[1] - ylim[0]) * 0.01 # Move the vertical line upperx = self.ui.mainplot.get_xlim() uppery = [newmaxY, newmaxY] setp(self.upperslideline, xdata=upperx, ydata=uppery) self.ui.graphicsView.draw() # Set the value to upper slider self._upperSlideValue = imaxlogval self.ui.verticalSlider.setValue(self._upperSlideValue) # Set the value to editor if necessary if resetL is True: self.ui.lineEdit_6.setText(str(newmaxY)) return def browse_File(self): """ Open a file dialog to get file """ filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog', self._defaultdir, "Data (*.nxs *.dat);;All files (*.*)") self.ui.lineEdit.setText(str(filename)) # print "Selected file: ", filename return def load_File(self): """ Load the file by file name or run number """ # Get file name from line editor filename = str(self.ui.lineEdit.text()) # Find out it is relative path or absolute path if os.path.abspath(filename) == filename: isabspath = True else: isabspath = False dataws = self._loadFile(str(filename)) if dataws is None: errmsg = "Unable to locate run %s in default directory %s." % (filename, self._defaultdir) print errmsg self._setErrorMsg(errmsg) else: self._importDataWorkspace(dataws) self._defaultdir = os.path.dirname(str(filename)) # Reset GUI self._resetGUI(resetfilerun=False) return def use_existWS(self): """ Set up workspace to an existing one """ wsname = str(self.ui.comboBox.currentText()) try: dataws = AnalysisDataService.retrieve(wsname) self._importDataWorkspace(dataws) except KeyError: pass # Reset GUI self._resetGUI(resetfilerun=True) return def plotLogValue(self): """ Plot log value """ # Get log value logname = str(self.ui.comboBox_2.currentText()) if len(logname) == 0: # return due to the empty one is chozen return samplelog = self._dataWS.getRun().getProperty(logname) vectimes = samplelog.times vecvalue = samplelog.value # check if len(vectimes) == 0: print "Empty log!" # Convert absolute time to relative time in seconds t0 = self._dataWS.getRun().getProperty("proton_charge").times[0] t0ns = t0.totalNanoseconds() # append 1 more log if original log only has 1 value tf = self._dataWS.getRun().getProperty("proton_charge").times[-1] vectimes.append(tf) vecvalue = numpy.append(vecvalue, vecvalue[-1]) vecreltimes = [] for t in vectimes: rt = float(t.totalNanoseconds() - t0ns) * 1.0E-9 vecreltimes.append(rt) # Set to plot xlim = [min(vecreltimes), max(vecreltimes)] ylim = [min(vecvalue), max(vecvalue)] self.ui.mainplot.set_xlim(xlim[0], xlim[1]) self.ui.mainplot.set_ylim(ylim[0], ylim[1]) setp(self.mainline, xdata=vecreltimes, ydata=vecvalue) samunit = samplelog.units if len(samunit) == 0: ylabel = logname else: ylabel = "%s (%s)" % (logname, samunit) self.ui.mainplot.set_ylabel(ylabel, fontsize=13) # assume that all logs are on almost same X-range. Only Y need to be reset setp(self.leftslideline, ydata=ylim) setp(self.rightslideline, ydata=ylim) # reset the log value limit as previous one does not make any sense setp(self.lowerslideline, xdata=xlim, ydata=[ylim[0], ylim[0]]) self._lowerSlideValue = 0 self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.lineEdit_5.setText("") setp(self.upperslideline, xdata=xlim, ydata=[ylim[1], ylim[1]]) self._upperSlideValue = 100 self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.lineEdit_6.setText("") self.ui.graphicsView.draw() # Load property's statistic and give suggestion on parallel and fast log timeavg = samplelog.timeAverageValue() numentries = samplelog.size() stat = samplelog.getStatistics() duration = stat.duration mean = stat.mean freq = float(numentries)/float(duration) self.ui.label_mean.show() self.ui.label_meanvalue.show() self.ui.label_avg.show() self.ui.label_timeAvgValue.show() self.ui.label_freq.show() self.ui.label_freqValue.show() self.ui.label_logname.show() self.ui.label_lognamevalue.show() self.ui.label_logsize.show() self.ui.label_logsizevalue.show() self.ui.label_meanvalue.setText("%.5e"%(mean)) self.ui.label_timeAvgValue.setText("%.5e"%(timeavg)) self.ui.label_freqValue.setText("%.5e"%(freq)) self.ui.label_lognamevalue.setText(logname) self.ui.label_logsizevalue.setText(str(numentries)) # Set suggested processing scheme if numentries > HUGE_FAST: self.ui.checkBox_fastLog.setCheckState(True) if numentries > HUGE_PARALLEL: self.ui.checkBox_doParallel.setCheckState(True) else: self.ui.checkBox_doParallel.setCheckState(False) else: self.ui.checkBox_fastLog.setCheckState(False) self.ui.checkBox_doParallel.setCheckState(False) return def _importDataWorkspace(self, dataws): """ Import data workspace for filtering """ if dataws is None: return # Plot time counts errmsg = self._plotTimeCounts(dataws) if errmsg is not None: errmsg = "Workspace %s has invalid sample logs for splitting. Loading \ failure! \n%s\n" % (str(dataws), errmsg) self._setErrorMsg(errmsg) return False # Import log self._sampleLogNames = [""] run = dataws.getRun() plist = run.getProperties() for p in plist: pv = p.value if isinstance(pv, numpy.ndarray): times = p.times if len(times) > 1: self._sampleLogNames.append(p.name) # ENDFOR(p) # Set up sample log self.ui.comboBox_2.clear() self.ui.comboBox_2.addItems(self._sampleLogNames) # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() self.ui.label_avg.hide() self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() # Hide 'log name' above the graphic view self.ui.label_logname.hide() self.ui.label_lognamevalue.hide() # Set dataws to class variable self._dataWS = dataws return True def scanEventWorkspaces(self): """ """ wsnames = AnalysisDataService.getObjectNames() eventwsnames = [] for wsname in wsnames: wksp = AnalysisDataService.retrieve(wsname) if wksp.__class__.__name__.count("Event") == 1: eventwsnames.append(wsname) # ENDFOR if len(eventwsnames) > 0: self.ui.comboBox.clear() self.ui.comboBox.addItems(eventwsnames) return def _loadFile(self, filename): """ Load file or run File will be loaded to a workspace shown in MantidPlot """ config = ConfigService # Check input file name and output workspace name if filename.isdigit() is True: # Construct a file name from run number runnumber = int(filename) if runnumber <= 0: print "Run number cannot be less or equal to zero. User gives %s. " % (filename) return None else: ishort = config.getInstrument(self._instrument).shortName() filename = "%s_%s" %(ishort, filename) wsname = filename + "_event" elif filename.count(".") > 0: # A proper file name wsname = os.path.splitext(os.path.split(filename)[1])[0] elif filename.count("_") == 1: # A short one as instrument_runnumber iname = filename.split("_")[0] str_runnumber = filename.split("_")[1] if str_runnumber.isdigit() is True and int(str_runnumber) > 0: # Acccepted format ishort = config.getInstrument(iname).shortName() wsname = "%s_%s_event" % (ishort, str_runnumber) else: # Non-supported print "File name / run number in such format %s is not supported. " % (filename) return None else: # Unsupported format print "File name / run number in such format %s is not supported. " % (filename) return None # Load try: ws = api.Load(Filename=filename, OutputWorkspace=wsname) except: ws = None return ws def _plotTimeCounts(self, wksp): """ Plot time/counts """ import datetime # Rebin events by pulse time try: # Get run start and run stop if wksp.getRun().hasProperty("run_start"): runstart = wksp.getRun().getProperty("run_start").value else: runstart = wksp.getRun().getProperty("proton_charge").times[0] runstop = wksp.getRun().getProperty("proton_charge").times[-1] runstart = str(runstart).split(".")[0].strip() runstop = str(runstop).split(".")[0].strip() t0 = datetime.datetime.strptime(runstart, "%Y-%m-%dT%H:%M:%S") tf = datetime.datetime.strptime(runstop, "%Y-%m-%dT%H:%M:%S") # Calcualte dt = tf-t0 timeduration = dt.days*3600*24 + dt.seconds timeres = float(timeduration)/MAXTIMEBINSIZE if timeres < 1.0: timeres = 1.0 sumwsname = "_Summed_%s"%(str(wksp)) if AnalysisDataService.doesExist(sumwsname) is False: sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname, Params="0, %f, %d"%(timeres, timeduration)) sumws = api.SumSpectra(InputWorkspace=sumws, OutputWorkspace=str(sumws)) sumws = api.ConvertToPointData(InputWorkspace=sumws, OutputWorkspace=str(sumws)) else: sumws = AnalysisDataService.retrieve(sumwsname) except Exception as e: return str(e) vecx = sumws.readX(0) vecy = sumws.readY(0) xmin = min(vecx) xmax = max(vecx) ymin = min(vecy) ymax = max(vecy) # Reset graph self.ui.mainplot.set_xlim(xmin, xmax) self.ui.mainplot.set_ylim(ymin, ymax) self.ui.mainplot.set_xlabel('Time (seconds)', fontsize=13) self.ui.mainplot.set_ylabel('Counts', fontsize=13) # Set up main line setp(self.mainline, xdata=vecx, ydata=vecy) # Reset slide newslidery = [min(vecy), max(vecy)] newleftx = xmin + (xmax-xmin)*self._leftSlideValue*0.01 setp(self.leftslideline, xdata=[newleftx, newleftx], ydata=newslidery) newrightx = xmin + (xmax-xmin)*self._rightSlideValue*0.01 setp(self.rightslideline, xdata=[newrightx, newrightx], ydata=newslidery) self.ui.graphicsView.draw() return def filterByTime(self): """ Filter by time """ # Generate event filters kwargs = {} if self.ui.lineEdit_3.text() != "": rel_starttime = float(self.ui.lineEdit_3.text()) kwargs["StartTime"] = str(rel_starttime) if self.ui.lineEdit_4.text() != "": rel_stoptime = float(self.ui.lineEdit_4.text()) kwargs["StopTime"] = str(rel_stoptime) if self.ui.lineEdit_timeInterval.text() != "": interval = float(self.ui.lineEdit_timeInterval.text()) kwargs["TimeInterval"] = interval splitwsname = str(self._dataWS) + "_splitters" splitinfowsname = str(self._dataWS) + "_info" title = str(self.ui.lineEdit_title.text()) """ Debug for k in kwargs.keys(): print k, kwargs[k], type(kwargs[k]) print "Input workspace = ", str(self._dataWS) END DB """ splitws, infows = api.GenerateEventsFilter( InputWorkspace = self._dataWS, UnitOfTime = "Seconds", TitleOfSplitters = title, OutputWorkspace = splitwsname, InformationWorkspace = splitinfowsname, **kwargs) self.splitWksp(splitws, infows) return def filterByLogValue(self): """ Filter by log value """ # Generate event filter kwargs = {} samplelog = str(self.ui.comboBox_2.currentText()) if len(samplelog) == 0: print "No sample log is selected!" return if self.ui.lineEdit_3.text() != "": rel_starttime = float(self.ui.lineEdit_3.text()) kwargs["StartTime"] = str(rel_starttime) if self.ui.lineEdit_4.text() != "": rel_stoptime = float(self.ui.lineEdit_4.text()) kwargs["StopTime"] = str(rel_stoptime) if self.ui.lineEdit_5.text() != "": minlogvalue = float(self.ui.lineEdit_5.text()) kwargs["MinimumLogValue"] = minlogvalue if self.ui.lineEdit_6.text() != "": maxlogvalue = float(self.ui.lineEdit_6.text()) kwargs["MaximumLogValue"] = maxlogvalue if self.ui.lineEdit_7.text() != "": logvalueintv = float(self.ui.lineEdit_7.text()) kwargs["LogValueInterval"] = logvalueintv logvalchangedir = str(self.ui.comboBox_4.currentText()) kwargs["FilterLogValueByChangingDirection"] = logvalchangedir if self.ui.lineEdit_9.text() != "": logvalueintv = float(self.ui.lineEdit_9.text()) kwargs["TimeTolerance"] = logvalueintv logboundtype = str(self.ui.comboBox_5.currentText()) kwargs["LogBoundary"] = logboundtype if self.ui.lineEdit_8.text() != "": logvaluetol = float(self.ui.lineEdit_8.text()) kwargs["LogValueTolerance"] = logvaluetol splitwsname = str(self._dataWS) + "_splitters" splitinfowsname = str(self._dataWS) + "_info" title = str(self.ui.lineEdit_title.text()) splitws, infows = api.GenerateEventsFilter( InputWorkspace = self._dataWS, UnitOfTime = "Seconds", TitleOfSplitters = title, OutputWorkspace = splitwsname, LogName = samplelog, InformationWorkspace = splitinfowsname, **kwargs) try: self.splitWksp(splitws, infows) except Exception as mtderror: self._setErrorMsg("Splitting Failed!\n %s" % (str(mtderror))) return def splitWksp(self, splitws, infows): """ Run FilterEvents """ dogroupws = self.ui.checkBox_groupWS.isChecked() filterbypulse = self.ui.checkBox_filterByPulse.isChecked() startfrom1 = self.ui.checkBox_from1.isChecked() splitsamplelog = self.ui.checkBox_splitLog.isChecked() corr2sample = str(self.ui.comboBox_tofCorr.currentText()) how2skip = str(self.ui.comboBox_skipSpectrum.currentText()) kwargs = {} if corr2sample == "Direct": ei = float(self.ui.lineEdit_Ei.text()) kwargs["IncidentEnergy"] = ei elif corr2sample == "Customized": corrws = str(self.ui.comboBox_corrWS.currentText()) kwargs["DetectorTOFCorrectionWorkspace"] = corrws # Output workspace name outbasewsname = str(self.ui.lineEdit_outwsname.text()) if len(outbasewsname) == 0: outbasewsname = "tempsplitted" self.ui.lineEdit_outwsname.setText(outbasewsname) api.FilterEvents( InputWorkspace = self._dataWS, SplitterWorkspace = splitws, InformationWorkspace = infows, OutputWorkspaceBaseName = outbasewsname, GroupWorkspaces = dogroupws, FilterByPulseTime = filterbypulse, CorrectionToSample = corr2sample, SpectrumWithoutDetector = how2skip, SplitSampleLogs = splitsamplelog, OutputWorkspaceIndexedFrom1 = startfrom1, OutputTOFCorrectionWorkspace = 'TOFCorrTable', **kwargs) return def showHideEi(self): """ """ corrtype = str(self.ui.comboBox_tofCorr.currentText()) # Incident energy if corrtype == "Direct": self.ui.label_Ei.show() self.ui.lineEdit_Ei.show() else: self.ui.label_Ei.hide() self.ui.lineEdit_Ei.hide() # Workspace if corrtype == "Customized": self.ui.label_Ei_2.show() self.ui.comboBox_corrWS.show() self.ui.pushButton_refreshCorrWSList.show() # Search for table workspace self._searchTableWorkspaces() else: self.ui.label_Ei_2.hide() self.ui.comboBox_corrWS.hide() self.ui.pushButton_refreshCorrWSList.hide() return def _searchTableWorkspaces(self): """ Search table workspaces and add to 'comboBox_corrWS' """ wsnames = AnalysisDataService.getObjectNames() tablewsnames = [] for wsname in wsnames: wksp = AnalysisDataService.retrieve(wsname) if isinstance(wksp, mantid.api._api.ITableWorkspace): tablewsnames.append(wsname) # ENDFOR self.ui.comboBox_corrWS.clear() if len(tablewsnames) > 0: self.ui.comboBox_corrWS.addItems(tablewsnames) return def _clearErrorMsg(self): """ Clear error message """ #self.ui.plainTextEdit_ErrorMsg.setPlainText("") #self.ui.label_error.hide() return def _setErrorMsg(self, errmsg): """ Clear error message """ #self.ui.plainTextEdit_ErrorMsg.setPlainText(errmsg) #self.ui.label_error.show() #print "Testing Pop-up Error Message Window: %s" % (errmsg) self._errMsgWindow = MyPopErrorMsg() self._errMsgWindow.setMessage(errmsg) self._errMsgWindow.show() return def _resetGUI(self, resetfilerun=False, resetwslist=False): """ Reset GUI including all text edits and etc. """ if resetfilerun is True: self.ui.lineEdit.clear() # Plot related self.ui.lineEdit_3.clear() self.ui.lineEdit_4.clear() self.ui.horizontalSlider.setValue(0) self.ui.horizontalSlider_2.setValue(100) self.ui.lineEdit_outwsname.clear() self.ui.lineEdit_title.clear() # Filter by log value self.ui.lineEdit_5.clear() self.ui.lineEdit_6.clear() self.ui.verticalSlider_2.setValue(0) self.ui.verticalSlider.setValue(100) ylim = self.ui.mainplot.get_ylim() miny = ylim[0] maxy = ylim[1] xlim = self.ui.mainplot.get_xlim() setp(self.lowerslideline, xdata=xlim, ydata=[miny, miny]) setp(self.upperslideline, xdata=xlim, ydata=[maxy, maxy]) self.ui.graphicsView.draw() self.ui.lineEdit_7.clear() self.ui.lineEdit_8.clear() self.ui.lineEdit_9.clear() # Filter by time self.ui.lineEdit_timeInterval.clear() # Advanced setup self.ui.comboBox_tofCorr.setCurrentIndex(0) self.ui.lineEdit_Ei.clear() self.ui.checkBox_fastLog.setCheckState(False) self.ui.checkBox_doParallel.setCheckState(False) self.ui.comboBox_skipSpectrum.setCurrentIndex(0) self.ui.checkBox_filterByPulse.setCheckState(False) self.ui.checkBox_from1.setCheckState(False) self.ui.checkBox_groupWS.setCheckState(True) self.ui.checkBox_splitLog.setCheckState(False) # Error message # self.ui.plainTextEdit_ErrorMsg.clear() return
class MainWindow(QMainWindow): def __init__(self, app): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.app = app self.dir = os.path.expanduser("~") self.filepathShiftIn = "" self.filepathConcatIn1 = "" self.filepathConcatIn2 = "" self.filepathConcatOut = "" self.filepathSplitIn = "" self.filepathSplitOut1 = "" self.filepathSplitOut2 = "" self.ui.lineEditFormat.setText(REGEXP) self.current_action = self.ui.tabs.currentIndex() self.ui.lineEditPathShiftIn.setText(self.filepathShiftIn) self.ui.lineEditPathConcatIn1.setText(self.filepathConcatIn1) self.ui.lineEditPathConcatIn2.setText(self.filepathConcatIn2) self.ui.lineEditPathSplitIn.setText(self.filepathSplitIn) def browse(self, lineEdit): filepath = QFileDialog.getOpenFileName(self, QApplication.translate("Main", "Ouvrir", None, QApplication.UnicodeUTF8), self.dir, "Sous-titres .srt (*.srt)") if not filepath: return self.dir = os.path.dirname(str(filepath)) lineEdit.setText(filepath) return filepath def launch_shift(self): self.ui.textEditShiftOut.clear() sign = self.ui.comboBoxSignShift.itemText(self.ui.comboBoxSignShift.currentIndex()) h = self.ui.spinBoxShiftH.value() m = self.ui.spinBoxShiftM.value() s = self.ui.spinBoxShiftS.value() ms = self.ui.spinBoxShiftMS.value() format_ = str(self.ui.lineEditFormat.text()) filepath = str(self.ui.lineEditPathShiftIn.text()) if not filepath: return if self.ui.radioButtonBeginAt.isChecked(): delta = get_delta(h, m, s, ms, "+") first = get_first_time(filepath, format_) delta = delta - first else: delta = get_delta(h, m, s, ms, sign) new_lines = convert(filepath, delta, format_) new_lines = "\n".join(line.replace("\r\n", "").replace("\n", "") for line in new_lines) self.ui.textEditShiftOut.appendPlainText(new_lines) cursor = self.ui.textEditShiftOut.cursorForPosition(QPoint(0,0)) cursor.setPosition(QTextCursor.Start); self.ui.textEditShiftOut.setTextCursor(cursor); vScrollBar = self.ui.textEditShiftOut.verticalScrollBar() vScrollBar.setSliderPosition(0) def launch_concat(self): self.ui.textEditConcatOut.clear() sign = self.ui.comboBoxSignConcat.itemText(self.ui.comboBoxSignConcat.currentIndex()) decal_h = self.ui.spinBoxConcatH.value() decal_m = self.ui.spinBoxConcatM.value() decal_s = self.ui.spinBoxConcatS.value() decal_ms = self.ui.spinBoxConcatMS.value() format_ = str(self.ui.lineEditFormat.text()) filepathIn1 = str(self.ui.lineEditPathConcatIn1.text()) filepathIn2 = str(self.ui.lineEditPathConcatIn2.text()) if not filepathIn1 or not filepathIn2: return input_delta = get_delta(decal_h, decal_m, decal_s, decal_ms, sign) fd = open(filepathIn1, 'r') lines = fd.readlines() fd.close() last_lines = lines[len(lines)-10:len(lines)] for l in lines: self.ui.textEditConcatOut.appendPlainText(l.replace("\r\n", "").replace("\n", "")) last_delta = None for l in last_lines: matches = re.compile(format_).findall(l) if len(matches) != 0: e_h = int(matches[0][4]) e_m = int(matches[0][5]) e_s = int(matches[0][6]) e_ms = int(matches[0][7]) last_delta = get_delta(e_h, e_m, e_s, e_ms) total_delta = last_delta + input_delta new_lines2 = convert(filepathIn2, total_delta, format_) for l in new_lines2: self.ui.textEditConcatOut.appendPlainText(l.replace("\r\n", "").replace("\n", "")) vScrollBar = self.ui.textEditConcatOut.verticalScrollBar() vScrollBar.setSliderPosition(0) def launch_split(self): self.ui.textEditSplitOut1.clear() self.ui.textEditSplitOut2.clear() decal_h = self.ui.spinBoxSplitH.value() decal_m = self.ui.spinBoxSplitM.value() decal_s = self.ui.spinBoxSplitS.value() decal_ms = self.ui.spinBoxSplitMS.value() format_ = str(self.ui.lineEditFormat.text()) filepathIn = str(self.ui.lineEditPathSplitIn.text()) if not filepathIn: return split_delta = get_delta(decal_h, decal_m, decal_s, decal_ms) fd = open(filepathIn, 'r') lines = fd.readlines() fd.close() output = self.ui.textEditSplitOut1 last_delta = get_delta(0, 0, 0, 0) for l in lines: matches = re.compile(format_).findall(l) new_line = l new_b_dt = 0 new_e_dt = 0 if len(matches) != 0: b_h = int(matches[0][0]) b_m = int(matches[0][1]) b_s = int(matches[0][2]) b_ms = int(matches[0][3]) e_h = int(matches[0][4]) e_m = int(matches[0][5]) e_s = int(matches[0][6]) e_ms = int(matches[0][7]) b_dt = datetime.time(hour=b_h, minute=b_m, second=b_s, microsecond=b_ms) e_dt = datetime.time(hour=e_h, minute=e_m, second=e_s, microsecond=e_ms) current_delta = get_delta(b_h, b_m, b_s, b_ms) zero_delta = get_delta(0, 0, 0, 0) if split_delta - current_delta > zero_delta: new_b_delta = get_delta(b_h, b_m, b_s, b_ms) new_e_delta = get_delta(e_h, e_m, e_s, e_ms) last_delta = new_b_delta new_line = "%s --> %s" % ( format_delta(new_b_delta), format_delta(new_e_delta) ) else: output = self.ui.textEditSplitOut2 new_b_delta = get_delta(b_h, b_m, b_s, b_ms) - last_delta new_e_delta = get_delta(e_h, e_m, e_s, e_ms) - last_delta new_line = "%s --> %s" % ( format_delta(new_b_delta), format_delta(new_e_delta) ) output.appendPlainText(new_line.replace("\r\n", "\n").replace("\n", "")) output1 = self.ui.textEditSplitOut1.toPlainText() output2 = self.ui.textEditSplitOut2.toPlainText() # Récupération de la dernière ligne (correspondant au numéro) # pour la rajouter en début de 2è fichier cur1 = self.ui.textEditSplitOut1.cursorForPosition(QPoint(0,0)) cur2 = self.ui.textEditSplitOut2.cursorForPosition(QPoint(0,0)) cur1.movePosition(QTextCursor.End) cur2.movePosition(QTextCursor.Start) cur1.select(QTextCursor.LineUnderCursor) last1 = cur1.selectedText() + "\n" cur1.removeSelectedText() cur2.insertText(last1) vScrollBar2 = self.ui.textEditSplitOut2.verticalScrollBar() vScrollBar2.setSliderPosition(0) @pyqtSlot(str) def on_lineEditPathConcatIn1_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditConcatIn1.appendPlainText(l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathConcatIn2_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditConcatIn2.appendPlainText(l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathConcatOut_textChanged(self, path): self.filepathConcatOut = path @pyqtSlot(str) def on_lineEditPathSplitIn_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditSplitIn.appendPlainText(l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathSplitOut1_textChanged(self, path): self.filepathSplitOut1 = path @pyqtSlot(str) def on_lineEditPathSplitOut2_textChanged(self, path): self.filepathSplitOut2 = path @pyqtSlot() def on_pushButtonBrowseShiftIn_clicked(self): self.filepathShiftIn = self.browse(self.ui.lineEditPathShiftIn) @pyqtSlot() def on_pushButtonBrowseConcatIn1_clicked(self): self.filepathConcatIn1 = self.browse(self.ui.lineEditPathConcatIn1) @pyqtSlot() def on_pushButtonBrowseConcatIn2_clicked(self): self.filepathConcatIn2 = self.browse(self.ui.lineEditPathConcatIn2) @pyqtSlot() def on_pushButtonBrowseConcatOut_clicked(self): self.filepathConcatOut = self.browse(self.ui.lineEditPathConcatOut) @pyqtSlot() def on_pushButtonBrowseSplitIn_clicked(self): self.filepathSplitIn = self.browse(self.ui.lineEditPathSplitIn) @pyqtSlot() def on_pushButtonBrowseSplitOut1_clicked(self): self.filepathSplitOut1 = self.browse(self.ui.lineEditPathSplitOut1) @pyqtSlot() def on_pushButtonBrowseSplitOut2_clicked(self): self.filepathSplitOut2 = self.browse(self.ui.lineEditPathSplitOut2) @pyqtSlot() def on_pushButtonLaunch_clicked(self): if self.current_action == ACTION_SHIFT: self.launch_shift() elif self.current_action == ACTION_CONCAT: self.launch_concat() elif self.current_action == ACTION_SPLIT: self.launch_split() else: print "Pas d'action correspondante pour %s" % self.current_action @pyqtSlot(int) def on_tabs_currentChanged(self, num): self.current_action = num @pyqtSlot() def on_pushButtonCopy_clicked(self): if self.current_action == ACTION_SHIFT: self.app.clipboard().clear() self.ui.textEditShiftOut.selectAll() self.app.clipboard().setText(self.ui.textEditShiftOut.toPlainText()) elif self.current_action == ACTION_CONCAT: self.app.clipboard().clear() self.ui.textEditConcatOut.selectAll() self.app.clipboard().setText(self.ui.textEditConcatOut.toPlainText()) elif self.current_action == ACTION_SPLIT: self.app.clipboard().clear() self.ui.textEditSplitOut1.selectAll() self.ui.textEditSplitOut2.selectAll() self.app.clipboard().setText( self.ui.textEditSplitOut1.toPlainText() + self.ui.textEditSplitOut2.toPlainText() ) else: print "Pas d'action correspondante pour %s" % self.current_action @pyqtSlot() def on_pushButtonOverwrite_clicked(self): try: if self.current_action == ACTION_SHIFT: if not self.filepathShiftIn: return os.rename(self.filepathShiftIn, self.filepathShiftIn+'.org') fd = open(self.filepathShiftIn, 'w') fd.write(self.ui.textEditShiftOut.toPlainText()) fd.close() self.ui.statusbar.showMessage(u"Le fichier a bien été écrasé. Une sauvegarde a été effectuée") elif self.current_action == ACTION_CONCAT: if not self.filepathConcatOut: return fd = open(self.filepathConcatOut, 'w') fd.write(self.ui.textEditConcatOut.toPlainText()) fd.close() self.ui.statusbar.showMessage(u"Le fichier a bien été écrit.") elif self.current_action == ACTION_SPLIT: if not self.filepathSplitOut1 or not self.filepathSplitOut2: return fd = open(self.filepathSplitOut1, 'w') fd.write(self.ui.textEditSplitOut1.toPlainText()) fd.close() fd = open(self.filepathSplitOut2, 'w') fd.write(self.ui.textEditSplitOut2.toPlainText()) fd.close() self.ui.statusbar.showMessage(u"Les fichiers ont bien été écrit.") else: print "Pas d'action correspondante pour %s" % self.current_action except Exception, e: print e self.ui.statusbar.showMessage(u"Le fichier n'a pas été bien généré. Voir la sortie d'erreur")
class Main_PROGRAM(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.MainWindow = QtWidgets.QMainWindow() self.ui.setupUi(self.MainWindow) self.MainWindow.show() #self.ui.show() self.image_converter = Image_Converter() self.display_layer_counter = 0 self.model_layers = [] self.link_ui() def link_ui(self): #ret = self.image_converter.openfile('../../../ExampleSVGfiles\sphere.svg') # ret = self.image_converter.openfile(r'C:\Users\Jimmy\Desktop\3D Printing research\Silcers\Slic3r\STL SAMPLES\spheresmaller5x.svg') # self.model_layers = self.image_converter.get_model_layers() # print('layers:{}'.format(len(self.model_layers))) # imagex = self.model_layers[0] # imagex = np.uint8(imagex) # # img = Image.fromarray(imagex.data, 'I') # #img.save('my.png') # # np.set_printoptions(threshold=np.inf) # print(imagex) # # # plt.imshow(imagex) #interpolation='nearest' # # plt.show() # imagex2 = imagex*255 # image = QtGui.QImage(imagex2.data, imagex2.shape[1], # imagex2.shape[0] ,imagex2.shape[1],QtGui.QImage.Format_Indexed8) # pix = QtGui.QPixmap(image) # # '''Saving and Making PIL IMAGE ''' # #img = Image.fromarray(imagex2, 'L') # #img.save('my.png') # # # pix = QPixmap().loadFromData(img) # pix = QPixmap().fromImage(image) #self.ui.layer.setPixmap(pix) #self.ui.layer.setPixmap(QtGui.QPixmap('3dp.jpg') ) #self.ui.layer.setPixmap(QtGui.QPixmap(img) ) #self.ui.Next_layer.clicked.connect(lambda:self.increase_display_counter() ) print("x") #self.ui.verticalSlider.setRange(0,len(self.model_layers)-1) #changed self.ui.verticalSlider.valueChanged['int'].connect(self.disp_layers) #self.display_curr_layer(len(self.model_layers),self.display_layer_counter) self.ui.pushButton.clicked.connect(self.openSlic3r) self.ui.openGLWidget.initializeGL # self.ui.openGLWidget.initializeGL = self.initializeGL() # self.draw() self.ui.tabWidget.currentChanged['int'].connect(self.tabSelected) # self.ui.previous_layer.clicked.connect(lambda:self.ui.label_3.setText("Disconnected")) self.ui.previous_layer.clicked.connect(self.Printer_disconnected) #self.ui.label_3.setText("Disconnected") self.ui.pushButton_3.clicked.connect(self.openFileNameDialog) def openFileNameDialog(self): options = QFileDialog.Options() #options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", r'C:\Users\Jimmy\Desktop\3D Printing research\Silcers\Slic3r\STL SAMPLES', "SVG Files (*.svg);;All Files (*)", options=options) if fileName: self.ui.textBrowser.append( '<span style="color:darkolivegreen;font-weight:bold">File Found</span>' ) print(fileName) #return fileName self.model_layers = [] self.image_converter.openfile(fileName) self.model_layers = self.image_converter.get_model_layers() self.ui.verticalSlider.setRange(0, len(self.model_layers) - 1) self.disp_layers(0) def Printer_disconnected(self): #disconnect printer # code to be written here to disconnect printer # self.ui.label_3.setText("Disconnected") self.ui.textBrowser.append( '<span style="color:darkolivegreen;font-weight:bold">Printer is Disconnected</span>' ) #self.ui.textBrowser.setText('<span style="color:darkolivegreen;font-weight:bold">Printer is Disconnected</span>') def openSlic3r(self): #self.MainWindow.setEnabled(False) #subprocess.call(['C:\Program Files\Repetier-Host\Slic3r\Slic3r.exe']) process = subprocess.Popen( 'C:\Program Files\Repetier-Host\Slic3r\Slic3r.exe', shell=False) #self.MainWindow.setEnabled(True) def tabSelected(self, arg=0): print(arg) if (arg == 0): self.draw() def draw(self): # self.ui.openGLWidget.initializeGL() #self.ui.openGLWidget.initializeGL = self.initializeGL() self.ui.openGLWidget.paintGL = self.paintGL #self.ui.openGLWidget.repaint() def disp_layers(self, layer_no): if not self.model_layers: pass else: imagex = (np.uint8(self.model_layers[layer_no])) * 255 image1 = QtGui.QImage(imagex.data, imagex.shape[1], imagex.shape[0], imagex.shape[1], QtGui.QImage.Format_Indexed8) pix1 = QtGui.QPixmap(image1) self.ui.layer.setPixmap( pix1.scaled(self.ui.layer.width(), self.ui.layer.height(), QtCore.Qt.KeepAspectRatio)) def increase_display_counter(self): self.display_layer_counter = self.display_layer_counter + 1 print(self.display_layer_counter) self.display_curr_layer(len(self.model_layers), self.display_layer_counter) def display_curr_layer(self, total_layers, layer_counter): #print(layer_counter) if layer_counter in range(0, total_layers): #print(layer_counter) imagex = (np.uint8(self.model_layers[layer_counter])) * 255 image1 = QtGui.QImage(imagex.data, imagex.shape[1], imagex.shape[0], imagex.shape[1], QtGui.QImage.Format_Indexed8) pix1 = QtGui.QPixmap(image1) self.ui.layer.setPixmap( pix1.scaled(self.ui.layer.width(), self.ui.layer.height(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)) # self.paintGL(image1) # self.ui.openGLWidget.paintGL = self.paintGL(image1) #Comment Color code :#adadad #OPENGL PART funcs def paintGL(self): self.loadScene() vertices = [] # self.ui.openGLWidget.convertToGLFormat(img) # glut.glutWireSphere(2, 13, 13) #glut.glutSolidSphere(2,13,13) # vertices = [-10, -10,2, 0.0, 10,4, 10, -10,6] # # gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, vertices) # gl.glEnableVertexAttribArray(0) # gl.glColor(0,0,0) # gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) # # gl.glDisableVertexAttribArray(0) for x1 in range(0, 150, 1): for y1 in range(0, 150, 1): x2 = x1 + 1 y2 = y1 + 1 #vertices.extend([x1,y1,x2,y1,x2,y2,x1,y2]) #vertices.extend([x1,y1]) self._gl_set_color(gl.GL_FRONT_AND_BACK, [0.2, 0.2, 0.7, 0.3], shininess=0.75) gl.glBegin(gl.GL_LINE_LOOP) gl.glVertex3fv([x1, y1, 0]) gl.glVertex3fv([x2, y1, 0]) gl.glVertex3fv([x2, y2, 0]) gl.glVertex3fv([x1, y2, 0]) gl.glEnd() # self._gl_set_color(gl.GL_FRONT_AND_BACK, [0.2, 0.2, 0.7, 0.3], shininess=0.75) # gl.glBegin(gl.GL_LINE) # gl.glVertex3fv([x1+5, y1+5, 0]) # gl.glVertex3fv([x1+10, 150, 0]) # #gl.glVertex3fv([x2, y2, 0]) # # gl.glVertex3fv([x1, y2, 0]) # gl.glEnd() # gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, vertices) # gl.glEnableVertexAttribArray(0) # gl.glColor(1,1,1) # gl.glDrawArrays(gl.GL_LINE_LOOP, 0, len(vertices)-1) # gl.glDisableVertexAttribArray(0) print("hena") def _gl_set_color(self, side, color, shininess=0.33): gl.glMaterialfv(side, gl.GL_AMBIENT_AND_DIFFUSE, color) gl.glMaterialfv(side, gl.GL_SPECULAR, color) gl.glMaterialf(side, gl.GL_SHININESS, int(127 * shininess)) gl.glColor4fv(color) def initializeGL(self): print("\033[4;30;102m INITIALIZE GL 2 \033[0m") gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_DEPTH_TEST) def loadScene(self): gl.glClearColor(1.0, 1.0, 1.0, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glViewport(0, 0, self.ui.openGLWidget.width(), self.ui.openGLWidget.height()) x, y, width, height = gl.glGetDoublev(gl.GL_VIEWPORT) # glu.gluPerspective( # 90, # field of view in degrees # width / float(height or 1), # aspect ratio # .25, # near clipping plane # 200, # far clipping plane # ) gl.glOrtho(-2, 152, -2, 152, -1, 1) #gl.glOrtho(-1,16,-1,16,-1,1) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() # gl.glTranslatef(-50,-20,-50) # gl.glRotatef(40,1,1,0) #glu.gluLookAt(12, 12, 90, 0, 0, 0, 0, 1, 0) # glu.gluLookAt(0, 90, 90, 0, 90, 80, 0, 1, 0) # glu.gluLookAt(0, 0, 0, 0, 0, 0, 0, 0, 1) background = [.99, .99, .99, 1.0]
class Handler_MainWindow: x_lower = 0 x_upper = 4 max_itr = 50 epsilon = 0.00001 selected = "Root Finder" xl_bisection = 0 xu_bisection = 0 xl_falsePosition = 0 xu_falsePosition = 0 xi_fixedPoint = 0 xi_newtonRaphson = 0 x1_secant = 0 x2_secant = 0 xi_biergeVieta = 0 resultDialog = None list_methods = ["Bisection", "False-Position", "Fixed Point", \ "Newton-Raphson", "Secant", "Bierge-Vieta", "Muller"] def __init__(self): self.MainWindow = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.ui.btnGaussSeidel.hide() self.ui.btnSingleStep.hide() self.ui.contentWidget_1.hide() self.ui.contentWidget_2.hide() self.ui.btnResult.clicked.connect(self.btnResultClicked) self.ui.btnResult_2.clicked.connect(self.btnResultClicked_2) self.ui.btnSingleStep.clicked.connect(self.openSingleStep) self.ui.btnGaussSeidel.clicked.connect(self.openSeidelDetails) self.ui.treeSelection.currentItemChanged.connect(self.getSelected) self.ui.treeSelection.currentItemChanged.connect(self.setScene) self.ui.treeSelection.currentItemChanged.connect(self.setInputWidgets) self.ui.actionExit.triggered.connect(app.quit) self.ui.actionRoot_Finder.triggered.connect(self.read) self.ui.actionSystem_Solver.triggered.connect(self.read_2) self.method = None self.all_methods = list() self.method_2 = None self.all_methods_2 = list() def setScene(self): if self.selected == "Root Finder": return elif self.selected == "System of Equations Solver": return elif self.selected in ["Bisection", "False-Position", "Fixed Point",\ "Newton-Raphson", "Secant", "Bierge-Vieta", "Muller", "All Methods"]: self.ui.contentWidget_0.hide() self.ui.contentWidget_1.show() self.ui.contentWidget_2.hide() else: self.ui.contentWidget_0.hide() self.ui.contentWidget_1.hide() self.ui.contentWidget_2.show() def setInputWidgets(self): if self.selected in ["Bisection", "False-Position", "Fixed Point",\ "Newton-Raphson", "Secant", "Bierge-Vieta", "Muller", "All Methods"]: self.setInputsWidgets() elif self.selected in ["Gaussian-elimination", "LU decomposition", "Gaussian-Jordan", \ "Gauss-Seidel", "All"]: self.setInputsWidgets_2() def read_2(self): fileName, _ = QFileDialog.getOpenFileName(self.MainWindow, "Open file", "", "Text Documents (*.txt)") reader = None if fileName: try: reader = SystemSolverReader(fileName) except Exception as e: self.displayErrorMsg("Can't Read From File") #raise e else: try: method = self.readMethod_2(reader.method) self.readEquations(reader.equations) self.readParameters_2(method, reader.parameters) except RuntimeError as e: self.displayErrorMsg("Can't Read From File") #raise e return except Exception as e: #raise e self.displayErrorMsg("Can't Read From File") return def readMethod_2(self, s): s = s.replace(" ", "") s = s.replace("-", "") s = s.replace(".", "") s = s.lower() methods = ["gaussianelimination", "ludecomposition", "gaussianjordan", "gaussseidel"] for i in range(len(methods)): if s == methods[i]: self.ui.treeSelection.setCurrentItem(self.ui.treeSelection.topLevelItem(1).child(i)) print("method choosen from file is", s) return s raise RuntimeError("Couldn't Read From File: Wrong Method") def readParameters_2(self, s, para): if s == "gaussseidel": self.ui.txtEditInitial.clear() for i in para: self.ui.txtEditInitial.appendPlainText(i) else: if len(para) > 0: raise RuntimeError("Couldn't Read From File: Wrong Parameters") def readEquations(self, eqns): self.ui.txtEditEquations.clear() for i in eqns: self.ui.txtEditEquations.appendPlainText(i) def read(self): fileName, _ = QFileDialog.getOpenFileName(self.MainWindow, "Open file", "", "Text Documents (*.txt)") if fileName: try: reader = RootFinderReader(fileName) except Exception as e: self.displayErrorMsg("Can't Read From File") #raise e else: try: method = self.readMethod(reader.method) self.ui.txtFunction.setText(reader.function) self.readParameters(method, reader.parameters) if not(reader.max_itr is None): self.ui.txtMaxItr.setText(str(reader.max_itr)) self.ui.txtEpsilon.setText(str(0.00001)) elif not(reader.epsilon is None): self.ui.txtMaxItr.setText(str(50)) self.ui.txtEpsilon.setText(str(reader.epsilon)) else: self.ui.txtMaxItr.setText(str(50)) self.ui.txtEpsilon.setText(str(0.00001)) except RuntimeError as e: self.displayErrorMsg("Can't Read From File") #raise e except Exception as e: self.displayErrorMsg("Can't Read From File") #raise e def readMethod(self, s): s = s.replace(" ", "") s = s.replace("-", "") s = s.replace(".", "") s = s.lower() methods = ["bisection", "falseposition", "fixedpoint", "newtonraphson", "secant", "biergevieta", "muller"] for i in range(len(methods)): if s == methods[i]: self.ui.treeSelection.setCurrentItem(self.ui.treeSelection.topLevelItem(0).child(i)) print("method choosen from file is", s) return s raise RuntimeError("Couldn't Read From File: Wrong Method") def readParameters(self, s, para): if (s == "bisection") | (s == "falseposition") | (s == "secant"): if not (len(para) == 2): raise RuntimeError("Couldn't Read From File: Wrong Parameters") else: self.ui.txtXl.setText(para[0]) self.ui.txtXu.setText(para[1]) elif (s == "muller"): if not (len(para) == 3): raise RuntimeError("Couldn't Read From File: Wrong Parameters") else: self.ui.txtXl.setText(para[0]) self.ui.txtXu.setText(para[1]) self.ui.txtX3.setText(para[1]) else: if not (len(para) == 1): raise RuntimeError("Couldn't Read From File: Wrong Parameters") else: self.ui.txtXl.setText(para[0]) def setCE(self): if self.selected == "Bisection": self.ui.lblCE.setText("Theoretical Itration Number (for Bisection) = " + str(self.method.getTheUpperBoundOfIterations())) elif self.selected == "Fixed Point": self.ui.lblCE.setText("Theoretical g dash (for Fixed Point) = " + str(self.method.get_g_dash())) elif self.selected == "All Methods": self.ui.lblCE.setText("Theoretical Itration Number (for Bisection) = " + str(self.method.getTheUpperBoundOfIterations()) \ + " & Theoretical g dash (for Fixed Point) = " + self.method.get_g_dash()) else: self.ui.lblCE.setText("") def autoSave(self): if self.selected == "All Methods": for i in range(7): method = self.all_methods[i] filename = self.list_methods[i] + "_" + \ (str(datetime.datetime.now()).split())[1].replace(":", "") + ".csv" method.save(method.solution, filename) else: filename = self.selected + "_" + \ (str(datetime.datetime.now()).split())[1].replace(":", "") + ".csv" self.method.save(self.method.solution, filename) def autoSave_2(self): if self.selected == "All": filename = "Gauss-Seidel_" + (str(datetime.datetime.now()).split())[1].replace(":", "") + ".csv" self.all_methods_2[3].save(filename) elif self.selected == "Gauss-Seidel": filename = "Gauss-Seidel_" + (str(datetime.datetime.now()).split())[1].replace(":", "") + ".csv" self.method_2.save(filename) def btnResultClicked_2(self): try: self.readInputs_2() self.methodFactory_2() except RuntimeError as e: print(e) self.displayErrorMsg(e) #raise e return except Exception as e: print(e) self.displayErrorMsg("Please, Check Inputs") #raise e return try: self.run_2() except RuntimeError as e: print(e) self.displayErrorMsg(e) return except Exception as e: print(e) self.displayErrorMsg("Please, Check Inputs") #raise e return if self.ui.actionAuto_Save.isChecked(): try: self.autoSave_2() except Exception as e: print(e) self.displayErrorMsg("Can't Save") #raise e return self.populateResultTable_2() self.ui.btnGaussSeidel.setEnabled(True) def btnResultClicked(self): try: self.readInputs() self.methodFactory() except RuntimeError as e: print(e) self.displayErrorMsg(e) raise e return except Exception as e: print(e) self.displayErrorMsg("Please, Check Inputs") raise e return try: self.run() except RuntimeError as e: print(e) self.displayErrorMsg(e) raise e return except Exception as e: print(e) self.displayErrorMsg("Please, Check Inputs") raise e return if self.ui.actionAuto_Save.isChecked(): try: self.autoSave() except Exception as e: print(e) self.displayErrorMsg("Can't Save") raise e return self.populateResultTable() self.ui.btnSingleStep.setEnabled(True) def displayErrorMsg(self, s): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error") msg.setInformativeText(str(s)) msg.setWindowTitle("Error") msg.exec_() def readInputs(self): self.function = self.ui.txtFunction.text() self.max_itr = int(self.ui.txtMaxItr.text()) self.epsilon = float(self.ui.txtEpsilon.text()) if self.selected == "All Methods": self.xl_bisection = float(self.ui.txtXlBisection.text()) self.xu_bisection = float(self.ui.txtXuBisection.text()) self.xl_falsePosition = float(self.ui.txtXlFalsePosition.text()) self.xu_falsePosition = float(self.ui.txtXuFalsePosition.text()) self.xi_fixedPoint = float(self.ui.txtXiFixedPoint.text()) self.xi_newtonRaphson = float(self.ui.txtXiNewtonRaphson.text()) self.x1_secant = float(self.ui.txtX1Secant.text()) self.x2_secant = float(self.ui.txtX2Secant.text()) self.xi_biergeVieta = float(self.ui.txtXiBiergeVieta.text()) self.x1_muller = float(self.ui.txtX1Muller.text()) self.x2_muller = float(self.ui.txtX2Muller.text()) self.x3_muller = float(self.ui.txtX3Muller.text()) else: self.x_lower = float(self.ui.txtXl.text()) if not self.ui.txtXu.isHidden(): self.x_upper = float(self.ui.txtXu.text()) if not self.ui.txtX3.isHidden(): self.x_3 = float(self.ui.txtX3.text()) def readInputs_2(self): self.equations = self.ui.txtEditEquations.toPlainText().split("\n") if (self.selected == "All") | (self.selected == "Gauss-Seidel"): self.initial = [float(i) for i in self.ui.txtEditInitial.toPlainText().split("\n")] self.max_itr = int(self.ui.txtMaxItr_2.text()) self.epsilon = float(self.ui.txtEpsilon_2.text()) def openSeidelDetails(self): self.resultDialog = Handler_DialogResultSeidel(self) def populateResultTable_2(self): self.ui.resultTable.clear() (self.ui.resultTable.setVerticalHeaderItem(i, QTableWidgetItem()) for i in range(self.ui.resultTable.rowCount())) if self.selected == "All": self.ui.resultTable.setColumnCount(self.all_methods_2[0].parser.numOfVariables) self.ui.resultTable.setHorizontalHeaderLabels(self.all_methods_2[0].parser.variables) self.ui.resultTable.setRowCount(4) list_methods = ["Gaussian-elimination", "LU decomposition", "Gaussian-Jordan", \ "Gauss-Seidel"] self.ui.resultTable.setVerticalHeaderLabels(list_methods) for i in range(len(self.all_methods_2)): method = self.all_methods_2[i] for j in range(len(method.parser.variables)): item = QTableWidgetItem() item.setText(str(method.solution[j])) self.ui.resultTable.setItem(i, j, item) else: self.ui.resultTable.setColumnCount(self.method_2.parser.numOfVariables) self.ui.resultTable.setHorizontalHeaderLabels(self.method_2.parser.variables) self.ui.resultTable.setRowCount(1) self.ui.resultTable.setVerticalHeaderLabels([self.selected]) for j in range(len(self.method_2.parser.variables)): item = QTableWidgetItem() item.setText(str(self.method_2.solution[j])) self.ui.resultTable.setItem(0, j, item) def openSingleStep(self): self.resultDialog = Handler_DialogResult(self) def populateResultTable(self): self.ui.resultTable.clear() self.ui.resultTable.setColumnCount(5) self.ui.resultTable.setHorizontalHeaderLabels(["Number of Iterations" \ , "Execution Time", "Approximate Root", "Precision", "Graph"]) (self.ui.resultTable.setVerticalHeaderItem(i, QTableWidgetItem()) for i in range(self.ui.resultTable.rowCount())) if self.selected == "All Methods": self.ui.resultTable.setRowCount(7) self.ui.resultTable.setVerticalHeaderLabels(self.list_methods) for i in range(len(self.all_methods)): self.addToTable(self.ui.resultTable, self.all_methods[i], i) else: self.ui.resultTable.setRowCount(1) (self.ui.resultTable.setVerticalHeaderItem(i, QTableWidgetItem()) for i in range(self.ui.resultTable.rowCount())) self.ui.resultTable.setVerticalHeaderLabels([self.selected]) self.addToTable(self.ui.resultTable, self.method, 0) def methodFactory_2(self): self.all_methods_2 = [] self.method_2 = None parser = None parser = ParserAndChecker(self.equations.copy()) if self.selected == "Gaussian-elimination": self.method_2 = gaussEliminationClass(parser) elif self.selected == "LU decomposition": self.method_2 = LUClass(parser) elif self.selected == "Gaussian-Jordan": self.method_2 = gaussJordanClass(parser) elif self.selected == "Gauss-Seidel": self.method_2 = GaussSeidel(parser) elif self.selected == "All": self.all_methods_2.append(gaussEliminationClass(ParserAndChecker(self.equations))) self.all_methods_2.append(LUClass(ParserAndChecker(self.equations))) self.all_methods_2.append(gaussJordanClass(ParserAndChecker(self.equations))) self.all_methods_2.append(GaussSeidel(ParserAndChecker(self.equations))) def methodFactory(self): self.all_methods = [] self.method = None if self.selected == "Bisection": self.method = Bisection(self.function, self.x_lower, self.x_upper, self.epsilon, self.max_itr) elif self.selected == "False-Position": self.method = FalsePosition(self.function, self.x_lower, self.x_upper, self.epsilon, self.max_itr) elif self.selected == "Fixed Point": self.method = FixedPointIterationMethod() self.method.setFuncionAndIntialpoint(self.function, self.x_lower) self.method.setMaxIteration(self.max_itr) self.method.setEpsilon(self.epsilon) elif self.selected == "Newton-Raphson": self.method = NewtonRaphasonMethod() self.method.setFuncionAndIntialpoint(self.function, self.x_lower) self.method.setMaxIteration(self.max_itr) self.method.setEpsilon(self.epsilon) elif self.selected == "Secant": self.method = secantMethod() self.method.setFuncionAndIntialpoint(self.function, self.x_lower, self.x_upper) self.method.setMaxIteration(self.max_itr) self.method.setEpsilon(self.epsilon) elif self.selected == "Bierge-Vieta": self.method = birgeVietaMethod() self.method.setFuncionAndIntialpoint(self.function, self.x_lower) self.method.setMaxIteration(self.max_itr) self.method.setEpsilon(self.epsilon) elif self.selected == "Muller": self.method = MullerMethod() self.method.setFuncionAndIntialpoint(self.function, self.x_lower, self.x_upper, self.x_3) self.method.setMaxIteration(self.max_itr) self.method.setEpsilon(self.epsilon) elif self.selected == "All Methods": self.all_methods.append(Bisection(self.function, self.xl_bisection, self.xu_bisection, self.epsilon, self.max_itr)) self.all_methods.append(FalsePosition(self.function, self.xl_falsePosition, self.xu_falsePosition, self.epsilon, self.max_itr)) method = FixedPointIterationMethod() method.setFuncionAndIntialpoint(self.function, self.xi_fixedPoint) method.setMaxIteration(self.max_itr) method.setEpsilon(self.epsilon) self.all_methods.append(method) method = NewtonRaphasonMethod() method.setFuncionAndIntialpoint(self.function, self.xi_newtonRaphson) method.setMaxIteration(self.max_itr) method.setEpsilon(self.epsilon) self.all_methods.append(method) method = secantMethod() method.setFuncionAndIntialpoint(self.function, self.x1_secant, self.x2_secant) method.setMaxIteration(self.max_itr) method.setEpsilon(self.epsilon) self.all_methods.append(method) method = birgeVietaMethod() method.setFuncionAndIntialpoint(self.function, self.xi_biergeVieta) method.setMaxIteration(self.max_itr) method.setEpsilon(self.epsilon) self.all_methods.append(method) method = MullerMethod() method.setFuncionAndIntialpoint(self.function, self.x1_muller, self.x2_muller, self.x3_muller) method.setMaxIteration(self.max_itr) method.setEpsilon(self.epsilon) self.all_methods.append(method) def run_2(self): if self.selected == "All": for method in self.all_methods_2: method.solve() else : self.method_2.solve() def run(self): if self.selected == "All Methods": for method in self.all_methods: method.runMethod() else : self.method.runMethod() #self.setCE() def setInputsWidgets_2(self): self.ui.contentWidget_1.hide() self.ui.contentWidget_2.show() self.ui.btnSingleStep.hide() if (self.selected == "Gauss-Seidel") | (self.selected =="All"): self.ui.txtEpsilon_2.show() self.ui.txtMaxItr_2.show() self.ui.lblEpsilon_2.show() self.ui.lblMaxItr_2.show() self.ui.txtEditInitial.show() self.ui.btnGaussSeidel.show() else: self.ui.txtEpsilon_2.hide() self.ui.txtMaxItr_2.hide() self.ui.lblEpsilon_2.hide() self.ui.lblMaxItr_2.hide() self.ui.txtEditInitial.hide() self.ui.btnGaussSeidel.hide() def setInputsWidgets(self): self.ui.contentWidget_2.hide() self.ui.contentWidget_1.show() self.ui.btnGaussSeidel.hide() self.ui.btnSingleStep.show() if self.selected == "Bisection": self.ui.tabAllMethods.hide() self.ui.lblXl.setText("Xl:") self.ui.lblXl.show() self.ui.txtXl.show() self.ui.lblXu.setText("Xu:") self.ui.lblXu.show() self.ui.txtXu.show() self.ui.lblX3.hide() self.ui.txtX3.hide() elif self.selected == "False-Position": self.ui.tabAllMethods.hide() self.ui.lblXl.setText("Xl:") self.ui.txtXl.show() self.ui.lblXl.show() self.ui.lblXu.setText("Xu:") self.ui.lblXu.show() self.ui.txtXu.show() self.ui.lblX3.hide() self.ui.txtX3.hide() elif self.selected == "Fixed Point": self.ui.tabAllMethods.hide() self.ui.lblXl.setText("Xi:") self.ui.lblXl.show() self.ui.txtXl.show() self.ui.lblXu.setText("Xu:") self.ui.txtXu.hide() self.ui.lblXu.hide() self.ui.lblX3.hide() self.ui.txtX3.hide() elif self.selected == "Newton-Raphson": self.ui.tabAllMethods.hide() self.ui.lblXl.setText("Xi:") self.ui.lblXl.show() self.ui.txtXl.show() self.ui.lblXu.setText("Xu:") self.ui.lblXu.hide() self.ui.txtXu.hide() self.ui.lblX3.hide() self.ui.txtX3.hide() elif self.selected == "Secant": self.ui.tabAllMethods.hide() self.ui.lblXl.setText("X1:") self.ui.lblXl.show() self.ui.txtXl.show() self.ui.lblXu.setText("X2:") self.ui.lblXu.show() self.ui.txtXu.show() self.ui.lblX3.hide() self.ui.txtX3.hide() elif self.selected == "Bierge-Vieta": self.ui.tabAllMethods.hide() self.ui.lblXl.setText("Xi:") self.ui.lblXl.show() self.ui.txtXl.show() self.ui.lblXu.setText("Xu:") self.ui.lblXu.hide() self.ui.txtXu.hide() self.ui.lblX3.hide() self.ui.txtX3.hide() elif self.selected == "Muller": self.ui.tabAllMethods.hide() self.ui.lblXl.setText("X1:") self.ui.lblXl.show() self.ui.txtXl.show() self.ui.lblXu.setText("X2:") self.ui.lblXu.show() self.ui.txtXu.show() self.ui.lblX3.setText("X3:") self.ui.lblX3.show() self.ui.txtX3.show() elif self.selected == "All Methods": self.ui.lblXl.hide() self.ui.txtXl.hide() self.ui.lblXu.hide() self.ui.txtXu.hide() self.ui.lblX3.hide() self.ui.txtX3.hide() self.ui.tabAllMethods.show() def getSelected(self): if not self.resultDialog == None: return selected = mainWindow.ui.treeSelection.currentItem().text(0) if selected == "Root Finder": return elif selected == "System of Equations Solver": return self.method = None self.all_methods = None self.method_2 = None self.all_methods_2 = None self.ui.btnGaussSeidel.setDisabled(True) self.ui.btnSingleStep.setDisabled(True) self.selected = selected def addToTable(self, tableWidget, method, row): item_itrNum = QTableWidgetItem() item_itrNum.setText(str(method.getNumOfIteration())) tableWidget.setItem(row, 0, item_itrNum) item_executionTime = QTableWidgetItem() item_executionTime.setText(str(method.executionTime)) tableWidget.setItem(row, 1, item_executionTime) item_root = QTableWidgetItem() item_root.setText(str(method.getRoot())) tableWidget.setItem(row, 2, item_root) item_precision = QTableWidgetItem() item_precision.setText(str(method.getPrecision())) tableWidget.setItem(row, 3, item_precision) item_graph = QTableWidgetItem() tableWidget.setItem(row, 4, item_graph) if type(method) is birgeVietaMethod: item_graph.setText("-") return button = QPushButton("show..") button.setFlat(True) font = button.font() font.setUnderline(True) button.setFont(font) button.clicked.connect(lambda: self.btnGraphClicked(method, method.getNumOfIteration())) tableWidget.setCellWidget(row, 4, button) def btnGraphClicked(self, method, itr_num): plt.close() method.graph(itr_num)
class volBrainClient(QtWidgets.QMainWindow): def __init__(self, base_url, session, email, password, parent=None): super(volBrainClient, self).__init__(parent) self.session = session self.base_url = base_url self.jobUploadManager = JobUploadManager(base_url, session) self.jobUploadManager.uploaded.connect(self.uploaded) self.spacerItem = QtWidgets.QSpacerItem( 40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.selectFilesButton.clicked.connect(self.chooseFile) self.ui.cleanButton.clicked.connect(self.cleanList) self.ui.showJobsButton.clicked.connect(self.openProcessWindow) self.ui.uploadFilesButton.clicked.connect(self.uploadSelected) if (volbrain.upload_limit_reached(base_url, session)): self.disableUpload() else: self.ui.uploadLimitReachedLabel.hide() self.email = email self.password = password self.fileWidgets = [] def uploadSelected(self): files = [] for w in self.fileWidgets: if (w.getChecked()): files += [ FileUpload(w.getFile(), w.getGenre(), w.getAge(), w.getPipeline()) ] if len(files) > 0: self.upload(files) self.cleanList() else: QMessageBox.information( self, 'Selecciona un fichero.', "No hay ningún fichero pendiente por subir. Selecciona alguno.", QMessageBox.Ok, QMessageBox.Ok) def upload(self, files): QMessageBox.information(None, 'Cargando.', "Los archivos han comenzado a cargarse.", QMessageBox.Ok, QMessageBox.Ok) self.jobUploadManager.addJobs(files) # Este método es ejecutado cuando se termina de subir un paquete de ficheros # en el JobUploadManager. def uploaded(self, uploadedCount, total): if uploadedCount == total: QMessageBox.information( None, 'Completado', "Los archivos se han subido correctamente.", QMessageBox.Ok, QMessageBox.Ok) else: QMessageBox.warning( None, 'Error', "Ha habido un problema al cargar algún fichero. Quizá hayas superado el límite diario. Subidos " + str(uploadedCount) + "/" + str(total) + ".", QMessageBox.Ok, QMessageBox.Ok) def chooseFile(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog (fileNames, _) = QFileDialog.getOpenFileNames(None, "Selecciona un fichero", "", "Zip Files (*.zip)", options=options) print(fileNames) if len(fileNames) > 0: self.ui.jobListLayout.removeItem(self.spacerItem) for fileName in fileNames: w = FileWidget(fileName) self.fileWidgets += [w] self.ui.jobListLayout.addWidget(w) self.ui.jobListLayout.addItem(self.spacerItem) def cleanList(self): for w in self.fileWidgets: w.setParent(None) self.fileWidgets = [] def openProcessWindow(self): self.win = ProcessWindow.ProcessWindow(self.base_url, self.session) self.win.show() ''' Se deshabilita la subida si el usuario ha alcanzado el límite. ''' def disableUpload(self): self.ui.uploadLimitReachedLabel.show() self.ui.selectFilesButton.setEnabled(False) self.ui.uploadFilesButton.setEnabled(False)
class Anagram_Solver(QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.initUI() def initUI(self): # Activate SolveFunction when Solve button is clicked self.ui.SolveButton.clicked.connect(self.SolveFunction) # Activate various functions when menu actions are selected self.ui.actionSave.triggered.connect(self.SaveFunction) self.ui.actionLoad.triggered.connect(self.LoadFunction) self.ui.actionReset.triggered.connect(self.ResetFunction) self.ui.actionQuit.triggered.connect(self.QuitFunction) self.ui.actionAbout.triggered.connect(self.AboutFunction) # Set action menu shortcuts self.ui.actionSave.setShortcut("Ctrl+S") self.ui.actionLoad.setShortcut("Ctrl+L") self.ui.actionQuit.setShortcut("Ctrl+Q") self.show() def SolveFunction(self): # Collect input string and calculate its key value input = str(self.ui.InputString.toPlainText()).strip() input_key = getKey(input) # Collect list of required words and check if they are valid required = list( map(str.strip, str(self.ui.RequiredWords.toPlainText()).split(','))) input_key = anagram_solver.checkWords(input_key, required) if input_key == -1: self.ui.OutputList.clear() self.ui.OutputList.addItem("Required words not in input string") return # Collect min/max length inputs and check if they are valid min_s = str(self.ui.MinValue.currentText()) max_s = str(self.ui.MaxValue.currentText()) min = -1 if min_s == "(none)" else int(min_s) max = -1 if max_s == "(none)" else int(max_s) if max < min and not max == -1: self.ui.OutputList.clear() self.ui.OutputList.addItem("Max length is less than min length") return # Create trimmed dictionary from constraints trimmed_dict = anagram_solver.trimDictionary(hashmap, input_key, min, max) # Reset the progress bar and output list solution_counter, progress_counter = 0, 0 progress_max = len(trimmed_dict) self.ui.ProgressBar.setValue(0) self.ui.ProgressBar.setMaximum(progress_max) self.ui.OutputList.clear() QApplication.processEvents() # Start solving the anagrams for key in trimmed_dict.copy(): for word in trimmed_dict[key]: word_list = anagram_solver.solveHelper(trimmed_dict, input_key / key, required + [word]) if word_list: for sol in word_list: solutions = anagram_solver.StringMaker(sol) for s in solutions: self.ui.OutputList.addItem(s) solution_counter += 1 if solution_counter >= SOLUTION_LIMIT: break if solution_counter >= SOLUTION_LIMIT: break if solution_counter >= SOLUTION_LIMIT: break if solution_counter >= SOLUTION_LIMIT: break trimmed_dict.pop(key) progress_counter += 1 self.ui.ProgressBar.setValue(progress_counter) QApplication.processEvents() # Fill up progress bar if loop ended early for 1000 solution limit if not progress_counter == progress_max: self.ui.ProgressBar.setValue(progress_max) QApplication.processEvents() def SaveFunction(self): print("saved") def LoadFunction(self): print("loaded") def ResetFunction(self): print("reset") self.ui.OutputList.clear() self.ui.InputString.clear() self.ui.RequiredWords.clear() self.ui.MinValue.setCurrentIndex(0) self.ui.MaxValue.setCurrentIndex(0) self.ui.ProgressBar.setValue(0) QApplication.processEvents() def QuitFunction(self): print("quitting") QApplication.quit() def AboutFunction(self): print("about")
class MainWindow(QtGui.QMainWindow): needsThetaInputList = [ 'Momentum transfer (Q Angstroms^-1)', 'd-Spacing (Angstroms)' ] needsThetaOutputList = [ 'Momentum transfer (Q Angstroms^-1)', 'd-Spacing (Angstroms)' ] needsFlightPathInputList = ['Time of flight (microseconds)'] needsFlightPathOutputList = ['Time of flight (microseconds)'] def thetaEnable(self, enabled): self.ui.lineEdit_4.setEnabled(enabled) if enabled == False: self.ui.lineEdit_4.clear() def flightPathEnable(self, enabled): self.ui.lineEdit_3.setEnabled(enabled) if enabled == False: self.ui.lineEdit_3.clear() def setInstrumentInputs(self): #disable both self.thetaEnable(False) self.flightPathEnable(False) #get the values of the two unit strings inOption = self.ui.inputUnits.currentText() outOption = self.ui.outputUnits.currentText() #for theta: enable if input or output unit requires it if inOption in self.needsThetaInputList: self.thetaEnable(True) if outOption in self.needsThetaOutputList: self.thetaEnable(True) #for flightpath: enable if input or output unit requires it if inOption in self.needsFlightPathInputList: self.flightPathEnable(True) if outOption in self.needsFlightPathOutputList: self.flightPathEnable(True) def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) self.ui.lineEdit_3.setValidator( QtGui.QDoubleValidator(self.ui.lineEdit_3)) self.ui.lineEdit_4.setValidator( QtGui.QDoubleValidator(self.ui.lineEdit_4)) QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert) QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs) QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs) self.setInstrumentInputs() ##defaults self.flightpath = -1.0 self.Theta = -1.0 self.stage1output = 0.0 self.stage2output = 0.0 def convert(self): if self.ui.InputVal.text() == "": return try: inOption = self.ui.inputUnits.currentText() outOption = self.ui.outputUnits.currentText() if self.ui.lineEdit_3.text() != '': self.flightpath = float(self.ui.lineEdit_3.text()) else: self.flightpath = -1.0 if self.ui.lineEdit_4.text() != '': self.Theta = float(self.ui.lineEdit_4.text()) * math.pi / 360.0 self.stage1output = self.input2energy( float(self.ui.InputVal.text()), inOption) self.stage2output = self.energy2output(self.stage1output, outOption) self.ui.lineEdit_2.clear() self.ui.lineEdit_2.insert(str(self.stage2output)) except Exception, e: QtGui.QMessageBox.warning(self, "TofConverter", str(e)) return
class MainWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Status Lights statusGrid = self.ui.groupBoxStatus.layout() statusLightCom = QLedIndicator("COM") # statusLightCom.setIndicatorTitle("COM") statusLightRpi = QLedIndicator("RPi") # statusLightRpi.setIndicatorTitle("RPi") statusLightJoystick = QLedIndicator("Joystick") # statusLightJoystick.setIndicatorTitle("RPi") statusLightLights = QLedIndicator("Lights") statusGrid.addWidget(statusLightCom, 0, 0, 1, 1) statusGrid.addWidget(statusLightRpi, 0, 1, 1, 1) statusGrid.addWidget(statusLightJoystick, 1, 0, 1, 1) statusGrid.addWidget(statusLightLights, 1, 1, 1, 1) # Sensor Readouts self.rov = QRov() if len(self.rov.sensors) > 0: vLayout = QVBoxLayout(self.ui.groupBoxSensorReadouts) i = 0 for sensor in self.rov.sensors: hLayout = QHBoxLayout(self) hLayout.addWidget(sensor.labelName) hLayout.addWidget(sensor.lcd) hLayout.addWidget(sensor.labelUnits) hLayout.setAlignment(hLayout, Qt.AlignHCenter) vLayout.addLayout(hLayout) self.setup_plots(sensor.name, sensor.units, i) i += 1 self.ui.groupBoxSensorReadouts.setLayout(vLayout) if len(self.rov.relays) > 0: for relay in self.rov.relays: self.ui.groupBoxRelayButtons.layout().addWidget(relay.button) self.activityMonitor = QActivityMonitor(self.ui.teLog) self.activityMonitor.display("GUI started...", t.Message.INFO) self.ui.graphWidget.setBackground(self.palette().window().color()) self.ui.graphWidget.ci.layout.setContentsMargins(0, 0, 0, 0) self.ui.graphWidget.ci.layout.setSpacing(20) def on_buttonClearLog_clicked(self): self.ui.teLog.clear() def on_buttonCopyLogToClipboard_clicked(self): clipboard = QApplication.clipboard() clipboard.setText(self.ui.teLog.toPlainText()) def setup_plots(self, title, units, position): graphColor = self.palette().highlight().color() graphColor.setAlpha(90) p = self.ui.graphWidget.addPlot(0, position) leftAxis = p.getAxis('left') leftAxis.setLabel(units=units) leftAxis.setPen(self.palette().windowText().color()) leftAxis.setTextPen(self.palette().windowText().color()) topAxis = p.getAxis('top') topAxis.setPen(self.palette().windowText().color()) topAxis.setTextPen(self.palette().windowText().color()) topAxis.setStyle(showValues=False) rightAxis = p.getAxis('right') rightAxis.setPen(self.palette().windowText().color()) rightAxis.setTextPen(self.palette().windowText().color()) rightAxis.setStyle(showValues=False) bottomAxis = p.getAxis('bottom') bottomAxis.setPen(self.palette().windowText().color()) bottomAxis.setTextPen(self.palette().windowText().color()) bottomAxis.setStyle(showValues=False) titleColor = self.palette().windowText().color() p.setTitle(title, color=titleColor, size='12pt', bold=True) p.showAxis('top', True) p.showAxis('right', True) p.showGrid(x=True, y=True, alpha=0.2) p.setMouseEnabled(x=False, y=False) p.plot(y=3 + np.random.normal(size=50), brush=graphColor, fillLevel=0)
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() # ui init self.ui = Ui_MainWindow() self.ui.setupUi(self) # MainWindow Title self.setWindowTitle('Youtube2Mp3') # set window icon icon_path = self.resource_path('icon/icon_window.png') self.setWindowIcon(QtGui.QIcon(icon_path)) # save place self.save_dir = '轉換的音樂' os.makedirs(self.save_dir, exist_ok=True) # convert button self.ui.convertButton.clicked.connect(self.convert) # status label self.ui.statusLabel.setText('') # mp4 filepath self.mp4_file_path = '' # for packaging one file on pyinstaller def resource_path(self, relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath('.') return os.path.join(base_path, relative_path) def convert(self): url_text = self.ui.urlEdit.text( ) # https://www.youtube.com/watch?v=biSB9_Z3VUw if url_text is not '': QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) try: video = YouTube(url_text) video_name = sanitize_filename(video.title) if video_name == 'Youtube': raise NotImplementedError self.mp4_file_path = os.path.join(self.save_dir, f'{video_name}.mp4') video.streams.filter(progressive=True, file_extension='mp4').first().download( output_path=self.save_dir, filename=video_name) mp3_file_path = os.path.join(self.save_dir, f'{video_name}.mp3') stream = ffmpeg.input(self.mp4_file_path) stream = ffmpeg.output(stream, mp3_file_path) ffmpeg.run(stream, overwrite_output=True) except Exception as e: # fail to convert print(e) self.ui.statusLabel.setText( '轉換失敗,請重試一次') #self.ui.statusLabel.setText('轉換失敗,請重試一次') else: self.ui.statusLabel.setText('轉換成功') if os.path.exists(self.mp4_file_path): os.remove(self.mp4_file_path) QtWidgets.QApplication.restoreOverrideCursor() self.ui.urlEdit.setText('') else: self.ui.statusLabel.setText('請輸入 Youtube 網址')
class Main(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) #MGM(V0.2.1): This part is implementing multithreading techniques using Qtimer(0).In multithreaded applications, #you can use QTimer in any thread that has an event loop. A QTimer with a timeout of 0 will time out as soon as #all the events in the window system's event queue have been processed. This was used to do heavy work of #the annotations' calculations while providing a snappy user interface. Otherwise after printing is finished it #takes a couple of minutes to run QtGui.QApplication.instance().exec_() again. self.timer = QtCore.QTimer() #MGM(V0.2.1): To define a timer for using in self.print_plot() self.timer.timeout.connect(self.print_plot) #MGM(V0.2.1): To run self.print_plot() after timer emits timeout signal self.print_plot_Qtimer_Counter=0 #MGM(V0.2.1): This is a counter that is used in self.print_plot() to calculate the number of pages which have been printed. We can control Qtimer.stop by using this counter. #MGM(V0.2): These instance variables are defined for reading of the EDF files partially # self.timeaxis_start=0 #MGM(V0.2): The starting point on the time axis in the plot window self.timeaxis_end=10 #MGM(V0.2): The ending point on the time axis in the plot window self.time_readedf_start=0 #MGM(V0.2): The starting point for reading raw data records from EDF file. self.time_readedf_end=1 #MGM(V0.2): The ending point for reading raw data records from EDF file. In order than related function run for the first time, this value is chosen lesser than self.timeaxis_end. self._showLabels=False; self._needSave=False; self._script_dir=os.path.abspath(os.path.dirname(__file__)); # User Interface designed by designer # self.ui=Ui_MainWindow() self.ui.setupUi(self) # toolbar # MGM(V0.2.2): This part has been edited for creating the stand-alone executable. As after installing # setup.exe, the application can be lunched in every folder, we should use a address which # is not relative. self.viewGroup = QtGui.QActionGroup(self); self.panAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/pan_mode.png'), 'Pan', self) self.zoomAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/zoom_mode.png'), 'Zoom', self) self.editAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/edit_mode.png'), 'Edit', self) self.nextAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/next.png'), 'Next', self) self.backAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/prev.png'), 'Back', self) self.nextAction.setShortcut('Right') self.backAction.setShortcut('Left') self.panAction.setCheckable(True) self.panAction.setChecked(True); self.zoomAction.setCheckable(True) self.editAction.setCheckable(True) self.panAction.setDisabled(True) self.zoomAction.setDisabled(True) self.editAction.setDisabled(True) self.nextAction.setDisabled(True) self.backAction.setDisabled(True) # connect to functions # self.panAction.triggered.connect(self.setPan) self.zoomAction.triggered.connect(self.setZoom) self.editAction.triggered.connect(self.setEdit) self.nextAction.triggered.connect(self.goNext); self.backAction.triggered.connect(self.goBack); self.ui.plotWidget.sigTimeRangeChanged.connect(self.EDFDynamicPlotter) #MGM(V0.2): When the time range in the plot window is changing by moving slider or changing other features this signal will emit. #connect changed signal from EditPlotWidget # self.ui.plotWidget.sigDocChanged.connect(self.onDocChange) self.ui.plotWidget.sigConfirmed.connect(self.onConfirm) self.ui.plotWidget.sigRightAnnotationExist.connect(self.manageNextAnnotationButton) self.ui.plotWidget.sigLeftAnnotationExist.connect(self.manageBackAnnotationButton) self.viewGroup.addAction(self.panAction) self.viewGroup.addAction(self.zoomAction) self.viewGroup.addAction(self.editAction) self.toolbar=QtGui.QToolBar() self.toolbar.addAction(self.panAction) self.toolbar.addAction(self.zoomAction) self.toolbar.addAction(self.editAction) spacer = QtGui.QWidget() spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.toolbar.addWidget(spacer) self.toolbar.addAction(self.backAction) self.toolbar.addAction(self.nextAction) # MGM(V0.2.2): This part has been edited for creating the stand-alone executable. As after installing # setup.exe, the application can be lunch in every folder, we should use a address which # is not relative. self.confirmAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/confirm.png'), 'Confirm', self) self.confirmAction.setDisabled(True) self.cancelAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/cancel.png'), 'Cancel', self) self.cancelAction.setDisabled(True) self.saveAction = QtGui.QAction(QtGui.QIcon(self._script_dir+'/resource/save.png'), 'Save', self) self.saveAction.setDisabled(True) self.saveAction.triggered.connect(self.savePressed) self.confirmAction.triggered.connect(self.confirmPressed) self.cancelAction.triggered.connect(self.cancelPressed) spacer = QtGui.QWidget() spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.toolbar.addWidget(spacer) self.toolbar.addAction(self.cancelAction) self.toolbar.addAction(self.confirmAction) self.toolbar.addAction(self.saveAction) self.addToolBar(self.toolbar) # Project manager : a class that contains all methods to manage(create,read,interpret) a project # self.pmanager = None; self.project_directory=[]; self.status="project_close" self.current_user=""; # current active username self.current_annotation_key=None; #connect signals to slots # # actionNew self.ui.actionNew.setDisabled(True) #actionOpen self.ui.actionOpen.triggered.connect(self.open_project) # MGM(V0.2.1 ): : When print option in menu is pressed by user, print_plot() will be called. self.ui.actionPrint.triggered.connect(self.print_plot) #MGM(V0.2.1) # actionExit self.ui.actionExit.triggered.connect(self.exit) #amplitude scale self.ui.amplitudeSpinBox.setValue(0.00) self.ui.amplitudeSpinBox.setMinimum(1) self.ui.amplitudeSpinBox.setMaximum(5000) self.ui.amplitudeSpinBox.valueChanged.connect(self.ui.plotWidget.changeAmplitudescale) self.ui.timeSpinBox.setValue(10.0) #MGM(V0.2): The parameter of setValue changed from 0 to 10.00 self.ui.timeSpinBox.setMinimum(1) self.ui.timeSpinBox.setMaximum(300) self.ui.timeSpinBox.valueChanged.connect(self.ui.plotWidget.setTimescale) self.ui.showLabelButton.pressed.connect(self.showLabelPressed) self.ui.markFinishButton.pressed.connect(self.markFinishPressed) self.ui.markFinishButton.setDisabled(True) def setPan(self): self.ui.plotWidget.vb_mode="pan" self.ui.plotWidget.viewBox.set_mode("pan") def setEdit(self): self.ui.plotWidget.vb_mode="add" self.ui.plotWidget.viewBox.set_mode("add") pass def setZoom(self): self.ui.plotWidget.vb_mode="zoom" self.ui.plotWidget.viewBox.set_mode("zoom") pass def manageBackAnnotationButton(self,state): if state: self.backAction.setEnabled(True) else: self.backAction.setDisabled(True) # if user pressed next def goBack(self): self.ui.plotWidget.goBack() def manageNextAnnotationButton(self,state): if state: self.nextAction.setEnabled(True) else: self.nextAction.setDisabled(True) # if user pressed next def goNext(self): self.ui.plotWidget.goNext() # by save we just copy current session to last session def savePressed(self): self.pmanager.save(self.current_annotation_key, self.current_user) self.needSave = False self.saveAction.setDisabled(True) #if cancel pressed # def cancelPressed(self): self.ui.plotWidget.cancelChanges(); self.confirmAction.setDisabled(True) self.cancelAction.setDisabled(True) # if Confirm pressed # def confirmPressed(self): self.ui.plotWidget.confirmChanges(); #when confirmed is done def onConfirm(self): self.pmanager.writeAnnotationFile(self.current_annotation_key, self.ui.plotWidget._annotations) # reload the label annotations = self.loadAnnotations(self.pmanager.annotation_files[self.current_annotation_key],self.pmanager.montage_order) self.ui.plotWidget.set_annotations(annotations) self.ui.plotWidget.pre_compute_view() #MGM(V0.2): This line added because now pre_compute_view() is not a part of set_annotations() self.ui.plotWidget.update() self.confirmAction.setDisabled(True) self.cancelAction.setDisabled(True) self.needSave = True self.saveAction.setEnabled(True) # when document changes due to edit or add new annotations # def onDocChange(self): self.confirmAction.setEnabled(True) self.cancelAction.setEnabled(True) self.status="changed" def markFinishPressed(self): # check if user want to mark the last file as finished. # choice = QtGui.QMessageBox.question(self,'Message','Do you want to mark '+self.current_annotation_key+'as <b>Finished</b>?', QtGui.QMessageBox.Yes |QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if choice == QtGui.QMessageBox.Yes: self.pmanager.add_finished_file(self.current_annotation_key); self.pmanager.finished_files.append(self.current_annotation_key) self.edfListUpdate(); elif choice == QtGui.QMessageBox.Cancel: return; #MGM(V0.2.1): When print option in menu is pressed by user print_plot() will be called. It is using Qtimer(0) # multi-threading method which has been described before. # def print_plot(self): #MGM(V0.2.1): Start Qtimer and initialize related parameters for printing if (self.print_plot_Qtimer_Counter==0): # MGM(V0.2.2): This part is using dip.ui module. dip.ui module implements a toolkit independent API # for defining a user interface declaratively. Using dip.ui we are avoiding to create a lot # of .ui files and their related .py files for ever small task. Here we want to create a user # interface to get start time and end time for printing EEG signals and their annotations. model = dict(start_time_print='0',end_time_print=str(self.ui.plotWidget.total_time_recording)) # MGM(V0.2.2): Create the model. view_factory = Dialog(GroupBox('start_time_print','end_time_print'),window_title="Print Setting") # MGM(V0.2.2): Define the view. view = view_factory(model) # MGM(V0.2.2): Create an instance of the view bound to the model. view.execute() # MGM(V0.2.2): Enter the dialog's modal event loop. self.start_time_print = float(model['start_time_print']) # MGM(V0.2.2): Receive start time for printing. self.end_time_print = float(model['end_time_print']) # MGM(V0.2.2): Receive end time for printing. # MGM(V0.2.2): Check the parameters. if (self.start_time_print<0): self.start_time_print=0 if (self.end_time_print>self.ui.plotWidget.total_time_recording): self.end_time_print=self.ui.plotWidget.total_time_recording #MGM(V0.2.1): Open a dialog box for selecting a folder by user to save. Printed files will be saved in this folder. self.print_directory = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", QtCore.QDir.currentPath()); #MGM(V0.2.1): To start the Qtimer. It will be running until calling the timer.stop. self.timer.start(0) #MGM(V0.2.1): Calculate the number of pages which should be printed. #MGM(V0.2.2): Edited to calculate based on the parameters entered by the user. self.number_pages = int((self.end_time_print - self.start_time_print)/self.ui.plotWidget.time_scale) + 1 #MGM(V0.2.1): To initialize progress bar. self.progress = QtGui.QProgressDialog("Printing files...", "Cancel", 0, self.number_pages, self) self.progress.setWindowModality(QtCore.Qt.WindowModal) #MGM(V0.2.1): Moves and plots pages for a new print action. #MGM(V0.2.2): Edited to calculate based on the parameters entered by the user. self.ui.plotWidget.xpos_changed(self.start_time_print + (self.print_plot_Qtimer_Counter*self.ui.plotWidget.time_scale)) self.ui.plotWidget.slider.setValue(self.start_time_print + (self.print_plot_Qtimer_Counter*self.ui.plotWidget.time_scale)) #MGM(V0.2.1): To print plot window and export in .jpeg format using pyqtgraph library self.exportplotpng = pg.exporters.ImageExporter.ImageExporter(self.ui.plotWidget.PlotWidget.plotItem.scene()) #MGM(V0.2.1): To export the plot. @UndefinedVariable self.exportplotpng.parameters()['width'] = 1500 #MGM(V0.2.1) The with of the resolution of jpeg files. self.exportplotpng.export(self.print_directory + '\\' + str(self.print_plot_Qtimer_Counter) + '.jpg') #MGM(V0.2.1): To save the files in the folder which has been selected by user previously. #MGM(V0.2.1): To increase the progress bar. self.progress.setValue(self.print_plot_Qtimer_Counter) #MGM(V0.2.1): To calculate the number of pages which has been printed. self.print_plot_Qtimer_Counter+=1 #MGM(V0.2.1): To check if all pages have been printed or not. If yes timer will be stopped and progress bar will be finished. if (self.print_plot_Qtimer_Counter== self.number_pages): self.progress.setValue(self.number_pages) #MGM(V0.2.1): To finish the progress bar. self.timer.stop() #MGM(V0.2.1): To stop the timer self.print_plot_Qtimer_Counter=0 #MGM(V0.2.1): To reset the counter of number of pages which have been printed. #MGM(V0.2.1): To implement the cancel button in progress bar. if self.progress.wasCanceled(): self.progress.setValue(self.number_pages) self.timer.stop() self.print_plot_Qtimer_Counter=0 # called when show label button pressed # def showLabelPressed(self): if self._showLabels: self._showLabels = False; self.ui.plotWidget.hideLabels(); else: self._showLabels = True; self.ui.plotWidget.showLabels(); # redirect the close event into exit function # def closeEvent(self,ev): if self.exit(): ev.accept(); else: ev.ignore(); # manage exiting from the program # def exit(self): if self.saveAction.isEnabled(): choice = QtGui.QMessageBox.question(self,'Warning','Do you want to save changes?', QtGui.QMessageBox.Yes |QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if choice == QtGui.QMessageBox.Cancel: return False; elif choice == QtGui.QMessageBox.Yes: self.savePressed(); else: choice_final=QtGui.QMessageBox.question(self,'Warning','All changes will be lost',QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel,QtGui.QMessageBox.Cancel); if choice_final == QtGui.QMessageBox.Cancel: return False; if self.confirmAction.isEnabled(): choice = QtGui.QMessageBox.question(self,'Warning','You made some changes without confirming and saving. Do you like to apply and save the changes?', QtGui.QMessageBox.Yes |QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if choice == QtGui.QMessageBox.Cancel: return False; elif choice == QtGui.QMessageBox.Yes: self.confirmPressed() self.savePressed(); else: choice_final=QtGui.QMessageBox.question(self,'Warning','All changes will be lost',QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel,QtGui.QMessageBox.Cancel); if choice_final == QtGui.QMessageBox.Cancel: return False; QtGui.qApp.quit(); return True # open a project # def open_project(self): self.pmanager = ProjectManager(); self.ui.plotWidget.clear() self.ui.plotWidget.reset_annotation() #MGM(V0.2): For erasing annotations which have been loaded for previous files. filter_pname=QtCore.QString() #MGM(V0.2): The name of filter changed to filter_pname for removing the warning pname= str(QtGui.QFileDialog.getOpenFileName(self, 'Open Project', 'Projects','*.prj',filter_pname)) # pass to project manager if pname: self.ui.markFinishButton.setDisabled(True) self.project_directory = os.path.dirname(pname) os.chdir(self.project_directory) # read the project self.pmanager.read(pname) # ask for username and "login" the user (or add it the list of users or close the project) while 1==1: text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Enter your user-name:') if ok: username=str(text); if username in self.pmanager.usernames or self.pmanager.project_info["add_new_user"] == True: self.status = "project_open" else: self.status = "project_close" break; else: choice = QtGui.QMessageBox.question(self, 'Message',"Do you want to continue?", QtGui.QMessageBox.Yes |QtGui.QMessageBox.No, QtGui.QMessageBox.No) if choice == QtGui.QMessageBox.No: self.status="project_close" break; # return if the project is not open if self.status == "project_close": return if username in self.pmanager.usernames: choice = QtGui.QMessageBox.question(self, 'Message',"Are you "+self.pmanager.users[username]+"?", QtGui.QMessageBox.Yes |QtGui.QMessageBox.No, QtGui.QMessageBox.No) if choice == QtGui.QMessageBox.Yes: self.status="project_open" else: self.status="project_close" elif self.pmanager.project_info["add_new_user"]: while 1==1: text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog','Please, enter your first and last names:') if ok: self.pmanager.add_user(username,str(text)) break; else: choice = QtGui.QMessageBox.question(self, 'Message',"Do you want to continue?", QtGui.QMessageBox.Yes |QtGui.QMessageBox.No, QtGui.QMessageBox.No) if choice == QtGui.QMessageBox.No: self.status="project_close" break; if self.status == "project_close": return; self.current_user = username; # Now that user logged in successfully continue: # Create (if not existed) necessary directory structure (project_dir/username/root) and copy needed files self.pmanager.create_dir_structure(self.current_user) self.edfListUpdate(); def edfListUpdate(self): self.ui.edfListWidget.clear() for eeg_file in self.pmanager.eeg_files: self.litem=QtGui.QListWidgetItem(self.ui.edfListWidget) self.litem.setText(eeg_file) if eeg_file in self.pmanager.finished_files: icon=QtGui.QIcon(self._script_dir+"/resource/accept.png") else: icon=QtGui.QIcon(self._script_dir+"/resource/blank.png") self.litem.setIcon(icon) self.ui.edfListWidget.itemClicked.connect(self.edfChanged) def loadAnnotations(self,fname,map2order): with open(fname) as f: content = f.readlines() annotations = []; for line in content: tmp=line.split(",") chn_num=map2order[int(tmp[0])] st=float(tmp[1]) en=float(tmp[2]) cl=int(tmp[3]) annotations.append([chn_num,st,en,cl]) return annotations; def edfChanged(self,curr): self.timeaxis_start=0 #MGM(V0.2): To reset this parameter after opening a new EDF file. self.timeaxis_end=10 #MGM(V0.2): To reset this parameter after opening a new EDF file. self.time_readedf_start=0 #MGM(V0.2): To reset this parameter after opening a new EDF file. self.time_readedf_end=10 #MGM(V0.2): To reset this parameter after opening a new EDF file. key=str(curr.text()) # first check to see if the current open file is confirmed or saved # then ask the user if the task (for the open file) is finished or not if self.saveAction.isEnabled() or self.confirmAction.isEnabled(): choice = QtGui.QMessageBox.question(self,'Warning','You made some changes without confirming and saving. Do you like to apply and save the changes?', QtGui.QMessageBox.Yes |QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) if choice == QtGui.QMessageBox.Cancel: return; elif choice == QtGui.QMessageBox.Yes: self.confirmPressed() self.savePressed(); else: choice_final=QtGui.QMessageBox.question(self,'Warning','All changes will be lost',QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel,QtGui.QMessageBox.Cancel); if choice_final == QtGui.QMessageBox.Cancel: return; self.needSave = False; # enable the toolbar # self.panAction.setEnabled(True) self.zoomAction.setEnabled(True) self.editAction.setEnabled(True) # disable confirm, cancel and save self.cancelAction.setDisabled(True) self.confirmAction.setDisabled(True) self.saveAction.setDisabled(True) self.backAction.setDisabled(True) self.nextAction.setDisabled(True) self.ui.markFinishButton.setEnabled(True) self.current_annotation_key=key; fname = self.pmanager.eeg_files_full[key] y, sample_rate, physical_channels, time,tmp, self.ui.plotWidget.total_time_recording= ISIPEDFReader.load_edf(fname,0,100) #MGM(V0.2): Reads EDF file for 100 seconds. The variable of total_time_recording is using to transfer the the total time of the recording to EditPlotWidget module# @UnusedVariable # calculate the montage # self.pmanager.calculate_montage(physical_channels) cm_id=[] cm_name=[]; cm_color=[] for k in self.pmanager.class_mapping: cm_id.append(k) cm_name.append(self.pmanager.class_mapping[k]) for k in self.pmanager.class_mapping_colors: cm_color.append(self.pmanager.class_mapping_colors[k]) self.ui.plotWidget.setClassMapping(cm_id,cm_name) self.ui.plotWidget.setClassColorMapping(cm_id,cm_color) self.ui.plotWidget.setSignalNo(len(self.pmanager.montage_ids)) sig_labs=[self.pmanager.montage_names[self.pmanager.montage_map_order2id[i]] for i in self.pmanager.montage_map_order2id] self.ui.plotWidget.setSignalLabels(sig_labs) self.ui.plotWidget._x=time; for id in self.pmanager.montage_ids: # @ReservedAssignment if len(self.pmanager.montage_pairs[id])==2: self.ui.plotWidget._y[self.pmanager.montage_order[id]] = y[self.pmanager.montage_pairs[id][0]] - y[self.pmanager.montage_pairs[id][1]] elif len(self.pmanager.montage_pairs[id])==1: self.ui.plotWidget._y[self.pmanager.montage_order[id]] = y[self.pmanager.montage_pairs[id][0]] else: print "montage definition is either one or two channels" exit() # remove y del y; amps=[self.pmanager.montage_scales[self.pmanager.montage_map_order2id[i]] for i in self.pmanager.montage_map_order2id] # the assumption is that the first channel id is a representative of all (special channels with different scale should be set using config) self.ui.plotWidget.setAmplitudescale(amps) annotations = self.loadAnnotations(self.pmanager.annotation_files[key],self.pmanager.montage_order) self.ui.plotWidget.set_annotations(annotations) self.ui.plotWidget.pre_compute_view() #MGM(V0.2): This line added because now pre_compute_view() is not a part of set_annotations() ccolor = [self.pmanager.montage_color[self.pmanager.montage_map_order2id[i]] for i in self.pmanager.montage_map_order2id ] self.ui.plotWidget.setChannelColor(ccolor) self.ui.amplitudeSpinBox.setValue(self.pmanager.montage_scales[self.pmanager.montage_ids[0]]) self.ui.plotWidget.set_slider(self.ui.plotWidget) #MGM(V0.2): This line moved here. As running this line sooner is causing an error regarding recalling the class method of EDFDynamicPlotter. self.ui.plotWidget.update() # should be after update other wise it call the update function prematurely self.ui.plotWidget.setTimescale(10) #MGM(V0.2): This line moved here to reset time scale when EDF file changes. self.ui.timeSpinBox.setValue(10) #MGM(V0.2): This line moved here to reset time scale when EDF file changes. self.ui.showLabelButton.setEnabled(True) self.ui.plotWidget.check_annotation(0, 10) #MGM(V0.2): To check annotations when a new EDF file selects by user. Without this line Go Next annotation will remain inactive, when a new EDF file is loaded. #MGM(V0.2): This class method reads EDF file - which has been loaded before - partially and plot signals and # related annotations within the time of the plot window. For having a smoother slider this variable # is reading raw data recording from (timeaxis_start - 100 sec) to (timeaxis_end + 100 sec). # def EDFDynamicPlotter(self): key=self.current_annotation_key #MGM(V0.2): Assign EDF file which has been selected by user before. fname = self.pmanager.eeg_files_full[key] #MGM(V0.2): Open EDF file which has been selected before. self.timeaxis_start=int(self.ui.plotWidget.timeaxis_start) #MGM(V0.2): Getting the starting point on the time axis in the plot window. We need integer of this value to have an integer multiple of duration of time recording. self.timeaxis_end=int(self.ui.plotWidget.timeaxis_end) #MGM(V0.2): Getting the ending point on the time axis in the plot window. We need integer of this value to have an integer multiple of duration of time recording. if ((self.timeaxis_end>self.time_readedf_end) or (self.timeaxis_start<self.time_readedf_start)): #MGM(V0.2): This line is checking the value of time axis when time range changes. If the time is out of 200 sec buffer it reads new raw data records. self.time_readedf_start=self.timeaxis_start - 100 #MGM(V0.2):For having a smoother slider this variable is reading raw data recording from (timeaxis_start - 100 sec) to (timeaxis_end + 100 sec). self.time_readedf_end=self.timeaxis_end + 100 #MGM(V0.2):For having a smoother slider this variable is reading raw data recording from (timeaxis_start - 100 sec) to (timeaxis_end + 100 sec). if(self.time_readedf_start<0): #MGM(V0.2): To limit the starting point of time axis self.time_readedf_start=0 #MGM(V0.2): To limit the starting point of time axis if (self.time_readedf_end>self.ui.plotWidget.total_time_recording): #MGM(V0.2): To limit the ending point of time axis self.time_readedf_end=self.ui.plotWidget.total_time_recording #MGM(V0.2): To limit the ending point of time axis y, sample_rate, physical_channels, time, tmp, self.ui.plotWidget.total_time_recording= ISIPEDFReader.load_edf(fname,self.time_readedf_start,self.time_readedf_end) #MGM(V0.2): Reads EDF file Partially. The variable of total_time_recording is using as transfer the the total time of the recording to EditPlotWidget module# @UnusedVariable sig_labs=[self.pmanager.montage_names[self.pmanager.montage_map_order2id[i]] for i in self.pmanager.montage_map_order2id] #MGM(V0.2): self.ui.plotWidget.setSignalLabels(sig_labs) #MGM(V0.2) self.ui.plotWidget._x=time; #MGM(V0.2) for id in self.pmanager.montage_ids: #MGM(V0.2) # @ReservedAssignment if len(self.pmanager.montage_pairs[id])==2: #MGM(V0.2) self.ui.plotWidget._y[self.pmanager.montage_order[id]] = y[self.pmanager.montage_pairs[id][0]] - y[self.pmanager.montage_pairs[id][1]] #MGM(V0.2): elif len(self.pmanager.montage_pairs[id])==1: #MGM(V0.2) self.ui.plotWidget._y[self.pmanager.montage_order[id]] = y[self.pmanager.montage_pairs[id][0]] #MGM(V0.2) else: #MGM(V0.2): print "montage definition is either one or two channels" #MGM(V0.2) exit() #MGM(V0.2) # remove y del y; #MGM(V0.2): #annotations = self.loadAnnotations(self.pmanager.annotation_files[key],self.pmanager.montage_order) #MGM(V0.2) #MGM(V0.2.1):To make more efficient #MGM(V0.2):To make more efficient the program the program #self.ui.plotWidget.set_annotations(annotations) #MGM(V0.2) #MGM(V0.2.1):To make more efficient the program ccolor = [self.pmanager.montage_color[self.pmanager.montage_map_order2id[i]] for i in self.pmanager.montage_map_order2id ] #MGM(V0.2): self.ui.plotWidget.setChannelColor(ccolor) #MGM(V0.2): self.ui.amplitudeSpinBox.setValue(self.pmanager.montage_scales[self.pmanager.montage_ids[0]]) #MGM(V0.2): self.ui.plotWidget.update() #MGM(V0.2): # should be after update other wise it call the update function prematurely self.ui.showLabelButton.setEnabled(True); #MGM(V0.2):
class ArduloaderWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.portManager = PortManager(self.ui, startmonitor=True) self.configHelper = ConfigHelper(self.ui) self.initSignal() self.setupUi_Ex() def setupUi_Ex(self): self.setWindowTitle(const.windowtitle) self.ui.textEdit.append(const.aboutinfo) self.ui.headLabel.setPixmap(QPixmap(":/main/icons/main/arduloader.png")) self.setWindowIcon(QtGui.QIcon(":/main/icons/main/logo.png")) self.setBoards() self.configHelper.updateUiByConfig() def setBoards(self): ret, self.__boardsinfodict = BoardHelper.getBoardsInfo() if not ret: self.__boardsinfodict = {} return for boardname in self.__boardsinfodict.keys(): self.ui.mcuCombox.addItem(boardname) def onUploadFinish(self, ret, text): self.timer.stop() try: res = ret == 0 and "Upload SUCCESS:)" or ("%s\nUpload FAILED:(" % text) except IOError: res = "Read tmp file error" except: res = "Unknown error" self.ui.textEdit.append(res) def onUploading(self): prev_cursor = self.ui.textEdit.textCursor() self.ui.textEdit.moveCursor(QtGui.QTextCursor.End) self.ui.textEdit.insertPlainText (".") self.ui.textEdit.setTextCursor(prev_cursor) def getUploadArgs(self): infodict = self.__boardsinfodict.get(tostr(self.ui.mcuCombox.currentText())) if not infodict: return mcu = infodict["mcu"] speed = infodict["speed"] protocol = infodict["protocol"] maximum_size = infodict["maximum_size"] comport = tostr(self.ui.portCombox.currentText()) flash_bin = togbk(self.ui.hexfileCombox.currentText()) return {"mcu": mcu, "speed": speed, "protocol": protocol, "maximum_size": maximum_size, "comport": comport, "flash_bin": flash_bin } def checkUploadArgs(self, argsdict): if not argsdict: self.ui.textEdit.append("Get chip data error") return False if not OSPath.exists(argsdict.get("flash_bin", "")): self.ui.textEdit.append("Hex file not exists") return False # TODO: 检查文件大小是否超多当前芯片允许的最大值 return True def startUpload(self): argsdict = self.getUploadArgs() if not self.checkUploadArgs(argsdict): return self.uploader = Uploader() self.connect(self.uploader.qobj, QtCore.SIGNAL(const.finish_sig), self.onUploadFinish) self.uploader.resetUploadArgs(argsdict) self.ui.textEdit.clear() self.ui.textEdit.append("Start uploading\n") self.timer = QtCore.QTimer() self.timer.timeout.connect(self.onUploading) self.uploader.start() self.timer.start(const.process_interval) def onOpenHexFile(self): filename = QtGui.QFileDialog.getOpenFileName(self, "Choose a HEX file", ".", "HEX (*.hex)") if filename == "": return index = self.ui.hexfileCombox.findText(filename) if index < 0: self.ui.hexfileCombox.insertItem(0, filename) index = 0 self.ui.hexfileCombox.setCurrentIndex(index) def closeEvent(self, e): hex = tostr(self.ui.hexfileCombox.currentText()) com = tostr(self.ui.portCombox.currentText()) board = tostr(self.ui.mcuCombox.currentText()) self.configHelper.updateConfig(hex, com, board) e.accept() def initSignal(self): self.ui.exitButton.clicked.connect(self.close) self.ui.uploadButton.clicked.connect(self.startUpload) self.ui.openHexButton.clicked.connect(self.onOpenHexFile)
from PyQt5 import QtCore, QtGui, QtWidgets from Ui_MainWindow import Ui_MainWindow if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
class MainWindow(QMainWindow): def __init__(self, app): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.app = app self.dir = os.path.expanduser("~") self.filepathShiftIn = "" self.filepathConcatIn1 = "" self.filepathConcatIn2 = "" self.filepathConcatOut = "" self.filepathSplitIn = "" self.filepathSplitOut1 = "" self.filepathSplitOut2 = "" self.ui.lineEditFormat.setText(REGEXP) self.current_action = self.ui.tabs.currentIndex() self.ui.lineEditPathShiftIn.setText(self.filepathShiftIn) self.ui.lineEditPathConcatIn1.setText(self.filepathConcatIn1) self.ui.lineEditPathConcatIn2.setText(self.filepathConcatIn2) self.ui.lineEditPathSplitIn.setText(self.filepathSplitIn) def browse(self, lineEdit): filepath = QFileDialog.getOpenFileName( self, QApplication.translate("Main", "Ouvrir", None, QApplication.UnicodeUTF8), self.dir, "Sous-titres .srt (*.srt)") if not filepath: return self.dir = os.path.dirname(str(filepath)) lineEdit.setText(filepath) return filepath def launch_shift(self): self.ui.textEditShiftOut.clear() sign = self.ui.comboBoxSignShift.itemText( self.ui.comboBoxSignShift.currentIndex()) h = self.ui.spinBoxShiftH.value() m = self.ui.spinBoxShiftM.value() s = self.ui.spinBoxShiftS.value() ms = self.ui.spinBoxShiftMS.value() format_ = str(self.ui.lineEditFormat.text()) filepath = str(self.ui.lineEditPathShiftIn.text()) if not filepath: return if self.ui.radioButtonBeginAt.isChecked(): delta = get_delta(h, m, s, ms, "+") first = get_first_time(filepath, format_) delta = delta - first else: delta = get_delta(h, m, s, ms, sign) new_lines = convert(filepath, delta, format_) new_lines = "\n".join( line.replace("\r\n", "").replace("\n", "") for line in new_lines) self.ui.textEditShiftOut.appendPlainText(new_lines) cursor = self.ui.textEditShiftOut.cursorForPosition(QPoint(0, 0)) cursor.setPosition(QTextCursor.Start) self.ui.textEditShiftOut.setTextCursor(cursor) vScrollBar = self.ui.textEditShiftOut.verticalScrollBar() vScrollBar.setSliderPosition(0) def launch_concat(self): self.ui.textEditConcatOut.clear() sign = self.ui.comboBoxSignConcat.itemText( self.ui.comboBoxSignConcat.currentIndex()) decal_h = self.ui.spinBoxConcatH.value() decal_m = self.ui.spinBoxConcatM.value() decal_s = self.ui.spinBoxConcatS.value() decal_ms = self.ui.spinBoxConcatMS.value() format_ = str(self.ui.lineEditFormat.text()) filepathIn1 = str(self.ui.lineEditPathConcatIn1.text()) filepathIn2 = str(self.ui.lineEditPathConcatIn2.text()) if not filepathIn1 or not filepathIn2: return input_delta = get_delta(decal_h, decal_m, decal_s, decal_ms, sign) fd = open(filepathIn1, 'r') lines = fd.readlines() fd.close() last_lines = lines[len(lines) - 10:len(lines)] for l in lines: self.ui.textEditConcatOut.appendPlainText( l.replace("\r\n", "").replace("\n", "")) last_delta = None for l in last_lines: matches = re.compile(format_).findall(l) if len(matches) != 0: e_h = int(matches[0][4]) e_m = int(matches[0][5]) e_s = int(matches[0][6]) e_ms = int(matches[0][7]) last_delta = get_delta(e_h, e_m, e_s, e_ms) total_delta = last_delta + input_delta new_lines2 = convert(filepathIn2, total_delta, format_) for l in new_lines2: self.ui.textEditConcatOut.appendPlainText( l.replace("\r\n", "").replace("\n", "")) vScrollBar = self.ui.textEditConcatOut.verticalScrollBar() vScrollBar.setSliderPosition(0) def launch_split(self): self.ui.textEditSplitOut1.clear() self.ui.textEditSplitOut2.clear() decal_h = self.ui.spinBoxSplitH.value() decal_m = self.ui.spinBoxSplitM.value() decal_s = self.ui.spinBoxSplitS.value() decal_ms = self.ui.spinBoxSplitMS.value() format_ = str(self.ui.lineEditFormat.text()) filepathIn = str(self.ui.lineEditPathSplitIn.text()) if not filepathIn: return split_delta = get_delta(decal_h, decal_m, decal_s, decal_ms) fd = open(filepathIn, 'r') lines = fd.readlines() fd.close() output = self.ui.textEditSplitOut1 last_delta = get_delta(0, 0, 0, 0) for l in lines: matches = re.compile(format_).findall(l) new_line = l new_b_dt = 0 new_e_dt = 0 if len(matches) != 0: b_h = int(matches[0][0]) b_m = int(matches[0][1]) b_s = int(matches[0][2]) b_ms = int(matches[0][3]) e_h = int(matches[0][4]) e_m = int(matches[0][5]) e_s = int(matches[0][6]) e_ms = int(matches[0][7]) b_dt = datetime.time(hour=b_h, minute=b_m, second=b_s, microsecond=b_ms) e_dt = datetime.time(hour=e_h, minute=e_m, second=e_s, microsecond=e_ms) current_delta = get_delta(b_h, b_m, b_s, b_ms) zero_delta = get_delta(0, 0, 0, 0) if split_delta - current_delta > zero_delta: new_b_delta = get_delta(b_h, b_m, b_s, b_ms) new_e_delta = get_delta(e_h, e_m, e_s, e_ms) last_delta = new_b_delta new_line = "%s --> %s" % (format_delta(new_b_delta), format_delta(new_e_delta)) else: output = self.ui.textEditSplitOut2 new_b_delta = get_delta(b_h, b_m, b_s, b_ms) - last_delta new_e_delta = get_delta(e_h, e_m, e_s, e_ms) - last_delta new_line = "%s --> %s" % (format_delta(new_b_delta), format_delta(new_e_delta)) output.appendPlainText( new_line.replace("\r\n", "\n").replace("\n", "")) output1 = self.ui.textEditSplitOut1.toPlainText() output2 = self.ui.textEditSplitOut2.toPlainText() # Récupération de la dernière ligne (correspondant au numéro) # pour la rajouter en début de 2è fichier cur1 = self.ui.textEditSplitOut1.cursorForPosition(QPoint(0, 0)) cur2 = self.ui.textEditSplitOut2.cursorForPosition(QPoint(0, 0)) cur1.movePosition(QTextCursor.End) cur2.movePosition(QTextCursor.Start) cur1.select(QTextCursor.LineUnderCursor) last1 = cur1.selectedText() + "\n" cur1.removeSelectedText() cur2.insertText(last1) vScrollBar2 = self.ui.textEditSplitOut2.verticalScrollBar() vScrollBar2.setSliderPosition(0) @pyqtSlot(str) def on_lineEditPathConcatIn1_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditConcatIn1.appendPlainText( l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathConcatIn2_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditConcatIn2.appendPlainText( l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathConcatOut_textChanged(self, path): self.filepathConcatOut = path @pyqtSlot(str) def on_lineEditPathSplitIn_textChanged(self, path): fd = open(path) for l in fd.readlines(): self.ui.textEditSplitIn.appendPlainText( l.replace("\r\n", "").replace("\n", "")) fd.close() @pyqtSlot(str) def on_lineEditPathSplitOut1_textChanged(self, path): self.filepathSplitOut1 = path @pyqtSlot(str) def on_lineEditPathSplitOut2_textChanged(self, path): self.filepathSplitOut2 = path @pyqtSlot() def on_pushButtonBrowseShiftIn_clicked(self): self.filepathShiftIn = self.browse(self.ui.lineEditPathShiftIn) @pyqtSlot() def on_pushButtonBrowseConcatIn1_clicked(self): self.filepathConcatIn1 = self.browse(self.ui.lineEditPathConcatIn1) @pyqtSlot() def on_pushButtonBrowseConcatIn2_clicked(self): self.filepathConcatIn2 = self.browse(self.ui.lineEditPathConcatIn2) @pyqtSlot() def on_pushButtonBrowseConcatOut_clicked(self): self.filepathConcatOut = self.browse(self.ui.lineEditPathConcatOut) @pyqtSlot() def on_pushButtonBrowseSplitIn_clicked(self): self.filepathSplitIn = self.browse(self.ui.lineEditPathSplitIn) @pyqtSlot() def on_pushButtonBrowseSplitOut1_clicked(self): self.filepathSplitOut1 = self.browse(self.ui.lineEditPathSplitOut1) @pyqtSlot() def on_pushButtonBrowseSplitOut2_clicked(self): self.filepathSplitOut2 = self.browse(self.ui.lineEditPathSplitOut2) @pyqtSlot() def on_pushButtonLaunch_clicked(self): if self.current_action == ACTION_SHIFT: self.launch_shift() elif self.current_action == ACTION_CONCAT: self.launch_concat() elif self.current_action == ACTION_SPLIT: self.launch_split() else: print "Pas d'action correspondante pour %s" % self.current_action @pyqtSlot(int) def on_tabs_currentChanged(self, num): self.current_action = num @pyqtSlot() def on_pushButtonCopy_clicked(self): if self.current_action == ACTION_SHIFT: self.app.clipboard().clear() self.ui.textEditShiftOut.selectAll() self.app.clipboard().setText( self.ui.textEditShiftOut.toPlainText()) elif self.current_action == ACTION_CONCAT: self.app.clipboard().clear() self.ui.textEditConcatOut.selectAll() self.app.clipboard().setText( self.ui.textEditConcatOut.toPlainText()) elif self.current_action == ACTION_SPLIT: self.app.clipboard().clear() self.ui.textEditSplitOut1.selectAll() self.ui.textEditSplitOut2.selectAll() self.app.clipboard().setText( self.ui.textEditSplitOut1.toPlainText() + self.ui.textEditSplitOut2.toPlainText()) else: print "Pas d'action correspondante pour %s" % self.current_action @pyqtSlot() def on_pushButtonOverwrite_clicked(self): try: if self.current_action == ACTION_SHIFT: if not self.filepathShiftIn: return os.rename(self.filepathShiftIn, self.filepathShiftIn + '.org') fd = open(self.filepathShiftIn, 'w') fd.write(self.ui.textEditShiftOut.toPlainText()) fd.close() self.ui.statusbar.showMessage( u"Le fichier a bien été écrasé. Une sauvegarde a été effectuée" ) elif self.current_action == ACTION_CONCAT: if not self.filepathConcatOut: return fd = open(self.filepathConcatOut, 'w') fd.write(self.ui.textEditConcatOut.toPlainText()) fd.close() self.ui.statusbar.showMessage(u"Le fichier a bien été écrit.") elif self.current_action == ACTION_SPLIT: if not self.filepathSplitOut1 or not self.filepathSplitOut2: return fd = open(self.filepathSplitOut1, 'w') fd.write(self.ui.textEditSplitOut1.toPlainText()) fd.close() fd = open(self.filepathSplitOut2, 'w') fd.write(self.ui.textEditSplitOut2.toPlainText()) fd.close() self.ui.statusbar.showMessage( u"Les fichiers ont bien été écrit.") else: print "Pas d'action correspondante pour %s" % self.current_action except Exception, e: print e self.ui.statusbar.showMessage( u"Le fichier n'a pas été bien généré. Voir la sortie d'erreur")
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.itemBasePrice.setValidator(QtGui.QDoubleValidator()) self.ui.modifierEdit.setValidator(QtGui.QDoubleValidator()) # items self.ui.newItem.clicked.connect(self.newItemClicked) self.ui.deleteItem.clicked.connect(self.deleteItemClicked) self.ui.itemNameEdit.editingFinished.connect(self.saveItem) self.ui.itemBasePrice.editingFinished.connect(self.saveItem) self.ui.itemGroupSelect.itemClicked.connect(self.saveItem) self.ui.itemEditView.currentItemChanged.connect(self.itemEditViewSelectionChanged) self.ui.tabWidget.currentChanged.connect(self.refreshGroupsForItems) # groups self.ui.groupNameEdit.editingFinished.connect(self.saveGroup) self.ui.deleteGroup.clicked.connect(self.deleteGroupClicked) self.ui.newGroup.clicked.connect(self.newGroupClicked) self.ui.groupEditView.currentItemChanged.connect(self.groupEditViewSelectionChanged) # locations self.ui.newLocation.clicked.connect(self.newLocation) self.ui.deleteLocation.clicked.connect(self.deleteLocation) self.ui.locationNameEdit.editingFinished.connect(self.saveLocation) self.ui.locationSelection.currentItemChanged.connect(self.locationViewSelectionChanged) self.ui.tabWidget.currentChanged.connect(self.refreshModifiersForLocations) # modifiers self.ui.locationModifierSelection.currentItemChanged.connect(self.refreshModifiers) self.ui.locationSelection.currentItemChanged.connect(self.refreshModifiers) self.ui.saveModifier.clicked.connect(self.saveModifier) self.ui.modifierEdit.editingFinished.connect(self.saveModifier) self.ui.modifierTypeSelect.currentIndexChanged.connect(self.refreshModifiersForLocations) # Final view self.ui.tabWidget.currentChanged.connect(self.refreshFinalLocationsView) self.ui.locationsFinalView.currentItemChanged.connect(self.refreshFinalItemsView) self.ui.finalItemsView.setColumnCount(2) # menubar self.ui.actionNew.triggered.connect(self.newFile) self.ui.actionOpen.triggered.connect(self.openFile) self.ui.actionSave.triggered.connect(self.saveFile) # vars self.items = [] self.groups = [] self.locations = [] # Items creation def newItemClicked(self): newItem = Item("NewItem") self.items.append(newItem) self.ui.itemEditView.addItem(newItem.name) def deleteItemClicked(self): self.items.pop(self.ui.itemEditView.currentRow()) self.ui.itemEditView.takeItem(self.ui.itemEditView.currentRow()) def saveItem(self): item = self.items[self.ui.itemEditView.currentRow()] if item is None: return item.name = self.ui.itemNameEdit.text() price = self.ui.itemBasePrice.text().replace(',', '.') price = price + "0" item.basePrice = float(price) currentItem = self.ui.itemEditView.currentItem() if self.ui.itemEditView.currentItem() is not None: currentItem.setText(self.ui.itemNameEdit.text()) # groups item.groups.clear() for i in range(0, self.ui.itemGroupSelect.count()): if self.ui.itemGroupSelect.item(i).checkState() == Qt.Qt.Checked: item.groups.append(self.ui.itemGroupSelect.item(i).text()) def itemEditViewSelectionChanged(self): item = self.items[self.ui.itemEditView.currentRow()] self.ui.itemNameEdit.setText(item.name) self.ui.itemBasePrice.setText(str(item.basePrice)) # groups for i in range(0, self.ui.itemGroupSelect.count()): group = self.ui.itemGroupSelect.item(i) if group.text() in item.groups: group.setCheckState(Qt.Qt.Checked) else: group.setCheckState(Qt.Qt.Unchecked) def refreshGroupsForItems(self): while self.ui.itemGroupSelect.count() > 0: self.ui.itemGroupSelect.takeItem(0) for group in self.groups: self.ui.itemGroupSelect.addItem(group) for i in range(0, self.ui.itemGroupSelect.count()): item = self.ui.itemGroupSelect.item(i) item.setFlags(item.flags() | Qt.Qt.ItemIsUserCheckable) item.setCheckState(Qt.Qt.Unchecked) # Groups management def newGroupClicked(self): self.groups.append("New Group") self.ui.groupEditView.addItem("New Group") def deleteGroupClicked(self): self.groups.remove(self.ui.groupEditView.currentItem().text()) self.ui.groupEditView.takeItem(self.ui.groupEditView.currentRow()) def saveGroup(self): if self.ui.groupEditView.currentItem() is None: return self.ui.groupEditView.currentItem().setText(self.ui.groupNameEdit.text()) self.groups[self.ui.groupEditView.currentRow()] = self.ui.groupNameEdit.text() def groupEditViewSelectionChanged(self, current: QtWidgets.QListWidgetItem): self.ui.groupNameEdit.setText(current.text()) # locations def newLocation(self): location = Location("New Location") self.locations.append(location) self.ui.locationSelection.addItem(location) self.ui.locationSelection.setCurrentItem(location) def deleteLocation(self): self.locations.remove(self.ui.locationSelection.currentItem()) self.ui.locationSelection.takeItem(self.ui.locationSelection.currentRow()) def saveLocation(self): location = self.ui.locationSelection.currentItem() if location is None: return location.setText(self.ui.locationNameEdit.text()) def locationViewSelectionChanged(self, current: QtWidgets.QListWidgetItem): self.ui.locationNameEdit.setText(self.ui.locationSelection.currentItem().text()) def refreshModifiersForLocations(self): while self.ui.locationModifierSelection.count() > 0: self.ui.locationModifierSelection.takeItem(0) if self.ui.modifierTypeSelect.currentIndex() == 0: for group in self.groups: self.ui.locationModifierSelection.addItem(group) # highlight Groups as gray # self.ui.locationModifierSelection.item(self.ui.locationModifierSelection.count()-1).setBackground(QtGui.QBrush(QtGui.QColor(200, 200, 200))) else: for item in self.items: self.ui.locationModifierSelection.addItem(item.name) # modifiers def refreshModifiers(self): if self.ui.locationSelection.currentRow() == -1 or self.ui.locationModifierSelection.currentRow() == -1: return location = self.locations[self.ui.locationSelection.currentRow()] modifier = location.getModifier(self.ui.locationModifierSelection.currentItem().text()) if modifier is not None: self.ui.modifierEdit.setText(str(modifier.modifier)) else: self.ui.modifierEdit.setText("1.0") modifier = Modifier() if self.ui.modifierTypeSelect.currentIndex() == 0: modifier.identifier = self.groups[self.ui.locationModifierSelection.currentRow()] else: modifier.identifier = self.items[self.ui.locationModifierSelection.currentRow()] location.modifiers.append(modifier) def saveModifier(self): if self.ui.locationSelection.currentRow() == -1 or self.ui.locationModifierSelection.currentRow() == -1: return location = self.locations[self.ui.locationSelection.currentRow()] modifier = location.getModifier(self.ui.locationModifierSelection.currentItem().text()) modifier.modifier = float(self.ui.modifierEdit.text().replace(",", ".")) # Final view def refreshFinalLocationsView(self): while self.ui.locationsFinalView.count() > 0: self.ui.locationsFinalView.takeItem(0) for location in self.locations: self.ui.locationsFinalView.addItem(location.text()) def refreshFinalItemsView(self): self.ui.finalItemsView.clear() self.ui.finalItemsView.setRowCount(self.items.__len__()) if self.locations.__len__() == 0: return for i in range(0, self.items.__len__()): self.ui.finalItemsView.setItem(i, 0, QtWidgets.QTableWidgetItem(self.items[i].name)) location = self.locations[self.ui.locationsFinalView.currentRow()] for i in range(0, self.items.__len__()): baseModifier = location.getModifier(self.items[i].name) if baseModifier is None: itemModifier = 1.0 else: itemModifier = baseModifier.modifier for group in self.items[i].groups: mod = location.getModifier(group) if mod is not None: itemModifier *= mod.modifier finalPrice = self.items[i].basePrice * itemModifier self.ui.finalItemsView.setItem(i, 1, QtWidgets.QTableWidgetItem(str(finalPrice))) # general def refreshEverything(self): self.refreshModifiers() self.refreshFinalItemsView() self.refreshGroupsForItems() self.refreshFinalLocationsView() self.refreshModifiersForLocations() # menubar def newFile(self): self.items.clear() self.groups.clear() self.locations.clear() self.refreshEverything() def openFile(self): self.newFile() fileName = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', filter="Json files (*.json)") if fileName.__len__() == 0: return f = open(fileName[0], "r") file = f.read() f.close() itemArray = json.loads(file) # load items for item in itemArray[0]: newItem = Item(item["name"]) newItem.basePrice = item["basePrice"] newItem.groups = item["groups"] self.items.append(newItem) self.ui.itemEditView.addItem(newItem.name) # load groups for group in itemArray[1]: self.groups.append(group) self.ui.groupEditView.addItem(group) # load locations for location in itemArray[2]: loc = Location(location["name"]) loc.loadModifiers(location["modifiers"], self.items, self.groups) self.locations.append(loc) self.ui.locationSelection.addItem(loc) self.refreshEverything() def saveFile(self): file = "[" comma = False file += "[" for item in self.items: if comma: file += " ," file += json.dumps(item.__dict__) comma = True file += "]," file += json.dumps(self.groups) + ", " comma = False file += "[" for location in self.locations: if comma: file += " ," file += json.dumps(LocationContainer(location.name, location.getModifiersJson(self.items)).__dict__) comma = True file += "]" file += "]" dialog = QtWidgets.QFileDialog() dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) dialog.setWindowTitle("Save file") dialog.setNameFilter("Json files (*.json)") dialog.setDefaultSuffix("json") dialog.exec() if dialog.selectedFiles().__len__() > 0: f = open(dialog.selectedFiles()[0], "w") f.write(file) f.close()
class MainWindow(): def __init__(self): self.lineEdit = QMainWindow() self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.main_win) self.ui.Enter_Button.clicked.connect(self.showpage1) self.ui.pushButton.clicked.connect(self.showpage0) self.ui.Exit_Button.clicked.connect(self.Exit) self.ui.Exit2_butt.clicked.connect(self.Exit) self.ui.Load_Data.clicked.connect(self.getCSV) self.ui.Display_Graph_1.clicked.connect(self.Display_1) self.ui.calendarWidget.clicked[QDate].connect(self.show_Probabilty) self.ui.checkBox_1.stateChanged.connect(self.Uncheck23) self.ui.checkBox_2.stateChanged.connect(self.Uncheck13) self.ui.checkBox_3.stateChanged.connect(self.Uncheck12) # filepath = "python DataFile_db.py" # self.ui.Load_Data.clicked.connect(lambda checked, arg=filepath: self.execute(arg)) def show(self): self.main_win.show() def loadTemperatureData(self): data = pd.read_csv('Overview200.csv') df = data.drop_duplicates(subset=['DeviceTimeStamp']) df2 = df.loc[df['OTI'] >= 200] # removed all non failure data points return df2 def calcInterval(self, df2): # calculate interval between failure data points found = [] i = 0 for index, row in df2.iterrows(): if i > 0: diff = datetime.datetime.strptime( df2.iloc[i].DeviceTimeStamp, '%Y-%m-%dT%H:%M') - datetime.datetime.strptime( df2.iloc[i - 1].DeviceTimeStamp, '%Y-%m-%dT%H:%M') # less than 1 sec apart = redundant rows if diff > datetime.timedelta(seconds=1): found.append([i, diff, index, row.DeviceTimeStamp]) i += 1 # only count failures that happened > 1 day apart. multiple failures count as 1 incident time_list = [] for a in found: if (a[1] > datetime.timedelta(days=1)): # print(a) time_list.append(a[1]) interval = pd.Series(time_list).median().days return interval def poisson_probs(self, interval): pred_yst = 0 prob_list = [] for i in range(30): pred_today = 1 - pow(math.e, -1 / interval * i) prob_list.append(pred_today - pred_yst) pred_yst = pred_today return prob_list def show_Probabilty(self, date): df2 = self.loadTemperatureData() interval = self.calcInterval(df2) pred_probs = self.poisson_probs(interval) # assuming transformer failure just happened today :O td = QDate.currentDate() date_list = [] # dont count day 0 for i in range(0, len(pred_probs)): d = td.addDays(i) date_list.append(d) # index defaults to -1 if date is not in date_list try: dayIndex = date_list.index(date) # get index of the date except: dayIndex = -1 # dont show day 0 prob because its calculated at 0% lol if dayIndex > 0: # date clicked has a probability to display self.ui.label_3.setText(date.toString() + ' - ' + str(round(pred_probs[dayIndex] * 100, 2)) + '%') else: # date does not have a probability self.ui.label_3.setText(date.toString()) def showpage0(self): self.ui.stackedWidget.setCurrentIndex(0) def showpage1(self): self.ui.stackedWidget.setCurrentIndex(1) def Exit(self): exit() def Uncheck23(self): if self.ui.checkBox_1.isChecked(): if self.ui.checkBox_2.isChecked(): self.ui.checkBox_2.setChecked(False) if self.ui.checkBox_3.isChecked(): self.ui.checkBox_3.setChecked(False) def Uncheck13(self): if self.ui.checkBox_2.isChecked(): if self.ui.checkBox_1.isChecked(): self.ui.checkBox_1.setChecked(False) if self.ui.checkBox_3.isChecked(): self.ui.checkBox_3.setChecked(False) def Uncheck12(self): if self.ui.checkBox_3.isChecked(): if self.ui.checkBox_1.isChecked(): self.ui.checkBox_1.setChecked(False) if self.ui.checkBox_2.isChecked(): self.ui.checkBox_2.setChecked(False) def Display_1(self): data = pd.read_csv('mvlv-transformer.csv', usecols=[ 'active_power', 'current', 'voltage', 'active_power', 'reactive_power', 'apparent_power' ]) f, axes = plt.subplots(1, 1, figsize=(8, 4)) if self.ui.checkBox_1.isChecked(): axes.set_xlabel("Sample Size") axes.set_ylabel("Voltage (V)") data.head(10000).plot(y=['voltage'], ax=axes) plt.show() elif self.ui.checkBox_2.isChecked(): axes.set_xlabel("Sample Size") axes.set_ylabel("Current (A)") data.head(10000).plot(y=['current'], ax=axes) plt.show() elif self.ui.checkBox_3.isChecked(): axes.set_xlabel("Sample Size") axes.set_ylabel("Power (W)") data.head(10000).plot(y=['active_power'], ax=axes) plt.show() def getCSV(self): root = tk.Tk() root.title('PandasTable') frame = tk.Frame(root) frame.pack(fill='both', expand=True) pt = Table(frame) pt.show() import_file_path = filedialog.askopenfilename() pt.importCSV(filename=import_file_path, dialog=True) root.mainloop()
class MainWindowUi(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindowUi, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) pass
class ArduloaderWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.portManager = PortManager(self.ui, startmonitor=True) self.configHelper = ConfigHelper(self.ui) self.initSignal() self.setupUi_Ex() def setupUi_Ex(self): self.setWindowTitle(const.windowtitle) self.ui.textEdit.append(const.aboutinfo) self.ui.headLabel.setPixmap( QPixmap(":/main/icons/main/arduloader.png")) self.setWindowIcon(QtGui.QIcon(":/main/icons/main/logo.png")) self.setBoards() self.configHelper.updateUiByConfig() def setBoards(self): ret, self.__boardsinfodict = BoardHelper.getBoardsInfo() if not ret: self.__boardsinfodict = {} return for boardname in self.__boardsinfodict.keys(): self.ui.mcuCombox.addItem(boardname) def onUploadFinish(self, ret, text): self.timer.stop() try: res = ret == 0 and "Upload SUCCESS:)" or ("%s\nUpload FAILED:(" % text) except IOError: res = "Read tmp file error" except: res = "Unknown error" self.ui.textEdit.append(res) def onUploading(self): prev_cursor = self.ui.textEdit.textCursor() self.ui.textEdit.moveCursor(QtGui.QTextCursor.End) self.ui.textEdit.insertPlainText(".") self.ui.textEdit.setTextCursor(prev_cursor) def getUploadArgs(self): infodict = self.__boardsinfodict.get( tostr(self.ui.mcuCombox.currentText())) if not infodict: return mcu = infodict["mcu"] speed = infodict["speed"] protocol = infodict["protocol"] maximum_size = infodict["maximum_size"] comport = tostr(self.ui.portCombox.currentText()) flash_bin = togbk(self.ui.hexfileCombox.currentText()) return { "mcu": mcu, "speed": speed, "protocol": protocol, "maximum_size": maximum_size, "comport": comport, "flash_bin": flash_bin } def checkUploadArgs(self, argsdict): if not argsdict: self.ui.textEdit.append("Get chip data error") return False if not OSPath.exists(argsdict.get("flash_bin", "")): self.ui.textEdit.append("Hex file not exists") return False # TODO: 检查文件大小是否超多当前芯片允许的最大值 return True def startUpload(self): argsdict = self.getUploadArgs() if not self.checkUploadArgs(argsdict): return self.uploader = Uploader() self.connect(self.uploader.qobj, QtCore.SIGNAL(const.finish_sig), self.onUploadFinish) self.uploader.resetUploadArgs(argsdict) self.ui.textEdit.clear() self.ui.textEdit.append("Start uploading\n") self.timer = QtCore.QTimer() self.timer.timeout.connect(self.onUploading) self.uploader.start() self.timer.start(const.process_interval) def onOpenHexFile(self): filename = QtGui.QFileDialog.getOpenFileName(self, "Choose a HEX file", ".", "HEX (*.hex)") if filename == "": return index = self.ui.hexfileCombox.findText(filename) if index < 0: self.ui.hexfileCombox.insertItem(0, filename) index = 0 self.ui.hexfileCombox.setCurrentIndex(index) def closeEvent(self, e): hex = tostr(self.ui.hexfileCombox.currentText()) com = tostr(self.ui.portCombox.currentText()) board = tostr(self.ui.mcuCombox.currentText()) self.configHelper.updateConfig(hex, com, board) e.accept() def initSignal(self): self.ui.exitButton.clicked.connect(self.close) self.ui.uploadButton.clicked.connect(self.startUpload) self.ui.openHexButton.clicked.connect(self.onOpenHexFile)
class GmailWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.cookieJar = PersistenceCookieJar(QSettings("POWERUMC", "GmailTray")) self.onLoad(); def onLoad(self): self.menuBar().hide() self.menuBar().close() self.resize(500, 600) # SSL 구 sslcfg = QSslConfiguration.defaultConfiguration() ca_list = sslcfg.caCertificates() ca_new = QSslCertificate.fromData('CaCertificates') ca_list += ca_new sslcfg.setCaCertificates(ca_list) sslcfg.setProtocol(QSsl.AnyProtocol) QSslConfiguration.setDefaultConfiguration(sslcfg) # WebView 구성 QNetworkProxyFactory.setUseSystemConfiguration(True) set = self.ui.webView.settings().globalSettings() set.setAttribute(QWebSettings.PluginsEnabled, True) set.setAttribute(QWebSettings.AutoLoadImages, True) set.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True) set.setAttribute(QWebSettings.JavascriptEnabled, True) set.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) set.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) # 툴바 구성 toolbar = QToolBar('Command Toolbar', self) toolbar.addActions(self.ui.menuCommand.actions()) toolbar.addSeparator() toolbar.addActions(self.ui.menuCommand.actions()) self.addToolBar(toolbar) self.ui.actionGo_Home.triggered.connect(lambda: ()) self.ui.actionRefresh.triggered.connect(lambda: ()) self.ui.actionNext.triggered.connect(lambda: ()) self.ui.actionPrevious.triggered.connect(lambda: ()) self.ui.actionHelp.triggered.connect(lambda: ()) self.ui.actionPreferences.triggered.connect(lambda: ()) self.ui.actionHelp.setEnabled(False) self.ui.actionPreferences.setEnabled(False) # 트레이 아이콘 설 traymenu = QMenu('TRAY MENU', self) if sys.platform == 'darwin': action_open = QAction('O&pen', self) action_open.triggered.connect(lambda: ()) traymenu.addAction(action_open) traymenu.addSeparator() action_quit = QAction('Q&uit', self) action_quit.triggered.connect(lambda : ()) traymenu.addAction(action_quit) tray = HostSystemCounterTrayIcon(QImage('facebook.jpg')) tray.setContextMenu(traymenu) tray.setIcon(QIcon('facebook.jpg')) tray.show() tray.activated.connect(lambda reason:()) tray.messageClicked.connect(lambda: ()) # SSL 설정 manager = SslNetworkAccessManager(self) manager.setCookieJar(self.cookieJar)
class GmailWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.cookieJar = PersistenceCookieJar( QSettings("POWERUMC", "GmailTray")) self.onLoad() def onLoad(self): self.menuBar().hide() self.menuBar().close() self.resize(500, 600) # SSL 구 sslcfg = QSslConfiguration.defaultConfiguration() ca_list = sslcfg.caCertificates() ca_new = QSslCertificate.fromData('CaCertificates') ca_list += ca_new sslcfg.setCaCertificates(ca_list) sslcfg.setProtocol(QSsl.AnyProtocol) QSslConfiguration.setDefaultConfiguration(sslcfg) # WebView 구성 QNetworkProxyFactory.setUseSystemConfiguration(True) set = self.ui.webView.settings().globalSettings() set.setAttribute(QWebSettings.PluginsEnabled, True) set.setAttribute(QWebSettings.AutoLoadImages, True) set.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True) set.setAttribute(QWebSettings.JavascriptEnabled, True) set.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) set.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) # 툴바 구성 toolbar = QToolBar('Command Toolbar', self) toolbar.addActions(self.ui.menuCommand.actions()) toolbar.addSeparator() toolbar.addActions(self.ui.menuCommand.actions()) self.addToolBar(toolbar) self.ui.actionGo_Home.triggered.connect(lambda: ()) self.ui.actionRefresh.triggered.connect(lambda: ()) self.ui.actionNext.triggered.connect(lambda: ()) self.ui.actionPrevious.triggered.connect(lambda: ()) self.ui.actionHelp.triggered.connect(lambda: ()) self.ui.actionPreferences.triggered.connect(lambda: ()) self.ui.actionHelp.setEnabled(False) self.ui.actionPreferences.setEnabled(False) # 트레이 아이콘 설 traymenu = QMenu('TRAY MENU', self) if sys.platform == 'darwin': action_open = QAction('O&pen', self) action_open.triggered.connect(lambda: ()) traymenu.addAction(action_open) traymenu.addSeparator() action_quit = QAction('Q&uit', self) action_quit.triggered.connect(lambda: ()) traymenu.addAction(action_quit) tray = HostSystemCounterTrayIcon(QImage('facebook.jpg')) tray.setContextMenu(traymenu) tray.setIcon(QIcon('facebook.jpg')) tray.show() tray.activated.connect(lambda reason: ()) tray.messageClicked.connect(lambda: ()) # SSL 설정 manager = SslNetworkAccessManager(self) manager.setCookieJar(self.cookieJar)
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setCentralWidget(self.ui.mangaTableView) self.newMangaDialog = NewMangaDialog() self.mangaDownloadDialog = MangaDownloadDialog() self.mangaTableModel = QStandardItemModel(0, 3, self) self.mangaTableModel.setHorizontalHeaderItem(0, QStandardItem(QString("Manga"))) self.mangaTableModel.setHorizontalHeaderItem(1, QStandardItem(QString("Latest Chapter"))) self.mangaTableModel.setHorizontalHeaderItem(2, QStandardItem(QString("Status"))) self.ui.mangaTableView.setModel(self.mangaTableModel) newMangaAction = QAction(QIcon("./icon/add.ico"),'New Manga', self) newMangaAction.setShortcut('Ctrl+N') newMangaAction.triggered.connect(self.newMangaDialog.show) removeMangaAction = QAction(QIcon("./icon/delete.ico"),'Remove Manga', self) removeMangaAction.setShortcut('Delete') preferencesAction = QAction(QIcon("./icon/preferences.ico"),'Preferences', self) aboutAction = QAction(QIcon("./icon/about.ico"),'About', self) self.ui.toolBar.addAction(newMangaAction) self.ui.toolBar.addAction(removeMangaAction) self.ui.toolBar.addSeparator() self.ui.toolBar.addAction(preferencesAction) self.ui.toolBar.addSeparator() self.ui.toolBar.addAction(aboutAction) self.progressBar = QProgressBar(self.ui.statusbar) self.ui.statusbar.addPermanentWidget(self.progressBar) self.progressBar.hide() def closeEvent(self, QCloseEvent): mangaList = [] for i in range(self.mangaTableModel.rowCount()): mangaList.append({ "name" : str(self.mangaTableModel.item(i, 0).text()), "latestChapter" : str(self.mangaTableModel.item(i, 1).text()), "status" : "Updated", "link" : "/trial.html" }) self.emit(SIGNAL("applicationClosed"),mangaList) def initializeProgressBar(self, size): self.progressBar.setRange(0, size) self.progressBar.setValue(0) self.progressBar.show() def updateProgressBar(self, value): self.progressBar.setValue(value) def updateStatusBar(self, msg): self.ui.statusbar.showMessage(msg) def updateMangaTable(self, chapter): isFound = False for i in range(self.mangaTableModel.rowCount()): mangaItem = self.mangaTableModel.item(i) if mangaItem.text() == chapter["name"]: self.mangaTableModel.item(i, 1).setText(chapter["latestChapter"]) self.mangaTableModel.item(i, 2).setText(chapter["status"]) isFound = True break if not isFound: self.addRowToMangaTable(chapter) def addMangaListToMangaTable(self, mangaList): for i in range(len(mangaList)): self.addRowToMangaTable(mangaList[i]) def addRowToMangaTable(self, manga): i = self.mangaTableModel.rowCount() mangaItem = QStandardItem(QString(manga["name"])) latestChapterItem = QStandardItem(QString(manga["latestChapter"])) statusItem = QStandardItem(QString(manga["status"])) brush = QBrush(QColor(255, 255, 255)) if i%2==0 else QBrush(QColor(200, 200, 200)) mangaItem.setBackground(brush) latestChapterItem.setBackground(brush) statusItem.setBackground(brush) self.mangaTableModel.setItem(i, 0, mangaItem) self.mangaTableModel.setItem(i, 1, latestChapterItem) self.mangaTableModel.setItem(i, 2, statusItem)
class MainWindow(QMainWindow): def __init__(self,path=''): super(MainWindow, self).__init__() self.ui=Ui_MainWindow() self.ui.setupUi(self) self.refreshTimer=None self.frameSkippingCounter=0 self.ui.graphicsView.setOptimizationFlags( QGraphicsView.DontAdjustForAntialiasing | QGraphicsView.DontClipPainter | QGraphicsView.DontSavePainterState) #self.ui.graphics.setResizeAnchor(self.ui.graphics.NoAnchor) #self.on_tab_currentChanged(self.ui.tab.currentIndex()) #self.showMaximized() self.simulationFramerate=10 # mouse event handlers for painting on simulation map: self.lastMousePosOnMap = None self.drawOnMap = anthill.Painter.drawObstacles # current painting function self.drawingStuff = False # flag for moving the camera around self.draggingCamera = False self.lastMousePosGlobal = None def handleMousePress(event): if event.button() == QtCore.Qt.LeftButton: self.drawingStuff = True self.lastMousePosOnMap = None self.handlePainterOption() self.ui.graphicsView.setMouseTracking(True) elif event.button() == QtCore.Qt.RightButton: self.draggingCamera = True self.lastMousePosGlobal = None self.ui.graphicsView.setDragMode( self.ui.graphicsView.ScrollHandDrag) self.ui.graphicsView.setMouseTracking(True) def handleMouseRelease(event): self.lastMousePosOnMap = None self.drawingStuff = False self.lastMousePosGlobal = None self.draggingCamera = False self.ui.graphicsView.setMouseTracking(False) self.ui.graphicsView.setDragMode(self.ui.graphicsView.NoDrag) def handleMouseMove(event): if self.drawingStuff: mouse_in_map_coords = ( self.ui.graphicsView.mapToScene( self.ui.graphicsView.mapFromGlobal(QCursor.pos()))) coords = list( map(lambda p: int(p), [mouse_in_map_coords.x(), mouse_in_map_coords.y()])) coords[1] -= 1 # fix misalignment if self.lastMousePosOnMap is None: self.lastMousePosOnMap = coords self.drawOnMap(self.world, self.lastMousePosOnMap[0], self.lastMousePosOnMap[1], coords[0], coords[1], self.ui.painterRadius.value(), self.ui.painterIntensity.value() * 0.01 *\ anthill.WorldGenerator.default_pheromone_params.scale) self.lastMousePosOnMap = coords if self.draggingCamera: if self.lastMousePosGlobal is None: self.lastMousePosGlobal = QCursor.pos() delta = QCursor.pos() - self.lastMousePosGlobal self.ui.graphicsView.setTransformationAnchor( self.ui.graphicsView.NoAnchor) self.ui.graphicsView.translate(delta.x(), delta.y()) self.lastMousePosGlobal = QCursor.pos() self.ui.graphicsView.mousePressEvent = handleMousePress self.ui.graphicsView.mouseReleaseEvent = handleMouseRelease self.ui.graphicsView.mouseMoveEvent = handleMouseMove def handleWheelEvent(event): self.ui.graphicsView.setTransformationAnchor( self.ui.graphicsView.AnchorViewCenter) scaleFactor = 1.15 if event.angleDelta().y() < 0: scaleFactor = 1.0 / scaleFactor self.ui.graphicsView.scale(scaleFactor, scaleFactor) self.ui.graphicsView.wheelEvent = handleWheelEvent # configure world self.world = anthill.World(); self.paused = True self.statistics = Statistics(self.ui.stats_label, self.ui.gridLayout_3) def __exit__(self): self.refreshTimer.stop() def drawPheromoneMap(self,map, baseRGB=(50,30,100), baseRGB2=(10,10,10) ): data=map.getMap() data=list(data) scene=self.ui.graphicsView.scene() for x,a in enumerate(data): if(x > self.world.getDimensions().posX()): break for y,b in enumerate(a): if(y > self.world.getDimensions().posY()): break if(b<0.1): # too weak to be sensed continue alpha=30+b*8 if(alpha>100): # clamp alpha=100 pbrush=QBrush(QColor(baseRGB[0],baseRGB[1],baseRGB[2], alpha)) ppen=QPen(QBrush(QColor(baseRGB2[0],baseRGB2[1],baseRGB2[2], alpha)),0) scene.addRect(x,y,1,1,pen=ppen,brush=pbrush) def drawEntities(self,ents,qpen,qbrush,ellipse=False,drawRange=None): ents=[ents[a] for a in range(len(ents))] scene=self.ui.graphicsView.scene() for ent in ents: x=ent.getPos().posX() y=ent.getPos().posY() if(ellipse): scene.addEllipse(x,y,1,1,pen=qpen,brush=qbrush) else: scene.addRect(x,y,1,1,pen=qpen,brush=qbrush) if(drawRange!=None): rangepen=QPen(QBrush(QColor(0,0,0,30)),0) rangeBrush=QBrush(QColor(255,255,255,10)) scene.addEllipse((x-drawRange), (y-drawRange), drawRange*2,drawRange*2, brush=rangeBrush, pen=rangepen) def handlePainterOption(self): # we're checking against button text which is bad but it's the easiest # way I think... if self.ui.painterButtonGroup.checkedButton().text() == \ "Foods": self.drawOnMap = anthill.Painter.drawFoods elif self.ui.painterButtonGroup.checkedButton().text() == \ "Obstacles": self.drawOnMap = anthill.Painter.drawObstacles elif self.ui.painterButtonGroup.checkedButton().text() == \ "Pheromone (to food)": self.drawOnMap = anthill.Painter.drawPheromoneToFood elif self.ui.painterButtonGroup.checkedButton().text() == \ "Pheromone (from food)": self.drawOnMap = anthill.Painter.drawPheromoneFromFood @pyqtSlot() def refresh(self): if self.paused: return w = self.world.getDimensions().posX() h = self.world.getDimensions().posY() self.world.setMultithreaded(self.ui.multithreaded.isChecked()) self.world.simulationStep() # update statistics stats = self.world.getStatistics(); if self.ui.tabWidget.currentWidget().objectName() == "StatsTab": self.world.setStatisticsEnabled(True) self.statistics.refresh(stats) if self.ui.disableGraphics.isChecked(): return self.frameSkippingCounter+=1 if self.frameSkippingCounter > self.ui.frameSkipping.value(): self.frameSkippingCounter=0 if self.ui.graphicsView.scene() is None: self.ui.graphicsView.setScene(QGraphicsScene(0,0,w,h)) scene = self.ui.graphicsView.scene() scene.clear() bgBrush=QBrush(QColor(50,120,50,255)) bgPen=QPen(QBrush(QColor()),0) scene.addRect(0,0,w,h,pen=bgPen,brush=bgBrush) # draw pheromone map pMaps=self.world.getPheromoneMaps() pMaps=[pMaps[p] for p in range(len(pMaps))] pheromoneColors=[ (50,50,155), (255,50,50), (0,255,0)] displayPheromones= [self.ui.displayPheromones1.isChecked(), self.ui.displayPheromones2.isChecked(), self.ui.displayPheromones3.isChecked()] for i,m in enumerate(pMaps): if(displayPheromones[i]): self.drawPheromoneMap(m,baseRGB=(pheromoneColors[i])) # draw obstacles obstacles=self.world.getObstacles() obstaclePen=QPen(QBrush(QColor()),0) obstacleBrush=QBrush(QColor(50,50,50,255)) self.drawEntities(obstacles,obstaclePen,obstacleBrush) # draw foods foods=self.world.getFoods() foodPen=QPen(QBrush(QColor()),0) foodBrush=QBrush(QColor(200,200,200,70)) self.drawEntities(foods,foodPen,foodBrush) # draw creatures creatures=self.world.getCreatures() creaturePen=QPen(QBrush(QColor()),0) creatureBrush=QBrush(QColor(100,100,50,200)) if(self.ui.displayRanges.isChecked()): self.drawEntities(creatures,creaturePen,creatureBrush,True,7) else: self.drawEntities(creatures,creaturePen,creatureBrush,True) # draw anthills anthills=self.world.getAnthills() anthillPen=QPen(QBrush(QColor()),0) anthillBrush=QBrush(QColor(200,20,20,150)) self.drawEntities(anthills,anthillPen,anthillBrush) def restartTimer(self): self.refresh() if self.refreshTimer: self.refreshTimer.stop() self.refreshTimer=QTimer(self) self.refreshTimer.timeout.connect(self.refresh) self.refreshTimer.start(1000/self.simulationFramerate) def on_startSimulationButton_released(self): _translate = QtCore.QCoreApplication.translate if self.paused: if self.refreshTimer is None: self.restartTimer() # ask user for world generation params dialog = WorldGeneratorParamsDialog(self) if not dialog.exec_(): # if user clicked CANCEL return dialog.processResults() self.world.setDimensions(dialog.worldWidth, dialog.worldHeight) try: anthill.WorldGenerator.placeObstacles(self.world, dialog.obstaclesParams) anthill.WorldGenerator.placeFoods(self.world, dialog.foodsParams) anthill.WorldGenerator.placeAnthill(self.world, dialog.anthillParams) anthill.WorldGenerator.placeAnts(self.world, dialog.antsParams) anthill.WorldGenerator.initPheromoneMaps(self.world, dialog.pheromoneParams) except: pass self.statistics.reset() self.world.startSimulation() self.ui.startSimulationButton.setText(_translate( "MainWindow", "Pause Simulation")) self.paused = False else: self.ui.startSimulationButton.setText(_translate( "MainWindow", "Start Simulation")) self.paused = True def on_stopSimulationButton_released(self): if self.refreshTimer: _translate = QtCore.QCoreApplication.translate self.ui.startSimulationButton.setText(_translate( "MainWindow", "Start Simulation")) self.paused = True self.refresh() self.refreshTimer.stop() self.refreshTimer=None self.world.stopSimulation() def on_saveStateButton_released(self): self.paused = True path=QFileDialog.getSaveFileName(self, "Save File", ".", "All Files (*)") path=path[0] if(path and path!=''): print("Saving state to: ",path) self.paused = False self.world.saveState(path) self.restartTimer() self.paused = False def on_loadStateButton_released(self): self.paused = True path=QFileDialog.getOpenFileName(self, "Open File", ".", "All Files (*)") path=path[0] if(path and path!=''): self.world.loadState(path) self.world.startSimulation() self.restartTimer() self.paused = False def on_framerateBox_valueChanged(self): self.simulationFramerate=max(self.ui.framerateBox.value(),1) if(self.refreshTimer): self.refreshTimer.stop() self.refreshTimer.start(1000/self.simulationFramerate) def on_actionExit_triggered(self): self.close() def on_actionAbout_triggered(self): print("Anthill simulator version 0. ")
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self)
class CDL(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.wait = Ui_Wait(self) self.downloadsManager = DownloadsManager(self, self.ui.downloadsList) global config self.videosManager = VideosManager(self.ui.downloadsList, self.ui.categoriesList) QObject.connect(self.downloadsManager, SIGNAL("download_terminated(PyQt_PyObject)"), self.add_video) QObject.connect(self, SIGNAL("refresh(PyQt_PyObject)"), self.downloadsManager.refresh_downloads_list) QObject.connect(self.ui.downloadsList, SIGNAL("download(PyQt_PyObject)"), self.downloadsManager.download) QObject.connect(self, SIGNAL("construct_downloads(PyQt_PyObject)"), self.generate_downloads) QObject.connect(self.downloadsManager, SIGNAL("blacklist(PyQt_PyObject)"), self.blacklist) QObject.connect(self.ui.wait, SIGNAL("open()"), self.ui.wait.open) QObject.connect(self.ui.wait, SIGNAL("close()"), self.ui.wait.close) def showPreferences(self): self.pref = Preferences(self) QObject.connect(self.pref, SIGNAL("configChanged(PyQt_PyObject)"), self.videosManager.refresh_categoriesList) self.pref.show() def blacklist(self, download): config.blacklist.append(download) DAO.commit() def generate_downloads(self, list_data): downloads = [] for d in list_data: download = DAO.download(d['url'], d['category'], d['description'], d['name']) downloads.append(download) self.emit(SIGNAL("refresh(PyQt_PyObject)"), downloads) def add_video(self, download): new_video = Video(download.url, download.category, download.name, download.date, download.description) self.videosManager.add_new_video(new_video) def refresh_downloads_list(self): def threadListNewVideos(self): self.ui.wait.emit(SIGNAL("open()")) list_data = [] for c in config.categories: list_data.extend(c.find_new_videos_availables(config.blacklist)) self.emit(SIGNAL("construct_downloads(PyQt_PyObject)"), list_data) self.ui.wait.emit(SIGNAL("close()")) if self.downloadsManager.nb_downloads_in_progress != 0: r = QMessageBox.critical(self, "Veuillez patienter !", u"Tous les téléchargements ne sont pas terminés, veuillez patienter quelques instants avant de raffraichir cette liste") return config.blacklist config.categories = [DAO.merge(x) for x in config.categories] threading.Thread(target=threadListNewVideos, args=[self]).start() def quit(self): if hasattr(self, 'pref'): self.pref.close() if hasattr(self, 'downloadsManager'): self.downloadsManager.ui_download.close() self.close() def closeEvent(self, closeEvent): self.quit() @pyqtSlot() def on_pushButtonRefresh_clicked(self): self.refresh_downloads_list() @pyqtSlot() def on_pushButtonDownload_clicked(self): self.downloadsManager.download_selected() @pyqtSlot() def on_pushButtonPlay_clicked(self): self.videosManager.play_selected() @pyqtSlot() def on_pushButtonBlacklist_clicked(self): try: self.downloadsManager.blacklist_selected() except Exception, e: print "error while blacklisting video" print traceback.format_exc(e)
class MyMainWindow(qtw.QMainWindow): def __init__(self, *args, **kwds): super().__init__() # QtGui.QMainWindow.__init__(self, *args, **kwds) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.Base_Dir = os.path.dirname(os.path.realpath(__file__)) # wid = loadUi(os.path.join(self.Base_Dir, "Main.ui"), self) self.local_table_model = MediaLibrary.MediaLibrary(self, []) self.remote_table_model = MediaLibrary.MediaLibrary(self, []) self.left_playlist_table = PlaylistTable.PlaylistTable(self, []) self.right_playlist_table = PlaylistTable.PlaylistTable(self, []) self.ui.LocalTableL.setModel(self.local_table_model) self.ui.LocalTableR.setModel(self.local_table_model) self.ui.RemoteTableL.setModel(self.remote_table_model) self.ui.RemoteTableR.setModel(self.remote_table_model) self.ui.LeftPlaylistTable.setModel(self.left_playlist_table) self.ui.RightPlaylistTable.setModel(self.right_playlist_table) self.ui.LocalTableL.setSortingEnabled(True) self.ui.LocalTableR.setSortingEnabled(True) self.ui.RemoteTableL.setSortingEnabled(True) self.ui.RemoteTableR.setSortingEnabled(True) self.ui.RightPlaylistTable.setSortingEnabled(True) self.ui.LeftPlaylistTable.setSortingEnabled(True) self.AlbumList = {} self.sendQueue = queue.Queue() self.Id = 1 self.local_server = None self.local_server_thread = None self.remote_server = None self.remote_server_thread = None self.menu = qtw.QMenu(self) copy_action = qtw.QAction('Copy File', self) copy_action.triggered.connect(self.copy_file) self.menu.addAction(copy_action) add_action = qtw.QAction('Add to Playlist', self) add_action.triggered.connect(self.add_to_playlist) self.menu.addAction(add_action) self.playlistMenu = qtw.QMenu(self) delete_action = qtw.QAction('Remove File', self) delete_action.triggered.connect(self.delete_file) self.menu.addAction(delete_action) self.context_table = None self.present_dest = None PickleHandler.PickleReader(self.Base_Dir, self.local_table_model, self.remote_table_model) # @QtCore.Slot() def local_edit_dirs(self): self.edit_dirs(local=True) # @QtCore.Slot() def remote_edit_dirs(self): self.edit_dirs(local=False) # @QtCore.Slot() def left_save_remote(self): self.save_playlist(self.left_playlist_table, local=False) # @QtCore.Slot() def left_save_local(self): self.save_playlist(self.left_playlist_table, local=True) # @QtCore.Slot() def right_save_remote(self): self.save_playlist(self.right_playlist_table, local=False) # @QtCore.Slot() def right_save_local(self): self.save_playlist(self.right_playlist_table, local=True) def save_playlist(self, playlist_table, local=True): if not local: start_dir = Settings.Remote_Playlist_Dir else: start_dir = '' save_file = str( QtGui.QFileDialog.getSaveFileName(self, "Save Playlist As", start_dir, "MP3 Playlist (*.m3u)")[0]) log = playlist_table.save(save_file, local=local) display_msg = "" if log["none"]: display_msg = "The following files had no match:\n" for x in log["none"]: display_msg += "%s\n" % x if log["close"]: display_msg += "The following files are inexact matches:\n" for x in log["close"]: display_msg += "%s matched with %s\n" % (x[0], x[1]) if display_msg: print(display_msg) # @QtCore.Slot(QtCore.QPoint) def left_local_context(self, QPoint): self.context_table = self.ui.LocalTableL self.present_dest = "Xbmc" self.menu.popup(QtGui.QCursor.pos()) # @QtCore.Slot(QtCore.QPoint) def right_local_context(self, QPoint): self.context_table = self.ui.LocalTableR self.present_dest = "Xbmc" self.menu.popup(QtGui.QCursor.pos()) # @QtCore.Slot(QtCore.QPoint) def left_remote_context(self, QPoint): self.context_table = self.ui.RemoteTableL self.present_dest = "Local" self.menu.popup(QtGui.QCursor.pos()) # @QtCore.Slot(QtCore.QPoint) def right_remote_context(self, QPoint): self.context_table = self.ui.RemoteTableR self.present_dest = "Local" self.menu.popup(QtGui.QCursor.pos()) def copy_file(self): print("Called Copy Action!") rows = self.context_table.selectionModel().selectedRows() if self.present_dest == "Xbmc": table_list = self.local_table_model.my_list target_dir = str( QtGui.QFileDialog.getExistingDirectory( self, "Select Directory", Settings.Remote_Music_Dir)) else: table_list = self.remote_table_model.my_list target_dir = str( QtGui.QFileDialog.getExistingDirectory(self, "Select Directory", '')) if not target_dir: print("Skipping copy") return files = [] for row in rows: source_file = table_list[row.row()]['file'] target_file = os.path.join(target_dir, os.path.basename(source_file)) files.append([source_file, target_file]) print("Starting copy, this could take a sec") for file in files: if os.path.isfile(file[1]): print("File already exists at %s, skipping copy" % file[1]) continue shutil.copy(file[0], file[1]) #print(files) def add_to_playlist(self): print("Add Action Called!") model = self.context_table.selectionModel() rows = model.selectedRows() table_list = self.remote_table_model.my_list # target_dir = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory", '')) files = [] songList = [table_list[row.row()] for row in rows] self.right_playlist_table.insertRows(songList) for row in rows: source_file = table_list[row.row()]['file'] print(source_file) # files.append([source_file, target_file]) print("Files selected %s" % (files)) def edit_dirs(self, local=True): if local: dirs = str( QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")) else: dirs = Settings.Remote_Music_Dir #print("Dirs = %s" % dirs) if local: table = self.local_table_model else: table = self.remote_table_model MyMainWindow.scan_dir_to_table(table, dirs) print("Started") return @staticmethod def scan_dir_to_table(table, my_dir, ignore_files=()): print("Starting scan of %s" % (my_dir.encode())) table.server = FileScanner.LocalFileScanner(table.file_queue, ignore_files=ignore_files) table.server_thread = QtCore.QThread() table.server.set_params(my_dir, subdirs=True) table.server.moveToThread(table.server_thread) table.server.signal.connect(table.rows_from_server) table.server_thread.started.connect(table.server.run) table.server_thread.start() # @QtCore.Slot() def sync_files(self): self.local_table_model.sync_prep() self.remote_table_model.sync_prep() self.local_table_model.sync_to(self.remote_table_model) self.remote_table_model.sync_to(self.local_table_model) # @QtCore.Slot() def remote_quick_refresh(self): MyMainWindow.refresh( self.remote_table_model, ignore_files=self.remote_table_model.get_all_files()) # @QtCore.Slot() def local_quick_refresh(self): MyMainWindow.refresh( self.local_table_model, ignore_files=self.local_table_model.get_all_files()) # @QtCore.Slot() def local_full_refresh(self): MyMainWindow.refresh(self.local_table_model) # @QtCore.Slot() def remote_full_refresh(self): MyMainWindow.refresh(self.remote_table_model) def delete_file(self): pass @staticmethod def refresh(table, ignore_files=()): if len(ignore_files) == 0: table.clear_all_rows() # for my_dir in table.get_root_dirs(): MyMainWindow.scan_dir_to_table(table, my_dir, ignore_files=ignore_files) # @QtCore.Slot() def left_load_playlist(self): self.load_playlist(self.left_playlist_table) # @QtCore.Slot() def right_load_playlist(self): self.load_playlist(self.right_playlist_table) def load_playlist(self, list_table): file = str( QtGui.QFileDialog.getOpenFileName( self, 'Select Playlist', self.Base_Dir, # 'Playlists (*.m3u *.xspf);;All files (*.*)')[0]) print("Playlist = %s" % file) if not os.path.isfile(file): print("no such file") return scanner = PlaylistScanner.PlaylistScanner(self.local_table_model, self.remote_table_model, list_table) scanner.run(file) def send_req(self, method, params=None): Req = { "jsonrpc": "2.0", "id": "%s!%d" % (method, self.Id), "method": method } if params: Req["params"] = params self.sendQueue.put(Req) self.Id += 1 def on_close(self): PickleHandler.PickleWriter(self.Base_Dir, self.local_table_model, self.remote_table_model) self.local_table_model.close() self.remote_table_model.close() def closeEvent(self, *args, **kwargs): self.on_close() return QtGui.QMainWindow.closeEvent(self, *args, **kwargs) @staticmethod def get_bad_syncs(table): close_list = [] alone_list = [] for x in table.my_list: if x['sync state'] == "close": close_list.append(x) elif x['sync state'] == "alone": alone_list.append(x) return close_list, alone_list
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui_main = Ui_MainWindow() self.ui_main.setupUi(self) self.setWindowTitle("Sweep Measure System (SMS)") self.ui_serial = Ui_SerialWindow() self.ui_serial.setupUi( self.ui_main.tabSerial ) # register the serial page into tabwidget.tabSerial self.ui_main.tabWidget.setCurrentIndex(0) # matplot setting self.fig = Figure(figsize=(8, 4.5), dpi=100) self.static_canvas = FigureCanvas(self.fig) self.static_canvas.setParent(self.ui_main.tabPlot) self.axes = self.fig.add_subplot(211) self.axes_dynamic = self.fig.add_subplot(212) data = [random.random() for i in range(25)] self.axes.plot(data, '-r', linewidth=2.0) self.static_canvas.draw() self.timer = QTimer(self) self.timer.timeout.connect(self.update_figure) self.timer.start(20) # self.timer.stop() # shutdown # serial settings self.ser = serial.Serial() self.Com_Dict = {} # counting self.data_bytes_sent = 0 self.ui_serial.leSerialPortDataBytesSent.setText( str(self.data_bytes_sent)) self.ui_serial.leSerialPortDataBytesSent.setEnabled(False) self.data_bytes_received = 0 self.ui_serial.leSerialPortDataBytesReceived.setText( str(self.data_bytes_received)) self.ui_serial.leSerialPortDataBytesReceived.setEnabled(False) # ui_serial serial default settings default_index = self.ui_serial.cbbSerialPortBaudrate.findText( "9600") # baudrate if default_index == -1: self.ui_serial.cbbSerialPortBaudrate.setCurrentIndex(0) else: self.ui_serial.cbbSerialPortBaudrate.setCurrentIndex(default_index) default_index = self.ui_serial.cbbSerialPortDatabit.findText( "8") # Databit if default_index == -1: self.ui_serial.cbbSerialPortDatabit.setCurrentIndex(0) else: self.ui_serial.cbbSerialPortDatabit.setCurrentIndex(default_index) default_index = self.ui_serial.cbbSerialPortParity.findText( "N") # Parity if default_index == -1: self.ui_serial.cbbSerialPortParity.setCurrentIndex(0) else: self.ui_serial.cbbSerialPortParity.setCurrentIndex(default_index) default_index = self.ui_serial.cbbSerialPortStopbit.findText( "1") # Stopbit if default_index == -1: self.ui_serial.cbbSerialPortStopbit.setCurrentIndex(0) else: self.ui_serial.cbbSerialPortStopbit.setCurrentIndex(default_index) self.ui_serial.btnSerialCLose.setEnabled(False) # Receive Timer self.receive_timer = QTimer(self) self.receive_timer.timeout.connect(self.receive_data) # ui_serial slot connection self.ui_serial.btnCheckSerialPort.clicked.connect( self.check_serial_port) self.ui_serial.btnSerialOpen.clicked.connect(self.open_serial_port) self.ui_serial.btnSerialCLose.clicked.connect(self.close_serial_port) self.ui_serial.btnSerialPortSend.clicked.connect(self.send_data) self.ui_serial.btnSerialPortSendClear.clicked.connect( self.clear_send_data) self.ui_serial.btnSerialPortReceiveClear.clicked.connect( self.clear_receive_data) # OpenGL setup self.openGL = QOpenGLWidget() self.openGL.setParent(self.ui_main.tabOpenGL) self.openGL.initializeGL = self.init_gl self.openGL.initializeGL() self.openGL.resizeGL(851, 651) self.openGL.paintGL = self.paint_gl self.update_times = 0 self.timer_gl = QTimer() self.timer_gl.timeout.connect(self.openGL.update) self.timer_gl.start(20) def init_gl(self): gluPerspective(45, 851 / 651, 0.1, 50.0) gluLookAt(8.0, 8.0, 4.0, 0.0, 0.0, 0.0, -1, -1, 1) def paint_gl(self): glClear(GL_COLOR_BUFFER_BIT) line_length = 4 cur_line_size = 5 cube_length = 2.0 glPushMatrix() glPushMatrix() glRotatef(self.update_times * 10, 0.0, 0.0, 1.0) glLineWidth(cur_line_size) glColor3f(1, 0, 0) glBegin(GL_LINES) glVertex3f(0.0, 0.0, 0.0) glVertex3f(line_length, 0.0, 0.0) glEnd() glColor3f(0, 1, 0) glBegin(GL_LINES) glVertex3f(0.0, 0.0, 0.0) glVertex3f(0.0, line_length, 0.0) glEnd() glColor3f(0, 0, 1) glBegin(GL_LINES) glVertex3f(0.0, 0.0, 0.0) glVertex3f(0.0, 0.0, line_length) glEnd() glPopMatrix() glTranslate(-0.5 * cube_length, -0.5 * cube_length, -0.5 * cube_length) glColor3f(1, 1, 0) glBegin(GL_QUAD_STRIP) glVertex3f(0.0, 0.0, 0.0) glVertex3f(0.0, cube_length, 0.0) glVertex3f(cube_length, 0.0, 0.0) glVertex3f(cube_length, cube_length, 0.0) glVertex3f(cube_length, 0.0, -cube_length) glVertex3f(cube_length, cube_length, -cube_length) glVertex3f(0.0, 0.0, -cube_length) glVertex3f(0.0, cube_length, -cube_length) glVertex3f(0.0, 0.0, 0.0) glVertex3f(0.0, cube_length, 0.0) glEnd() glBegin(GL_QUAD_STRIP) glVertex3f(0.0, 0.0, 0.0) glVertex3f(cube_length, 0.0, 0.0) glVertex3f(0.0, 0.0, -cube_length) glVertex3f(cube_length, 0.0, -cube_length) glVertex3f(0.0, cube_length, 0.0) glVertex3f(cube_length, cube_length, 0.0) glVertex3f(0.0, cube_length, -cube_length) glVertex3f(cube_length, cube_length, -cube_length) glEnd() glPopMatrix() self.update_times += 1 def check_serial_port(self): # check virtual seiral port for port, desc, hwid in sorted(comports()): print("%s: %s [%s]" % (port, desc, hwid)) port_list = list(sorted(comports())) self.ui_serial.cbbSerialPorts.clear() for port in port_list: self.Com_Dict["%s" % port[0]] = "%s" % port[1] # print(self.Com_Dict) self.ui_serial.cbbSerialPorts.addItem(port[0]) if len(port_list) == 0: print("No serial port found") def open_serial_port(self): data_bits = { '5': serial.FIVEBITS, '6': serial.SIXBITS, '7': serial.SEVENBITS, '8': serial.EIGHTBITS } parity = { 'N': serial.PARITY_NONE, 'Odd': serial.PARITY_ODD, 'Even': serial.PARITY_EVEN } stop_bits = { '1': serial.STOPBITS_ONE, '1.5': serial.STOPBITS_ONE_POINT_FIVE, '2': serial.STOPBITS_TWO } self.ser.port = self.ui_serial.cbbSerialPorts.currentText() self.ser.baudrate = int( self.ui_serial.cbbSerialPortBaudrate.currentText()) self.ser.bytesize = data_bits[ self.ui_serial.cbbSerialPortDatabit.currentText()] self.ser.parity = parity[ self.ui_serial.cbbSerialPortParity.currentText()] self.ser.stopbits = stop_bits[ self.ui_serial.cbbSerialPortStopbit.currentText()] print("Serial Port: {0} {1} {2} {3}".format(self.ser.port, self.ser.baudrate, self.ser.parity, self.ser.stopbits)) try: self.ser.open() except: QMessageBox.critical(self, "Port Error", "Cannot open this port") if self.ser.isOpen(): self.receive_timer.start(100) print("{0} opened".format(self.ser.port)) self.ui_serial.btnSerialOpen.setEnabled(False) self.ui_serial.btnSerialCLose.setEnabled(True) pass def close_serial_port(self): if self.ser.is_open: try: self.receive_timer.stop() self.ser.close() self.ui_serial.btnSerialOpen.setEnabled(True) self.ui_serial.btnSerialCLose.setEnabled(False) print("{0} closed".format(self.ser.port)) except: pass def send_data(self): if self.ser.is_open: input_s = self.ui_serial.pteSerialPortInput.toPlainText() if input_s != '': if self.ui_serial.cbSerialPortSendHex.isChecked(): input_s = input_s.strip() send_list = [] while input_s != '': try: num = int(input_s[0:2], 16) except ValueError: QMessageBox.critical(self, "Wrong Data", "Please input Hex Number") return None input_s = input_s[2:].strip() send_list.append(num) input_s = bytes(send_list) else: input_s = (input_s + "\n").encode('utf-8') num = self.ser.write(input_s) self.data_bytes_sent += num self.ui_serial.leSerialPortDataBytesSent.setText( str(self.data_bytes_sent)) def receive_data(self): if not self.ser.is_open: return try: num = self.ser.in_waiting except: self.ser.close() return if num > 0: data = self.ser.read(num) num = len(data) if self.ui_serial.cbSerialPortReceiveHex.isChecked(): out_s = '' for i in range(len(data)): out_s = out_s + '{:02X}'.format(data[i]) + ' ' self.ui_serial.pteSerialPortReceive.insertPlainText(out_s) else: self.ui_serial.pteSerialPortReceive.insertPlainText( data.decode('utf-8')) # unicode text_cursor = self.ui_serial.pteSerialPortReceive.textCursor() text_cursor.movePosition(QTextCursor.EndOfLine) self.ui_serial.pteSerialPortReceive.setTextCursor(text_cursor) self.data_bytes_received += num self.ui_serial.leSerialPortDataBytesReceived.setText( str(self.data_bytes_received)) else: pass def clear_send_data(self): self.ui_serial.pteSerialPortInput.setPlainText("") self.data_bytes_sent = 0 self.ui_serial.leSerialPortDataBytesSent.setText( str(self.data_bytes_sent)) def clear_receive_data(self): self.ui_serial.pteSerialPortReceive.setPlainText("") self.data_bytes_received = 0 self.ui_serial.leSerialPortDataBytesReceived.setText( str(self.data_bytes_received)) def update_figure(self): t = np.linspace(0, 10, 101) self.axes_dynamic.cla() self.axes_dynamic.plot(t, np.sin(t + time.time()), 'r', linewidth=2.0) self.static_canvas.draw()
class CDL(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.wait = Ui_Wait(self) self.downloadsManager = DownloadsManager(self, self.ui.downloadsList) global config self.videosManager = VideosManager(self.ui.downloadsList, self.ui.categoriesList) QObject.connect(self.downloadsManager, SIGNAL("download_terminated(PyQt_PyObject)"), self.add_video) QObject.connect(self, SIGNAL("refresh(PyQt_PyObject)"), self.downloadsManager.refresh_downloads_list) QObject.connect(self.ui.downloadsList, SIGNAL("download(PyQt_PyObject)"), self.downloadsManager.download) QObject.connect(self, SIGNAL("construct_downloads(PyQt_PyObject)"), self.generate_downloads) QObject.connect(self.downloadsManager, SIGNAL("blacklist(PyQt_PyObject)"), self.blacklist) QObject.connect(self.ui.wait, SIGNAL("open()"), self.ui.wait.open) QObject.connect(self.ui.wait, SIGNAL("close()"), self.ui.wait.close) def showPreferences(self): self.pref = Preferences(self) QObject.connect(self.pref, SIGNAL("configChanged(PyQt_PyObject)"), self.videosManager.refresh_categoriesList) self.pref.show() def blacklist(self, download): config.blacklist.append(download) DAO.commit() def generate_downloads(self, list_data): downloads = [] for d in list_data: download = DAO.download(d['url'], d['category'], d['description'], d['name']) downloads.append(download) self.emit(SIGNAL("refresh(PyQt_PyObject)"), downloads) def add_video(self, download): new_video = Video(download.url, download.category, download.name, download.date, download.description) self.videosManager.add_new_video(new_video) def refresh_downloads_list(self): def threadListNewVideos(self): self.ui.wait.emit(SIGNAL("open()")) list_data = [] for c in config.categories: list_data.extend(c.find_new_videos_availables( config.blacklist)) self.emit(SIGNAL("construct_downloads(PyQt_PyObject)"), list_data) self.ui.wait.emit(SIGNAL("close()")) if self.downloadsManager.nb_downloads_in_progress != 0: r = QMessageBox.critical( self, "Veuillez patienter !", u"Tous les téléchargements ne sont pas terminés, veuillez patienter quelques instants avant de raffraichir cette liste" ) return config.blacklist config.categories = [DAO.merge(x) for x in config.categories] threading.Thread(target=threadListNewVideos, args=[self]).start() def quit(self): if hasattr(self, 'pref'): self.pref.close() if hasattr(self, 'downloadsManager'): self.downloadsManager.ui_download.close() self.close() def closeEvent(self, closeEvent): self.quit() @pyqtSlot() def on_pushButtonRefresh_clicked(self): self.refresh_downloads_list() @pyqtSlot() def on_pushButtonDownload_clicked(self): self.downloadsManager.download_selected() @pyqtSlot() def on_pushButtonPlay_clicked(self): self.videosManager.play_selected() @pyqtSlot() def on_pushButtonBlacklist_clicked(self): try: self.downloadsManager.blacklist_selected() except Exception, e: print "error while blacklisting video" print traceback.format_exc(e)
class Frame(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.__ui = Ui_MainWindow() self.__ui.setupUi(self) self.__windowlist = [] self.__windowindex = 0 self.__ui.tmpTextEdit.hide() self.__ui.tmpTextEdit.setLineWrapMode(QtGui.QTextEdit.WidgetWidth) self.minibuffer().hide() self.setObjectName(str(self)) self.completionswidget = CompletionsWidget(self.__ui.miniBuffer) def set_active(self): log.debug("Frame gets active") def closeEvent(self, closeevent): log.debug("Close event") def set_minibuffer(self, txt): self.__ui.miniBuffer.set(txt) def append_minibuffer(self, txt): self.__ui.miniBuffer.append(txt) def focus_minibuffer(self): self.__ui.miniBuffer.setFocus() def keyPressEvent(self, ke): log.debug("FRAME keyPressEvent") QtGui.QMainWindow.keyPressEvent(self, ke) def minibuffer(self): return self.__ui.miniBuffer def append_status(self, what): sb = self.statusBar() sb.showMessage(str(sb.currentMessage()) + what) def set_status(self, what, duration=0): log.debug("set_status %s", what) self.statusBar().showMessage(what, duration) def set_completion(self, what): self.set_minibuffer(what) def show_completions(self, completions): self.completionswidget.show_completions(completions, self) def next_completion(self): return self.completionswidget.next() def prev_completion(self): return self.completionswidget.prev() def unshow_completions(self): log.debug("unshow completions") self.completionswidget.hide() def set_prompt(self, what): self.__ui.promptLabel.show() self.__ui.promptLabel.setText(what) def new_dock_widget(self, buffername="*scratch*"): ndw = DockWidget(self) self.addDockWidget(QtCore.Qt.DockWidgetArea(4),ndw) self.__windowlist.append(ndw) return ndw def dockwidgets(self): return self.__windowlist def remove(self, window): log.debug("remove %s", window) assert window in self.__windowlist self.__windowlist.remove(window) window.close() def other_window(self): self.focusNextChild() def keyboard_quit(self): self.minibuffer().keyboard_quit() self.set_status("Quit") self.unshow_completions() def focusInEvent(self, focusevent): log.debug("Gets focus, parent is %s", self.parent()) QtGui.QMainWindow.focusInEvent(self, focusevent) def focusOutEvent(self, focusevent): log.debug("loses focus, parent is %s", self.parent()) QtGui.QMainWindow.focusOutEvent(self, focusevent)