Unittest class attribute error - unit-testing

the unittestcase class is returning the error that
AttributeError: 'M2McommTestMethods' object has no attribute 'ser'
while running the following code.Pleas explain why this happens
import unittest
import serial
import math
import numpy
import pandas as pd
import random
import sys
sys.path.append('/home/vasudev/M2Mtesting')
import espmasterdriver as em
class M2McommTestMethods(unittest.TestCase):
def setUP(self):
self.ser = serial.Serial('/dev/ttyUSB0', 9600)
print(self.ser.name)
self.ser.flushInput()
self.ser.flushOutput()
def test_config(self):
comm1 = "<CONFIG "
self.ser.write(bytes(comm1, "utf-8"))
arr = em.arraygen()
for k in arr:
if k not in range(0, 256):
t = em.ToArray(k)
self.ser.write(bytes(t))
else:
self.ser.write(bytes(k))
comm2 = ">"
self.ser.write(bytes(comm2, "utf-8"))
data_raw = self.ser.readline()
resp1 = b'ACK\r\n'
self.AssertEqual(data_raw, resp1, "Not Equal")
def tearDown(self):
self.ser.close()
suite = unittest.TestLoader().loadTestsFromTestCase(M2McommTestMethods)
unittest.TextTestRunner(verbosity=2).run(suite)

Related

Using the keyboard print data

I have a problem with python 2.7.
Question: When I use the zoom function, I can not use the "keyboard" to print my real data. Here, I add the keyboard event in my code.
How do I exist in both functions? How should I debug the code?
import matplotlib
import sys
import random
matplotlib.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
from PyQt5.QtCore import *
import re
class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=10, height=4, dpi=100):
FigureCanvas.__init__(self, Figure(figsize=(width, height), dpi=dpi))
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.axes = self.figure.add_subplot(211)
self.mpl_connect("motion_notify_event", self.on_move)
self.po_annotation = []
self.ff=[]
def start_static_plot(self):
for i in range(0, 990):
(point,) = self.axes.plot(x, y, "-o")
annotation = self.axes.annotate(
("x=" + str(x), "y=" + str(y)),
textcoords="data",
horizontalalignment="left",
arrowprops=dict(arrowstyle="simple",connectionstyle="arc3,rad=+0.2"), bbox=dict(boxstyle="round", facecolor="w", edgecolor="0.1", alpha=0.9)
annotation.set_visible(False)
self.po_annotation.append([point, annotation])
self.axes.set_xlim(-0.5, 1000)
self.axes.set_ylim(-5, 9.5 ** 2)
def on_move(self, event):
visibility_changed = Ture
for point, annotation in self.po_annotation:
should_be_visible = point.contains(event)[4]
if should_be_visible != annotation.get_visible():
visibility_changed = True
annotation.set_visible(should_be_visible)
datachouse=str(annotation)
self.ff = np.loadtxt(f)
if visibility_changed:
self.draw()
def mouseReleaseEvent(self, event):
if(event.button() == Qt.LeftButton):
def initUi(self):
self.mpl.start_static_plot()
self.layout.addWidget(self.mpl)
if __name__ == '__main__':
app = QApplication(sys.argv)
sys.exit(app.exec_())
If you don't want to remove the default behavior of a method then you must invoke the parent method:
def mouseReleaseEvent(self, event):
super(MyMplCanvas, self).mouseReleaseEvent(event)
if event.button() == Qt.LeftButton:
print("result=", self.ff)

How to search an item in list widget using with pyqt4

Here in my sample program,I want to display the lot of names in list widget.In that, I want to search a particular item in list widget using search button,and I want to print that item name in list widget.
Given below is my code:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
auto_search_vbox = QtGui.QVBoxLayout(self)
hbox=QtGui.QHBoxLayout()
le_search = QtGui.QLineEdit()
se_btn = QtGui.QPushButton("Search")
se_btn.clicked.connect(self.find_item)
hbox.addWidget(le_search)
hbox.addWidget(se_btn)
auto_search_vbox.addLayout(hbox)
self.listwidget = QtGui.QListWidget()
self.total_list =["machine","printer","xerox bundles"]
self.listwidget.addItems(self.total_list)
auto_search_vbox.addWidget(self.listwidget)
self.show()
def find_item(self):
out = self.listwidget.findItems("mac", QtCore.Qt.MatchExactly)
print out
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Sorry, I have PyQt5. Try it:
flags Qt::MatchFlags
This enum describes the type of matches that can be used when searching for items in a model.
import sys
#from PyQt4.QtGui import *
#from PyQt4.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.le_search = QLineEdit() # self. +++
se_btn = QPushButton("Search")
se_btn.clicked.connect(self.find_item)
self.listwidget = QListWidget()
self.total_list = ["machine", "mac1", "printer", "Printer","xerox bundles", "2mac"]
self.listwidget.addItems(self.total_list)
hbox = QHBoxLayout()
hbox.addWidget(self.le_search) # self. +++
hbox.addWidget(se_btn)
auto_search_vbox = QVBoxLayout(self)
auto_search_vbox.addLayout(hbox)
auto_search_vbox.addWidget(self.listwidget)
def find_item(self):
# out = self.listwidget.findItems("mac", QtCore.Qt.MatchExactly) # ---
# out = self.listwidget.findItems(self.le_search.text(), Qt.MatchExactly)
out = self.listwidget.findItems(self.le_search.text(),
Qt.MatchContains | # +++
Qt.MatchCaseSensitive) # +++
print("out->", [ i.text() for i in out ] )
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())

Syntax error creating ArcGIS Feature class from Twitter data

I've tried my best to solve this error-
SyntaxError: Invalid syntax in this line
if__name__==__main':
main()
I'm using #Tweepy and #PYTHON27 and attempting to build an #ArcGIS .mdb Feature Class with the collected tweets that contain geotags. Any ideas what is causing the bail? Thank you so much. #Twitter
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time
import sys
import arcpy
#global variables
consumer_key = 'xxx'
consumer_secret = 'xxxx'
token_key = 'xxx'
token_secret = 'xxx'
class StdOutListener(StreamListener):
def __init__(self, start_time, featureClass, time_limit):
super(StdOutListener, self).__init__()
self.time = start_time
self.limit = time_limit
self.featureClass = featureClass
def on_status(self, status):
while (time.time() - self.time) <self.limit:
if status.geo is not None:
dictCoords = status.geo
listCoords = dictCoords['coordinates']
latitude = listCoords[0]
longitude = listCo0ords[1]
cursor = arcpy.da.InsertCursor(self.featureClass,("SHAPE#XY"))
cursor.insertRow([(longitude,latitude)])
print(str(listCoords[0]) + "," + str(listCoords[1]))
return True
else:
print "No coordinates found"
return True
def on_error(self, status):
print('Error...')
print status
return True
def on_timeout(self):
print('Timeout...')
return True
start_time = time.time()
arcpy.env.workspace = r'c:\ArcGIS_Blueprint_Python\data\Twitter\TweetInformation.gdb'
def main():
try: #new
featureClass = sys.argv[1]
monitorTime = sys.argv[2]
monitorTime = monitorTime * 3600
sr = arcpy.SpatialReference(4326)
arcpy.env.overwriteOutput = True
arcpy.CreateFeatureClass_management(arcpy.env.workspace,
featureClass, "POINT", spatial_reference=sr)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(token_key, token_secret)
stream = Stream(auth, StdOutListener(start_time, featureClass,
time_limit=monitorTime)) #172800
stream.filter(track=['car'])
except Exception as e:
print(e.message)
if__name__ == '__main__':
main()

Trouble with Importing Data and displaying it on a graph on a button click in python

from PyQt4.uic import loadUiType
import pandas as pd
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
Ui_MainWindow, QMainWindow = loadUiType('EIA_20151504_v2.ui')
the above code i have done the following. I have imported the UI designed using QI designer and called matplotlib backend for putting matplotlib greaph in my app
class Main(QMainWindow, Ui_MainWindow):
def __init__(self, ):
super(Main, self).__init__()
self.setupUi(self)
self.RawData.clicked.connect(self.importdata)
def addmpl(self, fig):
self.canvas = FigureCanvas(fig)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,
self.MapCanvas, coordinates=True)
self.mplvl.addWidget(self.toolbar)
self.canvas.show()
def importdata(self):
choice = QtGui.QMessageBox.question(self, 'Import Data',"Do you want to import data?", QtGui.QMessageBox.Yes |QtGui.QMessageBox.No,QtGui.QMessageBox.No)
if choice == QtGui.QMessageBox.Yes:
xlsfile = pd.ExcelFile('import_file.xlsx')
self.dframe = xlsfile.parse('Sheet1', header=0, index_col=0, has_index_names=True)
self.xList = self.dframe.columns.values
self.xList = pd.to_datetime(self.xList)
self.yList = self.dframe.values
self.yList = self.yList.T
ax1f1.plot(self.xList,self.yList)
else:
pass
In the above code, I have declared a class Main which initialises the UI code imported from Qt designer and there are tw functions one is to initialise the map canvas and other to import data from another file and plot it on the click of the RawData button.
but if you try to run the code, the graph doesnot display any content
if __name__ == '__main__':
import sys
from PyQt4 import QtGui
import numpy as np
fig1 = Figure()
ax1f1 = fig1.add_subplot(111)
app = QtGui.QApplication(sys.argv)
main = Main()
main.addmpl(fig1)
main.show()
sys.exit(app.exec_())
Kindly let me know where I am going wrong
class Main(QMainWindow, Ui_MainWindow):
def __init__(self, ):
super(Main, self).__init__()
self.setupUi(self)
self.RawData.clicked.connect(self.importdata)
def addmpl(self, fig):
self.canvas = FigureCanvas(fig)
self.mplvl.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,
self.MapCanvas, coordinates=True)
self.mplvl.addWidget(self.toolbar)
self.canvas.show()
def rmmpl(self,):
self.mplvl.removeWidget(self.canvas)
self.canvas.close()
self.mplvl.removeWidget(self.toolbar)
self.toolbar.close()
def importdata(self):
choice = QtGui.QMessageBox.question(self, 'Import Data',"Do you want to import data?", QtGui.QMessageBox.Yes |QtGui.QMessageBox.No,QtGui.QMessageBox.No)
if choice == QtGui.QMessageBox.Yes:
xlsfile = pd.ExcelFile('import_file.xlsx')
self.dframe = xlsfile.parse('Sheet1', header=0, index_col=0, has_index_names=True)
self.xList = self.dframe.columns.values
self.xList = pd.to_datetime(self.xList)
self.yList = self.dframe.values
self.yList = self.yList.T
ax1f1.plot(self.xList,self.yList)
self.rmmpl()
self.addmpl(fig1)
else:
pass
def transition(self):
if __name__ == '__main__':
import sys
from PyQt4 import QtGui
import numpy as np
fig1 = Figure()
ax1f1 = fig1.add_subplot(111)
app = QtGui.QApplication(sys.argv)
main = Main()
main.addmpl(fig1)
main.show()
sys.exit(app.exec_())
There were some minor mistakes which I rectified.

python Attributes error

i just want to ask, what's wrong with my codes, or am i missing something. because when i call the function PausePlay() in the PlayAndPause() I always get an error saying:
self.dbusIfaceKey.Action(dbus.Int32("16"))
AttributeError: 'OpenOMX' object has no attribute 'dbusIfaceKey'
Here's the code:
OPTIONS = 'omxplayer -o local -t on --align center --win "0 0 {1} {2}" \"{0}\"'
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from Tkinter import *
import sys
import os
from os import system
import dbus,time
from subprocess import Popen
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
MoviePath = '/media/HP v250w/Our Story in 1 Minute.mp4'
class OpenOMX(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
global MoviePath
global myctr
width = QtGui.QApplication.desktop().width()
height = QtGui.QApplication.desktop().height()
cmd = OPTIONS.format(MoviePath,width,height-60)
Popen([cmd], shell=True)
done,retry = 0,0
while done==0:
try:
with open('/tmp/omxplayerdbus', 'r+') as f:
omxplayerdbus = f.read().strip()
bus = dbus.bus.BusConnection(self.omxplayerdbus)
print 'connected'
object = bus.get_object('org.mpris.MediaPlayer2.omxplayer','/org/mpris/MediaPlayer2', introspect=False)
self.dbusIfaceProp = dbus.Interface(object,'org.freedesktop.DBus.Properties')
self.dbusIfaceKey = dbus.Interface(object,'org.mpris.MediaPlayer2.Player')
done=1
except:
retry+=1
if retry >= 50:
print 'ERROR'
raise SystemExit
def PausePlay(self):
self.dbusIfaceKey.Action(dbus.Int32('16'))
class VidControls(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
def setupUi(self, MainWindow):
'some codes here'
def retranslateUi(self, MainWindow):
self.btnPause.clicked.connect(self.PlayAndPause)
def PlayAndPause(self):
self.opn = OpenOMX()
self.opn.PausePlay()
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
ex = VidControls()
ex.show()
play = OpenOMX()
play.start()
sys.exit(app.exec_())
Any Comments or Suggestions would be highly appreciated. Thanks.