Jupyter DataViewer does not offer view to show non basetype objects - visual-studio-code

I am using a jupyter notebook in Visual Studio Code.
In normal case when for example running a cell that contains a list or similar
my_test_list : list = [1,2,3]
I get the option Show variable in data viewer in the Window Juyper: Variables
But when I have an objects of one of my own classes:
class MyClass():
def __init__(self,val1,val2):
self.val1 = val1
self.val2 = val2
def __repr__(self):
return f"{self.val1} and {self.val2}"
def __str__(self):
return self.__repr__()
and create a new object in another cell with
myObject = MyClass(1,2)
myObject is shown in the Window Juyper: Variables but no button Show variable in data viewer appears.
My question: Is there any way to define a custom representation of for example MyObject that the data viewer can recognise and display or are there any packages that would allow the data viewer to pick up for example the repr or str method?

Related

LibreOffice Tree with columns

I am writing an extension for LibreOffifce.
A tree with columns on my sidebar is needed. (example - https://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html)
I found information about Tree Control and module "tree", e.g. here
https://wiki.openoffice.org/wiki/Treecontrol
https://www.openoffice.org/api/docs/common/ref/com/sun/star/awt/tree/module-ix.html
But I couldn't find anything about writing a tree with columns.
There is a quote "You can provide your own model which must at least support the interface com.sun.star.awt.XTreeModel." in the article "Tree control", but I also couldn't find any information about providing of my own models...
Please, help me find information and examples, if it is possible to provide tree with columns for LibreOffice extension.
Here is some Python-UNO code (as tagged in your question) that shows how to implement the XTreeDataModel UNO interface. You'll have to write a lot more code in order to render the nodes in multiple columns and do everything else you want. It may be required to create another class that implements XTreeNode.
import uno
import unohelper
from com.sun.star.awt.tree import XTreeDataModel
def myTree():
document = XSCRIPTCONTEXT.getDocument()
ctx = XSCRIPTCONTEXT.getComponentContext()
smgr = ctx.getServiceManager()
dlgprov = smgr.createInstanceWithArgumentsAndContext(
"com.sun.star.awt.DialogProvider", (document,), ctx)
dlg = dlgprov.createDialog(
"vnd.sun.star.script:Standard.Dialog1?location=application")
treeCtrl = dlg.getControl("TreeControl1")
treeModel = treeCtrl.getModel()
mutableTreeDataModel = smgr.createInstanceWithContext(
"com.sun.star.awt.tree.MutableTreeDataModel", ctx)
rootNode = mutableTreeDataModel.createNode("Root", True)
mutableTreeDataModel.setRoot(rootNode)
myTree = MyTreeDataModel(rootNode)
model = mutableTreeDataModel
childNode1 = model.createNode("Parent 1", True)
rootNode.appendChild(childNode1)
subChildNode = model.createNode("Child 1", True)
childNode1.appendChild(subChildNode)
treeModel.setPropertyValue("DataModel", myTree)
dlg.execute()
dlg.dispose()
class MyTreeDataModel(unohelper.Base, XTreeDataModel):
def __init__(self, root):
self.rootNode = root
def getRoot(self):
return self.rootNode
def addTreeDataModelListener(self, listener):
pass
def removeTreeDataModelListener(self, listener):
pass
More information for working with trees is at https://wiki.openoffice.org/wiki/Going_further_with_Dialog_and_Component#The_New_Tree_Control.
If it turns out that there is no convenient way to do this directly with UNO, I once did this with a JTreeTable in Java. LibreOffice extensions can be written in Java, so perhaps that would solve your needs instead.

configure_traits freezes console in Spyder/Anaconda

Trying the very first example in traitsui doc:
from traits.api import HasTraits, Str, Int
from traitsui.api import View, Item
import traitsui
class SimpleEmployee(HasTraits):
first_name = Str
last_name = Str
department = Str
employee_number = Str
salary = Int
view1 = View(Item(name = 'first_name'),
Item(name = 'last_name'),
Item(name = 'department'))
sam = SimpleEmployee()
sam.configure_traits(view=view1)
makes the Spyder IPython console hang, even after the UI window has been closed.
MacOSX 10.14.6, Spyder 4.0.0, Python 3.7.0, IPython 7.10.2, traitsui 6.1.3
Probably something to configure about the UI event loop, but what and how ?
The difference between the Canopy IPython console and the Spyder IPython console is that
app = QtGui.QApplication.instance()
print(app)
returns
<PyQt5.QtWidgets.QApplication at 0xXXXXXXXX>
for both, but
is_event_loop_running_qt4(app)
returns Truein Canopy IPython terminal and False in Spyder IPython terminal.
It is necessary to patch view_application() in traits.qt4.view_application by commenting out the lines starting a new ViewApplication instance depending on that test. Instead of changing the original file, it is possible to run the following code:
# -*- coding: utf-8 -*-
"""Avoid Spyder console to hang when using configure_traits()
"""
from IPython import get_ipython
from pyface.qt import QtCore, QtGui, qt_api
from pyface.util.guisupport import is_event_loop_running_qt4
from traitsui.api import toolkit
from traitsui.qt4.view_application import ViewApplication
KEEP_ALIVE_UIS = set()
def on_ui_destroyed(object, name, old, destroyed):
""" Remove the UI object from KEEP_ALIVE_UIS.
"""
assert name == 'destroyed'
if destroyed:
assert object in KEEP_ALIVE_UIS
KEEP_ALIVE_UIS.remove(object)
object.on_trait_change(on_ui_destroyed, 'destroyed', remove=True)
def _view_application(context, view, kind, handler, id, scrollable, args):
""" Creates a stand-alone PyQt application to display a specified traits UI
View.
Parameters
----------
context : object or dictionary
A single object or a dictionary of string/object pairs, whose trait
attributes are to be edited. If not specified, the current object is
used.
view : view object
A View object that defines a user interface for editing trait attribute
values.
kind : string
The type of user interface window to create. See the
**traitsui.view.kind_trait** trait for values and
their meanings. If *kind* is unspecified or None, the **kind**
attribute of the View object is used.
handler : Handler object
A handler object used for event handling in the dialog box. If
None, the default handler for Traits UI is used.
scrollable : Boolean
Indicates whether the dialog box should be scrollable. When set to
True, scroll bars appear on the dialog box if it is not large enough
to display all of the items in the view at one time.
"""
if (kind == 'panel') or ((kind is None) and (view.kind == 'panel')):
kind = 'modal'
# !!!!!!! The following 4 lines commented out !!!!!!!!!!!
# app = QtGui.QApplication.instance()
# if app is None or not is_event_loop_running_qt4(app):
# return ViewApplication(context, view, kind, handler, id,
# scrollable, args).ui.result
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ui = view.ui(context,
kind=kind,
handler=handler,
id=id,
scrollable=scrollable,
args=args)
# If the UI has not been closed yet, we need to keep a reference to
# it until it does close.
if not ui.destroyed:
KEEP_ALIVE_UIS.add(ui)
ui.on_trait_change(on_ui_destroyed, 'destroyed')
return ui.result
def view_application(self, context, view, kind=None, handler=None,
id='', scrollable=None, args=None):
""" Creates a PyQt modal dialog user interface that
runs as a complete application, using information from the
specified View object.
Parameters
----------
context : object or dictionary
A single object or a dictionary of string/object pairs, whose trait
attributes are to be edited. If not specified, the current object is
used.
view : view or string
A View object that defines a user interface for editing trait
attribute values.
kind : string
The type of user interface window to create. See the
**traitsui.view.kind_trait** trait for values and
their meanings. If *kind* is unspecified or None, the **kind**
attribute of the View object is used.
handler : Handler object
A handler object used for event handling in the dialog box. If
None, the default handler for Traits UI is used.
id : string
A unique ID for persisting preferences about this user interface,
such as size and position. If not specified, no user preferences
are saved.
scrollable : Boolean
Indicates whether the dialog box should be scrollable. When set to
True, scroll bars appear on the dialog box if it is not large enough
to display all of the items in the view at one time.
"""
return _view_application(context, view, kind, handler,
id, scrollable, args)
from traitsui.qt4.toolkit import GUIToolkit
GUIToolkit.view_application = view_application
Thus, the behavior is OK in both Spyder and Canopy IPython consoles. Note that configure_traits(kind='modal') is also OK in both.

Storing a variable from a class within a class (tkinter)

I am trying to capture the entry value from the pop up window into a variable that I can access later and manipulate. I need to make a lists of several message box entries to generate questions for the user. However, whenever I try to capture it the variable I assign it to comes up empty.
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
class popupWindowID (object):
def __init__(self,master):
top=self.top=Toplevel(master)
self.label=Label(top,text="ID")
self.label.pack()
self.entrybox=Entry(top)
self.entrybox.pack()
self.b=Button(top,text='Enter',command=self.cleanup)
self.b.pack()
def cleanup(self): # This cleans it up so it can be overwritten if needed
self.value=str(self.entrybox.get())
self.top.destroy()
class mainWindow(object):
def __init__(self,master):
self.master=master
self.ID=Button(topFrame,text="ID", command=self.popupID)
self.ID.pack(side = TOP)
self.info=Button(topFrame,text="Show Test Information",command=self.entryValue)
self.info.pack(side = TOP)
def popupID(self):
self.ID=popupWindowID(self.master)
self.master.wait_window(self.ID.top)
def entryValue(self):
print(self.ID.value)
m=mainWindow(root)
root.mainloop()

Multi Object View Behaviour - Creating an Editor for a HasTraits subclass

I am currently trying to make a traitsUI GUI for a class that contains many instances of a single object. My problem is very similar to the one solved in MultiObjectView Example TraitsUI.
However, I don't like the idea of using a context as it requires me to write out the same view many times for each object I have (and I might have a lot). So I tried to edit the code to make it so that each Instance of the House object would default to looking like its normal view when it is viewed from the Houses object. It almost worked, except now I get a button that takes me to the view I want rather than seeing the views nested in one window (like the output of the TraitsUI example above).
Is there a way to adapt the below to get the desired output? I think I have to further edit the create_editor function but I can find very little documentation on this - only many links to different trait editor factories...
Thanks,
Tim
# multi_object_view.py -- Sample code to show multi-object view
# with context
from traits.api import HasTraits, Str, Int, Bool
from traitsui.api import View, Group, Item,InstanceEditor
# Sample class
class House(HasTraits):
address = Str
bedrooms = Int
pool = Bool
price = Int
traits_view =View(
Group(Item('address'), Item('bedrooms'), Item('pool'), Item('price'))
)
def create_editor(self):
""" Returns the default traits UI editor for this type of trait.
"""
return InstanceEditor(view='traits_view')
class Houses(HasTraits):
house1 = House()
house2= House()
house3 = House()
traits_view =View(
Group(Item('house1',editor = house1.create_editor()), Item('house2',editor = house1.create_editor()), Item('house3',editor = house1.create_editor()))
)
hs = Houses()
hs.configure_traits()
Would something like this work?
It simplifies things a little bit and gives you a view that contains the list of views for your houses.
# multi_object_view.py -- Sample code to show multi-object view
# with context
from traits.api import HasTraits, Str, Int, Bool
from traitsui.api import View, Group, Item,InstanceEditor
# Sample class
class House(HasTraits):
address = Str
bedrooms = Int
pool = Bool
price = Int
traits_view =View(
Group(
Item('address'), Item('bedrooms'), Item('pool'), Item('price')
)
)
class Houses(HasTraits):
house1 = House()
house2= House()
house3 = House()
traits_view =View(
Group(
Item('house1', editor=InstanceEditor(), style='custom'),
Item('house2', editor=InstanceEditor(), style='custom'),
Item('house3', editor=InstanceEditor(), style='custom')
)
)
if __name__ == '__main__':
hs = Houses()
hs.configure_traits()

Django-Nonrel with Mongodb listfield

I am trying to implement manytomany field relation in django-nonrel on mongodb. It was suggessted at to:
Django-nonrel form field for ListField
Following the accepted answer
models.py
class MyClass(models.Model):
field = ListField(models.ForeignKey(AnotherClass))
i am not sure where the following goes, it has been tested in fields.py, widgets,py, models.py
class ModelListField(ListField):
def formfield(self, **kwargs):
return FormListField(**kwargs)
class ListFieldWidget(SelectMultiple):
pass
class FormListField(MultipleChoiceField):
"""
This is a custom form field that can display a ModelListField as a Multiple Select GUI element.
"""
widget = ListFieldWidget
def clean(self, value):
#TODO: clean your data in whatever way is correct in your case and return cleaned data instead of just the value
return value
admin.py
class MyClassAdmin(admin.ModelAdmin):
form = MyClassForm
def __init__(self, model, admin_site):
super(MyClassAdmin,self).__init__(model, admin_site)
admin.site.register(MyClass, MyClassAdmin)
The following Errors keep popping up:
If the middle custom class code is used in models.py
name 'SelectMultiple' is not defined
If custom class code is taken off models.py:
No form field implemented for <class 'djangotoolbox.fields.ListField'>
You just need to import SelectMultiple by the sound of it. You can put the code in any of those three files, fields.py would make sense.
Since it's pretty usual to have:
from django import forms
at the top of your file already, you probably just want to edit the code below to:
# you'll have to work out how to import the Mongo ListField for yourself :)
class ModelListField(ListField):
def formfield(self, **kwargs):
return FormListField(**kwargs)
class ListFieldWidget(forms.SelectMultiple):
pass
class FormListField(forms.MultipleChoiceField):
"""
This is a custom form field that can display a ModelListField as a Multiple Select GUI element.
"""
widget = ListFieldWidget
def clean(self, value):
#TODO: clean your data in whatever way is correct in your case and return cleaned data instead of just the value
return value
You probably also want to try and learn a bit more about how python works, how to import modules etc.