convert amount into words in NPR format in odoo12? - odoo-12

I want to convert amount in words in NPR format but it always shows in Euro and cents only. How to change it to NPR format while converting into words.
I have tried all the method lang also but euro and cent cannot be replaced. My company currency is NPR but not able to convert it. I have currency_id field relating to res.currency.
I have tried code as below:
#api.depends('amount')
def set_amt_in_words(self):
self.amt_inwords = num2words(self.amount, to = 'currency', lang = 'en_IN')
if self.currency_id == 'NPR':
amt_inwords = str(amt_inwords).replace('Euro', 'rupees')
amt_inwords = str(amt_inwords).replace('Cents', 'paise')
amt_inwords = str(amt_inwords).replace('Cent', 'paise')
self.amt_inwords += '\tonly'
self.amt_inwords = self.amt_inwords.title()
I want to output in Rupees and paise.

Try
self.env.ref('base.NPR').with_context({'lang': 'en_IN'}).amount_to_text(self.amount)
The following method belongs to the model res.currency and is the responsible for translating currency amount to text (<path_to_v12>/odoo/addons/base/models/res_currency.py):
#api.multi
def amount_to_text(self, amount):
self.ensure_one()
def _num2words(number, lang):
try:
return num2words(number, lang=lang).title()
except NotImplementedError:
return num2words(number, lang='en').title()
if num2words is None:
logging.getLogger(__name__).warning("The library 'num2words' is missing, cannot render textual amounts.")
return ""
formatted = "%.{0}f".format(self.decimal_places) % amount
parts = formatted.partition('.')
integer_value = int(parts[0])
fractional_value = int(parts[2] or 0)
lang_code = self.env.context.get('lang') or self.env.user.lang
lang = self.env['res.lang'].search([('code', '=', lang_code)])
amount_words = tools.ustr('{amt_value} {amt_word}').format(
amt_value=_num2words(integer_value, lang=lang.iso_code),
amt_word=self.currency_unit_label,
)
if not self.is_zero(amount - integer_value):
amount_words += ' ' + _('and') + tools.ustr(' {amt_value} {amt_word}').format(
amt_value=_num2words(fractional_value, lang=lang.iso_code),
amt_word=self.currency_subunit_label,
)
return amount_words

Related

Confused function in python

dosen't work when i try to excuted it's stock not work
def calculate_utility_cost(visitors) :
movies = ['Gifted Hands', 'Legends of the Fall', 'Patch Adams',
'The Sixth Sense', 'A Beautiful Mind']
visitors_per_movie = np.repeat(0, len(movies))
pred_bill_per_week = 100000/4
pred_visitors_per_week = 14413
return pred_bill_per_week / pred_visitors_per_week * visitors
utility_total_cost1 = int(input(calculate_utility_cost))
utility_total_cost2 = (visitors_per_day)
utility_total_cost= sum = utility_total_cost1 +
utility_total_cost2
print(utility_total_cost)

apply FilterCriteria "whenDateEqualToAny(dates)" - What is the correct form of the date array (dates) to parse?

I want to add some quick filters using the ui of google sheets. Currently I want to allow the user to click "show last month" to only see the data of the last month. The dates are written in the first column.
Now I prefer to use the filter of google sheets before just printing the values into the sheet, to allow the user to further modify that filter.
Thus I am trying to build filterCriteria using SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates) and I am parsing an array of valid dates. In the documentation it says I have to put a "Date[]" - doesn't that mean an array of dates?
Below the error message and my code:
Error message (linked to the line "var filterCriteria..."):
"Exception: The boolean condition can not have multiple values for equality checks for non-data source objects"
My code:
function showLastMonth() {
var ss = SpreadsheetApp.getActive()
var sheet = ss.getSheetByName('evaluation')
var now = new Date()
var thisYear = now.getFullYear()
var thisMonth = now.getMonth()
if(thisMonth == 0){var startMonth = 11; var startYear = thisYear - 1}
else{var startMonth = thisMonth - 1; var startYear = thisYear}
var startDate = new Date(startYear, startMonth, 1)
var endDate = new Date(thisYear, thisMonth, 0)
var dates = getDateArray(startDate, endDate)
var filter = sheet.getFilter()
if(filter == null ){
var range = sheet.getDataRange()
var filter = range.createFilter()
}
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates)
filter.setColumnFilterCriteria(1, filterCriteria)
}
getDateArray = function(startDate, endDate){
var startYear = startDate.getFullYear()
var startMonth = startDate.getMonth()
var dateArray = []; dateArray.push(startDate)
var date = startDate; var day = date.getDay()-1
while(date<endDate){
day++
date = new Date(startYear, startMonth, day)
if(date<=endDate){dateArray.push(date)}
}
return dateArray;
}
I believe your goal as follows.
You want to hide the rows of the values except for dates using the basic filter.
You want to achieve this using Google Apps Script.
Issue and workaround:
In the current stage, it seems that array of whenDateEqualToAny(array) is required to be the length of 1. I think that this is the reason of your issue. So for example, when var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny([dates[0]]) is used, no error occurs. This situation is the same with the setBasicFilter request of Sheets API. Unfortunately, it seems that this is the current specification. But, the official document says The acceptable values. which uses the plural form. Ref So I also think that this is not correct for the actual situation as mentioned by TheMaster's comment.
In order to achieve your goal, in this case, I would like to propose the following 2 patterns.
Pattern 1:
In this pattern, using setHiddenValues(), the values except for the values of dates in your script are set as the hidden values.
Modified script:
When your script is modified, please modify as follows.
From:
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates)
To:
var obj = dates.reduce((o, e) => Object.assign(o, {[`${e.getFullYear()}\/${e.getMonth() + 1}\/${e.getDate()}`]: true}), {});
var range = sheet.getRange("A1:A");
var dispValues = range.getDisplayValues();
var hiddenValues = range.getValues().reduce((ar, [a], i) => {
if (a instanceof Date && !obj[`${a.getFullYear()}\/${a.getMonth() + 1}\/${a.getDate()}`]) {
ar.push(dispValues[i][0]);
}
return ar;
}, []);
var filterCriteria = SpreadsheetApp.newFilterCriteria().setHiddenValues(hiddenValues).build();
Pattern 2:
In this pattern, using whenNumberBetween(), the values of dates in your script are shown. In this case, it is required to convert the date object to the serial number.
Modified script:
When your script is modified, please modify as follows.
From:
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenDateEqualToAny(dates)
To:
var filterCriteria = SpreadsheetApp.newFilterCriteria().whenNumberBetween(
(dates[0].getTime() / 1000 / 86400) + 25569,
(dates.pop().getTime() / 1000 / 86400) + 25569
).build();
The conversion from the date object to the serial number was referred from this thread.
References:
setHiddenValues(values)
whenNumberBetween(start, end)

Kivy getting values from Popup Window and use it at a Screen

Hi i am new to kivy and just started programming. So what i want to do is,once a user key in a valid date/time in the popup window, popup will close and will goes to a screen and create buttons. May i know how to pass the values get from getDay() which is dayoutput,timeoutput from popupwindow and transfer use it in another other class? and be able to use in the VariesTimeScreen?
Thank your for taking your time to help :)
class SetDateTime(Popup):
def getDay(self):
set_day = (self.ids.dayofmonth).text
set_month = (self.ids.month).text
set_year = (self.ids.year).text
set_hour = (self.ids.houroftime).text
set_minutes = (self.ids.minuteoftime).text
wrongtime = self.ids.wronginput_time
#Calculate Date and Time only when user input a valid number
if set_day.isdigit() and set_month.isdigit() and
set_year.isdigit()andset_hour.isdigit()
and set_minutes.isdigit():
try:
set_date = datetime.date(int(set_year),
int(set_month),int(set_day))
set_time = datetime.time(int(set_hour), int(set_minutes))
if not (set_date >= counttime.todaydate()):
wrongtime.text = "[color=#FF0000]Date is out of
range[/color]"
if not (set_time >= counttime.todaytime()):
wrongtime.text = "[color=#FF0000]Time is out of
range[/color]"
dayoutput = counttime.calculatedate(set_date)
timeoutput = set_hour + set_minutes
self.dismiss()
return dayoutput,timeoutput
except ValueError:
wrongtime.text = "[color=#FF0000]Please enter a valid
datetime.[/color]"
else:
wrongtime.text = "[color=#FF0000]Please enter a valid
date[/color]"
class VariesTimeScreen(Screen):
def __init__(self, **kwargs):
super(VariesTimeScreen, self).__init__(**kwargs)
a = '_icons_/mcdonald.png'
b = '_icons_/kfc.png'
c = '_icons_/subway.png'
Outlet_Store = [a,b,c]
layout = GridLayout(rows=1, spacing=100, size_hint_y=None,
pos_hint ={"top":.6,"x":0.2})
layout.bind(minimum_height=layout.setter('height'))
#Before the for loop there will be an if statement which is
the Day and Time i get from getDay() values. This part i'm
unsure how to retrieve the values from the SetDateTime Class
for image in Outlet_Store:
food_image = ImageButton(size_hint=(None, None),size=
(100,100),source=image)
layout.add_widget(food_image)
self.add_widget(layout)
One problem with your design is that the VariesTimeScreen is created very early in the App run, like when the GUI is created. So, the day and time from the SetDateTime Popup is not yet available. One way to handle this is to add an on_enter() method to the VariesTimeScreen to make any adjustments to the Screen at that time. To do that, I added Properties to the VariesTimeScreen:
class VariesTimeScreen(Screen):
day = StringProperty('None')
time = NumericProperty(0)
And add the on_enter() method to the VariesTimeScreen class:
def on_enter(self, *args):
print('day:', self.day, ', time:', self.time)
# make changes to the Screen
And then change the SetDateTime class slightly:
class SetDateTime(Popup):
def getDay(self):
set_day = (self.ids.dayofmonth).text
set_month = (self.ids.month).text
set_year = (self.ids.year).text
set_hour = (self.ids.houroftime).text
set_minutes = (self.ids.minuteoftime).text
wrongtime = self.ids.wronginput_time
# Calculate Date and Time only when user input a valid number
if set_day.isdigit() and set_month.isdigit() and set_year.isdigit() and set_hour.isdigit() and set_minutes.isdigit():
try:
set_date = datetime.date(int(set_year),
int(set_month), int(set_day))
set_time = datetime.time(int(set_hour), int(set_minutes))
if not (set_date >= counttime.todaydate()):
wrongtime.text = "[color=#FF0000]Date is out of range[ / color]"
if not (set_time >= counttime.todaytime()):
wrongtime.text = "[color=#FF0000]Time is out of range[ / color]"
dayoutput = counttime.calculatedate(set_date)
timeoutput = set_hour + set_minutes
# get the VariesTimeScreen
varies_time = App.get_running_app().root.ids.screen_manager.get_screen('variestime_screen')
# set the day and time for the VariesTimeScreen
varies_time.day = dayoutput
varies_time.time = timeoutput
# switch to the VariesTimeScreen
App.get_running_app().change_screen('variestime_screen')
# dismiss Popup
self.dismiss()
except ValueError:
wrongtime.text = "[color=#FF0000]Please enter a valid datetime.[ / color]"
else:
wrongtime.text = "[color=#FF0000]Please enter a valid date[ / color]"
The only changes are to set the day and time in the VariesTimeScreen, and to actually switch to the VariesTimeScreen. The switch to the VariesTimeScreen doesn't have to happen there, once the day and time are set, the on_enter() method will get called whenever it becomes the current Screen.

Question mark in reserved keyword

I am trying to write a parser for LOLCODE GOD, WHAT I AM DOING???
(just in case to explain those strange words=) )
So, I need to have tokens for O RLY? and YA RLY.
I am trying to do like this:
reserved = { ...,
'O': 'IF_O',
'RLY?': 'IF_RLY',
'YA': 'THEN_YA',
'RLY': 'THEN_RLY', ...}
tokens = reserved.values() + (...)
t_IF_O = r'O'
t_IF_RLY = r'RLY\?'
t_THEN_YA = r'YA'
t_THEN_RLY = r'RLY'
And when I write O RLY? it is parsed like IF_O THEN_RLY and an undefined symbol ?.
If I replace RLY? with, for example, RLYY, replacing in dictionary RLY?: 'IF_RLY' -> 'RLYY': 'IF_RLY' and t_IF_RLY = r'RLYY', then it works for O RLYY.
So I think this is a problem with question marks in reserved words and do not know a workaround for this.
Sorry, but I can't reproduce this problem. Here is a working sample (ply=3.10, python=3.6):
import ply.lex as lex
tokens = (
'IF_O',
'IF_RLY',
'THEN_YA',
'THEN_RLY'
)
t_IF_O = r'O'
t_IF_RLY = r'RLY\?'
t_THEN_YA = r'YA'
t_THEN_RLY = r'RLY'
t_ignore = ' \t'
def t_error(t):
print(t)
lexer = lex.lex()
lexer.input('O RLY?')
while True:
token = lexer.token()
if token is None:
break
print(token)
And it prints:
LexToken(IF_O,'O',1,0)
LexToken(IF_RLY,'RLY?',1,2)

Getting errors with Parameterized Update Sub

No idea why this isn't working.
I have a simple form with some text boxes and drop down lists. It displays the profile of an employee. Users should be able to manually edit the fields and click Save. When they click save I keep getting errors.
Q1: How can I handle inserting Null values for SmallDateTime data types?
Q2: What am I doing wrong with the TinyInt (SqlServer 2005) on the JobGrade?
Option Explicit On
Imports System
Imports System.Data
Imports System.Data.SqlClient
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdUpdate As SqlCommand = sqlJobsDB.CreateCommand()
Try
sqlJobsDB.Open()
sqlCmdUpdate.CommandText = _
"UPDATE tblEmployee " + _
"SET Firstname = #Firstname, LastName = #LastName, HiredLastName = #HiredLastName, " + _
"DateHired = #DateHired, Role = #Role, CADate = #CADate, CAType = #CAType, " + _
"JobDate = #JobDate, JobGrade = #JobGrade " + _
"WHERE EUID = '" & Session("sProfileEUID") & "';"
sqlCmdUpdate.Parameters.Add("#FirstName", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#LastName", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#HiredLastName", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#DateHired", SqlDbType.SmallDateTime)
sqlCmdUpdate.Parameters.Add("#Role", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#CADate", SqlDbType.SmallDateTime)
sqlCmdUpdate.Parameters.Add("#CAType", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#JobDate", SqlDbType.SmallDateTime)
sqlCmdUpdate.Parameters.Add("#JobGrade", SqlDbType.TinyInt)
sqlCmdUpdate.Parameters("#FirstName").Value = txtFirstName.Text
sqlCmdUpdate.Parameters("#LastName").Value = txtLastName.Text
sqlCmdUpdate.Parameters("#HiredLastName").Value = txtHiredLastName.Text
sqlCmdUpdate.Parameters("#DateHired").Value = txtDateHired.Text
sqlCmdUpdate.Parameters("#Role").Value = ddlRole.SelectedValue.ToString
If txtCADate.Text = "" Then
sqlCmdUpdate.Parameters("#CADate").Value = 0
Else
sqlCmdUpdate.Parameters("#CADate").Value = txtCADate.Text
End If
sqlCmdUpdate.Parameters("#CAType").Value = ddlCAType.SelectedValue
If txtJobDate.Text = "" Then
sqlCmdUpdate.Parameters("#JobDate").Value = 0
Else
sqlCmdUpdate.Parameters("#JobDate").Value = txtJobDate.Text
End If
sqlCmdUpdate.Parameters("#JobGrade").Value = CByte(txtJobGrade.Text)
sqlCmdUpdate.ExecuteNonQuery()
Catch ex As Exception
'Debugging
lblErrMsg.Text = ex.ToString
lblErrMsg.Visible = True
Finally
sqlJobsDB.Close()
End Try
End Sub</code>
I open the form and fill it out correctly.
I'll enter something like "4" (no quotes) for JobGrade. It still says "conversion from strink ''" like its not even seeing when I input items on the form.
Errors are below:
System.InvalidCastException: Conversion from string "" to type 'Byte' is not valid. ---> System.FormatException: Input string was not in a correct format. at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat) at Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String Value) --- End of inner exception stack trace --- at Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String Value) at Profile.btnSave_Click(Object sender, EventArgs e) in
Update
The DBNull.Value issue is resolved.
The JobGrade, and Role are still issues. When throwing up some breakpoints on it doens't fetch the contents of the textbox or the dropdown list.
** Updated Code **
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Session("sProfileEUID") = Nothing
Response.Redirect("~/Management/EditUsers.aspx")
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdUpdate As SqlCommand = sqlJobsDB.CreateCommand()
Try
sqlJobsDB.Open()
sqlCmdUpdate.CommandText = _
"UPDATE tblEmployee " + _
"SET FirstName = #FirstName, LastName = #LastName, HiredLastName = #HiredLastName, " + _
"DateHired = #DateHired, Role = #Role, CADate = #CADate, CAType = #CAType, " + _
"JobDate = #JobDate, JobGrade = #JobGrade " + _
"WHERE EUID = '" & Session("sProfileEUID") & "';"
sqlCmdUpdate.Parameters.Add("#FirstName", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#LastName", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#HiredLastName", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#DateHired", SqlDbType.SmallDateTime)
sqlCmdUpdate.Parameters.Add("#Role", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#CADate", SqlDbType.SmallDateTime)
sqlCmdUpdate.Parameters.Add("#CAType", SqlDbType.VarChar)
sqlCmdUpdate.Parameters.Add("#JobDate", SqlDbType.SmallDateTime)
sqlCmdUpdate.Parameters.Add("#JobGrade", SqlDbType.TinyInt)
sqlCmdUpdate.Parameters("#FirstName").Value = txtFirstName.Text
sqlCmdUpdate.Parameters("#LastName").Value = txtLastName.Text
sqlCmdUpdate.Parameters("#HiredLastName").Value = txtHiredLastName.Text
sqlCmdUpdate.Parameters("#DateHired").Value = txtDateHired.Text
sqlCmdUpdate.Parameters("#Role").Value = ddlRole.SelectedValue.ToString
If txtCADate.Text <> "" Then sqlCmdUpdate.Parameters("#CADate").Value = CDate(txtCADate.Text)
If txtCADate.Text = "" Then sqlCmdUpdate.Parameters("#CADate").Value = DBNull.Value
If ddlCAType.Text <> "" Then sqlCmdUpdate.Parameters("#CAType").Value = ddlCAType.SelectedValue
If ddlCAType.Text = "" Then sqlCmdUpdate.Parameters("#CAType").Value = DBNull.Value
If txtJobDate.Text <> "" Then sqlCmdUpdate.Parameters("#JobDate").Value = CDate(txtJobDate.Text)
If txtJobDate.Text = "" Then sqlCmdUpdate.Parameters("#JobDate").Value = DBNull.Value
If txtJobGrade.Text <> "" Then sqlCmdUpdate.Parameters("#JobGrade").Value = CInt(txtJobGrade.Text)
If txtJobGrade.Text = "" Then sqlCmdUpdate.Parameters("#JobGrade").Value = DBNull.Value
sqlCmdUpdate.ExecuteNonQuery()
Catch ex As Exception
lblErrMsg.Text = ex.ToString
lblErrMsg.Visible = True
Finally
sqlJobsDB.Close()
End Try
End Sub
Edit 2:
So I've pretty much given up on this, and instead moved the table into an FormView ItemTemplate, with an EditTemplate also. I modified it as described in the following link. http://www.beansoftware.com/ASP.NET-Tutorials/FormView-Control.aspx
Q1: Make sure the table structure allows nulls and set the parameter value to DBNull.Value.
Q2:
If IsNumeric(txtJobGrade.Text) Then
sqlCmdUpdate.Parameters("#JobGrade").Value = CInt(txtJobGrade.Text)
Else
sqlCmdUpdate.Parameters("#JobGrade").Value = 0 'Or Default Value
End If
You can always make that a drop down list to prevent open ended data input.
It's a little odd to see how you're done the parameters. Typically, I'd expect to see something more along these lines:
With sqlCmdUpdate.Parameters
.clear()
.addWithValue("#parm1", mytextbox1.text)
.addWithValue("#parm2", mytextbox2.text)
End With
For one, .add has been deprecated -- still works, but some issues to be aware of (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx).
Secondly, it's always best to call .clear().
Also -- you might think about a more standard approach to checking for values -- for example:
If txtJobGrade.Text <> "" Then...
Would be better written as
If NOT string.isnullorempty(me.txtJobGrade.text) Then...
Try making a few of those changes, and see what (if any) errors you're still getting.