I am working on the auto suggestion list box the logic is good - listbox

I am working on the project the application is working fine
but small issue with list box,
I created a class where we can call get suggestion from the entry data a sample code is given below
from tkinter import *
root = Tk()
root.geometry('300x300')
search = StringVar()
search1 = StringVar()
search_list = ["Apple", "Ball", "cat", "dog"]
Label(root, text="Search :").pack(pady=15)
search1_ent = Entry(root, textvariable=search)
search1_ent.pack(pady=15)
search2_ent = Entry(root, textvariable=search1)
search2_ent.pack(pady=15)
list_box = Listbox(root, height=10, width=20)
EntryList.EntryBoxListLink(search_list, list_box, search1_ent, search, 90, 87, 20)
root.mainloop()
I created a py file on the name Entry list in that created a class Entry box list link,
It may not be perfect code but worked fine.
the class code is
import contextlib
from tkinter import *
class EntryBoxListLink:
"""this class is created to link entry box and the listbox"""
def __init__(self, list_data='', list_box='', entry_box=None, set_variable='', x_axis=38, y_axis=52, width=20,
next_entry=None):
self.list_data = list_data
self.list_box = list_box
self.entry_box = entry_box
self.set_variable = set_variable
self.x_axis = x_axis
self.y_axis = y_axis
self.width = width
def destroyListBox(event):
"""this is the command when the list box to place forget"""
with contextlib.suppress(BaseException):
self.list_box.place_forget()
def searchIList(event):
"""this gives the list box where the data no are aligned"""
self.list_box.config(width=self.width)
self.list_box.place(x=self.x_axis, y=self.y_axis)
self.list_box.bind('<Leave>', destroyListBox)
self.list_box.bind('<Double-1>', itemsSelected)
self.list_box.bind('<Return>', itemsSelected)
if self.list_data is not None:
match = [i for i in self.list_data if
(self.set_variable.get().lower() or self.set_variable.get().capitalize()) in i]
self.list_box.delete(0, END)
for c in match:
try:
self.list_box.insert(END, c.title())
except BaseException:
self.list_box.insert(END, c)
if not match:
destroyListBox(None)
if self.set_variable.get() == "":
destroyListBox(None)
def itemsSelected(event):
"""when the no is selected from list box it aligned to
the phone number and gives the data"""
for i in self.list_box.curselection():
self.set_variable.set(self.list_box.get(i))
self.entry_box.focus_set()
destroyListBox(None)
if next_entry is not None:
next_entry.focus()
def set_entry_focus(event):
if list_box.curselection()[0] == 0:
return self.entry_box.focus_set()
def focusAndSelect():
self.list_box.focus_set()
self.list_box.select_set(0)
self.entry_box.bind("<KeyRelease>", searchIList)
self.entry_box.bind("<Down>", lambda event: focusAndSelect())
self.list_box.bind("<Up>", set_entry_focus)
the issue is when I select the second entry box the list box should be gone,
to be more frank when the search1 and listbox are not in focus the list box should be place forget!

Related

In Networkx is there a way to select when to save to a file, when show on screen and when both?

At the moment, I am doing both:
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
plt.savefig('graph.jpg')
I would like to be able to select if to display, save or both (what I am doing now)
There is no built-in option for that in networkx. One option is to wrap the code in a function along these lines:
def custom(G, plot=True, save_file=False):
'''plots G by default. save_file should be a string'''
pos = nx.spring_layout(G)
f1 = plt.figure(figsize=(18,10))
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
if save: plt.savefig(save) # can allow custom save name
if plot: plt.show()
return
Note that if the figure displays regardless of the option passed to the command, then the inline option might need to be disabled.

Synchronizing Tooltips over multiple plots bokeh

I have created a grid plot using bokeh consisting of multiple vertically stacked line charts senter code hereharing same X axis.My requirement is to have a tooltip displayed on all the charts on hovering over a point on one of the charts.Tried multiple ways, but couldn't find a solution.It would be great if someone out there assist me in resolving this issue.
from bokeh.palettes import RdBu3, RdYlGn3
from bokeh.plotting import figure, output_notebook, show
from bokeh.io import show
from bokeh.models import ColumnDataSource, BoxAnnotation, Button, HoverTool, Text, Circle
from bokeh.models.callbacks import CustomJS
from bokeh.layouts import column, gridplot
from bokeh.models.widgets import TextInput, Div, Select
output_notebook()
#Main Data Source
source = ColumnDataSource(df)
#Filtering the data source based on some condition
df1 = df[Some_Condition]
#Filtered Data Source
sc = ColumnDataSource(df1)
#Callback to be executed on selecting a value from Select widget
callback_select = CustomJS(args=dict(source=source, sc=sc),code="""
var indices = [];
var val = cb_obj.value
sc.data['xx'] = []
sc.data['yy'] = []
sc.data['Date'] = []
for (var i = 0; i < source.get_length(); i++){
if (source.data['ZZ'][i] == val){
sc.data['xx'].push(source.data['xx'][i])
sc.data['yy'].push(source.data['yy'][i])
sc.data['Date'].push(source.data['Date'][i])
} else {
}
}
sc.change.emit();
""")
#Select Widget
select = Select(title="ZZ:", value="Select", options=["Opt1", "Opt2", "Opt3"], callback = callback_select)
#Tooltips to be displayed
TOOLTIPS = [("Value: ", "#{xx}")]
TOOLTIPS1 = [("Value: ", "#{yy}")]
#Tools to be shown on plot
_tools_to_show = 'box_zoom,pan,save,reset,tap,wheel_zoom,crosshair'
#First Chart
p1 = figure(x_axis_type="datetime", plot_height=200, tools = _tools_to_show)
p1.xaxis.visible = False
p1.xgrid.grid_line_color=None
p1.ygrid.grid_line_alpha=0.5
p1.xaxis.axis_label = 'Date'
p1.yaxis.axis_label = 'xx'
#Second Chart
p2 = figure(x_axis_type="datetime", plot_height=200, tools = _tools_to_show)
p2.xgrid.grid_line_color=None
p2.ygrid.grid_line_alpha=0.5
p2.xaxis.axis_label = 'Date'
p2.yaxis.axis_label = 'yy'
#Line charts
c11 = p1.line(x='Date', y='xx', source = sc, color = "green")
c12 = p1.circle(x='Date', y='xx', source = sc)
c21 = p2.line(x='Date', y='yy', source = sc, color = "blue")
c22 = p2.circle(x='Date', y='yy', source = sc)
#Text to be displayed over points on the charts.
visible_text1 = Text(x='Date', y='xx', text='xx', text_color='black', text_alpha=0.5)
visible_text2 = Text(x='Date', y='yy', text='yy', text_color='black', text_alpha=0.5)
#Adding text to the graphs
crt1 = p1.add_glyph(sc, visible_text, selection_glyph=visible_text1)
crt2 = p2.add_glyph(sc, visible_text2, selection_glyph=visible_text2)
#This piece of code does display multiple tooltips but shows vague behaviour viz. displaying a tooltip where there is no glyph
hover1 = HoverTool(renderers=[c12, c22], tooltips = TOOLTIPS)
hover2 = HoverTool(renderers=[c22, c12], tooltips = TOOLTIPS1)
#Adding hover tools
p1.add_tools(hover1)
p2.add_tools(hover2)
#Creating a grid for plotting
grid = gridplot([select, p1, p2, p3, p4], ncols=1, plot_width=1000, plot_height=1000)
show(grid)
As of Bokeh 1.2 there is not a good way to accomplish this. There is an open issue about this on GitHub #1547 - Coordinate tooltips across multiple plots that you can follow for updates or add your voice to.

Odoo 10 Print multiple reports with one click

Is there any way to print more than one report by one click in Odoo 10? For example i have one report template and some employees. Each employee should has own report with same template. And i want to print all report by one button.
I created template and python file. But could not print for each employee. Can you help me please?
you must have to extend qweb report like this
class orders_print(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(orders_print,self).__init__(cr,uid, name, context=context)
class SaleOrderReport(models.AbstractModel):
_name = 'report.sale.report_saleorder'
_inherit = 'report.abstract_report'
_template = 'sale.report_saleorder'
_wrapped_report_class = orders_print
#api.multi
def render_html(self, docids,data=None,context=None):
report_obj = self.env['report']
report = report_obj._get_report_from_name('sale.report_saleorder')
if data['data']:
d = ast.literal_eval(data['data']['options'])
docs = self.env[report.model].browse(d['ids'])
docargs = {
'doc_ids': self._ids,
'doc_model': 'sale.order',
'docs': docs,
}
return report_obj.render('sale.report_saleorder', docargs)
else:
return super(SaleOrderReport,self).render_html(docids,data=data)

TabularAdapter Editor issue

I've run into an issue with the TabularAdapter in the TraitsUI package...
I've been trying to figure this out on my own for much too long now, so I wanted to ask the experts here for some friendly advise :)
I'm going to add a piece of my program that illustrates my problem(s), and I'm hoping someone can look it over and say 'Ah Ha!...Here's your problem' (my fingers are crossed).
Basically, I can use the TabularAdapter to produce a table editor into an array of dtypes, and it works just fine except:
1) whenever I change the # of elements (identified as 'Number of fractures:'), the array gets resized, but the table doesn't reflect the change until after I click on one of the elements. What I'd like to happen is that the # of rows (fractures) changes after I release the # of fractures slider. Is this doable?
2) The second issue I have is that if the array gets resized before it's displayed by .configure_traits() (by the notifier when Number_of_fractures gets modified), I can shrink the size of the array, but I can't increase it over the new size.
2b) I thought I'd found a way to have the table editor display the full array even when it's increased over the 5 set in the code (just before calling .trait_configure()), but I was fooled :( I tried adding another Group() in front of the vertical_fracture_group so the table wasn't the first thing to display. This more closely emulates my entire program. When I did this, I was locked into the new smaller size of the array, and I could no longer increase its size to my maximum of 15. I'm modifying the code to reflect this issue.
Here's my sample code:
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import zeros, dtype
from traits.api import HasTraits, Range
from traitsui.api import View, Group, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
vertical_frac_array = zeros((max_cracks), dtype=vertical_frac_dtype)
vertical_fracture_group = Group(
Item(name = 'vertical_frac_array',
show_label = False,
editor = TabularEditor(adapter = VertFractureAdapter()),
width = 0.5,
height = 0.5,
)
)
#-- THIS is the actual 'View' that gets put on the screen
view = View(
#Note: When as this group 'displays' before the one with the Table, I'm 'locked' into my new maximum table display size of 8 (not my original/desired maximum of 15)
Group(
Item( name = 'Number_Of_Fractures'),
),
#Note: If I place this Group() first, my table is free to grow to it's maximum of 15
Group(
Item( name = 'Number_Of_Fractures'),
vertical_fracture_group,
),
width = 0.60,
height = 0.50,
title = '****** Setup',
resizable=True,
)
#-- Traits Event Handlers --------------------------------------------------
def _Number_Of_Fractures_changed(self):
""" Handles resizing arrays if/when the number of Fractures is changed"""
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
#if not self.user_StartingUp:
self.vertical_frac_array.resize(self.Number_Of_Fractures, refcheck=False)
for crk in range(self.Number_Of_Fractures):
self.vertical_frac_array[crk]['Fracture'] = crk+1
self.vertical_frac_array[crk]['x'] = crk
self.vertical_frac_array[crk]['y'] = crk
self.vertical_frac_array[crk]['z'] = crk
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
fileDialog.configure_traits()
fileDialog.Number_Of_Fractures = 8
In my discussion with Chris below, he made some suggestions that so far haven't worked for me :( Following is my 'current' version of this test code so Chris (or anyone else who wishes to chime in) can see if I'm making some glaring error.
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import zeros, dtype
from traits.api import HasTraits, Range, Array, List
from traitsui.api import View, Group, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
even_bg_color = 0xf4f4f4 # very light gray
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
dummy = Range(1, max_cracks)
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
vertical_frac_array = Array(dtype=vertical_frac_dtype)
vertical_fracture_group = Group(
Item(name = 'vertical_frac_array',
show_label = False,
editor = TabularEditor(adapter = VertFractureAdapter()),
width = 0.5,
height = 0.5,
)
)
#-- THIS is the actual 'View' that gets put on the screen
view = View(
Group(
Item( name = 'dummy'),
),
Group(
Item( name = 'Number_Of_Fractures'),
vertical_fracture_group,
),
width = 0.60,
height = 0.50,
title = '****** Setup',
resizable=True,
)
#-- Traits Event Handlers --------------------------------------------------
def _Number_Of_Fractures_changed(self, old, new):
""" Handles resizing arrays if/when the number of Fractures is changed"""
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
vfa = self.vertical_frac_array
vfa.resize(self.Number_Of_Fractures, refcheck=False)
for crk in range(self.Number_Of_Fractures):
vfa[crk]['Fracture'] = crk+1
vfa[crk]['x'] = crk
vfa[crk]['y'] = crk
vfa[crk]['z'] = crk
self.vertical_frac_array = vfa
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
# put the actual dialog up...if I put it up 'first' and then resize the array, I seem to get my full range back :)
fileDialog.configure_traits()
#fileDialog.Number_Of_Fractures = 8
There are two details of the code that are causing the problems you describe. First, vertical_frac_array is not a trait, so the tabular editor cannot monitor it for changes. Hence, the table only refreshes when you manually interact with it. Second, traits does not monitor the contents of an array for changes, but rather the identity of the array. So, resizing and assigning values into the array will not be detected.
One way to fix this is to first make vertical_frac_array and Array trait. E.g. vertical_frac_array = Array(dtype=vertical_frac_dtype). Then, inside of _Number_Of_Fractures_changed, do not resize the vertical_frac_array and modify it in-place. Instead, copy vertical_frac_array, resize it, modify the contents, and then reassign the manipulated copy back to vertical_frac_array. This way the table will see that the identity of the array has changed and will refresh the view.
Another option is to make vertical_frac_array a List instead of an Array. This avoids the copy-and-reassign trick above because traits does monitor the content of lists.
Edit
My solution is below. Instead of resizing the vertical_frac_array whenever Number_Of_Fractures changes, I instead recreate the array. I also provide a default value for vertical_frac_array via the _vertical_frac_array_default method. (I removed from unnecessary code in the view as well.)
# -*- coding: utf-8 -*-
"""
This is a first shot at developing a ****** User Interface using Canopy by
Enthought. Canopy is a distribution of the Python language which has a lot of
scientific and engineering features 'built-in'.
"""
#-- Imports --------------------------------------------------------------------
from traitsui.api import TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import dtype, zeros
from traits.api import HasTraits, Range, Array
from traitsui.api import View, Item
#-- FileDialogDemo Class -------------------------------------------------------
max_cracks = 15 #maximum number of Fracs/cracks to allow
vertical_frac_dtype = dtype([('Fracture', 'int'), ('x', 'float'), ('y', 'float'),
('z', 'float'), ('Horiz Length', 'float'), ('Vert Length', 'float')
, ('z-axis Rotation, degrees', 'float')])
class VertFractureAdapter(TabularAdapter):
columns = [('Frac #',0), ('X Cen',1), ('Y Cen',2), ('Z Cen',3),
('Horiz',4), ('Vert',5), ('Angle',6)]
class SetupDialog ( HasTraits ):
Number_Of_Fractures = Range(1, max_cracks) # line 277
vertical_frac_array = Array(dtype=vertical_frac_dtype)
view = View(
Item('Number_Of_Fractures'),
Item(
'vertical_frac_array',
show_label=False,
editor=TabularEditor(
adapter=VertFractureAdapter(),
),
width=0.5,
height=0.5,
),
width=0.60,
height=0.50,
title='****** Setup',
resizable=True,
)
#-- Traits Defaults -------------------------------------------------------
def _vertical_frac_array_default(self):
""" Creates the default value of the `vertical_frac_array`. """
return self._calculate_frac_array()
#-- Traits Event Handlers -------------------------------------------------
def _Number_Of_Fractures_changed(self):
""" Update `vertical_frac_array` when `Number_Of_Fractures` changes """
print "I've changed the # of Fractures to " + repr(self.Number_Of_Fractures)
#if not self.user_StartingUp:
self.vertical_frac_array = self._calculate_frac_array()
#-- Private Interface -----------------------------------------------------
def _calculate_frac_array(self):
arr = zeros(self.Number_Of_Fractures, dtype=vertical_frac_dtype)
for crk in range(self.Number_Of_Fractures):
arr[crk]['Fracture'] = crk+1
arr[crk]['x'] = crk
arr[crk]['y'] = crk
arr[crk]['z'] = crk
return arr
# Run the program (if invoked from the command line):
if __name__ == '__main__':
# Create the dialog:
fileDialog = SetupDialog()
fileDialog.configure_traits()

Django-Admin Exception Value: 'DeclarativeFieldsMetaclass' object is not iterable

I have one form in forms.py
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
and my site url is
admin.autodiscover()
urlpatterns = patterns('', (r'^admin/(.*)',
include(admin.site.urls)),)
now I want it to be shown on admin interface
I tried so far
First attempt
from myapps.forms import EmailForm
class EmailAdmin(admin.ModelAdmin):
form = EmailForm
did not work Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
Second attempt
and now I followed http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contri...
but could not get help
class EmailAdmin(admin.ModelAdmin):
def my_view(self,request):
return admin_my_view(request,self)
def get_urls(self):
urls = super(SmsAdmin, self).get_urls()
my_urls = patterns('',(r'^my_view/
$',self.admin_site.admin_view(self.my_view)))
return my_urls + urls
def admin_my_view(request, model_admin):
opts = model_admin.model._meta
admin_site = model_admin.admin_site
has_perm = request.user.has_perm(opts.app_label \
+ '.' + opts.get_change_permission())
context = {'admin_site': admin_site.name,
'title': "My Custom View",
'opts': opts,
'root_path': '/%s' % admin_site.root_path,
'app_label': opts.app_label,
'has_change_permission': has_perm}
template = 'admin/demo_app/admin_my_view.html'
return render_to_response(template,
context,context_instance=RequestContext(request))
admin.site.register(EmailForm,EmailAdmin)
and when I run server and type on browser localhost:8000/admin
and hit enter button
Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
and second time just after first time when I again enter then it show
me the admin page but I can't see my EmailAdmin in admin interface..
Just help me or suggest me any link.
Thanks
(This is my attempt at reformatting your model code):
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
I would put my money on the bit that says "attrs=require" -- if that's not a typo.
What you want instead is something like this:
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(), required=True)

Resources