def init(serv): serv.loadConfig(populate=False) # Minecraft part of the Hub wsFactory = serv.factories["WorldServerFactory"] = WorldServerFactory(serv) # Populate configuration. serv.populateConfig() # Load up the database. serv.loadDatabase() # Start up everything. # Until Endpoint has reconnection abilities, this is unused #TCP4ClientEndpoint(reactor, serv.settings["world"]["main"]["hub-ip"], # serv.settings["world"]["main"]["hub-port"]).connect(serv.factories["WorldServerFactory"]).addCallback(serv.factories["WorldServerFactory"]) def afterLoadedPreloadedWorlds(): reactor.connectTCP(wsFactory.settings["main"]["hub-ip"], wsFactory.settings["main"]["hub-port"], wsFactory) def afterLoadedSelfID(): serv.factories["WorldServerFactory"].loadPreloadedWorlds().addCallback(noArgs(afterLoadedPreloadedWorlds)) def afterDBAPIReady(): # Get our ID wsFactory.loadID().addCallback(noArgs(afterLoadedSelfID)) pub.subscribe(afterDBAPIReady, "cloudbox.common.service.databaseAPIReady") reactor.run()
def __init__(self): """Constructor""" screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() Tk.Toplevel.__init__(self) self.overrideredirect(True) self.geometry("{0}x{1}+0+0".format(screenwidth, screenheight)) canvasFrame = Tk.Frame(self, width = screenwidth, height = (screenheight - 100)) instructionFrame = Tk.Frame(self, width = screenwidth, height = 50) self.canvas = Tk.Canvas(canvasFrame, width = screenwidth, height = (screenheight - 100)) # create the button calibrateButton = Tk.Button(instructionFrame, text="Start Calibration", command=self.ovalChange) exitButton = Tk.Button(instructionFrame, text="Quit", command=self.quitCal) canvasFrame.grid() instructionFrame.grid(row = 1) self.canvas.grid() calibrateButton.grid(column = 0) exitButton.grid(column = 1, row = 0) pub.subscribe(self.listener, "userFrameClosed")
def __init__(self, rect): super(TrackButtonBar, self).__init__() self.selected_index = 0 self.tiles_to_show = 0 self.rect = rect self.dirty = True pub.subscribe(self.on_key_up, "input.key-up")
def __init__(self): self.poller = select.poll() pub.subscribe(tracelogger, pub.ALL_TOPICS) pub.sendMessage('lifecycle', msg='Starting up') # Register modules handlers.insteon.InsteonHandler(self, dev='/dev/ttyS0') handlers.tcpsocket.TCPHandler(self, port=2062) Arduino(self,dev='/dev/ttyACM0') holdme = Light(self) holdme2 = ZabbixPush(self) testdev = X10('fishtank', 'L4', False) #self.add_io_handler(sys.stdin.fileno(), stdinhandler) # load configs? # main loop pub.sendMessage('lifecycle', msg='Starting main loop') while (True): try: active=self.poller.poll() for (fd, event) in active: # Call the FD event handler for i in self.FDs: if i.fileno() == fd: self.FDs[i](i, event) break except KeyboardInterrupt: break pub.sendMessage('lifecycle', msg='Quiting')
def __init__(self): pub.subscribe(self.queue_file, 'new_file') pub.subscribe(self.stop, 'wants_to_close') self.thread = None self.running = False self.queue = queue.Queue()
def test_pubsub(self): # Subscribe so we can catch the status update as it comes out. nodeuuid = str(uuid.uuid4()) self.configuration.set_node_uuid(nodeuuid) job_id = str(uuid.uuid4()) pub.subscribe(self.on_job_status_update, self.configuration.get_job_status_pub_topic(job_id)) # Now send off a job update. This should exit via the pub/sub system, but be dropped # on the incoming side. self.configuration.send_job_status(job_id, state='TEST') status = self.wait() self.assertEquals(status.job_id, job_id, "Job ID was not as expected.") self.assertEquals(status.state, 'TEST', "Job status was not as expected.") # Now, manually send a status and force it to go via the pub/sub system and # back out again. job_id = str(uuid.uuid4()) pub.subscribe(self.on_job_status_update, self.configuration.get_job_status_pub_topic(job_id)) message = paasmaker.common.configuration.JobStatusMessage(job_id, 'ROUNDTRIP', 'BOGUS') message.unittest_override = True self.backend.send_job_status(message) status = self.wait() self.assertEquals(status.job_id, job_id, "Job ID was not as expected.") self.assertEquals(status.state, 'ROUNDTRIP', "Job status was not as expected.") self.assertEquals(status.source, 'BOGUS', 'Source was correct.')
def __init__(self, parent, global_store, vsrc_name, *args, **kwargs): # If the device doesn't exist, give up. try: vsrc = global_store.devices[vsrc_name].device except (KeyError, AttributeError): self.Destroy() return Dialog.__init__(self, parent, title='Voltage source settings', *args, **kwargs) self.vsrc_name = vsrc_name # Dialog. dialog_box = wx.BoxSizer(wx.VERTICAL) ## Settings panel. self.panel = VoltageSourceSettingsPanel(self, global_store, vsrc) dialog_box.Add(self.panel) self.SetSizerAndFit(dialog_box) # Subscriptions. pub.subscribe(self.msg_device, 'device.added') pub.subscribe(self.msg_device, 'device.removed')
def job_subscribe(self, job_id): """ This event handler subscribes to the supplied job, and also the matching job tree. Future updates to this job and any jobs in the tree are automatically sent along to the client. The client is sent two messages: job.subscribed, with the entire job tree in flat format, and job.tree, which is the entire job tree in pretty format. """ if not self.configuration.is_pacemaker(): # We don't relay job information if we're not a pacemaker. self.emit('error', 'This node is not a pacemaker.') return # Start listening to job status's after the first subscribe request. if not self.job_listening: pub.subscribe(self.on_job_status, 'job.status') self.job_listening = True def got_pretty_tree(tree): # Send back the pretty tree to the client. self.emit('job.tree', job_id, tree) def got_flat_tree_subscribe(job_ids): for job_id in job_ids: self.job_subscribed[job_id] = True self.emit('job.subscribed', list(job_ids)) # Subscribe to everything in the tree. self.configuration.job_manager.get_pretty_tree(job_id, got_pretty_tree) self.configuration.job_manager.get_flat_tree(job_id, got_flat_tree_subscribe)
def testDeadListener(): # create a listener for listeners that have died class DeathListener(IgnoreNotificationsMixin): listenerStr = '' def notifyDeadListener(self, pubListener, topicObj): assert topicObj.getName() == 'sadTopic' #import pdb; pdb.set_trace() #print 'hi again' DeathListener.listenerStr = pubListener.name() dl = DeathListener() pub.addNotificationHandler( dl ) pub.setNotificationFlags(deadListener=True) # define a topic, subscribe to it, and kill its listener: class TempListener: def __call__(self, **kwargs): pass def __del__(self): # print 'being deleted' pass #def tempListener(): pass tempListener = TempListener() expectLisrStr, _ = getListenerID(tempListener) pub.subscribe(tempListener, 'sadTopic') del tempListener # verify: gc.collect() # for pypy: the gc doesn't work the same as cpython's assert DeathListener.listenerStr.startswith(expectLisrStr), \ '"%s" !~ "%s"' % (DeathListener.listenerStr, expectLisrStr) pub.addNotificationHandler(None) pub.clearNotificationHandlers()
def __init__(self, parent, global_store, model4g_name, *args, **kwargs): # If the device doesn't exist, give up. try: model4g = global_store.devices[model4g_name].device except (KeyError, AttributeError): self.Destroy() return Dialog.__init__(self, parent, title='Model4G Front Panel', *args, **kwargs) self.model4g_name = model4g_name # Dialog. dialog_box = wx.BoxSizer(wx.VERTICAL) ## Settings panel. self.panel = Model4GFrontPanel(self, global_store, model4g) dialog_box.Add(self.panel) self.SetSizerAndFit(dialog_box) self.Bind(wx.EVT_CLOSE, self.OnClose) # Subscriptions. pub.subscribe(self.msg_device, 'device.added') pub.subscribe(self.msg_device, 'device.removed')
def __init__(self): self.config = config.read('config.json') if not 'twitch_id' in self.config: raise config.ConfigurationError( 'Setting twitch_id incorrectly configured in config.json') self.wx = wx.App() self.plugins = plugins.PluginManager() self.plugins.load('plugins/') twitch_id = self.config['twitch_id'] login = self.config['services']['chat']['login'] bot_id = login['id'] bot_oauth = login['oauth'] chat.connect(bot_id, bot_oauth, twitch_id) reactor.interleave(wx.CallAfter) pub.subscribe(self.quit, 'command.quit') self.icon = gui.Icon(self.plugins.plugins()) self.menu = gui.Menu(self.plugins.plugins()) self.wx.MainLoop()
def __init__(self, parent=None, MainWindow=None ): QtGui.QWidget.__init__(self,parent) self.setupUi(self) self.ntb = NavigationToolbar(self.mpl_w, self.frame_plot) self.plot_frame_layout.addWidget(self.ntb) self.show() self.MainWindow = MainWindow self.colors = ['b','g','r','c','m','y','k'] self.fig = self.mpl_w.figure self.ax=self.fig.add_subplot(111) self.ax.hold(True) self.lines = [] self.plotted_list = [] self.legends=[] #signals: self.btn_plotsel.clicked.connect(self.add_var_to_plot) self.btn_clr.clicked.connect(self.clear_plot) self.btn_remvar.clicked.connect(self.remove_var_from_plot) self.lst_plotvar.itemSelectionChanged.connect(self.sel_changed) pub.subscribe(self.listener_new_value_received,'var_value_update') print('jinit plot')
def play (self): if ItemCard.play (self): pub.subscribe (self.on_end_turn, str(self.game_state.gameid1)+'.end_turn_event') self.counter = 3 self.owner.opponent.silencers += [self] return True return False
def __init__(self, parent, title, msg): # Create a dialog wx.Dialog.__init__(self, parent, -1, title, size=(350, 150), style=wx.CAPTION) # Add sizers box = wx.BoxSizer(wx.VERTICAL) box2 = wx.BoxSizer(wx.HORIZONTAL) # Add an Info graphic bitmap = wx.Bitmap(32, 32) bitmap = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_MESSAGE_BOX, (32, 32) ) graphic = wx.StaticBitmap(self, -1, bitmap) box2.Add(graphic, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, 10) # Add the message message = wx.StaticText(self, -1, msg) box2.Add(message, 0, wx.EXPAND | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 10 ) box.Add(box2, 0, wx.EXPAND) # Handle layout self.SetAutoLayout(True) self.SetSizer(box) self.Fit() self.Layout() pub.subscribe(self.getMessage, "RESULT_EVT")
def setup(self, options=None): logger.debug("Setting up track scene") self.space = pymunk.Space() self.space.gravity = (0.0, -900.0) if options: track_name = options.get("trackname") if track_name: tmx_data = self.resources.tilemaps[track_name] self.tmx_data = tmx_data load_shapes(tmx_data, space=self.space) self.map_data = pyscroll.TiledMapData(tmx_data) self.map_layer = pyscroll.BufferedRenderer(self.map_data, (640, 480)) self.karts = list() perf = KartPerf(100, 8, 15) green_kart = Kart( "green-kart", self.space, (200, 630), self.resources.images["green-kart"], self.resources.images["wheel"], perf) green_kart.init_physics() self.karts.append(green_kart) pub.subscribe(self.on_key_up, "input.key-up")
def found_log(result_job_id, result): if isinstance(result, basestring): logger.info("Found job log %s locally.", job_id) read_position = position log_size = os.path.getsize(result) if log_size > MAX_LOG_SIZE: # Don't send back any more than MAX_LOG_SIZE of the file. # Yes, this will potentially chop log lines in half. # TODO: Make it not chop log lines in half. read_position = log_size - MAX_LOG_SIZE # It's the path to the log. # Step 1: Feed since when they last saw. self.send_job_log(job_id, read_position) # Step 2: subscribe for future updates. pub.subscribe(self.log_message_update, self.configuration.get_job_message_pub_topic(job_id)) self.log_job_watcher.add_watch(job_id) self.log_subscribed[job_id] = True elif isinstance(result, paasmaker.model.Node): # It's a remote node containing the log. # Ie, the logs are in another Castle. Sorry Mario. self.handle_remote_subscribe( job_id, position, result, unittest_force_remote=unittest_force_remote )
def init(serv): # Populate configuration. serv.loadConfig(populate=False) # Minecraft part of the Hub serv.factories["MinecraftHubServerFactory"] = MinecraftHubServerFactory(serv) # WorldServer part of the Hub serv.factories["WorldServerCommServerFactory"] = WorldServerCommServerFactory(serv) serv.populateConfig() # Load up the database. serv.loadDatabase() # Start up everything. def afterDBAPIReady(): TCP4ServerEndpoint(reactor, serv.settings["hub"]["main"]["ports"]["clients"])\ .listen(serv.factories["MinecraftHubServerFactory"]) TCP4ServerEndpoint(reactor, serv.settings["hub"]["main"]["ports"]["worldservers"])\ .listen(serv.factories["WorldServerCommServerFactory"]) logging.getLogger("cloudbox.hub").info("Listeners started successfully - now accepting incoming connections.") # Heartbeat Service if serv.settings["hub"]["heartbeat"]["send-heartbeat"]: if serv.settings["hub"]["heartbeat"]["minecraft-heartbeat"]: serv.factories["HeartbeatService-Minecraft"] = HeartbeatService(serv, "Minecraft", "http://minecraft.net/heartbeat.jsp").start() if serv.settings["hub"]["heartbeat"]["classicube-heartbeat"]: serv.factories["HeartbeatService-ClassiCube"] = HeartbeatService(serv, "ClassiCube", "http://www.classicube.net/server/heartbeat").start() logging.getLogger("cloudbox.hub").info("HeartbeatServices started successfully.") pub.subscribe(afterDBAPIReady, "cloudbox.common.service.databaseAPIReady") reactor.run()
def setUp(self): super(PeriodicManagerTest, self).setUp() self.configuration = paasmaker.common.configuration.ConfigurationStub(0, ['pacemaker'], io_loop=self.io_loop) self.configuration.set_node_uuid('test') # Fire up the job manager. self.configuration.startup_job_manager(self.stop) self.wait() # Inject test periodic manager plugins. self.configuration.plugins.register( 'paasmaker.periodic.test', 'paasmaker.common.helper.periodicmanager.PeriodicTestPlugin', {}, 'Test Periodic plugin' ) self.configuration.plugins.register( 'paasmaker.periodic.testfail', 'paasmaker.common.helper.periodicmanager.PeriodicTestFailPlugin', {}, 'Test Fail Periodic plugin' ) # Set up to catch job statuses. pub.subscribe(self.on_job_catchall, 'job.status') self.job_statuses = {}
def test_track_event_seveal_subscriptions(self): c = peachbox.scheduler.ConditionalEvent('c5') e1 = peachbox.scheduler.Event('finished') status = e1.status() status['payload'] = {'latest_kafka_offset':123} e2 = peachbox.scheduler.Event('timer') status2 = e2.status() status2['payload'] = {'timestamp':123456} c.subscribe(e1) c.subscribe(e2) def receiver(param): self.assertEqual(123, param['payload']['latest_kafka_offset']) self.assertEqual(123456, param['payload']['timestamp']) pub.subscribe(receiver, c.name()) def publish_in_process(event): self.s.publish(event) p1 = multiprocessing.Process(target=self.s.publish, args=(e1,)) p2 = multiprocessing.Process(target=self.s.publish, args=(e2,)) p1.start() p2.start() p1.join() p2.join() # Check if the counters are reset subscriptions = c.get_subscriptions() self.assertEqual({'finished':1, 'timer':1}, subscriptions)
def __init__(self, parent): super(OverviewWidget, self).__init__(parent) self.label = QtGui.QLabel("Asymmetry") self.parent = parent self.active = False self.left_front = OverviewView(self, "Left Front", 0) self.left_hind = OverviewView(self, "Left Hind", 1) self.right_front = OverviewView(self, "Right Front", 2) self.right_hind = OverviewView(self, "Right Hind", 3) self.overview_list = [self.left_front, self.left_hind, self.right_front, self.right_hind] self.asymmetry_layout = QtGui.QGridLayout() self.asymmetry_layout.addWidget(self.left_front, 1, 0) self.asymmetry_layout.addWidget(self.left_hind, 2, 0) self.asymmetry_layout.addWidget(self.right_front, 1, 1) self.asymmetry_layout.addWidget(self.right_hind, 2, 1) self.main_layout = QtGui.QVBoxLayout() self.main_layout.addLayout(self.asymmetry_layout) self.main_layout.addStretch(1) self.setLayout(self.main_layout) pub.subscribe(self.active_widget, "active_widget")
def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1) self.CreateStatusBar(1) pub.subscribe(self.change_statusbar, "change.statusbar") tempheading = ((" ",10), (" ",15), (" ",10)) self.panel_login = panel_login(self, -1) self.panes = {} self.panes['base'] = self.panel_base = panel_base(self, -1) # top horizontal ctrls self.panes['rereg_list'] = self.panel_rereg_list = panel_rereg_list(self, -1) self.panes['edit_booking'] = self.edit_booking = edit_booking(self, -1) self.panes['edit_courses'] = self.panel_courses = panel_courses_picker(self, -1) self.panes['student_details'] = self.panel_student_details = cSiswaDetails(self, -1) self.panes['add_edit_course'] = self.panel_add_edit_course = panel_add_edit_course(self, -1) self.panes['course_bookings'] = self.panel_course_bookings = panel_course_bookings(self,-1) self.panes['edit_rereg_status'] = self.panel_edit_rereg_status = panel_edit_rereg_status(self, -1) self.panes['edit_booking_status'] = self.panel_edit_booking_status = panel_edit_booking_status(self, -1) self.panes['edit_guardian_data'] = self.PanelGuardianData = panel_edit_guardian(self, 1) self.panes['edit_booking_student_details'] = self.edit_booking_student_details = edit_booking_student_details(self, -1) self.panes['course_fees'] = self.panel_course_fees = course_fees(self, -1) self.panes['edit_schools'] = self.edit_school = edit_school(self, -1) self.panes['edit_address'] = self.panel_edit_address = panel_edit_address(self, -1) self.Bind(wx.EVT_CLOSE, self.OnClose, self) self.__set_properties() self.__do_layout() self.__do_main()
def __init__(self,parent,model,tkmaster,**kwargs): Tk.Frame.__init__(self,parent,**kwargs) self.parent = parent self.model = model self.log_vars = list() self.plotmode = 'scalar' self.index=0 self.tkmaster = tkmaster self.plotted_varid = None self.selected_varid = None self.selected_varname = "" self.s_value = 0.0 pub.subscribe(self.listener_new_value_received,'var_value_update') pub.subscribe(self.listener_var_selected,'new_var_selected') # Widgets self.liste = Tk.Listbox(self,height=1) self.liste.grid(column=1,row=1,sticky='EW',pady=3,padx=3,rowspan=2) self.scrollbar_liste = Tk.Scrollbar(self.liste) self.scrollbar_liste.config(command = self.liste.yview) self.liste.config(yscrollcommand = self.scrollbar_liste.set) self.scrollbar_liste.pack(side=Tk.RIGHT) # self.bouton_add_var = Tk.Button(self, text="PLOT SELECTION", command = self.add_var_to_plot) self.bouton_add_var.grid(column=0,row=1,rowspan=2,pady=3,padx=3,sticky='NSEW') # self.bouton_switch_mode = Tk.Button(self, text="REMOVE VAR", command = self.remove_var_from_plot) self.bouton_switch_mode.grid(column=2,row=2,pady=3,padx=3) # self.f = Figure(figsize=(5,4), dpi=100) self.a = self.f.add_subplot(111) self.a.set_xlim([0, 127]) self.a.set_ylim([-255, 255]) self.line1, = self.a.plot([],[]) self.x = deque(maxlen=128) self.y = deque(maxlen=128) self.ymin = 0 self.ymax = 1 self.first = False # self.dataPlot = FigureCanvasTkAgg(self.f, master=self) self.dataPlot.show() self.dataPlot.get_tk_widget().grid(column=0,row=0,sticky='EW',pady=3,padx=3,columnspan=5) # self.selected_var_name = Tk.StringVar() self.selected_var_name.set("No variable") self.selected_var = Tk.Label(self,textvariable=self.selected_var_name,bd=2,relief=Tk.GROOVE) self.selected_var.grid(column=2,row=1,sticky='EW',pady=3,padx=3) # self.selected_value = Tk.DoubleVar() self.selected_value.set(0.0) self.selected_var_val = Tk.Label(self,textvariable=self.selected_value,bd=2,relief=Tk.GROOVE) self.selected_var_val.grid(column=3,row=1,sticky='EW',pady=3,padx=3)
def init_ui(self): self.vbox = wx.BoxSizer(wx.VERTICAL) self.race_choice = wx.Choice(self, choices=[_i for _i in char_races.RACES], # style=wx.CB_READONLY, ) self.race_choice.SetSelection(0) self.race_choice.Bind(wx.EVT_CHOICE, self.send_update) # self.combo_box.Bind(wx.EVT_COMBOBOX, self.send_update) self.text = wx.StaticText(self, wx.ID_ANY, pos=(50, 50), label="Hello", ) # register listener pub.subscribe(self.update_text, 'updating text') self.vbox.Add(self.race_choice) self.vbox.Add(Abilities(self)) self.vbox.Add(wx.StaticText(self, label="Press CTRL-ALT-I to start inspector")) self.vbox.Add(self.text) self.SetSizer(self.vbox)
def testNotifyByPrint(): capture = captureStdout() def listener1(arg1): pass pub.subscribe(listener1, 'baz') pub.sendMessage('baz', arg1=123) pub.unsubscribe(listener1, 'baz') def doa(): def listener2(): pass pub.subscribe(listener2, 'bar') doa() # listener2 should be gc'd gc.collect() # for pypy: the gc doesn't work the same as cpython's topicMgr.delTopic('baz') expect = """\ PUBSUB: New topic "baz" created PUBSUB: Subscribed listener "listener1" to topic "baz" PUBSUB: Start sending message of topic "baz" PUBSUB: Sending message of topic "baz" to listener listener1 PUBSUB: Done sending message of topic "baz" PUBSUB: Unsubscribed listener "listener1" from topic "baz" PUBSUB: New topic "bar" created PUBSUB: Subscribed listener "listener2" to topic "bar" PUBSUB: Listener "listener2" of Topic "bar" has died PUBSUB: Topic "baz" destroyed """ captured = capture.getvalue() #print captured #print repr(expect) assert captured == expect, \ '\n'.join( unified_diff(expect.splitlines(), captured.splitlines(), n=0) )
def __init__(self, configFile, completed_callback): self.config = configFile super(audioUploader, self).__init__() self.dialog = wx_ui.audioDialog(services=self.get_available_services()) self.file = None self.recorded = False self.recording = None self.playing = None widgetUtils.connect_event(self.dialog.play, widgetUtils.BUTTON_PRESSED, self.on_play) widgetUtils.connect_event(self.dialog.pause, widgetUtils.BUTTON_PRESSED, self.on_pause) widgetUtils.connect_event(self.dialog.record, widgetUtils.BUTTON_PRESSED, self.on_record) widgetUtils.connect_event(self.dialog.attach_exists, widgetUtils.BUTTON_PRESSED, self.on_attach_exists) widgetUtils.connect_event(self.dialog.discard, widgetUtils.BUTTON_PRESSED, self.on_discard) if self.dialog.get_response() == widgetUtils.OK: self.postprocess() log.debug("Uploading file %s to %s..." % (self.file, self.dialog.get("services"))) self.uploaderDialog = wx_transfer_dialogs.UploadDialog(self.file) output.speak(_(u"Attaching...")) if self.dialog.get("services") == "SNDUp": base_url = "http://sndup.net/post.php" if len(self.config["sound"]["sndup_api_key"]) > 0: url = base_url + '?apikey=' + self.config['sound']['sndup_api_key'] else: url = base_url self.uploaderFunction = transfer.Upload(field='file', url=url, filename=self.file, completed_callback=completed_callback) elif self.dialog.get("services") == "TwUp": url = "http://api.twup.me/post.json" self.uploaderFunction = transfer.Upload(field='file', url=url, filename=self.file, completed_callback=completed_callback) pub.subscribe(self.uploaderDialog.update, "uploading") self.uploaderDialog.get_response() self.uploaderFunction.perform_threaded()
def __init__(self, guide): self.guide = guide pub.subscribe(self.feedback, 'guide.feedback') pub.subscribe(self.next_action, 'guide.next_action') self.orders, self.goals, self.predictions, self.effects = [], [], [], [] self.paths = 4*[0]
def __init__( self, task ): self.task = task self.previewView = PreviewView( None, -1, "" ) self.previewView.Show() self.previewModel = PreviewModel( self.task ) self.showCommands() pub.subscribe( self.exiting, 'EXITING' )
def __init__(self): """Set up the sensor with the topics it needs to listen to from the keyboard""" self._subscribedTopics = str(mt.Sensors.Keyboard) pub.subscribe(self.KBsensorSubscriber,self._subscribedTopics) self._year_max = 2015 self._year_min = 1989 self._year = self._year_max
def changer(self): # first time, subscribe new listener; if don't have this, will fail in # py3 because order of listeners opposite, so unsub will happen before # the sub (which succeeds even if no listeners) and newListener will # remain subscribed. if self.callCountForChanger == 0: pub.subscribe(self.newListener, 'test.change-listeners') self.callCountForChanger += 1
def __init__(self): pub.subscribe(self.rewind, 'REWIND') pub.subscribe(self.generate_xml, 'GENERATE_XML') pub.subscribe(self.process_file, 'PROCESS_FILE') pub.subscribe(self.output_xml, 'OUTPUT_XML') pub.subscribe(self.set_series, 'SET_SERIES') self.log = logging.getLogger('filetools') self.output = []
def subAll(): pub.subscribe(lisnr1, 'testUnsubAll') pub.subscribe(lisnr2, 'testUnsubAll') pub.subscribe(lisnr3, 'testUnsubAll') pub.subscribe(lisnr4, 'testUnsubAll') assert topicMgr.getTopic('testUnsubAll').getNumListeners() == 4
def __init__(self, master): self.model = Model() self.view = View(master) pub.subscribe(self.newSchedule, "New Menu Dropdown Pressed") # for populating planning worksheet pub.subscribe(self.planningWorksheet_open, "request_PPW") pub.subscribe(self.view.planningWorksheet_fill, "PPW_information") pub.subscribe(self.addCourse, "request_course#") pub.subscribe(self.findStudents, "requestStudents") pub.subscribe(self.view.openSchedule, "listOfStudents") # for populating Four Year Plan # pub.subscribe(self.fourYearPlan_open, "request_FYP") pub.subscribe(self.view.fourYearPlan_fill, "PPW_information") # for refreshing the four year plan pub.subscribe(self.model.getFourYear_refresh, "refresh_fyp") pub.subscribe(self.view.fourYearPlan_refresh, "FYP_refresh_info") # for specific mojor and minor under a school pub.subscribe(self.setMajor, "request_major") pub.subscribe(self.setMinor, "request_minor") pub.subscribe(self.setSchools, "request_allSchools") pub.subscribe(self.setSubjects, "request_allSubjects") # for saving info from program planning sheet pub.subscribe(self.saveSchedule, "save_schedule") pub.subscribe(self.saveMajorPlan, "save_maj_plan") pub.subscribe(self.saveMinorPlan, "save_min_plan") pub.subscribe(self.openPPW, "request_CSV") pub.subscribe(self.exportSchedule, "export_schedule") pub.subscribe(self.model.delMajor, "request_DelMajor") pub.subscribe(self.model.delMinor, "request_DelMinor") pub.subscribe(self.model.addMajor, "request_AddMajor") pub.subscribe(self.model.addMinor, "request_AddMinor") pub.subscribe(self.model.setAuthToken, "request_setAuthToken") # Requesting a list of all majors and minors when trying to edit/add a major or minor pub.subscribe(self.getMajors, "request_Majors") pub.subscribe(self.getMinors, "request_Minors") pub.subscribe(self.getMajorPlans, "request_Major_Plan") pub.subscribe(self.getMinorPlans, "request_Minor_Plan") # Requesting the courses for a majors FYP pub.subscribe(self.getMajorsFYP, "request_MajorsFYP") pub.subscribe(self.getMinorAddEdit, "request_MinorAddEdit") # pub.subscribe(self.setMemo, "request_Memo_to_Display") pub.subscribe(self.setPolicy, "request_Policy_to_Display") pub.subscribe(self.getCourseListbyRegex, "request_Course_by_Regex") pub.subscribe(self.getBackupCourseListbyRegex, "request_Backup_Course_by_Regex") pub.subscribe(self.getMajors, "request_ListMajors") pub.subscribe(self.getMinors, "request_ListMinors")
def __bind_events(self): Publisher.subscribe(self.OnEnableState, "Enable state project")
def __init__(self, parent): super().__init__(parent) pub.subscribe(self.update_path_via_pubsub, "path") self.SetBackgroundColour("red") self.display_path = os.path.abspath(__file__)
def subscribe(): """Subscribe to the topics the user probably wants to see, prints output to stdout""" pub.subscribe(onReceive, "meshtastic.receive")
def testSubscribe(): topicName = 'testSubscribe' def proto(a, b, c=None): pass topicMgr.getOrCreateTopic(topicName, proto) def listener(a, b, c=None): pass # verify that pub.isValid() works too pub.validate(listener, topicName) assert pub.isValid(listener, topicName) assert topicMgr.getTopic(topicName).getNumListeners() == 0 assert topicMgr.getTopicsSubscribed(listener) == [] assert not pub.isSubscribed(listener, topicName) assert pub.subscribe(listener, topicName) assert pub.isSubscribed(listener, topicName) def topicNames(listener): return [t.getName() for t in topicMgr.getTopicsSubscribed(listener)] assert topicNames(listener) == [topicName] # should do nothing if already subscribed: assert not pub.subscribe(listener, topicName)[1] assert topicMgr.getTopic(topicName).getNumListeners() == 1 # test topicMgr.getTopicsSubscribed() pub.subscribe(listener, 'lt2', ) assert set(topicNames(listener)) == set([topicName,'lt2']) pub.subscribe(listener, 'lt1.lst1') assert set(topicNames(listener)) == set([topicName,'lt2','lt1.lst1']) # test ALL_TOPICS def listenToAll(): pass pub.subscribe(listenToAll, pub.ALL_TOPICS) assert topicNames(listenToAll) == [pub.ALL_TOPICS] # test type hints in listeners: def listenerWithHints(a: int, b: bool, c: str = 2): pass topicForHintedListeners = 'topicForHints' topicMgr.getOrCreateTopic(topicForHintedListeners, listenerWithHints) assert not pub.isSubscribed(listenerWithHints, topicForHintedListeners) pub.subscribe(listenerWithHints, topicForHintedListeners) assert pub.subscribe(listenerWithHints, topicForHintedListeners) assert pub.isSubscribed(listenerWithHints, topicForHintedListeners)
def __bind_events(self): Publisher.subscribe(self._Exit, 'Exit')
def __init__(self, parent): super().__init__(parent, style=wx.BORDER_NONE) main_sizer = wx.BoxSizer(wx.VERTICAL) self.header_panel = HeaderPanel(self) main_sizer.Add(self.header_panel, flag=wx.EXPAND) self.note_list_panel = NoteListPanel(self) main_sizer.Add(self.note_list_panel, flag=wx.EXPAND, proportion=1) self.SetSizer(main_sizer) self._note_ids = [] pub.subscribe(self._on_notebook_selected, 'notebook.selected') pub.subscribe(self._on_root_selected, 'root.selected') pub.subscribe(self._on_note_created, 'note.created') pub.subscribe(self._on_note_deleting, 'note.deleting') pub.subscribe(self._on_note_sorting, 'note.sorting') self.searcher = NoteSearchService() pub.subscribe(self._on_note_updated, 'note.updated') self._notebook = None pub.subscribe(self._on_note_searching, 'note.searching')
def activate(): pub.subscribe(_listener, event_topics.OPTIMIZATION_TOPIC)
histc.SetValue(hist) txt = wx.StaticText( panel, wx.ID_ANY, 'Channel:'+'Gray', wx.DefaultPosition, wx.DefaultSize, 0 ) sizer.Add( txt, 0, wx.LEFT|wx.RIGHT, 8 ) sizer.Add( histc, 0, wx.LEFT|wx.RIGHT, 8 ) mean, lim = np.dot(hist, range(256))/hist.sum(), np.where(hist>0)[0] sta = 'Statistic: Mean:%s Min:%s Max:%s'%(mean.round(1), lim.min(), lim.max()) txt = wx.StaticText( panel, wx.ID_ANY, sta, wx.DefaultPosition, wx.DefaultSize, 0 ) sizer.Add( txt, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM, 8 ) panel.SetSizer( sizer ) self.SetSizer(back) self.Fit() def showhist(parent, title, hist): HistogramFrame(parent, title, hist).Show() pub.subscribe(showhist, 'showhist') def show_hist(parent, title, hist): wx.CallAfter(pub.sendMessage, 'showhist', parent=parent, title=title, hist=hist) class Histogram(Simple): title = 'Histogram' note = ['8-bit', '16-bit', 'rgb'] def run(self, ips, imgs, para = None): msk = ips.mask('in') if ips.channels == 3: img = ips.img if msk is None else ips.img[msk] hist = [np.histogram(img.ravel()[i::3], np.arange(257))[0] for i in (0,1,2)] else: img = ips.lookup() if msk is None else ips.lookup()[msk] hist = np.histogram(img, np.arange(257))[0]
def __init__(self): super().__init__() pub.subscribe(self.Thruster_Power_Listener_Max, "Thruster.Power") self.List = [(-1,0,1),(-1,0,1),(-1,0,1),(-1,0,1),(-1,0,1)] self.FL_List, self.FR_List, self.BL_List, self.BR_List, self.UF_List, self.UB_List = [],[],[],[],[],[]
__author__ = "schoenb" __date__ = "$31-May-2009 9:11:41 PM$" resultStep = 1000000 # how many counts for thread "result" to be available def threadObserver(transfers, threadObj, count): """Listener that listens for data from testTopic. This function doesn't know where the data comes from (or in what thread it was generated... but threadObj is the thread in which this threadObserver is called and should indicate Main thread).""" print(transfers, threadObj, count / resultStep) pub.subscribe(threadObserver, 'testTopic') def onIdle(): """This should be registered with 'gui' to be called when gui is idle so we get a chance to transfer data from aux thread without blocking the gui. Ie this function must spend as little time as possible so 'gui' remains reponsive.""" thread.transferData() class ParaFunction(threading.Thread): """ Represent a function running in a parallel thread. The thread just increments a counter and puts the counter value on a synchronized queue every resultStep counts. The content of the queue can be published by
def __init__(self, parent, manager=None): wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.Size(500, 300), style=wx.TAB_TRAVERSAL) #self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) sizer = wx.BoxSizer(wx.VERTICAL) self.canvas = Canvas3D(self, manager) self.toolbar = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize) tsizer = wx.BoxSizer(wx.HORIZONTAL) root = osp.abspath(osp.dirname(__file__)) #self.SetIcon(wx.Icon('data/logo.ico', wx.BITMAP_TYPE_ICO)) self.btn_x = wx.BitmapButton( self.toolbar, wx.ID_ANY, make_bitmap( wx.Bitmap(osp.join(root, 'imgs/x-axis.png'), wx.BITMAP_TYPE_ANY)), wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW) tsizer.Add(self.btn_x, 0, wx.ALIGN_CENTER | wx.ALL, 0) self.btn_y = wx.BitmapButton( self.toolbar, wx.ID_ANY, make_bitmap( wx.Bitmap(osp.join(root, 'imgs/y-axis.png'), wx.BITMAP_TYPE_ANY)), wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW) tsizer.Add(self.btn_y, 0, wx.ALIGN_CENTER | wx.ALL, 0) self.btn_z = wx.BitmapButton( self.toolbar, wx.ID_ANY, make_bitmap( wx.Bitmap(osp.join(root, 'imgs/z-axis.png'), wx.BITMAP_TYPE_ANY)), wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW) tsizer.Add(self.btn_z, 0, wx.ALIGN_CENTER | wx.ALL, 0) tsizer.Add( wx.StaticLine(self.toolbar, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_VERTICAL), 0, wx.ALL | wx.EXPAND, 2) self.btn_pers = wx.BitmapButton( self.toolbar, wx.ID_ANY, make_bitmap( wx.Bitmap(osp.join(root, 'imgs/isometric.png'), wx.BITMAP_TYPE_ANY)), wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW) tsizer.Add(self.btn_pers, 0, wx.ALIGN_CENTER | wx.ALL, 0) self.btn_orth = wx.BitmapButton( self.toolbar, wx.ID_ANY, make_bitmap( wx.Bitmap(osp.join(root, 'imgs/parallel.png'), wx.BITMAP_TYPE_ANY)), wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW) tsizer.Add(self.btn_orth, 0, wx.ALIGN_CENTER | wx.ALL, 0) tsizer.Add( wx.StaticLine(self.toolbar, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_VERTICAL), 0, wx.ALL | wx.EXPAND, 2) self.btn_open = wx.BitmapButton( self.toolbar, wx.ID_ANY, make_bitmap( wx.Bitmap(osp.join(root, 'imgs/open.png'), wx.BITMAP_TYPE_ANY)), wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW) tsizer.Add(self.btn_open, 0, wx.ALIGN_CENTER | wx.ALL, 0) self.btn_stl = wx.BitmapButton( self.toolbar, wx.ID_ANY, make_bitmap( wx.Bitmap(osp.join(root, 'imgs/stl.png'), wx.BITMAP_TYPE_ANY)), wx.DefaultPosition, wx.DefaultSize, wx.BU_AUTODRAW) tsizer.Add(self.btn_stl, 0, wx.ALIGN_CENTER | wx.ALL, 0) #pan = wx.Panel(self.toolbar, size=(50, 50)) self.btn_color = wx.ColourPickerCtrl( self.toolbar, wx.ID_ANY, wx.Colour(128, 128, 128), wx.DefaultPosition, [(33, 38), (-1, -1)][platform.system() in ['Windows', 'Linux']], wx.CLRP_DEFAULT_STYLE) tsizer.Add( self.btn_color, 0, wx.ALIGN_CENTER | wx.ALL | (0, wx.EXPAND)[platform.system() in ['Windows', 'Linux']], 0) tsizer.Add( wx.StaticLine(self.toolbar, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_VERTICAL), 0, wx.ALL | wx.EXPAND, 2) self.cho_light = wx.Choice( self.toolbar, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, ['force light', 'normal light', 'weak light', 'off light'], 0) self.cho_light.SetSelection(1) tsizer.Add(self.cho_light, 0, wx.ALIGN_CENTER | wx.ALL, 1) self.cho_bg = wx.Choice( self.toolbar, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, ['force scatter', 'normal scatter', 'weak scatter', 'off scatter'], 0) self.cho_bg.SetSelection(1) tsizer.Add(self.cho_bg, 0, wx.ALIGN_CENTER | wx.ALL, 1) self.toolbar.SetSizer(tsizer) tsizer.Layout() self.settingbar = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL) ssizer = wx.BoxSizer(wx.HORIZONTAL) self.m_staticText1 = wx.StaticText(self.settingbar, wx.ID_ANY, u"Object:", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText1.Wrap(-1) ssizer.Add(self.m_staticText1, 0, wx.ALIGN_CENTER | wx.LEFT, 10) cho_objChoices = ['None'] self.cho_obj = wx.Choice(self.settingbar, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, cho_objChoices, 0) self.cho_obj.SetSelection(0) ssizer.Add(self.cho_obj, 0, wx.ALIGN_CENTER | wx.ALL, 1) self.chk_visible = wx.CheckBox(self.settingbar, wx.ID_ANY, u"visible", wx.DefaultPosition, wx.DefaultSize, 0) ssizer.Add(self.chk_visible, 0, wx.ALIGN_CENTER | wx.LEFT, 10) self.col_color = wx.ColourPickerCtrl(self.settingbar, wx.ID_ANY, wx.BLACK, wx.DefaultPosition, wx.DefaultSize, wx.CLRP_DEFAULT_STYLE) ssizer.Add(self.col_color, 0, wx.ALIGN_CENTER | wx.ALL, 1) self.m_staticText2 = wx.StaticText(self.settingbar, wx.ID_ANY, u"Blend:", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText2.Wrap(-1) ssizer.Add(self.m_staticText2, 0, wx.ALIGN_CENTER | wx.LEFT, 10) self.sli_blend = wx.Slider(self.settingbar, wx.ID_ANY, 10, 0, 10, wx.DefaultPosition, wx.DefaultSize, wx.SL_HORIZONTAL) ssizer.Add(self.sli_blend, 0, wx.ALIGN_CENTER | wx.ALL, 1) self.settingbar.SetSizer(ssizer) self.m_staticText2 = wx.StaticText(self.settingbar, wx.ID_ANY, u"Mode:", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText2.Wrap(-1) ssizer.Add(self.m_staticText2, 0, wx.ALIGN_CENTER | wx.LEFT, 10) cho_objChoices = ['mesh', 'grid'] self.cho_mode = wx.Choice(self.settingbar, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, cho_objChoices, 0) self.cho_mode.SetSelection(0) ssizer.Add(self.cho_mode, 0, wx.ALIGN_CENTER | wx.ALL, 1) sizer.Add(self.toolbar, 0, wx.EXPAND | wx.ALL, 0) sizer.Add(self.canvas, 1, wx.EXPAND | wx.ALL, 0) sizer.Add(self.settingbar, 0, wx.EXPAND | wx.ALL, 0) self.SetSizer(sizer) self.Layout() self.Centre(wx.BOTH) self.btn_x.Bind(wx.EVT_BUTTON, self.view_x) self.btn_y.Bind(wx.EVT_BUTTON, self.view_y) self.btn_z.Bind(wx.EVT_BUTTON, self.view_z) self.btn_open.Bind(wx.EVT_BUTTON, self.on_open) self.btn_stl.Bind(wx.EVT_BUTTON, self.on_stl) self.btn_pers.Bind(wx.EVT_BUTTON, lambda evt, f=self.on_pers: f(True)) self.btn_orth.Bind(wx.EVT_BUTTON, lambda evt, f=self.on_pers: f(False)) self.btn_color.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_bgcolor) self.cho_obj.Bind(wx.EVT_CHOICE, self.on_select) self.cho_mode.Bind(wx.EVT_CHOICE, self.on_mode) self.cho_light.Bind(wx.EVT_CHOICE, self.on_light) self.cho_bg.Bind(wx.EVT_CHOICE, self.on_bg) self.chk_visible.Bind(wx.EVT_CHECKBOX, self.on_visible) self.sli_blend.Bind(wx.EVT_SCROLL, self.on_blend) self.col_color.Bind(wx.EVT_COLOURPICKER_CHANGED, self.on_color) if manager != None: self.cho_obj.Set(list(manager.objs.keys())) pub.subscribe(self.add_surf, 'add_surf') pub.subscribe(self.add_mark, 'add_mark')
from pubsub import pub from eventscanner.monitors.payments import (BinPaymentMonitor, EthPaymentMonitor) pub.subscribe(BinPaymentMonitor.on_new_block_event, 'BINANCE_MAINNET') pub.subscribe(EthPaymentMonitor.on_new_block_event, 'ETHEREUM_MAINNET')
def __bind_events(self): Publisher.subscribe(self.ShowRaycastingWidget, 'Show raycasting widget') Publisher.subscribe(self.HideRaycastingWidget, 'Hide raycasting widget') Publisher.subscribe(self.OnSetRaycastPreset, 'Update raycasting preset') Publisher.subscribe(self.RefreshPoints, 'Refresh raycasting widget points') Publisher.subscribe(self.LoadHistogram, 'Load histogram') Publisher.subscribe(self._Exit, 'Exit')
def __bind_events(self): Publisher.subscribe(self.ChangeButtonColour, 'Change volume viewer gui colour') Publisher.subscribe(self.DisablePreset, 'Close project data') Publisher.subscribe(self.Uncheck, 'Uncheck image plane menu') Publisher.subscribe(self.DisableVolumeCutMenu, 'Disable volume cut menu') Publisher.subscribe(self.StatusTargetSelect, 'Disable or enable coil tracker') Publisher.subscribe(self.StatusObjTracker, 'Status target button') Publisher.subscribe(self.ActiveTarget, 'Active target button') Publisher.subscribe(self.DeactiveTarget, 'Deactive target button')
def __init__(self, address, speed): super().__init__() self.speed = speed self.address = address pub.subscribe(self.Listener, "gamepad.gripper")
def on_close(self): pass @staticmethod def sendLog(message): WSHandler.connection.write_message(message) @staticmethod def sendAnnotation(message): WSHandler.connection.write_message(message) def check_origin(self, origin): return True pub.subscribe(WSHandler.sendLog, 'logger') pub.subscribe(WSHandler.sendAnnotation, 'annotations') def start_server(host, port, handler): print (f'Start server at {host}, {port}') FuncHandler.handler = handler app = tornado.web.Application([ #(r"/", MainHandler), (r"/func", FuncHandler), (r'/ws', WSHandler), (r'/(.*)', tornado.web.StaticFileHandler, {'path':os.path.join(path, 'static'), 'default_filename': "index.html"}), ]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(port, host) tornado.ioloop.IOLoop.current().start()
def __init__(self): super().__init__() pub.subscribe(self.Listener, "can.send")
def InitUI(self): panel = wx.Panel(self) Label1 = wx.StaticText(panel, -1, 'Demand rate', pos=(20, 25)) Label1.SetForegroundColour('#0a74f7') self.demand_input = wx.SpinCtrl(panel, -1, "", min=1, max=100000, initial=2000, pos=(150, 25), size=[80, -1]) Label2 = wx.StaticText(panel, -1, 'Working minute', pos=(20, 50)) Label2.SetForegroundColour('#0a74f7') self.workhour_input = wx.SpinCtrl(panel, -1, "", min=1, max=60, initial=10, pos=(150, 50), size=[80, -1]) Label3 = wx.StaticText(panel, -1, 'Rhythm', pos=(20, 75)) Label3.SetForegroundColour('#0a74f7') self.rhythm_input = wx.SpinCtrl(panel, -1, "", min=1, max=10, initial=2, pos=(150, 75), size=[80, -1]) Label4 = wx.StaticText(panel, -1, 'Platoon length', pos=(20, 100)) Label4.SetForegroundColour('#0a74f7') self.platoon_input = wx.SpinCtrl(panel, -1, "", min=1, max=50, initial=1, pos=(150, 100), size=[80, -1]) self.sureButton = wx.Button(panel, -1, 'Generate', pos=(20, 140), size=(80, 40)) self.sureButton.SetForegroundColour('white') self.sureButton.SetBackgroundColour('#0a74f7') self.Bind(wx.EVT_BUTTON, self.sureEvent, self.sureButton) self.cancleButton = wx.Button(panel, -1, 'Cancel', pos=(140, 140), size=(80, 40)) self.cancleButton.SetBackgroundColour('black') self.cancleButton.SetForegroundColour('#ffffff') self.Bind(wx.EVT_BUTTON, self.cancleEvent, self.cancleButton) self.gauge = wx.Gauge(panel, -1, 100, pos=(30, 200)) self.gauge.SetBezelFace(3) self.gauge.SetShadowWidth(3) pub.subscribe(self.set_gauge, "change_guage_generating")
def __bind_events(self): Publisher.subscribe(self.OnFlipVolume, 'Flip volume') Publisher.subscribe(self.OnSwapVolumeAxes, 'Swap volume axes')
def __init__(self): self.algorithm = "Watershed" self.con_2d = 4 self.con_3d = 6 self.mg_size = 3 self.use_ww_wl = True self.operation = BRUSH_FOREGROUND self.cursor_type = const.BRUSH_CIRCLE self.cursor_size = const.BRUSH_SIZE Publisher.subscribe(self.set_operation, "Set watershed operation") Publisher.subscribe(self.set_use_ww_wl, "Set use ww wl") Publisher.subscribe(self.set_algorithm, "Set watershed algorithm") Publisher.subscribe(self.set_2dcon, "Set watershed 2d con") Publisher.subscribe(self.set_3dcon, "Set watershed 3d con") Publisher.subscribe(self.set_gaussian_size, "Set watershed gaussian size")
def __init__(self, parent, TagsTracker, questions, OutputFiles): wx.Panel.__init__(self, parent=parent) self.NumQuestions = len(questions) self.pos = 0 # The position in positions self.positions = [0] * len(OutputFiles.InputPaths) # The position in questions corresponding to each image self.sizer = wx.BoxSizer(wx.VERTICAL) self.OutputFiles = OutputFiles # A FileManager object self.QuestionWidgets = [] # wxWidgets corresponding to each question for q in questions: proportion = 0 if q.type == OptionQuestionType.RADIO_QUESTION: self.QuestionWidgets.append( RadioQuestion(self, TagsTracker, q) ) proportion = 100 elif q.type == OptionQuestionType.CHECK_QUESTION: self.QuestionWidgets.append( CheckQuestion(self, TagsTracker, q) ) proportion = 100 elif q.type == QuestionType.ENTRY_QUESTION: self.QuestionWidgets.append( EntryQuestion(self, len(OutputFiles.InputPaths), TagsTracker) ) proportion = 100 elif q.type == QuestionType.SESSION_TAGS: self.QuestionWidgets.append( SessionTags(self, TagsTracker) ) proportion = 100 elif q.type == QuestionType.NAME_QUESTION: self.QuestionWidgets.append( NameQuestion(self) ) elif q.type == QuestionType.SOURCE_QUESTION: self.QuestionWidgets.append( SourceQuestion(self) ) elif q.type == QuestionType.SAFETY_QUESTION: self.QuestionWidgets.append( SafetyQuestion(self) ) proportion = 100 elif q.type == QuestionType.IMAGE_TAGS_ENTRY: self.QuestionWidgets.append( ImageTagsEntry(self, TagsTracker) ) proportion = 100 else: # q.type == QuestionType.SESSION_TAGS_IMPORTER self.QuestionWidgets.append( SessionTagsImporter(self, OutputFiles.ControlFiles, TagsTracker) ) proportion = 100 self.sizer.Add(self.QuestionWidgets[-1], proportion, wx.ALIGN_LEFT | wx.LEFT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND) self.QuestionWidgets[-1].Hide() self.sizer.AddStretchSpacer(1) self.SetSizer(self.sizer) self._LoadAll() self._disp() pub.subscribe(self._OnIndexImage, "IndexImage") pub.subscribe(self._OnIndexQuestion, "IndexQuestion") pub.subscribe(self._OnLeftImage, "LeftImage") pub.subscribe(self._OnRightImage, "RightImage") pub.subscribe(self._OnLeftQuestion, "LeftQuestion") pub.subscribe(self._OnRightQuestion, "RightQuestion") pub.subscribe(self._OnFocusQuestionBody, "FocusQuestionBody")
def testSendTopicWithMessage(): class MyListener: def __init__(self): self.count = 0 self.heardTopic = False self.listen2Topics = [] def listen0(self): pass def listen1(self, **kwarg): self.count += 1 self.heardTopic = True def listen2(self, msgTopic=pub.AUTO_TOPIC, **kwarg): self.listen2Topics.append(msgTopic.getName()) my = MyListener() pub.subscribe(my.listen0, 'testSendTopic') pub.subscribe(my.listen1, 'testSendTopic') pub.subscribe(my.listen2, 'testSendTopic') pub.sendMessage('testSendTopic') assert my.count == 1 assert my.heardTopic == True pub.subscribe(my.listen0, 'testSendTopic.subtopic') pub.subscribe(my.listen1, 'testSendTopic.subtopic') pub.subscribe(my.listen2, 'testSendTopic.subtopic') pub.sendMessage('testSendTopic.subtopic') assert my.count == 3 assert [] == [topic for topic in my.listen2Topics if topic not in ('testSendTopic', 'testSendTopic.subtopic')] # type hints on listeners: result = [] def listenerWithHints(a: int, b: bool, c: str = 2): result.append((a, b, c)) topicForHintedListeners = 'topicForHints' pub.subscribe(listenerWithHints, topicForHintedListeners) assert pub.subscribe(listenerWithHints, topicForHintedListeners) pub.sendMessage(topicForHintedListeners, b=456, a=123, c='hello') assert result == [(123, 456, 'hello')]
yield env.timeout(1) def case_done_listener(case=None): # Move the case to the done_pile pile assert case is not None, "case_done_listener: No case provided" done_pile.put(case) def dispatch_work_listener(work=None): # Move the case to the done_pile pile assert work is not None, "dispatch_work_listener: No work provided" dispatch_pile.append(work) pub.subscribe(case_done_listener, 'case_is_done') pub.subscribe(dispatch_work_listener, 'dispatch_work') def assign_work_to_pile(work): """ Assign a work item to the relevant pile depending on the type of the work :param work: :return: """ if work.name in work_piles.keys(): logging.debug('Assigning work item %s to pile %s at %s' % (work, work.name, env.now)) work_piles[work.name].put(work)
def testSubscribeCurriedListeners(): result = [] def proto_listener(a, b, c=1, d=2): pass def listener1(a, b, c=1, d=2, nonTopicArg=3): result.append((a, b, c, d)) # no currying: pub.subscribe(proto_listener, 'topic1') pub.subscribe(listener1, 'topic1') # ok: pub.subscribe(proto_listener, 'topic2') pub.subscribe(listener1, 'topic2', nonTopicArg=4) # curried arg typo: pub.subscribe(proto_listener, 'topic3') pytest.raises(ListenerMismatchError, pub.subscribe, listener1, 'topic3', invalidArg=4) # curried arg is in topic args: pub.subscribe(proto_listener, 'topic4') pytest.raises(ListenerMismatchError, pub.subscribe, listener1, 'topic4', a=4)
def __init__(self): super().__init__() pub.subscribe(self.Thruster_Power_Listener_Single, "Thruster.Power")
def __init__(self): self.Value = 0 self.Level = 0 self.Count = 0 self.History = deque(maxlen=90) pub.subscribe(self.parseData, "data_update")
def __init__(self, *args, **kwargs): super(ModuleList, self).__init__(*args, **kwargs) # 初始化日志类 self.__logger = SingleLogger() # 创建数据库管理类 self.__sql = db_sql() # 当前Module Tab显示的列名 self.AddColumns() # 初始化私有变量 self._monitor_modules_list = { } # 对应每个设备(uuid), 记录这个设备的每个module的名字和位置的对应关系 # self._monitor_modules_log = {} # 对应每个设备(uuid), 记录这个设备的每个module的名字和日志的对应关系 # self._monitor_modules_max_state = {} # 对应每个设备(uuid), 记录这个设备的每个module的名字和状态的对应关系 # 默认的焦点设备,节点和设备的uuid devices_info = DevicesInfo() devices = devices_info.get_devices_name() self.__logger.debug("all devices list = {}".format(devices)) # self.__focus_device = list(devices.keys())[0] self.__focus_node = devices[self.__focus_device][0] self.__focus_uuid = devices_info.get_uuid()[0] # 初始化每个设备,必须监控的模块 for uuid in devices_info.get_uuid(): # 当前Module Tab监控的模块 self._monitor_modules_list[uuid] = { } # {name : index} --> 记录每个module的名字和位置的对应关系 # self._monitor_modules_max_state[uuid] = {} # {name : state} --> 记录每个module的名字和最差状态的对应关系 # self._monitor_modules_log[uuid] = {} # {name : log} --> 记录每个module的名字和日志的对应关系 # self.__focus_uuid = uuid # 显示当前节点必须监控的模块 for module in devices_info.get_module_monitor_name_from_uuid(uuid): item = (module, '') index = self.AddItem(item) self._monitor_modules_list[self.__focus_uuid][module] = {} self._monitor_modules_list[ self.__focus_uuid][module]["index"] = index self._monitor_modules_list[ self.__focus_uuid][module]["log"] = '' self._monitor_modules_list[ self.__focus_uuid][module]["state"] = "none" self.__sql.create_table(uuid=uuid, name=module) # 订阅消息 (module信息传输触发事件消息) self.__pub_module_info_msg_name = 'module_info_event' pub.subscribe(self.OnReceiveModuleEvent, self.__pub_module_info_msg_name) # 绑定公共事件处理 self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected) self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemDoubleClicked) self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnItemRightClicked) # 绑定自定义事件处理 self.Bind(EVT_NODE, self.OnNodeShow)
def __do_subscribe(self): pub.subscribe(self.update, "progress_update")