How to configure IPython session using start_ipython()? - ipython

I have some code that launches an IPython session using start_ipython. It accepts a config option allowing to pass in a Config() object.
I can do things like:
c = Config()
c.InteractiveShellEmbed.colors = args.color
c.InteractiveShell.confirm_exit = args.confirmexit
c.InteractiveShell.prompts_class = MyPrompt
c.InteractiveShell.ast_node_interactivity = 'last_expr_or_assign'
IPython.start_ipython(config=c, user_ns=globals())
which changes prompts and display behaviour. All good.
I also wish to set some of the default formatters. The following works once I am in IPython
plain = get_ipython().display_formatter.formatters['text/plain']
plain.for_type(np.float64, plain.lookup_by_type(float))
but I want to set this up before launching IPython. The config object has a DisplayFormatter attribute but I don't understand how to configure it.
An ugly workaround is
code = [
"plain = get_ipython().display_formatter.formatters['text/plain'];",
"plain.for_type(np.float64, plain.lookup_by_type(float));",
"precision('%.3g');"
]
c.InteractiveShellApp.exec_lines = code
IPython.start_ipython(config=c, user_ns=globals())
which does the trick but the IPython session starts with
Out[1]: <function IPython.core.formatters.PlainTextFormatter._type_printers_default.<locals>.<lambda>(obj, p, cycle)>
Out[1]: "('%.3g');"
which I'd prefer not to see (and despite semicolons on the ends of the lines).
I want to avoid the need to change any external configuration files, so that IPython works for the user out of the box with specific behaviour.

The formatter classes are configurable as well.
Passing the type to formatter func dict might work for you. Refer https://ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-BaseFormatter.type_printers.
PlainTextFormatter also has an option to set the precision. Refer
https://ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-PlainTextFormatter.float_precision
Update #1:
c.PlainTextFormatter.float_precision = "%.3f"
c.BaseFormatter.type_printers = {np.float64: lambda obj, *args: str("%.3f" % obj)}

Related

How to show paths for auto imports with neovim nvim-cmp

Using neovim with nvim-cmp in ecmascript/typescript I want the menu to show 2 things that are not there by default.
If it's a local module, show the path.
If it's an import from a library, show the library name. (preferably in different color/font/icon than import from local component).
The docs shows a few examples of how to setup icons, but not how to show paths.
You can achieve something similar by adding these lines in the format function while calling nvim-cmp's setup:
if entry.completion_item.detail ~= nil and entry.completion_item.detail ~= "" then
vim_item.menu = entry.completion_item.detail
else
vim_item.menu = ({
nvim_lsp = "[LSP]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]",
})[entry.source.name]
end
result:

Protractor Custom Locator: Not available in production, but working absolutely fine on localhost

I have added a custom locator in protractor, below is the code
const customLocaterFunc = function (locater: string, parentElement?: Element, rootSelector?: any) {
var using = parentElement || (rootSelector && document.querySelector(rootSelector)) || document;
return using.querySelector("[custom-locater='" + locater + "']");
}
by.addLocator('customLocater', customLocaterFunc);
And then, I have configured it inside protractor.conf.js file, in onPrepare method like this:
...
onPrepare() {
require('./path-to-above-file/');
...
}
...
When I run my tests on the localhost, using browser.get('http://localhost:4200/login'), the custom locator function works absolutely fine. But when I use browser.get('http://11.15.10.111/login'), the same code fails to locate the element.
Please note, that the test runs, the browser gets open, user input gets provided, the user gets logged-in successfully as well, but the element which is referred via this custom locator is not found.
FYI, 11.15.10.111 is the remote machine (a virtual machine) where the application is deployed. So, in short the custom locator works as expected on localhost, but fails on production.
Not an answer, but something you'll want to consider.
I remember adding this custom locator, and encounter some problems with it and realised it's just an attribute name... nothing fancy, so I thought it's actually much faster to write
let elem = $('[custom-locator="locator"]')
which is equivalent to
let elem = element(by.css('[custom-locator="locator"]'))
than
let elem = element(by.customLocator('locator'))
And I gave up on this idea. So maybe you'll want to go this way too
I was able to find a solution to this problem, I used data- prefix for the custom attribute in the HTML. Using which I can find that custom attribute on the production build as well.
This is an HTML5 principle to prepend data- for any custom attribute.
Apart from this, another mistake that I was doing, is with the selector's name. In my code, the selector name is in camelCase (loginBtn), but in the production build, it was replaced with loginbtn (all small case), that's why my custom locater was not able to find it on the production build.

How to clear method call parameters/arguments filled by SublimeText Jedi-autocomplete?

I am testing out SublimeText auto-complete using JEDI package and one problem I am having is unrequired parameters are auto-filling function/method calls:
For example in Flask:
I can just call the function as such:
app.run(),
but JEDI-Autocomplete is doing something like this:
app.run(host= , port=..., debug=..., load_dotenv=...)
I can't figure out how to clear the parameters as it's not needed in this case.
Same problem with:
app = Flask(__name__)
Instead autocomplete is automatically filling in unrequired parameters and seemingly forcing me to add value to each argument.
Searching the Sublime Text 3's SublimeJEDI repo (issue #290 - open() autocompletes all args when in required mode) seems to suggests that there's an option to control autocomplete aggressiveness:
"auto_complete_function_params": "all",
In your preference settings (either user preferences or syntax preferences).
From their README.md:
Function parameters completion has 3 different behaviors:
Insert all function arguments on autocomplete:
# complete result
func(a, b, c, d=True, e=1, f=None)
# sublime_jedi.sublime-settings
{
"auto_complete_function_params": "all"
}
Insert only required arguments that don't have default value (default behavior):
# complete result
func(a, b, c)
# sublime_jedi.sublime-settings
{
"auto_complete_function_params": "required"
}
Do not insert any arguments:
# complete result
func()
# sublime_jedi.sublime-settings
{
"auto_complete_function_params": ""
}
More info about auto_complete_function_params
You may experiment with those options to see what fits you better.
Turning auto_complete off and using SublimeJedi: ShowDocstring (defaults to Ctrl+Alt+D) when the cursor is after the function name fixes the issue for me.
You can also hover over the function name or use SublimeJedi: Show Signature.

adding syntax highlighting to Jupyter notebook cell magic

I'm trying to figure out how to activate CodeMirror syntax highlighting for a CodeMirror-supported language (cypher) within a cell for a custom Jupyter cell magic (%%mymagic). The magic isn't associated with a special kernel - it just runs Python commands that process the string entered into the cell that I want to highlight. From what I can tell, this ostensibly can be done using something like
from notebook.services.config.manager import ConfigManager
cm = ConfigManager()
cm.update('notebook', {'CodeCell': {'highlight_modes': {'magic_cypher': {'reg': '^%%mymagic'}}}})
within the class that implements the magic.
I can't seem to get this to work, however; no change in highlighting occurs when I enter stuff in a cell that starts with %%mymagic. Is the above approach accurate? Does 'magic_cypher' need to have a specific format? Does the magic need to somehow specify the MIME type CodeMirror associates with the desired highlighting language? I'm using notebook 5.0.0, jupyter_core 4.3.0, and python 2.7.13.
The following code works for SQL when placed in ~/.jupyter/custom/custom.js with notebook 5.x:
require(['notebook/js/codecell'], function(codecell) {
codecell.CodeCell.options_default.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
Jupyter.notebook.events.one('kernel_ready.Kernel', function(){
Jupyter.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});
});
Credit goes to Thomas K for this info!
The case where I've been successful doing this was in adding SQL highlighting for the %%sql magic. I did this by adding the following to ~/.jupyter/custom/custom.js. The first line adds the mode to the Codemirror configuration, the rest apply the style to any existing cells in the workbook that need it (later cells will get styled appropriately as they are created). I haven't been successful in having it happen when the magic is installed, although I expect that it is possible.
IPython.CodeCell.config_defaults.highlight_modes['magic_text/x-mssql'] = {'reg':[/^%%sql/]} ;
IPython.notebook.events.one('kernel_ready.Kernel', function(){
IPython.notebook.get_cells().map(function(cell){
if (cell.cell_type == 'code'){ cell.auto_highlight(); } }) ;
});

Turn off auto-closing parentheses in ipython

I stay up-to-date with ipython's dev branch (because ipython is pretty much the most awesome thing ever). Fairly recently (before yesterday's awesome ipython 2.0 release) I noticed that it has started to automatically close parentheses, brackets, quotes, etc., as I type them. It happens in both terminal [nothing else I use in terminal does it] and notebook sessions, so I assume it was an intentional choice on the part of the developers. I can respect that other people might like this feature, but it drives me completely nuts.
I can't find any option for it in the configuration files. I can't even google for it, because I don't know what it's called. The only thing that comes up is the different feature of automatic parentheses. I did actually find this question, but that's old, and suggests that the behavior I'm seeing can't happen.
How can I turn this feature off?
[I mostly just use the notebook interface anyway, so just turning it off there would be fine, but I'd prefer to turn it off in both notebooks and ipython sessions at the terminal.]
#minrk's answer is the meat and bones of the fix, but you'll need to wrap it in an initialization callback, at least with IPython-3.1.0. In your custom.js:
require(['base/js/namespace', 'base/js/events'], function(IPython, events) {
events.on('app_initialized.NotebookApp', function() {
IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
});
});
Thanks #Mike for your comment about IPython's RequireJS dependency loading and the pointer to a better formulation at IPython/Jupyter Installing Extensions.
Edit for Jupyter 4.0.x:
The current IPython notebook implementation, Jupyter 4.0.0, revamped JS customizations. It now uses ~/.jupyter/custom/custom.js by default, and you'll need to replace that whole require(... events.on(...)) snippet with just the following in global scope:
IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
Likewise, if you want to use jQuery to manipulate anything, just use the jQuery global directly. For example, I like to hide the fixed header by default, which gives me another 40px of space for my code, which I find a bit more valuable than looking at the Jupyter logo all the time:
jQuery('#header-container').hide();
Edit for Jupyter ≥ 4.0.6 (but < Jupyter Lab):
If the custom.js solution above doesn't work, try adding the following to your ~/.jupyter/nbconfig/notebook.json:
{
"CodeCell": {
"cm_config": {
"autoCloseBrackets": false
}
}
}
The notebook behavior is the result of the CodeMirror autoCloseBrackets plugin. You can turn this off by editing (create it with ipython profile create if you haven't already) ~/.ipython/profile_default/static/custom/custom.js and adding:
if (IPython.CodeCell) {
IPython.CodeCell.options_default.cm_config.autoCloseBrackets = false;
}
As for the terminal, I don't see the parenthesis behavior you describe. Do you perhaps have a PYTHONSTARTUP defined? IPython executes this file by default, which you can disable by adding to ~/.ipython/profile_default/ipython_config.py:
c.InteractiveShellApp.exec_PYTHONSTARTUP = False
If you want to do it just from python:
from notebook.services.config import ConfigManager
c = ConfigManager()
c.update('notebook', {"CodeCell": {"cm_config": {"autoCloseBrackets": False}}})
This is what works for me in Jupyter 4.0.6:
require(['notebook/js/codecell'], function (codecell) {
codecell.CodeCell.options_default.cm_config.autoCloseBrackets = false;
})
in ~/.jupyter/custom/custom.js.
BTW, If you additionally want to switch off the syntax higlighting of matching parentheses:
codecell.CodeCell.options_default.cm_config.matchBrackets = false;
In the JupyterLab Notebook you can turn off the autoClosingBrackets plugin in the settings menu. Go to Settings --> Advanced Settings Editor and add the following in the User Overrides section:
{
"codeCellConfig": {
"autoClosingBrackets": false
}
}
Screenshot
This worked with JupyterLab 0.32.1 and jupyter_core 4.4.0
The above suggestions didn't worked for me in Jupyter 4.3.0 with Jupyter Notebook 5.0.0
I found that I needed to create a file called ~/.jupyter/custom/custom.js with the following contents:
var cell = Jupyter.notebook.get_selected_cell();
var patch = {
CodeCell: {
cm_config: {
autoCloseBrackets: false,
}
}
}
cell.config.update(patch);
Note that the directory ~/.juypter/custom didn't exist before I did this.
This was hacked together from suggestions in v5.0 docs, and for future readers these are the latest
For Jupyter Notebook 5.1 use the same thing as for 4.2, i.e. put the following snippet into ~/.jupyter/custom/custom.js:
require(['notebook/js/codecell'], function (codecell) {
codecell.CodeCell.options_default.cm_config.autoCloseBrackets = false;
})
I found it was not mentioned in other answers. In my case(OS X, Jupyter 4.2.0), custom.js is located in
~/anaconda/lib/python3.5/site-packages/notebook/static/custom/custom.js
I think it may help somebody like me.
We can do that from jupyter console, try it.