Create a figure from what is returned by :meth:`inspect_figure`
546981
def load_figure(d, new_fig=True):
        """"""
        import matplotlib.pyplot as plt
        subplotpars = d.pop('subplotpars', None)
        if subplotpars is not None:
            subplotpars.pop('validate', None)
            subplotpars = mfig.SubplotParams(**subplotpars)
        if new_fig:
            nums = plt.get_fignums()
            if d.get('num') in nums:
                d['num'] = next(
                    i for i in range(max(plt.get_fignums()) + 1, 0, -1)
                    if i not in nums)
        return plt.figure(subplotpars=subplotpars, **d)
36167
def makefig(code, code_path, output_dir, output_base, config):
    

    # -- Parse format list
    default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 50}
    formats = []
    for fmt in config.plot_formats:
        if isinstance(fmt, str):
            formats.append((fmt, default_dpi.get(fmt, 80)))
        elif type(fmt) in (tuple, list) and len(fmt)==2:
            formats.append((str(fmt[0]), int(fmt[1])))
        else:
            raise PlotError('invalid image format "%r" in plot_formats' % fmt)

    # -- Try to determine if all images already exist

    code_pieces = split_code_at_show(code)

    # Look for single-figure output files first
    all_exists = True
    img = ImageFile(output_base, output_dir)
    for format, dpi in formats:
        if out_of_date(code_path, img.filename(format)):
            all_exists = False
            break
        img.formats.append(format)

    if all_exists:
        return [(code, [img])]

    # Then look for multi-figure output files
    results = []
    all_exists = True
    for i, code_piece in enumerate(code_pieces):
        images = []
        for j in range(1000):
            img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir)
            for format, dpi in formats:
                if out_of_date(code_path, img.filename(format)):
                    all_exists = False
                    break
                img.formats.append(format)

            # assume that if we have one, we have them all
            if not all_exists:
                all_exists = (j > 0)
                break
            images.append(img)
        if not all_exists:
            break
        results.append((code_piece, images))

    if all_exists:
        return results

    # -- We didn't find the files, so build them

    results = []
    ns = {}

    for i, code_piece in enumerate(code_pieces):
        # Clear between runs
        plt.close('all')

        # Run code
        run_code(code_piece, code_path, ns)

        # Collect images
        images = []
        fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
        for j, figman in enumerate(fig_managers):
            if len(fig_managers) == 1 and len(code_pieces) == 1:
                img = ImageFile(output_base, output_dir)
            else:
                img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
                                output_dir)
            images.append(img)
            for format, dpi in formats:
                try:
                    figman.canvas.figure.savefig(img.filename(format), dpi=dpi)
                except exceptions.BaseException as err:
                    raise PlotError(traceback.format_exc())
                img.formats.append(format)

        # Results
        results.append((code_piece, images))

    return results
498366
def make_figure_source_geom(extractors, what):
    
    import matplotlib.pyplot as plt
    fig = plt.figure()
    [ex] = extractors
    sitecol = ex.get('sitecol')
    geom_by_src = vars(ex.get(what))
    ax = fig.add_subplot(1, 1, 1)
    ax.grid(True)
    ax.set_xlabel('Source')
    bmap = basemap('cyl', sitecol)
    for src, geom in geom_by_src.items():
        if src != 'array':
            bmap.plot(geom['lon'], geom['lat'], label=src)
    bmap.plot(sitecol['lon'], sitecol['lat'], 'x')
    ax.legend()
    return plt
155147
def _get_dpi_from(cmd, pattern, func):
    
    try:
        out, _ = run_subprocess([cmd])
    except (OSError, CalledProcessError):
        pass
    else:
        match = re.search(pattern, out)
        if match:
            return func(*map(float, match.groups()))
1350845
def _import_data(data, axis, slice_step, first_slice_offset=0):
    
    try:
        import SimpleITK as sitk
        if type(data) is sitk.SimpleITK.Image:
            data = sitk.GetArrayFromImage(data)
    except:
        pass

    data = __select_slices(data, axis, slice_step, first_slice_offset=first_slice_offset)
    return data
1261387
def inspect
      attributes = to_h.map { |key, value| "#{key}=#{value.inspect}" }.join(', ')

      format(INSPECT_TEMPLATE, class_name: self.class.name, attributes: attributes)
    end
768285
def new_figure_manager_given_figure(num, figure):
    
    canvas = FigureCanvasAgg(figure)
    manager = FigureManagerBase(canvas, num)
    return manager
578928
def new(self, size, fill):
        """"""
        return Image(PIL.Image.new("RGB", size, fill))
1246039
def inspect
      expr = @expr || @unit.expr
      expr = (expr) ? ","+expr.inspect : ""
      sufx = (@@verbose_inspect) ? " "+@unit.inspect : ""
      self.class.to_s+"["+Unit::Utils.num_inspect(@value)+expr+"]"+sufx
    end
994738
def from_image(cls, image):
        
        (w, h) = image.size

        # Thermal paper is 512 pixels wide
        if w > 512:
            ratio = 512. / w
            h = int(h * ratio)
            image = image.resize((512, h), Image.ANTIALIAS)
        if image.mode != '1':
            image = image.convert('1')

        pixels = np.array(list(image.getdata())).reshape(h, w)

        # Add white pixels so that image fits into bytes
        extra_rows = int(math.ceil(h / 24)) * 24 - h
        extra_pixels = np.ones((extra_rows, w), dtype=bool)
        pixels = np.vstack((pixels, extra_pixels))
        h += extra_rows
        nb_stripes = h / 24
        pixels = pixels.reshape(nb_stripes, 24, w).swapaxes(1, 2).reshape(-1, 8)

        nh = int(w / 256)
        nl = w % 256
        data = []

        pixels = np.invert(np.packbits(pixels))
        stripes = np.split(pixels, nb_stripes)

        for stripe in stripes:

            data.extend([
                ESC,
                42,  # *
                33,  # double density mode
                nl,
                nh])

            data.extend(stripe)
            data.extend([
                27,   # ESC
                74,   # J
                48])

        # account for double density mode
        height = h * 2
        return cls(data, height)
999170
def new_figure_manager_given_figure(num, figure):
    
    frame = FigureFrameWxAgg(num, figure)
    figmgr = frame.get_figure_manager()
    if matplotlib.is_interactive():
        figmgr.frame.Show()
    return figmgr
578265
def do_inspect(self, arg):
        
        if arg in self.curframe.f_locals:
            obj = self.curframe.f_locals[arg]
        elif arg in self.curframe.f_globals:
            obj = self.curframe.f_globals[arg]
        else:
            obj = WebPdb.null
        if obj is not WebPdb.null:
            self.console.writeline(
                '{0} = {1}:\n'.format(arg, type(obj))
            )
            for name, value in inspect.getmembers(obj):
                if not (name.startswith('__') and (name.endswith('__'))):
                    self.console.writeline('    {0}: {1}\n'.format(
                        name, self._get_repr(value, pretty=True, indent=8)
                    ))
        else:
            self.console.writeline(
                'NameError: name "{0}" is not defined\n'.format(arg)
            )
        self.console.flush()
1281578
def inspect
      img = []
      @images.each { |image| img << image.inspect }
      img = '[' + img.join(",\n") + "]\nscene=#{@scene}"
    end
1310630
def _make_image(tensor):
    """"""
    assert isinstance(tensor, NDArray)
    if Image is None:
        raise ImportError('need to install PIL for visualizing images')
    height, width, channel = tensor.shape
    tensor = _make_numpy_array(tensor)
    image = Image.fromarray(tensor)
    output = io.BytesIO()
    image.save(output, format='PNG')
    image_string = output.getvalue()
    output.close()
    return Summary.Image(height=height, width=width, colorspace=channel,
                         encoded_image_string=image_string)
1223884
def fig2x(figure, format):
    """"""

    # Save svg to file like object svg_io
    io = StringIO()
    figure.savefig(io, format=format)

    # Rewind the file like object
    io.seek(0)

    data = io.getvalue()
    io.close()

    return data
1131560
def png_img_html_from_pyplot_figure(fig: "Figure",
                                    dpi: int = 100,
                                    extra_html_class: str = None) -> str:
    
    if fig is None:
        return ""
    # Make a file-like object
    memfile = io.BytesIO()
    # In general, can do
    #   fig.savefig(filename/file-like-object/backend, format=...)
    # or
    #   backend.savefig(fig):
    # see e.g. http://matplotlib.org/api/backend_pdf_api.html
    fig.savefig(memfile, format="png", dpi=dpi)
    memfile.seek(0)
    pngblob = memoryview(memfile.read())
    return rnc_web.get_png_img_html(pngblob, extra_html_class)
1285175
def create_figures(self):
        


        try:
            self.horizontalLayout_14.removeWidget(self.matplotlibwidget_1)
            self.matplotlibwidget_1.close()
        except AttributeError:
            pass
        try:
            self.horizontalLayout_15.removeWidget(self.matplotlibwidget_2)
            self.matplotlibwidget_2.close()
        except AttributeError:
            pass
        self.matplotlibwidget_2 = MatplotlibWidget(self.plot_2)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.matplotlibwidget_2.sizePolicy().hasHeightForWidth())
        self.matplotlibwidget_2.setSizePolicy(sizePolicy)
        self.matplotlibwidget_2.setMinimumSize(QtCore.QSize(200, 200))
        self.matplotlibwidget_2.setObjectName("matplotlibwidget_2")
        self.horizontalLayout_16.addWidget(self.matplotlibwidget_2)
        self.matplotlibwidget_1 = MatplotlibWidget(self.plot_1)
        self.matplotlibwidget_1.setMinimumSize(QtCore.QSize(200, 200))
        self.matplotlibwidget_1.setObjectName("matplotlibwidget_1")
        self.horizontalLayout_15.addWidget(self.matplotlibwidget_1)

        self.matplotlibwidget_1.mpl_connect('button_press_event', self.plot_clicked)
        self.matplotlibwidget_2.mpl_connect('button_press_event', self.plot_clicked)

        # adds a toolbar to the plots
        self.mpl_toolbar_1 = NavigationToolbar(self.matplotlibwidget_1.canvas, self.toolbar_space_1)
        self.mpl_toolbar_2 = NavigationToolbar(self.matplotlibwidget_2.canvas, self.toolbar_space_2)
        self.horizontalLayout_9.addWidget(self.mpl_toolbar_2)
        self.horizontalLayout_14.addWidget(self.mpl_toolbar_1)

        self.matplotlibwidget_1.figure.set_tight_layout(True)
        self.matplotlibwidget_2.figure.set_tight_layout(True)