<commit_before>import sys

from io import BytesIO
from tempfile import NamedTemporaryFile
from contextlib import contextmanager
from itertools import chain

import matplotlib as mpl
from matplotlib import pyplot as plt

from matplotlib.transforms import Bbox, TransformedBbox, Affine2D

import param
from param.parameterized import bothmethod

from ...core import HoloMap
from ...core.options import Store

from ..renderer import Renderer, MIME_TYPES
from .comms import (JupyterComm, NbAggJupyterComm,
                    mpl_msg_handler, mpld3_msg_handler)
from .widgets import MPLSelectionWidget, MPLScrubberWidget
from .util import get_tight_bbox

class OutputWarning(param.Parameterized):pass
outputwarning = OutputWarning(name='Warning')


class MPLRenderer(Renderer):
    """
    Exporter used to render data from matplotlib, either to a stream
    or directly to file.

    The __call__ method renders an HoloViews component to raw data of
    a specified matplotlib format.  The save method is the
    corresponding method for saving a HoloViews objects to disk.

    The save_fig and save_anim methods are used to save matplotlib
    figure and animation objects. These match the two primary return
    types of plotting class implemented with matplotlib.
    """
    drawn = {}

    backend = param.String('matplotlib', doc="The backend name.")

    fig = param.ObjectSelector(default='auto',
                               objects=['png', 'svg', 'pdf', 'html', None, 'auto'], doc="""
        Output render format for static figures. If None, no figure
        rendering will occur. """)

    holomap = param.ObjectSelector(default='auto',
                                   objects=['widgets', 'scrubber', 'webm','mp4', 'gif', None, 'auto'], doc="""
        Output render multi-frame (typically animated) format. If
        None, no multi-frame rendering will occur.""")

    mode = param.ObjectSelector(default='default',
                                objects=['default', 'mpld3', 'nbagg'], doc="""
         The 'mpld3' mode uses the mpld3 library whereas the 'nbagg' uses
         matplotlib's the experimental nbagg backend. """)


    # <format name> : (animation writer, format,  anim_kwargs, extra_args)
    ANIMATION_OPTS = {
        'webm': ('ffmpeg', 'webm', {},
                 ['-vcodec', 'libvpx', '-b', '1000k']),
        'mp4': ('ffmpeg', 'mp4', {'codec': 'libx264'},
                 ['-pix_fmt', 'yuv420p']),
        'gif': ('imagemagick', 'gif', {'fps': 10}, []),
        'scrubber': ('html', None, {'fps': 5}, None)
    }

    mode_formats = {'fig':{'default': ['png', 'svg', 'pdf', 'html', None, 'auto'],
                           'mpld3': ['html', 'json', None, 'auto'],
                           'nbagg': ['html', None, 'auto']},
                    'holomap': {m:['widgets', 'scrubber', 'webm','mp4', 'gif',
                                   'html', None, 'auto']
                                for m in ['default', 'mpld3', 'nbagg']}}

    counter = 0

    # Define appropriate widget classes
    widgets = {'scrubber': MPLScrubberWidget,
               'widgets': MPLSelectionWidget}

    # Define comm targets by mode
    comms = {'default': (JupyterComm, mpl_msg_handler),
             'nbagg':   (NbAggJupyterComm, None),
             'mpld3':   (JupyterComm, mpld3_msg_handler)}

    def __call__(self, obj, fmt='auto'):
        """
        Render the supplied HoloViews component or MPLPlot instance
        using matplotlib.
        """
        plot, fmt =  self._validate(obj, fmt)
        if plot is None: return

        if isinstance(plot, tuple(self.widgets.values())):
            data = plot()
        elif fmt in ['png', 'svg', 'pdf', 'html', 'json']:
            data = self._figure_data(plot, fmt, **({'dpi':self.dpi} if self.dpi else {}))
        else:
            if sys.version_info[0] == 3 and mpl.__version__[:-2] in ['1.2', '1.3']:
                raise Exception("<b>Python 3 matplotlib animation support broken &lt;= 1.3</b>")
            anim = plot.anim(fps=self.fps)
            data = self._anim_data(anim, fmt)

        data = self._apply_post_render_hooks(data, obj, fmt)
        return data, {'file-ext':fmt,
                      'mime_type':MIME_TYPES[fmt]}


    @classmethod
    def plot_options(cls, obj, percent_size):
        """
        Given a holoviews object and a percentage size, apply heuristics
        to compute a suitable figure size. For instance, scaling layouts
        and grids linearly can result in unwieldy figure sizes when there
        are a large number of elements. As ad hoc heuristics are used,
        this functionality is kept separate from the plotting classes
        themselves.

        Used by the IPython Notebook display hooks and the save
        utility. Note that this can be overridden explicitly per object
        using the fig_size and size plot options.
        """
        from .plot import MPLPlot
        factor = percent_size / 100.0
        obj = obj.last if isinstance(obj, HoloMap) else obj
        options = Store.lookup_options(cls.backend, obj, 'plot').options
        fig_size = options.get('fig_size', MPLPlot.fig_size)*factor

        return dict({'fig_size':fig_size},
                    **Store.lookup_options(cls.backend, obj, 'plot').options)


    @bothmethod
    def get_size(self_or_cls, plot):
        w, h = plot.state.get_size_inches()
        dpi = plot.state.dpi
        return (w*dpi, h*dpi)


    def diff(self, plot):
        """
        Returns the latest plot data to update an existing plot.
        """
        data = None
        if self.mode != 'nbagg':
            if self.mode == 'mpld3':
                figure_format = 'json'
            elif self.fig == 'auto':
                figure_format = self.renderer.params('fig').objects[0]
            else:
                figure_format = self.fig
            data = self.html(plot, figure_format, comm=False)
        return data

<commit_msg>Fixed bug in renderer required for testing<commit_after>import sys

from io import BytesIO
from tempfile import NamedTemporaryFile
from contextlib import contextmanager
from itertools import chain

import matplotlib as mpl
from matplotlib import pyplot as plt

from matplotlib.transforms import Bbox, TransformedBbox, Affine2D

import param
from param.parameterized import bothmethod

from ...core import HoloMap
from ...core.options import Store

from ..renderer import Renderer, MIME_TYPES
from .comms import (JupyterComm, NbAggJupyterComm,
                    mpl_msg_handler, mpld3_msg_handler)
from .widgets import MPLSelectionWidget, MPLScrubberWidget
from .util import get_tight_bbox

class OutputWarning(param.Parameterized):pass
outputwarning = OutputWarning(name='Warning')


class MPLRenderer(Renderer):
    """
    Exporter used to render data from matplotlib, either to a stream
    or directly to file.

    The __call__ method renders an HoloViews component to raw data of
    a specified matplotlib format.  The save method is the
    corresponding method for saving a HoloViews objects to disk.

    The save_fig and save_anim methods are used to save matplotlib
    figure and animation objects. These match the two primary return
    types of plotting class implemented with matplotlib.
    """
    drawn = {}

    backend = param.String('matplotlib', doc="The backend name.")

    fig = param.ObjectSelector(default='auto',
                               objects=['png', 'svg', 'pdf', 'html', None, 'auto'], doc="""
        Output render format for static figures. If None, no figure
        rendering will occur. """)

    holomap = param.ObjectSelector(default='auto',
                                   objects=['widgets', 'scrubber', 'webm','mp4', 'gif', None, 'auto'], doc="""
        Output render multi-frame (typically animated) format. If
        None, no multi-frame rendering will occur.""")

    mode = param.ObjectSelector(default='default',
                                objects=['default', 'mpld3', 'nbagg'], doc="""
         The 'mpld3' mode uses the mpld3 library whereas the 'nbagg' uses
         matplotlib's the experimental nbagg backend. """)


    # <format name> : (animation writer, format,  anim_kwargs, extra_args)
    ANIMATION_OPTS = {
        'webm': ('ffmpeg', 'webm', {},
                 ['-vcodec', 'libvpx', '-b', '1000k']),
        'mp4': ('ffmpeg', 'mp4', {'codec': 'libx264'},
                 ['-pix_fmt', 'yuv420p']),
        'gif': ('imagemagick', 'gif', {'fps': 10}, []),
        'scrubber': ('html', None, {'fps': 5}, None)
    }

    mode_formats = {'fig':{'default': ['png', 'svg', 'pdf', 'html', None, 'auto'],
                           'mpld3': ['html', 'json', None, 'auto'],
                           'nbagg': ['html', None, 'auto']},
                    'holomap': {m:['widgets', 'scrubber', 'webm','mp4', 'gif',
                                   'html', None, 'auto']
                                for m in ['default', 'mpld3', 'nbagg']}}

    counter = 0

    # Define appropriate widget classes
    widgets = {'scrubber': MPLScrubberWidget,
               'widgets': MPLSelectionWidget}

    # Define comm targets by mode
    comms = {'default': (JupyterComm, mpl_msg_handler),
             'nbagg':   (NbAggJupyterComm, None),
             'mpld3':   (JupyterComm, mpld3_msg_handler)}

    def __call__(self, obj, fmt='auto'):
        """
        Render the supplied HoloViews component or MPLPlot instance
        using matplotlib.
        """
        plot, fmt =  self._validate(obj, fmt)
        if plot is None: return

        if isinstance(plot, tuple(self.widgets.values())):
            data = plot()
        elif fmt in ['png', 'svg', 'pdf', 'html', 'json']:
            data = self._figure_data(plot, fmt, **({'dpi':self.dpi} if self.dpi else {}))
        else:
            if sys.version_info[0] == 3 and mpl.__version__[:-2] in ['1.2', '1.3']:
                raise Exception("<b>Python 3 matplotlib animation support broken &lt;= 1.3</b>")
            anim = plot.anim(fps=self.fps)
            data = self._anim_data(anim, fmt)

        data = self._apply_post_render_hooks(data, obj, fmt)
        return data, {'file-ext':fmt,
                      'mime_type':MIME_TYPES[fmt]}


    @classmethod
    def plot_options(cls, obj, percent_size):
        """
        Given a holoviews object and a percentage size, apply heuristics
        to compute a suitable figure size. For instance, scaling layouts
        and grids linearly can result in unwieldy figure sizes when there
        are a large number of elements. As ad hoc heuristics are used,
        this functionality is kept separate from the plotting classes
        themselves.

        Used by the IPython Notebook display hooks and the save
        utility. Note that this can be overridden explicitly per object
        using the fig_size and size plot options.
        """
        from .plot import MPLPlot
        factor = percent_size / 100.0
        obj = obj.last if isinstance(obj, HoloMap) else obj
        options = Store.lookup_options(cls.backend, obj, 'plot').options
        fig_size = options.get('fig_size', MPLPlot.fig_size)*factor

        return dict({'fig_size':fig_size},
                    **Store.lookup_options(cls.backend, obj, 'plot').options)


    @bothmethod
    def get_size(self_or_cls, plot):
        w, h = plot.state.get_size_inches()
        dpi = plot.state.dpi
        return (w*dpi, h*dpi)


    def diff(self, plot):
        """
        Returns the latest plot data to update an existing plot.
        """
        data = None
        if self.mode != 'nbagg':
            if self.mode == 'mpld3':
                figure_format = 'json'
            elif self.fig == 'auto':
                figure_format = self.params('fig').objects[0]
            else:
                figure_format = self.fig
            data = self.html(plot, figure_format, comm=False)
        return data


{'fraction_non_alphanumeric': 0.11550075490689482, 'fraction_numerical': 0.007213554772689146, 'mean_word_length': 2.371889140271493, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '800873', 'n_tokens_mistral': 3540, 'n_tokens_neox': 3401, 'n_words': 1090}