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 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 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): 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 __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, 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()
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-----------'