<commit_before>""" Plotly Offline
    A module to use Plotly's graphing library with Python
    without connecting to a public or private plotly enterprise
    server.
"""
from __future__ import absolute_import

import json
import os
import uuid
import warnings
from pkg_resources import resource_string
import webbrowser

import plotly
from plotly import tools, utils

try:
    import IPython
    from IPython.display import HTML, display
    _ipython_imported = True
except ImportError:
    _ipython_imported = False

try:
    import matplotlib
    _matplotlib_imported = True
except ImportError:
    _matplotlib_imported = False


def download_plotlyjs(download_url):
    warnings.warn('''
        `download_plotlyjs` is deprecated and will be removed in the
        next release. plotly.js is shipped with this module, it is no
        longer necessary to download this bundle separately.
    ''', DeprecationWarning)
    pass


def get_plotlyjs():
    path = os.path.join('offline', 'plotly.min.js')
    plotlyjs = resource_string('plotly', path).decode('utf-8')
    return plotlyjs


def init_notebook_mode():
    """
    Initialize plotly.js in the browser if it hasn't been loaded into the DOM
    yet. This is an idempotent method and can and should be called from any
    offline methods that require plotly.js to be loaded into the notebook dom.
    """
    warnings.warn('''
        `init_notebook_mode` is deprecated and will be removed in the
        next release. Notebook mode is now automatically initialized when
        notebook methods are invoked, so it is no
        longer necessary to manually initialize.
    ''', DeprecationWarning)

    if not _ipython_imported:
        raise ImportError('`iplot` can only run inside an IPython Notebook.')

    script_inject = (
        ''
        '<script type=\'text/javascript\'>'
        'if(!window.Plotly){{'
        'define(\'plotly\', function(require, exports, module) {{'
        '{script}'
        '}});'
        'require([\'plotly\'], function(Plotly) {{'
        'console.log(Plotly);'
        'window.Plotly = Plotly;'
        '}});'
        '}}'
        '</script>'
        '').format(script=get_plotlyjs())

    display(HTML(script_inject))


def _plot_html(figure_or_data, show_link, link_text,
               validate, default_width, default_height, global_requirejs):

    figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

    width = figure.get('layout', {}).get('width', default_width)
    height = figure.get('layout', {}).get('height', default_height)

    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    plotdivid = uuid.uuid4()
    jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder)
    jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder)

    config = {}
    config['showLink'] = show_link
    config['linkText'] = link_text
    jconfig = json.dumps(config)

    # TODO: The get_config 'source of truth' should
    # really be somewhere other than plotly.plotly
    plotly_platform_url = plotly.plotly.get_config().get('plotly_domain',
                                                         'https://plot.ly')
    if (plotly_platform_url != 'https://plot.ly' and
            link_text == 'Export to plot.ly'):

        link_domain = plotly_platform_url\
            .replace('https://', '')\
            .replace('http://', '')
        link_text = link_text.replace('plot.ly', link_domain)

    script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format(
        id=plotdivid,
        data=jdata,
        layout=jlayout,
        config=jconfig)

    optional_line1 = ('require(["plotly"], function(Plotly) {{ '
                      if global_requirejs else '')
    optional_line2 = '}});' if global_requirejs else ''

    plotly_html_div = (
        ''
        '<div id="{id}" style="height: {height}; width: {width};" '
        'class="plotly-graph-div">'
        '</div>'
        '<script type="text/javascript">' +
        optional_line1 +
        'window.PLOTLYENV=window.PLOTLYENV || {{}};'
        'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";'
        '{script}' +
        optional_line2 +
        '</script>'
        '').format(
        id=plotdivid, script=script,
        height=height, width=width)

    return plotly_html_div, plotdivid, width, height


def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',
          validate=True):
    """
    Draw plotly graphs inside an IPython notebook without
    connecting to an external server.
    To save the chart to Plotly Cloud or Plotly Enterprise, use
    `plotly.plotly.iplot`.
    To embed an image of the chart, use `plotly.image.ishow`.

    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.

    Keyword arguments:
    show_link (default=True) -- display a link in the bottom-right corner of
                                of the chart that will export the chart to
                                Plotly Cloud or Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
                               are valid? omit if your version of plotly.js
                               has become outdated with your version of
                               graph_reference.json or if you need to include
                               extra, unnecessary keys in your figure.

    Example:
    ```
    from plotly.offline import, iplot

    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
    ```
    """

    init_notebook_mode()
<commit_msg>Bow to the :cow2:<commit_after>""" Plotly Offline
    A module to use Plotly's graphing library with Python
    without connecting to a public or private plotly enterprise
    server.
"""
from __future__ import absolute_import

import json
import os
import uuid
import warnings
from pkg_resources import resource_string
import webbrowser

import plotly
from plotly import tools, utils

try:
    import IPython
    from IPython.display import HTML, display
    _ipython_imported = True
except ImportError:
    _ipython_imported = False

try:
    import matplotlib
    _matplotlib_imported = True
except ImportError:
    _matplotlib_imported = False


def download_plotlyjs(download_url):
    warnings.warn('''
        `download_plotlyjs` is deprecated and will be removed in the
        next release. plotly.js is shipped with this module, it is no
        longer necessary to download this bundle separately.
    ''', DeprecationWarning)
    pass


def get_plotlyjs():
    path = os.path.join('offline', 'plotly.min.js')
    plotlyjs = resource_string('plotly', path).decode('utf-8')
    return plotlyjs


def init_notebook_mode():
    """
    Initialize plotly.js in the browser if it hasn't been loaded into the DOM
    yet. This is an idempotent method and can and should be called from any
    offline methods that require plotly.js to be loaded into the notebook dom.
    """
    warnings.warn('''
        `init_notebook_mode` is deprecated and will be removed in the
        next release. Notebook mode is now automatically initialized when
        notebook methods are invoked, so it is no
        longer necessary to manually initialize.
    ''', DeprecationWarning)

    if not _ipython_imported:
        raise ImportError('`iplot` can only run inside an IPython Notebook.')

    script_inject = (
        ''
        '<script type=\'text/javascript\'>'
        'if(!window.Plotly){{'
        'define(\'plotly\', function(require, exports, module) {{'
        '{script}'
        '}});'
        'require([\'plotly\'], function(Plotly) {{'
        'console.log(Plotly);'
        'window.Plotly = Plotly;'
        '}});'
        '}}'
        '</script>'
        '').format(script=get_plotlyjs())

    display(HTML(script_inject))


def _plot_html(figure_or_data, show_link, link_text,
               validate, default_width, default_height, global_requirejs):

    figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

    width = figure.get('layout', {}).get('width', default_width)
    height = figure.get('layout', {}).get('height', default_height)

    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    plotdivid = uuid.uuid4()
    jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder)
    jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder)

    config = {}
    config['showLink'] = show_link
    config['linkText'] = link_text
    jconfig = json.dumps(config)

    # TODO: The get_config 'source of truth' should
    # really be somewhere other than plotly.plotly
    plotly_platform_url = plotly.plotly.get_config().get('plotly_domain',
                                                         'https://plot.ly')
    if (plotly_platform_url != 'https://plot.ly' and
            link_text == 'Export to plot.ly'):

        link_domain = plotly_platform_url\
            .replace('https://', '')\
            .replace('http://', '')
        link_text = link_text.replace('plot.ly', link_domain)

    script = 'Plotly.newPlot("{id}", {data}, {layout}, {config})'.format(
        id=plotdivid,
        data=jdata,
        layout=jlayout,
        config=jconfig)

    optional_line1 = ('require(["plotly"], function(Plotly) {{ '
                      if global_requirejs else '')
    optional_line2 = '}});' if global_requirejs else ''

    plotly_html_div = (
        ''
        '<div id="{id}" style="height: {height}; width: {width};" '
        'class="plotly-graph-div">'
        '</div>'
        '<script type="text/javascript">' +
        optional_line1 +
        'window.PLOTLYENV=window.PLOTLYENV || {{}};'
        'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";'
        '{script}' +
        optional_line2 +
        '</script>'
        '').format(
        id=plotdivid, script=script,
        height=height, width=width)

    return plotly_html_div, plotdivid, width, height


def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly',
          validate=True):
    """
    Draw plotly graphs inside an IPython notebook without
    connecting to an external server.
    To save the chart to Plotly Cloud or Plotly Enterprise, use
    `plotly.plotly.iplot`.
    To embed an image of the chart, use `plotly.image.ishow`.

    figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
                      dict or list that describes a Plotly graph.
                      See https://plot.ly/python/ for examples of
                      graph descriptions.

    Keyword arguments:
    show_link (default=True) -- display a link in the bottom-right corner of
                                of the chart that will export the chart to
                                Plotly Cloud or Plotly Enterprise
    link_text (default='Export to plot.ly') -- the text of export link
    validate (default=True) -- validate that all of the keys in the figure
                               are valid? omit if your version of plotly.js
                               has become outdated with your version of
                               graph_reference.json or if you need to include
                               extra, unnecessary keys in your figure.

    Example:
    ```
    from plotly.offline import iplot

    iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
    ```
    """

    init_notebook_mode()

{'fraction_non_alphanumeric': 0.10879880129859319, 'fraction_numerical': 0.0020810788312661285, 'mean_word_length': 2.403399433427762, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 8, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3711656', 'n_tokens_mistral': 3539, 'n_tokens_neox': 3468, 'n_words': 997}