class ProducerConsumer(unittest.TestCase): '''Basic test case for producer-consumer QThread''' def setUp(self): #Create fixtures self.app = QCoreApplication([]) def tearDown(self): #Destroy fixtures del self.app def finishCb(self): #Quits the application self.app.exit(0) def testProdCon(self): #QThread producer-consumer example bucket = Bucket() prod = Producer(bucket) cons = Consumer(bucket) prod.start() cons.start() QObject.connect(prod, SIGNAL('finished()'), self.finishCb) QObject.connect(cons, SIGNAL('finished()'), self.finishCb) self.app.exec_() prod.wait() cons.wait() self.assertEqual(prod.production_list, cons.consumption_list)
def main(): parser = OptionParser(description='A chat client/server') parser.add_option('-s', '--server', help='Start a server. If not ' 'given, a client will be started', action='store_true') opts, args = parser.parse_args() if opts.server: from PySide.QtCore import QCoreApplication app = QCoreApplication(sys.argv) # spawn a server server = ChatServer() listening = server.listen(HOST_ADDRESS, PORT) if not listening: # a server error print('Server start failed: {}'.format(server.errorString()), file=sys.stderr) server.serverShutdown.connect(app.quit) # print everything received by the server to standard output server.textReceived.connect(partial(print, '>>')) else: app = QApplication(sys.argv) chat_window = ChatWindow() chat_window.show() app.exec_()
def main(): parser = OptionParser( description='A chat client/server') parser.add_option('-s', '--server', help='Start a server. If not ' 'given, a client will be started', action='store_true') opts, args = parser.parse_args() if opts.server: from PySide.QtCore import QCoreApplication app = QCoreApplication(sys.argv) # spawn a server server = ChatServer() listening = server.listen(HOST_ADDRESS, PORT) if not listening: # a server error print('Server start failed: {}'.format(server.errorString()), file=sys.stderr) server.serverShutdown.connect(app.quit) # print everything received by the server to standard output server.textReceived.connect(partial(print, '>>')) else: app = QApplication(sys.argv) chat_window = ChatWindow() chat_window.show() app.exec_()
def main(): app = QCoreApplication(sys.argv) context = Context() monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='input') observer = QUDevMonitorObserver(monitor) observer.deviceAdded.connect( partial(print_mouse_status, status_message="added")) observer.deviceRemoved.connect( partial(print_mouse_status, status_message="removed")) monitor.start() app.exec_()
def testEmitOutsideThread(self): global thread_run app = QCoreApplication([]) source = Source() thread = ThreadJustConnects(source) QObject.connect(thread, SIGNAL('finished()'), lambda: app.exit(0)) thread.start() while not thread_run: pass source.emit_sig() app.exec_() thread.wait() self.assert_(thread.target.called)
class HttpSignalsCase(unittest.TestCase): '''Test case for bug #124 - readDatagram signature QUdpSocket.readDatagram must return a tuple with the datagram, host and port, while receiving only the max payload size.''' def setUp(self): #Acquire resources self.called = False self.app = QCoreApplication([]) self.socket = QUdpSocket() self.server = QUdpSocket() self.server.bind(QHostAddress(QHostAddress.LocalHost), 45454) def tearDown(self): #Release resources del self.socket del self.server del self.app def sendPackage(self): addr = QHostAddress(QHostAddress.LocalHost) self.socket.writeDatagram('datagram', addr, 45454) def callback(self): while self.server.hasPendingDatagrams(): datagram, host, port = self.server.readDatagram(self.server.pendingDatagramSize()) self.called = True self.app.quit() def testDefaultArgs(self): #QUdpSocket.readDatagram pythonic return # @bug 124 QObject.connect(self.server, SIGNAL('readyRead()'), self.callback) self.sendPackage() self.app.exec_() self.assert_(self.called)
class HttpSignalsCase(unittest.TestCase): '''Test case for bug #124 - readDatagram signature QUdpSocket.readDatagram must return a tuple with the datagram, host and port, while receiving only the max payload size.''' def setUp(self): #Acquire resources self.called = False self.app = QCoreApplication([]) self.socket = QUdpSocket() self.server = QUdpSocket() self.server.bind(QHostAddress(QHostAddress.LocalHost), 45454) def tearDown(self): #Release resources del self.socket del self.server del self.app def sendPackage(self): addr = QHostAddress(QHostAddress.LocalHost) self.socket.writeDatagram('datagram', addr, 45454) def callback(self): while self.server.hasPendingDatagrams(): datagram, host, port = self.server.readDatagram( self.server.pendingDatagramSize()) self.called = True self.app.quit() def testDefaultArgs(self): #QUdpSocket.readDatagram pythonic return # @bug 124 QObject.connect(self.server, SIGNAL('readyRead()'), self.callback) self.sendPackage() self.app.exec_() self.assert_(self.called)
t = translate(s, to=to, fr=fr) print t print type(t) #session = requests #with SkProfiler(): # for i in range(10): # t = translate(s, to=to, fr=fr) #print t app.quit() from PySide.QtCore import QCoreApplication, QTimer app = QCoreApplication(sys.argv) QTimer.singleShot(0, test) app.exec_() # EOF #import urllib, urllib2 #url = createUrl(text, to=INFOSEEK_LCODE[to], fr=INFOSEEK_LCODE[fr]) #try: # # See: http://stackoverflow.com/questions/3465704/python-urllib2-urlerror-http-status-code # response = urllib2.urlopen(url) # ret = response.read() #except urllib2.HTTPError, e: # dwarn("http error code =", e.code) # return "" #except urllib2.URLError, e: # dwarn("url error args =", e.args) # return ""
class StatusNetHandler(dbus.service.Object): def __init__(self): dbus_main_loop = dbus.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus(dbus_main_loop) bus_name = dbus.service.BusName("com.mikeasoft.statusnet", bus=session_bus) dbus.service.Object.__init__(self, object_path="/synchronize", bus_name=bus_name) self.app = QCoreApplication(sys.argv) signal.signal(signal.SIGINT, signal.SIG_DFL) self.client = gconf.client_get_default() self.api_path = self.client.get_string( '/apps/ControlPanel/Statusnet/api_path') self.latest = self.client.get_int( '/apps/ControlPanel/Statusnet/latest') self.eventService = EventFeedService('statusnet', 'StatusNet') self.eventService.local_name = "com.mikeasoft.statusnet.eventcallback" self.eventService.DEFAULT_INTF = "com.mikeasoft.statusnet.eventcallback" if not self.api_path: return self.cacheDir = QDesktopServices.storageLocation( QDesktopServices.CacheLocation) if not os.path.exists(self.cacheDir): os.mkdir(self.cacheDir) sys.exit(self.app.exec_()) def login(self): if self.api_path in oauth_consumer_keys: key = oauth_consumer_keys[self.api_path] secret = oauth_consumer_secrets[self.api_path] oauth_token = self.client.get_string( "/apps/ControlPanel/Statusnet/oauth_token") oauth_token_secret = self.client.get_string( "/apps/ControlPanel/Statusnet/oauth_token_secret") self.statusNet = StatusNet(self.api_path, auth_type="oauth", consumer_key=key, consumer_secret=secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) else: username = self.client.get_string( '/apps/ControlPanel/Statusnet/username') password = self.client.get_string( '/apps/ControlPanel/Statusnet/password') self.statusNet = StatusNet(self.api_path, username, password) @dbus.service.method("com.mikeasoft.statusnet") def refresh(self): thread = threading.Thread(target=self.updateTimeline) thread.start() def updateTimeline(self): self.login() statuses = self.statusNet.statuses_home_timeline(self.latest) if len(statuses) > 0: self.client.set_int('/apps/ControlPanel/Statusnet/latest', statuses[0]['id']) for status in statuses: self.showStatus(status) self.app.exit() def showStatus(self, status): if status['text'] == None: # HTML only message return icon = statusnetutils.getAvatar(status['user']['profile_image_url'], self.cacheDir) title = "%s on StatusNet" % status['user']['name'] creationtime = statusnetutils.getTime(status['created_at']) item = EventFeedItem(icon, title, creationtime) item.set_body(status['text']) item.set_action_data(status['id'], status['statusnet_conversation_id']) self.eventService.add_item(item)
c.waitForDataReceived() t = '1' * 100 #print t c.sendDataLater(t, interval) t = '2' * 100 #print t c.sendDataLater(t, interval) t = '3' * 100 #print t c.sendDataLater(t, interval) t = '4' * 100 #print t c.sendDataLater(t, interval) t = '5' * 100 #print t c.sendDataLater(t, interval) print c.isActive() #t = '1' * 100 #ok = c.sendData(t) #print ok c.disconnected.connect(app.quit) #c.dumpSocketInfo() sys.exit(app.exec_()) # EOF
def main(): app = QCoreApplication(sys.argv) server = Server() signal.signal(signal.SIGINT, exit_handler) return app.exec_()
class StatusNetHandler(dbus.service.Object): def __init__(self): dbus_main_loop = dbus.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus(dbus_main_loop) bus_name = dbus.service.BusName("com.mikeasoft.statusnet", bus=session_bus) dbus.service.Object.__init__(self, object_path="/synchronize", bus_name=bus_name) self.app = QCoreApplication(sys.argv) signal.signal(signal.SIGINT, signal.SIG_DFL) self.client = gconf.client_get_default() self.api_path = self.client.get_string('/apps/ControlPanel/Statusnet/api_path') self.latest = self.client.get_int('/apps/ControlPanel/Statusnet/latest') self.eventService = EventFeedService('statusnet', 'StatusNet') self.eventService.local_name = "com.mikeasoft.statusnet.eventcallback" self.eventService.DEFAULT_INTF = "com.mikeasoft.statusnet.eventcallback" if not self.api_path: return self.cacheDir = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) if not os.path.exists(self.cacheDir): os.mkdir(self.cacheDir) sys.exit(self.app.exec_()) def login(self): if self.api_path in oauth_consumer_keys: key = oauth_consumer_keys[self.api_path] secret = oauth_consumer_secrets[self.api_path] oauth_token = self.client.get_string("/apps/ControlPanel/Statusnet/oauth_token") oauth_token_secret = self.client.get_string("/apps/ControlPanel/Statusnet/oauth_token_secret") self.statusNet = StatusNet(self.api_path, auth_type="oauth", consumer_key=key, consumer_secret=secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) else: username = self.client.get_string('/apps/ControlPanel/Statusnet/username') password = self.client.get_string('/apps/ControlPanel/Statusnet/password') self.statusNet = StatusNet(self.api_path, username, password) @dbus.service.method("com.mikeasoft.statusnet") def refresh(self): thread = threading.Thread(target=self.updateTimeline) thread.start() def updateTimeline(self): self.login() statuses = self.statusNet.statuses_home_timeline(self.latest) if len(statuses) > 0: self.client.set_int('/apps/ControlPanel/Statusnet/latest', statuses[0]['id']) for status in statuses: self.showStatus(status) self.app.exit() def showStatus(self, status): if status['text'] == None: # HTML only message return icon = statusnetutils.getAvatar(status['user']['profile_image_url'], self.cacheDir) title = "%s on StatusNet" % status['user']['name'] creationtime = statusnetutils.getTime(status['created_at']) item = EventFeedItem(icon, title, creationtime) item.set_body(status['text']) item.set_action_data(status['id'], status['statusnet_conversation_id']) self.eventService.add_item(item)
class QtMobility(PositionSource): def __init__(self, location): PositionSource.__init__(self, location) self.qtApplication = None # used for headless location support # connect to QT Mobility position source self.source = None # self.satelliteSource = QGeoSatelliteInfoSource.createDefaultSource(None) self.satsInViewCount = None self.satsInUseCount = None # if self.satelliteSource is not None: ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInViewUpdateCB) ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInUseUpdateCB) # print("location Qt Mobility: satellite info source created") # else: # print("location Qt Mobility: satellite info source creation failed") def start(self, startMainLoop=False): if startMainLoop: from PySide.QtCore import QCoreApplication self.qtApplication = QCoreApplication(sys.argv) # we import QGeoPositionInfoSource after the Qt Application is # created to get rid of the: # " # QDBusConnection: system D-Bus connection created before QCoreApplication. Application may misbehave. # QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave. # " # warnings from QtMobility.Location import QGeoPositionInfoSource self.source = QGeoPositionInfoSource.createDefaultSource(None) if self.source is not None: self.source.positionUpdated.connect(self._positionUpdateCB) print("location Qt Mobility: position source created") # TODO: custom interval setting self.source.setUpdateInterval(1000) self.source.startUpdates() print("location qt mobility: started") # only start the mainloop if the source was created successfully, # otherwise it would never end as the signal provided by the source, # that stops the main lopp, would never be triggered if startMainLoop: print("location qt mobility: starting headless mainloop") self.qtApplication.exec_() else: print("location Qt Mobility: source creation failed") # if self.satelliteSource: # print(self.satelliteSource.availableSources()) # self.satelliteSource.startUpdates() # print("location qt mobility: sat source started") def stop(self): print("location qt mobility: stopping") if self.source: self.source.stopUpdates() print("location qt mobility: stopped") if self.qtApplication: print("location qt mobility: stopping headless mainloop") self.qtApplication.exit() # if self.satelliteSource: # self.satelliteSource.stopUpdates() # print("location qt mobility: sat source stopped") def canSetUpdateInterval(self): return True def setUpdateInterval(self, interval): if self.source: self.source.setUpdateInterval(interval) def getFix(self): return self.fix # def _satsInViewUpdateCB(self, satellites=None): # """update the count of visible GPS satellites""" # if satellites is not None: # self.satsInViewCount = len(satellites) # # def _satsInUseUpdateCB(self, satellites=None): # """update the count of GPS satellites in use to # determine the current position""" # if satellites is not None: # self.satsInUseCount = len(satellites) def _positionUpdateCB(self, update): direction = update.attribute(update.Direction) speed = update.attribute(update.GroundSpeed) mode = 3 # 3d fix if update.coordinate().isValid(): if update.coordinate().CoordinateType == update.coordinate().Coordinate2D: mode = 2 # 2D fix else: mode = 0 # no fix if direction == -1.0: direction = 0 if speed == -1.0: speed = 0 fix = Fix((update.coordinate().latitude(), update.coordinate().longitude()), update.coordinate().altitude(), direction, speed, mode=mode, magnetic_variation=update.attribute(update.MagneticVariation), sats=self.satsInViewCount, sats_in_use=self.satsInUseCount, horizontal_accuracy=update.attribute(update.HorizontalAccuracy), vertical_accuracy=update.attribute(update.VerticalAccuracy) ) # print debug message if enabled # self.debug = True if self.debug: print("Qt-Mobility POS DEBUG") print("%s, %s" % (update.coordinate().latitude(), update.coordinate().longitude())) print(update) # trigger update in the location module self.location.updatePosition(fix) self.fix = fix
if __name__ == "__main__": app = QCoreApplication(sys.argv) manager = MNotificationManager('wazapp_notify','Wazapp Notify'); #group = MNotificationGroup(MNotification.ImReceivedEvent,"Message from Reem","tikoooooooooooo"); #group.manager = manager; #group.setImage('/usr/share/icons/hicolor/80x80/apps/waxmppplugin80.png'); #print group.publish(); n = MNotification(MNotification.MessageArrivedEvent,"Reem", "Ezayak?"); n.manager = manager; #n.setAction(sayHello); n.setImage('/usr/share/icons/hicolor/80x80/apps/waxmppplugin80.png'); #n.setGroup(group); res = n.publish(); print res; ''' n.setSummary("CHANGED"); print n.publish(); ''' #n.addNotification(0,MNotification.ImReceivedEvent,"THIS IS SUMMARY", "THIS IS BODY", "NONE", "NONE", 1); app.exec_()
class QtMobility(PositionSource): def __init__(self, location): PositionSource.__init__(self, location) self.qtApplication = None # used for headless location support # connect to QT Mobility position source self.source = None # self.satelliteSource = QGeoSatelliteInfoSource.createDefaultSource(None) self.satsInViewCount = None self.satsInUseCount = None # if self.satelliteSource is not None: ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInViewUpdateCB) ## self.satelliteSource.satellitesInViewUpdated.connect(self._satsInUseUpdateCB) # log.info("location Qt Mobility: satellite info source created") # else: # log.error("location Qt Mobility: satellite info source creation failed") def start(self, startMainLoop=False): if startMainLoop: from PySide.QtCore import QCoreApplication self.qtApplication = QCoreApplication(sys.argv) # we import QGeoPositionInfoSource after the Qt Application is # created to get rid of the: # " # QDBusConnection: system D-Bus connection created before QCoreApplication. Application may misbehave. # QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave. # " # warnings from QtMobility.Location import QGeoPositionInfoSource self.source = QGeoPositionInfoSource.createDefaultSource(None) if self.source is not None: self.source.positionUpdated.connect(self._positionUpdateCB) log.info("position source created") # TODO: custom interval setting self.source.setUpdateInterval(1000) self.source.startUpdates() log.info("started") # only start the mainloop if the source was created successfully, # otherwise it would never end as the signal provided by the source, # that stops the main loop, would never be triggered if startMainLoop: log.info("starting headless mainloop") self.qtApplication.exec_() else: log.error("source creation failed") # if self.satelliteSource: # log.info(self.satelliteSource.availableSources()) # self.satelliteSource.startUpdates() # log.info("sat source started") def stop(self): log.info("location qt mobility: stopping") if self.source: self.source.stopUpdates() log.info("stopped") if self.qtApplication: log.info("stopping headless mainloop") self.qtApplication.exit() # if self.satelliteSource: # self.satelliteSource.stopUpdates() # log.info("sat source stopped") def canSetUpdateInterval(self): return True def setUpdateInterval(self, interval): if self.source: self.source.setUpdateInterval(interval) def getFix(self): return self.fix # def _satsInViewUpdateCB(self, satellites=None): # """update the count of visible GPS satellites""" # if satellites is not None: # self.satsInViewCount = len(satellites) # # def _satsInUseUpdateCB(self, satellites=None): # """update the count of GPS satellites in use to # determine the current position""" # if satellites is not None: # self.satsInUseCount = len(satellites) def _positionUpdateCB(self, update): direction = update.attribute(update.Direction) speed = update.attribute(update.GroundSpeed) mode = 3 # 3d fix if update.coordinate().isValid(): if update.coordinate().CoordinateType == update.coordinate( ).Coordinate2D: mode = 2 # 2D fix else: mode = 0 # no fix if direction == -1.0: direction = 0 if speed == -1.0: speed = 0 fix = Fix( (update.coordinate().latitude(), update.coordinate().longitude()), update.coordinate().altitude(), direction, speed, mode=mode, magnetic_variation=update.attribute(update.MagneticVariation), sats=self.satsInViewCount, sats_in_use=self.satsInUseCount, horizontal_accuracy=update.attribute(update.HorizontalAccuracy), vertical_accuracy=update.attribute(update.VerticalAccuracy)) # print debug message if enabled # self.debug = True if self.debug: log.debug("Qt-Mobility POS DEBUG") log.debug("%s, %s", update.coordinate().latitude(), update.coordinate().longitude()) log.debug(update) # trigger update in the location module self.location.updatePosition(fix) self.fix = fix
def stop(self): pass def volume(self): return 1.0 def setVolume(self, v): pass if __name__ == '__main__': path = "Z:/Local/Windows/Applications/AHS/VOICEROID+/zunko" os.environ['PATH'] += os.pathsep + path from PySide.QtCore import QCoreApplication a = QCoreApplication(sys.argv) ai = ZunkoTalk() print ai.load() #t = u"憎しみ!!憎しみ。" t = u"「あ、自分は島津秀隆と言います。この中でも新人中の新人ですので、どうぞお手柔らかに」" #t = u"あ、自分は島津秀隆と言います、この中でも新人中の新人ですので、どうぞお手柔らかに" #t = u"】「……」" print ai.speak(t) a.exec_() # EOF