<jupyter_start><jupyter_text>.. _code_cells: Writing Code and Formatting OutputIPyPublish utilises metadata to mark-up the notebook with information onhow output should be represented in the converted notebook,as shown in :numref:`fig:mpl1`.<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.sin(np.linspace(0, 6)))
plt.show()<jupyter_output><empty_output><jupyter_text>.. seealso::    [The PDF representation of this notebook](_static/code_cells.pdf)    :ref:`metadata_tags`, for a full description and list of ipypublish metadata.. _jupytext_python: Converting Notebooks to Pure PythonTo write code, we can work in the conventional Jupyter Notebook environment,or we can use [jupytext](https://github.com/mwouts/jupytext),to convert between a notebook and the pure python[percent format](https://github.com/mwouts/jupytextthe-percent-format)```console$ jupytext --to py:percent notebook.ipynb$ jupytext --to notebook notebook.py             overwrite notebook.ipynb$ jupytext --to notebook --update notebook.py    update notebook.ipynb```This will produce a standard python file,with commented notebook level metadata commented at the top (in YAML format),and each cell beginning with ``%%`` (known as the percent format):The percent format can be utilised in IDEs, such as[Spyder](https://docs.spyder-ide.org/editor.htmldefining-code-cells),[Atom](https://atom.io/packages/hydrogen),[PyCharm](https://www.jetbrains.com/pycharm/), and[VS Code](https://code.visualstudio.com/docs/python/jupyter-support),to run individual cells:![Running Notebooks in VS Code](_static/vscode_python.png){fig:vscode_py width=60%}.. important::    To preserve ipypublish notebook metadata, you must add:    `"jupytext": {"metadata_filter": {"notebook": "ipub"}}` to    your notebooks metadata before conversion... seealso::    :ref:`jupytext_rmarkdown`    [Using YAML metadata blocks in Pandoc](https://pandoc.org/MANUAL.htmlextension-yaml_metadata_block). NB Setup Helper Functions:py:mod:`ipypublish.scripts.nb_setup` offers a number of useful functions,to setup common packages (matplotlib, pandas, etc) for outputting contentin high quality formats.<jupyter_code>from ipypublish import nb_setup<jupyter_output><empty_output><jupyter_text>.. note::    `ipypublish.scripts.ipynb_latex_setup` is deprecated in v0.9 Text Output<jupyter_code>print("""
This is some printed text,
with a nicely formatted output.
""")<jupyter_output><empty_output><jupyter_text>Images (with PIL)<jupyter_code>import os
from ipypublish.tests import TEST_PIC_PATH

nb_setup.images_hconcat([TEST_PIC_PATH, TEST_PIC_PATH],
               width=600, gap=10)
nb_setup.images_vconcat([TEST_PIC_PATH, TEST_PIC_PATH],
               height=400, gap=10)
nb_setup.images_gridconcat([[_,_] for _ in [TEST_PIC_PATH, TEST_PIC_PATH]],
               height=300, vgap=10,hgap=20)<jupyter_output><empty_output><jupyter_text>Plots (with Matplotlib)A matplotlib figure (+@fig:example_mpl{}), and its code (+@code:example_mpl{}).<jupyter_code>plt = nb_setup.setup_matplotlib(output=('pdf','svg'))
plt.scatter(np.random.rand(10), np.random.rand(10),
            label='data label')
plt.ylabel(r'a y label with latex $\alpha$')
plt.legend();<jupyter_output><empty_output><jupyter_text>.. note::    If outputting the Matplotlib figures in a PDF format.    See [usetex tutorial](https://matplotlib.org/users/usetex.htmlusetex-tutorial),     and [Stackoverflow question](https://stackoverflow.com/questions/38731201/latex-escaping-in-matplotlib). Tables (with pandas)A pandas table (+@tbl:example_pd{}), and its code (+@code:example_pd{}).<jupyter_code>pd = nb_setup.setup_pandas(escape_latex=False)
df = pd.DataFrame(np.random.rand(3,4),columns=['a','b','c','d'])
df.a = ['$\delta$','x','y']
df.b = ['l','m','n']
df.set_index(['a','b'])
df.round(3)<jupyter_output><empty_output><jupyter_text>.. note::    If using `escape_latex=False`, then PDF conversion will throw an error     if there are e.g. `_`'s in your column names. You either need to escape    these manually (`\_`) or use `escape_latex=True`. But note that,     `escape_latex=True` will also escape math (e.g. `$\delta$`) causing it not    to render. Equations (with ipython or sympy)An ipython and sympy equation =[@eqn:example_ipy;@eqn:example_sympy].<jupyter_code>from IPython.display import Latex
Latex('$$ a = b+c $$')
sym = nb_setup.setup_sympy()
f = sym.Function('f')
y = sym.Function('y')
n = sym.symbols(r'\alpha')
f = y(n)-2*y(n-1/sym.pi)-5*y(n-2)
sym.rsolve(f,y(n),[1,4])<jupyter_output><empty_output><jupyter_text>IPywidgets [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/)can be added to the notebook, to create interactive elements.These widgets are preserved in `sphinx` HTML outputs.<jupyter_code>import ipywidgets
slider1 = ipywidgets.FloatSlider()
slider1.description = "Slide Me"
slider1<jupyter_output><empty_output><jupyter_text>Multiple views of the same widget can be created:<jupyter_code>slider1<jupyter_output><empty_output><jupyter_text>Using `jslink`, widgets can also be synced,without the need for an active python kernel:<jupyter_code>slider2 = ipywidgets.BoundedFloatText()
link = ipywidgets.jslink(
    (slider1, 'value'),
    (slider2, 'value'))
slider2<jupyter_output><empty_output><jupyter_text>For more complex examples see: [jupyter.org/widgets](https://jupyter.org/widgets)  Object Output FormatsThe format of the Jupyter Notebook file allows for the storageof a single output in multiple formats. This is taken advantage of bypackages such as matplotlib and pandas, etc to store a figure/table inboth latex and html formats, which can then be selected by ipypublishbased on the document type required.Sometimes a user may wish to have greater control over the output formatand/or which output types are to be stored. It it possible to achievethis *via* the Jupyter `display` function. For example, if we wantedto display a pandas.DataFrame table without the index column, such thatit can be output to both a pdf and html document:<jupyter_code>from IPython.display import display
df = pd.DataFrame(np.random.random((3, 3)))
latex = df.to_latex(index=False)
html = df.to_html(index=False)
display({'text/latex': latex,
        'text/html': html}, raw=True)<jupyter_output><empty_output><jupyter_text>If you wish to create your own object with multiple output formats, youshould create a class with multiple `_repr_*_()` methods:<jupyter_code>class MyObject(object):
    def __init__(self, text):
        self.text = text

    def _repr_latex_(self):
        return "\\textbf{LaTex: " + self.text + "}"

    def _repr_html_(self):
        return "<b>HTML: " + self.text + "</b>"

MyObject('hallo')<jupyter_output><empty_output><jupyter_text>.. seealso::    :ref:`nbformat:notebook_file_format`    [IPython Rich Display](http://ipython.readthedocs.io/en/stable/config/integrating.htmlrich-display).. _multiple_outputs: Multiple Outputs from a Single Code CellSimilarly, with the Jupyter `display` functionality, you can control the outputmetadata for multiple outputs in a single code cell:<jupyter_code>from IPython.display import display
from IPython.display import display_latex
from IPython.display import display_markdown

x = np.linspace(0, 3.42)

for i in range(1,3):

    display_markdown(
      '### Code Created Heading {0}'.format(i), raw=True)

    fig, ax = plt.subplots()
    ax.plot(x, np.sin(x*i))
    metadata={'ipub': {
      'figure': {
        'caption': 'Code Created Heading {0}'.format(i)}}}
    display(fig, metadata=metadata)
    plt.close()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12467053241960992, 'fraction_numerical': 0.008302583025830259, 'mean_word_length': 5.604873803307224, 'pattern_counts': {'":': 3, '<': 55, '<?xml version=': 0, '>': 55, 'https://': 11, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '158287', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 2584, 'n_tokens_neox': 2494, 'n_words': 655, 'path': 'docs/source/code_cells.ipynb', 'repo_name': 'mgeier/ipypublish', 'size': '7588'}