How to clear method call parameters/arguments filled by SublimeText Jedi-autocomplete? - 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.

Related

How to configure IPython session using start_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)}

VS Code: How to access debug variables from within extension?

I am writing an extension for visual studio code where I want to evaluate the current variables of a javascript debug session. These variables are normally shown when one have open the debug pane under the section VARIABLES. See the attached screenshot.
I want to get access to these variables when the user right clicks the editor, but I don't know how.
My current extension setting for this is like that: in the package.json I have registered a menu contribution along with a command:
"contributes": {
"menus": {
"editor/context": [{
"command": "extension.showVariables",
"group": "navigation"
}]
}
}
In my extension.ts I register the command like that:
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.showVariables', () => {
// TODO: let variables = vscode.debug.activeDebugSession.variables.toString();
vscode.window.showInformationMessage(variables);
});
}
I have tried to get them through vscode.debug.activeDebugSession but there is no API for variables here. I also tried to register an event handler for vscode.debug.onDidReceiveDebugSessionCustomEvent but I can't figure out where to search for the debug variables.
Is it even possible to access these variables in an vs extension or do I need to implement my own debugger?
I have managed to get access to the local variables although this is not a general solution - it may only work in a single threaded debugger. If you know any better way, please answer or comment.
Say, the debugger breaks in a method that has a local variable car.
To get the value of car, I am using the customRequest method on the active debug session:
const session = vscode.debug.activeDebugSession;
const response = await session.customRequest('evaluate', { expression: 'car', frameId: frameId });
const car = response.result;
To get the frameId, I use another call of customRequest:
const session = vscode.debug.activeDebugSession;
const response = await session.customRequest('stackTrace', { threadId: 1 })
const frameId = response.stackFrames[0].id;
To get a real car object (not a string representation) in my extension, I pass "JSON.stringify(car)" as expression in the evaluate customRequest. Then, I can use JSON.parse(response.result).
To get all scopes, stacks and variables, have a look at the
Debug Session API and the specification of the DebugProtocol.
You have to talk to the debug adapter using the debug adapter protocol directly using vscode.debug.activeDebugSession.customRequest(command: string, args?: any) (Ref)
This function receives 2 parameters: command and args. Check out this resource to find all possible values of those parameters. One example is the 'evaluate' command that Michael Hilus uses in his answer:
If you want to get the variables in a multi threaded debug session, you must do these requests in this order
Threads Request: Get the thread ids
StackTrace Request: Get the frame ids
Scopes Request: Get the variablesReference
Variables Request: Finally, get the variable names with their values. If a variable is an object you might want to use Variables Request again with the variablesReference of the variable with an object value.
PS: It's kind of hard to find what you want in the DAP specification, so here is a tip:
Go to the 'Types' section in the right menu and find what you want. For instance, Breakpoints.
Ctrl+F and search ': Breakpoint'
Take a look at all matches in the response section of each request.
In the case of variablesReference I had to search variablesReference: number to find it in the responses of Evaluate Request, Scope (type) and Variable (also type).

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(); } }) ;
});

install4j: how can i pass command line arguments to windows service

I've created a windows service using install4j and everything works but now I need to pass it command line arguments to the service. I know I can configure them at service creation time in the new service wizard but i was hoping to either pass the arguments to the register service command ie:
myservice.exe --install --arg arg1=val1 --arg arg1=val2 "My Service Name1"
or by putting them in the .vmoptions file like:
-Xmx256m
arg1=val1
arg2=val2
It seems like the only way to do this is to modify my code to pick up the service name via exe4j.launchName and then load some other file or environment variables that has the necessary configuration for that particular service. I've used other service creation tools for java in the past and they all had straightforward support for command line arguments registered by the user.
I know you asked this back in January, but did you ever figure this out?
I don't know where you're sourcing val1, val2 etc from. Are they entered by the user into fields in a form in the installation process? Assuming they are, then this is a similar problem to one I faced a while back.
My approach for this was to have a Configurable Form with the necessary fields (as Text Field objects), and obviously have variables assigned to the values of the text fields (under the 'User Input/Variable Name' category of the text field).
Later in the installation process I had a Display Progress screen with a Run Script action attached to it with some java to achieve what I wanted to do.
There are two 'gotchas' when optionally setting variables in install4j this way. Firstly, the variable HAS to be set no matter what, even if it's just to the empty string. So, if the user leaves a field blank (ie they don't want to pass that argument into the service), you'll still need to provide an empty string to the Run executable or Launch Service task (more in that in a moment) Secondly, arguments can't have spaces - every space-separated argument has to have its own line.
With that in mind, here's a Run script code snippet that might achieve what you want:
final String[] argumentNames = {"arg1", "arg2", "arg3"};
// For each argument this method creates two variables. For example for arg1 it creates
// arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional.
// If the value of the variable set from the previous form (in this case, arg1) is not empty, then it will
// set 'arg1ArgumentIdentifierOptional' to '--arg', and 'arg1ArgumentAssignmentOptional' to the string arg1=val1 (where val1
// was the value the user entered in the form for the variable).
// Otherwise, both arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional will be set to empty.
//
// This allows the installer to pass both parameters in a later Run executable task without worrying about if they're
// set or not.
for (String argumentName : argumentNames) {
String argumentValue = context.getVariable(argumentName)==null?null:context.getVariable(argumentName)+"";
boolean valueNonEmpty = (argumentValue != null && argumentValue.length() > 0);
context.setVariable(
argumentName + "ArgumentIdentifierOptional",
valueNonEmpty ? "--arg": ""
);
context.setVariable(
argumentName + "ArgumentAssignmentOptional",
valueNonEmpty ? argumentName+"="+argumentValue : ""
);
}
return true;
The final step is to launch the service or executable. I'm not too sure how services work, but with the executable, you create the task then edit the 'Arguments' field, giving it a line-separated list of values.
So in your case, it might look like this:
--install
${installer:arg1ArgumentIdentifierOptional}
${installer:arg1ArgumentAssignmentOptional}
${installer:arg2ArgumentIdentifierOptional}
${installer:arg2ArgumentAssignmentOptional}
${installer:arg3ArgumentIdentifierOptional}
${installer:arg3ArgumentAssignmentOptional}
"My Service Name1"
And that's it. If anyone else knows how to do this better feel free to improve on this method (this is for install4j 4.2.8, btw).

How to support powershell tab expansion in psprovider?

I'm implementing Powershell PSProvider for some internal hierarchical data. Everything works fine, I can navigate through the tree with usual cd/dir commands, the only thing doesn't work is tab completion.
What I can see is that Powershell calls function GetChildName() with an asterisk in the path when Tab is pressed (if I type "dir c" and press Tab, GetChildName() function will be called with string "c*", several times). I tried to return all child names from the folder that begins with "c", but Powershell always displays just the first child name in the front. I can't find any documentation about this behavior, what I'm missing?
Are you sure you aren't just seeing normal behavior? With the default Tab Expansion, you will only see the first result. Pressing tab additional times will cycle through the list of returned results from the provider.
There are some quirks with providers. I have been working on one using the Script Provider project. I put debug code in all my methods to see which ones PowerShell was calling, when, and with what arguments.
I found where's the problem - function GetChildName() in the provider shouldn't try to expand given file name if asterisk is part of the name; The function should return child name if it can find an exact match, or call base.GetChildName() in any other case. Something like this:
protected override string GetChildName(string path) {
string name = SomeFunctionThatTriesToFindExactMatchForGivenPath(path);
if(string.IsNullOrEmpty( ret ) )
ret = base.GetChildName( path );
return ret;
}
BTW, I found that default tab expansion is very forgiving about stuff that can be returned from GetChildName() function - even if return value have slash/backslash in the front/back, tab expansion will work. But PowerTab, popular tab expansion module, is much more picky about return values.