def PreDelete(self): pub.unsubAll(topicFilter=self._topic_filter) self.view._objects = {} try: self.view.Destroy() except: pass
def test_ping_cycle(self): _ = SimpleEther("TestEther1") scenarios = [[[SimpleCapability(str(CapabilityRegister.POOL))], 1], [[], 1], [[SimpleCapability(str(CapabilityRegister.AGENT))], 0], [[SimpleCapability("MadeUpCapability")], 0]] for scenario in scenarios: reqd_cap, expected_notification = scenario logging.info( "\n\nTesting Ping Cycle with capabilities [{}]\n\n".format( str(reqd_cap))) ping_srcsink = DummySrcSink("PingSrcSink") task_pool = SimpleTaskPool('Task Pool 1') time.sleep(.25) ping_workref = ping_srcsink.send_ping( required_capabilities=reqd_cap) time.sleep(1) self.assertEqual(expected_notification, len(ping_srcsink.ping_notifications)) if expected_notification > 0: self.assertEqual( ping_workref.id, ping_srcsink.ping_notifications[0].sender_work_ref.id) pub.unsubAll() del task_pool del ping_srcsink return
def OnQuit(self, event): dlg = wx.MessageDialog(None, u"Are you sure you want to close the window?", u"Confirm close", wx.YES_NO) if dlg.ShowModal() == wx.ID_YES: ## RuntimeError: wrapped C/C++ object of type TextCtrl has been deleted ## 主線程關閉了但其他線程還在訪問 --> 取消pubsub的訂閱 --> pub.unsubscribe ## C++ assertion "GetEventHandler() == this" failed at ..\..\src\common\wincmn.cpp(475) in wxWindowBase::~wxWindowBase(): ## any pushed event handlers must have been removed ## 所有推播程序都要關閉 --> pub.unsubAll ## https://pypubsub.readthedocs.io/en/v4.0.3/usage/module_pub.html ## 取消所有pubsub的訂閱 ## (切記要是所有) try: self.taskmode.mgr.UnInit() pub.unsubAll("path") except: pass print("Exit the program : [True] ") wx.CallAfter(self.Destroy) ## Veto()用於防止事件的處理,而Skip()允許事件的傳播和“更多”事件的處理 event.Veto() else: print("Exit the program : [False] ") return
def test_scenario_runner(self): # [task_effort, agent_capacity, num_tasks, num_agents] greedy_policy = GreedyTaskConsumptionPolicy() scenarios = [[1, 1, 1, 1, State.S0, State.S1, greedy_policy], [2, 1, 1, 1, State.S0, State.S1, greedy_policy], [2, 2, 1, 1, State.S0, State.S1, greedy_policy], [2, 4, 1, 1, State.S0, State.S1, greedy_policy], [4, 2, 25, 1, State.S0, State.S1, greedy_policy], [8, 2, 33, 10, State.S0, State.S1, greedy_policy], [100, 1, 1, 1, State.S0, State.S1, greedy_policy], [1, 1, 1, 1, State.S0, State.S8, greedy_policy], [3, 2, 10, 5, State.S0, State.S8, greedy_policy], [10, 2, 100, 10, State.S0, State.S8, greedy_policy], [10, 2, 200, 50, State.S0, State.S8, greedy_policy]] scenarios = [[1, 1, 1, 1, State.S0, State.S2, greedy_policy]] case_num = 1 for task_effort, agent_capacity, num_tasks, num_agents, start_state, end_state, cons_policy in scenarios: case_description \ = "{}: Eff={}, Cap={}, Tsks={}, Agnts={} St={}, Ed={}, Cons={}".format(case_num, task_effort, agent_capacity, num_tasks, num_agents, start_state, end_state, cons_policy) self.scenario_execute(case_description, task_effort, agent_capacity, num_tasks, num_agents, start_state, end_state, cons_policy) pub.unsubAll() case_num += 1 return
def tearDown(self) -> None: pub.unsubAll() if self._ether is not None: del self._ether if self._task_pool is not None: del self._task_pool return
def test_ping_cycle(self): scenarios = [[[SimpleCapability(str(CapabilityRegister.AGENT))], 1], [[], 1], [[SimpleCapability(str(CapabilityRegister.POOL))], 0], [[SimpleCapability("MadeUpCapability")], 0]] for scenario in scenarios: reqd_cap, expected_notification = scenario logging.info( "\n\nTesting Ping Cycle with capabilities [{}]\n\n".format( str(reqd_cap))) sa = SimpleAgent( 'test agent', start_state=State.S0, end_state=State.S1, capacity=1, task_consumption_policy=GreedyTaskConsumptionPolicy(), trace=True) time.sleep(.5) ping_srcsink = DummySrcSink("PingSrcSink", ping_topic=sa.topic) ping_workref = ping_srcsink.send_ping( required_capabilities=reqd_cap) time.sleep(1) self.assertEqual(expected_notification, len(ping_srcsink.ping_notifications)) if expected_notification > 0: self.assertEqual( ping_workref.id, ping_srcsink.ping_notifications[0].sender_work_ref.id) pub.unsubAll() return
def on_exit(self, e=None): """ Exit the Program :param e: Dummy wx event :return: None """ pub.unsubAll() self.Close(True)
def UnRegisterAll(): # type: () -> None """ This function unregister all listeners to messages and will stop call its callback function when the event is raised """ with SysEventManager._dispatch_sys_event_lock: pub.unsubAll() SysEventManager._remove_all_events()
def SystemStop(self): if self.trader.started == True: self.trader.stop() if self.strate.started == True: self.strate.stop() if self.logger.started == True: self.logger.StopServer() pub.unsubAll()
def remove_all_listeners(self, topic: str = None): """Remove all listeners for one or all topics Args: ---- topic : str The topic to stop listening for (default is None). Default will cause unsubscribing from all topics. """ # Note advanced use of function can include both listenerFilter and topicFilter for this # Add when needed try: pub.unsubAll(topicName=topic) except Exception as exc: print(f"Removing all webhooks listeners failed! {exc!r} occurred.") logger.warn( f"Removing all webhooks listeners failed! {exc!r} occurred.")
def testUnsubAll(): def lisnr1(): pass def lisnr2(): pass class MyListener: def __call__(self): pass def meth(self): pass def __hash__(self): return 123 lisnr3 = MyListener() lisnr4 = lisnr3.meth def lisnrSub(listener=None, topic=None, newSub=None): pass pub.subscribe(lisnrSub, 'pubsub.subscribe') assert topicMgr.getTopic('pubsub.subscribe').getNumListeners() == 1 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 filter(lisnr): passes = str(lisnr).endswith('meth') return passes # test unsub many non-pubsub topic listeners subAll() pub.unsubAll('testUnsubAll') assert topicMgr.getTopic('testUnsubAll').getNumListeners() == 0 assert topicMgr.getTopic('pubsub.subscribe').getNumListeners() == 1 # now same but with filter: subAll() unsubed = pub.unsubAll('testUnsubAll', listenerFilter=filter) assert topicMgr.getTopic('testUnsubAll').getNumListeners() == 3 assert topicMgr.getTopic('pubsub.subscribe').getNumListeners() == 1 # test unsub all listeners of all topics subAll() assert topicMgr.getTopic('testUnsubAll').getNumListeners() == 4 unsubed = pub.unsubAll(listenerFilter=filter) assert unsubed == [lisnr4] assert topicMgr.getTopic('testUnsubAll').getNumListeners() == 3 assert topicMgr.getTopic('pubsub.subscribe').getNumListeners() == 1 unsubed = set( pub.unsubAll() ) expect = set([lisnr1, lisnrSub, lisnr3, lisnr2]) # at least all the 'expected' ones were unsub'd; will be others if this # test is run after other unit tests in same py.test run assert unsubed >= expect
def __init__( self, name: str, startup_event: multiprocessing.Event, shutdown_event: multiprocessing.Event, event_q: mptools.MPQueue, work_q: mptools.MPQueue, *args, scan_counter: Optional[multiprocessing.Value] = None, environment: Optional[Environment] = None, **kwargs, ): # Message is rolled by hand and sent via a direct message to the # ProcessManager as we want to announce CREATING at the earliest # possible moment; we can't announce via pypubsub just yet as the # intraprocess<->interprocess republish function is not registered # till later in the construction process msg = EventMessage( msg_src=name, msg_type="PUBSUB", msg=dict( topic="procedure.lifecycle.statechange", kwargs=dict(new_state=ProcedureState.CREATING), ), ) event_q.put(msg) self.name = name self._scan_counter = scan_counter self._environment = environment self.work_q = work_q # user_module will be set on LOAD message self.user_module = None super().__init__(name, startup_event, shutdown_event, event_q, *args, **kwargs) # AT2-591. The forked process inherits all subscriptions of the # parent, which we do not want to maintain in this child process. This # could be done before super().__init__() at the expense of losing the # log message, as logging is set up in the super constructor unsubscribed = pub.unsubAll() self.log( logging.DEBUG, "Unsubscribed %s pypubsub subscriptions in Procedure #%s (PID=%s)", len(unsubscribed), self.name, os.getpid(), ) # Register a callback function so that all pypubsub messages broadcast # in this process are also queued for distribution to remote processes pub.subscribe(self.republish, pub.ALL_TOPICS)
def cleanup(self, callback, error_callback): """ Clean up anything set up during this unit tests. This means stopping any redis servers that were started, and deleting all files and directories that were created. """ # Unsubscribe any listeners, to prevent leaks between tests. # This doesn't stop all leaks, but certainly helps. pub.unsubAll() def finished_shutdown(message): # Remove files that we created. shutil.rmtree(self.params['scratch_dir']) os.unlink(self.configname) callback("Completed cleanup.") def jobmanager_shutdown(message): self.shutdown_managed_redis(finished_shutdown, error_callback) self.job_manager.shutdown(jobmanager_shutdown, error_callback)
def close(self): pub.unsubAll("PieceManager.receive_block") pub.unsubAll("PieceManager.receive_file") pub.unsubAll("PieceManager.update_bitfield") self.torrent = None self.bitfield = None self.pieces = None self.files = None
def unsubAll(self): # print ('Unsubscribing ALL', self._topic_filter) # # topicName – if none given, unsub from all topics # listenerFilter – filter function to apply to listeners, # unsubscribe only the listeners that satisfy # listenerFilter(listener: Listener) == True # topicFilter - topic name, or a filter function to apply to topics; # in latter case, only topics that satisfy # topicFilter(topic name) == True will be affected # # pubsub.pub.unsubAll(topicName=None, listenerFilter=None, # topicFilter=None) # return pub.unsubAll(topicFilter=self._topic_filter)
def startup(self) -> None: """ Connect republishing function to pypubsub. """ super().startup() # AT2-591. Clear any subscriptions inherited from parent process during fork unsubscribed = pub.unsubAll() self.log( logging.DEBUG, "Unsubscribed %s pypubsub subscriptions in Procedure #%s (PID=%s)", len(unsubscribed), self.name, os.getpid(), ) # Request republish method be called for all pypubsub messages pub.subscribe(self.republish, pub.ALL_TOPICS)
def OnLoadPatientData(self, msg): """Update and load the patient data.""" # Skip loading if the dataset is empty or if the dataset is the same if (not len(msg)) or (self.ptdata == msg): return else: # Unsubscribe all listeners to the raw data updated while # it is re-processed pub.unsubAll('patient.updated.raw_data') pub.subscribe(self.OnLoadPatientData, 'patient.updated.raw_data') self.ptdata = msg # Delete the previous notebook pages self.notebook.DeleteAllPages() # Delete the previous toolbar items for t in range(0, self.toolbar.GetToolsCount()): # Only delete the plugin toolbar items if (t >= len(self.maintools)): self.toolbar.DeleteToolByPos(len(self.maintools)) # Delete the previous plugin menus if len(self.menuDict): self.menuPlugins.Delete(wx.ID_SEPARATOR) for menuid, menu in self.menuDict.items(): self.menuPlugins.Delete(menuid) # Remove the menu object from memory del (menu) self.menuDict = {} # Delete the previous export menus if len(self.menuExportDict): self.menuExportItem.Enable(False) for menuid, menu in self.menuExportDict.items(): self.menuExport.Delete(menuid) del (menu) self.menuExportDict = {} # Reset the preferences template self.preftemplate = [{'General': self.generalpreftemplate}] # Initialize the list of subplugins subplugins = [] # Set up the plugins for each plugin entry point of dicompyler for i, plugin in enumerate(self.plugins): # Skip plugin if it doesn't contain the required dictionary # or actually is a proper Python module p = plugin['plugin'] if not hasattr(p, 'pluginProperties') or \ (p.__name__ in self.pluginsDisabled): continue props = p.pluginProperties() # Only load plugin versions that are qualified if (props['plugin_version'] == 1): # Check whether the plugin can view the loaded DICOM data add = False if len(props['min_dicom']): for key in props['min_dicom']: if (key == 'rxdose'): pass elif key in self.ptdata.keys(): add = True else: add = False break # Plugin can view all DICOM data so always load it else: add = True # Initialize the plugin if add: # Load the main panel plugins if (props['plugin_type'] == 'main'): plugin = p.pluginLoader(self.notebook) self.notebook.AddPage(plugin, props['name']) # Load the menu plugins elif (props['plugin_type'] == 'menu'): if not len(self.menuDict): self.menuPlugins.AppendSeparator() self.menuPlugins.Append(100 + i, props['name'] + '...') plugin = p.plugin(self) self.menuDict[100 + i] = plugin self.Bind(wx.EVT_MENU, plugin.pluginMenu, id=100 + i) # Load the export menu plugins elif (props['plugin_type'] == 'export'): if not len(self.menuExportDict): self.menuExportItem.Enable(True) self.menuExport.Append(200 + i, props['menuname']) plugin = p.plugin(self) self.menuExportDict[200 + i] = plugin self.Bind(wx.EVT_MENU, plugin.pluginMenu, id=200 + i) # If a sub-plugin, mark it to be initialized later else: subplugins.append(p) continue # Add the plugin preferences if they exist if hasattr(plugin, 'preferences'): self.preftemplate.append( {props['name']: plugin.preferences}) pub.sendMessage('preferences.updated.template', msg=self.preftemplate) # Load the subplugins and notify the parent plugins for s in subplugins: props = s.pluginProperties() msg = 'plugin.loaded.' + props['plugin_type'] + '.' + s.__name__ pub.sendMessage(msg, msg=s) # Initialize the import location via pubsub pub.subscribe(self.OnImportPrefsChange, 'general.dicom') pub.sendMessage('preferences.requested.values', msg='general.dicom') dlgProgress = guiutil.get_progress_dialog(self, "Loading Patient Data...") self.t = threading.Thread(target=self.LoadPatientDataThread, args=(self, self.ptdata, dlgProgress.OnUpdateProgress, self.OnUpdatePatientData)) self.t.start() dlgProgress.ShowModal() if dlgProgress: dlgProgress.Destroy()
def tearDown(self): pub.unsubAll()
def unregister_listeners(self): pub.unsubAll()
def unregister_events(self): pub.unsubAll() return
def close(self): pub.unsubAll(topicName="do_next_calculation") self.Destroy()
def remove_all_listeners(self, topic: str = None): # Note advanced use of function can include both listenerFilter and topicFilter for this # Add when needed pub.unsubAll(topicName=topic)
def setUp(self): pub.unsubAll() self.answer = None
def close(self, *evt): pub.unsubAll(topicName="progress_update") self.parent.pdf_miner_window = None wx.CallAfter(self.Destroy)
def tearDown(self) -> None: pub.unsubAll()
def unsub_all(): pub.unsubAll()
def __do_unsubscribe(): pub.unsubAll(topicName="progress_update") pub.unsubAll(topicName="progress_set_title") pub.unsubAll(topicName="progress_close")