import the matplotlib modules and set the style
960969
def setup():
    
    import sys
    already_loaded = 'matplotlib' in sys.modules

    # just make sure we can access matplotlib as mpl
    import matplotlib as mpl

    if not already_loaded:
        mpl.use('Agg')

    import matplotlib.pyplot as plt

    plt.style.use('seaborn')

    general_settings()

    import mpl_toolkits.axes_grid1 as axes_grid1
    axes_grid1
    return plt, mpl
855860
def import_fonts(style_less, fontname, font_subdir):
    

    ftype_dict = {'woff2': 'woff2',
                  'woff': 'woff',
                  'ttf': 'truetype',
                  'otf': 'opentype',
                  'svg': 'svg'}

    define_font = (
        "@font-face {{font-family: {fontname};\n\tfont-weight:"
        "{weight};\n\tfont-style: {style};\n\tsrc: local('{fontname}'),"
        "\n\turl('fonts{sepp}{fontfile}') format('{ftype}');}}\n")
    fontname = fontname.split(',')[0]
    fontpath = os.path.join(fonts_dir, font_subdir)
    for fontfile in os.listdir(fontpath):
        if '.txt' in fontfile or 'DS_' in fontfile:
            continue
        weight = 'normal'
        style = 'normal'
        if 'medium' in fontfile:
            weight = 'medium'
        elif 'ital' in fontfile:
            style = 'italic'
        ft = ftype_dict[fontfile.split('.')[-1]]
        style_less += define_font.format(
            fontname=fontname,
            weight=weight,
            style=style,
            sepp='/',
            fontfile=fontfile,
            ftype=ft)
        send_fonts_to_jupyter(os.path.join(fontpath, fontfile))

    return style_less
1155924
def plot(self):
		
		import matplotlib.pyplot as plt
		plt.plot(self.E)
		plt.show()
797017
def plot(self, figure_list):
        '''
        
        '''
        # if there is not image data get it from the current plot
        if not self.data == {} and self.data['image_data'] is  None:
            axes = figure_list[0].axes[0]
            if len(axes.images)>0:
                self.data['image_data'] = np.array(axes.images[0].get_array())
                self.data['extent'] = np.array(axes.images[0].get_extent())
                self.plot_settings['cmap'] = axes.images[0].get_cmap().name
                self.plot_settings['xlabel'] = axes.get_xlabel()
                self.plot_settings['ylabel'] = axes.get_ylabel()
                self.plot_settings['title'] = axes.get_title()
                self.plot_settings['interpol'] = axes.images[0].get_interpolation()

        Script.plot(self, figure_list)
1163094
def set(self, **kwargs):
        
        if len(kwargs)==0: return self
        
        # Set settings
        for k in list(kwargs.keys()): self[k] = kwargs[k]
        
        # Plot if we're supposed to.
        if self['autoplot'] and not self._initializing: self.plot()

        return self
1321207
def _import_module(module_name, warn=True, prefix='_py_', ignore='_'):
    
    try:
        module = __import__(module_name)
    except ImportError:
        if warn:
            warnings.warn("Failed to import module " + module_name)
    else:
        for attr in dir(module):
            if ignore and attr.startswith(ignore):
                continue
            if prefix:
                if attr in globals():
                    globals()[prefix + attr] = globals()[attr]
                elif warn:
                    warnings.warn("No Python implementation of " + attr)
            globals()[attr] = getattr(module, attr)
        return True
1299825
def customize(func):
    
    @wraps(func)
    def call_w_context(*args, **kwargs):
        set_context = kwargs.pop('set_context', True)
        if set_context:
            color_palette = sns.color_palette('colorblind')
            with plotting_context(), axes_style(), color_palette:
                sns.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)
    return call_w_context
668105
def _import(func):
        """"""
        func_name = func.__name__

        # from foo.bar import func // func()
        # WARNING: May be broken in IPython, in which case the widget will use a fallback
        if func_name in globals():
            return func_name

        # import foo.bar // foo.bar.func()
        module_name = func.__module__
        submodules = module_name.split('.')

        if submodules[0] in globals():
            return module_name + '.' + func_name

        # from foo import bar // bar.func()
        for i in range(len(submodules)):
            m = submodules[i]
            if m in globals():
                return '.'.join(submodules[i:]) + '.' + func_name

        # import foo.bar as fb // fb.func()
        module_ref = sys.modules[func.__module__]
        all_globals = globals()

        for n in all_globals:
            if all_globals[n] == module_ref:
                return n + '.' + func_name

        # Not Found, return function name
        return func_name
587204
def ensure_pyplot(self):
        
        # We are here if the @figure pseudo decorator was used. Thus, it's
        # possible that we could be here even if python_mplbackend were set to
        # `None`. That's also strange and perhaps worthy of raising an
        # exception, but for now, we just set the backend to 'agg'.

        if not self._pyplot_imported:
            if 'matplotlib.backends' not in sys.modules:
                # Then ipython_matplotlib was set to None but there was a
                # call to the @figure decorator (and ipython_execlines did
                # not set a backend).
                #raise Exception("No backend was set, but @figure was used!")
                import matplotlib
                matplotlib.use('agg')

            # Always import pyplot into embedded shell.
            self.process_input_line('import matplotlib.pyplot as plt',
                                    store_history=False)
            self._pyplot_imported = True
619430
def apply_ipython_style(shell):
    """"""
    try:
        from IPython.terminal.prompts import Prompts, Token
    except Exception:
        from scapy.error import log_loading
        log_loading.warning(
            "IPython too old. Shell color won't be handled."
        )
        return
    from scapy.config import conf
    scapy_style = {}
    # Overwrite colors
    if isinstance(conf.color_theme, NoTheme):
        shell.colors = 'nocolor'
    elif isinstance(conf.color_theme, BrightTheme):
        # lightbg is optimized for light backgrounds
        shell.colors = 'lightbg'
    elif isinstance(conf.color_theme, ColorOnBlackTheme):
        # linux is optimised for dark backgrounds
        shell.colors = 'linux'
    else:
        # default
        shell.colors = 'neutral'
    try:
        get_ipython()
        # This function actually contains tons of hacks
        color_magic = shell.magics_manager.magics["line"]["colors"]
        color_magic(shell.colors)
    except NameError:
        pass
    # Prompt Style
    if isinstance(conf.prompt, Prompts):
        # Set custom prompt style
        shell.prompts_class = conf.prompt
    else:
        if isinstance(conf.color_theme, (FormatTheme, NoTheme)):
            # Formatable
            if isinstance(conf.color_theme, HTMLTheme):
                prompt = cgi.escape(conf.prompt)
            elif isinstance(conf.color_theme, LatexTheme):
                from scapy.utils import tex_escape
                prompt = tex_escape(conf.prompt)
            else:
                prompt = conf.prompt
            prompt = conf.color_theme.prompt(prompt)
        else:
            # Needs to be manually set
            prompt = str(conf.prompt)
            scapy_style[Token.Prompt] = Color.ansi_to_pygments(
                conf.color_theme.style_prompt
            )

        class ClassicPrompt(Prompts):
            def in_prompt_tokens(self, cli=None):
                return [(Token.Prompt, prompt), ]

            def out_prompt_tokens(self):
                return [(Token.OutPrompt, ''), ]
        # Apply classic prompt style
        shell.prompts_class = ClassicPrompt
        sys.ps1 = prompt
    # Register scapy color style
    shell.highlighting_style_overrides = scapy_style
    # Apply if Live
    try:
        get_ipython().refresh_style()
    except NameError:
        pass
250535
def _init_plot_handles(self):
        
        plots = [self.plot]
        if self.plot.subplots:
            plots += list(self.plot.subplots.values())

        handles = {}
        for plot in plots:
            for k, v in plot.handles.items():
                handles[k] = v
        self.plot_handles = handles

        requested = {}
        for h in self.models+self.extra_models:
            if h in self.plot_handles:
                requested[h] = handles[h]
            elif h in self.extra_models:
                print("Warning %s could not find the %s model. "
                      "The corresponding stream may not work."
                      % (type(self).__name__, h))
        self.handle_ids.update(self._get_stream_handle_ids(requested))

        return requested
1181853
def import_module(module_name):
    """"""
    import sys, os
    import importlib
    sys.path.append(os.path.dirname(__file__))
    return importlib.import_module(module_name)
857007
def import_classes(name, currmodule):
    # type: (unicode, unicode) -> Any
    """"""
    target = None

    # import class or module using currmodule
    if currmodule:
        target = try_import(currmodule + '.' + name)

    # import class or module without currmodule
    if target is None:
        target = try_import(name)

    if target is None:
        raise InheritanceException(
            'Could not import class or module %r specified for '
            'inheritance diagram' % name)

    if inspect.isclass(target):
        # If imported object is a class, just return it
        return [target]
    elif inspect.ismodule(target):
        # If imported object is a module, return classes defined on it
        classes = []
        for cls in target.__dict__.values():
            if inspect.isclass(cls) and cls_is_in_module(cls, mod=target):
                classes.append(cls)
        return classes
    raise InheritanceException('%r specified for inheritance diagram is '
                               'not a class or module' % name)
386294
def setup_figcanvas(self):
        """"""
        self.figcanvas = FigureCanvas(background_color=self.background_color)
        self.figcanvas.installEventFilter(self)
        self.setWidget(self.figcanvas)
615569
def generate_import_from(module_, names):
        
        regular_names = [n for n in names if "::" not in n]
        as_names = [n for n in names if "::" in n]

        line = ""
        if len(regular_names) > 0:
            slots = {"m": module_, "n": ", ".join(sorted(regular_names))}
            line = "from %(m)s import %(n)s" % slots
            if len(line) > LINE_LENGTH_LIMIT:
                slots["n"] = INDENT + (",\n" + INDENT).join(sorted(regular_names)) + ","
                line = "from %(m)s import (\n%(n)s\n)" % slots
            if len(as_names) > 0:
                line += "\n"

        for as_name in as_names:
            a, n = as_name.split("::")
            line += "from %(m)s import %(n)s as %(a)s" % {"m": module_, "n": n, "a": a}
        return line
539884
def install_code_colorscheme(self, name, style_dict):
        
        assert isinstance(name, six.text_type)
        assert isinstance(style_dict, dict)

        self.code_styles[name] = style_dict
17227
def set_broad_fig_style(self):
        ''''''
        plt.rcParams.update({
            'figure.figsize' : [self.frontierswidth/self.inchpercm*4, self.frontierswidth/self.inchpercm*1.5],
        })