Is there a way of converting jupyter notebook to slides without codes? - jupyter-notebook

My goal is to create a presentation with Jupyter notebook without code input.
I have tried the following code
!jupyter nbconvert Explanatory_Analysis.ipynb --to slides --post serve --no-input --no-prompt
This code is prompting the NotImplementedError

Here's a somewhat hacky solution.
Paste the following code into a new code cell, then execute the cell.
Be sure to change the NOTEBOOK variable to the filename of the current notebook and SAVE the notebook BEFORE running.
The hackiest thing about it is that the code overwrites the current notebook, so you'll need to refresh the juptyer page in your browser after running the script.
import nbformat as nbf
import os
NOTEBOOK = "Explanatory_Analysis.ipynb"
PATH = f'{os.path.abspath("")}/{NOTEBOOK}'
ntbk = nbf.read(PATH, nbf.NO_CONVERT)
for i, cell in enumerate(ntbk.cells):
if cell.cell_type == "code":
metadata = cell["metadata"]
slideshow = metadata.get("slideshow", {})
print(f"[cell#index={i}] {cell.cell_type=}")
print(f"BEFORE {metadata=}, {slideshow=}")
slideshow["slide_type"] = "skip"
metadata["slideshow"] = slideshow
print(f"AFTER {metadata=}, {slideshow=}")
nbf.write(ntbk, PATH)

Related

Pyinstaller opens Stockfish in console

I have made a GUI (using PySimpleGUI) where you can play against Stockfish (I used python-chess module). I make an .exe-file using Pyinstaller --noconsole, but when i run it, it opens Stockfish in a console. When I run it form source, in PyCharm, Stockfish runs silently in the background.
The relevant lines of code are (I guess):
engine = chess.engine.SimpleEngine.popen_uci(engine_filename, shell = False)
and, a bit later,
best_move = engine.play(board, chess.engine.Limit(depth=20)).move
Any advice on how I can make Stockfish run silently in the background also form the .exe-file?
Define your engine like below.
import subprocess
engine = chess.engine.SimpleEngine.popen_uci(
engine_filename,
shell = False,
creationflags=subprocess.CREATE_NO_WINDOW)
See python subprocess ref.

How to source R code from another Jupyter notebook file?

I am new to using the Jupyter notebook with R kernel.
I have R code written in two files Settings.ipynb and Main_data.ipynb.
My Settings.ipynb file has a lot of details. I am showing sample details below
Schema = "dist"
resultsSchema = "results"
sourceName = "hos"
dbms = "postgresql" #Should be "sql server", "oracle", "postgresql" or "redshift"
user <- "hos"
pw <- "hos"
server <- "localhost/hos"
port <- "9763"
I would like to source Settings file in Main_data code file.
When I was using R studio, it was easy as I just use the below
source('Settings.R')
But now in Main_data Jupyter Notebook with R kernel, when I write the below piece of code
source('Settings.R') # settings file is in same directory as main_data file
I get the below error
Error in source("Settings.R"): Settings.R:2:11: unexpected '['
1: {
2: "cells": [
^
Traceback:
1. source("Settings.R")
When I try the below, I get another error as shown below
source('Settings.ipynb')
Error in source("Settings.ipynb"): Settings.ipynb:2:11: unexpected '['
1: {
2: "cells": [
^
Traceback:
1. source("Settings.ipynb")
How can I source an R code and what is the right way to save it (.ipynb or .R format in a jupyter notebook (which uses R kernel)). Can you help me with this please?
updated screenshot
We could create a .INI file in the same working directory (or different) and use ConfigParser to parse all the elements. The .INI file would be
Settings.INI
[settings-info]
schema = dist
resultsSchema = results
sourceName = hos
dbms = postgresql
user = hos
pw = hos
server = localhost/hos
Then, we initialize a parser object, read the contents from the file. We could have multiple subheadings (here it is only 'settings-info') and extract the components using either [[ or $
library(ConfigParser)
props <- ConfigParser$new()
props <- props$read("Settings.INI")$data
props[["settings-info"]]$schema
From the Jupyter notebook
the 'Settings.INI' file
Trying to save a Jupyter notebook file in .R format will not work as the format is a bit messed up (due to the presence of things like { "cells" : [....". You can verify this by opening your .R file in Jupyter Notebook.
However, you can use a vim editor/R studio to create a .R file. This will allow you to have the contents as is without any format issues such as { "cells" : [....".
Later from another jupyter notebook, you can import/source the .R file created using vim editor/R studio. This resolved the issue for me.
In summary, don't use jupyter notebook to create .R file and source them using another jupyter notebook file.

IPython: ipywidgets bug - Code working on Goolge Colab, but not on Jupyter Notebook (tested on 2 different PCs)?

This code is a "Filter as you type" textbox example. It works fine on Google Colab, but not on Jupyter Notebook. I tried it on 2 different computers (and on 2 different browsers) that have Jupyter Notebook installed and the 'out' widget only displays the textbox but nothing else. Any idea how to fix this?
I have tried pip uninstall ipywidgets then install again without success.
Thanks.
import pandas as pd, IPython.display, ipywidgets as widgets
out = widgets.Output()
df = pd.DataFrame ({'PLAYER':['MOHAMED SALAH', 'MESSI', 'MO SALAH', 'RONALDO', 'PELE', 'PEPE', 'MANE', 'RAMREZ']})
textbox = widgets.Text(value='', description='Player:')
display(textbox)
def display_result(value):
value = str(value['new']).upper()
if "{" not in value:
result = df[(df['PLAYER'].str.contains(value))]
if result.shape[0]>0:
with out:
out.clear_output()
display(result)
display(out)
textbox.observe(display_result)
This is the output from Google Colab:
This is the output from Jupyter Notebook:
I have discovered that this is caused by the "Limit Output" extension in NbExtensions. When I disabled it, the output widget worked.

How to execute cell 1 from another notebook in current notebook

I have a bunch of notebooks in a directory dir1 and would like to write a master notebook that executes the first cell of each notebook in dir1. All notebooks in dir1 have markdown describing themselves in cell 1. So by executing the first cell of all of them, the master notebook will document all notebooks in dir1. This sounds easily doable but I don't have any idea how to proceed.
A more general question is, is there software that will extract the markdown in cell 1 of all notebooks in dir1 and create a nice master notebook from them? nbsphinx produces an html doc, but I would like something much more lightweight and quicker.
Here is the code that I used. I create a notebook called SUMMARY.ipynb inside dir1 and I put this code into a cell of SUMMARY.ipynb. Running this cell produces a nice summary of all the notebooks in dir1 with a link to them
import os
import json
from IPython.display import display, Markdown
# the name of this file
this_fname = 'SUMMARY.ipynb'
fname_to_md = {}
for fname in os.listdir('./'):
if fname[-6:] == '.ipynb' and fname != this_fname:
# print('------------', fname)
with open(fname, 'r', encoding="utf-8") as f:
fdata = json.load(f)
fname_to_md[fname] = ''.join(fdata['cells'][0]['source'])
# print(fname_to_md)
pre_sep = '\n\n<span style="color:red">%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%</span>\n\n'
full_md = ''
for fname, md in fname_to_md.items():
sep = pre_sep
sep += '[' + fname + ']\n\n'
full_md += sep + md
display(Markdown(full_md))

Converting PDF to a collection of images on the server using GhostScript

These are the steps I am trying to achieve:
Upload a PDF document on the server.
Convert the PDF document to a set of images using GhostScript (every page is converted to an image).
Send the collection of images back to the client.
So far, I am interested in #2.
First, I downloaded both gswin32c.exe and gsdll32.dll and managed to manually convert a PDF to a collection of images(I opened cmd and run the command bellow):
gswin32c.exe -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dMaxStripSize=8192 -sOutputFile=image_%d.jpg somepdf.pdf
Then I thought, I'll put gswin32c.exe and gsdll32.dll into ClientBin of my web project, and run the .exe via a Process.
System.Diagnostics.Process process1 = new System.Diagnostics.Process();
process1.StartInfo.WorkingDirectory = Request.MapPath("~/");
process1.StartInfo.FileName = Request.MapPath("ClientBin/gswin32c.exe");
process1.StartInfo.Arguments = "-dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dMaxStripSize=8192 -sOutputFile=image_%d.jpg somepdf.pdf"
process1.Start();
Unfortunately, nothing was output in ClientBin. Anyone got an idea why? Any recommendation will be highly appreciated.
I've tried your code and it seem to be working fine. I would recommend checking following things:
verify if your somepdf.pdf is in the working folder of the gs process or specify the full path to the file in the command line. It would also be useful to see ghostscript's output by doing something like this:
....
process1.StartInfo.RedirectStandardOutput = true;
process1.StartInfo.UseShellExecute = false;
process1.Start();
// read output
string output = process1.StandardOutput.ReadToEnd();
...
process1.WaitForExit();
...
if gs can't find your file you would get an "Error: /undefinedfilename in (somepdf.pdf)" in the output stream.
another suggestion is that you proceed with your script without waiting for the gs process to finish and generate resulting image_N.jpg files. I guess adding process1.WaitForExit should solve the issue.

Resources