def extractContours(segImg, checkImgBorders, h, w): print("Extracting contours...") t = StopWatch() contours, _ = cv2.findContours(segImg.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) maxi = 0 if checkImgBorders: contours = cleanSmallComponents(contours) if len(contours)==0: raise ContoursException("No contours found") if len(contours)==1: #if there is only one just send it back return [contours[0]] pos = -1 posactual = 0 maxinters = 0 posareas = [] for ctr in contours: inters, area = calculateIntersectionWithImageBorder(ctr[:,0], h, w) posareas.append(area) if ((inters>maxinters)): maxinters = inters pos = posactual posactual+=1 if pos>-1: posareas.pop(pos) contours.pop(pos) maxi = contours[posareas.index(max(posareas))] else: areas = [cv2.contourArea(ctr) for ctr in contours] maxi = contours[areas.index(max(areas))] if maxi.shape[0] < C.MINIMUM_LEAF_VALID_CONTOUR_POINT_NUMBER: raise ContoursException("No valid leaf found. Contours too small, most likely segmentation error.") t.stopAndPrint() return [maxi]
def cleanStem(segImg, h, w): print("Cleaning stem....") t = StopWatch() _, nComponents = ndimage.measurements.label(segImg) ''' def getContourAspectRatio(contour): _,_,w,h = cv2.boundingRect(contour) a = cv2.contourArea(contour) return float(w)/float(h) * a ''' kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(C.STEM_KERNEL_SIZE,C.STEM_KERNEL_SIZE)) th = topHat(segImg, kernel) contours, _ = cv2.findContours(th.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) n = len(contours) posactual = 0 while posactual < n: mask = segImg.copy() cv2.drawContours(mask, contours[posactual],-1,0,-1) _, nCComponents = ndimage.measurements.label(mask) if nCComponents == nComponents: #eliminate small contours, mostly garbage contours.pop(posactual) n = len(contours) else: posactual+=1 if contours == []: t.stopAndPrint() return segImg ars = [getContourAspectRatio(ctr) for ctr in contours] stem = contours[ars.index(max(ars))] cv2.drawContours(segImg, [stem],-1,0,-1) #deletethe stem from the segmentation #segImg = getBiggestComponent(segImg) * 255 #segImg = segImg.astype(np.uint8) t.stopAndPrint() return segImg
def extractHoCSNaive(self, segImg, contours, disks, circumferences): print("Extracting HCoS...") t = StopWatch() ys = contours[:,1] xs = contours[:,0] n = len(xs) nrad = 25 histAreas = [] #this will hold all histograms, 25 diff ones, one per radius histArcs = [] #this will hold all histograms, 25 diff ones, one per radius, for arcs for k in range(0,nrad): #calculate 25 diff areas imgBoundaryIncreased = self.increaseImageBundaries(segImg, disks[k]) #generates the same image with increased boundaries areas = [] #all areas from all point at certain disk radius arcs = [] for i in range(0, n): #go through every boundary point area, arc = self.findAreaAndArc(imgBoundaryIncreased, disks[k], circumferences[k], ys[i], xs[i]) arcs = arcs + [arc] areas = areas + [area] histArea, bin = np.histogram(areas, density=False, bins=21) histArea = normalize(np.float32(histArea)) histAreas.append(histArea) histArc, bin = np.histogram(arcs, density=False, bins=21) histArc = normalize(np.float32(histArc)) histArcs.append(histArc) ''' plt.bar(bin[:-1], histArc, width = 1) plt.xlim(min(bin), max(bin)) plt.show() ''' hcos = np.float32(np.concatenate(histAreas+histArcs)) t.stopAndPrint() return hcos
def __init__(self): self.gameInProgress = False self.direction = 0 self.timeout = 0 self.side = "" self.bounce = 0 self.LEFT = "left" self.RIGHT = "right" #player 1 is left #player 2 is right self.scoreP1 = 0 self.scoreP2 = 0 self.timer = StopWatch() self.newGame()
def train(self, sess, num_epochs, num_batches_per_epoch): """Method to actually run training given a session, and data. The train method is responsible for the main job of the trainer class. It takes a supervisor, session, training and validation data, number of epochs, and epoch size as input. It will write summaries and print reports. Args: sess: TF session to use for running the graph num_epochs: integer number of epochs of training to perform num_batches_per_epoch: integer number of batches in a single epoch Yields: None, after completing each epoch. Raises: eval_ff.TrainingDivergedException: when training loss gets above MAX_COST. This might be caused by bad initial weights or a large learning rate and/or momentum. """ gs = self.global_step.eval(sess) # if global_step > 0, resume training where we left off epoch_start, step_start = divmod(gs, num_batches_per_epoch) logger.info('Starting training at global_step=%d', gs) for epoch in range(epoch_start, num_epochs): sw = StopWatch() num_steps = num_batches_per_epoch - step_start for _ in pybar.BarGenerator(list(range(num_steps)), message='Epoch %d' % epoch): sw.start('step') gs, cur_cost = sess.run([self.global_step, self.train_op]) sw.stop('step') if (cur_cost > MAX_COST or cur_cost < self.min_cost or (cur_cost <= self.min_cost and not self.min_is_inclusive)): lower_bracket = '[' if self.min_is_inclusive else '(' msg = ( 'instantaneous training cost of %f is outside bounds %s%f, %f]' % (cur_cost, lower_bracket, self.min_cost, MAX_COST)) raise eval_ff.TrainingDivergedException(msg) examples_per_sec = float( self.mbsz * num_steps) / sw.timervalue('step') logger.info('gs=%d, epoch=%d, examples/second=%f', gs, epoch, examples_per_sec) yield epoch step_start = 0
def __init__(self, host=None, generate=False, soapStr=None, method=None, service=None, https=False, keyfile=None, certfile=None, proxy=None, proxyport=None, version=0): object.__init__(self) self.host = self.sanitizeHost(host) self.method = "" self.service = service self.requestTracker = [] self.version = version self.proxy = proxy self.proxyport = proxyport self.https = https self.alterHost = False self.operationTimeout = False self.soapVersion = "1.1" # create httplib connection if (self.proxy and self.proxyport and https and (keyfile is None and certfile is None)): ''' Proxy servers don't seem to like this. And this prog seems to hang when that happens. Researching it shows that its a Python issue. ''' print "Due to a limitation within Python, \nHTTPS requests through", print "Proxy servers are not fully supported yet. No guarantees of", print "this functionality working ......" self.ws = httplib.HTTPSConnection(self.proxy, self.proxyport) elif (self.proxy and self.proxyport and not https and (keyfile is None and certfile is None)): self.ws = httplib.HTTPConnection(self.proxy, self.proxyport) elif (https and (keyfile is not None and certfile is not None)): ''' According to http://docs.python.org/lib/module-httplib.html key_file is the name of a PEM formatted file that contains your private key. cert_file is a PEM formatted certificate chain file. Warning: This does not do any certificate verification ''' self.ws = httplib.HTTPSConnection(self.host, key_file=keyfile, cert_file=certfile) elif (https and (keyfile is None and certfile is None)): self.ws = httplib.HTTPSConnection(self.host) else: self.ws = httplib.HTTPConnection(self.host) self.response = self.responseVersion = self.responseCode = self.responseMsg = \ self.responseHeaders = self.responseData = self.basicAuthUser = self.basicAuthPass = \ self.action = None self.sw = StopWatch.StopWatch() if generate == True and method: self.method = method # we will generate XML here, (self.method), eventually elif generate == False and soapStr: # xml is passed in via a StringIO object if type(soapStr) is dict: self.soapStr = soapStr.keys()[0].getvalue().strip() elif type( soapStr ) is str: # dont for XDos attacks as XML payload is a String self.soapStr = soapStr.strip() else: self.soapStr = str(soapStr.getvalue().strip())
def __init__(self, folder, output, iterations, tiles, processors, noise, noiseH, noiseL): stopWatch = StopWatch.stopWatch() #Start the Stopwatch #Get a list of files to process and then process 'Destriping for each. for __file in glob.glob(os.path.join(folder, '*.TIF')): imageName = os.path.basename(__file) #Weighting for the moving window and variable to define window size. windowSize = 5 windowScalingTop = numpy.array([(1, 1, 1, 1, 1), (0, 1, 2, 1, 0), (0, 0, 1, 1, 0), (0, 1, 2, 1, 0), (1, 1, 1, 1, 1)]) windowScalingBot = numpy.array([(1, 1, 1, 1, 1), (0, 0, 2, 1, 0), (0, 0, 1, 0, 0), (0, 1, 2, 1, 0), (1, 1, 1, 1, 1)]) print '-------------------------------------' print 'Image:', os.path.basename(__file) print 'Output Folder:', output print 'Job started at:', stopWatch.getCurrentTime() print ' Number of Iterations:', iterations print ' Number of Tiles:', tiles print ' Number of Processors:', processors if noise == 1: print ' Noise Added - Yes (scaling ', noiseL, 'to', noiseH, ')' else: print ' Noise Added - No (scaling ', noiseL, 'to', noiseH, ')' print 'Scaling factors for the moving window' print 'Top of stripe scaling:' print windowScalingTop print '' print 'Bottom of stripe scaling:' print windowScalingBot print '-------------------------------------' __image__ = Image.Image( __file) #Create and 'Image' From the input file rows = __image__.getRows() #Find the number of rows in the image. cols = __image__.getColumns( ) #Find the number of rows in the image. tileSize = int(math.ceil(float(cols) / float(tiles))) # Call back to start a tile for destriping. This will be sent out as # a package to a processer when one is available. def __callbackDestripe(CB_currentTile, CB_tileSize, CB_rows, CB_windowSize, CB_windowScalingTop, CB_windowScalingBot, CB_iterations, CB_noise, CB_noiseH, CB_noiseL): result = LandsatDestripe.Destripe().runDestripe( CB_currentTile, CB_tileSize, CB_rows, CB_windowSize, CB_windowScalingTop, CB_windowScalingBot, CB_iterations, CB_noise, CB_noiseH, CB_noiseL) return result ppservers = () #Start the job server. job_server = pp.Server( ppservers=ppservers, ncpus=processors ) # Creates jobserver with automatically detected number of workers # For each tile, send out a new job for destriping. jobs = [] #List to keep the results of a job. jobID = 0 tile = range(0, cols, tileSize) while 1: if len(jobs) < (processors * 2) and jobID < tiles: try: currentTile = __image__.getTile(tile[jobID], tileSize) jobs.append((job_server.submit(__callbackDestripe, ( currentTile, tileSize, rows, windowSize, windowScalingTop, windowScalingBot, iterations, noise, noiseH, noiseL, ), (), ( "numpy", "LandsatDestripe", )), jobID)) print ' ', jobID, '- Tile segment', tile[ jobID], '-', tile[ jobID] + tileSize, 'started at:', stopWatch.getEllapsedTime( ) except: print 'ERROR Retrieving Tile' jobID += 1 if len(jobs) >= (processors * 2): for job in jobs: if job[0].finished: popped = jobs.pop(jobs.index(job)) __image__.returnTile(popped[0](), tile[popped[1]], tileSize) print ' Returned tile ', popped[ 1], 'at', stopWatch.getEllapsedTime() if jobID == tiles: while jobs: for job in jobs: if job[0].finished: popped = jobs.pop(jobs.index(job)) __image__.returnTile(popped[0](), tile[popped[1]], tileSize) print ' Returned tile ', popped[ 1], 'at', stopWatch.getEllapsedTime() break print '' job_server.print_stats() __image__.saveTiff(output + '\\' + imageName) #Saves the new image. del jobs, jobID, tile, __image__, cols, rows, tileSize, imageName, job_server.destroy() print 'Job completed at:', stopWatch.getCurrentTime() print 'Elapsed time:', stopWatch.getEllapsedTime() raw_input("Processing Complete. Press Any Key.")
def __init__(self, root): self.urlStr = StringVar() self.urlStr.set("") self.root = root root.title("Scan a URL :") self.Scanlbl = Label(root, text="Enter the url : ") self.Scanlbl.pack() # register a function into the window validate_command = root.register(self.validate) self.inputText = Entry(root, width=50, validate="key", validatecommand=(validate_command, '%P')) self.inputText.pack() self.mylbl = Label(root, text="The Url is: ") self.mylbl.pack() Label(root, textvariable=self.urlStr).pack() self.sw = StopWatch(root) self.sw.pack(side=TOP) BtnsFrame = Frame(root) BtnsFrame.pack() self.S1Btn = Button(BtnsFrame, text='StartT', command=self.sw.Start) self.S1Btn.bind("<Button-1>", self.StartTheScan) self.S1Btn.pack(side=LEFT) self.S2Btn = Button(BtnsFrame, text='Stop', command=self.sw.Stop) self.S2Btn.bind("<Button-1>", self.StopTheScan) self.S2Btn.pack(side=LEFT) Button(BtnsFrame, text='Quit', command=root.quit).pack(side=LEFT) frameListBx = Frame(root) frameListBx.pack() Label(root, text="The result of the scan is :").pack() self.OutputListBx = Listbox(frameListBx, width="100") self.OutputListBx.pack(side="left", fill="y") scrollbar = Scrollbar(frameListBx, orient="vertical") scrollbar.config(command=self.OutputListBx.yview) scrollbar.pack(side="right", fill="y") self.OutputListBx.config(yscrollcommand=scrollbar.set) MODES = [("InnerLinks", "OnlyInner"), ("OuterLinks", "OnlyOuter"), ("BothInnerNOuterLinks", "Both")] Label(root, text="Choose scan mode :").pack() self.con = StringVar() self.con.set("OnlyInner") # initialize for text, mode in MODES: self.b = Radiobutton(root, text=text, variable=self.con, value=mode, indicatoron=0, width=30) self.b.pack() self.modebtn = Button(root, text="Print", command=lambda: print(self.con.get())) self.modebtn.pack()
class ScanGui: def __init__(self, root): self.urlStr = StringVar() self.urlStr.set("") self.root = root root.title("Scan a URL :") self.Scanlbl = Label(root, text="Enter the url : ") self.Scanlbl.pack() # register a function into the window validate_command = root.register(self.validate) self.inputText = Entry(root, width=50, validate="key", validatecommand=(validate_command, '%P')) self.inputText.pack() self.mylbl = Label(root, text="The Url is: ") self.mylbl.pack() Label(root, textvariable=self.urlStr).pack() self.sw = StopWatch(root) self.sw.pack(side=TOP) BtnsFrame = Frame(root) BtnsFrame.pack() self.S1Btn = Button(BtnsFrame, text='StartT', command=self.sw.Start) self.S1Btn.bind("<Button-1>", self.StartTheScan) self.S1Btn.pack(side=LEFT) self.S2Btn = Button(BtnsFrame, text='Stop', command=self.sw.Stop) self.S2Btn.bind("<Button-1>", self.StopTheScan) self.S2Btn.pack(side=LEFT) Button(BtnsFrame, text='Quit', command=root.quit).pack(side=LEFT) frameListBx = Frame(root) frameListBx.pack() Label(root, text="The result of the scan is :").pack() self.OutputListBx = Listbox(frameListBx, width="100") self.OutputListBx.pack(side="left", fill="y") scrollbar = Scrollbar(frameListBx, orient="vertical") scrollbar.config(command=self.OutputListBx.yview) scrollbar.pack(side="right", fill="y") self.OutputListBx.config(yscrollcommand=scrollbar.set) MODES = [("InnerLinks", "OnlyInner"), ("OuterLinks", "OnlyOuter"), ("BothInnerNOuterLinks", "Both")] Label(root, text="Choose scan mode :").pack() self.con = StringVar() self.con.set("OnlyInner") # initialize for text, mode in MODES: self.b = Radiobutton(root, text=text, variable=self.con, value=mode, indicatoron=0, width=30) self.b.pack() self.modebtn = Button(root, text="Print", command=lambda: print(self.con.get())) self.modebtn.pack() @multitasking.task def StartTheScan(self, event=""): try: print("Starting !!") if self.urlStr.get() != "": crawl(self.urlStr.get()) if self.con.get() == "OnlyInner": for n in range(len(internal_urls)): self.OutputListBx.insert(END, list(internal_urls)[n]) elif self.con.get() == "OnlyOuter": for n in range(len(external_urls)): self.OutputListBx.insert(END, list(external_urls)[n]) else: # - Both for n in range(len(internal_urls)): self.OutputListBx.insert(END, list(internal_urls)[n]) for n in range(len(external_urls)): self.OutputListBx.insert(END, list(external_urls)[n]) print("[+] Total External links:", len(external_urls)) print("[+] Total Internal links:", len(internal_urls)) print("[+] Total:", len(external_urls) + len(internal_urls)) except ValueError: print(ValueError) @multitasking.task def StopTheScan(self, event=""): print("Stoping !!") StopCrawl() def validate(self, new_text): try: if new_text == "": self.urlStr.set("") return True fl = str(new_text) self.urlStr.set(fl) return True except ValueError: return False
class GameState: def __init__(self): self.gameInProgress = False self.direction = 0 self.timeout = 0 self.side = "" self.bounce = 0 self.server = "" self.p1name = "" self.p2name = "" self.LEFT = "left" self.RIGHT = "right" #player 1 is left #player 2 is right self.scoreP1 = 0 self.scoreP2 = 0 self.timer = StopWatch() self.newGame() def tick(self): # print(timer.get_elapsed_time()) if self.timer.isRunning(): if self.timer.get_elapsed_time() >= 3: if self.side == self.LEFT: print('\a') print('\a') self.scoreP2 += 1 else: print('\a') self.scoreP1 += 1 self.timer.reset() #timeout has expired return self.scoreP1, self.scoreP2 def setMetaData(self, server, p1name, p2name): self.server = server self.p1name = p1name self.p2name = p2name def addBounce(self): self.bounce += 1 def inPlay(self): return self.timer.get_elapsed_time != 0 def getSide(self): return self.side def getHighestScore(self): if self.scoreP1 >= self.scoreP2: return self.scoreP1 else: return self.scoreP2 def updateSide(self, newSide): # print(newSide) if newSide != self.side: self.bounce = 0 self.side = newSide self.timer.restart() def newGame(self): self.side = self.LEFT #setup player sides #player 1 left side #player 2 right side print("start a new game") def endGame(self): r = requests.post("http://" + self.server + "/match?p1name=" + self.p1name + "&p2name=" + self.p2name) y = json.loads(r.text) theID = y["id"] graduation = requests.post("http://" + self.server + "/match/" + str(theID) + "?p1score=" + str(self.scoreP1) + "&p2score=" + str(self.scoreP2)) print("Game ended!")
def __init__ (self, folder, output, iterations, tiles, processors, noise, noiseH, noiseL): stopWatch = StopWatch.stopWatch() #Start the Stopwatch #Get a list of files to process and then process 'Destriping for each. for __file in glob.glob (os.path.join (folder, '*.TIF')): imageName = os.path.basename(__file) #Weighting for the moving window and variable to define window size. windowSize = 5 windowScalingTop = numpy.array ([(1,1,1,1,1), (0,1,2,1,0), (0,0,1,1,0), (0,1,2,1,0), (1,1,1,1,1)]) windowScalingBot = numpy.array ([(1,1,1,1,1), (0,0,2,1,0), (0,0,1,0,0), (0,1,2,1,0), (1,1,1,1,1)]) print '-------------------------------------' print 'Image:' , os.path.basename(__file) print 'Output Folder:' , output print 'Job started at:' , stopWatch.getCurrentTime() print ' Number of Iterations:' , iterations print ' Number of Tiles:', tiles print ' Number of Processors:', processors if noise == 1: print ' Noise Added - Yes (scaling ', noiseL, 'to', noiseH, ')' else: print ' Noise Added - No (scaling ', noiseL, 'to', noiseH, ')' print 'Scaling factors for the moving window' print 'Top of stripe scaling:' print windowScalingTop print '' print 'Bottom of stripe scaling:' print windowScalingBot print '-------------------------------------' __image__ = Image.Image(__file) #Create and 'Image' From the input file rows = __image__.getRows() #Find the number of rows in the image. cols = __image__.getColumns() #Find the number of rows in the image. tileSize = int(math.ceil(float(cols) / float(tiles))) # Call back to start a tile for destriping. This will be sent out as # a package to a processer when one is available. def __callbackDestripe (CB_currentTile, CB_tileSize, CB_rows, CB_windowSize, CB_windowScalingTop, CB_windowScalingBot, CB_iterations, CB_noise, CB_noiseH, CB_noiseL): result = LandsatDestripe.Destripe().runDestripe(CB_currentTile, CB_tileSize, CB_rows, CB_windowSize, CB_windowScalingTop, CB_windowScalingBot, CB_iterations, CB_noise, CB_noiseH, CB_noiseL) return result ppservers = () #Start the job server. job_server = pp.Server(ppservers=ppservers,ncpus=processors) # Creates jobserver with automatically detected number of workers # For each tile, send out a new job for destriping. jobs = [] #List to keep the results of a job. jobID = 0 tile = range (0, cols, tileSize); while 1: if len(jobs) < (processors*2) and jobID < tiles: try: currentTile = __image__.getTile(tile[jobID], tileSize) jobs.append((job_server.submit(__callbackDestripe, (currentTile, tileSize, rows, windowSize, windowScalingTop, windowScalingBot, iterations, noise, noiseH, noiseL,), (), ("numpy", "LandsatDestripe",)), jobID)) print ' ', jobID, '- Tile segment', tile[jobID] , '-' , tile[jobID]+tileSize, 'started at:' , stopWatch.getEllapsedTime() except: print 'ERROR Retrieving Tile' jobID += 1 if len(jobs) >= (processors*2): for job in jobs: if job[0].finished: popped = jobs.pop(jobs.index(job)) __image__.returnTile(popped[0](), tile[popped[1]], tileSize) print ' Returned tile ', popped[1], 'at' , stopWatch.getEllapsedTime() if jobID == tiles: while jobs: for job in jobs: if job[0].finished: popped = jobs.pop(jobs.index(job)) __image__.returnTile(popped[0](), tile[popped[1]], tileSize) print ' Returned tile ', popped[1], 'at' , stopWatch.getEllapsedTime() break print '' job_server.print_stats() __image__.saveTiff(output + '\\' + imageName) #Saves the new image. del jobs, jobID, tile, __image__, cols, rows, tileSize, imageName, job_server.destroy() print 'Job completed at:', stopWatch.getCurrentTime() print 'Elapsed time:', stopWatch.getEllapsedTime() raw_input ("Processing Complete. Press Any Key.")
def testTimer(): stopWatch = StopWatch.StopWatch() print '-----------Start StopWatch Test-----------' assert round(stopWatch.getElapsedTime(), 1) == 0.0 print '1. getElapsedTime = 0.00 | %.2f' % stopWatch.getElapsedTime() stopWatch.reset() assert round(stopWatch.getElapsedTime(), 1) == 0.0 print '2. reset + getElapsedTime = 0.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(1) assert round(stopWatch.getElapsedTime(), 1) == 1.0 print '3. start + sleep(1) + getElapsedTime = 1.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.pause() time.sleep(1) assert round(stopWatch.getElapsedTime(), 1) == 1.0 print '4. pause + sleep(1) + getElapsedTime = 1.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(2) assert round(stopWatch.getElapsedTime(), 1) == 3.0 print '5. start + sleep(2) + getElapsedTime = 3.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.pause() time.sleep(1) assert round(stopWatch.getElapsedTime(), 1) == 3.0 print '6. pause + sleep(1) + getElapsedTime = 3.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(3) stopWatch.pause() assert round(stopWatch.getElapsedTime(), 1) == 6.0 print '7. start + sleep(3) + pause + getElapsedTime = 6.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(2.5) assert round(stopWatch.getElapsedTime(), 1) == 8.5 print '8. start + sleep(2.5) + getElapsedTime = 8.50 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.pause() assert round(stopWatch.getElapsedTime(), 1) == 8.5 print '9. pause + getElapsedTime = 8.50 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(1.2) stopWatch.pause() assert round(stopWatch.getElapsedTime(), 1) == 9.7 print '10. start + sleep(1.2) + pause + getElapsedTime = 9.7 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(1.3) assert round(stopWatch.getElapsedTime(), 1) == 11.0 print '11. start + sleep(1.3) + getElapsedTime = 11.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(2) assert round(stopWatch.getElapsedTime(), 1) == 13.0 print '12. start + sleep(2) + getElapsedTime = 13.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.reset() assert round(stopWatch.getElapsedTime(), 1) == 0.0 print '13. reset + getElapsedTime = 0.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.reset() time.sleep(2) assert round(stopWatch.getElapsedTime(), 1) == 2.0 print '14. reset + sleep(2) + getElapsedTime = 2.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.pause() assert round(stopWatch.getElapsedTime(), 1) == 2.0 print '15. pause + getElapsedTime = 2.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.reset() time.sleep(2) assert round(stopWatch.getElapsedTime(), 1) == 0.0 print '16. reset + getElapsedTime = 0.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.start() time.sleep(3) assert round(stopWatch.getElapsedTime(), 1) == 3.0 print '17. start + sleep(3) + getElapsedTime = 3.00 | %.2f' % stopWatch.getElapsedTime( ) stopWatch.reset() assert round(stopWatch.getElapsedTime(), 1) == 0.0 print '18. reset + getElapsedTime = 0.00 | %.2f' % stopWatch.getElapsedTime( ) time.sleep(2) assert round(stopWatch.getElapsedTime(), 1) == 2.0 print '19. sleep(2) + getElapsedTime = 2.00 | %.2f' % stopWatch.getElapsedTime( ) time.sleep(1) stopWatch.pause() assert round(stopWatch.getElapsedTime(), 1) == 3.0 print '19. sleep(1) + pause + getElapsedTime = 3.00 | %.2f' % stopWatch.getElapsedTime( ) time.sleep(1) stopWatch.pause() assert round(stopWatch.getElapsedTime(), 1) == 3.0 print '20. sleep(1) + pause + getElapsedTime = 3.00 | %.2f' % stopWatch.getElapsedTime( ) print '-----------StopWatch Test Finished-----------'
class GameState: def __init__(self): self.gameInProgress = False self.direction = 0 self.timeout = 0 self.side = "" self.bounce = 0 self.LEFT = "left" self.RIGHT = "right" #player 1 is left #player 2 is right self.scoreP1 = 0 self.scoreP2 = 0 self.timer = StopWatch() self.newGame() def tick(self): # print(timer.get_elapsed_time()) if self.timer.isRunning(): if self.timer.get_elapsed_time() >= 3: if self.side == self.LEFT: print('\a') print('\a') self.scoreP2 += 1 else: print('\a') self.scoreP1 += 1 self.timer.reset() #timeout has expired return self.scoreP1, self.scoreP2 def addBounce(self): self.bounce += 1 def inPlay(self): return self.timer.get_elapsed_time != 0 def getSide(self): return self.side def updateSide(self, newSide): # print(newSide) if newSide != self.side: self.bounce = 0 self.side = newSide self.timer.restart() def newGame(self): self.side = self.LEFT #setup player sides #player 1 left side #player 2 right side print("start a new game") def endGame(self): print("end a game")