How to add/edit code snippets in jupyer notebook? - jupyter-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?

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.

In windows(os) jupyter notebook extension are hidden in programData folder (C:\ProgramData\jupyter\nbextensions\snippets)
To make changes in snippet just edit the snippets.JSON file accordingly:

I think you are searching in the wrong directory.
In windows, run command jupyter --paths in anaconda prompt
this will return the locations of config: data: & runtime:
search for the file snippets.json in the data: locations
in my case it is C:\ProgramData\jupyter\nbextensions\snippets
change and save the content in snippets.json and then restart your jupyter notebook
it will work!

Related

VSCode: ctrl+alt+i json keybind returns í (acute i) - how to override to create R chunk in Rmd file?

I am using VSCode to work on an R Markdown file. I want to keybind CTRL+Alt+I to create an R chunk, so I wrote a JSON file, but the keys return í (acute i).
Here is the JSON file:
[
// Insert a chunk
{
"key": "cmd+alt+i",
"command": "type",
"when": "editorLangId == r || editorLangId == rmd && editorTextFocus",
"args": {
"text": "```{r}\n\n```"
}
},
]
However, my laptop (Dell XPS 13 2-in-1) seems to override this keybind and inserts í (acute i) whenever I use Ctrl+Alt+I. This is annoying, and I don't want to use different keybinds for RStudio and VScode. Notably, I do not have this issue in RStudio - Ctrl+Alt+I creates the code chunk just fine.
How come RStudio works fine with this keybind, but VSCode doesn't?

How to use rules_webtesting?

I want to use https://github.com/bazelbuild/rules_webtesting. I am using Bazel 5.2.0.
The whole project can be found here.
My WORKSPACE.bazel file looks like this:
load("#bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "io_bazel_rules_webtesting",
sha256 = "3ef3bb22852546693c94e9b0b02c2570e74abab6f800fd58e0cbe79492e49c1b",
urls = [
"https://github.com/bazelbuild/rules_webtesting/archive/581b1557e382f93419da6a03b91a45c2ac9a9ec8/rules_webtesting.tar.gz",
],
)
load("#io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories")
web_test_repositories()
My BUILD.bazel file looks like this:
load("#io_bazel_rules_webtesting//web:py.bzl", "py_web_test_suite")
py_web_test_suite(
name = "browser_test",
srcs = ["browser_test.py"],
browsers = [
"#io_bazel_rules_webtesting//browsers:chromium-local",
],
local = True,
deps = ["#io_bazel_rules_webtesting//testing/web"],
)
browser_test.py looks like this:
import unittest
from testing.web import webtest
class BrowserTest(unittest.TestCase):
def setUp(self):
self.driver = webtest.new_webdriver_session()
def tearDown(self):
try:
self.driver.quit()
finally:
self.driver = None
# Your tests here
if __name__ == "__main__":
unittest.main()
When I try to do a bazel build //... I get (under Ubuntu 20.04 and macOS):
INFO: Invocation ID: 74c03efd-9caa-4174-9fda-42f7ff37e38b
ERROR: error loading package '': Every .bzl file must have a corresponding package, but '#io_bazel_rules_webtesting//web:repositories.bzl' does not have one. Please create a BUILD file in the same or any parent directory. Note that this BUILD file does not need to do anything except exist.
INFO: Elapsed time: 0.038s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (0 packages loaded)
The error message does not make sense to me, since there is a BUILD file in
https://github.com/bazelbuild/rules_webtesting/blob/581b1557e382f93419da6a03b91a45c2ac9a9ec8/BUILD.bazel
and https://github.com/bazelbuild/rules_webtesting/blob/581b1557e382f93419da6a03b91a45c2ac9a9ec8/web/BUILD.bazel.
I also tried a different version of Bazel - but with the same result.
Any ideas on how to get this working?
You need to add a strip_prefix = "rules_webtesting-581b1557e382f93419da6a03b91a45c2ac9a9ec8" in your http_archive call.
For debugging, you can look in the folder where Bazel extracts it: bazel-out/../../../external/io_bazel_rules_webtesting. #io_bazel_rules_webtesting//web translates to bazel-out/../../../external/io_bazel_rules_webtesting/web, so if that folder doesn't exist things won't work.

cx_freeze include css file and image in dash app

I have some difficulties to apply a css file to my dash app when using cx_freeze. If I run python app.py the layout is properly applied, however not if I am executing the .exe generated by cx_freeze. Then the default html layout is displayed. The css and the image appear in the same directory where the .exe is located.
This is how my setup.py looks like.
from setuptools import find_packages
from cx_Freeze import setup, Executable
options = {
'build_exe': {
'includes': [
'cx_Logging', 'idna', 'idna.idnadata'
],
'packages': [
'asyncio', 'flask', 'jinja2', 'dash', 'plotly', 'waitress'
],
'excludes': ['tkinter'],
'include_files': [
'assets/logo.jpg', 'assets/style.css'
],
}
}
executables = [
Executable('server.py',
base='console',
targetName='dash_app.exe')
]
setup(
name='BI_Report',
packages=find_packages(),
version='0.0.1',
description='rig',
executables=executables,
options=options
)
To load the external files I use a helper function as suggested here:
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
app = dash.Dash(__name__,
assets_folder=find_data_file('assets/'))
I am using:
Python 3.7.6
dash 1.9.1
cx-freeze 6.1
Any help much appreciated!

Keyboard shortcut to expand code snippets in JupyterLab

Does anyone know how to make a shortcut that would paste a certain code to the selected cell or expand a snippet into a chunk of code?
For example I would like to fill a cell with a list of useful imports when pressing something like Ctrl+Shift+M. This would expand the cell content to:
import numpy as np
import pandas as pd
(...) .
Optionally this could work also like text completion tools available in some IDEs. For example when I write something like:
;imp + TAB .
it would expand into the same list as above.
Any ideas how this could be defined in JupyterLab?
I saw this answer, but it does not work for me (returning javascript error)
In JupyterLab 2.1+ you can add a shortcut to insert a snippet using the following settings:
{
"shortcuts": [
{
"command": "apputils:run-first-enabled",
"selector": "body",
"keys": ["Accel Shift M"],
"args": {
"commands": [
"console:replace-selection",
"fileeditor:replace-selection",
"notebook:replace-selection",
],
"args": {"text": "import numpy as np\nimport pandas as pd\n"}
}
}
]
}
For more detailed instruction see my new answer to the question you linked.
Another option is to use one of the code snippet extensions for JupyterLab:
jupyterlab-code-snippets from CalPoly
jupyterlab-snippets from QuantStack
elyra-code-snippet-extension from Elyra IBM team (with multiple contributions from the CalPoly team)
For emmet-style expansion of snippets in IPython, you can use:
from IPython import get_ipython
def import_completer(ipython, event):
return [
'import numpy as np\nimport pandas as pd\n',
'import tensorflow as tf\nimport autokeras as ak\n'
]
ipython = get_ipython()
ipython.set_hook('complete_command', import_completer, re_key='.*imp')

SublimeREPL Unable to Find R

Okay, this is driving my crazy. I had set this up before, deleted Sublime Text, and now I can't remember what the right configuration was.
Very simple: I'm running R through SublimeREPL and need to point the REPL to where R is installed.
I followed the directions at http://sublimerepl.readthedocs.org/en/latest/, which say to go into the user-defined REPL settings and add this:
{
...
"default_extend_env": {"PATH": "{PATH}:/home/myusername/bin"}
...
}
where the path points to the right directory. I tried replacing it with
{
...
"default_extend_env": {"PATH": "C:/Program Files/R/R-3.0.2/bin"}
...
}
and it's still unable to find R, plus now it's giving me the error:
Error trying to parse settings: Expected value in Packages\User\SublimeREPL.sublime- settings:2:2
I know this is an easy fix. Can anybody point out what I'm doing wrong here?
*I'm using Sublime Text 3. I previously had this working, but on Sublime Text 2.
I've been to http://tomschenkjr.net/using-sublime-text-2-for-r/ and the piece where he mentions "pointing SublimeREPL at R" ... he doesn't include the actual code, as far as I can see
I've also seen this thread Error 2 The system cannot find the file specified in Sublime Text 2, Windows 8, but I had it working before and didn't have to do anything along those lines
Go to Preferences -> Browse Packages... and create a directory tree User/SublimeREPL/config/R. In that directory, create a new file named Main.sublime-menu with the following contents:
[
{
"id": "tools",
"children":
[{
"caption": "SublimeREPL",
"mnemonic": "r",
"id": "SublimeREPL",
"children":
[
{"command": "repl_open",
"caption": "Rterm",
"id": "repl_r",
"mnemonic": "r",
"args": {
"type": "subprocess",
"external_id": "r",
"additional_scopes": ["tex.latex.knitr"],
"encoding": {"windows": "$win_cmd_encoding"},
"soft_quit": "\nquit(save=\"no\")\n",
"cmd": {"windows": ["C:/Program Files/R/R-3.0.2/bin/x64/Rterm.exe", "--ess", "--encoding=$win_cmd_encoding"]},
"cwd": "$file_path",
"extend_env": {"windows": {"PATH": "{PATH}:/C/Program Files/R/R-3.0.2/bin"}},
"cmd_postfix": "\n",
"suppress_echo": {"windows": false},
"syntax": "Packages/R/R.tmLanguage"
}
}
]
}]
}
]
Save the file, and you should now have a Tools -> SublimeREPL -> Rterm menu option. Double-check that the path is the correct one to the Rterm.exe file. On my computer (32-bit XP) it's in the i386 subfolder of bin, so yours may be in bin/x64 or something like that.
I hope this helps, let me know if you still have issues.
I resolved this by adding the location of Rterm.exe to PATH

Resources