def __init__(self, parent=None): super(ZOpenGLView, self).__init__(parent) self.parent = parent self.timerThread = None self.renderingInterval = 30 self.mutex = QMutex()
def load_data(self, param_file): with open(param_file, 'r') as inputf: self.parameters = json.load(inputf) # Set imported parameters as properties for parameter in self.parameters: setattr(self, parameter, self.parameters[parameter]) # use for threadsafe commnications with the GUI thread self.mutex = QMutex() self.atmosphere = Atmosphere() # TODO Error analysis vs. ticksize self.ticksize = 0.001 self.time = 0 self.height = self.launch_height self.velocity = 0 self.acceleration = 0 self.max_height = 0 self.max_velocity = 0 self.max_acceleration = 0 self.mass = self.launch_mass self.thruster = Thruster() self.data = {} self.data['time'] = [] self.data['height'] = [] self.data['velocity'] = [] self.data['acceleration'] = []
class DataGenerator(QtCore.QObject): newData = QtCore.pyqtSignal(object) def __init__(self, parent=None, sizey=100, rangey=[0, 100], delay=1000): QtCore.QObject.__init__(self) self.parent = parent self.sizey = sizey self.rangey = rangey self.delay = delay self.mutex = QMutex() self.y = [0 for i in range(sizey)] self.run = True def generateData(self): while self.run: try: self.mutex.lock() for i in range(self.sizey): self.y[i] = randint(*self.rangey) self.mutex.unlock() self.newData.emit(self.y) QtCore.QThread.msleep(self.delay) except: pass
def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.no_internet_msg = _('Cannot download news as no internet connection ' 'is active') self.no_internet_dialog = d = error_dialog(self._parent, self.no_internet_msg, _('No internet connection'), show_copy_button=False) d.setModal(False) self.recipe_model = RecipeModel() self.db = db self.lock = QMutex(QMutex.Recursive) self.download_queue = set() self.news_menu = QMenu() self.news_icon = QIcon(I('news.png')) self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self) self.news_menu.addAction(self.scheduler_action) self.scheduler_action.triggered[bool].connect(self.show_dialog) self.cac = QAction(QIcon(I('user_profile.png')), _('Add or edit a custom news source'), self) self.cac.triggered[bool].connect(self.customize_feeds) self.news_menu.addAction(self.cac) self.news_menu.addSeparator() self.all_action = self.news_menu.addAction( _('Download all scheduled news sources'), self.download_all_scheduled) self.timer = QTimer(self) self.timer.start(int(self.INTERVAL * 60 * 1000)) self.timer.timeout.connect(self.check) self.oldest = gconf['oldest_news'] QTimer.singleShot(5 * 1000, self.oldest_check)
def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.canvasMutex = QMutex( ) # protects canvas (probably redundant since I don't use workers) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.draw_step) # connect actions self.ui.drawPushButton.clicked.connect(self.redraw_background) self.ui.startPushButton.clicked.connect(self.start_presentation) self.ui.stopPushButton.clicked.connect(self.timer.stop) self.ui.stepPushButton.clicked.connect(self.on_step_pushed) self.ui.functionEdit.textChanged.connect(self.set_redraw_needed) self.ui.x0DoubleSpinBox.valueChanged.connect(self.set_redraw_needed) self.ui.leftIntervalSpinBox.valueChanged.connect( self.set_redraw_needed) self.ui.rightIntervalSpinBox.valueChanged.connect( self.set_redraw_needed) self.ui.xyCheckBox.clicked.connect(self.set_redraw_needed) self.eps = 1e-15 self.itTBD = 0 self.xx = None # x axes - linspace from left self.gx = None # lambda function g(x) self.xc = None # current value of x self.redraw = True # indicates that old values are no longer valid! self.show()
def __init__(self, parent=None, sizey=100, rangey=[0, 100], delay=1000): QtCore.QObject.__init__(self) self.parent = parent self.sizey = sizey self.rangey = rangey self.delay = delay self.mutex = QMutex() self.y = [0 for i in range(sizey)] self.run = True
def __init__(self): self.mutex = QMutex() self.timeStamps = None self.stream = None self.inlet = None self.info = None self.channelCount = None self.doRec = False self.srate = None self.data = None self.bufferUpdateThread = None
class Write(QObject): signal_begin = pyqtSignal(str) def __init__(self, rest): # QObject().__init__(self) self.mutex = QMutex() def WriteCMD(self, command): self.mutex.lock() SensorSerial.write(str.encode(str(command))) readline = SensorSerial.readline().decode('utf-8').strip() self.mutex.unlock() return readline
def __init__(self, ip_port, game_rules): self.server_data = dict.copy(self.get_network_packet_definition()) self.setup_game_rules_to_server_data(game_rules) self._dealer = DealerClass(data=self.server_data) self.mutex = QMutex() self.conn_player_number = 0 self.conn_players_addresses = [0 for x in range(MAX_CLIENTS)] self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind(ip_port) except socket.error as e: str(e) self.s.listen(MAX_CLIENTS) print("Server Started... Waiting for a connection") thread = threading.Thread(target=self.server_listening_for_new_connections_loop, args=()) thread.start()
def __init__(self, parent=None, delay=50): QtCore.QObject.__init__(self) self.parent = parent self.delay = delay self.mutex = QMutex() self.run = True self.actionModule = ActionModule(None)
def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.no_internet_msg = _('Cannot download news as no internet connection ' 'is active') self.no_internet_dialog = d = error_dialog(self._parent, self.no_internet_msg, _('No internet connection'), show_copy_button=False) d.setModal(False) self.recipe_model = RecipeModel() self.db = db self.lock = QMutex(QMutex.Recursive) self.download_queue = set([]) self.news_menu = QMenu() self.news_icon = QIcon(I('news.png')) self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self) self.news_menu.addAction(self.scheduler_action) self.scheduler_action.triggered[bool].connect(self.show_dialog) self.cac = QAction(QIcon(I('user_profile.png')), _('Add a custom news source'), self) self.cac.triggered[bool].connect(self.customize_feeds) self.news_menu.addAction(self.cac) self.news_menu.addSeparator() self.all_action = self.news_menu.addAction( _('Download all scheduled news sources'), self.download_all_scheduled) self.timer = QTimer(self) self.timer.start(int(self.INTERVAL * 60 * 1000)) self.timer.timeout.connect(self.check) self.oldest = gconf['oldest_news'] QTimer.singleShot(5 * 1000, self.oldest_check)
class Write(QObject): signal_begin = pyqtSignal(str) def __init__(self, rest): QObject().__init__(self) self.mutex = QMutex() def WriteCMD(self, command): self.mutex.lock() print("Command: " + command) BridgeSerial.write(str.encode(command)) readline = BridgeSerial.readline() if command.startswith('RDGRNG '): time.sleep(3) if command.startswith('SCAN '): time.sleep(4) time.sleep(0.1) self.mutex.unlock() return readline
class InfoSocketNotification(QThread): def __init__(self, tray_icon): QThread.__init__(self) self.tray_icon = tray_icon self.mutex = QMutex() def __del__(self): self.wait() def run(self): wss = websocket.create_connection('wss://listen.moe/api/v2/socket') while True: self.mutex.lock() if not self.tray_icon.isPlaying: self.tray_icon.notificationWaitCondition.wait(self.mutex) data = wss.recv() if data != '': info = json.loads(data) self.tray_icon.new_song_notification_sent.emit(info) self.mutex.unlock()
def __init__(self): super().__init__() self.setupUi(self) self.rec_selction() self.send_selction() self.timer = QTimer() self.timer1 = QTimer() # self.time_now = time.strftime('%H:%M:%S',time.localtime()) self.timer1.timeout.connect(self.time_now) self.timer.timeout.connect(self.data_send) self.ser = serial.Serial() self.port_check() self.thread = Worker() self.qmut = QMutex() con = config.Myform() self.comboBox_port.addItem(con.com) self.comboBox_baud.setCurrentText(con.baud) self.comboBox_databit.setCurrentText(con.databit) self.comboBox_polarity.setCurrentText(con.polarity) self.comboBox_stopbit.setCurrentText(con.stopbit) self.comboBox_baud.currentIndexChanged.connect(self.combox_baud_cb) self.comboBox_databit.currentIndexChanged.connect(self.combox_databit_cb) self.comboBox_polarity.currentIndexChanged.connect(self.combox_polarity_cb) self.comboBox_stopbit.currentIndexChanged.connect(self.combox_stopbit_cb) self.btn_send.clicked.connect(self.btn_send_cb) self.action_start.setEnabled(True) self.action_Pause.setEnabled(False) self.action_Stop.setEnabled(False) self.action_start.triggered.connect(self.action_start_cb) self.action_Pause.triggered.connect(self.action_Pause_cb) self.action_Clear.triggered.connect(self.action_Clear_cb) self.action_Stop.triggered.connect(self.action_Stop_cb) self.Infor = QAction('串口信息',self) self.menu_2.addAction(self.Infor) self.Infor.triggered.connect(self.display_cb)
class Scheduler(QObject): INTERVAL = 1 # minutes delete_old_news = pyqtSignal(object) start_recipe_fetch = pyqtSignal(object) def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.no_internet_msg = _('Cannot download news as no internet connection ' 'is active') self.no_internet_dialog = d = error_dialog(self._parent, self.no_internet_msg, _('No internet connection'), show_copy_button=False) d.setModal(False) self.recipe_model = RecipeModel() self.db = db self.lock = QMutex(QMutex.Recursive) self.download_queue = set([]) self.news_menu = QMenu() self.news_icon = QIcon(I('news.png')) self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self) self.news_menu.addAction(self.scheduler_action) self.scheduler_action.triggered[bool].connect(self.show_dialog) self.cac = QAction(QIcon(I('user_profile.png')), _('Add a custom news source'), self) self.cac.triggered[bool].connect(self.customize_feeds) self.news_menu.addAction(self.cac) self.news_menu.addSeparator() self.all_action = self.news_menu.addAction( _('Download all scheduled news sources'), self.download_all_scheduled) self.timer = QTimer(self) self.timer.start(int(self.INTERVAL * 60 * 1000)) self.timer.timeout.connect(self.check) self.oldest = gconf['oldest_news'] QTimer.singleShot(5 * 1000, self.oldest_check) def database_changed(self, db): self.db = db def oldest_check(self): if self.oldest > 0: delta = timedelta(days=self.oldest) try: ids = list(self.db.tags_older_than(_('News'), delta, must_have_authors=['calibre'])) except: # Happens if library is being switched ids = [] if ids: if ids: self.delete_old_news.emit(ids) QTimer.singleShot(60 * 60 * 1000, self.oldest_check) def show_dialog(self, *args): self.lock.lock() try: d = SchedulerDialog(self.recipe_model) d.download.connect(self.download_clicked) d.exec_() gconf['oldest_news'] = self.oldest = d.old_news.value() d.break_cycles() finally: self.lock.unlock() def customize_feeds(self, *args): from calibre.gui2.dialogs.user_profiles import UserProfiles d = UserProfiles(self._parent, self.recipe_model) try: d.exec_() d.break_cycles() finally: d.deleteLater() def do_download(self, urn): self.lock.lock() try: account_info = self.recipe_model.get_account_info(urn) customize_info = self.recipe_model.get_customize_info(urn) recipe = self.recipe_model.recipe_from_urn(urn) un = pw = None if account_info is not None: un, pw = account_info add_title_tag, custom_tags, keep_issues = customize_info script = self.recipe_model.get_recipe(urn) pt = PersistentTemporaryFile('_builtin.recipe') pt.write(script) pt.close() arg = { 'username': un, 'password': pw, 'add_title_tag':add_title_tag, 'custom_tags':custom_tags, 'recipe':pt.name, 'title':recipe.get('title',''), 'urn':urn, 'keep_issues':keep_issues } self.download_queue.add(urn) self.start_recipe_fetch.emit(arg) finally: self.lock.unlock() def recipe_downloaded(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def recipe_download_failed(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def download_clicked(self, urn): if urn is not None: return self.download(urn) for urn in self.recipe_model.scheduled_urns(): if not self.download(urn): break def download_all_scheduled(self): self.download_clicked(None) def has_internet_connection(self): if not internet_connected(): if not self.internet_connection_failed: self.internet_connection_failed = True if self._parent.is_minimized_to_tray: self._parent.status_bar.show_message(self.no_internet_msg, 5000) elif not self.no_internet_dialog.isVisible(): self.no_internet_dialog.show() return False self.internet_connection_failed = False if self.no_internet_dialog.isVisible(): self.no_internet_dialog.hide() return True def download(self, urn): self.lock.lock() if not self.has_internet_connection(): return False doit = urn not in self.download_queue self.lock.unlock() if doit: self.do_download(urn) return True def check(self): recipes = self.recipe_model.get_to_be_downloaded_recipes() for urn in recipes: if not self.download(urn): # No internet connection, we will try again in a minute break
def __init__(self, tray_icon): QThread.__init__(self) self.tray_icon = tray_icon self.mutex = QMutex()
from PyQt5.Qt import (QApplication, QWidget, QPushButton, QThread, QMutex, pyqtSignal) import sys import time qmutex_1 = QMutex() # 创建线程锁 qmutex_2 = QMutex() # 继承QThread class Thread_1(QThread): # 线程1 def __init__(self): super().__init__() def run(self): qmutex_1.lock() # 加锁 values = [1, 2, 3, 4, 5] for i in values: print(i) time.sleep(0.5) # 休眠 qmutex_1.unlock() # 解锁 class Thread_2(QThread): # 线程2 _signal = pyqtSignal() def __init__(self): super().__init__() def run(self): # qmutex_2.lock() # 加锁
class MultiplayerServerClass(NetworkPacketClass, CardDeckClass): def __init__(self, ip_port, game_rules): self.server_data = dict.copy(self.get_network_packet_definition()) self.setup_game_rules_to_server_data(game_rules) self._dealer = DealerClass(data=self.server_data) self.mutex = QMutex() self.conn_player_number = 0 self.conn_players_addresses = [0 for x in range(MAX_CLIENTS)] self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.s.bind(ip_port) except socket.error as e: str(e) self.s.listen(MAX_CLIENTS) print("Server Started... Waiting for a connection") thread = threading.Thread(target=self.server_listening_for_new_connections_loop, args=()) thread.start() def server_listening_for_new_connections_loop(self): while True: conn, addr = self.s.accept() self.conn_players_addresses[self.conn_player_number] = addr # save the connected player info print(f'SERVER: New Connection Established. Client (C{self.conn_player_number}) from {self.conn_players_addresses[CLIENT_SRV]}.') thread = threading.Thread(target=self.main_communication_loop, args=(conn, self.conn_player_number)) thread.start() self.conn_player_number += 1 print(f'SERVER: Active connections: {self.conn_player_number}. ') def main_communication_loop(self, conn, client_number): # Handshake message send_simple_message(conn, client_number) connected = True while connected: try: # We send 2 messages between client-server. # First we find the size of the dictionary we want to send, and tell the server to receive that size. # Second we send the dictionary in string format. client_data = receive_message_with_size_confirmation(conn) client_data = transform_into_data(client_data) while True: # Try to access Server Data (Thread-Safe) if self.mutex.tryLock(): # Are we still connected to this player? if client_data: self.server_data[client_number][PS_ConnectionStatus] = CONN_STATUS_CONNECTED else: self.server_data[client_number][PS_ConnectionStatus] = CONN_STATUS_DISCONNECTED # Copy the clients data onto the server data. self.server_update_from_this_player_data_fields(client_data=client_data, client_id=client_number) if client_number == CLIENT_SRV: # The server should theoretically loop through communication with all clients # So if we do the dealer logic only on player0 (DEALER) then we should theoretically # do the dealer logic only once per update to all other clients. self._dealer.dealer_evaluate_next_step() # Send the updated info back to the client: server_reply = transform_into_string(self.server_data) # Unlock the server_data_dict for other threads. self.mutex.unlock() break if connected: send_message_with_size_confirmation(conn, server_reply) print(f'SERVER: Communication done for C{client_number}.') except socket.error as e: print(f'SERVER: main_communication_loop -> {e}') send_message_with_size_confirmation(conn, MESSAGE_DISCONNECTED) self.conn_player_number -= 1 conn.close() break def setup_game_rules_to_server_data(self, rules): # 0 gameName = self._win.getGameName() # 1 startingMoney = self._win.getStartingAmount() # 2 currency = self._win.getCurrency() # 3 bigBlind = self._win.getBigBlind() # 4 blindInterval = self._win.getBlindInterval() # tpl = (gameName, startingMoney, currency, bigBlind, blindInterval) for player in range(MAX_CLIENTS): self.server_data[player][PS_MoneyAvailable] = rules[1] self.server_data[player][PS_MoneyBoughtIn] = rules[1] self.server_data[DL_GameName] = str(rules[0]) self.server_data[DL_Currency] = str(rules[2]) self.server_data[DL_BigBlind] = float(rules[3]) def server_update_from_this_player_data_fields(self, client_data, client_id): self.server_data[client_id][PC_Name] = client_data[client_id][PC_Name] self.server_data[client_id][PC_Icon] = client_data[client_id][PC_Icon] self.server_data[client_id][PC_TableSpot] = client_data[client_id][PC_TableSpot] self.server_data[client_id][PC_BuyInReq] = client_data[client_id][PC_BuyInReq] self.server_data[client_id][PC_idPlayerAction] = client_data[client_id][PC_idPlayerAction] self.server_data[client_id][PC_isPlayerPlaying] = client_data[client_id][PC_isPlayerPlaying] self.server_data[client_id][PC_BetAmount] = client_data[client_id][PC_BetAmount] self.server_data[client_id][PC_ClientOverwrite] = client_data[client_id][PC_ClientOverwrite]
class Scheduler(QObject): INTERVAL = 1 # minutes delete_old_news = pyqtSignal(object) start_recipe_fetch = pyqtSignal(object) def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.no_internet_msg = _('Cannot download news as no internet connection ' 'is active') self.no_internet_dialog = d = error_dialog(self._parent, self.no_internet_msg, _('No internet connection'), show_copy_button=False) d.setModal(False) self.recipe_model = RecipeModel() self.db = db self.lock = QMutex(QMutex.Recursive) self.download_queue = set() self.news_menu = QMenu() self.news_icon = QIcon(I('news.png')) self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self) self.news_menu.addAction(self.scheduler_action) self.scheduler_action.triggered[bool].connect(self.show_dialog) self.cac = QAction(QIcon(I('user_profile.png')), _('Add or edit a custom news source'), self) self.cac.triggered[bool].connect(self.customize_feeds) self.news_menu.addAction(self.cac) self.news_menu.addSeparator() self.all_action = self.news_menu.addAction( _('Download all scheduled news sources'), self.download_all_scheduled) self.timer = QTimer(self) self.timer.start(int(self.INTERVAL * 60 * 1000)) self.timer.timeout.connect(self.check) self.oldest = gconf['oldest_news'] QTimer.singleShot(5 * 1000, self.oldest_check) def database_changed(self, db): self.db = db def oldest_check(self): if self.oldest > 0: delta = timedelta(days=self.oldest) try: ids = list(self.db.tags_older_than(_('News'), delta, must_have_authors=['calibre'])) except: # Happens if library is being switched ids = [] if ids: if ids: self.delete_old_news.emit(ids) QTimer.singleShot(60 * 60 * 1000, self.oldest_check) def show_dialog(self, *args): self.lock.lock() try: d = SchedulerDialog(self.recipe_model) d.download.connect(self.download_clicked) d.exec_() gconf['oldest_news'] = self.oldest = d.old_news.value() d.break_cycles() finally: self.lock.unlock() def customize_feeds(self, *args): from calibre.gui2.dialogs.custom_recipes import CustomRecipes d = CustomRecipes(self.recipe_model, self._parent) try: d.exec_() finally: d.deleteLater() def do_download(self, urn): self.lock.lock() try: account_info = self.recipe_model.get_account_info(urn) customize_info = self.recipe_model.get_customize_info(urn) recipe = self.recipe_model.recipe_from_urn(urn) un = pw = None if account_info is not None: un, pw = account_info add_title_tag, custom_tags, keep_issues = customize_info arg = { 'username': un, 'password': pw, 'add_title_tag':add_title_tag, 'custom_tags':custom_tags, 'title':recipe.get('title',''), 'urn':urn, 'keep_issues':keep_issues } self.download_queue.add(urn) self.start_recipe_fetch.emit(arg) finally: self.lock.unlock() def recipe_downloaded(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def recipe_download_failed(self, arg): self.lock.lock() try: self.recipe_model.update_last_downloaded(arg['urn']) self.download_queue.remove(arg['urn']) finally: self.lock.unlock() def download_clicked(self, urn): if urn is not None: return self.download(urn) for urn in self.recipe_model.scheduled_urns(): if not self.download(urn): break def download_all_scheduled(self): self.download_clicked(None) def has_internet_connection(self): if not internet_connected(): if not self.internet_connection_failed: self.internet_connection_failed = True if self._parent.is_minimized_to_tray: self._parent.status_bar.show_message(self.no_internet_msg, 5000) elif not self.no_internet_dialog.isVisible(): self.no_internet_dialog.show() return False self.internet_connection_failed = False if self.no_internet_dialog.isVisible(): self.no_internet_dialog.hide() return True def download(self, urn): self.lock.lock() if not self.has_internet_connection(): return False doit = urn not in self.download_queue self.lock.unlock() if doit: self.do_download(urn) return True def check(self): recipes = self.recipe_model.get_to_be_downloaded_recipes() for urn in recipes: if not self.download(urn): # No internet connection, we will try again in a minute break
from oil_hmi_pro_ui import * from save_states import create_group_state # QT相关 from PyQt5.Qt import QMutex, pyqtSignal from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget from PyQt5.QtGui import QIcon fake = False # 虚拟执行标志 """ python中内置数据类型(int、list、dict)的操作都是原子的,多线程读写不需要加锁 """ # 互斥锁 command_arr_mutex = QMutex() # 发送给Oil_driver的控制指令 command_arr = Int32MultiArray() # ROS中自定义的数据类型,保险起见,对其读写加锁 command_cnt = 4 command_arr.data = [0]*command_cnt # 0:使能 1:复位 2:置零 3:急停, PubThread及主线程按钮函数均会写,须加锁 joint_ctl_arr = [0]*7 # 关节控制标志位, 可弃用 vel_scaling = 0.0 # 速度调整比例 movej_rad_deg_flag = 1 # 角度显示单位切换标志, 默认为角度 movel_rad_deg_flag = 1 # 角度显示单位切换标志, 默认为角度 movel_m_cm_flag = 1 # 距离显示单位切换标志, 默认为米 curr_joints = [0.0]*7 # 当前关节角 goal_joints = [0.0]*7 # 目标关节角 curr_pose = [0.0]*7 # 当前位置
class OpenGLView(ZOpenGLView): def __init__(self, parent=None): super(ZOpenGLView, self).__init__(parent) self.parent = parent self.timerThread = None self.renderingInterval = 30 self.mutex = QMutex() def initializeGL(self): self.angles = [0.0] * NUMBER_OF_PLANETS for i in range(NUMBER_OF_PLANETS): self.angles[i] = 30.0 * i self.sun = None self.planets = [None] * NUMBER_OF_PLANETS self.orbits = [None] * NUMBER_OF_PLANETS black = [0.0, 0.0, 0.0, 1.0] ambient = [0.5, 0.5, 0.5, 1.0] diffuse = [0.2, 0.4, 0.8, 1.0] greendiffuse = [0.0, 1.0, 0.0, 1.0] reddiffuse = [1.0, 0.0, 0.0, 1.0] bluediffuse = [0.0, 0.0, 1.0, 1.0] silverdiffuse = [0.8, 0.8, 0.8, 1.0] specular = [1.0, 1.0, 1.0, 1.0] emission = [0.8, 0.2, 0.0, 0.0] lowShining = [10.0] highShining = [100.0] sunMateria = ZOpenGLMateria(GL_FRONT, black, diffuse, black, emission, highShining) self.sun = ZOpenGLSolidSphere(sunMateria, 0.5, 40, 40) self.orbits[0] = ZOpenGLCircle(0.0, 0.0, 0.0, 1.0) self.orbits[1] = ZOpenGLCircle(0.0, 0.0, 0.0, 1.6) self.orbits[2] = ZOpenGLCircle(0.0, 0.0, 0.0, 2.4) self.orbits[3] = ZOpenGLCircle(0.0, 0.0, 0.0, 2.9) materia = [None] * NUMBER_OF_PLANETS materia[0] = ZOpenGLMateria(GL_FRONT, ambient, bluediffuse, specular, black, lowShining) materia[1] = ZOpenGLMateria(GL_FRONT, ambient, silverdiffuse, specular, black, lowShining) materia[2] = ZOpenGLMateria(GL_FRONT, ambient, greendiffuse, specular, black, lowShining) materia[3] = ZOpenGLMateria(GL_FRONT, ambient, reddiffuse, specular, black, lowShining) self.planets[0] = ZOpenGLSolidSphere(materia[0], 0.10, 20, 20) self.planets[1] = ZOpenGLSolidSphere(materia[1], 0.18, 20, 20) self.planets[2] = ZOpenGLSolidSphere(materia[2], 0.18, 20, 20) self.planets[3] = ZOpenGLSolidSphere(materia[3], 0.12, 20, 20) self.timerThread = ZOpenGLTimerThread(self, self.renderingInterval) self.timerThread.start() def paintGL(self): self.mutex.lock() for i in range(NUMBER_OF_PLANETS): if (self.angles[i] < CIRCLE_ANGLE - INCREMENT[i]): self.angles[i] += INCREMENT[i] else: self.angles[i] = INCREMENT[i] glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() gluLookAt(-1.0, 8.0, 17.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glColor(1.0, 1.0, 1.0) glTranslate(0, 0, 0) self.sun.draw() # 0.0, 0.0, 0.0) light = ZOpenGLLight(GL_LIGHT0) lightPosition = [-2.0, 0.0, -1.0, 1.0] light.positionv(lightPosition) for i in range(NUMBER_OF_PLANETS): pos = self.orbits[i].getOrbitPosition(int(self.angles[i])) glPushMatrix() glTranslate(pos[0], pos[1], pos[2]) self.planets[i].draw() glPopMatrix() self.mutex.unlock() def resizeGL(self, w, h): if (w == 0 or h == 0): return glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(16.0, w / h, 0.5, 40.0) glMatrixMode(GL_MODELVIEW)
class RocketSimulator(QtCore.QObject): R_EARTH = 6371000 # meters G_0 = -9.80665 # m/s^2 (at sea level) new_data = QtCore.pyqtSignal(object) def __init__(self, ticksize, param_file='parameters.json'): QtCore.QObject.__init__(self) self.load_data(param_file) def load_data(self, param_file): with open(param_file, 'r') as inputf: self.parameters = json.load(inputf) # Set imported parameters as properties for parameter in self.parameters: setattr(self, parameter, self.parameters[parameter]) # use for threadsafe commnications with the GUI thread self.mutex = QMutex() self.atmosphere = Atmosphere() # TODO Error analysis vs. ticksize self.ticksize = 0.001 self.time = 0 self.height = self.launch_height self.velocity = 0 self.acceleration = 0 self.max_height = 0 self.max_velocity = 0 self.max_acceleration = 0 self.mass = self.launch_mass self.thruster = Thruster() self.data = {} self.data['time'] = [] self.data['height'] = [] self.data['velocity'] = [] self.data['acceleration'] = [] def run_simulation(self): while self.height >= self.launch_height: self.run_tick() print(self.max_height, self.max_velocity, self.max_acceleration) def run_tick(self): self.height += self.velocity * self.ticksize self.velocity += self.acceleration * self.ticksize force = self.thrust_force() + self.drag_force() + self.gravity_force() self.acceleration = force / self.mass locked = False if self.mutex.tryLock(10): self.new_data.emit([self.time, self.height, self.velocity, self.acceleration]) self.mutex.unlock() self.data['time'].append(self.time) self.data['height'].append(self.height) self.data['velocity'].append(self.velocity) self.data['acceleration'].append(self.acceleration) self.update_mass() self.update_max_values() self.time += self.ticksize def drag_force(self): pressure = self.atmosphere.get_density_by_height(self.height) # Rocket is heading up if self.velocity >= 0: drag_coef = self.rocket_drag_coef area = self.cross_sectional_area # Rocket is falling with parachute deployed else: drag_coef = self.parachute_drag_coef area = self.parachute_area # Drag force is the opposite direction of velocity if self.velocity > 0: direction = -1 else: direction = 1 # TODO use increased parachute area return (direction * drag_coef * pressure * self.velocity**2 * area ) / 2 def gravity_force(self): return self.mass * self.get_g_at_alitude(self.height) def get_g_at_alitude(self, height): return self.G_0 * ((height + self.R_EARTH) / self.R_EARTH)**2 def thrust_force(self): if self.time < self.burn_length: return self.thruster.get_thrust_at_time(self.time) else: return 0 def update_mass(self): if self.time > self.burn_length: return else: self.mass -= (self.propellent_mass / self.burn_length) * self.ticksize def update_max_values(self): if self.height > self.max_height: self.max_height = self.height if self.velocity > self.max_velocity: self.max_velocity = self.velocity if self.acceleration > self.max_acceleration: self.max_acceleration = self.acceleration
from PyQt5.Qt import (QApplication, QWidget, QPushButton, QThread, QMutex, pyqtSignal) import sys import time qmut_1 = QMutex() # 创建线程锁 qmut_2 = QMutex() # 继承QThread class Thread_1(QThread): # 线程1 def __init__(self): super().__init__() def run(self): qmut_1.lock() # 加锁 values = [1, 2, 3, 4, 5] for i in values: print(i) time.sleep(0.5) # 休眠 qmut_1.unlock() # 解锁 class MyWin(QWidget): def __init__(self): super().__init__() # 按钮初始化 self.btn_1 = QPushButton('按钮1', self) self.btn_1.move(120, 80) self.btn_1.clicked.connect(self.click_1) # 绑定槽函数
class AppWindow(QDialog): @staticmethod def error_window(txt='Unknown Error!'): msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error") msg.setInformativeText(txt) msg.setWindowTitle("Error") msg.exec_() def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.canvasMutex = QMutex( ) # protects canvas (probably redundant since I don't use workers) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.draw_step) # connect actions self.ui.drawPushButton.clicked.connect(self.redraw_background) self.ui.startPushButton.clicked.connect(self.start_presentation) self.ui.stopPushButton.clicked.connect(self.timer.stop) self.ui.stepPushButton.clicked.connect(self.on_step_pushed) self.ui.functionEdit.textChanged.connect(self.set_redraw_needed) self.ui.x0DoubleSpinBox.valueChanged.connect(self.set_redraw_needed) self.ui.leftIntervalSpinBox.valueChanged.connect( self.set_redraw_needed) self.ui.rightIntervalSpinBox.valueChanged.connect( self.set_redraw_needed) self.ui.xyCheckBox.clicked.connect(self.set_redraw_needed) self.eps = 1e-15 self.itTBD = 0 self.xx = None # x axes - linspace from left self.gx = None # lambda function g(x) self.xc = None # current value of x self.redraw = True # indicates that old values are no longer valid! self.show() def set_redraw_needed(self): self.redraw = True def start_presentation(self): if not self.redraw_background(): return self.itTBD = self.ui.iterationSpinBox.value() self.timer.start(int(self.ui.delaySpinBox.value() * 1000)) def on_step_pushed(self): if self.redraw and not self.redraw_background(): return self.itTBD = 1 self.draw_step() # should only be called by draw_step() def reset_drawing(self): self.timer.stop() self.itTBD = 0 self.canvasMutex.unlock() # draws one iteration on graph def draw_step(self): if self.canvasMutex.tryLock(): if self.itTBD < 1: self.reset_drawing() return nxc = self.gx(self.xc) # value of g(x_{n+1}) if abs(self.xc - nxc) < self.eps: print('I am unable to reach better precision so I\'ll stop.') self.reset_drawing() return if nxc < self.ui.leftIntervalSpinBox.value( ) or nxc > self.ui.rightIntervalSpinBox.value(): self.error_window('Out of interval!') self.reset_drawing() return # self.gx(nxc) may reach value out of interval but only on y-axis # I could also remember its value so I don't have to compute it in next iteration # but it is so cheap that I don't care self.ui.myMplCanvas.axes.plot([self.xc, nxc, nxc], [nxc, nxc, self.gx(nxc)], r'r--', linewidth=0.75) self.ui.myMplCanvas.draw() self.xc = nxc self.itTBD -= 1 self.ui.xValueLabel.setText('Current value of x is: %.6f' % self.xc) self.canvasMutex.unlock() def redraw_background(self): self.gx = lambda x: eval(self.ui.functionEdit.text()) self.xc = self.ui.x0DoubleSpinBox.value() li = self.ui.leftIntervalSpinBox.value() ri = self.ui.rightIntervalSpinBox.value() if li >= ri or self.xc < li or self.xc > ri: self.error_window('Invalid interval!') return False self.xx = np.linspace(self.ui.leftIntervalSpinBox.value(), self.ui.rightIntervalSpinBox.value(), 10000) try: yy = self.gx(self.xx) except SyntaxError: self.error_window('Unable to parse g(x)!') return False if self.canvasMutex.tryLock(): self.ui.myMplCanvas.clear() self.ui.myMplCanvas.axes.plot(self.xx, yy, label='g(x)') if self.ui.xyCheckBox.isChecked(): self.ui.myMplCanvas.axes.plot(self.xx, self.xx, label='y = x') self.ui.myMplCanvas.draw() self.redraw = False self.canvasMutex.unlock() return True
self.flag_time_edit.text()) self.close() def dele_staff(self): temp = "<font size='9'>是否删除id为" + self.dele_staff_edit.text( ) + "的员工</font>" message = QMessageBox.warning(self, "警告", temp, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if message == QMessageBox.Yes: delete_data(int(self.dele_staff_edit.text())) elif message == QMessageBox.No: self.dele_staff_edit.clear() lock = QMutex() # 创建进程锁 class ThreadIntoDB(QThread): def __init__(self, idn=None, parent=None): super().__init__(parent) self.id = idn def run(self): lock.lock() pics = os.listdir(Path_face + self.id) feature_list = [] feature_average = [] for i in range(len(pics)): pic_path = Path_face + self.id + "/" + pics[i] print("读取成功:", pic_path)
class Lslrecorder: def __init__(self): self.mutex = QMutex() self.timeStamps = None self.stream = None self.inlet = None self.info = None self.channelCount = None self.doRec = False self.srate = None self.data = None self.bufferUpdateThread = None def findStream(self, hostname=None, timeout=1): # Gather lsl stream and create respective inlet and buffer, returns channelcount of that stream print("Searching for streams with a timeout of " + str(timeout) + " seconds") streams = resolve_stream(timeout) if len(streams) < 1: print("No stream found - exiting") return -1 else: print("Found " + str(len(streams)) + " streams") if hostname is None: print( "No stream hostname has been specified - selecting first stream" ) self.stream = streams[0] else: for stream in streams: if stream.hostname() == hostname: self.stream = stream print("Selected stream with hostname " + str(hostname)) break if self.stream is None: print("No stream with hostname " + str(hostname) + " has been found - exiting") self.inlet = StreamInlet(self.stream) self.info = self.inlet.info() self.channelCount = self.info.channel_count() self.srate = self.info.nominal_srate() self.data = np.empty((0, self.channelCount)) try: self.offset = self.inlet.time_correction(timeout=3) print("Offset: " + str(self.offset)) except TimeoutError: self.offset = 0 print("Offset Retrieval Timed Out") #print("Stream Meta Info:") #print(self.info.as_xml()) return self.channelCount def startRec(self): # Create and Start buffer update thread as daemon so that it gets terminated automatically when program exits self.doRec = True self.bufferUpdateThread = Thread(target=self.grabData, args=()) self.bufferUpdateThread.daemon = True self.bufferUpdateThread.start() def stopRec(self): self.doRec = False self.bufferUpdateThread.join() print("Stopped recording") def grabData(self): print("Starting recording") while self.doRec: c, t = self.inlet.pull_chunk(timeout=0.0) if c: # add offset to timestamps and transform timestamps to ms and round to int tmp_t = np.array([int((ts + self.offset) * 1000) for ts in t]) self.mutex.lock() self.data = np.concatenate((self.data, c), axis=0) if self.timeStamps is None: self.timeStamps = np.array(tmp_t) else: self.timeStamps = np.concatenate((self.timeStamps, tmp_t)) self.mutex.unlock()
} Range = [ 0.002, 0.00632, 0.02, 0.0632, 0.2, 0.632, 2, 6.32, 20, 63.2, 200, 632, 2000, 6320, 20000, 63200, 200000, 632000, 2000000, 6320000, 20000000, 63200000 ] def find_n_sub_str(src, sub, pos, start): index = src.find(sub, start) if index != -1 and pos > 0: return find_n_sub_str(src, sub, pos - 1, index + 1) return index mutex = QMutex() class Write(QObject): signal_begin = pyqtSignal(str) def __init__(self, rest): QObject().__init__(self) self.mutex = QMutex() def WriteCMD(self, command): self.mutex.lock() print("Command: " + command) BridgeSerial.write(str.encode(command)) readline = BridgeSerial.readline() if command.startswith('RDGRNG '):
self.display.setText("请选择文件!") else: self.write_sign = auto_w.Read(self.docx_in.text()) self.write_sign.str_out.connect(self.display_out) self.write_sign.start() @pyqtSlot(str) def prompt_out(self, i): self.prompt.setText(i) @pyqtSlot(str) def display_out(self, i): self.display.setText(i) lock = QMutex() class ThreadRW(QThread): str_out = pyqtSignal(str) def __init__(self, wfile=None, item=None, parent=None): super().__init__(parent) self.W_file = wfile # word文件名 self.Item = item # 类型选项 self.number = 0 # 记录差 self.num = 0 # 列表下表值 self.t_number = 5 # 表格index self.t_number_copy = 0 # 复制表格index self.t_rows = 1 # 表格的行index self.example_name = [] # 用例名称
def __init__(self, rest): QObject().__init__(self) self.mutex = QMutex()
class OpenGLView(ZOpenGLView): CIRCLE_ANGLE = 360 INCREMENT = 2 def __init__(self, parent=None): super(ZOpenGLView, self).__init__(parent) self.parent = parent self.angle = 0 self.timerThread = None self.renderingInterval = 40 self.mutex = QMutex() def initializeGL(self): self.quadric = ZOpenGLQuadric() self.quadric.drawStyle(GLU_FILL) self.quadric.normals(GLU_SMOOTH) self.sphere = ZOpenGLSphere(self.quadric, None, 0.5, 40, 40) self.circle = ZOpenGLCircle(0.0, 0.0, 0.0, 1.3) self.timerThread = ZOpenGLTimerThread(self, self.renderingInterval) self.timerThread.start() def paintGL(self): self.mutex.lock() if (self.angle < (self.CIRCLE_ANGLE - self.INCREMENT)): self.angle += self.INCREMENT else: self.angle = self.INCREMENT if (self.sphere != None): pos = self.circle.getOrbitPosition(self.angle) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() gluLookAt(-5.0, 10.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glTranslate(0.0, 0.0, 0.0) glColor(1.0, 1.0, 1.0) #green self.circle.draw() glTranslate(pos[0], pos[1], pos[2]) light = ZOpenGLLight(GL_LIGHT0) lightPosition = [-2.0, 0.0, -1.0, 1.0] light.positionv(lightPosition) white = [1.0, 1.0, 1.0, 1.0] blue = [0.0, 0.0, 1.0, 1.0] green = [0.0, 1.0, 0.0, 1.0] shininess = 100.0 material = ZOpenGLMaterial(GL_FRONT) material.diffusev(green) material.specularv(white) material.shininess(shininess) self.sphere.draw() self.mutex.unlock() def resizeGL(self, width, height): if width == 0 or height == 0: return glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(16.0, width / height, 0.5, 40.0) glMatrixMode(GL_MODELVIEW)