Jupyter nbextensions

I wrote a collection of techniques that are useful to remember by using the nb extension of Jupyter Notebook.

--Installation --Config --Creating a config file --Browser specification --Automatic save

Installation

Official ipython-contrib / jupyter_contrib_nbextensions

$ conda install -c conda-forge jupyter_contrib_nbextensions

This is the easiest because it will drop css


Config

Creating a config file

$ jupyter notebook --generate-config

Browser specification

Jupyter Notebook opens in a browser that opens by default if not specified.

Since key bindings will often be worn in the future, the browser that opens the jupyter notebook selects "unused" = "shortcut keys are not customized".

Look for the line # c.NotebookApp.browser ='' in the created ~ \ .jupyter \ jupyter_notebook_config.py and specify the browser.

python:~/.jupyter/jupyter_notebook_config.py


import webbrowser
webbrowser.register('chrome', None, webbrowser.GenericBrowser('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'))
c.NotebookApp.browser = 'chrome'

reference:

Auto save

Is jupyter notebook every 2 minutes by default? Will save it. (The save interval can be changed with ʻauto save time of nbextension` described below)

If you write the following in ~ / .jupyter / jupyter_notebook_config.py

Is created.

python:~/.jupyter/jupyter_notebook_config.py


import os
from subprocess import check_call

def post_save(model, os_path, contents_manager):
    """post-save hook for converting notebooks to .py scripts
Every time ipynb is saved[py, html, md, tex, pdf]To create."""
    if model['type'] != 'notebook':
        return # only do this for notebooks
    d, fname = os.path.split(os_path)
    base, ext = os.path.splitext(fname)
    check_call(['jupyter', 'nbconvert', '--to', 'script', fname], cwd=d)
    check_call(['jupyter', 'nbconvert', '--to', 'html', fname], cwd=d)
    check_call(['jupyter', 'nbconvert', '--to', 'markdown', fname], cwd=d)
    # check_call(['jupyter-nbconvert', '--to', 'latex', fname, '--template', 'jsarticle.tplx'], cwd=d)
    # check_call(['extractbb', base+'_files/*.png'], cwd=d)
    # check_call(['platex', '-interaction=nonstopmode', '-synctex=1', '-kanji=utf8', '-guess-input-enc' , base+'.tex'], cwd=d)
    # check_call(['dvipdfmx', base+'.dvi'], cwd=d)

c.FileContentsManager.post_save_hook = post_save
import os
from subprocess import check_call

def post_save(model, os_path, contents_manager):
    """post-save hook for converting notebooks to .py scripts
Every time ipynb is saved[py, html, md, tex, pdf]To create."""
    if model['type'] != 'notebook':
        return # only do this for notebooks
    d, fname = os.path.split(os_path)
    check_call(['jupyter', 'nbconvert', '--to', 'script', fname], cwd=d)
    check_call(['jupyter', 'nbconvert', '--to', 'html', fname], cwd=d)
    check_call(['jupyter', 'nbconvert', '--to', 'markdown', fname], cwd=d)
    check_call(['jupyter', 'nbconvert', '--to', 'latex', '--template', 'jsarticle.tplx', 'lualatex', fname], cwd=d)

c.FileContentsManager.post_save_hook = post_save

TeX generation

If you use Japanese, you cannot use Export as PDF on the menu bar.

Because the documentclass of \ documentclass [a4paper, dvipdfmx] {jsarticle} is generated in English.

So create a tex file with jsarticle applied to the style

Use template file (jsarticle.tplx)

If you prepare a template file (here, jsarticle.tplx), it will be rewritten to jsarticle and generated.

When executing the nbconvert command

Execute jupyter nbconvert --to latex --template jsarticle.tplx lualatex <filename>

The specific method is as follows.

~~ 1. Put jsarticle.tplx in the place where the environment variable of tex passes (such as where platex.exe is) ~~

  1. Create a jsarticle.tplx file under <...> \ Anaconda3 \ Lib \ site-packages \ nbconvert \ templates \ latex`.

<...> is your Anaconda directory. In my case, C: \ tools \ Anaconda3 \.

  1. Type the command jupyter-nbconvert --to latex% 1 --template jsarticle.tplx, which automatically converts to jsarticle, into the terminal. % 1 is the file name and% 2 is the file base name.
  2. Export the image as png. Images are saved under the directory under the file base name under the work directory as the folder name. ʻExtractbb% 2_files /*.png`

jsarticle


% Default to the notebook output style
((* if not cell_style is defined *))
    ((* set cell_style = 'style_ipython.tplx' *))
((* endif *))

% Inherit from the specified cell style.
((* extends cell_style *))

%===============================================================================
% Latex Article
%===============================================================================

((* block docclass *))
\documentclass[a4paper,dvipdfmx]{jsarticle}
((* endblock docclass *))

reference: Memo of Hashikure engineer-Jupyter nbconvert (file conversion) memo Automatically create HTML with Qiita --Jupyter notebook

Build TeX with Sublime Text 3

So far, I wrote it in sublime text-build format and executed it with build (ctrl + b). (Therefore, the file name may be% 1 or an argument.)

Jupyter2PDF.sublime-build


{
    "cmd":["Jupyter2PDF.bat","$file","$file_base_name"],
}

Jupyter2PDF.bat


@echo off
jupyter-nbconvert --to latex %1 --template jsarticle.tplx
extractbb %2_files/*.png

platex run

Below here, you have to retype the file name, not% 1 and% 2 as arguments.

  1. Run platex on the command line. I'm screaming that the platex% 2.tex.sty file isn't there, but keep pressing Enter to continue.
  2. Run dvipdfmx on the command line. dvipdfmx% 2.dvi

Open pdf with Sumatra PDF

The pdf has been created so far.

  1. If you want to go to the tex source when you click pdf, start SumatraPDF with reuse-instance. SumatraPDF -reuse-instance% 2.pdf

nbextensions

If you check with nbextention, the settings will be saved in ~ / .jupyter / nbconfig / notebook.json. My environment looks like this

python:~/.jupyter/nbconfig/notebook.json


{
  "code_format_hotkey": "Ctrl-Alt-D",
  "kse_rebinds": {
    "command": [
      {
        "action_name": "auto:autogenerated-function () {\n                    IPython.notebook.edit_mode();\n                    return false;\n                }",
        "from": "esc"
      }
    ],
    "edit": [
      {
        "action_name": "jupyter-notebook:run-cell-and-insert-below",
        "from": "alt-enter"
      },
      {
        "to": "alt-enter",
        "action_name": "auto:autogenerated-function () {\n                    var cell = IPython.notebook.get_selected_cell();\n                    var mode = cell.mode;\n                    cell.execute();\n                    if (mode === \"edit\") IPython.notebook.edit_mode();\n                    return false;\n                }",
        "from": "ctrl-enter"
      }
    ]
  },
  "limit_output": 1000,
  "stored_keymap": "sublime",
  "load_extensions": {
    "exercise/main": false,
    "collapsible_headings/main": true,
    "python-markdown/main": true,
    "autosavetime/main": true,
    "spellchecker/main": false,
    "dragdrop/main": true,
    "nbpresent/js/nbpresent.min": true,
    "highlighter/highlighter": true,
    "hide_input/main": true,
    "runtools/main": false,
    "hinterland/hinterland": false,
    "contrib_nbextensions_help_item/main": true,
    "keyboard_shortcut_editor/main": true,
    "init_cell/main": true,
    "splitcell/splitcell": true,
    "toggle_all_line_numbers/main": false,
    "freeze/main": true,
    "hide_input_all/main": true,
    "move_selected_cells/main": true,
    "nb_anacondacloud/main": true,
    "select_keymap/main": true,
    "nb_conda/main": true,
    "code_prettify/code_prettify": true,
    "ruler/main": false,
    "navigation-hotkeys/main": true,
    "limit_output/main": false,
    "printview/main": true,
    "nbextensions_configurator/config_menu/main": true,
    "jupyter-js-widgets/extension": true,
    "execute_time/ExecuteTime": true,
    "toc2/main": true,
    "scratchpad/main": true,
    "search-replace/main": false,
    "codefolding/main": true,
    "exercise2/main": false,
    "qtconsole/qtconsole": true
  },
  "kse_show_rebinds": true,
  "autosavetime_starting_interval": "5"
}

Jupyter Notebook settings related

Nbextensions edit menu item "nbextensions_configurator/config_menu/main": true, Nbextension config is added to the menu bar ʻEdit, and you can move to the nbextension screen by clicking it. It's easy to understand and convenient because you usually have to enter localhost: 8888 / nbextensions /` in the address field of your browser.

editmenuitem.png

Nbextensions dashboard tab "nbextensions_configurator/config_menu/main": true, The nbextension settings menu appears in the menu bar of the Jupyter Notebook home screen.

I want to set either Nbextensions edit menu item.

dashboard.png

Select CodeMirror Keymap "select_keymap/main": true, Can vim and Sublime text keymaps be darker than the default? For example, even if I put Sublime in the keymap by default, I couldn't do "Select in parentheses" ctrl + shift + m or" Select multiple lines "ctrl + alt + up <down>. Can be executed by setting to True. Convenient and unavoidable "Multiple selection of selected character strings" ctrl + d often overlaps with" Register bookmark "of the browser, so I change the key with an add-on.

For Firefox, Menu Wizard For Chrome Keyconfig

Split Cells Notebook "splitcell/splitcell": true, Divide into left and right paragraphs. Shortcut key is Shift + S

"stored_keymap": "sublime"

Collapsible Headings "collapsible_headings/main": true, You can close cells for each hierarchy of Heading (markdown cell heading #).

collapsibleheading.png

Input related

Freeze "freeze/main": true, read-only: Can be executed but cannot be rewritten frozen: cannot be written or executed

freeze.png

Codefolding "codefolding/main": true, Fold the indented code. Shortcut key is ʻalt + f`

codefolding.png

Hide input "hide_input/main": true, Hide individual cell inputs.

hideinput.png

Hide input all "hide_input_all/main": true,

Hide input in all cells. Only the result can be output, which is convenient for creating pdfs and presentations.

hideinputall.png

Move selected cells "move_selected_cells/main": true,

It seems that you can move cells with Alt + ↑ / Alt + ↓, but for some reason I can't do it in my environment

Code prettify

"code_prettify/code_prettify": true,

If you press the hammer icon that appears when you enable it, it will fix the python code so that it follows pep8 etc.

Modifying python code has to drop yapf.

conda install --channel https://conda.anaconda.org/conda-forge yapf

I haven't tried it, but for R ʻinstall.packages ("formatR", repos = "http://cran.rstudio.com")`

For javascript, you have to drop the module to format with npm install js-beautify.

codeprettify.gif

"toggle_all_line_numbers/main": true, Number all cells with row numbers. It is possible to assign a cell number to each cell with the default setting (shortcut L) of jupyter-notebook, so do not use it.

toggleallnumber.png

Limit Output "limit_output/main": true,

If you write the following function to ~ \ .jupyter \ jupyter_notebook_config.py, the output will be automatically collapsed when the output of 1000 lines or more is output.

from notebook.services.config import ConfigManager
cm = ConfigManager().update('notebook', {'limit_output': 1000})

Output related

"execute_time/ExecuteTime": true, Display the execution time. Only the cell selected from Cell on the menu bar / Execution time display can be switched in all cells.

Printview "printview/main": true You can easily see the preview converted to html or pdf format without doing Download as ....


Markdown related

"highlighter/highlighter": true, Markdown cell highlights

"dragdrop/main": true, Image embedding. In markdown cell

<img  src="http://127.0.0.1:8888/notebooks/myimage.png "/>

You can write it like this, but for those who want to make progress with D & D.

Python Markdown "python-markdown/main": true, A mix of python code and markdown.

python-markdown-post.png python-markdown-pre.png


Kernel related

"keyboard_shortcut_editor/main": true,

An edit icon for keyboard shortcuts is added to the keyboard shortcut list.

To call a keyboard shortcut, search for show keyboard shortcut from the command palette (ctrl + shift + p), or press h in normal mode.

keyboardshoetcuteditor.png

Launch QTConsole "qtconsole/qtconsole": true, Start qtcosele by taking over the objects on the current kernel. I don't like the fact that ~~ style remains the default white. ~~ ← Solved. Write to jupyter_qtconsole_config.py as follows

Create ~ / .jupyter / jupyter_qtconsole_config.py

c.JupyterWidget.syntax_style = "monokai"

If you type in, it will always start up in the monokai style when you start up qtconsole.

** If you just want to give it a try, we recommend the Scratchpad listed below **

Scratchpad notebook extension "scratchpad/main": true, Useful when you want to easily try out the code without polluting the current kernel. Display the input screen on the right side of the screen Shortcut key is ctrl + b

scratchpad.gif

Navigation-Hotkeys "navigation-hotkeys/main": true

Add a new shortcut key (likely)

Edit-mode hotkeys:
pageup - scroll page up
pagedown - scroll page down
Alt- + - Split cell and keep cursor position
Alt- - - Combine cell and keep cursor position
Alt-n - Toggle line number display in current codecell
Shift-Enter - Execute cell, goto next cell and stay in edit mode if next cell is a code cell or unredered markdown cell
Ctrl-Enter - Execute cell and stay in edit mode if cell is a code cell
Ctrl-y - toggle celltype between markdown and code
Command-mode hotkeys:
esc - toggle to edit mode
home - Go to top of notebook
end - Go to bottom of notebook
pageup - scroll page up
pagedown - scroll page down

reference Memo like a Hashikure engineer --Try using the extension of Jupyter Notebook Add Qiita --extension to build a more comfortable Jupyter environment

Relation

Reference list

My page

JupyterNotebook Shortcut key, TeX, image embedding, etc., a lot of information to be covered (copy and paste)

Explanation of python development environment including Jupyter, Ipython as well as Jupyter Notebook

Recommended Posts

Jupyter nbextensions
Jupyter begins
Jupyter Tips 4
Jupyter Tips 5
Jupyter Tips 3
Jupyter Tips 2
Jupyter installation
Jupyter tricks
Jupyter installation error
Jupyter Notebook memo
Introducing Jupyter Notebook
Jupyter Lab begins
Powerful Jupyter Notebook
Golang on jupyter
Bash in Jupyter
Jupyter on AWS
Jupyter Study Note_002
Jupyter notebook password
Build Jupyter Hub
Jupyter Notebook memo
Jupyter study notes_008
Jupyter study notes_004
jupyter qtconsole config
Jupyter study notes_001
Jupyter Study Note_003
Jupyter Study Note_007
Jupyter Study Note_005