<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Notebook snippets, tips and tricks
TODO
Step1:  Useful keyboard shortcuts
Enter edit mode
Step2:  3D plots
Step3:  Animations
Step4:  Interactive plots with Plotly
TODO
Step5:  IPython built-in magic commands
See http
Step7:  Load an external python script
Load the full script
Step8:  Load a specific symbol (funtion, class, ...)
Step10:  Load specific lines
Step11:  Time measurement
%time
Step12:  %timeit
Step13:  ipywidget
On jupyter lab, you should install widgets extension first (see https
Step14:  ipywidgets.interact
Documentation
See http
Step15:  Using interact as a decorator with named parameters
To me, this is the best option for single usage functions...
Text
Step16:  Integer (IntSlider)
Step17:  Float (FloatSlider)
Step18:  Boolean (Checkbox)
Step19:  List (Dropdown)
Step20:  Dictionnary (Dropdown)
Step21:  Using interact as a decorator
Text
Step22:  Integer (IntSlider)
Step23:  Float (FloatSlider)
Step24:  Boolean (Checkbox)
Step25:  List (Dropdown)
Step26:  Dictionnary (Dropdown)
Step27:  Using interact as a function
To me, this is the best option for multiple usage functions...
Text
Step28:  Integer (IntSlider)
Step29:  Float (FloatSlider)
Step30:  Boolean (Checkbox)
Step31:  List (Dropdown)
Step32:  Dictionnary (Dropdown)
Step33:  Example of using multiple widgets on one function
Step34:  Display images (PNG, JPEG, GIF, ...)
Within a code cell (using IPython.display)
Step35:  Within a Markdown cell
Sound player widget
See
Step36:  Generate a sound
Step37:  Generate a multi-channel (stereo or more) sound
Step38:  From URL
Step39:  From file
Step40:  From bytes
Step41:  Youtube widget
Class for embedding a YouTube Video in an IPython session, based on its video id.
e.g. to embed the video from https
<ASSISTANT_TASK:>
Python Code:
%matplotlib notebook
# As an alternative, one may use: %pylab notebook
# For old Matplotlib and Ipython versions, use the non-interactive version:
# %matplotlib inline or %pylab inline
# To ignore warnings (http://stackoverflow.com/questions/9031783/hide-all-warnings-in-ipython)
import warnings
warnings.filterwarnings('ignore')
import math
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets
from ipywidgets import interact
Explanation: Notebook snippets, tips and tricks
TODO:
* Read https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/
* Read http://blog.juliusschulz.de/blog/ultimate-ipython-notebook
* howto avoid loosing matplotlib interactive rendering when a document is converted to HTML ?
  * https://www.reddit.com/r/IPython/comments/36p360/try_matplotlib_notebook_for_interactive_plots/
  * http://stackoverflow.com/questions/36151181/exporting-interactive-jupyter-notebook-to-html
  * https://jakevdp.github.io/blog/2013/12/05/static-interactive-widgets/
* table of contents (JS)
* matplotlib / D3.js interaction
* matplotlib animations: how to make it faster
* inspiration
  * http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/
  * https://github.com/ltiao/notebooks
  * https://blog.dominodatalab.com/lesser-known-ways-of-using-notebooks/
* Howto make (personalized) Reveal.js slides from this notebook: https://forum.poppy-project.org/t/utiliser-jupyter-pour-des-presentations-etape-par-etape-use-jupyter-to-present-step-by-step/2271/2
* See https://blog.dominodatalab.com/lesser-known-ways-of-using-notebooks/
Extension wishlist and todo:
- Table of content
- Hide some blocks in the HTML export
    - See https://github.com/jupyter/notebook/issues/534
- Customize CSS in HTML export
- Add disqus in HTML export
    - See: https://github.com/jupyter/nbviewer/issues/80
    - Example: http://nbviewer.jupyter.org/gist/tonyfast/977184c1243287e7e55e
- Add metadata header/footer (initial publication date, last revision date, author, email, website, license, ...)
- Vim like editor/navigation shortcut keys (search, search+edit, ...)
- Spell checking
    - See https://github.com/ipython/ipython/issues/3216#issuecomment-59507673 and http://www.simulkade.com/posts/2015-04-07-spell-checking-in-jupyter-notebooks.html
Inspiration:
- https://github.com/jupyter/jupyter/wiki/A-gallery-of-interesting-Jupyter-Notebooks
Import directives
End of explanation
x = np.arange(-2 * np.pi, 2 * np.pi, 0.1)
y = np.sin(x)
plt.plot(x, y)
Explanation: Useful keyboard shortcuts
Enter edit mode: Enter
Enter command mode: Escape
In command mode:
Show keyboard shortcuts: h
Find and replace: f
Insert a cell above the selection: a
Insert a cell below the selection: b
Switch to Markdown: m
Delete the selected cells: dd (type twice 'd' quickly)
Undo cell deletion: z
Execute the selected cell: Ctrl + Enter
Execute the selected cell and select the next cell: Shift + Enter
Execute the selected cell and insert below: Alt + Enter
Toggle output: o
Toggle line number: l
Copy selected cells: c
Paste copied cells below: v
Select the previous cell: k
Select the next cell: j
Merge selected cells, or current cell with cell below if only one cell selected: Shift + m
In edit mode:
Code completion or indent: Tab
Tooltip: Shift + Tab
Type "Shift + Tab" twice to see the online documentation of the selected element
Type "Shift + Tab" 4 times to the online documentation in a dedicated frame
Indent: ⌘]  (on MacOS)
Dedent: ⌘[  (on MacOS)
Execute the selected cell: Ctrl + Enter
Execute the selected cell and select the next cell: Shift + Enter
Execute the selected cell and insert below: Alt + Enter
Cut a cell at the current cursor position: Ctrl + Shift + -
Matplotlib
To plot a figure within a notebook, insert the
%matplotlib notebook (or %pylab notebook)
directive at the begining of the document.
As an alternative, one may use
%matplotlib inline (or %pylab inline)
for non-interactive plots on old Matplotlib/Ipython versions.
2D plots
End of explanation
from mpl_toolkits.mplot3d import axes3d
# Build datas ###############
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
xx,yy = np.meshgrid(x, y)
z = np.sin(np.sqrt(xx**2 + yy**2))
# Plot data #################
fig = plt.figure()
ax = axes3d.Axes3D(fig)
ax.plot_wireframe(xx, yy, z)
plt.show()
Explanation: 3D plots
End of explanation
from matplotlib.animation import FuncAnimation
# Plots
fig, ax = plt.subplots()
def update(frame):
    x = np.arange(frame/10., frame/10. + 2. * math.pi, 0.1)
    ax.clear()
    ax.plot(x, np.cos(x))
    # Optional: save plots
    filename = "img_{:03}.png".format(frame)
    plt.savefig(filename)
# Note: "interval" is in ms
anim = FuncAnimation(fig, update, interval=100)
plt.show()
Explanation: Animations
End of explanation
%%html
<div id="toc"></div>
%%javascript
var toc = document.getElementById("toc");
toc.innerHTML = "<b>Table of contents:</b>";
toc.innerHTML += "<ol>"
var h_list = $("h2, h3");    //$("h2");    // document.getElementsByTagName("h2");
for(var i = 0 ; i < h_list.length ; i++) {
    var h = h_list[i];
    var h_str = h.textContent.slice(0, -1);  // "slice(0, -1)" remove the last character
    if(h_str.length > 0) {
        if(h.tagName == "H2") {  // https://stackoverflow.com/questions/10539419/javascript-get-elements-tag
            toc.innerHTML += "<li><a href=\"#" + h_str.replace(/\s+/g, '-') + "\">" + h_str + "</a></li>";
        } else if(h.tagName == "H3") {  // https://stackoverflow.com/questions/10539419/javascript-get-elements-tag
            toc.innerHTML += "<li> &nbsp;&nbsp;&nbsp; <a href=\"#" + h_str.replace(/\s+/g, '-') + "\">" + h_str + "</a></li>";
        }
    }
}
toc.innerHTML += "</ol>"
Explanation: Interactive plots with Plotly
TODO: https://plot.ly/ipython-notebooks/
Interactive plots with Bokeh
TODO: http://bokeh.pydata.org/en/latest/docs/user_guide/notebook.html
Embedded HTML and Javascript
End of explanation
%run ./notebook_snippets_run_test.py
%run ./notebook_snippets_run_mpl_test.py
Explanation: IPython built-in magic commands
See http://ipython.readthedocs.io/en/stable/interactive/magics.html
Execute an external python script
End of explanation
# %load ./notebook_snippets_run_mpl_test.py
#!/usr/bin/env python3
# Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
This module has been written to illustrate the ``%run`` magic command in
``notebook_snippets.ipynb``.
import numpy as np
import matplotlib.pyplot as plt
def main():
    x = np.arange(-10, 10, 0.1)
    y = np.cos(x)
    plt.plot(x, y)
    plt.grid(True)
    plt.show()
if __name__ == '__main__':
    main()
Explanation: Load an external python script
Load the full script
End of explanation
# %load -s main ./notebook_snippets_run_mpl_test.py
def main():
    x = np.arange(-10, 10, 0.1)
    y = np.cos(x)
    plt.plot(x, y)
    plt.grid(True)
    plt.show()
Explanation: Load a specific symbol (funtion, class, ...)
End of explanation
# %load -r 22-41 ./notebook_snippets_run_mpl_test.py
This module has been written to illustrate the ``%run`` magic command in
``notebook_snippets.ipynb``.
import numpy as np
import matplotlib.pyplot as plt
def main():
    x = np.arange(-10, 10, 0.1)
    y = np.cos(x)
    plt.plot(x, y)
    plt.grid(True)
    plt.show()
if __name__ == '__main__':
    main()
Explanation: Load specific lines
End of explanation
%%time
plt.hist(np.random.normal(loc=0.0, scale=1.0, size=100000), bins=50)
Explanation: Time measurement
%time
End of explanation
%%timeit
plt.hist(np.random.normal(loc=0.0, scale=1.0, size=100000), bins=50)
Explanation: %timeit
End of explanation
#help(ipywidgets)
#dir(ipywidgets)
from ipywidgets import IntSlider
from IPython.display import display
slider = IntSlider(min=1, max=10)
display(slider)
Explanation: ipywidget
On jupyter lab, you should install widgets extension first (see https://ipywidgets.readthedocs.io/en/latest/user_install.html#installing-the-jupyterlab-extension):
jupyter labextension install @jupyter-widgets/jupyterlab-manager
End of explanation
#help(ipywidgets.interact)
Explanation: ipywidgets.interact
Documentation
See http://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html
End of explanation
@interact(text="IPython Widgets")
def greeting(text):
    print("Hello {}".format(text))
Explanation: Using interact as a decorator with named parameters
To me, this is the best option for single usage functions...
Text
End of explanation
@interact(num=5)
def square(num):
    print("{} squared is {}".format(num, num*num))
@interact(num=(0, 100))
def square(num):
    print("{} squared is {}".format(num, num*num))
@interact(num=(0, 100, 10))
def square(num):
    print("{} squared is {}".format(num, num*num))
Explanation: Integer (IntSlider)
End of explanation
@interact(num=5.)
def square(num):
    print("{} squared is {}".format(num, num*num))
@interact(num=(0., 10.))
def square(num):
    print("{} squared is {}".format(num, num*num))
@interact(num=(0., 10., 0.5))
def square(num):
    print("{} squared is {}".format(num, num*num))
Explanation: Float (FloatSlider)
End of explanation
@interact(upper=False)
def greeting(upper):
    text = "hello"
    if upper:
        print(text.upper())
    else:
        print(text.lower())
Explanation: Boolean (Checkbox)
End of explanation
@interact(name=["John", "Bob", "Alice"])
def greeting(name):
    print("Hello {}".format(name))
Explanation: List (Dropdown)
End of explanation
@interact(word={"One": "Un", "Two": "Deux", "Three": "Trois"})
def translate(word):
    print(word)
x = np.arange(-2 * np.pi, 2 * np.pi, 0.1)
@interact(function={"Sin": np.sin, "Cos": np.cos})
def plot(function):
    y = function(x)
    plt.plot(x, y)
Explanation: Dictionnary (Dropdown)
End of explanation
@interact
def greeting(text="World"):
    print("Hello {}".format(text))
Explanation: Using interact as a decorator
Text
End of explanation
@interact
def square(num=2):
    print("{} squared is {}".format(num, num*num))
@interact
def square(num=(0, 100)):
    print("{} squared is {}".format(num, num*num))
@interact
def square(num=(0, 100, 10)):
    print("{} squared is {}".format(num, num*num))
Explanation: Integer (IntSlider)
End of explanation
@interact
def square(num=5.):
    print("{} squared is {}".format(num, num*num))
@interact
def square(num=(0., 10.)):
    print("{} squared is {}".format(num, num*num))
@interact
def square(num=(0., 10., 0.5)):
    print("{} squared is {}".format(num, num*num))
Explanation: Float (FloatSlider)
End of explanation
@interact
def greeting(upper=False):
    text = "hello"
    if upper:
        print(text.upper())
    else:
        print(text.lower())
Explanation: Boolean (Checkbox)
End of explanation
@interact
def greeting(name=["John", "Bob", "Alice"]):
    print("Hello {}".format(name))
Explanation: List (Dropdown)
End of explanation
@interact
def translate(word={"One": "Un", "Two": "Deux", "Three": "Trois"}):
    print(word)
x = np.arange(-2 * np.pi, 2 * np.pi, 0.1)
@interact
def plot(function={"Sin": np.sin, "Cos": np.cos}):
    y = function(x)
    plt.plot(x, y)
Explanation: Dictionnary (Dropdown)
End of explanation
def greeting(text):
    print("Hello {}".format(text))
    
interact(greeting, text="IPython Widgets")
Explanation: Using interact as a function
To me, this is the best option for multiple usage functions...
Text
End of explanation
def square(num):
    print("{} squared is {}".format(num, num*num))
interact(square, num=5)
def square(num):
    print("{} squared is {}".format(num, num*num))
interact(square, num=(0, 100))
def square(num):
    print("{} squared is {}".format(num, num*num))
interact(square, num=(0, 100, 10))
Explanation: Integer (IntSlider)
End of explanation
def square(num):
    print("{} squared is {}".format(num, num*num))
interact(square, num=5.)
def square(num):
    print("{} squared is {}".format(num, num*num))
interact(square, num=(0., 10.))
def square(num):
    print("{} squared is {}".format(num, num*num))
interact(square, num=(0., 10., 0.5))
Explanation: Float (FloatSlider)
End of explanation
def greeting(upper):
    text = "hello"
    if upper:
        print(text.upper())
    else:
        print(text.lower())
interact(greeting, upper=False)
Explanation: Boolean (Checkbox)
End of explanation
def greeting(name):
    print("Hello {}".format(name))
interact(greeting, name=["John", "Bob", "Alice"])
Explanation: List (Dropdown)
End of explanation
def translate(word):
    print(word)
interact(translate, word={"One": "Un", "Two": "Deux", "Three": "Trois"})
x = np.arange(-2 * np.pi, 2 * np.pi, 0.1)
def plot(function):
    y = function(x)
    plt.plot(x, y)
interact(plot, function={"Sin": np.sin, "Cos": np.cos})
Explanation: Dictionnary (Dropdown)
End of explanation
@interact(upper=False, name=["john", "bob", "alice"])
def greeting(upper, name):
    text = "hello {}".format(name)
    if upper:
        print(text.upper())
    else:
        print(text.lower())
Explanation: Example of using multiple widgets on one function
End of explanation
from IPython.display import Image
Image("fourier.gif")
Explanation: Display images (PNG, JPEG, GIF, ...)
Within a code cell (using IPython.display)
End of explanation
from IPython.display import Audio
Explanation: Within a Markdown cell
Sound player widget
See: https://ipython.org/ipython-doc/dev/api/generated/IPython.display.html#IPython.display.Audio
End of explanation
framerate = 44100
t = np.linspace(0, 5, framerate*5)
data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
Audio(data, rate=framerate)
Explanation: Generate a sound
End of explanation
data_left = np.sin(2 * np.pi * 220 * t)
data_right = np.sin(2 * np.pi * 224 * t)
Audio([data_left, data_right], rate=framerate)
Explanation: Generate a multi-channel (stereo or more) sound
End of explanation
Audio("http://www.nch.com.au/acm/8k16bitpcm.wav")
Audio(url="http://www.w3schools.com/html/horse.ogg")
Explanation: From URL
End of explanation
#Audio('/path/to/sound.wav')
#Audio(filename='/path/to/sound.ogg')
Explanation: From file
End of explanation
#Audio(b'RAW_WAV_DATA..)
#Audio(data=b'RAW_WAV_DATA..)
Explanation: From bytes
End of explanation
from IPython.display import YouTubeVideo
vid = YouTubeVideo("0HlRtU8clt4")
display(vid)
Explanation: Youtube widget
Class for embedding a YouTube Video in an IPython session, based on its video id.
e.g. to embed the video from https://www.youtube.com/watch?v=0HlRtU8clt4 , you would do:
See https://ipython.org/ipython-doc/dev/api/generated/IPython.display.html#IPython.display.YouTubeVideo
End of explanation
<END_TASK>