Reassining variables - oop

I was doing a test project just to train my Python and I stumbled upon something that I don't quite understand so I would appreciate if someone explained it to me.
Below, I'm giving two similar Test scripts that give different results and I don't know why that is so:
class Test:
def __init__(self):
self.test = ""
self.testing("test_word", self.test)
def testing(self, word, test_var):
print(f"{self.test = }")
print(f"{test_var = }")
self.test = word
print(f"{self.test = }")
print(f"{test_var = }")
if __name__ == "__main__":
Test()
class Test1:
def __init__(self):
self.test = ["", ""]
self.testing("test_word", self.test)
def testing(self, word, test_var):
print(f"{self.test = }")
print(f"{test_var = }")
self.test[0] = word
print(f"{self.test = }")
print(f"{test_var = }")
if __name__ == "__main__":
Test1()
[What I DON'T understand]
Why in the case with the list (Test1), when I assign the first item in "self.test" to be "test_word", it also assigns it to the local, already passed list "test_var" as well, whereas in the other example (Test), when using a string variable I assign "self.test" to be "test_word" but the local "test_var" argument stays an empty string. I thought both these Test classes should give the same output, so why don't they?
P.S: I did a little more testing and found out that in the case with lists the test_var IS self.test, so they're pointing to the same object, whereas in the case of the string, in the beginning they have the same value but they're not referencing the same object. So in that case, how would I get a copy of the list instead of referencing the same object? Maybe I can assign a copy at the beginning of the "testing" method but is there a way to do it by passing arguments?
I'm sorry if this is a duplicate question, I couldn't find an answer to it.

I think I mostly answered my own question.
Here's a bunch of tests that you can copy-paste and execute to see the difference:
class Test:
def __init__(self):
self.test = ""
self.testing("test_word", self.test)
def testing(self, word, test_var):
print(f"{self.test = }")
print(f"{test_var = }")
self.test = word
print(f"{self.test = }")
print(f"{test_var = }")
print(test_var is self.test)
if __name__ == "__main__":
print("-"*50)
Test()
class Test0:
def __init__(self):
self.test = ""
self.testing("test_word")
def testing(self, word):
test_var = self.test
print(f"{self.test = }")
print(f"{test_var = }")
self.test = word
print(f"{self.test = }")
print(f"{test_var = }")
print(test_var is self.test)
if __name__ == "__main__":
print("-"*50)
Test0()
class Test1:
def __init__(self):
self.test = ["", ""]
self.testing("test_word", self.test)
def testing(self, word, test_var):
print(f"{self.test = }")
print(f"{test_var = }")
self.test[0] = word
print(f"{self.test = }")
print(f"{test_var = }")
print(test_var is self.test)
if __name__ == "__main__":
print("-"*50)
Test1()
class Test2:
def __init__(self):
self.test = ["", ""]
self.testing("test_word")
def testing(self, word):
test_var = self.test
print(f"{self.test = }")
print(f"{test_var = }")
self.test[0] = word
print(f"{self.test = }")
print(f"{test_var = }")
print(test_var is self.test)
if __name__ == "__main__":
print("-"*50)
Test2()
class Test3:
def __init__(self):
self.test = ["", ""]
self.testing("test_word")
def testing(self, word):
test_var = self.test.copy()
print(f"{self.test = }")
print(f"{test_var = }")
self.test[0] = word
print(f"{self.test = }")
print(f"{test_var = }")
print(test_var is self.test)
if __name__ == "__main__":
print("-"*50)
Test3()
class Test4:
def __init__(self):
self.test = ["", ""]
self.testing("test_word", self.test.copy())
def testing(self, word, test_var):
print(f"{self.test = }")
print(f"{test_var = }")
self.test[0] = word
print(f"{self.test = }")
print(f"{test_var = }")
print(test_var is self.test)
if __name__ == "__main__":
print("-"*50)
Test4()
Output:
--------------------------------------------------
self.test = ''
test_var = ''
self.test = 'test_word'
test_var = ''
False
--------------------------------------------------
self.test = ''
test_var = ''
self.test = 'test_word'
test_var = ''
False
--------------------------------------------------
self.test = ['', '']
test_var = ['', '']
self.test = ['test_word', '']
test_var = ['test_word', '']
True
--------------------------------------------------
self.test = ['', '']
test_var = ['', '']
self.test = ['test_word', '']
test_var = ['test_word', '']
True
--------------------------------------------------
self.test = ['', '']
test_var = ['', '']
self.test = ['test_word', '']
test_var = ['', '']
False
--------------------------------------------------
self.test = ['', '']
test_var = ['', '']
self.test = ['test_word', '']
test_var = ['', '']
False

Related

Why does QThread freezes Gui Thread while working?

I need to keep updating the table to have up-to-date information. To do this, I created a Thread and implemented an infinite loop in it, which iterates through all the values and compares them, but for some reason the work of this thread affects GUI and as a result, the thread with GUI freezes.
import random
import sys
import pandas as pd
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal, Qt, QThread, QModelIndex
from PyQt5.QtWidgets import QApplication, QMainWindow
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, header: list):
super(TableModel, self).__init__()
self._data = pd.DataFrame(columns=header)
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return self._data.values[index.row()][index.column()]
return None
def rowCount(self, parent: QModelIndex = ...) -> int:
return len(self._data.values)
def columnCount(self, index):
return self._data.columns.size
def headerData(self, section, orientation, role):
# section is the index of the column/row.
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return str(self._data.columns[section])
if orientation == Qt.Vertical:
return str(self._data.index[section])
def setData(self, index, value, role):
if not index.isValid():
return False
row = index.row()
if row < 0 or row >= len(self._data.values):
return False
column = index.column()
if column < 0 or column >= self._data.columns.size:
return False
self._data.iloc[row, column] = value
self.dataChanged.emit(index, index)
return True
def removeRows(self, position, rows, parent=QModelIndex()):
start, end = position, position + rows - 1
if 0 <= start <= end < self.rowCount(parent):
self.beginRemoveRows(parent, start, end)
for index in range(start, end + 1):
self._data.drop(index, inplace=True)
self._data.reset_index(drop=True, inplace=True)
self.endRemoveRows()
return True
return False
def insertRows(self, position, rows, parent=QModelIndex()):
start, end = position, position + rows - 1
if 0 <= start <= end:
self.beginInsertRows(parent, start, end)
for index in range(start, end + 1):
default_row = [[None] for _ in range(self._data.shape[1])]
new_df = pd.DataFrame(dict(zip(list(self._data.columns), default_row)))
self._data = pd.concat([self._data, new_df])
self._data = self._data.reset_index(drop=True)
self.endInsertRows()
return True
return False
def addRow(self, item):
self.insertRows(self.rowCount(), 1)
row = self.rowCount() - 1
self.setData(self.index(row, 0), item[0], Qt.DisplayRole)
self.setData(self.index(row, 1), item[1], Qt.DisplayRole)
self.setData(self.index(row, 2), item[2], Qt.DisplayRole)
self.setData(self.index(row, 3), item[3], Qt.DisplayRole)
self.setData(self.index(row, 4), item[4], Qt.DisplayRole)
def getTable(self):
return self._data
class Updater(QObject):
addRow = pyqtSignal(object)
def __init__(self, table: TableModel):
super().__init__()
self.items = []
for i in range(50):
item = [
random.randint(10, 100),
random.randint(10, 100),
random.randint(10, 100),
random.randint(10, 100),
random.randint(10, 100),
]
self.items.append(item)
self._table = table
self._status = False
def start(self):
self._status = True
if self._table.getTable().empty:
items = self.items
for item in items:
self.addRow.emit(item)
while self._status:
self.Update(self.items)
def Update(self, items: list):
# This function is looking for items in table and changes data if its not up-to-date
data = self._table.getTable()
for item in items:
result = data.loc[
(data['Col1'] == item[0]) &
(data['Col2'] == item[1]) &
(data['Col3'] == item[2])
]
if len(result.values) != 0:
pass
# Code ...
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setObjectName("MainWindow")
self.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(self)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout = QtWidgets.QGridLayout()
self.gridLayout.setObjectName("gridLayout")
self.tableWidget = QtWidgets.QTableView(self.centralwidget)
self.tableWidget.setObjectName("tableWidget")
self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1)
self.gridLayout_2.addLayout(self.gridLayout, 0, 0, 1, 1)
self.setCentralWidget(self.centralwidget)
header = ["Col1", "Col2", "Col3", "Col4", "Col5"]
self.model = TableModel(header)
self.tableWidget.setModel(self.model)
self._updater = Updater(self.model)
self._thread = QThread()
self._updater.moveToThread(self._thread)
self._thread.started.connect(self._updater.start)
self._thread.finished.connect(self._thread.deleteLater)
self._updater.addRow.connect(self.model.addRow, Qt.QueuedConnection)
self.show()
self._thread.start()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
Do not judge strictly. I've only recently started learning pyqt and I don't really understand it yet.Thank you in advance!

QMediaPlayer.setVideoOutput frozen

I tried to add videowidget to QFrame inside QstackedWidget but when i use QMediaPlayer.setVideoOutput the program run but
frozen, when i click on the window it just give beeping sound. when i comment the setVideoOutput it
run just fine.
`class halaman_belajar(QWidget):
def init(self):
super().init()
uic.loadUi(".\Asset\GuiHalamanBelajar.ui", self)
self.kembali_menu.clicked.connect(self.kembali)
self.kembali_menu.setCursor(QCursor(Qt.PointingHandCursor))
self.kembali_menu.setShortcut("esc")
self.bab_selanjutnya.clicked.connect(self.selanjutnya)
self.bab_selanjutnya.setCursor(QCursor(Qt.PointingHandCursor))
self.bab_selanjutnya.setShortcut(Qt.Key_Right)
self.bab_sebelumnya.clicked.connect(self.sebelumnya)
self.bab_sebelumnya.setCursor(QCursor(Qt.PointingHandCursor))
self.bab_sebelumnya.setShortcut(Qt.Key_Left)
self.halaman_isi.setCurrentIndex(0)
self.bab_sebelumnya.setEnabled(False)
if self.halaman_isi.currentIndex == 0:
self.bab_sebelumnya.setEnabled(False)
else:
self.bab_sebelumnya.setEnabled(True)
#Combo Box
self.pintasan_halaman.activated.connect(self.pintasanhalaman)
#video player
video = QVideoWidget()
self.videoproklamasi = QMediaPlayer(None, QMediaPlayer.VideoSurface)
self.videoproklamasi.setMedia(QMediaContent(QUrl.fromLocalFile("E:\ProjectHistoryApp\Asset\proklamasi.mp4")))
#self.videoproklamasi.setVideoOutput(video)
self.play = QPushButton()
self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
#self.play.clicked.connect(self.mulaivideo)
self.slider= QSlider(Qt.Horizontal)
self.slider.setRange(0,0)
self.wadahnisor = QHBoxLayout()
self.wadahnisor.setContentsMargins(0,0,0,0)
self.wadahnisor.addWidget(self.play)
self.wadahnisor.addWidget(self.slider)
self.wadahvideo = QVBoxLayout(self.isi_video)
self.wadahvideo.addWidget(video)
self.wadahvideo.addLayout(self.wadahnisor)
def kembali(self):
pesan2 = QMessageBox()
pesan2.setWindowTitle("Status")
pesan2.setText("Kembali Ke Menu?")
pesan2.setWindowIcon(QIcon(".\Asset\Mascot.png"))
pesan2.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
hasil = pesan2.exec()
if hasil == QMessageBox.Yes:
show_halaman.setCurrentIndex(show_halaman.currentIndex() - 1)
def selanjutnya(self):
self.halaman_isi.setCurrentIndex(self.halaman_isi.currentIndex() + 1)
self.bab_sebelumnya.setEnabled(True)
#if halaman_isi.currentIndex == 10:
#self.bab_selanjutnya.setEnabled(False)
def sebelumnya(self):
self.halaman_isi.setCurrentIndex(self.halaman_isi.currentIndex() - 1)
if self.halaman_isi.currentIndex() == 0:
self.bab_sebelumnya.setEnabled(False)
def pintasanhalaman(self):
self.halaman_isi.setCurrentIndex(self.pintasan_halaman.currentIndex())
if self.halaman_isi.currentIndex() != 0:
self.bab_sebelumnya.setEnabled(True)
def mulaivideo(self):
if self.videoproklamasi.state() == QMediaPlayer.PlayingState():
self.videoproklamasi.pause()
else:
self.videoproklamasi.play()`

Rewritten QLabel class seems wrong in PyQt5

I rewrite the QLabel class to select ROI on the QLabel, aimed to acheive the cv2.selectROI function. But still wrong......
This is the code:
The QMainWindows Code:
class MyGui(QMainWindow):
def __init__(self, parent=None):
super(MyGui, self).__init__(parent)
self.init_rect = [0, 0, 0, 0]
self.tracker = None
self.first_frame = True
self.video_name = r'G:\dataset\example_Trim.mp4'
self.setupUi()
self.cap = None
self.status = self.statusBar() # 实例化创建状态栏
self.status.showMessage('Author', 10000) # 显示状态栏信息
self.timer_camera = QTimer()
self.show_windows = roiLabel()
self.show_windows.setFixedSize(1500, 800)
self.show_windows.move(50, 10)
self.show_windows.setStyleSheet("QLabel{background-color:gray;}")
def setupUi(self):
self.setObjectName("MainWindow")
self.setFixedSize(1600, 900) # 设置窗口的大小
self.setWindowFlag(QtCore.Qt.WindowMinimizeButtonHint) # 去掉最小化按钮
self.setWindowTitle('基于Transformer的视频目标跟踪方法研究') # 设置窗口标题
self.setWindowIcon(QIcon(r'F:\PythonDoc\trans_tt_backup\gui\pic\Windows_icon.png')) # 设置图标
self.move_center()
And the rewritten QLabel class is :
class roiLabel(QLabel): # 利用QLabel绘制ROI
def __init__(self):
super().__init__()
self.open_keyboard_flag = False
self.open_mouse_flag = False
self.draw_roi_flag = False
self.select_roi_flag = False
self.clear_flag = False
self.x0 = 0
self.y0 = 0
self.x1 = 0
self.y1 = 0
self.rect = QRect()
self.label_show = None
# 按下鼠标时,记录左上角坐标
def mousePressEvent(self, event):
if self.open_mouse_flag is True:
self.select_roi_flag = True
self.x0 = event.x()
self.y0 = event.y()
The problem is:
I want the 'python' windows is embed in mainwindows

batch normalization switch in tensorflow

Here is an autoencoder.
My problem is that I don't know how to set "mode" to let it split into "train" and "test".
I'm glad if you guys can show me an example:D
Can I use a global variable or placeholder to change "mode" ?
I'm glad you can answer it for me.
#batch normalization
def Batch_norm_en(Wx_plus_b, i):
if mode == 1:
fc_mean_en, fc_var_en = tf.nn.moments(Wx_plus_b, axes=[0, 1])
else:
fc_mean_en, fc_var_en = fc_mean_en, fc_var_en
Wx_plus_b = tf.nn.batch_normalization(Wx_plus_b, fc_mean_en, fc_var_en, shift_en[i], scale_en[i], 10**(-3))
return Wx_plus_b
def Batch_norm_de(Wx_plus_b, i):
if mode == 1:
fc_mean_de, fc_var_de = tf.nn.moments(Wx_plus_b, axes=[0, 1])
else:
fc_mean_de, fc_var_de = fc_mean_de, fc_var_de
Wx_plus_b = tf.nn.batch_normalization(Wx_plus_b, fc_mean_de, fc_var_de, shift_de[i], scale_de[i], 10**(-3))
return Wx_plus_b
#encoder data
def encoder_model(x):
res = x
for i in range(0, len(en_n_neurons)-1):
Wx_plus_b = tf.matmul(res,W_en[i]) + b_en[i]
Wx_plus_b = Batch_norm_en(Wx_plus_b, i)
res = tf.nn.sigmoid(Wx_plus_b)
return res
#decoder data
def decoder_model(x):
res = x
for i in range(0, len(de_n_neurons)-1):
Wx_plus_b = tf.matmul(res,W_de[i]) + b_de[i]
Wx_plus_b = Batch_norm_de(Wx_plus_b, i)
res = tf.nn.sigmoid(Wx_plus_b)
return res

Double buffering in Jython

recently I started learning Jython and now I have rather simply problem. I would like to improve quality of my animation. Unfortunately I don't know how to add double buffering to my applet . Could you help me?
Best regards!
from javax.swing import JToolBar
from javax.swing import JButton
from javax.swing import JFrame
import time
from java import awt
from java.awt import BorderLayout
class Canvas(awt.Canvas):
u"Canvas - drawing area"
def __init__(self,winSize = 400):
self.play = False
self.background=awt.Color.black
self.winSize = winSize
self.l = 0
def playSim(self, play):
if play == True:
self.play = True
self.repaint()
else: self.play = False
def paint(self, g):
g.fillRect(50, int(self.winSize/4), self.l, int(self.winSize/2))
if self.l < self.winSize: self.l += 1
else: self.l = 0
time.sleep(0.02)
if self.play == True: self.repaint()
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
winSize = 600
toolbar = JToolBar()
self.playButton = JButton("Start", actionPerformed=self.playButtonPress )
toolbar.add(self.playButton)
self.add(toolbar, BorderLayout.NORTH)
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(winSize, winSize)
self.setResizable(False)
self.setLocationRelativeTo(None)
self.setVisible(True)
self.canvas = Canvas(winSize)
self.getContentPane().add(self.canvas)
self.setTitle("TEST")
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
def playButtonPress(self, e):
if self.playButton.getLabel() == "Start":
self.canvas.playSim(True)
self.playButton.setLabel("Stop")
else:
self.playButton.setLabel("Start")
self.canvas.playSim(False)
if __name__ == '__main__':
Example()
I solved my recent problem:
from javax.swing import JToolBar
from javax.swing import JButton
from javax.swing import JFrame
import time
from java import awt
from java.awt import BorderLayout
class Canvas(awt.Canvas):
u"Canvas - drawing area"
def __init__(self,winSize = 400):
self.play = False
self.background=awt.Color.black
self.winSize = winSize
self.l = 0
self.bi = BufferedImage(winSize, winSize, BufferedImage.TYPE_INT_RGB)
self.offScreenGraphics = self.bi.getGraphics()
def playSim(self, play):
if play == True:
self.play = True
self.repaint()
else: self.play = False
def paint(self, g):
self.offScreenGraphics.fillRect(50, int(self.winSize/4), self.l, int(self.winSize/2))
if self.l < self.winSize: self.l += 1
else: self.l = 0
g.drawImage(self.bi, 0, 0, None)
time.sleep(0.02)
if self.play == True: self.repaint()
class Example(JFrame):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
winSize = 600
toolbar = JToolBar()
self.playButton = JButton("Start", actionPerformed=self.playButtonPress )
toolbar.add(self.playButton)
self.add(toolbar, BorderLayout.NORTH)
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
self.setSize(winSize, winSize)
self.setResizable(False)
self.setLocationRelativeTo(None)
self.setVisible(True)
self.canvas = Canvas(winSize)
self.getContentPane().add(self.canvas)
self.setTitle("TEST")
self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
def playButtonPress(self, e):
if self.playButton.getLabel() == "Start":
self.canvas.playSim(True)
self.playButton.setLabel("Stop")
else:
self.playButton.setLabel("Start")
self.canvas.playSim(False)
if __name__ == '__main__':
Example()
Now I've another(rather trivial) problem:
How can I make from this python file *the class file* which would be ready to publish it on website as an applet?