Jupyter and IRuby: how to reset all variables befor executing a cell? - jupyter

For study I am using IRuby in Jupyter.
How to reset all all variables before executing a cell?
I need the equivalent of %reset for IPython.
I want to be sure that values from previous cells don't interfere with the ones I am working on.

Short answer
Install Pry.
gem install pry
then use
cd Module.new
a = 1
b = 2
c = 3
d = a + b + c + d
puts d
exit
Answer
IRuby does not have magic commands.
So you can't use %reset.
Unfortunately, IRuby defines local variables at the top level.
Ruby is a language that does not have the right way to delete local variables once you defined it.
The good news is that you can use Pry commands available in IRuby.
Open Jupyter, and write the first line of the cell.
cd Module.new
cd is a Pry command that is used to move into a new object (or scope) inside a Pry session.
So cd Module.new means you create a new disposable nameless module object, as a custom sandbox, and then move into it. You define variables as much as you like. After calculation, you can exit the pry session with exit.

Related

Fish shell git_prompt inside TIDE

Is it possible to force Fish shell extention TIDE to
use fish_git_prompt instead of its own _tide_item_git.fish?
My goal is to make TIDE git prompt identical to this tutorial.
Right now with default TIDE setting I have this git prompt:
However, I want to make it look like this, but still use TIDE:
Source image
fish, version 3.2.1
Fedora 33
So what that tide function does is simply collect the git info and print it. Tide calls it, takes what it prints, and puts it in the correct place. This is also how the fish_git_prompt works - it prints the git stuff, your prompt is responsible for putting that in the correct place.
Simplified:
function fish_prompt
set gitstuff (_tide_item_git)
# do other tide stuff
printf '%s' $gitstuff $otherstuff
end
When fish calls a function, it goes through $fish_function_path for a file with the name of the function (plus a ".fish" suffix).
So what you would simply do is make your own function _tide_item_git, and put it first in $fish_function_path.
I'm not sure how you've installed tide, I'm assuming it's not directly in ~/.config/fish/functions - the normal directory for your functions. That's the simple case, so you can just call funced _tide_item_git, which will open it in your editor, and replace it with
function _tide_item_git
fish_git_prompt
end
then run funcsave _tide_item_git once you're happy.
In the more complicated case, make another directory for your functions - ~/.config/fish/myfunctions maybe - add it to $fish_function_path:
set -g fish_function_path ~/.config/fish/myfunctions $fish_function_path
(put that in config.fish)
make a file called _tide_item_git.fish there and put the above function in.

Complete command from history in ipython

For reasons outside of my control I'm stuck using python 2.6.6 and IPython 0.10.2. I also normally use the tcsh shell, and have gotten quite used to completing a command from the history using <A-p> (i.e. pressing the ALT key and p). However, this doesn't work in IPython. I know I can press <C-r> and then start typing a command, but what inevitably is happening is that I start a command, press <A-p>, get a colon indicating some weird state, then exit out of that state, delete my command, press <C-r> then search for my command. It's getting rather irritating. Is there any way to make <A-p> complete my already started command by relying on the history?
Ouch, this is an old version of IPython, Python (and pip). The bad news is I don't have much experience with such an old version of IPython, the good new is; it was way simpler at that time.
Most of the shortcut and feature are provided using readline, and the python bindings of stdlib. Meaning that most likely what you are trying to configure is readline itself and not only IPython; so you can find more information on that outside of IPython !
The secret is to grep in the source-code for parse_and_bind, then you'll find the following example configuration, leading me to change the ~/.ipython/ipy_user_conf.py to be like so at around line 99 (all indented an extra 4 space to be in the main() function):
import readline
readline.parse_and_bind('set completion-query-items 1000')
readline.parse_and_bind('set page-completions no')
rlopts = """\
tab: complete
"\C-l": possible-completions
set show-all-if-ambiguous on
"\C-o": tab-insert
"\M-i": " "
"\M-o": "\d\d\d\d"
"\M-I": "\d\d\d\d"
"\C-r": reverse-search-history
"\C-s": forward-search-history
"\C-p": history-search-backward
"\C-n": history-search-forward
"\e[A": history-search-backward
"\e[B": history-search-forward
"\C-k": kill-line
"\C-u": unix-line-discard"""
for cmd in rlopts.split('\n'):
readline.parse_and_bind(cmd)
The repetition of commands make me think that what \C,\M or [e mean might be system dependant. I would bet on \C being Control, and \M being Meta (Alt, Opt), but at least one of these line did the trick for me (and also now tab allows to complete). See also man readline for the list of commands you can bind to what, and enjoy! Hoping you can upgrade to Python 3 and IPython 6 at some point.
[Edit]
See Eric Carlsen second comment under this answer for how it was resolved.

How to open a file and select/highlight several lines on Sublime from the command line?

I know subl myfile.txt:5 would open “myfile.txt” on line 5. I however want to be able to, from the command line, open a file with say lines 5,9,15 highlighted or selected. I know adding –command should enable me to do that, but how? What would the command be?
There's no built-in command that I know of that can do this, but one can easily create one.
(Technically, it could be done using the bookmarks functionality from the Default package, and the built-in "Expand Selection to Line" functionality. However, experience shows that it would be better and more reliable to write a command in ST specifically for this purpose.)
In ST:
from the Tools menu -> Developer -> New Plugin...
select all and replace with the following
import sublime
import sublime_plugin
class SelectSpecificLinesCommand(sublime_plugin.TextCommand):
def run(self, edit, lines):
self.view.sel().clear()
for line in lines:
position = self.view.text_point(int(line) - 1, 0) # internally, line numbers start from 0
self.view.sel().add(self.view.line(position))
save it, in the folder ST recommends (Packages/User/) as something like select_lines.py (file extension is important).
subl myfile.txt
subl --command "select_specific_lines { \"lines\": [5, 9, 15] }" (this style of escaping the quotes for JSON strings works from the Windows Command Prompt and Linux's Bash)
Why did I specify the command on a separate line / call to subl? Because of these 2 caveats:
ST must already be running, otherwise commands specified on the command line may not get executed, because the plugins haven't loaded yet.
the command could get executed before the file is loaded.
Arguably, point 2 could still happen with multiple invocations of subl, but hopefully it is less likely. There is an open issue on the ST bug tracker for better command line command handling: https://github.com/SublimeTextIssues/Core/issues/1457.

Running "preamble" code in MATLAB

Is there any way to make MATLAB run a certain chunk of code every time you try to run a script? For instance, I would like MATLAB to run
sprintf('Here we go...')
as soon as I hit the Run button and then move on to execute my script, so if my script were
i = 1;
i = i * i;
display(i)
I would get
ans =
Here we go...
i =
1
P.S. I would appreciate it if the people with higher reputation please corrected the title of my question for it to better reflect the content.
as soon as I hit the Run button
I am assuming you are talking about the run button in the editor. In R2012a there was a feature called "Run Configuration". A run configuration was linked to a specific script and included code to be executed prior to the script being run. There does not appear to be a global setting to be used on all function. This feature appears to have been silently removed in R2012b.
In R2013b you can chose to run a different script. Presumably you could hack the editor to get the current file and use the custom run script to run your preamble and then the current editor file. This seems like a lot of work for not much return ...
You could create a file called myrun.m
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
jEditor = desktop.getGroupContainer('Editor').getTopLevelAncestor;
title = jEditor.getTitle;
currentFilename = char(title.replaceFirst('Editor - ',''));
fprintf('Here we go...');
run(currentFilename);
and this in the editor under run Run: type code to run type myrun. One you do this once it will remember your preferences and you can then run you code via myrun with F5. It will remember your preferences across restarts.
The way to do this would be to have a preamble.m and doThis.m. In preamble.m you'd have this:
sprintf('Here we go...')
and then in doThis.m, you'd have
preamble
i = 1;
i = i * i;
display(i)
The only trick to making this work is to have them both on the path, or in the same directory.
Not sure if I got what you want, but you can divide Your m file into Code Sections. For example:
%% Section 1
sprintf('Here we go...')
%% Section 2
i = 1;
i = i * i;
display(i)
The %% is a section break. Place your cursor in the relevant section, and on the Editor tab, in the Run section, click Run Section. (or press Ctrl+Enter)
see here for more info.
If you only want this for one (or a few scripts) either add the command in the script, or make a wrapper function/shortcut.
If you want this for many scripts without input, you can create a generic wrapper:
Suppose you want to run things like myFun(a,b,c) then create a wrapper that you can call like this:
myWrapper('myFun(a,b,c)')
Then you can first call your display command and then use eval on the input of myWrapper. Note that this becomes cumbersome if your function call is multiline or contains quotes.
If these solutions can't help, you probably need to ask yourself why you are trying to do this and whether there is a better solution for the underlying problem.

How do I reset the Jupyter/IPython input prompt numbering?

I just wrote my first extensive Python tutorial using IPython notebooks. All went well, except I did a lot of testing and moving blocks around. How do I reset the In [ ]: numbering? I have tried quitting and reloading, but that doesn't seem to work.
I think, the only way to to what you want is:
- 'Kernel > Restart' (restart the kernel) and then 'Cell > Run All' (run the script).
Every .ipynb file can be opened in an editor. Everything written there is in plain text (JSON). For each cell which has the "cell_type": "code" there'd be another key-value pair as "execution_count": <number>. As you might have guessed, that is the prompt numbering. Hence, if the notebook contains code which will take time to execute (as was, in my case) this method would be time efficient.
Now, either you can manually change each execution_count or write a simple script to get the numbering right. To check the results just refresh the notebook in the browser without stopping the kernel. And, everything will be as per your needs, even all the variables/loaded data will remain in the environment.
You can reset the kernel (shortcut: C-m .) and re-run the whole notebook.
Quitting and reloading doesn't work because the code is not re-evaluated.
'Kernel' -> 'Restart & Run All'
Just make sure you saved your Notebook. You can also bind/assign keyboard key for running this command.
'Help' -> 'Edit Keyboard Shortcuts'
If what you want is to remove the numbers themselves, so that each cell shows In [ ] (instead of something like In [247] which is leftover from some previous incarnation of the kernel), use "Cell" > "All Output" > "Clear" (in Jupyter Notebook 5.4.0) or "Edit" > "Clear All Outputs" (In Jupyter Lab 0.32.1).
This will remove all the numbers, even if you're in the middle of running a notebook. It will not reset the numbering back to 1; e.g. if the last cell you executed was 18, the next will be 19.
If you're using this because you want clarity about which cells you've executed during this run of the kernel and which cells you haven't executed yet, use "Cell" > "All Output" > "Clear" (or "Edit" > "Clear All Outputs") immediately after you start (or restart) the kernel. This can be useful when restarting a kernel, or when opening a saved or duplicated notebook.
This will also remove all outputs from the notebook.
Thanks to user2651084 in a previous comment for this.
I'm a bit too late, but I had the same problem, and since my notebook had cells with execution time up to 5 minutes, I had to wait a long time until Restart & Run All finished.
So I've made a Python script to make this task for me:
import json
file = '/your/notebook/path/Notebook.ipynb'
# Since every notebook is actually a JSON (JavaScript
# Object Notation), then its contents can be represented
# in a dictionary (or a list of dictionaries)
with open(file, encoding='utf-8') as f:
nb = json.load(f)
count = 1
for cell in nb['cells']:
# Markdown cells doesn't have execution count,
# so apply this only to cells that have one
if 'execution_count' in cell:
cell['execution_count'] = count
count += 1
# Not all code cells have output, such as functions
# that return None or simple declarations, so apply
# this only to cells that have some output
try:
for output in cell['outputs']:
if 'execution_count' in output:
output['execution_count'] = cell['execution_count']
except KeyError:
continue
with open(file, 'w+') as f:
json.dump(nb, f, indent=2, ensure_ascii=False)
But be careful with the execution order and the variables in your cells, since applying the script above on your notebook can generate a different output if you run the notebook again. For example, let's suppose your notebook have the following cells with the execution order in square brackets:
In [2]: a = 1
In [1]: a = 2
In [3]: a
Out[3]: 1
If you apply the above script into your notebook, it'll show the following:
In [1]: a = 1
In [2]: a = 2
In [3]: a
Out[3]: 1
But if you run the notebook again, it'll show the following:
In [1]: a = 1
In [2]: a = 2
In [3]: a
Out[3]: 2
This can be a bit confusing for people who are downloading your notebook via GitHub for example, since they can see an output in the repository, but when they run on their machine, the output will be different.
Cell > All Output > Clear Clear all In []: numbers but do not reset them back to 1 for the next cell you run.
Kernel > Restart & Clear Output Restart the kernel, clear output, clear In []: numbers and reset them to 1, and clear output.
Restart & Run All isn't a good solution, because simply I don't want to run all (and that's the purpose of a notebook to run things cell by cell).
Anyways, I found this solution more plausible:
Main Menu > Cell > All Output > Clear
For those coming from Google:
%reset
This is useful when you want to reset all variables after a certain point in the notebook. It is going to ask if you are sure that you want to reset. If you want to force reset without asking, then use:
%reset -f
Here is how to clear the execution numbers to [ ] without re-running the whole notebook:
Just to be safe, make a copy of your notebook:
cp notebook.ipynb notebook_copy.ipynb
Open your notebook with vim:
vim notebook.ipynb
In vim, reset the execution numbers with the following search-replace command:
:%s/"execution_count":.*/"execution_count": null,/gc
You will then get the following prompt. Type a to replace all occurrences:
replace with "execution_count": null, (y/n/a/q/l/^E/^Y)? a
Save notebook and quit vim:
:wq