class mywindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.student_info = [] self.thread = [] self.main_thread = "" self.result = [] def add(self): url = self.ui.url_text.text() time = self.ui.time_text.text() name = self.ui.name_text.text() student_id = self.ui.id_text.text() self.student_info.append([name, student_id]) t = threading.Thread(target=self.post, args=(url, time, name, student_id)) t.daemon = True t.start() self.thread.append(t) self.print_info() def confirm(self): self.check_alive(self.thread) def print_info(self): self.result_text = '请求队列信息如下:\n' for name, student_id in self.student_info: self.result_text += name + " " + student_id + " 加入队列\n" self.ui.result_text.setText(self.result_text) def check_alive(self, thread_list): # while True: # for t in thread_list: # if(t.is_alive()): # time.sleep(1) # break # else: # break for t in thread_list: if (t.is_alive()): return self.result_text = "结果显示:\n" for name, student_id, flag in self.result: if flag: flag = "成功" else: flag = "失败" self.result_text += name + " " + student_id + " " + flag + "\n" self.ui.result_text.setText(self.result_text) def post(self, url, time, name, student_id): spider = Spider(url, time, name, student_id) self.result.append([name, student_id, spider.run()])
class Form(QtGui.QDialog): def __init__(self, parent=None, name=None): QtGui.QDialog.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) brands = controller.get_brands() for brand in brands: self.ui.brand.addItem(brand["name"], brand["id_brand"]) if name is None: self.ui.btn_add.clicked.connect(self.add) else: self.setWindowTitle(u"Editar producto") self.name = name product_data = controller.get_product(name) self.ui.name.setText(product_data["prod"]) self.ui.desc.setText(product_data["description"]) self.ui.color.setText(product_data["color"]) self.ui.price.setValue(product_data["price"]) self.ui.brand.currentText() self.ui.btn_add.clicked.connect(self.edit) self.ui.btn_cancel.clicked.connect(self.cancel) def add(self): #Take the values from the ui form and add the new product name = self.ui.name.text() description = self.ui.desc.text() color = self.ui.color.text() price = self.ui.price.value() brand = self.ui.brand.currentText() id_brand = controller.get_id_brand(brand) result = controller.add_product(name, description, color, price, id_brand) if result: self.reject() else: self.ui.message.setText( "Hubo un problema al intentar agregar el producto") def edit(self): #Take the values form a product, then save the edited values id_product = controller.get_id_product(self.name) name = self.ui.name.text() description = self.ui.desc.text() color = self.ui.color.text() price = self.ui.price.value() brand = self.ui.brand.currentText() id_brand = controller.get_id_brand(brand) result = controller.edit_product(id_product, name, description, color, price, id_brand) if result: self.reject() else: self.ui.message.setText( "Hubo un problema al intentar editar el producto") def cancel(self): #Cancel the operation on the ui form self.reject()
class Form(QtGui.QDialog): def __init__(self, parent=None, name=None): QtGui.QDialog.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) brands = controller.get_brands() for brand in brands: self.ui.brand.addItem(brand["name"], brand["id_brand"]) if name is None: self.ui.btn_add.clicked.connect(self.add) else: self.setWindowTitle(u"Editar producto") self.name = name product_data = controller.get_product(name) self.ui.name.setText(product_data["prod"]) self.ui.desc.setText(product_data["description"]) self.ui.color.setText(product_data["color"]) self.ui.price.setValue(product_data["price"]) self.ui.brand.currentText() self.ui.btn_add.clicked.connect(self.edit) self.ui.btn_cancel.clicked.connect(self.cancel) def add(self): #Take the values from the ui form and add the new product name = self.ui.name.text() description = self.ui.desc.text() color = self.ui.color.text() price = self.ui.price.value() brand = self.ui.brand.currentText() id_brand = controller.get_id_brand(brand) result = controller.add_product(name, description, color, price, id_brand) if result: self.reject() else: self.ui.message.setText("Hubo un problema al intentar agregar el producto") def edit(self): #Take the values form a product, then save the edited values id_product = controller.get_id_product(self.name) name = self.ui.name.text() description = self.ui.desc.text() color = self.ui.color.text() price = self.ui.price.value() brand = self.ui.brand.currentText() id_brand = controller.get_id_brand(brand) result = controller.edit_product(id_product, name, description, color, price, id_brand) if result: self.reject() else: self.ui.message.setText("Hubo un problema al intentar editar el producto") def cancel(self): #Cancel the operation on the ui form self.reject()
def main(): app = QApplication(sys.argv) window=QDialog() ui=Ui_Form() ui.setupUi(window) control=controller(ui,window) window.show() sys.exit(app.exec_()) pass
def main(): print sys.getdefaultencoding() app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() ui = Ui_Form() ui.setupUi(w) control = Control(ui) msg = QtGui.QMessageBox() msg.setText( u'Результаты помещены в файл res.txt и загружены в облако DropBox') msg.exec_() w.show() sys.exit(app.exec_()) pass
class TestForm(QtWidgets.QDialog): def __init__(self, parent=None): super().__init__() self.parser = parser.Parser(file_name()) self.parser.split_on_selectors() self.parser_dict = self.parser.parser_dict() self.ui = Ui_Form() self.ui.setupUi(self) self.ui.pushButton_1.clicked.connect(self.do_replace) self.ui.LineEdit_1.currentIndexChanged.connect(self.add_properties) self.style_file = StyleFile(file_name()) self.add_selectors() # self.ui.LineEdit_1.addItems(self.parser.selectors()) # self.ui.LineEdit_3.addItems(self.parser.properties()) def add_selectors(self): self.selectors = sorted(self.parser_dict.keys()) self.ui.LineEdit_1.addItems(self.selectors) def add_properties(self, i): self.ui.LineEdit_3.clear() properties = self.parser_dict[self.selectors[i]] self.ui.LineEdit_3.addItems(sorted(properties.keys())) def do_replace(self): new_css_lst = [] selector = self.ui.LineEdit_1.currentText() property = self.ui.LineEdit_3.currentText() value = self.ui.LineEdit_4.text() for s in self.parser.selectors_split_lst: print(s) new = self.parser.new_css_value(selector, property, value, s) print("-----------------") print(new) new_css_lst.append(new) new_css_str = ''.join(new_css_lst) self.parser.file_obj.write_style_to_file(new_css_str) sys.exit()
class OSD: def __init__(self, size=(640, 480), pos1=(0, 0), pos2=(0, 0)): app = QtGui.QApplication(sys.argv) window = QtGui.QWidget() self.ui = Ui_Form() self.ui.setupUi(window) app2 = QtGui.QApplication(sys.argv) window2 = QtGui.QWidget() self.ui2 = Ui_Form() self.ui2.setupUi(window2) self.telem = None self.r = True self.mainThr = threading.Thread(target=self.update) self.mainThr.start() self.ui.move(*pos1) self.ui2.move(*pos2) self.ui.resize(size) self.ui2.resize(size) window.show() window2.show() sys.exit(app.exec_()) def newTelemetry(self, telem): self.telem = telem def update(self): while self.r: if self.telem == None: continue self.ui.q1.setText(str(time.time())) self.ui.n1.display(111) time.sleep(1)
class Joining(QWidget): def __init__(self): super().__init__() self.ui_form = Ui_Form() self.join = False self.ui_form.setupUi(self) self.ui_form.pushButton_2.clicked.connect(self.is_existed) def is_existed(self): self.con = sqlite3.connect('library.sqlite') self.cur = self.con.cursor() users = self.cur.execute( '''SELECT nickname, password FROM [people]''').fetchall() for i in users: if i[0] == self.ui_form.lineEdit_2.text( ) and i[1] == self.ui_form.lineEdit.text(): ui.user_label.setText(f'Пользователь: {i[0]}') ui.error_label_1.setText('') self.join = True window.show_for_current_user(i[0]) self.close() if not self.join: self.ui_form.label_3.setText('Неверный логин или пароль') self.con.close()
class MainForm(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) self.control = Controller.Controller() self.logTimer = QtCore.QTimer() self.uiToConvertState() # Set up some initial states: # The following line is for debugging purposes only: self.ui.le_scenePath.setText("/Users/Murphy/currentProjects/A_1.mb") # Set the stylesheet sheetObj = open('./styles/style.qss') self.setStyleSheet(sheetObj.read()) # Set up the history list: self.ui.list_scenes.setModel(self.control.histModel) self.ui.list_scenes.setSortingEnabled(True) self.ui.list_scenes.hideColumn(1) self.ui.list_scenes.hideColumn(4) self.ui.list_scenes.resizeColumnsToContents() self.ui.list_scenes.sortByColumn(3, QtCore.Qt.DescendingOrder) self.ui.list_scenes.setGridStyle(QtCore.Qt.NoPen) self.ui.list_scenes.verticalHeader().hide() self.ui.list_scenes.horizontalHeader().stretchLastSection() self.ui.list_scenes.setSelectionBehavior(QtGui.\ QAbstractItemView.SelectRows) # Set up some slots and signals. self.ui.but_go.clicked.connect(self.startNewConversion) self.ui.but_tab_convert.clicked.connect(self.switchConvTab) self.ui.but_tab_history.clicked.connect(self.switchHistTab) self.ui.but_pick.clicked.connect(self.getSceneFile) self.ui.but_another.clicked.connect(self.uiToConvertState) self.connect(self.logTimer,\ QtCore.SIGNAL("timeout()"), self.updateLogProgbar) # Define some methods to react to signals def refreshStylesheet(self): ''' This method opens and applies the custom style sheet for UI ''' sheetObj = open('./styles/style.qss') self.setStyleSheet(sheetObj.read()) def switchConvTab(self): ''' Switches the UI tab to converter. ''' self.ui.stackedWidget.setCurrentWidget(self.ui.page_convert) def switchHistTab(self): ''' Switches the UI tab to history. ''' self.ui.stackedWidget.setCurrentWidget(self.ui.page_history) def uiToConvertState(self): ''' Controls visibility of ui elements to reflect the convert layout.''' self.ui.frame_progress.hide() self.ui.frame_convert.show() def uiToProgressState(self): ''' Controls visibility of ui elements to reflect the progress layout ''' self.ui.frame_progress.show() self.ui.frame_convert.hide() def getSceneFile(self): ''' This opens a dialog box to be able to pick a maya file ''' fileName = QtGui.QFileDialog.getOpenFileName(self, \ "Select Scene File", "/", "Maya Files (*.ma *.mb)") self.ui.le_scenePath.setText(fileName[0]) def startNewConversion(self): ''' Tell the controller to instantiate a new scene, switch UI to progress layout and begin timer to update the log. ''' path = self.ui.le_scenePath.text() if (path == ""): return self.control.startNewScene(path) self.logTimer.start() self.uiToProgressState() def updateLogProgbar(self): ''' If the scene is done converting, stop the watch timer. else, get teh contents of the log for that scene and update the progress bar ''' if self.control.getCurrentStatus() == "True": self.logTimer.stop() self.ui.te_activeLog.setText(self.control.getCurrentLog()) self.ui.progressBar.setValue(int(self.control.getCurrentProgress()))
class EditForm(QtGui.QDialog): """ Edit one song - small dialog. """ def __init__(self, parent=None): """ Class constructor. """ super(EditForm, self).__init__(parent) # UI setup self.ui = Ui_Form() self.ui.setupUi(self) self.ui.saveButton.clicked.connect(self.HandleSaveButton) self.ui.okButton.clicked.connect(self.HandleOkButton) self.ui.resetButton.clicked.connect(self.HandleResetButton) self.ui.deleteButton.clicked.connect(self.HandleDeleteButton) self.ui.musicButton.clicked.connect(self.HandleMusicButton) self.ui.saveFileButton.clicked.connect(self.HandleSaveFileButton) self.ui.startTime.setDisplayFormat('hh:mm:ss') self.ui.endTime.setDisplayFormat('hh:mm:ss') self.ui.startTime.setMinimumTime(QTime(0, 0, 0)) # Class members self.song = None self.data = None self.resetData = None self.bitrate = None self.name = None self.result = None self.index = None self.isPlaying = False def __del__(self): """ Class destuctor. """ if self.isPlaying: sd.stop() def Init(self, song, data, bitrate): """ Initialize with song. :param song: input song :type song: list :param data: input data from wav file :type data: numpy.array :param bitrate: bitrate of input file :type bitrate: int """ self.song = copy.deepcopy(song) self.index = self.song[0] self.name = self.song[1] self.ui.saveButton.setText(self.name) self.data = data self.resetData = copy.deepcopy(song) self.bitrate = bitrate h, m, s = EditForm.ParseTime(self.song[2]) self.ui.startTime.setTime(QTime(h, m, s)) h, m, s = EditForm.ParseTime(self.song[3]) self.ui.endTime.setTime(QTime(h, m, s)) end_time = datetime.timedelta(seconds=int(self.data.shape[0] / self.bitrate)) h, m, s = EditForm.ParseTime(str(end_time)) self.ui.endTime.setMaximumTime(QTime(h, m, s)) def HandleSaveButton(self): """ Handle save button. Saves separate file. """ name = QtGui.QFileDialog.getSaveFileName(self, 'Save File') if len(name) > 0: self.name = name self.ui.saveButton.setText(name) def HandleOkButton(self): """ Handle ok button. Save changes to parent window(table). """ start = str(self.ui.startTime.time().toString()) end = str(self.ui.endTime.time().toString()) self.result = [self.index, str(self.name), start, end] self.accept() def HandleResetButton(self): """ Handle reset button. Resets to default configuration. """ self.ui.saveButton.setText(self.resetData[1]) h, m, s = EditForm.ParseTime(self.resetData[2]) self.ui.startTime.setTime(QTime(h, m, s)) h, m, s = EditForm.ParseTime(self.resetData[3]) self.ui.endTime.setTime(QTime(h, m, s)) def HandleDeleteButton(self): """ Handle delete button. Deletes input row from table. """ self.result = [] self.accept() def HandleMusicButton(self): """ Handle music playing button. Play/Stop music by input interval. """ if not self.isPlaying: self.ui.musicButton.setText('Stop') start = EditForm.Time2Frames( str(self.ui.startTime.time().toString()), self.bitrate) end = EditForm.Time2Frames(str(self.ui.endTime.time().toString()), self.bitrate) sd.play(self.data[start:end], self.bitrate) self.isPlaying = True else: self.ui.musicButton.setText('Play') sd.stop() self.isPlaying = False def HandleSaveFileButton(self): """ Handle separated save file button. """ start = EditForm.Time2Frames(str(self.ui.startTime.time().toString()), self.bitrate) end = EditForm.Time2Frames(str(self.ui.endTime.time().toString()), self.bitrate) wf.write(self.name, self.bitrate, self.data[start:end]) @staticmethod def ParseTime(time): """ Parse time in format hh:mm:ss. :param time: input time :type time: str :returns: hours, minutes, seconds :rtype: tuple """ f = time.find(':') l = time.rfind(':') h = time[:f] m = time[f + 1:l] s = time[l + 1:] return int(h), int(m), int(s) @staticmethod def Time2Frames(time, freq): """ Transfer time in h:m:s string to index by frequency. :param time: input time :type time: str :param freq: input frequency :type freq: int """ time = EditForm.ParseTime(time) sec = time[0] * 3600 + time[1] * 60 + time[2] return sec * freq
class App(object): def __init__(self): self.ip_address = "192.168.1.33" self.ip_port = "5000" self.db_user = "******" self.db_pass = "******" self.server_ip = f"http://{self.ip_address}:{self.ip_port}" self.nam = QtNetwork.QNetworkAccessManager() self.df = None self.data = None self.temp_data = None # schedule.every().second.do(self.update_plot_data) schedule.every().second.do(self.graph_display) ### schedule.every().second.do(self.temp_display) self.calibration_data = { "Co2 Calibration Data": {}, "Fertilizer Calibration Data": {}, "Water Conditioner Calibration Data": {}, } self.ratio_data = { "Tank": {}, "Co2_ratio": {}, "Co2_Water": {}, "Fertilizer_ratio": {}, "Fertilizer_water": {}, "WaterConditioner_ratio": {}, "WaterConditioner_water": {}, "Co2_dosage": {}, "Fertilizer_dosage": {}, "WaterConditioner_dosage": {}, } self.setting_data = { "IP Address": {}, "Temperature Alerts": {}, "Email Alert": {} } self.new_data = {"Ratio Data": {}} self.config_data = { "network_data": {}, } self.calibration_mode_on = True self.app = QtWidgets.QApplication(sys.argv) self.central = QtWidgets.QWidget() self.window = AsyncScheduleMainWindow() self.form = Ui_Form() self.window.setCentralWidget(self.central) self.form.setupUi(self.central) try: file = QFile(":/dark.qss") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) self.app.setStyleSheet(stream.readAll()) except: logger.exception("Couldn't Load Style Sheet") self.ratio_displays = [ self.form.Tank, self.form.Co2_ratio, self.form.Co2_water, self.form.Fertilizer_ratio, self.form.Fertilizer_water, self.form.WaterConditioner_ratio, self.form.WaterConditioner_water, self.form.Co2_dosage, self.form.Fertilizer_dosage, self.form.WaterConditioner_dosage ] # logger.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) self.log = logging.getLogger('AquariumQT') # self.log.handlers = [InfoHandler(self.form.textBrowser)] # logger. = [PropagateHandler(self.form.textBrowser)] # logger.add(PropagateHandler(), format="{message}") # logger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>") # log_decorate = logger.level("Decorator", no=38, color="<yellow>", icon="🐍") # self.client = QtWebSockets.QWebSocket("", QtWebSockets.QWebSocketProtocol.Version13, None) # self.client.error.connect(self.on_error) # self.client.open(QUrl(f"ws://{self.ip_address}:5000/csv")) # self.client.pong.connect(self.ws_receive) # self.client.textMessageReceived.connect(self.ws_receive) # self.client.open(QUrl(f"ws://{self.ip_address}:5000/csv")) # self.client.pong.connect(self.ws_receive2) # self.client.textMessageReceived.connect(self.ws_receive2) self.form.Co2_calibrateButton.clicked.connect( lambda: self.enter_calibrationMode("Co2")) self.form.save_ratios_pushButton.clicked.connect(self.save_ratios) self.form.ht_alert_doubleSpinBox.valueChanged.connect( self.set_temp_alert) self.form.lt_alert_doubleSpinBox.valueChanged.connect( self.set_temp_alert) self.form.ht_checkBox.stateChanged.connect(self.set_temp_alert) self.form.lt_checkBox.stateChanged.connect(self.set_temp_alert) self.form.view_pass_checkBox.stateChanged.connect(self.view_pass) self.form.sys_setting_save_pushButton.clicked.connect(self.save_email) self.form.sys_setting_test_pushButton.clicked.connect(self.email_test) self.form.sys_setting_update_pushButton.clicked.connect(self.update) self.form.alert_limit_spinBox.valueChanged.connect( self.save_email_alert) # self.form.aquaPi_calendarWidget.selectionChanged.connect(self.aquaPi_schedules) # self.temperature_graph = TemperatureWidget() # self.plot = pg.PlotWidget(self.form.temperatureGraph) self.aquaPi_schedules = {} self.aquaPi_hours_list = [ self.form.hours_0, self.form.hours_1, self.form.hours_2, self.form.hours_3, self.form.hours_4, self.form.hours_5, self.form.hours_6, self.form.hours_7, self.form.hours_8, self.form.hours_9, self.form.hours_10, self.form.hours_11, self.form.hours_12, self.form.hours_13, self.form.hours_14, self.form.hours_15, self.form.hours_16, self.form.hours_17, self.form.hours_18, self.form.hours_19, self.form.hours_20, self.form.hours_21, self.form.hours_22, self.form.hours_23 ] self.form.hour_save_button.clicked.connect(self.save_aquaPi_schedules) parent = self.form.temperatureGraph.parent() geom_object = self.form.temperatureGraph.frameGeometry() geometry = QtCore.QRect(geom_object.left(), geom_object.top(), geom_object.width(), geom_object.height()) object_name = self.form.temperatureGraph.objectName() del self.form.temperatureGraph self.plot = pg.PlotWidget( parent, title="Aquarium Temperature", labels={'left': 'Temperature / °C'}, axisItems={'bottom': TimeAxisItem(orientation='bottom')}) self.plot.setGeometry(geometry) self.plot.setObjectName(object_name) self.plot.showGrid(x=True, y=True) self.plotCurve = self.plot.plot(pen='y') self.plotData = {'x': [], 'y': []} self.load_config() self.load_server() self.timer = QtCore.QTimer() self.timer.setInterval(1000) self.timer.timeout.connect(self.window.sch_run) self.timer.start() self.pool = None self.rows = [] #asyncio.run(self.sch_run()) #asyncio.get_event_loop().run_until_complete(self.sch_run()) #asyncio.get_event_loop().run_until_complete( # self.sch_run() #) #asyncio.get_event_loop().run_forever(self.tank_db()) #asyncio.get_event_loop().create_task(self.sch_run()) def save_aquaPi_schedules(self): logger.info("=" * 125) hour_results = [hour.isChecked() for hour in self.aquaPi_hours_list] hour_0, hour_1, hour_2, hour_3, hour_4, hour_5, hour_6, hour_7, hour_8, hour_9, hour_10, hour_11, \ hour_12, hour_13, hour_14, hour_15, hour_16, hour_17, hour_18, hour_19, hour_20, hour_21, hour_22, \ hour_23 = hour_results a = [index for index, val in enumerate(hour_results) if val] print(f"Selected Hours = {a}") """ date = self.form.aquaPi_calendarWidget.selectedDate().toString("dd-MM-yyyy") does_operation = self.form.hour_comboBox.currentText() run_operation_on = for True in hour_results print(f"On {date}, {does_operation} Will run at {run_operation_on}") print(hour_results) print(hour_10)""" # a = self.form.hours_0.isChecked() # print(a) # hours = async def sql_connection(self): logger.info("=" * 125) logger.info("sql_connection: Entered".center(125)) try: pool = await asyncpgsa.create_pool(host=self.ip_address, database="AquaPiDB", user=self.db_user, password=self.db_pass) logger.debug( "Connection is established: Database has been created ") return pool except Error: logger.exception(Error) finally: logger.info("sql_connection: Exited".center(125)) logger.info("=" * 125) async def tank_db(self): logger.info("=" * 125) logger.info("tank_db: Entered".center(125)) try: if not self.pool: logger.critical('NEW POOL') self.pool = await self.sql_connection() async with self.pool.transaction() as conn: if not self.rows: logger.warning("Rows Empty, Fetching Whole DB") rows = await conn.fetch('SELECT * FROM tank_temperature') else: last_id = self.rows[-1]['id'] rows = await conn.fetch( f'SELECT * FROM tank_temperature WHERE id > {last_id}') logger.debug( f"DB still in Memory, last row id := {last_id}") logger.success(f"New DB Data Received: {rows}") logger.debug(f"Rows Received : {len(rows)}") self.rows.extend(rows) self.df = pandas.DataFrame(rows, columns=list(self.rows[0].keys())) return self.df except: logger.exception("tank_db Error") finally: logger.info("tank_db: Exited".center(125)) logger.info("=" * 125) """async def graph_display(self): logger.info("=" * 125) logger.info("graph_display: Entered".center(125)) try: rows = await self.tank_db() self.df = pandas.DataFrame(rows, columns=list(rows[0].keys())) if self.df is not None: self.y = self.df['temperature_c'].to_numpy(dtype=float) self.x = self.df['date'] self.x = [t.timestamp() for t in self.x] self.x = [round(t) for t in self.x] self.plotData['x'] = self.x self.plotData['y'] = self.y self.plotCurve.setData(self.plotData['x'], self.plotData['y']) logger.critical('Plotting') logger.debug(f"X = {len(self.x)}") logger.debug(f"Y = {len(self.y)}") except: logger.exception("oops") finally: logger.info("graph_display: Exited".center(125)) logger.info("=" * 125)""" async def graph_display(self): logger.info("=" * 125) logger.info("graph_display: Entered".center(125)) try: db = await self.tank_db() self.y = db['temperature_c'].to_numpy(dtype=float) self.x = db['date'] self.x = [t.timestamp() for t in self.x] self.x = [round(t) for t in self.x] self.plot.plot().setData(self.x, self.y) except: logger.exception("oops") finally: logger.info("graph_display: Exited".center(125)) logger.info("=" * 125) async def temp_display(self): logger.info("=" * 125) logger.info("temp_display: Entered".center(125)) logger.debug(self.df) if self.df is not None and not self.df.empty: c = self.df['temperature_c'].iat[-1] f = self.df['temperature_f'].iat[-1] self.form.tank_display_c.display(c) self.form.tank_display_f.display(f) logger.debug(f"°C: {c}") logger.debug(f"°F: {f}") logger.info("temp_display: Exited".center(125)) logger.info("=" * 125) def load_server(self): logger.info("=" * 125) resp = requests.get(url=f"{self.server_ip}/getServerData") self.new_data = json.loads(resp.content) """try: resp = requests.get(url=f"{self.server_ip}/getServerData") self.new_data = json.loads(resp.content) return schedule.cancel_job(self.load_server()) except requests.exceptions.ConnectionError: logger.critical("Server Not Responding") schedule.every().minute.do(self.load_server())""" try: logger.debug("Loading 'data.txt' From Server") if resp.json() is None: logger.warning("No 'data.txt' Found on Server") else: logger.success("'data.txt' Loaded from Server") logger.debug(f"Response:{self.new_data}") logger.info("Assigning Data Values from 'self.new_data'") self.calibration_data = self.new_data["Calibration Data"] self.ratio_data = self.new_data["Ratio Data"] co2_cal = self.calibration_data["Co2 Calibration Data"][ "Time per 10mL"] self.setting_data = self.new_data["Setting Data"] ht = self.setting_data["Temperature Alerts"]["High Temp"] ht_enabled = self.setting_data["Temperature Alerts"][ "High Enabled"] lt = self.setting_data["Temperature Alerts"]["Low Temp"] lt_enabled = self.setting_data["Temperature Alerts"][ "Low Enabled"] try: self.form.ht_alert_doubleSpinBox.blockSignals(True) self.form.lt_alert_doubleSpinBox.blockSignals(True) self.form.ht_checkBox.blockSignals(True) self.form.lt_checkBox.blockSignals(True) for key in self.ratio_data: ui_obj = getattr(self.form, key) if isinstance(ui_obj, QtWidgets.QDoubleSpinBox): ui_obj.setValue(self.ratio_data[key]) else: ui_obj.setText(str(self.ratio_data[key])) self.form.lcd_co2_cal.display(co2_cal) self.form.ht_alert_doubleSpinBox.setValue(float(ht)) self.form.lt_alert_doubleSpinBox.setValue(float(lt)) self.form.ht_checkBox.setChecked(bool(int(ht_enabled))) self.form.lt_checkBox.setChecked(bool(int(lt_enabled))) self.form.ht_alert_doubleSpinBox.blockSignals(False) self.form.lt_alert_doubleSpinBox.blockSignals(False) logger.success("Data Display Values Updated") except (KeyError, ValueError, TypeError): logger.warning("Couldn't Assign Values from 'data.txt'") except (UnboundLocalError, json.decoder.JSONDecodeError): logger.warning("Couldn't Load Data") logger.info("=" * 125) def load_config(self): logger.info("=" * 125) logger.info("Connecting To Server".center(125)) logger.info("=" * 125) try: resp = requests.get(url=f"{self.server_ip}/getConfig") self.config_data = json.loads(resp.content) logger.debug("Loading 'config.json' From Server") if resp.json() is None: logger.warning("No 'config.json' Found on Server") else: logger.success("'config.json' Loaded from Server") logger.debug(f"Response:{self.config_data}") logger.info("Assigning Config Values from Config.json") try: email_user = self.config_data["network_config"][ "target_email"] service_email = self.config_data["network_config"][ "service_email"] alert_limit_email = int( self.config_data["network_config"]["alert_limit"]) self.form.email_lineEdit.setText(email_user) self.form.sys_setting_atemail_comboBox.setCurrentText( service_email) self.form.alert_limit_spinBox.blockSignals(True) self.form.alert_limit_spinBox.setValue(alert_limit_email) self.form.alert_limit_spinBox.blockSignals(False) logger.success("Config Values Updated") self.view_pass() except (KeyError, ValueError, TypeError): logger.warning("Couldn't Assign Values from 'config.json") except requests.exceptions.ConnectionError: logger.critical("Couldn't Connect To Server".center(125)) logger.info("=" * 125) def view_pass(self): logger.info("=" * 125) pass_chk = self.form.view_pass_checkBox.checkState() logger.info("Loading Saved Password") if self.config_data["network_config"]["password_email"]: logger.success("Password Found") pass_email = self.config_data["network_config"]["password_email"] logger.debug(f"Password: {pass_email}") try: logger.debug(f"Pass Reveal State: {pass_chk}") i = len(pass_email) if pass_chk == 2: self.form.email_pass_lineEdit.setText(pass_email) logger.debug(f"Revealing Pass: {pass_email}") else: self.form.email_pass_lineEdit.setText("*" * i) logger.info("Pass Hidden") except KeyError: logger.warning("Couldn't Email Password to Load") else: logger.warning("Couldn't Email Password to Load") logger.info(f"self.config data: {self.config_data}") logger.info("=" * 125) def update(self): try: resp = requests.get(url=f"{self.server_ip}/update") logger.info("Checking for Updates...") logger.info(f"Response: {resp}") except: logger.exception("Couldn't Update") def temp_alert_test(self): resp = requests.get(url=f"{self.server_ip}/alertTest") logger.info(f"Response: {resp}") logger.info(f"Sending Alert Test") def save_ratios(self): self.log.info("Sending New Ratio Data to Server") ratio_results = [ int(ratio.value()) for ratio in (self.form.Tank, self.form.Co2_ratio, self.form.Co2_water, self.form.Fertilizer_ratio, self.form.Fertilizer_water, self.form.WaterConditioner_ratio, self.form.WaterConditioner_water) ] Tank, Co2_ratio, Co2_water, Fertilizer_ratio, Fertilizer_water, WaterConditioner_ratio, WaterConditioner_water \ = ratio_results self.log.info( 'Tank Size: {} Litres,\n' 'Co2 Concentrate: {} mL, Co2 to Water: {} Litres,\n' 'Fertilizer Concentrate: {} mL, Fertilizer to Water: {} Litres,\n' 'WaterConditioner Concentrate: {} mL, WaterConditioner to Water: {} Litres' .format(*ratio_results)) url = f"http://192.168.1.33:5000/setRatios?Tank={Tank}&Co2_ratio={Co2_ratio}&Co2_water={Co2_water}" \ f"&Fertilizer_ratio={Fertilizer_ratio}&Fertilizer_water={Fertilizer_water}" \ f"&WaterConditioner_ratio={WaterConditioner_ratio}&WaterConditioner_water={WaterConditioner_water}" request = QtNetwork.QNetworkRequest(QUrl(url)) self.nam.get(request) self.load_server() def enter_calibrationMode(self, pump_type): try: self.calibration_mode_on = not self.calibration_mode_on if not self.calibration_mode_on: requests.get( url=f"{self.server_ip}/calibrationModeOn?type={pump_type}") logger.info("Calibration Mode: ON") else: requests.get( url=f"{self.server_ip}/calibrationModeOff?type={pump_type}" ) logger.info("Calibration Mode: OFF") self.load_server() except Exception as e: logger.exception(e) def exit_calibrationMode(self, pump_type): requests.get( url=f"{self.server_ip}/calibrationModeOff?type={pump_type}") def set_temp_alert(self): ht = self.form.ht_alert_doubleSpinBox.value() ht_enabled = self.form.ht_checkBox.checkState() lt = self.form.lt_alert_doubleSpinBox.value() lt_enabled = self.form.lt_checkBox.checkState() logger.info(f"Sending Alert Changes to Network".center(125)) logger.info(f"High Temperature: {ht}") logger.info(f"Low Temperature: {lt}") requests.get( url= f"{self.server_ip}/setTemperatureAlert?ht={ht}<={lt}&ht_enabled={ht_enabled}" f"<_enabled={lt_enabled}") self.load_server() def ip_update(self): LAN_host = self.form.ip_spinBox.value() LAN_id = "192.168.1." logger.info(f"Ip Address Updated") def save_email(self): logger.debug("=" * 125) logger.info(f"config start of email function: {self.config_data}") email_user = self.form.email_lineEdit.text() password_email = self.form.email_pass_lineEdit.text() if password_email != 0: password_email = self.form.email_pass_lineEdit.text() else: pass if "*" in password_email: password_email = self.config_data["network_config"][ "password_email"] logger.info(f"config middle of email function: {self.config_data}") logger.info(f"config password_email: {password_email}") service_email_drop = self.form.sys_setting_atemail_comboBox.currentText( ) service_email = service_email_drop.strip() # alert_limit = self.form.alert_limit_spinBox.value() requests.get( url= f"{self.server_ip}/saveEmail?email_user={email_user}&service_email={service_email}\ &password_email={password_email}") logger.info(f"config end of email function: {self.config_data}") self.load_config() logger.info( f"config after reloading email function: {self.config_data}") def save_email_alert(self): logger.debug("=" * 125) logger.info(f"Email Alert Limit Updated".center(125)) logger.debug("=" * 125) alert_limit = self.form.alert_limit_spinBox.value() logger.info(f"Type:{type(alert_limit)} Value: {alert_limit}") requests.get( url=f"{self.server_ip}/saveEmail_limit?alert_limit={alert_limit}") logger.debug("=" * 125) def email_test(self): logger.info("Asking Server to Test Email") requests.get(url=f"{self.server_ip}/emailTest") def run(self): #self.window.show() #self.app.exec() loop = QEventLoop(self.app) asyncio.set_event_loop(loop) self.window.show() with loop: sys.exit(loop.run_forever()) def handle_response(self, response): logger.info(response.readAll( )) # you can change this to show in the log instead if you want to def start_timers(self): return def set_temp_display_color(self, color): return self.form.tank_display_c.setStyleSheet( f"QLCDNumber {{background-color: {color}}}") def graph_test(self): pass """@asyncSlot() async def sch_run(self): print("nuts") #try: # schedule.run_pending() #except: # logger.exception("schedule run error") #while True: # await schedule.run_pending() # await asyncio.sleep(0.1)""" def ws_receive(self, csv): try: self.data = io.StringIO(csv) # logger.debug(len(csv)) except: logger.debug("stringio error") """ def ws_receive(self, text): self.temp_c = text self.update_plot_data() self.form.tank_display_c.display(text) ht_chk = self.setting_data["Temperature Alerts"]["High Enabled"] lt_chk = self.setting_data["Temperature Alerts"]["Low Enabled"] ht_thr = self.setting_data["Temperature Alerts"]["High Temp"] lt_thr = self.setting_data["Temperature Alerts"]["Low Temp"] # try: # self.graphTest() # except Exception as e: # logger.exception(e) try: # print(f"ht_chk: {ht_chk}") # print(f"lt_chk: {lt_chk}") # print(f"ht_thr: {ht_thr}") # print(f"lt_thr: {lt_thr}") if ht_thr < lt_thr: logger.warning("High Temp Cannot Be Lower Than low Temp") return if ht_chk == '2': if float(text) > float(ht_thr): logger.warning("High Temp Alert!!!") self.set_temp_display_color("red") else: self.set_temp_display_color("white") if lt_chk == '2': if float(text) < float(lt_thr): logger.warning("Low Temp Alert!!!") self.set_temp_display_color("cyan") else: self.set_temp_display_color("white") # print(f"ws_receive: {text}") except: logger.exception("Alert :ERROR") """ def on_error(self, error_code): return
class Form(QtGui.QDialog): """clase que crea la ventana de ingreso de empleados""" def __init__(self, parent=None, rut=None): """constructor que crea la ventana de ingreso de empleados""" QtGui.QDialog.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) if rut is None: self.ui.comboBox.addItem("Masculino","Masculino") self.ui.comboBox.addItem("Femenino","Femenino") else: datos_empleado = controller.obtener_empleado_por_rut(rut) self.ui.rut_bar.setText(str(datos_empleado[0][0])) self.ui.rut_bar.setReadOnly(True) self.ui.nombre_bar.setText(datos_empleado[0][1]) self.ui.cargo_bar.setText(datos_empleado[0][2]) self.ui.sueldo_bar.setText(datos_empleado[0][4]) self.ui.local_bar.setText(str(datos_empleado[0][5])) if(datos_empleado[0][3]=="Masculino"): self.ui.comboBox.addItem("Masculino","Masculino") self.ui.comboBox.addItem("Femenino","Femenino") else: self.ui.comboBox.addItem("Femenino","Femenino") self.ui.comboBox.addItem("Masculino","Masculino") self.ui.cancel_btn.clicked.connect(self.cancel) self.show() def add(self): """función que crea el ingreso de empleados""" genero = self.ui.comboBox.itemData(self.ui.comboBox.currentIndex()) if(self.ui.rut_bar.text()!="" and self.ui.nombre_bar.text()!="" and self.ui.cargo_bar.text()!="" and self.ui.sueldo_bar.text()!=""): try: int(self.ui.rut_bar.text()) res = controller.agregar_empleado(int(self.ui.rut_bar.text()),self.ui.nombre_bar.text(),self.ui.cargo_bar.text(), genero,self.ui.sueldo_bar.text(),self.ui.local_bar.text()) if res: self.reject() msgBox = QtGui.QMessageBox.information(self,"Exito","El empleado fue agregado.") else: msgBox = QtGui.QMessageBox.critical(self,"Error","No se pudo agregar el empleado.") except: msgBox = QtGui.QMessageBox.information(self,"Error","ingrese el rut sin puntos ni guion") else: msgBox = QtGui.QMessageBox.information(self,"Error","ingrese todos los campos de informacion") def edit(self): rut = self.ui.rut_bar.text() nombre = self.ui.nombre_bar.text() cargo = self.ui.cargo_bar.text() genero = self.ui.comboBox.itemData(self.ui.comboBox.currentIndex()) sueldo = self.ui.sueldo_bar.text() result = controller.editar_empleado(rut,nombre, cargo, genero, sueldo) if result: self.reject() #Cerramos y esto cargara nuevamente la grilla else: self.ui.mensajes.setText("Hubo un problema al intentar editar el alumno") def cancel(self): """ventana que permite la cancelación de la ventana""" self.reject()
class Form(QtGui.QDialog): def __init__(self, parent=None, common_name=None, image=None): QtGui.QDialog.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) types = controller.get_types() self.directory = QDir.root() self.display = QGraphicsView() self.ui.scrollArea.setWidget(self.display) for tipo in types: self.ui.typeBox.addItem(tipo["nombre"], tipo["id_tipo"]) if common_name is None: self.ui.btn_done.clicked.connect(self.add) if image is None: self.ui.image.setPlainText(image) else: self.setWindowTitle(u"Editar animal") self.common = common_name animal_data = controller.get_animal(common_name) self.ui.common_name.setPlainText(animal_data["nombre_comun"]) self.ui.cientific_name.setText(animal_data["nombre_cientifico"]) self.ui.data.setText(animal_data["datos"]) tipo = self.ui.typeBox.currentText() id_type = controller_form.get_id_type(tipo) id_animal = controller_form.get_id_animal(common_name) self.image = controller_form.get_image(id_animal) if self.image: self.path = QDir.currentPath() + "/images/" + self.image[0] + self.image[1] self.ui.image.setPlainText(self.path) Ifile = QFileInfo(self.path) pixImage = controller_form.get_root_image(self.path) item = QGraphicsPixmapItem(pixImage.scaled(100,100)) scene = QGraphicsScene() scene.addItem(item) self.display.setScene(scene) self.ui.image.setPlainText(self.path) else: noimage = controller_form.no_image() item = QGraphicsPixmapItem(noimage.scaled(100,100)) scene = QGraphicsScene() scene.addItem(item) self.display.setScene(scene) scene = QGraphicsScene() scene.addItem(item) self.display.setScene(scene) self.path = "" self.ui.image.setPlainText(self.path) self.ui.btn_done.clicked.connect(self.edit) self.ui.btn_delete.clicked.connect(self.delete) self.ui.btn_open.clicked.connect(self.open) self.ui.btn_cancel.clicked.connect(self.cancel) def add(self): """ Agrega un nuevo animal """ common = self.ui.common_name.toPlainText() if common == "": self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"Debe ingresar al menos el nombre común") else: cientific = self.ui.cientific_name.toPlainText() other = self.ui.data.toPlainText() tipo = self.ui.typeBox.currentText() id_type = controller_form.get_id_type(tipo) result = controller_form.add_animal(common, cientific, other, id_type) path = self.ui.image.toPlainText() if path != "": id_animal = controller_form.get_id_animal(common) shutil.copy(path,(self.directory.currentPath()+"/images/")) Ifile = QFileInfo(path) controller_form.add_image_dir(id_animal,Ifile.fileName()) else: noimage = controller_form.no_image() item = QGraphicsPixmapItem(noimage.scaled(100,100)) self.scene = QGraphicsScene() self.ui.graphicsView.setSceneRect(0,0,100,100) self.ui.graphicsView.setScene(self.scene) self.scene.addItem(item) if result: self.reject() else: self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"Hubo un problema al intentar agregar el animal") def cancel(self): """ Cancela la operacion """ self.reject() def edit(self): """ Modifica un animal que se encuentre en la base de datos """ id_animal = controller_form.get_id_animal(self.common) common = self.ui.common_name.toPlainText() if common == "": self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"El nombre común no puede estar en blanco") else: cientific = self.ui.cientific_name.toPlainText() other = self.ui.data.toPlainText() tipo = self.ui.typeBox.currentText() id_type = controller_form.get_id_type(tipo) path = self.ui.image.toPlainText() result = controller_form.edit_animal(id_animal,common,cientific,other,id_type) if path != "": pixImage = controller_form.get_root_image(path) item = QGraphicsPixmapItem(pixImage.scaled(100,100)) scene = QGraphicsScene() scene.addItem(item) self.display.setScene(scene) self.ui.image.setPlainText(path) Ifile = QFileInfo(path) if controller_form.search_image(id_animal,Ifile.fileName()): controller_form.add_image_dir(id_animal,Ifile.fileName()) result = True else: result = False else: noimage = controller_form.no_image() item = QGraphicsPixmapItem(noimage.scaled(100,100)) scene = QGraphicsScene() scene.addItem(item) self.display.setScene(scene) self.ui.image.setPlainText(path) if result: self.reject() else: self.ui.msgBox = QtGui.QMessageBox.information(self, u'Error', u"Hubo un problema al intentar editar el animal, intentelo de nuevo") def open(self): """ Abre una ventana para buscar imagen en el directorio """ dialog = QtGui.QFileDialog() imagen = dialog.getOpenFileName(self,"Abrir imagen" , "?" , "Image Files (*.png *.jpg *.bmp)") Ifile = QFileInfo(imagen[0]) pixImage = controller_form.get_root_image(imagen[0]) item = QGraphicsPixmapItem(pixImage.scaled(100,100)) scene = QGraphicsScene() scene.addItem(item) scene.setSceneRect(0, 0, 100, 100) self.display.setScene(scene) if imagen[0] != "": self.ui.image.setPlainText(imagen[0]) def delete(self): """ Borra la imagen del animal cuando se preciona quitar """ path = self.ui.image.toPlainText() Ifile = QFileInfo(path) success = controller_form.del_image(Ifile.fileName()) if not success: self.ui.errorMessageDialog = QtGui.QMessageBox.information(self, 'Error', u"Dirección incorrecta", QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ok) self.ui.image.setPlainText("")
class MainWindow(QtWidgets.QDialog): def __init__(self): QtWidgets.QDialog.__init__(self) self.ui = Ui_Dialog() self.ui.setupUi(self) self.t_form = False self.a_form = False self.ag_form = False self.tests = QtWidgets.QComboBox(self) self.ui.formWidgetLayout.insertWidget(1, self.tests) self.loader = Loader() self.loadTests() self.act_lable = QtWidgets.QLabel(self.ui.formWidget) font = QtGui.QFont() font.setPointSize(12) font.setWeight(75) font.setBold(True) self.act_lable.setFont(font) self.ui.formWidgetLayout.insertWidget(3, self.act_lable) self.actions = QtWidgets.QComboBox(self) self.ui.formWidgetLayout.insertWidget(4, self.actions) self.loadActions() self.agg_lable = QtWidgets.QLabel(self.ui.formWidget) self.agg_lable.setFont(font) self.ui.formWidgetLayout.insertWidget(6, self.agg_lable) self.aggregation = QtWidgets.QComboBox(self) self.ui.formWidgetLayout.insertWidget(7, self.aggregation) self.loadAggregation() self.loadKeys() self.tests.currentIndexChanged.connect(self.loadTestFile) self.actions.currentIndexChanged.connect(self.loadActionFile) self.aggregation.currentIndexChanged.connect(self.loadAggFile) self.ui.fromDate.dateChanged.connect(self.updateResult) self.ui.toDate.dateChanged.connect(self.updateResult) self.ui.fromTime.timeChanged.connect(self.updateResult) self.ui.toTime.timeChanged.connect(self.updateResult) self.ui.statusCheckbox.stateChanged.connect(self.updateResult) self.ui.periodSpinBox.valueChanged.connect(self.updateResult) self.ui.resultCombo.currentIndexChanged.connect(self.updateResult) def loadTests(self): for i in self.loader.t_names: self.tests.addItem(i) self.loadTestFile() def loadTestFile(self): if self.t_form: self.t_form.deleteLater() item_list = self.loader.readFile( "Test/", self.loader.t_names.get(self.tests.currentText())) self.t_form = Ui_Form() self.t_form.english = True self.t_form.setupUi(item_list) self.t_form.flagged.connect(self.updateResult) self.ui.formWidgetLayout.insertWidget(2, self.t_form) self.updateResult() def loadActions(self): self.actions.addItem("NULL") for i in self.loader.a_names: self.actions.addItem(i) self.loadActionFile() def loadActionFile(self): if self.a_form: self.a_form.deleteLater() if self.actions.currentText() != "NULL": item_list = self.loader.readFile( "Action/", self.loader.a_names.get(self.actions.currentText())) else: item_list = [] self.a_form = Ui_Form() self.a_form.english = True self.a_form.setupUi(item_list) self.a_form.flagged.connect(self.updateResult) self.ui.formWidgetLayout.insertWidget(5, self.a_form) self.updateResult() def loadAggregation(self): self.aggregation.addItem("NULL") for i in self.loader.ag_names: self.aggregation.addItem(i) self.loadAggFile() def loadAggFile(self): if self.ag_form: self.ag_form.deleteLater() if self.aggregation.currentText() != "NULL": item_list = self.loader.readFile( "Aggregation/", self.loader.ag_names.get(self.aggregation.currentText())) else: item_list = [] self.ag_form = Ui_Form() self.ag_form.english = True self.ag_form.setupUi(item_list) self.ag_form.flagged.connect(self.updateResult) self.ui.formWidgetLayout.insertWidget(8, self.ag_form) spacer_item = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.ui.formWidgetLayout.addItem(spacer_item) self.updateResult() def loadKeys(self): keys = self.loader.readFile("", "keys.json") self.ui.resultCombo.addItem("All") for i in keys: self.ui.resultCombo.addItem(i) def updateResult(self): result = Result(self) self.ui.resultLineEdit.setText(result.final_result)
class WorkForm(): def __init__(self): self.engine = Engine() self.ui = Ui_Form() self.MainWindow = QtGui.QMainWindow() self.ui.setupUi(self.MainWindow) self.ui.stackedWidget.setCurrentIndex(4) self.setSignals() palette = QPalette() palette.setBrush(QPalette.Background, QBrush(QPixmap("background.jpg"))) #self.MainWindow.setPalette(palette) #self.ui.page_2.setStyleSheet("background-image: url("+"background.jpg"+"); background-repeat: no-repeat; background-position: center;") pass def chooseWay(self): wayIndex = self.ui.comboBox.currentIndex() if (wayIndex == 2): wayIndex = 3 elif (wayIndex == 3): wayIndex = 6 self.ui.stackedWidget.setCurrentIndex(wayIndex) pass def calculate1(self): square = self.ui.spinBox_2.value() sizeOne = self.ui.spinBox_3.value() print self.engine.bySquare(square, sizeOne) self.ui.stackedWidget.setCurrentIndex(2) self.ui.textBrowser.setText( u"Понадобится " + str(self.engine.bySquare(square, sizeOne)) + u" огнетушителей") pass def calculate2(self): square = self.ui.spinBox.value() category = self.ui.comboBox_2.currentIndex() min = self.engine.byDistance(category, square).x max = self.engine.byDistance(category, square).y self.ui.stackedWidget.setCurrentIndex(2) self.ui.textBrowser.setText(u"Понадобится " + str(min) + u" огнетушителей") pass def escape(self): outputs = self.ui.spinBox_7.value() people = self.ui.spinBox_6.value() for_one_output = 55 # 55 mans per minute needs_min = people / (outputs * for_one_output) if (needs_min < 0.5): needs_min = 1 self.ui.textBrowser_4.setText(u"Эвакуация будет длиться около " + str(needs_min) + u" минут") pass def gidranty(self): low = (30, 51, 101, 301, 1001, 1501) up = (50, 100, 300, 1000, 1500, 2000) litres = (15, 20, 25, 40, 60, 80, 100) grounds = self.ui.spinBox_4.value() one_gidrant = self.ui.spinBox_5.value() need_speed = 0 for i in range(len(low)): if (grounds >= low[i] and grounds <= up[i]): need_speed = litres[i] need_gidrants = need_speed / one_gidrant if need_gidrants < 0.5: need_gidrants = 1 self.ui.textBrowser_5.setText(u"Понадобится " + str(need_gidrants) + u" гидрантов") pass def go_to_info(self): self.ui.stackedWidget.setCurrentIndex(5) pass def go_to_main(self): self.ui.stackedWidget.setCurrentIndex(4) pass def aboutAuthor(self): self.ui.textBrowser_2.setText(u"Об авторе") pass def show_discription(self, index): text = [ u"Общественных здания , до огнетушителя не более 20 м", u"Помещения с этой категорией (АБВ), до огнетушителя не более 30 м", u"Помещения с этой категорией (Г) , до огнетушителя не более 20 м", u"Помещения с этой категорией (Д) , до огнетушителя не более 20 м" ] self.ui.textBrowser_6.setText(text[index]) pass def setSignals(self): self.ui.spinBox.setMaximum(99999999) self.ui.spinBox_2.setMaximum(99999999) self.ui.spinBox_3.setMaximum(99999999) self.ui.pushButton.clicked.connect(self.chooseWay) self.ui.pushButton_2.clicked.connect(self.calculate2) self.ui.pushButton_3.clicked.connect(self.calculate1) self.ui.pushButton_4.clicked.connect(self.go_to_info) self.ui.pushButton_5.clicked.connect(self.go_to_main) self.ui.pushButton_6.clicked.connect(self.go_to_main) self.ui.pushButton_7.clicked.connect(self.go_to_main) self.ui.pushButton_8.clicked.connect(self.go_to_main) self.ui.pushButton_9.clicked.connect(self.gidranty) self.ui.pushButton_10.clicked.connect(self.escape) self.ui.pushButton_11.clicked.connect(self.aboutAuthor) self.ui.comboBox_2.currentIndexChanged.connect(self.show_discription) pass pass
class MyForm(QMainWindow): def __init__(self, parent=None): QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) # self.api = TodoistAPI() # self.api.login("*****@*****.**", "zmxncbv") MyForm.api = TodoistAPI() MyForm.api.login("*****@*****.**", "zmxncbv") res = MyForm.api.sync(resource_types=["all"]) # print res MyForm.seq_no = res["seq_no"] # self.model = ProjectListModel(self.api.state["Projects"]) # self.model = ProjectListModel(MyForm.api.state["Projects"]) MyForm.projectModel = ProjectListModel(MyForm.api.state["Projects"]) # self.ui.projectsView.setModel(self.model) self.ui.projectsView.setModel(MyForm.projectModel) self.ui.projectsView.clicked.connect(self.itemSelected) self.ui.pushButton.clicked.connect(self.addProject) self.ui.addTaskButton.clicked.connect(self.addTask) self.ui.refreshBtn.clicked.connect(self.refresh) def itemSelected(self, index): # print "Index " + index.__str__ + " clicked..." # print index.row() # project = self.model.listdata[index.row()] project = MyForm.projectModel.listdata[index.row()] details = MyForm.api.get_project(project["id"]) # items = MyForm.api.get_completed_items(project["id"]) # print items # print MyForm.api.state["Items"] items = MyForm.api.state["Items"] relavant_items = [x for x in items if x["project_id"] == project["id"]] self.ui.projectName.setText(project["name"]) print relavant_items # set the view with selected items MyForm.itemsModel = ItemListModel(relavant_items) self.ui.itemsView.setModel(MyForm.itemsModel) # print details # print project # load all the items self.ui.textBrowser.setText(str(project)) def contextMenuEvent(self, pos): # print "context menu..." pass def addProject(self): # print "Adding project..." # make a popup here # self.w = MyPopup() # self.w.setGeometry(QRect(100, 100, 400, 200)) # self.w.show() self.w = MyPopup() self.w.show() def addTask(self): self.w = AddTaskPopup() self.w.show() def refresh(self): # res = MyForm.api.sync(resource_types=["all"]) # print "---------------" # print MyForm.api.seq_no # MyForm.api.seq_no = 0 # print MyForm.api.state # res = MyForm.api.sync(resource_types=["all"]) # print res # print MyForm.api.state["Projects"] # print self.ui.projectsView.model().listdata model = self.ui.projectsView.model() # self.ui.projectsView.model().dataChanged.emit() index = model.index(5) model.dataChanged.emit(index, index)
class mainForm(QWidget): def __init__(self): # 调用父类构造函数,初始化空窗口 super().__init__() # 使用ui文件导入定义界面类 self.ui = Ui_Form() # 初始化界面 self.ui.setupUi(self) # 设置类成员 self.qList = [] self.subMSD = None # 日志对象 self.log = Logger('debug.log', level='debug') # 设置信号 self.ui.toolButton_gamePos.clicked.connect(self.open_file_game) self.ui.toolButton_savePos.clicked.connect(self.open_file_txtsave) self.ui.pushButton_scan.clicked.connect(self.scanThreadFunc) self.ui.pushButton_opentxt.clicked.connect(self.open_txtlist) self.ui.pushButton_readtxt.clicked.connect(self.read_txtlist) self.ui.pushButton_index.clicked.connect(self.index_search) self.ui.pushButton_down.clicked.connect(self.download_mes) self.ui.lineEdit_audioPath.textChanged.connect(self.on_audiopath_changed) self.ui.comboBox_legend.currentIndexChanged.connect(self.legend_chosen) self.ui.pushButton_diag.clicked.connect(self.search_diag) self.ui.pushButton_effect.clicked.connect(self.search_effect) self.ui.commandLinkButton.clicked.connect(self.about) # 获得音源列表txt文件所在地址 def get_txtPos(self): gamePos = self.ui.lineEdit_gamePath.text() txtPos = self.ui.lineEdit_savePath.text() if txtPos == "": txtPos = gamePos + "/miles_audio/audio_list.txt" else: if txtPos[-1] == '/': txtPos = txtPos + "audio_list.txt" else: txtPos = txtPos + "/audio_list.txt" return txtPos def scanThreadFunc(self): thread = Thread(target=self.on_scan) thread.start() self.ui.pushButton_scan.setEnabled(False) # 点击扫描按钮,调用MSD获得音频列表,写入txt文件 def on_scan(self): try: self.ui.listWidget.clear() gamePos = self.ui.lineEdit_gamePath.text() print(gamePos) headPos = gamePos[0:2] txtPos = self.get_txtPos() print(headPos, txtPos) audioPos = self.ui.lineEdit_audioPath.text() if not os.path.isfile(gamePos + "\\MSD.exe"): QMessageBox.critical(self, "错误", "请检查MSD.exe文件是否在相应目录下") return cmdMSD = "" if audioPos != "": audioPos = '.' + audioPos cmdMSD = ''' %s & cd "%s" & .\\msd --folder=%s 0 1 & .\\msd --folder=%s -l > "%s" ''' \ % (headPos, gamePos, audioPos, audioPos, txtPos) else: cmdMSD = ''' %s & cd "%s" & .\\msd 0 1 & .\\msd -l > "%s" ''' % (headPos, gamePos, txtPos) print(cmdMSD) self.log.logger.info(cmdMSD) q = os.popen(cmdMSD) q.close() cnt = 0 with open(txtPos, 'r') as flist: for cnt, _ in enumerate(flist): pass cnt += 1 self.ui.label_nAudio.setText(str(cnt)) self.ui.spinBox.setMaximum(cnt - 1) self.ui.pushButton_opentxt.setEnabled(True) self.ui.pushButton_readtxt.setEnabled(True) except Exception as e: print(e) self.log.logger.error(e) QMessageBox.critical(self, "错误", "请确认路径参数正确后重试!", QMessageBox.Close) # 从txt文件中读取音频名称,展示到列表中,并初始化搜索框 def read_txtlist(self): txtPos = self.get_txtPos() self.qList.clear() # 获得所有音频名称的列表 with open(txtPos, 'r') as flist: for line in flist: self.qList.append(line) self.ui.listWidget.addItems(self.qList) # 连接信号:双击调用MSD播放音频 self.ui.listWidget.itemDoubleClicked.connect(self.play_one_aduio) # 启用查找按钮 self.ui.pushButton_index.setEnabled(True) self.ui.pushButton_diag.setEnabled(True) self.ui.pushButton_effect.setEnabled(True) self.ui.pushButton_down.setEnabled(True) self.init_diag_combo() # 防止重复读取,读取后禁用按钮 self.ui.pushButton_readtxt.setEnabled(False) # 按照序号搜索 def index_search(self): # 获得数字框的数字 id = int(self.ui.spinBox.text()) # 清除列表中的所有项目,再加入新项目 self.ui.listWidget.clear() self.ui.listWidget.addItem(self.qList[id]) # 允许重新读取整个列表 self.ui.pushButton_readtxt.setEnabled(True) # 打开选择文件夹窗口 def open_file_game(self): filepath = QtWidgets.QFileDialog.getExistingDirectory(self, "选取文件夹", ".") print(filepath) self.ui.lineEdit_gamePath.setText(filepath) def open_file_txtsave(self): filepath = QtWidgets.QFileDialog.getExistingDirectory(self, "选取文件夹", ".") print(filepath) self.ui.lineEdit_savePath.setText(filepath) # 用默认程序打开txt文件 def open_txtlist(self): gamePos = self.ui.lineEdit_gamePath.text() txt = self.ui.lineEdit_savePath.text() if txt == "": txt = gamePos + "\\miles_audio" head = txt[0:2] command = '''%s & \ cd %s & \ start .\\audio_list.txt ''' % (head, txt) try: p_res = os.popen(command) print(p_res.read()) except Exception as e: print(e) # 播放一次音频(会将wav文件存储到默认音频目录) def play_one_aduio(self): thread = Thread(target=self.playThreadFunc) thread.start() QMessageBox.information(self, "请稍等", "正在播放抓取的音频") def playThreadFunc(self): try: gamePos = self.ui.lineEdit_gamePath.text() headPos = gamePos[0:2] item = self.ui.listWidget.selectedItems()[0] id = item.text().split(',')[0] print(id) audioPos = self.ui.lineEdit_audioPath.text() cmdMSD = "" if audioPos != "": audioPos = '.' + audioPos cmdMSD = '''%s & \ cd %s & \ .\\msd --folder=%s %s ''' % (headPos, gamePos, audioPos, id) else: cmdMSD = '''%s & \ cd %s & \ .\\msd %s ''' % (headPos, gamePos, id) p_res = os.popen(cmdMSD) print(p_res.read()) except Exception as e: print(e) self.log.logger.error(e) def download_mes(self): thread = Thread(target=self.DownThreadFunc) thread.start() # 另存音频到指定地址 def DownThreadFunc(self): filepath = QtWidgets.QFileDialog.getExistingDirectory(self, "选择保存文件路径", ".") print(filepath) try: gamePos = self.ui.lineEdit_gamePath.text() headPos = gamePos[0:2] item = self.ui.listWidget.selectedItems()[0] id = item.text().split(',')[0] print(id) audioPos = self.ui.lineEdit_audioPath.text() cmdMSD = "" if audioPos != "": audioPos = '.' + audioPos cmdMSD = '''%s & \ cd %s & \ .\\msd -m --folder=%s --out=%s %s ''' % (headPos, gamePos, audioPos, filepath, id) else: cmdMSD = '''%s & \ cd %s & \ .\\msd -m --out=%s %s ''' % (headPos, gamePos, filepath, id) p_res = os.popen(cmdMSD) if p_res.read() != "": os.popen("start %s" % filepath) except Exception as e: print(e) self.log.logger.error(e) def on_audiopath_changed(self): self.ui.pushButton_scan.setEnabled(True) self.ui.pushButton_readtxt.setEnabled(False) self.ui.pushButton_index.setEnabled(False) self.ui.pushButton_diag.setEnabled(False) self.ui.pushButton_effect.setEnabled(False) self.ui.pushButton_down.setEnabled(False) def init_diag_combo(self): legendList = [] for each in self.qList: # print(each) # 匹配传奇名最小字符长度为3,别问我之前为啥是4,问就是出了ash这个怪物:( result = re.search(r"[0-9]+,diag_(ap|mp)_([a-zA-Z]{3,})_", each) if result is not None: l = result.group(2) # print(each, l) if l not in legendList: legendList.append(l) self.ui.comboBox_legend.addItems(legendList) def legend_chosen(self): actionList = [] self.ui.comboBox_action.clear() legend = self.ui.comboBox_legend.currentText() for each in self.qList: # print(each) result = re.search(r"[0-9]+,diag_(ap|mp)_%s_([a-zA-Z]+)_" % legend, each) if result is not None: l = result.group(2) # print(each, l) if l not in actionList: actionList.append(l) actionList.append("[None]") self.ui.comboBox_action.addItems(actionList) def search_diag(self): legend = self.ui.comboBox_legend.currentText() action = self.ui.comboBox_action.currentText() key = self.ui.lineEdit_diag.text() items = [] result = "" for each in self.qList: if action == "[None]": result = re.search(r"([0-9]+),diag_(ap|mp)_%s_.*%s.*" % (legend, key), each, flags=re.IGNORECASE) else: result = re.search(r"([0-9]+),diag_(ap|mp)_%s_%s_.*%s.*" % (legend, action, key), each, flags=re.IGNORECASE) if result is not None: id = int(result.group(1)) if id not in items: items.append(self.qList[id]) self.ui.listWidget.clear() self.ui.listWidget.addItems(items) # 允许重新读取整个列表 self.ui.pushButton_readtxt.setEnabled(True) def search_effect(self): key = self.ui.lineEdit_effect.text() items = [] for each in self.qList: result = re.search(r"([0-9]+),((?!diag).)*%s((?!diag).)*" % key, each, flags=re.IGNORECASE) if result is not None: id = int(result.group(1)) if id not in items: items.append(self.qList[id]) self.ui.listWidget.clear() self.ui.listWidget.addItems(items) # 允许重新读取整个列表 self.ui.pushButton_readtxt.setEnabled(True) def about(self): QMessageBox.about(self, "关于", "Apex 音频提取器v0.2 \n Github:Nick-bit233")
class mywindow(QtWidgets.QWidget): def __init__(self): super(mywindow, self).__init__() self.new = Ui_Form() self.new.setupUi(self)
class AppWindow(QWidget): dataset = [] numm = 0 dataset_old = [] C = [] #original classification result D = [] #normalized classification result def __init__(self): super().__init__() self.ui = Ui_Form() self.ui.setupUi(self) #1.open file self.ui.btopenfile.clicked.connect(self.openbt_Click) self.ui.btrun.clicked.connect(self.run) def openbt_Click(self): a = [] self.dataset = [] self.dataset_old = [] self.C = [] self.D = [] self.numm = 0 dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter(QDir.Files) if dlg.exec_(): filenames = dlg.selectedFiles() f = open(filenames[0], 'r') #show filename filename = os.path.basename(filenames[0]) self.ui.filenamelabel.setText(filename) with f: line = f.read() #print(line) f.close() ##process data a = line.split() self.dataset = np.mat([[float(a[i]), float(a[i + 1])] for i in range(0, len(a) - 1, 3)]) #print(self.dataset) #print(self.dataset.shape[0]) #print(self.dataset.shape[1]) self.numm = self.dataset.shape[0] def run(self): self.dataset_old = self.dataset.copy() som = SOM(self.dataset, (15, 15), 1, self.numm) som.train() res = som.train_result() classify = {} for i, win in enumerate(res): if not classify.get(win[0]): classify.setdefault(win[0], [i]) else: classify[win[0]].append(i) for i in classify.values(): self.C.append(self.dataset_old[i].tolist()) self.D.append(self.dataset[i].tolist()) ##draw the result self.drawO(self.C) self.drawN(self.D) def drawO(self, A): self.ui.mplwidget1.canvas.ax.clear() colValue = [ 'r', 'y', 'g', 'b', 'c', 'k', 'm', 'gray', 'rosybrown', 'bisque', 'darkkhaki', 'darkturquoise', 'plum', 'purple', 'lightcoral' ] for i in range(len(A)): coo_X = [] #x坐标列表 coo_Y = [] #y坐标列表 for j in range(len(A[i])): coo_X.append(A[i][j][0]) coo_Y.append(A[i][j][1]) self.ui.mplwidget1.canvas.ax.scatter(coo_X, coo_Y, marker='x', color=colValue[i % len(colValue)], label=i) self.ui.mplwidget1.canvas.ax.legend(loc='upper right') self.ui.mplwidget1.canvas.draw() def drawN(self, A): self.ui.mplwidget2.canvas.ax.clear() colValue = [ 'r', 'y', 'g', 'b', 'c', 'k', 'm', 'gray', 'rosybrown', 'bisque', 'darkkhaki', 'darkturquoise', 'plum', 'purple', 'lightcoral' ] for i in range(len(A)): coo_X = [] #x坐标列表 coo_Y = [] #y坐标列表 for j in range(len(A[i])): coo_X.append(A[i][j][0]) coo_Y.append(A[i][j][1]) self.ui.mplwidget2.canvas.ax.scatter(coo_X, coo_Y, marker='x', color=colValue[i % len(colValue)], label=i) self.ui.mplwidget2.canvas.ax.legend(loc='upper right') self.ui.mplwidget2.canvas.draw()