odoo 11 Expected singleton - singleton

guys why is this thing happening?
I'm getting this error!
raise ValueError("Expected singleton: %s" % self)
ValueError: Expected singleton: product.pricelist.item(8, 9)
this is the related code:
if price is not False:
if rule.compute_price == 'fixed':
price = convert_to_price_uom(rule.fixed_price)
elif rule.compute_price == 'percentage':
price = (price - (price * (rule.percent_price / 100))) or 0.0
**elif rule.compute_price == 'nettech':
if product.aed_is_true:
price_tempo = self.env['res.currency'].search([('name', '=', 'IRR')], limit=1).rate * product.aed_in_irr + product.sud2 + (((self.env['res.currency'].search([('name', '=', 'IRR')], limit=1).rate * product.aed_in_irr + product.sud2) * (product.sud-rule.product_sub) / 100)) or 0.0
price = round(price_tempo,-4)
elif not product.aed_is_true:
price = price**

Search the variable of the product.pricelist.item model and create a for loop on it.
You have this error because there is a variable that contains an object of two records and you are trying to get one value from both. For this reason you should create a loop to get the value from each object.

Related

singleton error when computing age and working time odoo14

i encountered raise when trying to compute age and working time
ValueError("Expected singleton: %s" % self))
ValueError: Expected singleton: restaurant.karyawan(1, 2)
#computing age
#api.depends('tanggal_lahir')
def _hitung_usia(self):
if self.tanggal_lahir is not False:
self.usia = (datetime.today().date() - datetime.strptime(str(self.tanggal_lahir),'%Y-%m-%d').date()) // timedelta(days=365)
#computing working time
#api.depends('mulai_bekerja')
# #api.multi
def _lama_bekerja(self):
if self.mulai_bekerja:
years = relativedelta(date.today(), self.mulai_bekerja).years
months = relativedelta(date.today(), self.mulai_bekerja).months
day = relativedelta(date.today(), self.mulai_bekerja).days
self.lama_bekerja = str(int(years)) + ' Tahun ' + str(int(months)) + ' Bulan ' + str(day) + ' Hari'
how to resolve it ?
Computed methods may get called in tree views if fields are present or still needed to be computed for any dependency.
This means your self will contain N instances of your model instead of one.
Ensure your logic supports multi instances by iterating over them.
#api.multi
def _compute_fun(self):
for record in self:
// record.field = ... logic

How to resolve an error using apply to create a new column in pandas?

I am trying to create a new column with a function who transform positions in strings Degrees minutes and simbol to position in number.
The column is:
Latitud
45º27.19'N
45º17,4'N
46º18,8'N
45º19.54'N
45º32.47'N
....
def formatear (x):
deg, minutes, direction = re.split('[º\']', x)
valor = float(deg) + float(minutes.replace(",","."))/60 * (-1 if direction in ['W', 'S'] else 1)
return valor
Apply function to create a new column
df["LatitudDec"] = df["Latitud"].apply(formatear)
when I apply the function the error is.
ValueError: not enough values to unpack (expected 3, got 2)
The question is not providing enough information to be properly answered, but here a little modification to track down the reason of the error:
def formatear (x):
try:
deg, minutes, direction = re.split('[º\']', x)
valor = float(deg) + float(minutes.replace(",","."))/60 * (-1 if direction in ['W', 'S'] else 1)
except ValueError:
print(f'There has been an error associated with the Latitud {x}')
valor = np.nan
return valor

Pytorch TypeError: eq() received an invalid combination of arguments

num_samples = 10
def predict(x):
sampled_models = [guide(None, None) for _ in range(num_samples)]
yhats = [model(x).data for model in sampled_models]
mean = torch.mean(torch.stack(yhats), 0)
return np.argmax(mean.numpy(), axis=1)
print('Prediction when network is forced to predict')
correct = 0
total = 0
for j, data in enumerate(test_loader):
images, labels = data
predicted = predict(images.view(-1,28*28))
total += labels.size(0)
correct += (predicted == labels).sum().item()
print("accuracy: %d %%" % (100 * correct / total))
Error:
correct += (predicted == labels).sum().item() TypeError:
eq() received an invalid combination of arguments - got (numpy.ndarray), but expected one of:
* (Tensor other)
didn't match because some of the arguments have invalid types: (!numpy.ndarray!)
* (Number other)
didn't match because some of the arguments have invalid types: (!numpy.ndarray!)
*
You are trying to compare predicted and labels. However, your predicted is an np.array while labels is a torch.tensor therefore eq() (the == operator) cannot compare between them.
Replace the np.argmax with torch.argmax:
return torch.argmax(mean, dim=1)
And you should be okay.

function' object is not subscriptable", 'occurred at index 0'

I have a dataframe (maple) that, amongst others, has the columns 'THM', which is filled with float64 and 'Season_index', which is filled with int64. The 'THM' column has some missing values, and I want to fill them using the following function:
def fill_thm(cols):
THM = cols[0]
Season_index = cols[1]
if pd.isnull[THM]:
if Season_index == 1:
return 10
elif Season_index == 2:
return 20
elif Season_index == 3:
return 30
else:
return 40
else:
return THM
Then, to apply the function I used
maple['THM']= maple[['THM','Season_index']].apply(fill_thm,axis=1)
But I am getting the ("'function' object is not subscriptable", 'occurred at index 0') error. Anyone has any idea why? Thanks!
Try this:
def fill_thm(THM, S_i):
if pd.isnull[THM]:
if S_i == 1:
return 10
elif S_i == 2:
return 20
elif S_i == 3:
return 30
else:
return 40
else:
return THM
And apply with:
maple.loc[:,'THM'] = maple[['THM','Season_index']].apply(lambda row: pd.Series((fill_thm(row['THM'], row['Season_index']))), axis=1)
Try this code:
def fill(cols):
Age = cols[0]
Pclass=cols[1]
if pd.isnull['Age']:
if Pclass==1:
return 37
elif Pclass==2:
return 30
else:
return 28
else:
return Age
train[:,'Age'] = train[['Age','Pclass']].apply(fill,axis=1)
first of all, when you use apply on a specific column, you need not to specify axis=1.
second, if you are using pandas 0.22, just upgrade to 0.24. It solves all the issues with apply on Dataframes.

PyQt exclusive OR in sql query

How can I make that if my first search shows results it doesn't do the second part of the query, but stops and displays results? I tried something like this, but it just gives me blank window and it's pretty chaotic:
def test_update(self):
projectModel = QSqlQueryModel()
projectModel.setQuery("""SELECT * FROM pacijent WHERE prezime = '%s' OR (prezime, 3) = metaphone('%s', 3) OR LEVENSHTEIN(LOWER(prezime), '%s') < 3 AND NOT (prezime = '%s' AND (prezime, 3) = metaphone('%s', 3) AND LEVENSHTEIN(LOWER(prezime), '%s') < 3)""" % (str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text()), str(self.lineEdit.text())))
global projectView
projectView = QtGui.QTableView()
projectView.setModel(projectModel)
projectView.show()
So, if it finds the exact value of attribute "prezime" it should display it, but if it doesn't it should call for more advance saerch tactics, such as metaphone and levenshtein.
EDIT:
I got it working like this:
ef search_data(self):
myQSqlQueryModel = QSqlQueryModel()
query = QSqlQueryModel()
global myQTableView
myQTableView = QtGui.QTableView()
querySuccess = False
for queryCommand in [""" SELECT * FROM "%s" WHERE "%s" = '%s' """ % (str(self.search_from_table_lineEdit.text()), str(self.search_where_lineEdit.text()), str(self.search_has_value_lineEdit.text()))]:
myQSqlQueryModel.setQuery(queryCommand)
if myQSqlQueryModel.rowCount() > 0:
myQTableView.setModel(myQSqlQueryModel)
myQTableView.show()
querySuccess = True
break
if not querySuccess:
query.setQuery(""" SELECT * FROM "%s" WHERE METAPHONE("%s", 3) = METAPHONE('%s', 3) OR LEVENSHTEIN("%s", '%s') < 4 """ % (str(self.search_from_table_lineEdit.text()), str(self.search_where_lineEdit.text()), str(self.search_has_value_lineEdit.text()), str(self.search_where_lineEdit.text()), str(self.search_has_value_lineEdit.text())))
global var
var = QtGui.QTableView()
var.setModel(query)
var.show()
After your query success, your can check your data in model if have any row count in this method. And your for loop to get many query;
def testUpdate (self):
myQSqlQueryModel = QtSql.QSqlQueryModel()
myQTableView = QtGui.QTableView()
querySuccess = False
for queryCommand in ["YOUR QUERY 1", "YOUR QUERY 2"]:
myQSqlQueryModel.setQuery(queryCommand)
if myQSqlQueryModel.rowCount() > 0:
myQTableView.setModel(myQSqlQueryModel)
myQTableView.show()
querySuccess = True
break
if not querySuccess:
QtGui.QMessageBox.critical(self, 'Query error', 'Not found')