How to use selectrow method in pyatom

Best Python code snippet using pyatom_python

csvedit

Source:csvedit Github

copy

Full Screen

1#!/usr/bin/python32import curses3import pandas as pd4import time5import os6import csv7import sys8from curses import wrapper9from math import nan10from curses import ascii11COLUMN_LENGTH_DEFAULT = 1212COLUMN_LENGTH_MIN = 413COLUMN_LENGTH_MAX = 4014#--First row of the table--15#CHRHEADERTOPLEFT = '\u2554' #CHRHEADERTOPMIDDLE = '\u2564' #CHRHEADERTOPLINE = '\u2550' #CHRHEADERTOPRIGHT = '\u2557'16CHRHEADERTOPLEFT = '\u250c'17CHRHEADERTOPMIDDLE = '\u252c'18CHRHEADERTOPLINE = '\u2500'19CHRHEADERTOPRIGHT = '\u2510'20#--Header line with column names--21#CHRHEADERDATALEFT = '\u2551' #CHRHEADERDATARIGHT = '\u2551'22CHRHEADERDATALEFT = '\u2502'23CHRHEADERDATAMIDDLE = '\u2502'24CHRHEADERDATARIGHT = '\u2502'25#--Line right below the column names--26#CHRHEADERMIDDLELEFT = '\u255F' #CHRHEADERMIDDLERIGHT = '\u2562'27CHRHEADERMIDDLELEFT = '\u251C'28CHRHEADERMIDDLEMIDDLE = '\u253C'29CHRHEADERMIDDLELINE = '\u2500'30CHRHEADERMIDDLERIGHT = '\u2524'31#--Last line of the table--32#CHRHEADERBOTTOMLEFT = '\u255A' #CHRHEADERBOTTOMMIDDLE = '\u2567' #CHRHEADERBOTTOMLINE = '\u2550' #CHRHEADERBOTTOMRIGHT = '\u255D'33CHRHEADERBOTTOMLEFT = '\u2514'34CHRHEADERBOTTOMMIDDLE = '\u2534'35CHRHEADERBOTTOMLINE = '\u2500'36CHRHEADERBOTTOMRIGHT = '\u2518'37def getstartrow(startrow,selectrow,height):38 if (selectrow<startrow+5):39 startrow = max(0,selectrow-5)40 if (selectrow>startrow+height-5-5-1):41 startrow = min(selectrow-(height-5-5-1),TblLayout['numrows']-(height-5))42 return(startrow)43def getstartcol(startcol,selectcol,width):44 if (selectcol<startcol): #Scroll left if needed45 startcol = selectcol46 elif (selectcol>startcol):47 endwidth = 048 for i in range(startcol,selectcol+1):49 endwidth = endwidth + 2 + TblLayout['columnwidths'][i] + 150 if (endwidth>width):51 startcol = getstartcol(startcol+1,selectcol,width)52 else:53 startcol = startcol54 return(startcol)55def displayheader(stdscr,startcol,rows,height,width):56 # https://www.unicode.org/charts/PDF/U2500.pdf57 if ( (height < 15) | (width < 40) ):58 if (height>0):59 stdscr.addstr(0,0,'Enlarge terminal to a minimum of 15x40'[:(width-1)])60 else:61 if (startcol == 0):62 headertop = CHRHEADERTOPLEFT63 headermiddle = CHRHEADERMIDDLELEFT64 headerbottom = CHRHEADERBOTTOMLEFT65 headerdata = CHRHEADERDATALEFT66 else:67 headertop = CHRHEADERTOPMIDDLE68 headermiddle = CHRHEADERMIDDLEMIDDLE69 headerbottom = CHRHEADERBOTTOMMIDDLE70 headerdata = CHRHEADERDATAMIDDLE71 for i in range(startcol,TblLayout['numcols']):72 if (len(headertop)<width):73 headertop = headertop + CHRHEADERTOPLINE*(TblLayout['columnwidths'][i]+2)74 headermiddle = headermiddle + CHRHEADERMIDDLELINE*(TblLayout['columnwidths'][i]+2)75 headerbottom = headerbottom + CHRHEADERBOTTOMLINE*(TblLayout['columnwidths'][i]+2)76 headerdata = headerdata + ' '+TblLayout['columnnames'][i][:TblLayout['columnwidths'][i]].ljust(TblLayout['columnwidths'][i])+' '77 if (i<TblLayout['numcols']-1):78 headertop = headertop + CHRHEADERTOPMIDDLE79 headermiddle = headermiddle + CHRHEADERMIDDLEMIDDLE80 headerbottom = headerbottom + CHRHEADERBOTTOMMIDDLE81 headerdata = headerdata + CHRHEADERDATAMIDDLE82 else:83 headertop = headertop + CHRHEADERTOPRIGHT84 headermiddle = headermiddle + CHRHEADERMIDDLERIGHT85 headerbottom = headerbottom + CHRHEADERBOTTOMRIGHT86 headerdata = headerdata + CHRHEADERDATARIGHT87 else:88 break; #Break out of the for loop89 stdscr.addstr(0, 0, headertop[:width].ljust(width))90 stdscr.addstr(1, 0, headerdata[:width].ljust(width))91 stdscr.addstr(2, 0, headermiddle[:width].ljust(width))92 lastrow = min(2+rows+1,height-2)93 stdscr.addstr(lastrow, 0, headerbottom[:width].ljust(width))94def displaydata(stdscr,startcol,startrow,maxrows,selectrow,selectcol,height,width):95 if ( (height < 15) | (width < 40) ):96 return(0)97 tic = time.perf_counter()98 stoprow = min(maxrows-1,TblLayout['numrows']-1)99 displayrow = 3100 for j in range(startrow, stoprow+1):101 displaycol = 0102 if (width>displaycol):103 if (startcol == 0):104 stdscr.addstr(displayrow, displaycol, CHRHEADERDATALEFT)105 else:106 stdscr.addstr(displayrow, displaycol, CHRHEADERDATAMIDDLE)107 displaycol = displaycol + 1 #Also foresee an extra space at the left of the first data field108 if (width>displaycol):109 stdscr.addstr(displayrow, displaycol, ' ')110 displaycol = displaycol + 1 #Also foresee an extra space at the left of the first data field111 for i in range(startcol,TblLayout['numcols']):112 if (width>displaycol):113 cellwidth = TblLayout['columnwidths'][i]114 displaywidth = min(cellwidth,width-displaycol-1)115 datastr = str(df.iloc[j,i])[:displaywidth].ljust(displaywidth)116 if (j==selectrow):117 highlight = curses.A_BOLD | curses.A_REVERSE * (i==selectcol)118 else:119 highlight = 0120 stdscr.addstr(displayrow, displaycol, datastr, highlight)121 displaycol = displaycol + displaywidth #Also foresee an extra space at the right of the data field122 if (width>displaycol):123 stdscr.addstr(displayrow, displaycol, ' ')124 displaycol = displaycol + 1 #Also foresee an extra space at the left of the first data field125 if (width>displaycol):126 if (i<TblLayout['numcols']-1):127 stdscr.addstr(displayrow, displaycol, CHRHEADERDATAMIDDLE)128 else: #end of the line129 stdscr.addstr(displayrow, displaycol, CHRHEADERDATARIGHT.ljust(width-displaycol-1))130 displaycol = displaycol + 1 #Also foresee an extra space at the left of the separator131 if (width>displaycol):132 stdscr.addstr(displayrow, displaycol, ' ')133 displaycol = displaycol + 1 #Also foresee an extra space at the left of the first data field134 displayrow = displayrow + 1135 toc=time.perf_counter()136 statusline = 'Cell {}:{} ({})'.format(selectrow+1,selectcol+1,TblLayout['numrows'])137 statusline = statusline + ' | Ctrl-(W/X): Insert (Above/Below) | Ctrl-D: Delete record | F4: Save | Ctrl-E: Exit (no save)'138 #statusline = statusline + f" Updated the screen in {toc - tic:0.8f} seconds "139 #stdscr.addstr(height-1, 0, '> Row {} (0-{})'.format(selectrow,TblLayout['numrows']-1).ljust(30))140 stdscr.addstr(height-1,0,statusline[:(width-1)].ljust(width-1))141def editdata(stdscr,startcol,startrow,selectrow,selectcol,mykey):142 #editstr = str(df.loc[selectrow][selectcol])143 curses.curs_set(1)144 returncode = ''145 editstr = "" + mykey146 charpos = 0 + len(mykey)147 docontinue = True148 displaycol = 2149 for i in range(startcol,selectcol):150 displaycol = displaycol + TblLayout['columnwidths'][i]+3151 cellwidth = TblLayout['columnwidths'][selectcol]152 stdscr.addstr(3+selectrow-startrow,displaycol,editstr.ljust(cellwidth),(curses.A_REVERSE | curses.A_BOLD))153 stdscr.move(3+selectrow-startrow,displaycol+charpos)154 while (docontinue):155 mykey = stdscr.get_wch()156 if (isinstance(mykey,int)):157 if ( (mykey == curses.KEY_BTAB) | (mykey == curses.KEY_UP) | (mykey == curses.KEY_DOWN) | (mykey == 410) ):158 docontinue = False159 returncode = mykey #Enter160 elif ( (mykey == curses.KEY_BACKSPACE) | (mykey == 127) ):161 if (charpos > 0):162 charpos = charpos - 1163 editstr = editstr[0:charpos]164 elif ( (mykey == '\n') | (mykey == '\t') ):165 docontinue = False166 returncode = mykey167 elif ( mykey == chr(27) ):168 editstr = str(df.iloc[selectrow,selectcol]) #Put original text back169 docontinue = False170 returncode = mykey171 else:172 if ( (mykey == chr(127)) | (mykey == '\b') ):173 if (charpos > 0):174 charpos = charpos - 1175 editstr = editstr[0:charpos]176 if (curses.ascii.iscntrl(mykey) == False): #Do not accept control characters177 editstr = editstr + mykey[0]178 charpos = charpos + 1179 if (charpos <= cellwidth):180 showstr = editstr[:cellwidth].ljust(cellwidth)181 showpos = charpos182 else:183 showstr = editstr[charpos-cellwidth:charpos]184 showpos = cellwidth185 stdscr.addstr(3+selectrow-startrow,displaycol,showstr,(curses.A_REVERSE | curses.A_BOLD))186 stdscr.move(3+selectrow-startrow,displaycol+showpos)187 df.iloc[selectrow,selectcol] = editstr188 curses.curs_set(0)189 return(returncode)190def main(stdscr):191 global df192 stdscr.clear()193 curses.curs_set(0)194 height,width = stdscr.getmaxyx()195 startrow = 0196 startcol = 0197 selectrow = 0198 selectcol = 0199 while(1):200 displayheader(stdscr,startcol,TblLayout['numrows'],height,width)201 displaydata(stdscr,startcol,startrow,startrow+height-5,selectrow,selectcol,height,width)202 mykey = stdscr.get_wch()203 returnkey = 0204 if (isinstance(mykey,int)):205 if (mykey == curses.KEY_NPAGE):206 selectrow = max(0,min(selectrow + (height-5-2),TblLayout['numrows']-1))207 elif (mykey == curses.KEY_PPAGE):208 selectrow = max(0,selectrow - (height-5-2))209 elif (mykey == curses.KEY_DOWN):210 selectrow = max(0,min(selectrow + 1,TblLayout['numrows']-1))211 elif (mykey == curses.KEY_UP):212 selectrow = max(0,selectrow - 1)213 elif (mykey == curses.KEY_BTAB):214 returnkey = curses.KEY_BTAB215 elif (mykey == curses.KEY_LEFT):216 selectcol = max(0,selectcol-1)217 elif (mykey == curses.KEY_RIGHT):218 selectcol = min(selectcol+1,TblLayout['numcols']-1)219 elif (mykey == curses.KEY_F2):220 if (TblLayout['numrows']>0):221 returnkey = editdata(stdscr,startcol,startrow,selectrow,selectcol,'')222 elif (mykey == curses.KEY_F4):223 df.to_csv(sys.argv[1],index=False)224 stdscr.addstr(height-1,0,"File saved as \"{}\", press a key to continue".format(sys.argv[1]).ljust(width-1))225 stdscr.getch()226 elif (mykey == 410): #resize227 returnkey = mykey228 else:229 stdscr.addstr(height-1, 30, 'You pressed #{}# '.format(mykey))230 #elif (mykey == ':'):231 # df.to_csv('out.csv',index=False)232 # curses.curs_set(1)233 # exit(0)234 elif (mykey == '\t'):235 returnkey = '\t'236 elif (mykey == '\n'):237 returnkey = '\n';238 elif (len(mykey)==1):239 if (ord(mykey)>31): #We will not match stuff like an escape character (27)240 if (TblLayout['numrows']>0):241 returnkey = editdata(stdscr,startcol,startrow,selectrow,selectcol,mykey)242 elif (ord(mykey)==23): #Ctrl-W243 df = pd.concat([df.head(selectrow), pd.DataFrame([[nan] * df.shape[1]], columns=df.columns), df.tail(TblLayout['numrows']-selectrow)], ignore_index=True)244 df.astype(str)245 TblLayout['numrows'] = df.shape[0]246 returnkey = 410 #Force resize247 elif (ord(mykey)==5): #Ctrl-E248 curses.curs_set(1)249 exit(0)250 elif (ord(mykey)==24): #Ctrl-X251 df = pd.concat([df.head(selectrow+1), pd.DataFrame([[nan] * df.shape[1]], columns=df.columns), df.tail(TblLayout['numrows']-selectrow-1)], ignore_index=True)252 df.astype(str)253 TblLayout['numrows'] = df.shape[0]254 selectrow = max(0,min(selectrow + 1,TblLayout['numrows']-1))255 returnkey = 410 #Force resize256 elif (ord(mykey)==4): #Ctrl-D257 if (TblLayout['numrows']>0):258 df = df.drop(df.index[[selectrow]])259 TblLayout['numrows'] = df.shape[0]260 selectrow = max(0,selectrow - 1)261 returnkey = 410 #Force resize262 selectrow = max(0,min(selectrow + 1,TblLayout['numrows']-1))263 #else:264 # stdscr.addstr(height-1, 30, 'You pressed #{}# '.format(ord(mykey)))265 #else:266 # stdscr.addstr(height-1, 30, 'You pressed #{}# '.format(mykey))267 #---------------------------------------------------------268 if (isinstance(returnkey,int)):269 if ( (returnkey == curses.KEY_DOWN) ):270 selectrow = min(selectrow + 1,TblLayout['numrows']-1)271 elif ( (returnkey == curses.KEY_UP) ):272 selectrow = max(0,selectrow - 1)273 elif (returnkey == curses.KEY_BTAB):274 if ( (selectcol == 0) & (selectrow > 0) ):275 selectcol = TblLayout['numcols']-1276 selectrow = selectrow - 1277 else:278 selectcol = max(0,selectcol-1)279 elif (returnkey == 410): #resize280 height,width = stdscr.getmaxyx()281 stdscr.clear()282 elif ( (returnkey == '\t') | (returnkey == '\n') ):283 if ( (selectcol == TblLayout['numcols']-1) & (selectrow < TblLayout['numrows']-1) ):284 selectcol = 0285 selectrow = selectrow + 1286 else:287 selectcol = min(selectcol+1,TblLayout['numcols']-1)288 #-----------------------------------------------------------289 startrow = getstartrow(startrow,selectrow,height)290 startcol = getstartcol(startcol,selectcol,width)291#--- Main programming code ---292if len(sys.argv) > 1:293 df = pd.read_csv(sys.argv[1],dtype=str)294else:295 print("Syntax: csvedit <filename>")296 exit(1)297TblLayout = {}298TblLayout['numcols'] = df.shape[1]299TblLayout['numrows'] = df.shape[0]300TblLayout['columnnames'] = df.columns301TblLayout['columnwidths'] = [COLUMN_LENGTH_DEFAULT]*TblLayout['numcols']302counter = 0303for column in df:304 TblLayout['columnwidths'][counter] = max(min(max(df[column].map(str).map(len).max(),len(column)),COLUMN_LENGTH_MAX),COLUMN_LENGTH_MIN)305 counter = counter + 1306os.environ.setdefault('ESCDELAY', '25')...

Full Screen

Full Screen

predict.py

Source:predict.py Github

copy

Full Screen

1# coding=utf-82import csv3import matplotlib.pyplot as plt4import numpy as np5from sklearn.model_selection import train_test_split6from sklearn.tree import DecisionTreeClassifier7from GenerateModel import type8import joblib9import pandas as pd10import pandas.plotting11import mglearn12import seaborn as sns13class PredictModel:14 def __init__(self):15 self.tree = None16 self.feature_name = None17 self.X_train = None18 self.y_train = None19 self.X_test = None20 self.y_test = None21 def loadFile(self, filename):22 with open(filename, "r") as f:23 reader = csv.reader(f)24 datalist = []25 ylist = []26 i = 027 for row in reader:28 selectRow = []29 if i == 0:30 # self.feature_name = np.array(row[:9] + row[41:42])31 selectRow.append(row[1])32 selectRow.append(row[2])33 selectRow.append(row[3])34 selectRow.append(row[4])35 selectRow.append(row[28])36 selectRow.append(row[32])37 selectRow.append(row[33])38 selectRow.append(row[34])39 selectRow.append(row[38])40 self.feature_name = np.array(selectRow)41 if i > 0:42 selectRow.append(type.Protocol.Type[row[1]])43 selectRow.append(type.Service.Type[row[2]])44 selectRow.append(type.Flag.Type[row[3]])45 selectRow.append(row[4])46 selectRow.append(row[28])47 selectRow.append(row[32])48 selectRow.append(row[33])49 selectRow.append(row[34])50 selectRow.append(row[38])51 datalist.append(selectRow)52 # datalist.append(row[:41])53 # datalist.append(row[:9] + row[41:42])54 # ylist.append(row[41:42])55 ylist.append(type.Attack.Type[row[41]])56 i += 157 X = np.array(datalist)58 y = np.array(ylist)59 self.X_train, self.X_test, self.y_train, self.y_test = \60 train_test_split(X, y, random_state=0)61 def loadTrainAndTestFile(self, trainFileName,62 testFileName):63 with open(trainFileName, "r") as f:64 reader = csv.reader(f)65 datalist = []66 ylist = []67 i = 068 for row in reader:69 selectRow = []70 if i == 0:71 selectRow.append(row[1])72 selectRow.append(row[2])73 selectRow.append(row[3])74 selectRow.append(row[4])75 selectRow.append(row[28])76 selectRow.append(row[32])77 selectRow.append(row[33])78 selectRow.append(row[34])79 selectRow.append(row[38])80 self.feature_name = np.array(selectRow)81 elif i > 0 and row[41] not in type.Attack.R2L \82 and row[41] not in type.Attack.U2R:83 selectRow.append(type.Protocol.Type[row[1]])84 selectRow.append(type.Service.Type[row[2]])85 selectRow.append(type.Flag.Type[row[3]])86 selectRow.append(row[4])87 selectRow.append(row[28])88 selectRow.append(row[32])89 selectRow.append(row[33])90 selectRow.append(row[34])91 selectRow.append(row[38])92 datalist.append(selectRow)93 if row[41] == "normal":94 ylist.append(0)95 elif row[41] in type.Attack.DOS:96 ylist.append(1)97 elif row[41] in type.Attack.PROBE:98 ylist.append(2)99 else:100 print("error (predict.py 110)")101 # ylist.append(type.Attack.Type[row[41]])102 i += 1103 self.X_train = np.array(datalist)104 self.y_train = np.array(ylist)105 with open(testFileName, "r") as f:106 reader = csv.reader(f)107 datalist = []108 ylist = []109 i = 0110 for row in reader:111 selectRow = []112 if i > 0 and row[41] not in type.Attack.R2L \113 and row[41] not in type.Attack.U2R:114 selectRow.append(type.Protocol.Type[row[1]])115 selectRow.append(type.Service.Type[row[2]])116 selectRow.append(type.Flag.Type[row[3]])117 selectRow.append(row[4])118 selectRow.append(row[28])119 selectRow.append(row[32])120 selectRow.append(row[33])121 selectRow.append(row[34])122 selectRow.append(row[38])123 datalist.append(selectRow)124 # ylist.append(type.Attack.Type[row[41]])125 if row[41] == "normal":126 ylist.append(0)127 elif row[41] in type.Attack.DOS:128 ylist.append(1)129 elif row[41] in type.Attack.PROBE:130 ylist.append(2)131 else:132 print("error (predict.py 145)")133 i += 1134 self.X_test = np.array(datalist)135 self.y_test = np.array(ylist)136 def train(self, depth, modelFileName):137 tree = DecisionTreeClassifier(random_state=10, max_depth=depth)138 tree.fit(self.X_train, self.y_train)139 joblib.dump(tree, "../model/" + modelFileName)140 train_accuracy = tree.score(self.X_train, self.y_train)141 test_accuracy = tree.score(self.X_test, self.y_test)142 print("Accuracy on training set: {:.3f}".format(train_accuracy))143 print("Accuracy on test set: {:.3f}".format(test_accuracy))144 def loadModel(self, modelFileName):145 self.tree = joblib.load(modelFileName)146 def predict(self, feature):147 feature[0][0] = type.Protocol.Type[feature[0][0]]148 label = self.tree.predict(feature)149 return label[0]150 def selectDepth(self, max_depth):151 neighbors_settings = range(1, max_depth)152 test_accuracys = []153 training_accuracys = []154 for i in neighbors_settings:155 tree = DecisionTreeClassifier(random_state=10, max_depth=i) # 13156 tree.fit(self.X_train, self.y_train)157 train_accuracy = tree.score(self.X_train, self.y_train)158 test_accuracy = tree.score(self.X_test, self.y_test)159 training_accuracys.append(train_accuracy)160 test_accuracys.append(test_accuracy)161 print("//////////////////////////" + str(i) + "//////////////////////////////")162 print("Accuracy on training set: {:.3f}".format(train_accuracy))163 print("Accuracy on test set: {:.3f}".format(test_accuracy))164 print("")165 plt.plot(neighbors_settings, training_accuracys, label="training accuracy")166 plt.plot(neighbors_settings, test_accuracys, label="test accuracy")167 plt.ylabel("Accuracy")168 plt.xlabel("n_neighbors")169 plt.legend()170 plt.show()171 def showGraph(self):172 X_train, X_test, y_train, y_test = train_test_split(173 self.X, self.y, random_state=0)174 iris = sns.load_dataset("iris")175 featur_dataframe = pd.DataFrame(X_train, columns=self.feature_name)176 g4 = sns.pairplot(featur_dataframe, hue="label")177 plt.show()178 print()179 # feature_dataframe = pd.DataFrame(X_train,columns=self.feature_name)180 # grr = pandas.plotting.scatter_matrix(feature_dataframe,181 # c=y_train, figsize=(15, 15),182 # marker="o", hist_kwds={"bins": 20},183 # s=60, alpha=.8, cmap=mglearn.cm3)184 # plt.show()185if __name__ == "__main__":186 trainModel = PredictModel()187 # trainModel.loadFile("../data/KDDTest+.csv")188 trainModel.loadTrainAndTestFile("../data/KDDTrain+.csv",189 "../data/KDDTest+.csv")190 # trainModel.showGraph()191 # trainModel.selectDepth(20)...

Full Screen

Full Screen

Exercise2.py

Source:Exercise2.py Github

copy

Full Screen

1import RPi.GPIO as GPIO2from time import sleep3import GPIO_EX4ROW0_PIN = 05ROW1_PIN = 16ROW2_PIN = 27ROW3_PIN = 38COL0_PIN = 49COL1_PIN = 510COL2_PIN = 611COL_NUM = 312ROW_NUM = 413g_preData = 014colTable = [COL0_PIN, COL1_PIN, COL2_PIN]15rowTable = [ROW0_PIN, ROW1_PIN, ROW2_PIN, ROW3_PIN]16LED_1 = 417LED_2 = 518LED_3 = 1519LED_4 = 1420LED_1_status = True21LED_2_status = True22LED_3_status = True23LED_4_status = True24def initKeypad():25 for i in range(0, COL_NUM):26 GPIO_EX.setup(colTable[i], GPIO_EX.IN)27 for i in range(0, ROW_NUM):28 GPIO_EX.setup(rowTable[i], GPIO_EX.OUT)29def selectRow(rowNum):30 for i in range(0, ROW_NUM):31 if rowNum == (i + 1):32 GPIO_EX.output(rowTable[i], GPIO_EX.HIGH)33 sleep(0.001)34 else:35 GPIO_EX.output(rowTable[i], GPIO_EX.LOW)36 sleep(0.001)37 return rowNum38def readCol():39 keypadstate = -140 for i in range(0, COL_NUM):41 inputKey = GPIO_EX.input(colTable[i])42 if inputKey:43 keypadstate = keypadstate + (i+2)44 sleep(0.5)45 return keypadstate46def readKeypad():47 global g_preData48 keyData = -149 50 runningStep = selectRow(1)51 row1Data = readCol()52 selectRow(0)53 sleep(0.001)54 if (row1Data != -1):55 keyData = row1Data56 57 if runningStep == 1:58 if keyData == -1:59 runningStep = selectRow(2)60 row2Data = readCol()61 selectRow(0)62 sleep(0.001)63 if (row2Data != -1):64 keyData = row2Data + 365 if runningStep == 2:66 if keyData == -1:67 runningStep = selectRow(3)68 row3Data = readCol()69 selectRow(0)70 sleep(0.001)71 if (row3Data != -1):72 keyData = row3Data +673 if runningStep == 3:74 if keyData == -1:75 runningStep = selectRow(4)76 row4Data = readCol()77 selectRow(0)78 sleep(0.001)79 if (row4Data != -1):80 if row4Data == 1:81 keyData = "*"82 elif row4Data == 2:83 keyData = 084 else:85 keyData = "#"86 if keyData == -1:87 return -188 if g_preData == keyData:89 g_preData = -190 return -191 g_preData = keyData92 print("\r\nKeypad Data : {}".format(keyData))93 return keyData94def LED_Initial():95 global LED_1_status, LED_2_status, LED_3_status, LED_4_status96 GPIO.setmode(GPIO.BCM)97 GPIO.setwarnings(False)98 GPIO.setup(LED_1, GPIO.OUT, initial=LED_1_status)99 GPIO.setup(LED_2, GPIO.OUT, initial=LED_2_status)100 GPIO.setup(LED_3, GPIO.OUT, initial=LED_3_status)101 GPIO.setup(LED_4, GPIO.OUT, initial=LED_4_status)102def LED_Conrtrol(LED_Num):103 global LED_1_status, LED_2_status, LED_3_status, LED_4_status104 if LED_Num == 1:105 if LED_1_status:106 GPIO.output(LED_1, GPIO.LOW)107 else:108 GPIO.output(LED_1, GPIO.HIGH)109 LED_1_status = not LED_1_status110 elif LED_Num == 2:111 if LED_2_status:112 GPIO.output(LED_2, GPIO.LOW)113 else:114 GPIO.output(LED_2, GPIO.HIGH)115 LED_2_status = not LED_2_status116 elif LED_Num == 3:117 if LED_3_status:118 GPIO.output(LED_3, GPIO.LOW)119 else:120 GPIO.output(LED_3, GPIO.HIGH)121 LED_3_status = not LED_3_status122 elif LED_Num == 4:123 if LED_4_status:124 GPIO.output(LED_4, GPIO.LOW)125 else:126 GPIO.output(LED_4, GPIO.HIGH)127 LED_4_status = not LED_4_status128 else:129 GPIO.output(LED_1, GPIO.LOW)130 GPIO.output(LED_2, GPIO.LOW)131 GPIO.output(LED_3, GPIO.LOW)132 GPIO.output(LED_4, GPIO.LOW)133 LED_1_status = False134 LED_2_status = False135 LED_3_status = False136 LED_4_status = False137def main():138 GPIO.setwarnings(False)139 GPIO.setmode(GPIO.BCM)140 initKeypad()141 LED_Initial()142 print("setup keypad pin")143 try:144 while True:145 keyData = readKeypad()146 if keyData != -1:147 LED_Conrtrol(keyData)148 except KeyboardInterrupt:149 GPIO.cleanup()150if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pyatom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful