Can I create an iPython notebook using JavaScript as the language in the cells? - ipython

I love IPython to explain algorithms in python. But I want to do the same using javascript. Is it possible to write a notebook where I use javascript as the cell language?

You can use the %%javascript magic function for running javascript in IPython notebook. For example Paste the following code in a IPython cell and run it. You should see the output in your browser's javascript console.
%%javascript
console.log("Hello World!")
For global variables, you can add an attribute to the windows object for
example, in a cell run the following code:
%%javascript
window.myvar = 12;
In another cell, run the following code and check browser's javascript console. The variable's value should be printed.
%%javascript
console.log(myvar)
Use the element variable for printing in the cell output area as shown below:
%%javascript
element.append(myvar)

Related

How do I edit a jupyter notebook cell's tags in visual studio code?

I am editing a .ipynb file in Visual Studio Code, with the file open in VS code's Jupyter Notebook editor.
When I edit this notebook in the Jupyter Notebook App (i.e. if I were not using VS code, instead using the interface described here), I could add tags to cells by clicking View > Cell Toolbar > Tags, and then entering tags into the UI that comes up.
Is there an equivalent way to do this in VS Code?
I am aware I can reopen the file in a text editor view and edit the JSON directly. But I am looking for something a bit more user friendly than this.
Try installing this jupyter on vs code.
On my old windows 7 I used to use this. It has the same interface as when you open Jupiter in your browser but you don't need to load a bunch of stuff to open jupyter. You can open it in one single click like changing text file while writing code inside vc code.
Also you need to install one library to use it but unfortunately I can't remember the library as I don't use python or Jupiter anymore.
In the documentation is a python code cell which enables to change all the cell tags.
import nbformat as nbf
from glob import glob
# Collect a list of all notebooks in the content folder
notebooks = glob("**/*.ipynb", recursive=True)
notebooks_windows = []
for i in notebooks:
j = i.replace("\\", "/")
notebooks_windows.append(j)
notebooks_windows
# Text to look for in adding tags
text_search_dict = {
"# HIDDEN": "remove-cell", # Remove the whole cell
"# NO CODE": "remove-input", # Remove only the input
"# HIDE CODE": "hide-input" # Hide the input w/ a button to show
}
# Search through each notebook and look for the text, add a tag if necessary
for ipath in notebooks_windows:
ntbk = nbf.read(ipath, nbf.NO_CONVERT)
for cell in ntbk.cells:
cell_tags = cell.get('metadata', {}).get('tags', [])
for key, val in text_search_dict.items():
if key in cell['source']:
if val not in cell_tags:
cell_tags.append(val)
if len(cell_tags) > 0:
cell['metadata']['tags'] = cell_tags
Microsoft have finally released an extra extension to support this.
ms-toolsai.vscode-jupyter-cell-tags
See this long running github.com/microsoft/vscode-jupyter issue #1182 and comment recently closing the issue.
Be ware however, that while you can set tags, e.g. raises-exception, which is meant to make the runtime expect and ignore the exception and keep on running more cells, but the vscode-jupyter extension that runs the cells does not always honor tag features the same way that the standard Jupyter notebook runtime does, and so, disappointingly, it's still difficult to demo common mistakes or what not to do (exceptions).
Just copy everything in .py file with the unremovable tags, paste that into a plaintext file. The tags are now just editable text. Remove them, Save As or copy/paste back to the .py file.

Is it possible to use %edit in an IPython Notebook to edit in-browser?

I have been using the magic %edit in Ipython to edit strings on the fly and was wondering whether this is also possible in an IPython Notebook without having to leave the browser (Possibly in a new cell)?
It turns out that %edit does not load variable content in a new cell in jupyter notebooks for now (https://github.com/jupyter/help/issues/147).
However, you can load variable s contents in a new cell by using %load s. you can then edit the content and store it in a new variable from within the same cell.

Jupyter Notebook: command for hide the output of a cell?

In my notebook, I have a cell returning temp calculation results. It's a bit long, so after it is run, I want to hide it and when needed, to show it.
To do it manually, I can double click the left side of the output, to hide it
After double click
But is there any way I can do this by code? For example,
the last line of the cell, use a command like %%hide output, and the output would be hidden after finished running.
Additionally, can I get this feature in output HTML?
Add ; by the end of the cell to hide the output of that cell.
In the newer versions(5.0.0 at the time I'm writing this), pressing o in the command mode hides the output of the cell in focus. The same happens if you triple click in front of the output.
o is
the first letter in the word "output" or
lower case of 15th letter in the alphabet
You can add %%capture to the beginning of the cell.
Jupyter provides a magic cell command called %%capture that allows you to capture all of to outputs from that cell.
You can use it like this:
%%capture test
print('test')
test.stdout => 'test\n'
https://ipython.readthedocs.io/en/stable/interactive/magics.html
In newer versions of Jupiter Notebook, select the desired cell, make sure you're in command mode and then on the menubar press Cell > Current Outputs. You have then three options:
Toggle (press O in the command mode to apply the same effect)
Toggle Scrolling (the default output)
Clear (to clear the output all together)
Image to Menubar Options
Additionally, you can apply the same effect to all the cells in your document if you chose All Output instead of Current Output.
Not exactly what you are after, but the effect might be good enough for your purposes:
Look into the %%capture magic (https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb). It lets you assign that cell output to a variable. By calling that variable later you could see the output.
Based on this, I just came up with this for myself a few minutes ago:
%%javascript
$('#maintoolbar-container').children('#toggleButton').remove()
var toggle_button = ("<button id='toggleButton' type='button'>Show Code</button>");
$('#maintoolbar-container').append(toggle_button);
var code_shown = false;
function code_toggle()
{
if (code_shown)
{
console.log("code shown")
$('div.input').hide('500');
$('#toggleButton').text('Show Code');
}
else
{
console.log("code not shown")
$('div.input').show('500');
$('#toggleButton').text('Hide Code');
}
code_shown = !code_shown;
}
$(document).ready(function()
{
code_shown=false;
$('div.input').hide();
});
$('#toggleButton').on('click', code_toggle);
It does have a glitch: each time you run that cell (which I put at the top), it adds a button. So, that is something that needs to be fixed. Would need to check in the maintoolbar-container to see if the button already exists, and then not add it.
EDIT
I added the necessary piece of code:
$('#maintoolbar-container').children('#toggleButton').remove()
You can use the notebook utils from https://github.com/google/etils:
!pip install etils[ecolab]
from etils import ecolab
with etils.collapse():
print('This content will be hidden by default')
It will capture the stdout/stderr output and display it a some collapsible section.
Internally, this is more or less equivalent to:
import contextlib
import html
import io
import IPython.display
#contextlib.contextmanager
def collapse(name: str = ''):
f = io.StringIO()
with contextlib.redirect_stderr(f):
with contextlib.redirect_stdout(f):
yield
name = html.escape(name)
content = f.getvalue()
content = html.escape(content)
content = f'<pre><code>{content}</code></pre>'
content = IPython.display.HTML(
f'<details><summary>{name}</summary>{content}</details>')
IPython.display.display(content)
The section is collapsed by default, but I uncollapsed it for the screenshot.
To prepend a cell from getting rendered in the output, in the notebook, by voilo or voila gridstack, just put in the first line of each cell to hide the output:
%%capture --no-display
reference in ipypthon documentation
For Windows,
in Jupyter Notebook, click the cell whose output you want to hide.
Click Esc + o for toggling the output
So I totally understand. When you have like 100 different plot and when you do the "Restart & Run All" those ugly plots all show up again
what you can do is ctrl+A and press o it will all of a sudden hide all your cells!!! For you to collapse automatically, you may need to use JupyterLab (another level after JupyterNotebook) but still, by doing ctrl+A then o you will be able to collapse all the results!!!
ctrl+A --> select ALL (make sure to click outside of coding box before you do it!)
o --> toggle collapse
If you don't mind a little hacking, then you may write a simple script for inverting the "collapsed" attribute of each cell from false to true
in the notebook .ipynb file (which is a simple JSON file).
This is however may fail in the future if a the .ipynb format changes.

How does the code in Jupyter Notebook get executed in Ipython

I am new to jupyter and I modify the html content of the generated notebook when you click create new Notebook in Jupyter. I have added an html block that contains a jupyter code to display graph or markdown code. Now, does anybody know how do I use the jupyter javascripts to interpret my code and display it inside the jupyter notebook cell index 0?. If my question is not clear please let me know and would love to edit it.
currently, I see this code in jupyter main.min.js. But how do they get the code and send it to python.
'run-cell':{
help : 'run selected cells',
help_index : 'bb',
handler : function (env) {
env.notebook.execute_selected_cells();
}
},

How to show (as output cell) the contents of a .py file with syntax highlighting?

I'm aware of the %load function (formerly %loadpy) which loads the contents of a file (or URL, ...) into a new input cell (which can be executed afterwards).
I'm also aware of %less, %more and %pycat, which show the contents of a file in a pager (which means in the notebook it's shown in the split-window at the bottom of the screen).
Is there a (magic) command to load a file and show its content (with syntax highlighting) in an output cell?
I.e. something like the following but with syntax highlighting of the result:
with open('my_file.py', 'r') as f:
print(f.read())
I want the file content to be stored with the .ipynb file but I don't want it to be executed when I do Cell -> Run All.
Is there a command similar to %psource which shows the source code in an output cell instead of a pager?
Example code based on answer by #Matt:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import IPython
with open('my_file.py') as f:
code = f.read()
formatter = HtmlFormatter()
IPython.display.HTML('<style type="text/css">{}</style>{}'.format(
formatter.get_style_defs('.highlight'),
highlight(code, PythonLexer(), formatter)))
No there is not way to do that with current magics, but it is pretty easy using pygments and returning IPython.display.HTML(...).
10 years later, and there's now a much simpler solution:
https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.Code
from IPython.display import Code
Code(filename='my_file.py', language='python')