def start(self, application): """ Starts the plugin. """ # Tell the FBI to wiretap all unauthorized exceptions: enable_fbi() push_exception_handler( handler=lambda obj, name, old, new: fbi(), locked=False, main=True)
def setup(): # If a trait exception occurs, fail the test. push_exception_handler( handler=lambda o, t, ov, nv: None, reraise_exceptions=True, main=True, )
def remote_main(parent_workflow_conn, parent_mpl_conn, log_q, running_event): # this should only ever be main method after a spawn() call # (not fork). So we should have a fresh logger to set up. # messages that end up at the root logger to go log_q from logging.handlers import QueueHandler h = QueueHandler(log_q) logging.getLogger().addHandler(h) # We want matplotlib to use our backend .... in both the GUI and the # remote process. Must be called BEFORE cytoflow is imported import matplotlib matplotlib.use('module://cytoflowgui.matplotlib_backend_remote') from traits.api import push_exception_handler from cytoflowgui.workflow import RemoteWorkflow # install a global (gui) error handler for traits notifications push_exception_handler(handler=log_notification_handler, reraise_exceptions=False, main=True) sys.excepthook = log_excepthook # take care of the 3 places in the cytoflow module that # need different behavior in a GUI import cytoflow cytoflow.RUNNING_IN_GUI = True running_event.set() RemoteWorkflow().run(parent_workflow_conn, parent_mpl_conn)
def start ( self, application ): """ Starts the plugin. """ # Tell the FBI to wiretap all unauthorized exceptions: enable_fbi() push_exception_handler( handler = lambda obj, name, old, new: fbi(), locked = False, main = True )
def traits_test_context(): """Context to raise errors in trait handlers.""" from traits.api import push_exception_handler push_exception_handler(reraise_exceptions=True) try: yield finally: push_exception_handler(reraise_exceptions=False)
def setUp(self): self.binder = DummyBinder() self.model = DummyModel() self.blah = DummyBinder() self.context = dict( object=self.model, blah=self.blah, ) push_exception_handler(lambda *args, **kwds: None, reraise_exceptions=True)
def remote_main(parent_workflow_conn, parent_mpl_conn, log_q): from cytoflowgui.workflow import RemoteWorkflow # install a global (gui) error handler for traits notifications push_exception_handler(handler=log_notification_handler, reraise_exceptions=debug, main=True) sys.excepthook = log_excepthook RemoteWorkflow().run(parent_workflow_conn, parent_mpl_conn, log_q)
def test_validator_change(self): """ Check that changing a validator works properly. """ output = [False] def handler(obj, name, old, new): output[0] = True push_exception_handler(handler) old = self.component.validator self.component.validator = IntValidator() self.component.validator = old pop_exception_handler() self.assertTrue(output[0])
def reraise_exceptions(logger=_TRAITSUI_LOGGER): """ Context manager to capture all exceptions occurred in the context and then reraise a RuntimeError if there are any exceptions captured. Exceptions from traits change notifications are also captured and reraised. Depending on the GUI toolkit backend, unexpected exceptions occurred in the GUI event loop may (1) cause fatal early exit of the test suite or (2) be printed to the console without causing the test to error. This context manager is intended for testing purpose such that unexpected exceptions will result in a test error. Parameters ---------- logger : logging.Logger Logger to use for logging errors. """ serialized_exceptions = [] def excepthook(type, value, tb): serialized = _serialize_exception(type, value, tb) serialized_exceptions.append(serialized) logger.error("Unexpected error captured in sys excepthook. \n%s", serialized[-1]) def handler(object, name, old, new): type, value, tb = sys.exc_info() serialized_exceptions.append(_serialize_exception(type, value, tb)) logger.exception( "Unexpected error occurred from change handler " "(object: %r, name: %r, old: %r, new: %r).", object, name, old, new, ) push_exception_handler(handler=handler) sys.excepthook = excepthook try: yield finally: sys.excepthook = sys.__excepthook__ pop_exception_handler() if serialized_exceptions: msg = "Uncaught exceptions found.\n" msg += "\n".join("=== Exception (type: {}, value: {}) ===\n" "{}".format(*record) for record in serialized_exceptions) raise RuntimeError(msg)
def setUp(self): """ Prepares the test fixture before each test method is called. """ self.preferences = set_default_preferences(Preferences()) # The filename of the example preferences file. self.example = os.fspath(files(PKG) / "example.ini") # A temporary directory that can safely be written to. self.tmpdir = tempfile.mkdtemp() # Path to a temporary file self.tmpfile = os.path.join(self.tmpdir, "tmp.ini") push_exception_handler(reraise_exceptions=True) self.addCleanup(pop_exception_handler)
def init_error_handlers(debug = False): """ Initialize application error handlers. """ # Configure logging. logging.basicConfig() logger = logging.getLogger('nemesis') logger.setLevel(logging.DEBUG if debug else logging.WARN) # Prevent Traits from suppressing errors. push_exception_handler(handler = lambda o, t, ov, nv: None, reraise_exceptions = True, main = True, locked = True) # Install GUI exception handler. if not debug: sys.excepthook = gui_except_hook
def setUp(self): # Start up a QApplication if needed. self.app = QtGui.QApplication.instance() if self.app is None: self.app = QtGui.QApplication([]) push_exception_handler(reraise_exceptions=True) # We make a new class here to test that the traits get added only at # the right time. # WARNING: If anyone instantiates Binder() itself, this subclass will # see its added traits, and the test will fail. class Object(Binder): qclass = QtCore.QObject x = QtDynamicProperty(10) self.Object = Object
def remote_main(parent_workflow_conn, parent_mpl_conn, log_q, running_event): # We want matplotlib to use our backend .... in both the GUI and the # remote process. Must be called BEFORE cytoflow is imported import matplotlib matplotlib.use('module://cytoflowgui.matplotlib_backend') from traits.api import push_exception_handler from cytoflowgui.workflow import RemoteWorkflow # install a global (gui) error handler for traits notifications push_exception_handler(handler=log_notification_handler, reraise_exceptions=False, main=True) sys.excepthook = log_excepthook running_event.set() RemoteWorkflow().run(parent_workflow_conn, parent_mpl_conn, log_q)
def notification_context(handler=null_handler, reraise_exceptions=True, main=False, locked=True): """ Context manager to temporarily add a TraitsExceptionHandler We use a context manager to ensure that the exception handler gets cleared no matter what. Default behaviour is to use the null_handler with exceptions re-raised, which means any exceptions which occur will be passed through. """ yield push_exception_handler(handler, reraise_exceptions, main, locked) pop_exception_handler()
def main(): """ A program for visualizing Sim4Life EM fields from scES simulations """ configuration = ConfigParser() configuration.read_file(open('src/default.ini')) configuration.read(['config.ini']) push_exception_handler(reraise_exceptions=True) # Create the GUI (this does NOT start the GUI event loop). gui = GUI() # Create a Task and add it to a TaskWindow. task = S4LVisualizationTask(configuration=configuration) window = TaskWindow( size=(configuration.getint('Display', 'window_width'), configuration.getint('Display', 'window_height'))) window.add_task(task) # Show the window. window.open() # Start the GUI event loop. gui.start_event_loop()
def run(self): options, args = self.parseargs() logger = logging.getLogger() if options.debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.WARNING) sys.excepthook = self.excepthook traits.push_exception_handler(self.trait_exception_handler, main=True, locked=True) if options.pypy: if platform.system() == 'Windows' and sys.executable: prefix = os.path.dirname(sys.executable) pypymanager.set_executable(os.path.join(prefix, 'pypy', 'pypy.exe')) else: pypymanager.set_executable('pypy') pypymanager.launch_delegate() try: app = wx.App(False) self.moduleloader = modules.loader.Loader() self.ui = self.edit_traits() self.context.uiparent = self.ui.control self.context.plot = self.plot self.prefs.restore_window('main', self.ui) self.init_recent_menu() if args: # passing in 'self' for the info argument is a bit of a hack, but fortunately self.ui.context seems to be working fine self.ui.handler.do_open(self, args[0]) # silently ignore multiple projects for Windows Explorer integration app.MainLoop() finally: pypymanager.shutdown_delegate()
def remote_main(parent_workflow_conn, parent_mpl_conn, log_q, running_event): # We want matplotlib to use our backend .... in both the GUI and the # remote process. Must be called BEFORE cytoflow is imported import matplotlib matplotlib.use('module://cytoflowgui.matplotlib_backend_remote') from traits.api import push_exception_handler from cytoflowgui.workflow import RemoteWorkflow # install a global (gui) error handler for traits notifications push_exception_handler(handler = log_notification_handler, reraise_exceptions = False, main = True) sys.excepthook = log_excepthook # take care of the 3 places in the cytoflow module that # need different behavior in a GUI import cytoflow cytoflow.RUNNING_IN_GUI = True running_event.set() RemoteWorkflow().run(parent_workflow_conn, parent_mpl_conn, log_q)
import pandas as pd from traits.api import (HasTraits, File, Property, Int, Str, Dict, List, Type, Bool, Either, push_exception_handler, cached_property, Array, Instance, Float, Any) from pysemantic.utils import TypeEncoder, get_md5_checksum, colnames from pysemantic.custom_traits import (DTypesDict, NaturalNumber, AbsFile, ValidTraitList) try: from yaml import CDumper as Dumper from yaml import CLoader as Loader except ImportError: from yaml import Dumper, Loader push_exception_handler(lambda *args: None, reraise_exceptions=True) logger = logging.getLogger(__name__) class DataFrameValidator(HasTraits): """A validator class for `pandas.DataFrame` objects.""" # The dataframe in question data = Instance(pd.DataFrame) # the column rules to be enforced column_rules = Dict # rules related to the dataset itself rules = Dict
def setUp(self): super(TestUiLoader, self).setUp() push_exception_handler(reraise_exceptions=True)
def setup_package(): push_exception_handler(handler=lambda *args, **kwds: None, reraise_exceptions=True)
def __enter__(self): self.notification_handler = push_exception_handler(self.handler, self.reraise_exceptions, self.main, self.locked) return self
def run_gui(): debug = ("--debug" in sys.argv) remote_process, remote_connection = start_remote_process(debug) import matplotlib # We want matplotlib to use our backend matplotlib.use('module://cytoflowgui.matplotlib_backend') # getting real tired of the matplotlib deprecation warnings import warnings warnings.filterwarnings('ignore', '.*is deprecated and replaced with.*') from traits.api import push_exception_handler def QtMsgHandler(msg_type, msg_string): # Convert Qt msg type to logging level log_level = [ logging.DEBUG, logging.WARN, logging.ERROR, logging.FATAL ][int(msg_type)] logging.log(log_level, 'Qt message: ' + msg_string.decode('utf-8')) ## monkey-patch envisage for a py3k bug. this is fixed in envisage HEAD, ## so check for version import envisage if envisage.__version__ == '4.6.0': import pickle from envisage.ui.tasks.tasks_application import TasksApplication, TasksApplicationState logger = logging.getLogger(__name__) logger.info("Monkey-patching envisage 4.6.0") def _envisage_load_state(self): """ Loads saved application state, if possible. """ state = TasksApplicationState() filename = os.path.join(self.state_location, 'application_memento') if os.path.exists(filename): # Attempt to unpickle the saved application state. try: with open(filename, 'rb') as f: restored_state = pickle.load(f) if state.version == restored_state.version: state = restored_state else: logger.warn('Discarding outdated application layout') except: # If anything goes wrong, log the error and continue. logger.exception('Restoring application layout from %s', filename) self._state = state def _envisage_save_state(self): """ Saves the application state. """ # Grab the current window layouts. window_layouts = [w.get_window_layout() for w in self.windows] self._state.previous_window_layouts = window_layouts # Attempt to pickle the application state. filename = os.path.join(self.state_location, 'application_memento') try: with open(filename, 'wb') as f: pickle.dump(self._state, f) except: # If anything goes wrong, log the error and continue. logger.exception('Saving application layout') TasksApplication._load_state = _envisage_load_state TasksApplication._save_state = _envisage_save_state from envisage.core_plugin import CorePlugin from envisage.ui.tasks.tasks_plugin import TasksPlugin from pyface.image_resource import ImageResource from cytoflowgui.flow_task import FlowTaskPlugin from cytoflowgui.cytoflow_application import CytoflowApplication from cytoflowgui.op_plugins import ( ImportPlugin, ThresholdPlugin, RangePlugin, QuadPlugin, Range2DPlugin, PolygonPlugin, BinningPlugin, GaussianMixture1DPlugin, GaussianMixture2DPlugin, BleedthroughLinearPlugin, #BleedthroughPiecewisePlugin, BeadCalibrationPlugin, AutofluorescencePlugin, ColorTranslationPlugin, TasbePlugin, ChannelStatisticPlugin, TransformStatisticPlugin, RatioPlugin) from cytoflowgui.view_plugins import ( HistogramPlugin, Histogram2DPlugin, ScatterplotPlugin, BarChartPlugin, Stats1DPlugin, Kde1DPlugin, #Kde2DPlugin, ViolinPlotPlugin, TablePlugin, Stats2DPlugin) # assert(multiprocessing.get_start_method() == "spawn") from cytoflow.utility.custom_traits import Removed, Deprecated Removed.gui = True Deprecated.gui = True from pyface.qt import qt_api cmd_line = " ".join(sys.argv) if qt_api == "pyside": print("Cytoflow uses PyQT; but it is trying to use PySide instead.") print(" - Make sure PyQT is installed.") print( " - If both are installed, and you don't need both, uninstall PySide." ) print(" - If you must have both installed, select PyQT by setting the") print(" environment variable QT_API to \"pyqt\"") print(" * eg, on Linux, type on the command line:") print(" QT_API=\"pyqt\" " + cmd_line) print(" * on Windows, try: ") print(" setx QT_API \"pyqt\"") sys.exit(1) from pyface.qt.QtCore import qInstallMsgHandler qInstallMsgHandler(QtMsgHandler) # if we're frozen, add _MEIPASS to the pyface search path for icons etc if getattr(sys, 'frozen', False): from pyface.resource_manager import resource_manager resource_manager.extra_paths.append(sys._MEIPASS) # @UndefinedVariable # install a global (gui) error handler for traits notifications push_exception_handler(handler=log_notification_handler, reraise_exceptions=debug, main=True) sys.excepthook = log_excepthook plugins = [ CorePlugin(), TasksPlugin(), FlowTaskPlugin(debug=debug, remote_connection=remote_connection) ] # reverse of the order on the toolbar view_plugins = [ TablePlugin(), Stats2DPlugin(), Stats1DPlugin(), BarChartPlugin(), ViolinPlotPlugin(), # Kde2DPlugin(), # disabled until we can make it faster Kde1DPlugin(), Histogram2DPlugin(), ScatterplotPlugin(), HistogramPlugin() ] plugins.extend(view_plugins) op_plugins = [ RatioPlugin(), TransformStatisticPlugin(), ChannelStatisticPlugin(), TasbePlugin(), ColorTranslationPlugin(), AutofluorescencePlugin(), BeadCalibrationPlugin(), # BleedthroughPiecewisePlugin(), BleedthroughLinearPlugin(), GaussianMixture2DPlugin(), GaussianMixture1DPlugin(), BinningPlugin(), PolygonPlugin(), QuadPlugin(), Range2DPlugin(), RangePlugin(), ThresholdPlugin(), ImportPlugin() ] plugins.extend(op_plugins) # these two lines stop pkg_resources from trying to load resources # from the __main__ module, which is frozen (and thus not loadable.) icon = ImageResource('icon') icon.search_path = [] app = CytoflowApplication(id='edu.mit.synbio.cytoflow', plugins=plugins, icon=icon, debug=debug) app.run() remote_process.join() logging.shutdown()
def setUp(self): push_exception_handler(lambda *args: None, reraise_exceptions=True)
def setUp(self): push_exception_handler(reraise_exceptions=True)
def setUp(self): def ignore(*args): pass push_exception_handler(handler=ignore, reraise_exceptions=True)
def setUp(self): push_exception_handler(reraise_exceptions=True) self.addCleanup(pop_exception_handler)
def rotate_scene(t): """ Rotate the camera of the mayavi scene at time t. :param t: time in the range [0, duration] :return: a screenshot of the scene """ mlab.view(azimuth=360 / duration * t, elevation=63, distance=distance) return mlab.screenshot(figure=myfig, mode='rgb', antialiased=True) # return a RGB image ############# # load data # ############# push_exception_handler( reraise_exceptions=True) # force exceptions to be re-raised in Traits root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename(initialdir=homedir, title="Select the diffraction pattern", filetypes=[("NPZ", "*.npz")]) data, _ = util.load_file(file_path) assert data.ndim == 3, 'data should be a 3D array' nz, ny, nx = data.shape print("Initial data shape: ", nz, ny, nx) file_path = filedialog.askopenfilename(initialdir=homedir, title="Select q values", filetypes=[("NPZ", "*.npz")])
from mayavi import mlab from mayavi.core import lut_manager from mayavi.core.ui.api import MlabSceneModel, SceneEditor from mayavi.core.ui.mayavi_scene import MayaviScene from pyface.api import FileDialog, OK, confirm, YES, GUI from tvtk.api import tvtk from traits.api import push_exception_handler push_exception_handler( handler = lambda o,t,ov,nv: None, reraise_exceptions = True, main = True, locked = True ) class MouseHandler(object): """ interactor style for escher application. how to do right clicking on mousepad? create toggle button for mousepad? rotation needs be improved; pick point on right click and match it to raycasted point left click; for spline manipulation, raycast to sphere for height editor, pick world coord on surface """ def __init__(self, interactor): self.interactor = interactor
def __enter__(self): self.notification_handler = push_exception_handler( self.handler, self.reraise_exceptions, self.main, self.locked) return self
def run_gui(): import os, sys try: # if we're running as a one-click from a MacOS app, # we need to reset the working directory os.chdir(sys._MEIPASS) except: # if we're not running as a one-click, fail gracefully pass # take care of the 3 places in the cytoflow module that # need different behavior in a GUI import cytoflow cytoflow.RUNNING_IN_GUI = True # this is ridiculous, but here's the situation. Qt5 now uses Chromium # as their web renderer. Chromium needs OpenGL. if you don't # initialize OpoenGL here, things crash on some platforms. # so now i guess we depend on opengl too. from OpenGL import GL # @UnresolvedImport @UnusedImport # check that we're using the right Qt API from pyface.qt import qt_api cmd_line = " ".join(sys.argv) if qt_api == "pyside": print("Cytoflow uses PyQT; but it is trying to use PySide instead.") print(" - Make sure PyQT is installed.") print( " - If both are installed, and you don't need both, uninstall PySide." ) print(" - If you must have both installed, select PyQT by setting the") print(" environment variable QT_API to \"pyqt5\"") print(" * eg, on Linux, type on the command line:") print(" QT_API=\"pyqt5\" " + cmd_line) print(" * on Windows, try: ") print(" setx QT_API \"pyqt5\"") sys.exit(1) # parse args parser = argparse.ArgumentParser(description='Cytoflow GUI') parser.add_argument("--debug", action='store_true') parser.add_argument("filename", nargs='?', default="") args = parser.parse_args() # start the remote process remote_process, remote_connection, queue_listener = start_remote_process() # getting real tired of the matplotlib deprecation warnings import warnings warnings.filterwarnings('ignore', '.*is deprecated and replaced with.*') # if we're frozen, add _MEIPASS to the pyface search path for icons etc if getattr(sys, 'frozen', False): from pyface.resource_manager import resource_manager resource_manager.extra_paths.append(sys._MEIPASS) # @UndefinedVariable # these three lines stop pkg_resources from trying to load resources # from the __main__ module, which is frozen (and thus not loadable.) from pyface.image_resource import ImageResource icon = ImageResource('icon') icon.search_path = [] # monkey patch the resource manager to use SVGs for icons import pyface.resource.resource_manager pyface.resource.resource_manager.ResourceManager.IMAGE_EXTENSIONS.append( '.svg') # monkey patch checklist editor to stop lowercasing import traitsui.qt4.check_list_editor # @UnusedImport traitsui.qt4.check_list_editor.capitalize = lambda s: s # define and install a message handler for Qt errors from traits.api import push_exception_handler def QtMsgHandler(msg_type, msg_context, msg_string): # Convert Qt msg type to logging level log_level = [ logging.DEBUG, logging.WARN, logging.ERROR, logging.FATAL ][int(msg_type)] logging.log(log_level, 'Qt message: ' + msg_string) from pyface.qt.QtCore import qInstallMessageHandler # @UnresolvedImport qInstallMessageHandler(QtMsgHandler) # install a global (gui) error handler for traits notifications push_exception_handler(handler=log_notification_handler, reraise_exceptions=False, main=True) sys.excepthook = log_excepthook # Import, then load, the envisage plugins from envisage.core_plugin import CorePlugin from envisage.ui.tasks.tasks_plugin import TasksPlugin from cytoflowgui.flow_task import FlowTaskPlugin from cytoflowgui.tasbe_task import TASBETaskPlugin from cytoflowgui.export_task import ExportFigurePlugin from cytoflowgui.cytoflow_application import CytoflowApplication from cytoflowgui.op_plugins import ( ImportPlugin, ThresholdPlugin, RangePlugin, QuadPlugin, Range2DPlugin, PolygonPlugin, BinningPlugin, GaussianMixture1DPlugin, GaussianMixture2DPlugin, BleedthroughLinearPlugin, BeadCalibrationPlugin, AutofluorescencePlugin, ColorTranslationPlugin, TasbePlugin, ChannelStatisticPlugin, TransformStatisticPlugin, RatioPlugin, DensityGatePlugin, FlowPeaksPlugin, KMeansPlugin, PCAPlugin) from cytoflowgui.view_plugins import ( HistogramPlugin, Histogram2DPlugin, ScatterplotPlugin, BarChartPlugin, Stats1DPlugin, Kde1DPlugin, Kde2DPlugin, ViolinPlotPlugin, TablePlugin, Stats2DPlugin, DensityPlugin, ParallelCoordinatesPlugin, RadvizPlugin) plugins = [ CorePlugin(), TasksPlugin(), FlowTaskPlugin(), TASBETaskPlugin(), ExportFigurePlugin() ] # ordered as we want them to show up in the toolbar view_plugins = [ HistogramPlugin(), ScatterplotPlugin(), Histogram2DPlugin(), DensityPlugin(), Kde1DPlugin(), Kde2DPlugin(), RadvizPlugin(), ParallelCoordinatesPlugin(), ViolinPlotPlugin(), BarChartPlugin(), Stats1DPlugin(), Stats2DPlugin(), TablePlugin() ] plugins.extend(view_plugins) op_plugins = [ ImportPlugin(), ThresholdPlugin(), RangePlugin(), QuadPlugin(), Range2DPlugin(), PolygonPlugin(), RatioPlugin(), ChannelStatisticPlugin(), TransformStatisticPlugin(), BinningPlugin(), GaussianMixture1DPlugin(), GaussianMixture2DPlugin(), DensityGatePlugin(), KMeansPlugin(), FlowPeaksPlugin(), PCAPlugin(), AutofluorescencePlugin(), BleedthroughLinearPlugin(), BeadCalibrationPlugin(), ColorTranslationPlugin(), TasbePlugin() ] plugins.extend(op_plugins) # start the app app = CytoflowApplication(id='edu.mit.synbio.cytoflow', plugins=plugins, icon=icon, remote_process=remote_process, remote_connection=remote_connection, filename=args.filename, debug=args.debug) from pyface.qt import QtGui QtGui.QApplication.instance().setStyle( QtGui.QStyleFactory.create('Fusion')) app.run() remote_process.join() queue_listener.stop() logging.shutdown()
def setup(): # If a trait exception occurs, fail the test. push_exception_handler( handler = lambda o,t,ov,nv: None, reraise_exceptions = True, main = True, )
import numpy as np from numpy.testing import assert_allclose from traits.testing.unittest_tools import UnittestTools from traits.api import push_exception_handler import vtk from mayavi import mlab from mayavi.core.engine import Engine from tvtk.api import tvtk from mayavi.tools.engine_manager import engine_manager from mayavi.core.registry import registry from mayavi.tests.common import get_example_data push_exception_handler(reraise_exceptions=True) # XXX should probably be elsewhere ################################################################################ # class `TestMlabNullEngine` ############################################################################### class TestMlabNullEngine(unittest.TestCase): """ Stub mlab to isolate as well as possible from creation of a new figure. """ def _stop_unregister_all_engines(self): # Some tests leave around engines hanging around, so we clean them # up to avoid strange test errors. for engine in list(registry.engines.values()): engine.stop()
import numpy as np from numpy.testing import assert_allclose from traits.testing.unittest_tools import UnittestTools from traits.api import push_exception_handler import vtk from mayavi import mlab from mayavi.core.engine import Engine from tvtk.api import tvtk from mayavi.tools.engine_manager import engine_manager from mayavi.core.registry import registry from mayavi.tests.common import get_example_data # XXX should probably be elsewhere push_exception_handler(reraise_exceptions=True) class TestMlabNullEngine(unittest.TestCase): """ Stub mlab to isolate as well as possible from creation of a new figure. """ def _stop_unregister_all_engines(self): # Some tests leave around engines hanging around, so we clean them # up to avoid strange test errors. for engine in list(registry.engines.values()): engine.stop() registry.unregister_engine(engine) def setUp(self):
def main(): # show complete stacktraces for debugging push_exception_handler(reraise_exceptions=True) gui = CiteOverlapGUI() gui.configure_traits()
def setUp(self): push_exception_handler(handler=lambda *args: None, reraise_exceptions=True) self.addTypeEqualityFunc(traits_listener.ListenerItem, partial(assert_listener_item_equal, self))
import logging import click from envisage.core_plugin import CorePlugin from envisage.ui.tasks.tasks_plugin import TasksPlugin from stevedore import extension from stevedore.exception import NoMatches from traits.api import push_exception_handler from force_bdss.core_plugins.factory_registry_plugin import ( FactoryRegistryPlugin) from force_wfmanager.version import __version__ from force_wfmanager.wfmanager import WfManager from force_wfmanager.plugins.wfmanager_plugin import WfManagerPlugin push_exception_handler(lambda *args: None, reraise_exceptions=True) @click.command() @click.version_option(version=__version__) @click.option('--debug', is_flag=True, default=False, help="Prints extra debug information in force_wfmanager.log") @click.option('--profile', is_flag=True, default=False, help="Run GUI under cProfile, creating .prof and .pstats " "files in the current directory.") @click.option('--window-size', nargs=2,
except Exception: pass else: scrapers += ('mayavi',) try: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) import pyvista pyvista.OFF_SCREEN = False except Exception: pass else: scrapers += ('pyvista',) if any(x in scrapers for x in ('pyvista', 'mayavi')): from traits.api import push_exception_handler push_exception_handler(reraise_exceptions=True) report_scraper = mne.report._ReportScraper() scrapers += (report_scraper,) else: report_scraper = None if 'pyvista' in scrapers: brain_scraper = mne.viz._brain._BrainScraper() scrapers = list(scrapers) scrapers.insert(scrapers.index('pyvista'), brain_scraper) scrapers = tuple(scrapers) def append_attr_meth_examples(app, what, name, obj, options, lines): """Append SG examples backreferences to method and attr docstrings.""" # NumpyDoc nicely embeds method and attribute docstrings for us, but it # does not respect the autodoc templates that would otherwise insert