no bar on MDScrollView in kivyMD - scrollview

i have a label that prints out data and it needs to be scrollable.
so it scrolls now but it does not have a scroll bar and the text bounces back to top once you release it.I have tried adding bar_width: 10 changed nothing.
from kivy.lang import Builder
from kivymd.uix.scrollview import MDScrollView
from kivy.properties import StringProperty, ObjectProperty
from kivymd.uix.pickers import MDDatePicker
from kivymd.app import MDApp
import json
KV = '''
MDScreenManager:
MDScreen:
name: "main"
MDGridLayout:
cols: 1
MDRaisedButton:
font_size: "32sp"
text: "Enter payments"
pos_hint: {"y": .2, "center_x" : .5}
size_hint: 1, 1
on_release:
root.current = "enter"
MDRaisedButton:
font_size: "32sp"
text: "Check payments"
pos_hint: {"y": .6, "center_x" : .5}
size_hint: 1, 1
on_release:
root.current = "view"
MDScreen:
#----------------------------------------------------------------------------------------------------------------------
name: "enter"
MDFloatLayout:
MDLabel:
text: "Date"
pos_hint: {"x" : 0, "center_y" : .9}
size_hint: None, None
MDIconButton:
icon: "calendar"
pos_hint: {"center_x": .3, "center_y": .9}
on_release: app.show_date_picker()
MDTextField:
id: date
helper_text: "Enter a valid date yyyy/mm/dd "
date_format: 'yyyy/mm/dd'
validator: "date"
hint_text: "Enter date"
pos_hint: {"center_x" : 0.9, "center_y" : .9}
text: ""
MDLabel:
text: "Case id"
pos_hint: {"x": 0, "center_y": .8}
MDTextField:
id: case_id
hint_text: "Enter case id"
pos_hint: {"center_x": .9, "center_y": .8}
MDLabel:
text: "Payment type"
size_hint: 1, None
pos_hint: {"x": 0, "center_y": .7}
MDTextField:
id: payment_type
hint_text: "Payment type"
pos_hint: {"center_x": .9, "center_y": .7}
MDLabel:
text: "Amount"
pos_hint: {"x" : 0, "center_y": .6}
MDSwitch:
pos_hint: {"center_y" : 0.6, "center_x" : 0.3}
on_active: app.on_checkbox_active(*args)
MDTextField:
id: amount
hint_text: "Enter amount"
pos_hint: {"center_x": .9, "center_y": .6}
MDRaisedButton:
text: "Submit"
pos_hint: {"y": .2, "center_x" : .5}
size_hint: 1, 0.3
on_release: app.add_payment()
MDRaisedButton:
text: "Go back"
pos_hint: {"y": 0, "center_x" : .5}
size_hint: 1, 0.25
on_release:
root.current = "main"
#---------------------------------------------------------------------------------------------------------------
MDScreen:
name: "view"
MDFloatLayout:
MDScrollView:
do_scroll_x: False
padding: 10, 10
scroll_type: ['content', 'bars' ]
bar_width: 20
MDLabel:
id: print_date
text: "Nothing to display"
pos_hint: {"center_x" : 0, "y" : .6}
size_hint: .4, None
text_size: self.width, None
height: self.texture_size[1]
halign: "left"
MDTextField:
id: show_date
mode: "rectangle"
pos_hint: {"x" : .5, "y" : .7}
MDIconButton:
icon: "calendar"
pos_hint: {"center_x": .7, "center_y": .9}
size_hint: None, None
on_release: app.show_date_picker_1()
MDRaisedButton:
text: "Check payments"
pos_hint: {"y" : .2}
size_hint: 1, 0.1
on_release:
app.view_payment()
MDRaisedButton:
text: "Total"
pos_hint: {"y" : .1}
size_hint: 1, 0.1
on_release:
app.total()
MDRaisedButton:
text: "Go back"
pos_hint: {"y" : 0}
size_hint: 1, 0.1
on_release:
root.current = "main"
'''
payments = {}
file = "work.json"
class Test(MDApp):
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "Orange"
return Builder.load_string(KV)
def on_save(self, instance, value, date_range):
'''sets the date in Add payment'''
self.root.ids.date.text = str(value.strftime("%Y/%m/%d"))
print(value)
def on_save_1(self, instance, value, date_range):
'''sets the date in view payment'''
self.root.ids.show_date.text = str(value.strftime("%Y/%m/%d"))
def on_cancel(self, instance, value):
'''Events called when the "CANCEL" dialog box button is clicked.'''
def show_date_picker(self):
'''calls the date picker in add payment window'''
date_dialog = MDDatePicker()
date_dialog.bind(on_save=self.on_save, on_cancel=self.on_cancel)
date_dialog.open()
def show_date_picker_1(self):
'''calls the date picker in view window'''
date_dialog = MDDatePicker()
date_dialog.bind(on_save=self.on_save_1, on_cancel=self.on_cancel)
date_dialog.open()
def on_checkbox_active(self, checkbox, value):
if value:
payment_amount = float(self.root.ids.amount.text) * 1.5
else:
payment_amount = float(self.root.ids.amount.text) / 1.5
self.root.ids.amount.text = str(payment_amount)
##########################################
def add_payment(self):
"""creates dictionary entry and saves it."""
# sets date as user input in date field
date = self.root.ids.date.text
# sets case_id as user input in case_id field
case_id = self.root.ids.case_id.text
# sets amount as user input in amount field
amount = self.root.ids.amount.text
# sets payment_type as user input in payment_type field
payment_type = self.root.ids.payment_type.text
try:
self._extracted_from_add_payment_11(date, case_id, payment_type, amount)
except ValueError as Error:
self._extracted_from_add_payment_11(date, case_id, payment_type, amount)
# TODO Rename this here and in `add_payment`
def _extracted_from_add_payment_11(self, date, case_id, payment_type, amount):
# checks if json file exists if it doesnt creates it if it does it dumps payments in it
try:
with open(file, 'x') as f:
payments = {}
j = json.dump(payments, f)
except FileExistsError:
with open(file, 'r') as f:
payments = json.load(f)
#creates entry in dictionary if date exists appends it if not creates an entry
if date not in payments:
payments[date] = []
payments[date].append(
{
"Case id" : case_id,
"Payment type" : payment_type,
"Amount" : amount
})
#resets the input fields to empty
self.root.ids.case_id.text = ''
self.root.ids.amount.text = ''
self.root.ids.payment_type.text = ''
#dumps data in json
with open(file, 'w') as f:
j = json.dump(payments, f)
def view_payment(self):
"""finds entry in dictionary and puts all matches to a label"""
#sets date as input from date field
date = self.root.ids.show_date.text
#sets print_date label to empty
self.root.ids.print_date.text = ""
#loads data from json
with open(file, 'r') as f:
payments = json.load(f)
#if it finds entry puts it in a label if not sets label text as date does not exist
try:
for b, i in enumerate(payments.get(date, None), start=0):
self.root.ids.print_date.text += f"{b+1}. Case id:{payments[date][b].get('Case id')}, Payment type:{payments[date][b].get('Payment type')}, Amount:{payments[date][b].get('Amount')}.\n"
except (KeyError, TypeError) as error: # handle file not found on first launch
date = self.root.ids.show_date.text
self.root.ids.print_date.text = "No payments or wrong date"
def total(self):
"""finds entrys in specific date and sums them up"""
#sets date as input from show_date field
date = self.root.ids.show_date.text
#resets print_date label to empty
self.root.ids.print_date.text = ''
total1 = 0
# finds required dates amount entrys and sums them
try:
with open(file, 'r') as f:
payments = json.load(f)
for i in payments[date]:
# if there is no value it skips it and look for other entry
if amount := i.get('Amount'):
total1 += float(amount)
self.root.ids.print_date.text += str(total1)
except (KeyError,ValueError) as Error:
self.root.ids.print_date.text = 'Date does not exist'
Test().run()
the only thing i noticed it says that MDScrollView import is not being accessed.
any help would be greatly appreciated

Related

Adjust plotly-Dash table column width

I want to adjust the width of columns in Dash table (created from Pandas Dataframe). There are 3 columns in table :
Path
Scenario
Step
I want to set the column width of first column (Path) to 10% and the second column (Scenario) to 40% and the last column (Step) to 50%.
I am running below code, but the column width changes are not working as expected. "Path" column is taking more than 50% of width and "Steps" column around 20%.
Dataframe name is dfSteps
columns=[{"name": i, "id": i} for i in dfSteps.columns],
data=dfSteps.to_dict('records'),
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold'
},
style_table={
'maxWidth': '2000px',
'overflowX': 'scroll',
'border': 'thin lightgrey solid'
},
style_cell={
'font_family': 'cursive',
'font_size': '16px',
'border': '1px solid grey',
'minWidth': '1px', 'width': 'fixed', 'maxWidth': '1000px',
'textAlign': 'left', 'whiteSpace': 'normal'
},
style_cell_conditional=[
{'if': {'column_id': 'Path'},
'width': '10%'},
{'if': {'column_id': 'Scenario'},
'width': '40%'},
{'if': {'column_id': 'Path'},
'width': '50%'},
],
),
Just redefine your table as they suggest in the documentation
https://plotly.com/python/table/
fig = go.Figure(data=[go.Table(
columnorder = [1,2],
columnwidth = [80,400],
header = dict(
values = [['<b>EXPENSES</b><br>as of July 2017'],
['<b>DESCRIPTION</b>']],
line_color='darkslategray',
fill_color='royalblue',
align=['left','center'],
font=dict(color='white', size=12),
height=40
),
cells=dict(
values=values,
line_color='darkslategray',
fill=dict(color=['paleturquoise', 'white']),
align=['left', 'center'],
font_size=12,
height=30)
)
])
fig.show()

How can i generate xls report in odoo

I want to generate my own excel report using Excel report engine in odoo 8. someone please send me a simple excel report sample or any helping URL. I'll be very thankful to you ....
Here is a simple piece of code. There is really a lot of examples on the internet with good explanations. I suggest you go through the code in detail to see how it works (by the way I have copied the code also from somewhere - I cannot remember where. Also have a look at the examples here:https://github.com/OCA/reporting-engine/tree/8.0
The version 8 branch also have a number of examples.
You can add columns by editing the "my_change" variable.
from openerp.osv import orm
from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import _
class account_move_line(orm.Model):
_inherit = 'abc.salesforecast'
# override list in custom module to add/drop columns or change order
def _report_xls_fields(self, cr, uid, context=None):
return [
'contract', 'proposal', 'description',
#'amount_currency', 'currency_name',
]
# Change/Add Template entries
def _report_xls_template(self, cr, uid, context=None):
"""
Template updates, e.g.
my_change = {
'move':{
'header': [1, 20, 'text', _('My Move Title')],
'lines': [1, 0, 'text', _render("line.move_id.name or ''")],
'totals': [1, 0, 'text', None]},
}
return my_change
"""
return {}
The code for the parser is as follows.
import xlwt
import time
from datetime import datetime
from openerp.osv import orm
from openerp.report import report_sxw
from openerp.addons.report_xls.report_xls import report_xls
from openerp.addons.report_xls.utils import rowcol_to_cell, _render
from openerp.tools.translate import translate, _
from openerp import pooler
import logging
_logger = logging.getLogger(__name__)
class contract_sales_forecast_xls_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(contract_sales_forecast_xls_parser, self).__init__(cr, uid, name, context=context)
forecast_obj = self.pool.get('msr.salesforecast')
self.context = context
wanted_list = forecast_obj._report_xls_fields(cr, uid, context)
template_changes = forecast_obj._report_xls_template(cr, uid, context)
self.localcontext.update({
'datetime': datetime,
'wanted_list': wanted_list,
'template_changes': template_changes,
'_': self._,
})
def _(self, src):
lang = self.context.get('lang', 'en_US')
return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
class contract_sales_forecast_xls(report_xls):
def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
super(contract_sales_forecast_xls, self).__init__(name, table, rml, parser, header, store)
# Cell Styles
_xs = self.xls_styles
# header
rh_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rh_cell_style = xlwt.easyxf(rh_cell_format)
self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
self.rh_cell_style_right = xlwt.easyxf(rh_cell_format + _xs['right'])
# lines
aml_cell_format = _xs['borders_all']
self.aml_cell_style = xlwt.easyxf(aml_cell_format)
self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str = report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# totals
rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rt_cell_style = xlwt.easyxf(rt_cell_format)
self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])
self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# XLS Template
self.col_specs_template = {
'contract':{
'header': [1, 20, 'text', _render("_('Contract Number')")],
'lines': [1, 0, 'text', _render("msr_contract_id or ''")],
'totals': [1, 0, 'text', None]},
'proposal':{
'header': [1, 42, 'text', _render("_('Proposal Number')")],
'lines': [1, 0, 'text', _render("msr_proposal or ''")],
'totals': [1, 0, 'text', None]},
'description':{
'header': [1, 42, 'text', _render("_('Description')")],
'lines': [1, 0, 'text', _render("name or ''")],
'totals': [1, 0, 'text', None]},
}
def generate_xls_report(self, _p, _xs, data, objects, wb):
wanted_list = _p.wanted_list
self.col_specs_template.update(_p.template_changes)
_ = _p._
#report_name = objects[0]._description or objects[0]._name
report_name = _("Sales forecast from current contracts")
ws = wb.add_sheet(report_name[:31])
ws.panes_frozen = True
ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1
row_pos = 0
# set print header/footer
ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard']
# Title
cell_style = xlwt.easyxf(_xs['xls_title'])
c_specs = [
('report_name', 1, 0, 'text', report_name),
]
row_data = self.xls_row_template(c_specs, ['report_name'])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=cell_style)
row_pos += 1
# Column headers
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'header', render_space={'_': _p._}), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.rh_cell_style, set_column_size=True)
ws.set_horz_split_pos(row_pos)
# account move lines
for line in objects:
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'lines'), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.xls_write_row(ws, row_pos, row_data, row_style=self.aml_cell_style)
# Totals
contract_sales_forecast_xls('report.contract.sales.forecast.xls',
'abc.salesforecast',
parser="contract_sales_forecast_xls_parser")
The xml file will look as follows to setup the necessary actions etc.
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="action_contract_sales_forecast_xls" model="ir.actions.report.xml">
<field name="name">Export Selected Lines To Excel</field>
<field name="model">abc.salesforecast</field>
<field name="type">ir.actions.report.xml</field>
<field name="report_name">contract.sales.forecast.xls</field>
<field name="report_type">xls</field>
<field name="auto" eval="False"/>
</record>
<record model="ir.values" id="contract_sales_forecast_xls_values">
<field name="name">Export Selected Lines</field>
<field name="key2">client_action_multi</field>
<field name="value" eval="'ir.actions.report.xml,' +str(ref('action_contract_sales_forecast_xls'))" />
<field name="model">abc.salesforecast</field>
</record>
</data>
</openerp>
A second example. First the xml to create a button. This is only an extract.
<form string = "Contract Search Wizard" version="7.0">
<sheet>
<group>
<button icon="gtk-ok" name="print_contract_list" string="Print Contract List" type="object" />
<button icon="gtk-ok" name="export_contract_product" string="Export Contract vs. Product Pivot Table" type="object" />
<button icon="gtk-ok" name="export_contract_country" string="Export Contract vs. Country Pivot Table" type="object" />
<button icon="gtk-cancel" special="cancel" string="Cancel" />
</group>
</sheet>
</form>
The below code is a wizard with several buttons. I removed some code to save space. The report is activated from a button:
class abc_contract_search_wizard(osv.osv):
def _prd_report_xls_fields(self, cr, uid, context=None):
SQLstring = "SELECT abc_product_list.name FROM abc_product_list;"
cr.execute(SQLstring)
tbl_products = cr.dictfetchall()
header_list=['contract_id','contract_name','exclusive']
for t in tbl_products:
header_list.append(t['name'])
return header_list
# Change/Add Template entries
def _prd_report_xls_template(self, cr, uid, context=None):
"""
Template updates, e.g.
my_change = {
'move':{
'header': [1, 20, 'text', _('My Move Title')],
'lines': [1, 0, 'text', _render("line.move_id.name or ''")],
'totals': [1, 0, 'text', None]},
}
return my_change
"""
SQLstring = "SELECT abc_product_list.name FROM abc_product_list;"
cr.execute(SQLstring)
tbl_products = cr.dictfetchall()
abc_tmpl = {
'contract_id':
{
'header':[1,20, 'text', _render("_('Contract ID')")],
'lines':[1,0, 'text', _render("line.abc_contract_id.name or ''")],
'totals':[1, 0, 'text', None],
},
'contract_name' :
{
'header':[1,40, 'text', _render("_('Contract Name')")],
'lines':[1,0, 'text', _render("line.abc_contract_name or ''")],
'totals':[1, 0, 'text', None],
},
'exclusive':
{
'header':[1,10, 'text', _render("_('Exlusive')")],
'lines':[1,0, 'text', _render("line.abc_country.name or ''")],
'totals':[1, 0, 'text', None],
},
}
for t in tbl_products:
abc_tmpl[t['name']]={
'header':[1,3, 'text', _render("_('" + t['name']+"')")],
'lines':[1,0, 'text', _render("line.abc_contract_id.name or ''")],
'totals':[1, 0, 'text', None],
}
return abc_tmpl
_name='abc.contract.search.wizard'
_columns={
'country':fields.many2one('abc.countries','Country'),
'product':fields.many2one('abc.product.list','Product'),
'start_date':fields.date('Start Date'),
'end_date':fields.date('End Date'),
'partner':fields.many2one('res.partner','Partner'),
'product_type':fields.many2one('abc.product.type','Product Type'),
'regions':fields.many2one('abc.regions', 'Regions'),
'exclusive':fields.boolean('Exclusive'),
'contract_type':fields.many2one('abc.contract.types','Contract Type'),
}
def find_product(self, tbl_contractproducts, product_id):
is_there=False
for t in tbl_contractproducts:
if product_id==t['product_id']:
is_there=True
return is_there
def get_contract_products(self, cr, uid, ids, context, contract_id, tbl_products):
products={}
SQLstring = "SELECT abc_contract_product_list.product_id, abc_contract_product_list.contract_id FROM abc_contract_product_list " \
+ "WHERE (((abc_contract_product_list.contract_id) =" + str(contract_id) + "));"
cr.execute(SQLstring)
tbl_contractproducts = cr.dictfetchall()
for t in tbl_products:
if self.find_product(tbl_contractproducts,t['product_id']):
products[t['product_name']]='X'
else:
products[t['product_name']]=''
return products
def export_contract_product(self, cr, uid, ids, context=None):
rst = self.browse(cr, uid, ids)[0]
country_id = rst.country.id
product_id = rst.product.id
start_date = rst.start_date
end_date = rst.end_date
product_type_id = rst.product_type.id
partner_id = rst.partner.id
region_id = rst.regions.id
exclusive = rst.exclusive
contract_type_id = rst.contract_type.id
SQLwhere = ""
SQLstring = "SELECT DISTINCT abc_official_documents.id, abc_official_documents.contract_id, abc_official_documents.name AS doc_name, abc_official_documents.contract_exclusive_agreemnet " \
+ "FROM res_partner INNER JOIN (((abc_contract_countries INNER JOIN (((abc_contract_product_list INNER JOIN (abc_product_type INNER JOIN abc_product_list " \
+ "ON abc_product_type.id = abc_product_list.product_type) ON abc_contract_product_list.product_id = abc_product_list.id) INNER JOIN abc_official_documents ON "\
+ "abc_contract_product_list.contract_id = abc_official_documents.id) INNER JOIN abc_contract_types ON abc_official_documents.contract_type = abc_contract_types.id) "\
+ "ON abc_contract_countries.contract_id = abc_official_documents.id) INNER JOIN abc_countries ON abc_contract_countries.country_id = abc_countries.id) INNER JOIN "\
+ "abc_regions ON abc_countries.country_region = abc_regions.id) ON res_partner.id = abc_official_documents.contract_partner_id "
if country_id:
SQLwhere = " AND ((abc_contract_countries.country_id) = " + str(country_id) + ")"
if product_id:
SQLwhere = SQLwhere + " AND ((abc_contract_product_list.product_id) = " + str(product_id) + ")"
if start_date:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_start_date) < " + str(start_date) + ")"
if end_date:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_termination_date) < " + str(end_date) + ")"
if partner_id:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_partner_id) = " + str(partner_id) +")"
if region_id:
SQLwhere = SQLwhere + " AND ((abc_countries.country_region) = " + str(region_id) + ")"
if exclusive:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_exclusive_agreemnet) = true )"
if contract_type_id:
SQLwhere = SQLwhere + " AND ((abc_official_documents.contract_type) = " + str(contract_type_id) + ")"
if product_type_id:
SQLwhere = SQLwhere + " AND ((abc_product_list.product_type) = " +str(product_type_id) + ")"
SQLwhere = SQLwhere[-(len(SQLwhere)-5):] #Vat die eerste "AND" weg (5 karakters)
if ((not SQLwhere) | (len(SQLwhere)==0)):
SQLstring = SQLstring + " LIMIT 100;"
else:
SQLstring = SQLstring + "WHERE (" + SQLwhere + ") LIMIT 100;"
cr.execute(SQLstring)
tblContracts = cr.dictfetchall()
SQLstring = "SELECT abc_product_list.id AS product_id, abc_product_list.name as product_name FROM abc_product_list;"
cr.execute(SQLstring)
tbl_products = cr.dictfetchall()
pivot_table = []
datas={'ids':context.get('active_ids', [])}
for t in tblContracts:
if t:
if t['contract_exclusive_agreemnet']:
excl="Yes"
else:
excl = "No"
contract_table = {
'contract_id': t['contract_id'],
'contract_name': t['doc_name'],
'exclusive':excl,
}
product_table=self.get_contract_products(cr, uid, ids, context, t['id'], tbl_products)
full_table = dict(contract_table.items() + product_table.items())
pivot_table.append(full_table)
datas['contract_list']= pivot_table
return {
'type':'ir.actions.report.xml',
'report_name': 'contract_products',
'datas':datas,
}
abc_contract_search_wizard()
Here is the code for the parser:
class contract_products_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(contract_products_parser, self).__init__(cr, uid, name, context=context)
forc_obj = self.pool.get('abc.contract.search.wizard')
self.context = context
wanted_list = forc_obj._prd_report_xls_fields(cr, uid, context)
template_changes = forc_obj._prd_report_xls_template(cr, uid, context)
self.localcontext.update({
'datetime': datetime,
'wanted_list': wanted_list,
'template_changes': template_changes,
'_': self._,
})
def _(self, src):
lang = self.context.get('lang', 'en_US')
return translate(self.cr, _ir_translation_name, 'report', lang, src) or src
class contract_products_xls(report_xls):
def __init__(self, name, table, rml=False, parser=False, header=True, store=False):
super(contract_products_xls, self).__init__(name, table, rml, parser, header, store)
# Cell Styles
_xs = self.xls_styles
# header
rh_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rh_cell_style = xlwt.easyxf(rh_cell_format)
self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
self.rh_cell_style_right = xlwt.easyxf(rh_cell_format + _xs['right'])
# lines
aml_cell_format = _xs['borders_all']
self.aml_cell_style = xlwt.easyxf(aml_cell_format)
self.aml_cell_style_center = xlwt.easyxf(aml_cell_format + _xs['center'])
self.aml_cell_style_date = xlwt.easyxf(aml_cell_format + _xs['left'], num_format_str = report_xls.date_format)
self.aml_cell_style_decimal = xlwt.easyxf(aml_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
# totals
rt_cell_format = _xs['bold'] + _xs['fill'] + _xs['borders_all']
self.rt_cell_style = xlwt.easyxf(rt_cell_format)
self.rt_cell_style_right = xlwt.easyxf(rt_cell_format + _xs['right'])
self.rt_cell_style_decimal = xlwt.easyxf(rt_cell_format + _xs['right'], num_format_str = report_xls.decimal_format)
self.col_specs_template = {
}
def get_c_specs(self, wanted, col_specs, rowtype, data):
"""
returns 'evaluated' col_specs
Input:
- wanted: element from the wanted_list
- col_specs : cf. specs[1:] documented in xls_row_template method
- rowtype : 'header' or 'data'
- render_space : type dict, (caller_space + localcontext)
if not specified
"""
row = col_specs[wanted][rowtype][:]
row[3]=data[wanted]
row.insert(0, wanted)
return row
return True
def new_xls_write_row(self, ws, row_pos, row_data, header, headrot_style, dark_style,
row_style=default_style, set_column_size=False ):
r = ws.row(row_pos)
orig_style=row_style
for col, size, spec in row_data:
data = spec[4]
if header:
if (col!=0) & (col!=1) & (col!=2):
row_style=headrot_style #+ 'align: rotation 90;'
else:
if data=="X":
row_style=dark_style #+ 'pattern: pattern solid, fore_color 0;'
else:
row_style=orig_style
formula = spec[5].get('formula') and \
xlwt.Formula(spec[5]['formula']) or None
style = spec[6] and spec[6] or row_style
if not data:
# if no data, use default values
data = report_xls.xls_types_default[spec[3]]
if size != 1:
if formula:
ws.write_merge(
row_pos, row_pos, col, col + size - 1, data, style)
else:
ws.write_merge(
row_pos, row_pos, col, col + size - 1, data, style)
else:
if formula:
ws.write(row_pos, col, formula, style)
else:
spec[5]['write_cell_func'](r, col, data, style)
if set_column_size:
ws.col(col).width = spec[2] * 256
return row_pos + 1
def generate_xls_report(self, _p, _xs, data, objects, wb):
wanted_list = _p.wanted_list
self.col_specs_template.update(_p.template_changes)
_ = _p._
#report_name = objects[0]._description or objects[0]._name
report_name = _("Export Contract Countries")
ws = wb.add_sheet(report_name[:31])
ws.panes_frozen = True
ws.remove_splits = True
ws.portrait = 0 # Landscape
ws.fit_width_to_pages = 1
row_pos = 0
_xs = self.xls_styles
headrot_style = _xs['bold'] + _xs['fill'] + _xs['borders_all'] + 'align: rotation 90'
xlwt_headrot=xlwt.easyxf(headrot_style)
dark_style = _xs['borders_all']+'pattern: pattern solid, fore_color 0;'
#self.rh_cell_style = xlwt.easyxf(rh_cell_format)
#self.rh_cell_style_center = xlwt.easyxf(rh_cell_format + _xs['center'])
# set print header/footer
ws.header_str = self.xls_headers['standard']
ws.footer_str = self.xls_footers['standard']
# Title
cell_style = xlwt.easyxf(_xs['xls_title'])
c_specs = [
('report_name', 1, 0, 'text', report_name),
]
row_data = self.xls_row_template(c_specs, ['report_name'])
row_pos = self.new_xls_write_row(ws, row_pos, row_data, False, xlwt_headrot , xlwt.easyxf(dark_style), row_style=cell_style )
row_pos += 1
# Column headers
c_specs = map(lambda x: self.render(x, self.col_specs_template, 'header', render_space={'_': _p._}), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.new_xls_write_row(ws, row_pos, row_data, True, xlwt_headrot, xlwt.easyxf(dark_style), row_style=self.rh_cell_style, set_column_size=True)
ws.set_horz_split_pos(row_pos)
# account move lines
for line in data['contract_list']:
c_specs = map(lambda x: self.get_c_specs(x, self.col_specs_template, 'lines', line), wanted_list)
row_data = self.xls_row_template(c_specs, [x[0] for x in c_specs])
row_pos = self.new_xls_write_row(ws, row_pos, row_data, False, xlwt_headrot, xlwt.easyxf(dark_style), row_style=self.aml_cell_style)
contract_products_xls('report.contract_products',
'abc.contract.search.wizard',
parser=contract_products_parser)
To Create an Excel file or a spreadsheet
“import xlwt” package functionality to create sheet in your Py file.We can define the title, header, number, date, and normal style using xlwt.easyxf().
For example title style is given below
new_style = xlwt.easyxf(‘font:height 230; align: wrap No;border: top thick;border: bottom thick;’)
Define how the border should appear.define the workbook. Workbook is actually what we view in our spreadsheet.
To define workbook,
wbk = xlwt.Workbook()
sheet = wbk.add_sheet(‘New_sheet’, cell_overwrite_ok=True)
for write in to the sheet
sheet.write(4, 4, ‘Spellbound Soft Solution’,font_size)
To change the width and height of a cell,
sheet.col(1).width = 500*12
sheet.row(5).height = 70*5
for more goto :
http://spellboundss.com/xls-report-in-odoo/
Thanks
Simply add this report_xlsx module from the app store.
your_module_name --> report--> my_report.py
your_module_name --> report--> my_report.xml
my_report.py
try:
from openerp.addons.report_xlsx.report.report_xlsx import ReportXlsx
except ImportError:
class ReportXlsx(object):
def __init__(self, *args, **kwargs):
pass
class PartnerXlsx(ReportXlsx):
def generate_xlsx_report(self, workbook, data, partners):
for obj in partners:
report_name = obj.name
# One sheet by partner
sheet = workbook.add_worksheet(report_name[:31])
bold = workbook.add_format({'bold': True})
sheet.write(0, 0, obj.name, bold)
PartnerXlsx('report.res.partner.xlsx', 'res.partner')
my_report.xml
`<report
id="partner_xlsx"
model="res.partner"
string="Print to XLSX"
report_type="xlsx"
name="res.partner.xlsx"
file="res.partner.xlsx"
attachment_use="False"
/>`

Single word per line in kivy(GridLayout)

I'm trying to make a app similar a menu. I already did scrollview with gridLayout, but I don't know how to show this separate, for instance, in the left column names, and in the right column age, in this way the app may have variable number of rows (infinity). I hope I have been less confusing as possible, the same for my english. Thanks everybody, I didn't post my code here because I think it isn't necessary. Bye, have a good day.
Ass is important I post my code here, I'm going to try to post. I'm sorry for the mistakes like indent.
.py
class PrimeiroScreen(Screen):
def __init__(self, **kwargs):
self.name = 'home'
super(Screen,self).__init__(**kwargs)
class SegundoScreen(Screen):
text = StringProperty('')
def __init__(self, **kwargs):
self.name = 'dois'
super(Screen,self).__init__(**kwargs)
class RootScreen(ScreenManager):
pass
class scrollmanageApp(App):
def build(self):
return RootScreen()
if __name__ == '__main__':
appVar = scrollmanageApp()
scrollmanageApp().run()
.kv
<RootScreen>:
PrimeiroScreen:
SegundoScreen:
<PrimeiroScreen>:
BoxLayout:
size_hint: (.3,.15)
pos_hint:{'x': .35, 'y': .84}
Label:
text: "Teste de união scrollview com screenmanage"
font_size: '30dp'
GridLayout:
cols: 1
rows: 2
size_hint: (.20,.10)
pos_hint:{'x': .25, 'y': .64}
Button:
text: "Scrollview!"
font_size: '30dp'
text_size: self.size
on_press: root.manager.current = 'dois'
<SegundoScreen>:
text: 'This is just a test ' * 50
ScrollView:
size_hint: 1, 1
pos_hint:{'x': .0, 'y': .0}
size: 100, 100
GridLayout:
cols: 2
#rows:
padding: 10
spacing: 10
size_hint: None, None
width: 500
height: self.minimum_height
Label:
text: root.text
font_size: 50
text_size: self.width, None
size_hint_y: None
height: self.texture_size[1]
Button:
text: "Voltar!"
size_hint: .1, .1
pos_hint:{'x': .9, 'y': .0}
text_size: self.width, None
on_press: root.manager.current = 'home'
I hope I had sucess in this time(post my code).Very thanks!

Pygtk: How do I change the treestore color of a row?

Currently I am developing a tool by using Python with Gtk+ library. And I met an issue here as $subject. Is there any effective way for changing the treestore "1/8"'s background color to red ? Something like the below image:
http://imagebin.ca/v/1pZgJ61cWi9D
I use treestore.set_value to change it, but unfortunately it does not work for me, it can only change the value of the treestore.
No idea about it so I raise a question here.
Can anybody keep an eye of it ? Any suggestions that would be appreciated.
you can use documents of pygtk2.0 about TreeViewColumn.set_cell_data_func method and read important page about CellRenderers and special properties of PyGTK2.0 that also is useful on version 3 of PyGTK :)
Below code can helping you:
#!/usr/bin/env python
try:
import pygtk; pygtk.require('2.0')
except:
pass
import gtk
import pango
COL_FIRST_NAME = 0
COL_LAST_NAME = 1
COL_YEAR_BORN = 2
COL_COLOR = 3
class TreeStoreExample:
def createAndFillModel(self):
treestore = gtk.TreeStore(str, str, str, str)
toplevel1 = treestore.append(None)
toplevel2 = treestore.append(None)
child = treestore.append(toplevel2)
pre_child = treestore.append(child)
tree = [(toplevel1,
COL_FIRST_NAME, "Maria",
COL_LAST_NAME, "Incognito",
COL_YEAR_BORN, 1982,
COL_COLOR, 'black'),
(toplevel2,
COL_FIRST_NAME, "Jane",
COL_LAST_NAME, "Average",
COL_YEAR_BORN, 1962,
COL_COLOR, 'black'),
(child,
COL_FIRST_NAME, "Janinita",
COL_LAST_NAME, "Average",
COL_YEAR_BORN, 1985,
COL_COLOR, 'black'),
(pre_child,
COL_FIRST_NAME, "ABC",
COL_LAST_NAME, "DEF",
COL_COLOR, 'black')
]
year_now = 2015
for item in tree:
iter = item[0]
treestore.set(*item)
if item[5] == COL_COLOR:
treestore.set_value(iter, COL_YEAR_BORN, "age unknown")
for x in range(1, len(treestore.get_path(iter)) + 1):
niter = treestore.get_iter(treestore.get_path(iter)[:x])
treestore.set_value(niter, COL_COLOR, "red")
else:
treestore.set_value(iter, COL_YEAR_BORN, year_now - item[6])
return treestore
def ageCellDataFunc(self, column, renderer, model, iter, data):
year_now = 2015
year_born = model.get_value(iter, COL_YEAR_BORN)
if year_born and year_born <= year_now:
age = year_now - year_born
buf = "%u years old" % age
renderer.set_property("foreground-set", gtk.FALSE)
else:
buf = "age unknown"
#renderer.set_property("foreground", "red")
model.set_value(iter, COL_COLOR, "red")
for x in range(1, len(model.get_path(iter))):
niter = model.get_iter(model.get_path(iter)[:x])
node = model.set_value(niter, COL_COLOR, "red")
print model.get_path(iter)[:x], ":", model.get_value(niter, COL_COLOR)
#renderer.set_property("text", buf)
def createViewAndModel(self):
view = gtk.TreeView(self.createAndFillModel())
self.view = view
# --- Column 1 ---
column = gtk.TreeViewColumn()
column.set_title("First Name")
view.append_column(column)
renderer = gtk.CellRendererText()
column.pack_start(renderer, gtk.TRUE)
column.add_attribute(renderer, "text", COL_FIRST_NAME)
# --- Column 2 ---
column = gtk.TreeViewColumn()
column.set_title("Last Name")
view.append_column(column)
renderer = gtk.CellRendererText()
column.pack_start(renderer, gtk.TRUE)
column.add_attribute(renderer, "text", COL_LAST_NAME)
renderer.set_property("weight", pango.WEIGHT_BOLD)
# --- Column 3 ---
renderer = gtk.CellRendererText()
renderer.set_property('foreground-set',True)
column = gtk.TreeViewColumn("age", renderer, foreground=COL_COLOR)
column.pack_start(renderer, gtk.TRUE)
column.add_attribute(renderer, "text", COL_YEAR_BORN)
column.add_attribute(renderer, "foreground", COL_COLOR)
#column.set_title("age")
view.append_column(column)
#column.set_cell_data_func(renderer, self.ageCellDataFunc, None)
#model = self.createAndFillModel()
#view.set_model(model)
view.get_selection().set_mode(gtk.SELECTION_NONE)
return view
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("delete_event", gtk.mainquit)
view = self.createViewAndModel()
window.add(view)
window.show_all()
def main():
gtk.main()
return 0
if __name__ == "__main__":
TreeStoreExample()
main()
The ageCellDataFunc method not run because if set set_cell_data_func then add_attribute method not running.

Trouble setting up the SimpleVector encoder

Using the commits from breznak for the encoders (I wasn't able to figure out "git checkout ..." with GitHub, so I just carefully copied over the three files - base.py, multi.py, and multi_test.py).
I ran multi_test.py without any problems.
Then I adjusted my model parameters (MODEL_PARAMS), so that the encoders portion of 'sensorParams' looks like this:
'encoders': {
'frequency': {
'fieldname': u'frequency',
'type': 'SimpleVector',
'length': 5,
'minVal': 0,
'maxVal': 210
}
},
I also adjusted the modelInput portion of my code, so it looked like this:
model = ModelFactory.create(model_params.MODEL_PARAMS)
model.enableInference({'predictedField': 'frequency'})
y = [1,2,3,4,5]
modelInput = {"frequency": y}
result = model.run(modelInput)
But I get the final error, regardless if I instantiate 'y' as a list or a numpy.ndarray
File "nta/eng/lib/python2.7/site-packages/nupic/encoders/base.py", line 183, in _getInputValue
return getattr(obj, fieldname)
AttributeError: 'list' object has no attribute 'idx0'
I also tried initializing a SimpleVector encoder inline with my modelInput, directly encoding my array, then passing it through modelInput. That violated the input parameters of my SimpleVector, because I was now double encoding. So I removed the encoders portion of my model parameters dictionary. That caused a spit up, because some part of my model was looking for that portion of the dictionary.
Any suggestions on what I should do next?
Edit: Here're the files I'm using with the OPF.
sendAnArray.py
import numpy
from nupic.frameworks.opf.modelfactory import ModelFactory
import model_params
class sendAnArray():
def __init__(self):
self.model = ModelFactory.create(model_params.MODEL_PARAMS)
self.model.enableInference({'predictedField': 'frequency'})
for i in range(100):
self.run()
def run(self):
y = [1,2,3,4,5]
modelInput = {"frequency": y}
result = self.model.run(modelInput)
anomalyScore = result.inferences['anomalyScore']
print y, anomalyScore
sAA = sendAnArray()
model_params.py
MODEL_PARAMS = {
'model': "CLA",
'version': 1,
'predictAheadTime': None,
'modelParams': {
'inferenceType': 'TemporalAnomaly',
'sensorParams': {
'verbosity' : 0,
'encoders': {
'frequency': {
'fieldname': u'frequency',
'type': 'SimpleVector',
'length': 5,
'minVal': 0,
'maxVal': 210
}
},
'sensorAutoReset' : None,
},
'spEnable': True,
'spParams': {
'spVerbosity' : 0,
'globalInhibition': 1,
'columnCount': 2048,
'inputWidth': 5,
'numActivePerInhArea': 60,
'seed': 1956,
'coincInputPoolPct': 0.5,
'synPermConnected': 0.1,
'synPermActiveInc': 0.1,
'synPermInactiveDec': 0.01,
},
'tpEnable' : True,
'tpParams': {
'verbosity': 0,
'columnCount': 2048,
'cellsPerColumn': 32,
'inputWidth': 2048,
'seed': 1960,
'temporalImp': 'cpp',
'newSynapseCount': 20,
'maxSynapsesPerSegment': 32,
'maxSegmentsPerCell': 128,
'initialPerm': 0.21,
'permanenceInc': 0.1,
'permanenceDec' : 0.1,
'globalDecay': 0.0,
'maxAge': 0,
'minThreshold': 12,
'activationThreshold': 16,
'outputType': 'normal',
'pamLength': 1,
},
'clParams': {
'regionName' : 'CLAClassifierRegion',
'clVerbosity' : 0,
'alpha': 0.0001,
'steps': '5',
},
'anomalyParams': {
u'anomalyCacheRecords': None,
u'autoDetectThreshold': None,
u'autoDetectWaitRecords': 2184
},
'trainSPNetOnlyIfRequested': False,
},
}
The problem seems to be that the SimpleVector class is accepting an array instead of a dict as its input, and then reconstructs that internally as {'list': {'idx0': 1, 'idx1': 2, ...}} (ie as if this dict had been the input). This is fine if it is done consistently, but your error shows that it's broken down somewhere. Have a word with #breznak about this.
Working through the OPF was difficult. I wanted to input an array of indices into the temporal pooler, so I opted to interface directly with the algorithms (I relied heavy on hello_tp.py). I ignored SimpleVector all together, and instead worked through the BitmapArray encoder.
Subutai has a useful email on the nupic-discuss listserve, where he breaks down the three main areas of the NuPIC API: algorithms, networks/regions, & the OPF. That helped me understand my options better.