Populate selection field from loop odoo 9 - odoo

How populate selection field from loop?
Example:
date = fields.Selection([],string='Date')
list = []
for i in diff:
print(i) #return 07:00
self.date = list

You can get selection field key,value pair via following method.
result=self.env[model].fields_get([field_name])
key=False
if result and result.get(field_name) and result.get(field_name).get('selection'):
for dict_value in result.get(field_name).get('selection'):
print dict_value
This may help you.

Related

Problem in creating a new column using for loop

I have to create a new column 'Action' in a dataframe whose values are :
1 if the next day's Close Price is greater than the present day's
-1 if the next day's Close Price is less than the present day's
that is,
Action[i] = 1 if Close Price[i+1]>Close Price[i]
Action[i] = -1 if Close Price[i+1]
I have used the following code:
dt = pd.read_csv("C:\Subhro\ML_Internship\HDFC_Test.csv", sep=',',header=0)
df = pd.DataFrame(dt)
for i in df.index:
if(df['Close Price'][i+1]>df['Close Price'][i]):
df['Action'][i]=1
elif(df['Close Price'][i+1]<df['Close Price'][i]):
df['Action'][i]=-1
print(df)
But I am getting an error :
KeyError: 'Action'
in line:
df['Action'][i]=1
Please help me out
You are getting the key error because you don't have a column called action. Any of the following before the loop will resolve the error:
df['Action'] = 0
or
df['Action'] = np.nan
However, you will get warnings because of the way you are assigning the cell values. (See here)
It is recommended that you instead use e.g.
df.loc[i, "Action"] = 1
Note that with this method, you won't even need to create an empty "Action" column before the loop.

Count items in Infopath field

I created a form in Infopath with a rich text box field. The field is used to keep a list of usernames (first and last). I want to be able to keep a of count each entry and keep a tally. I then want to use that total # of entries to add or subtract from other fields. Is there any way to do that?
Is the rich text box field just a large string? If so you could just use python's built in split function, and either split by ("\r\n"), or (",").
Example:
u = "Bob, Michael, Jean"
x = u.split(",")
X will be a list of usernames. If you are using line breaks for each new username, then replace (",") with ("\r\n").
Now to count the items in a list you just need to iterate on the list you created with a for loop.
Example:
b = 0
u = "Bob, Michael, Jean"
x = u.split(",")
for i in x:
b += 1 // b will be the number of usernames

Conditional If Statement: If value in row starts with letter in string … set another column with some corresponding value

I have the 'Field_Type' column filled with strings and I want to derive the values in the 'Units' column using an if statement.
So Units shows the desired result. Essentially I want to call out what type of activity is occurring.
I tried to do this using my code below but it won't run (please see screen shot below for error). Any help is greatly appreciated!
create_table['Units'] = pd.np.where(create_table['Field_Name'].str.startswith("W"), "MW",
pd.np.where(create_table['Field_Name'].str.contains("R"), "MVar",
pd.np.where(create_table['Field_Name'].str.contains("V"), "Per Unit")))```
ValueError: either both or neither of x and y should be given
You can write a function to define your conditionals, then use apply on the dataframe and pass the funtion
def unit_mapper(row):
if row['Field_Type'].startswith('W'):
return 'MW'
elif 'R' in row['Field_Type']:
return 'MVar'
elif 'V' in row['Field_Type']:
return 'Per Unit'
else:
return 'N/A'
And then
create_table['Units'] = create_table.apply(unit_mapper, axis=1)
In your text you talk about Field_Type but you are using Field_Name in your example. Which one is good ?
You want to do something like:
create_table[create_table['Field_Type'].str.startwith('W'), 'Units'] = 'MW'
create_table[create_table['Field_Type'].str.startwith('R'), 'Units'] = 'MVar'
create_table[create_table['Field_Type'].str.startwith('V'), 'Units'] = 'Per Unit'

Iterate on OrientRecord object

I am trying to increment twice in a loop and print the OrientRecord Objects using Python.
Following is my code -
for items in iteritems:
x = items.oRecordData
print (x['attribute1'])
y=(next(items)).oRecordData #Here is the error
print (y['attribute2'])
Here, iteritems is a list of OrientRecord objects. I have to print attributes of two consecutive objects in one loop.
I am getting the following error -
TypeError: 'OrientRecord' object is not an iterator
Try using a different approach to it:
for i in range(0,len(iteritems),2):
x = iteritems[i].oRecordData
print (x['attribute1'])
y = iteritems[i+1].oRecordData
print (y['attribute2'])
The range() function will start from 0 and iterate by 2 steps.
However, this will work properly only if the total amount (range) of records is an even number, otherwise it'll return:
IndexError: list index out of range
I hope this helps.

Web2py - SQLFORM.smartgrid: how to retrieve field name and value before submission

I use smartgrid with 'in the grid' edition of values. To do this, I use the .represent function to add the row_id to the variable name, so that I can retrieve what to update in request.post_vars, where I can retrieve the list of filed name, ids, with the submitted value.
But I'd like to identify what has been changed by the user in the smartgrid without making an additional I/O in the DB. Is there a global variable where the form fields and initial values are recorded before user change ? Or a function to extract form fields and values before sending it to the view?
db.define_table('cny',Field('f_cny'))
def tst():
tb = db.cny
if len(request.post_vars) >0:
d = {}
for k,v in request.post_vars.iteritems():
(f,sep,r) = k.partition('_r_')
if r:
if not r in d:
d[r] = {}
d[r][f] = v #should only be done if d[r][f] was changed!!!
for r in d:
if len(d[r]):
db(tb.id==r).update(**d[r])
tb.f_cny.represent=lambda v,r:string_widget(tb.f_cny, v, **{'_name':'f_cny_r_%s' % r.id})
f = SQLFORM.smartgrid(tb,
linked_tables=[],
selectable=(lambda ids:redirect(URL(request.controller,request.function,args=request.args))))
return dict(f=f)