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

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:

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

typo3 read configuration options in typoscript

I've tried several approaches to read the configuration options of my plugin in typoscript, but none of them seem to work
ajax.30 = TEXT
ajax.30.value = {plugin.tx_parser.settings.numVar}
ajax.40 < {tx_parser.settings.numVar}
ajax.50 < {tx_parser.settings.numVar}
ajax.80 = TEXT
ajax.80.value = {options.numVar}
ajax.90 = TEXT
ajax.90.value = {settings.numVar}
Can anyone please explain me the syntax or post a link where it is explained; I can use ext_conf_template.txt explained here https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ExtensionArchitecture/ConfigurationOptions/Index.html but I didn't get these options in typoscript.
All I want is to access (in typoscript) the configuration options of the following picture
If I browse Constants I don't see any of these options
If I add my plugin to the site I see some plugin options but none of them I wanted
You can use constants with this syntax in TypoScript setup or constants
var = {$plugin.tx_parser.settings.numVar}
So in your case:
ajax.30 = TEXT
ajax.30.value = {$plugin.tx_parser.settings.numVar}
See https://docs.typo3.org/m/typo3/reference-typoscript/master/en-us/UsingSetting/Constants.html
To assign an earlier declared setup value you would use the < (object copy) operator
ajax.30 = TEXT
ajax.30.value < plugin.tx_parser.settings.numVar
Here is an on overview of its syntax: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/TypoScriptSyntax/Syntax/TypoScriptSyntax.html
The difference between constants and setup is essential. You can check in the backend in the module Template -> Template browser - see https://docs.typo3.org/m/typo3/reference-typoscript/master/en-us/UsingSetting/Debugging.html

Python w/QT Creator form - Possible to grab multiple values?

I'm surprised to not find a previous question about this, but I did give an honest try before posting.
I've created a ui with Qt Creator which contains quite a few QtWidgets of type QLineEdit, QTextEdit, and QCheckbox. I've used pyuic5 to convert to a .py file for use in a small python app. I've successfully got the form connected and working, but this is my first time using python with forms.
I'm searching to see if there is a built-in function or object that would allow me to pull the ObjectNames and Values of all widgets contained within the GUI form and store them in a dictionary with associated keys:values, because I need to send off the information for post-processing.
I guess something like this would work manually:
...
dict = []
dict['checkboxName1'] = self.checkboxName1.isChecked()
dict['checkboxName2'] = self.checkboxName2.isChecked()
dict['checkboxName3'] = self.checkboxName3.isChecked()
dict['checkboxName4'] = self.checkboxName4.isChecked()
dict['lineEditName1'] = self.lineEditName1.text()
... and on and on
But is there a way to grab all the objects and loop through them, even if each different type (i.e. checkboxes, lineedits, etc) needs to be done separately?
I hope I've explained that clearly.
Thank you.
Finally got it working. Couldn't find a python specific example anywhere, so through trial and error this worked perfectly. I'm including the entire working code of a .py file that can generate a list of all QCheckBox objectNames on a properly referenced form.
I named my form main_form.ui from within Qt Creator. I then converted it into a .py file with pyuic5
pyuic5 main_form.ui -o main_form.py
This is the contents of a sandbox.py file:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import main_form
# the name of my Qt Creator .ui form converted to main_form.py with pyuic5
# pyuic5 original_form_name_in_creator.ui -o main_form.py
class MainApp(QtWidgets.QMainWindow, main_form.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
# Push button object on main_form named btn_test
self.btn_test.clicked.connect(self.runTest)
def runTest(self):
# I believe this creates a List of all QCheckBox objects on entire UI page
c = self.findChildren(QtWidgets.QCheckBox)
# This is just to show how to access objectName property as an example
for box in c:
print(box.objectName())
def main():
app = QtWidgets.QApplication(sys.argv) # A new instance of QApplication
form = MainApp() # We set the form to be our ExampleApp (design)
form.show() # Show the form
app.exec_() # and execute the app
if __name__ == '__main__': # if we're running file directly and not importing it
main() # run the main function
See QObject::findChildren()
In C++ the template argument would allow one to specify which type of widget to retrieve, e.g. to just retrieve the QLineEdit objects, but I don't know if or how that is mapped into Python.
Might need to retrieve all types and then switch handling while iterating over the resulting list.

Do Flask/Jinja2 have a provision to save rendered templates during debugging?

While debugging it's useful to view the rendered HTML and JS templates through a "view source" menu item in a browser, but doing so forces one to use the UI of the browser.
Does Jinja2 (or Flask) provide a facility to save the last n rendered templates on the server? It would then be possible to use one's favorite editor to view the rendered files, along with using one's familiar font-locking and search facilities.
It's of course possible to implement such a facility by hand, but doing so smacks too much like peppering one's programs while debugging with print statements, an approach that doesn't scale. I'm seeking a better alternative.
I'd think the easiest thing to do would be to use the after_request hook.
from flask import g
#main.route('/')
def index():
models = Model.query.all()
g.template = 'index'
return render_template('index.html', models=models)
#main.after_request
def store_template(response):
if hasattr(g, 'template'):
with open('debug/{0}-{1}'.format(datetime.now(), g.template), 'w') as f:
f.write(response.data)
return response
Here are the docs.
http://flask.pocoo.org/snippets/53/
As far as only collecting the last n templates I'd likely setup a cron job to do that. Here is an example
import os
from datetime import datetime
def make_files(n):
text = '''
<html>
</html>
'''
for a in range(n):
with open('debug/index-{0}.html'.format(datetime.now()), 'w') as f:
f.write(text)
def get_files(dir):
return [file for file in os.listdir(dir) if file.endswith('.html')]
def delete_files(dir, files, amount_kept):
rev = files[::-1]
for file in rev[amount_kept:]:
loc = dir + '/' + file
os.remove(loc)
if __name__ == '__main__':
make_files(7)
files = get_files('debug')
print files
delete_files('debug', files, 5)
files = get_files('debug')
print files
EDIT
reversed order of files inside the delete function so it will keep the most recent files. Also unable to find a way of accessing the original template name to avoid hardcoding.
EDIT 2
Alright so updated it to show how you can use flask.g to pass the template name to the after_request function
docs http://flask.pocoo.org/docs/0.11/testing/#faking-resources

Trac - Get date of last commit of a specific repository file in wiki page

I'm using Trac to manage my projects. Some guys have to take a regular look to my wiki pages to watch changes in a special file. Therefore I have a link on my wikipage. Something link this:
[source:MyRepository/trunk/subfolder/file.pdf#head The file to read]
What I would like to have is the following output:
The file to read (last commited: 11/01/15 at 08:52am)
Any ideas how to manage that in trac wiki?
You will probably have to write a small plugin for that, something like the following:
from genshi.builder import tag
from trac.util.datefmt import format_datetime
from trac.util.translation import _
from trac.versioncontrol.api import RepositoryManager
from trac.wiki.api import parse_args
from trac.wiki.macros import WikiMacroBase
class SourceMacro(WikiMacroBase):
def expand_macro(self, formatter, name, content):
args, kwargs = parse_args(content)
path = args[0]
label = kwargs.get('label', path)
rm = RepositoryManager(self.env)
reponame, repos, path = rm.get_repository_by_path(path)
node = repos.get_node(path)
href = formatter.href.browser(reponame or None, path)
return tag(tag.a(label, href=href),
_(' (last committed: %(date)s)',
date=format_datetime(node.last_modified)))
(For Trac 0.12 or later, error handling left as the dreaded exercise to the reader.)
Place this in a file file named source_link.py in the plugins directory of your Trac environment. Then you can reference your files with the following macro:
[[Source(MyRepository/trunk/subfolder/file.pdf)]]
or if you want a specific label:
[[Source(MyRepository/trunk/subfolder/file.pdf, label=The file to read)]]