Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add/edit code snippets in jupyer notebook?

I tried to follow the instructions given in the README file of the extension. Im using Windows and to open my notebooks I use the jupyter-notebook.exe stored in the directory

..\Anaconda3\Scripts

Within the Anaconda3 directory I go to the subdirectory

Anaconda3\Lib\site-packages\jupyter_contrib_nbextensions\nbextensions\snippets

and there change the code of the file "snippets.json" from

{
"snippets" : [
    {
        "name" : "example",
        "code" : [
            "# This is an example snippet!",
            "# To create your own, add a new snippet block to the",
            "# snippets.json file in your jupyter data directory under nbextensions:",
            "# $(jupyter --data-dir)/nbextensions/snippets/snippets.json",
            "import this"
        ]
    }
]
}

to

{
    "snippets" : [
        {
            "name" : "example",
            "code" : [
                "# This is a test if something changed",
            ]
    ]
}

Then I restart my notebook and insert the example snippet. But my changes weren't adopted, I still get the original example snipped.

What I am doing wrong?

like image 816
zwithouta Avatar asked Oct 27 '25 04:10

zwithouta


1 Answers

If you are using Anaconda, you don't necessarily need to go searching for directories. There is a template embedded in the "Nbextensions" tab.

  • Check "Snippets Menu" box
  • Scroll down to 'Parameters' and check the "Include custom menu...JSON string below" box
  • Insert whatever sample snippet you want
  • Refresh your notebook

Check out one of my snippets:

{
    "name" : "My favorites",
    "sub-menu" : [
        {
            "name" : "import packages",
            "snippet" : ["# import various packages"
                   "import os"
                   "import scipy"
                   "import pandas as pd"
                   "import numpy as np"
                   "import seaborn as sns"
                   "import matplotlib.pyplot as plt"

                   "%matplotlib inline"

                   "# plot settings"
                   "from pandas.plotting import register_matplotlib_converters"
                   "register_matplotlib_converters()"
                   "plt.rcParams['agg.path.chunksize'] = 10000"]
        },
        {
            "name" : "TeX can be written in menu labels $\\alpha_W e\\int_0 \\mu \\epsilon$",
            "snippet" : ["another_new_command(2.78)"]
        }
    ]
}

Also, be careful with the quotations and commas. Additional help on that can be found here.

like image 144
TonyV Avatar answered Oct 30 '25 15:10

TonyV