Relocate the table index in python 3 - python

Query = search _entry.get()
Sql = *SELECT FROM customers where last_name = %s"
Data = (query,)
Result = my_cursor. Execute (sql, data)
Result = my_cursor. fetchall ()
If not result :
Result = "record not found... "
Query_label = Label(search _customer _window, text =result)
Query_label. Place (x=40,y=130)
else :
For index, x in enumerate (result) :
Num =0
Index +=2
For y in x:
Query_label = Label(search _customer_window, text=y)
Query_label.grid(row=index,column=num)
Num +=1
I set the value of index to 2 but nothing happens. Thanks for your help.
When I run the program, the label (query_lqbel) is shown at top left side of the window (row 0, column =0), how can I change the location of label. Its actually a label on which some data are shown.

Related

PyQt5: Get row number from button-menu action in QTableView index-widget

Basically, I have a QTableView and the last column of each row contains a QMenu where if triggered, the row should be deleted. I tried the code below, but if I click on the menu that is in a row number > 1, the returned rowNum is -1:
Code:
def addrowIntable(self, a, b):
Column1 = QStandardItem("%s" % (a))
Column2 = QStandardItem("%s" % (b))
actionBTN = QPushButton("")
actionMenu = QMenu()
self.RemList = QtWidgets.QAction("Remove row", actionMenu)
actionMenu.addAction(self.RemList)
actionMenu.raise_()
actionBTN.setMenu(actionMenu)
self.rulesWhitelistWidgetModel.appendRow([Column1, Column2])
self.rulesWhiteListFileTBL.setIndexWidget(
self.rulesWhitelistWidgetModel.index(self.rulesWhitelistWidgetModel.rowCount() - 1,
self.rulesWhiteListFileTBL.model().columnCount() - 1), actionBTN)
self.RemList.triggered.connect(lambda: self.deleteRow("Hello"))
def deleteRow(self, str):
rowNum = self.rulesWhiteListFileTBL.rowAt(self.rulesWhiteListFileTBL.viewport().mapFromGlobal(self.sender().parent().pos()).y())
print(self.rulesWhiteListFileTBL.indexAt(self.sender().parent().pos()).row())
print(rowNum)
I just need to know which row number was the sender from inside deleteRow where I could then use model.removeRow() to delete it.
The main reason why your code doesn't work as expected is because you set the menu as the parent of the action. A menu is a popup window, so its position will be in global coordinates, whereas you want the position relative to the table. A simple way to achieve this is to make the button the parent of the action instead.
The following revision of your code should do what you want:
def addrowIntable(self, a, b):
Column1 = QStandardItem("%s" % (a))
Column2 = QStandardItem("%s" % (b))
actionBTN = QPushButton()
actionMenu = QMenu()
actionRem = QtWidgets.QAction("Remove row", actionBTN)
actionMenu.addAction(actionRem)
actionBTN.setMenu(actionMenu)
self.rulesWhitelistWidgetModel.appendRow([Column1, Column2])
self.rulesWhiteListFileTBL.setIndexWidget(Column2.index(), actionBTN)
actionRem.triggered.connect(lambda: self.deleteRow("Hello"))
def deleteRow(self, str):
pos = self.sender().parent().pos()
index = self.rulesWhiteListFileTBL.indexAt(pos)
self.rulesWhitelistWidgetModel.removeRow(index.row())

How create a sqlalchemy delete query with multiples parameter from a loop

I'm new in python and sqlalchemy.
I already have a delete method working if I construct the where conditions by hand.
Now, I need to read the columns and values from an enter request in yaml format and create the where conditions.
#enter data as yaml
items:
- item:
table: [MyTable,OtherTable]
filters:
field_id: 1234
#other_id: null
Here is what I try and can't go ahead:
for i in use_case_cfg['items']:
item = i.get('item')
for t in item['table']:
if item['filters']:
filters = item['filters']
where_conditions = ''
count = 0
for column, value in filters.items():
aux = str(getattr(t, column) == bindparam(value))
if count == 0:
where_conditions += aux
else:
where_conditions += ', ' + aux
count += 1
to_delete = inv[t].__table__.delete().where(text(where_conditions))
#to_delete = t.__table__.delete().where(getattr(t, column) == value)
else:
to_delete = inv[t].__table__.delete()
CoreData.session.execute(to_delete)
To me, it looks ok, but when I run, I got the error below:
sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter '9876'
[SQL: DELETE FROM MyTable WHERE "MyTable".field_id = %(1234)s]
[parameters: [{}]]
(Background on this error at: http://sqlalche.me/e/cd3x)
Can someone explain to me what is wrong or the proper way to do it?
Thanks.
There are two problems with the code.
Firstly,
str(getattr(t, column) == bindparam(value))
is binding the value as a placeholder, so you end up with
WHERE f2 = :Bob
but it should be the name that maps to the value in filters (so the column name in your case), so you end up with
WHERE f2 = :f2
Secondly, multiple WHERE conditions are being joined with a comma, but you should use AND or OR, depending on what you are trying to do.
Given a model Foo:
class Foo(Base):
__tablename__ = 'foo'
id = sa.Column(sa.Integer, primary_key=True)
f1 = sa.Column(sa.Integer)
f2 = sa.Column(sa.String)
Here's a working version of a segment of your code:
filters = {'f1': 2, 'f2': 'Bob'}
t = Foo
where_conditions = ''
count = 0
for column in filters:
aux = str(getattr(t, column) == sa.bindparam(column))
if count == 0:
where_conditions += aux
else:
where_conditions += ' AND ' + aux
count += 1
to_delete = t.__table__.delete().where(sa.text(where_conditions))
print(to_delete)
session.execute(to_delete, filters)
If you aren't obliged to construct the WHERE conditions as strings, you can do it like this:
where_conditions = [(getattr(t, column) == sa.bindparam(column))
for column in filters]
to_delete = t.__table__.delete().where(sa.and_(*where_conditions))
session.execute(to_delete, filters)

How do I update a value in a dataframe in a loop?

I am trying to update a rating row by row. I have one dataframe of players, that all start with the same rating. For each match, I want the rating to change. Another dataframe contains results of each match.
import pandas as pd
gamesdata = [['paul','tom'],['paul','lisa'],['tom','paul'],['lisa','tom'],['paul','lisa'],['lisa','tom'],['paul','tom']]
games = pd.DataFrame(gamesdata, columns = ['Winner', 'Looser'])
playersdata= ['lisa','paul','tom']
players = pd.DataFrame(playersdata, columns = ['Name'])
mean_elo = 1000
elo_width = 400
k_factor = 64
players['elo'] = mean_elo
def update_elo(winner_elo, loser_elo):
expected_win = expected_result(winner_elo, loser_elo)
change_in_elo = k_factor * (1-expected_win)
winner_elo += change_in_elo
loser_elo -= change_in_elo
return winner_elo, loser_elo
def expected_result(elo_a, elo_b):
expect_a = 1.0/(1+10**((elo_b - elo_a)/elo_width))
return expect_a
for index, row in games.iterrows():
winnername = row['Winner']
losername = row['Looser']
web = players['elo'].loc[players['Name'] == winnername].values[0]
wIndex = players.loc[players['Name'] == winnername]
#I want to return just the index, so I can update the value
print(wIndex)
leb = players['elo'].loc[players['Name'] == losername].values[0]
print('Winner Elo before: ' + str(web))
winner_elo, looser_elo = update_elo(web, leb)
print('Winner Elo after: ' + str(winner_elo))
#here I want to update value
#players.at[wIndex,'elo']=winner_elo
I am trying to update the value in the players table using
players.at[wIndex,'elo']=winner_elo
but i struggle to get the index with this code:
wIndex = players.loc[players['Name'] == winnername]
Found a sollution:
wIndex = players.loc[players['Name'] == winnername].index.values
Can't believe i missed that

Setting row Span in QTableView using Python?

I am trying to set rowspan on second column of my QTableView but somehow logically i am missing something. i am only able to get A and B but not C. Plus i am getting warning QTableView::setSpan: span cannot overlap and QTableView::setSpan: single cell span won't be added
My code snippet is:-
startspan = 0
for i, tcname in enumerate(tcfilename):
if tcfilename[i]:
if i > 0:
print '#######################'
print 'startspan = '+str(startspan)+' i = '+str(i)
if tcname == tcfilename[i-1]:
#setSpan (row, column, rowSpan, columnSpan)
print 'if (from_row, till_row) '+str(startspan)+' '+str(i)
table_view.setSpan(startspan, 1, i, 1);
elif tcname != tcfilename[i-1]:
print 'Else no span (from_row, till_row) '+str(startspan)+' '+str(i)
table_view.setSpan(startspan, 1, i, 1);
if i == 1:
startspan = 0
else:
startspan = i
else:
break
Did this with simple two line code below
for toRow, tcname in enumerate(tcfilename):
table_view.setSpan(tcfilename.index(tcname), 1, tcfilename.count(tcname), 1)
I made a nifty little function to solve this.. Had recursion but then optimized it without recursion.. feed it a table and a data set
def my_span_checker(self, my_data, table):
for i in range(len(my_data)):
my_item_count = 0
my_label = table.item(i, 0).text()
for j in range(len(my_data)):
if table.item(j, 0).text() == my_label:
my_item_count += 1
if my_item_count != 1:
table.setSpan(i, 0, my_item_count, 1)

IndexError: tuple index out of range ----- Python

Please Help me. I'm running a simple python program that will display the data from mySQL database in a tkinter form...
from Tkinter import *
import MySQLdb
def button_click():
root.destroy()
root = Tk()
root.geometry("600x500+10+10")
root.title("Ariba")
myContainer = Frame(root)
myContainer.pack(side=TOP, expand=YES, fill=BOTH)
db = MySQLdb.connect ("localhost","root","","chocoholics")
s = "Select * from member"
cursor = db.cursor()
cursor.execute(s)
rows = cursor.fetchall()
x = rows[1][1] + " " + rows[1][2]
myLabel1 = Label(myContainer, text = x)
y = rows[2][1] + " " + rows[2][2]
myLabel2 = Label(myContainer, text = y)
btn = Button(myContainer, text = "Quit", command=button_click, height=1, width=6)
myLabel1.pack(side=TOP, expand=NO, fill=BOTH)
myLabel2.pack(side=TOP, expand=NO, fill=BOTH)
btn.pack(side=TOP, expand=YES, fill=NONE)
Thats the whole program....
The error was
x = rows[1][1] + " " + rows[1][2]
IndexError: tuple index out of range
y = rows[2][1] + " " + rows[2][2]
IndexError: tuple index out of range
Can anyone help me??? im new in python.
Thank you so much....
Probably one of the indices is wrong, either the inner one or the outer one.
I suspect you meant to say [0] where you said [1], and [1] where you said [2]. Indices are 0-based in Python.
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.
This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.
I received the same error with
query = "INSERT INTO table(field1, field2,...) VALUES (%s,%s,...)"
but in the statement
cursor.execute(query, (field1, field2,..)
I had delivered less variables as necessary...
In this case I used
import mysql.connector as mysql
I just wanted to say that this is also possible...not only in arrays
(I didn't have a very close look at this specific case...)

Categories