def run(self, argv): self.banner() try: opts, args = getopt.getopt(argv, self.short, self.long) except getopt.GetoptError: self.usage() sys.exit(-1) for opt, arg in opts: if opt in ("-h", "--help"): self.usage() sys.exit(0) elif opt in ("-s", "--server"): self.servermode = 1 elif opt in ("-c", "--client"): self.clientmode = 1 elif opt in ("--check"): self.checkmode = 1 elif opt in ("--config"): self.configfile = arg elif opt in ("--split"): self.splitmode = 1 elif opt in ("--verbose"): try: self.verbosity = int(arg) except: common.internal_print( "Invalid verbose value: {0}".format(arg), -1) sys.exit(-1) if not common.get_privilege_level(): common.internal_print( "The tool needs superuser or admin privileges. Run as root or Administrator.", -1) sys.exit(-1) # set the servermode when it was not specified expicitly if (not self.clientmode and not self.checkmode): self.servermode = 1 # checking for the config file if not os.path.isfile(self.configfile): common.internal_print("config file missing!", -1) sys.exit(-1) # Looking for and parsing config file. common.internal_print("Parsing config file") config = ConfigParser.ConfigParser() try: config.read(self.configfile) except: common.internal_print( "Invalid or malformed configuration file specified", -1) sys.exit(-1) # sanity check on configuration, exit on error if not common.config_sanity_check(config, (self.servermode)): sys.exit(-1) # load authentication module auth_module = self.authentication.load_auth_module(config) #sanity check for the auth module if not auth_module.sanity_check(config): sys.exit(-1) if self.splitmode: self.scope = common.parse_scope_file(config.get("Global", "scope")) if self.scope == []: common.internal_print( "Split tunnelling mode enabled, but no scope was defined or entries were invalid", -1) sys.exit(-1) # Check system config for routing. If the OS was not set up for IP # forwarding then we need to exit. if self.servermode: if not common.check_router_settings(config): sys.exit(-1) # Loading modules from modules/ directory # 1. listing and loading all modules except forbidden ones common.internal_print("Loading all modules from 'modules' directory") for module in os.listdir("./modules/"): if module == '__init__.py' or module[-3:] != '.py' or ( module[:-3] in self.forbidden_modules): continue module_list = __import__("modules." + module[:-3], locals(), globals()) modules = [] for m in dir(module_list): # 2. going thru all the modules if m != 'Generic_module' and m[:2] != "__": module_attributes = getattr(module_list, m) # 3. get the classes from the modules module_classes = [ c for c in module_attributes.__dict__.values() if inspect.isclass(c) ] # 4. select classes that are XFLTReaT modules real_modules = [ c for c in module_classes if (issubclass(c, Generic_module) and ( c not in self.forbidden_modules_instance)) ] for r in real_modules: # 5. actual instantiation of a module modules.append(r()) # if the module is enabled from config, we store it in modules_enabled[] modules_enabled = [] for m in modules: enabled = "no" # is there any section in the config for the module? if not config.has_section(m.get_module_configname()): common.internal_print( "No section in config for module: {0}".format( m.get_module_configname()), -1) continue # is the 'enabled' option there for the module? if not config.has_option(m.get_module_configname(), "enabled"): common.internal_print( "No option 'enabled' in config for module: {0}".format( m.get_module_configname()), -1) sys.exit(-1) enabled = config.get(m.get_module_configname(), "enabled") if enabled == "yes": # looks like the module is enabled, adding to modules_enabled[] modules_enabled.append(m) # check if more than one module is enabled for client mode if self.clientmode and (len(modules_enabled) > 1): common.internal_print( "In client mode only one module can be used.", -1) sys.exit(-1) if not len(modules_enabled): common.internal_print("No modules were enabled in configuration", -1) sys.exit(-1) # One Interface to rule them all, One Interface to find them, # One Interface to bring them all and in the darkness bind them common.internal_print("Setting up interface") interface = Interface() # Setting up interface related things for server mode if self.servermode: server_tunnel = interface.tun_alloc( config.get("Global", "serverif"), interface.IFF_TUN | interface.IFF_NO_PI) interface.set_ip_address(config.get("Global", "serverif"), config.get("Global", "serverip"), config.get("Global", "serverip"), config.get("Global", "servernetmask")) interface.set_mtu(config.get("Global", "serverif"), int(config.get("Global", "mtu"))) # start thread with socket-interface related pipes ps = PacketSelector(server_tunnel) ps.start() # Setting up interface related things for client mode if self.clientmode: client_tunnel = interface.tun_alloc( config.get("Global", "clientif"), interface.IFF_TUN | interface.IFF_NO_PI) interface.set_ip_address(config.get("Global", "clientif"), config.get("Global", "clientip"), config.get("Global", "serverip"), config.get("Global", "clientnetmask")) if not self.splitmode: interface.set_default_route( config.get("Global", "remoteserverip"), config.get("Global", "clientip"), config.get("Global", "serverip")) else: interface.set_split_route(self.scope, config.get("Global", "serverip")) interface.set_mtu(config.get("Global", "clientif"), int(config.get("Global", "mtu"))) common.internal_print("Please use CTRL+C to exit...") module_threads = [] module_thread_num = 0 for m in modules_enabled: # Executing module in server mode if self.servermode: module_thread_num = module_thread_num + 1 if m.__init_thread__(module_thread_num, config, server_tunnel, ps, auth_module, self.verbosity): m.start() module_threads.append(m) # Executing module in check mode if self.checkmode: interface.check_default_route() if m.__init_thread__(0, config, None, None, None, self.verbosity): try: m.check() except KeyboardInterrupt: pass # Executing module in client mode if self.clientmode: try: remoteserverip = config.get("Global", "remoteserverip") if not config.has_section(m.get_module_configname()): common.internal_print( "No section in config for module: {0}".format( m.get_module_configname()), -1) continue # if the module requires an indirect connection (proxy, # dns) then we need to amend the routing table intermediate_hop = m.get_intermediate_hop(config) if intermediate_hop and (not self.splitmode): remoteserverip = intermediate_hop interface.set_intermediate_route( config.get("Global", "remoteserverip"), remoteserverip) # init "thread" for client mode, this will not be run in a thread. if m.__init_thread__(0, config, client_tunnel, None, auth_module, self.verbosity): # run in client mode m.connect() # client finished, closing down tunnel and restoring routes interface.close_tunnel(client_tunnel) if self.splitmode: interface.del_split_route( self.scope, config.get("Global", "serverip")) else: interface.restore_routes( remoteserverip, config.get("Global", "clientip"), config.get("Global", "serverip")) except KeyboardInterrupt: # CTRL+C was pushed interface.close_tunnel(client_tunnel) if self.splitmode: interface.del_split_route( self.scope, config.get("Global", "serverip")) else: interface.restore_routes( remoteserverip, config.get("Global", "clientip"), config.get("Global", "serverip")) pass except socket.error as e: # socket related error interface.close_tunnel(client_tunnel) if self.splitmode: interface.del_split_route( self.scope, config.get("Global", "serverip")) else: interface.restore_routes( remoteserverip, config.get("Global", "clientip"), config.get("Global", "serverip")) if e.errno == errno.ECONNREFUSED: common.internal_print( "Socket does not seem to answer.", -1) else: common.internal_print( "Socket died, probably the server went down. ({0})" .format(e.errno), -1) except: interface.close_tunnel(client_tunnel) if self.splitmode: interface.del_split_route( self.scope, config.get("Global", "serverip")) else: interface.restore_routes( remoteserverip, config.get("Global", "clientip"), config.get("Global", "serverip")) raise # No modules are running if not module_threads: common.internal_print("Exiting...") if self.servermode: ps.stop() else: try: time.sleep(0.5) common.internal_print("Please use CTRL+C to exit...") # found no better solution to keep the main thread and catch CTRL+C # if you know any, you know how to tell me ;) while True: time.sleep(1000) except KeyboardInterrupt: common.internal_print("Interrupted. Exiting...") ps.stop() for t in module_threads: t.stop() # give one sec to clean up for modules, otherwise some objects just # disapper and cannot be closed properly like the tunnel interface try: time.sleep(1.0) except KeyboardInterrupt: common.internal_print("Are you really this impatient????", -1) pass
] # conductor = gdspy.Polygon(cond_rem[0],2) # poly_cell.add(conductor) for i in range(0, len(cond_rem)): #poly_cell.add(gdspy.Polygon(cav[i],1)) remove = gdspy.Polygon(cond_rem[i], cond_layer) substrate = gdspy.fast_boolean(substrate, remove, 'not', precision=1e-9, max_points=1000, layer=sub_layer) poly_cell.add(substrate) # cav_cond = [rs.rect(wc, lcav2,cav_x0+gc, cav_y0)] # cav_cond += [rs.halfarc(rlow+gc,wc,cav_x0+rlow+wc+2*gc,cav_y0,orientation='S')] # cav_cond += [rs.rect(wc, lcav1,cav_x0+rlow+wc+3*gc+rlow, cav_y0)] # for i in range(0,len(cav_cond)): # #poly_cell.add(gdspy.Polygon(cav[i],1)) # cavity = gdspy.Polygon(cav_cond[i],1) # poly_cell.add(cavity) ########################################################################### # Make gds file and open up klayout inter = Interface() inter.klayout(layout_file)
# File: main # Description: starts the api # Copyright (c) 2013 Wayne Moulden ### # # # import sys from interface import Interface from thegamesdb import theGamesDB if __name__ == "__main__": running = True menu = True gui = Interface() scraper = theGamesDB() # Read the Platform List from the API p_list = scraper.readUrl('GetPlatformsList.php') proot = scraper.readXML(p_list) g_list = scraper.menuXML(proot, 'Platform') # Program loop (Unrestricted) while running: # Draw the table while menu: g_id = gui.draw_table(g_list) # check the user input if g_id: if g_id == 'Q' or g_id == 'q':
def create(self): tree = Interface() tree.main_menu()
from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl, QObject from interface import Interface from ImageProviders import PyplotImageProvider, CvImageProvider import matplotlib.pyplot as plt if __name__ == '__main__': app = QApplication(sys.argv) appEngine = QQmlApplicationEngine() context = appEngine.rootContext() appEngine.load(QUrl('prairie-tool-qml/main.qml')) root = appEngine.rootObjects()[0] # Register python classes with qml interface = Interface(app, context, root, appEngine) context.setContextProperty('iface', interface) root.show() try: apcode = app.exec_() except: print('there was an issue') finally: sys.exit(apcode)
def start(): interface = Interface()
## Règles et moteur from xml.etree.ElementTree import parse, XML from ordre0.moteur import Moteur ## Triage du mode d'opération if argv[1] == "interactive": from interface import Interface try: ## Analyser la base de connaissances en entrée et ## initialiser l'application là-dessus application = Interface() except IndexError: application = Interface() application.mainloop() elif argv[1] in {"avant", "arriere"}: from sys import stdin, stdout ## À compléter en fonction du modèle qui sera adopté else: msg(usage) exit(1)
def __init__(self, slaveAddress, interfaceLock): self.memory = Memory() self.sif = Interface(slaveAddress, interfaceLock) self.temperatureChangeRateCperSec = 1 / 60
import ipkiss3.all as i3 # from picazzo3.container.transition_ports import AutoTransitionPorts # from picazzo3.filters.mmi.cell import MMI2x2Tapered from MMI22 import my_dc from interface import Interface dc_10 = my_dc(gap_inc_vec=[390, 398, 406], name="ring1") dc_10_layout = dc_10.Layout() # dc_10_layout.visualize(annotate=True) # dc_10_layout.write_gdsii("DC_V4.gds") # # Interface(pocket= False, tilt=False).Layout.view.write_gdsii("interface1.gds") dc20 = Interface(name="haha", pocket= False, tilt=False) dc20_layout = dc20.Layout() # dc20.visualize() print("Done writing Release.gds!") dc_15 = my_dc(gap_inc_vec=[390, 398, 406], name="ring2") dc_15_layout = dc_15.Layout() pr = PlaceAndAutoRoute( child_cells={ "dc1": dc_10, "dc2": dc_15, "dc3": dc20, # "dc3": dc_20,
#!/usr/bin/env python3 from tkinter import * from interface import Interface root = Tk() inter = Interface(root) root.mainloop()
from interface import Interface import tkinter as tk root = tk.Tk() app = Interface(master=root) app.execute_interface() app.mainloop()
def game_of_draw_letters(color_point, color_pen, level): level = int(level) inf_ob = Interface('gameofdrawletters') max_level = inf_ob.getMaxLevel() if level > max_level: temp = np.ones((480, 640, 3), dtype=np.uint8) temp *= 255 cv2.putText(temp, "You have completed all levels of this game", (50, 220), cv2.FONT_HERSHEY_SIMPLEX, 0.8, ( 0, 255, 0, ), 2, cv2.LINE_AA) cv2.imshow('Message', temp) cv2.waitKey(5000) cv2.destroyAllWindows() return blueLower1 = None blueUpper1 = None blueLower2 = None blueUpper2 = None redLower1 = None redUpper1 = None redLower2 = None redUpper2 = None if color_pen == 'Blue': blueLower1 = np.array([100, 60, 60]) blueUpper1 = np.array([140, 255, 255]) blueLower2 = np.array([100, 60, 60]) blueUpper2 = np.array([140, 255, 255]) elif color_pen == 'Red': blueLower1 = np.array([170, 70, 50]) blueUpper1 = np.array([180, 255, 255]) blueLower2 = np.array([0, 70, 50]) blueUpper2 = np.array([10, 255, 255]) else: #[40,100,50],[75,255,255] blueLower1 = np.array([36, 25, 25]) blueUpper1 = np.array([70, 255, 255]) blueLower2 = np.array([36, 25, 25]) blueUpper2 = np.array([70, 255, 255]) if color_point == 'Blue': redLower1 = np.array([100, 60, 60]) redUpper1 = np.array([140, 255, 255]) redLower2 = np.array([100, 60, 60]) redUpper2 = np.array([140, 255, 255]) elif color_point == 'Red': redLower1 = np.array([170, 70, 50]) redUpper1 = np.array([180, 255, 255]) redLower2 = np.array([0, 70, 50]) redUpper2 = np.array([10, 255, 255]) else: #[40,100,50],[75,255,255] redLower1 = np.array([36, 25, 25]) redUpper1 = np.array([70, 255, 255]) redLower2 = np.array([36, 25, 25]) redUpper2 = np.array([70, 255, 255]) # Load the models built in the previous steps cnn_model = load_model('emnist_cnn_model.h5') # Letters lookup letters = { 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 27: '-' } # Define the upper and lower boundaries for a color to be considered "Blue" min_area = 1200 max_area = 10000 # Define a 5x5 kernel for erosion and dilation kernel = np.ones((5, 5), np.uint8) # Define Black Board blackboard = np.zeros((480, 640, 3), dtype=np.uint8) alphabet = np.zeros((200, 200, 3), dtype=np.uint8) # Setup deques to store alphabet drawn on screen points = deque(maxlen=512) # Define prediction variables prediction = 26 def getContour(cnts): cnt = None cur_area = 0 for ct in cnts: area = float(cv2.contourArea(ct)) if area >= min_area and area <= max_area and area > cur_area: cur_area = area cnt = ct return cnt camera = cv2.VideoCapture(0) br = True while level <= max_level and br: cv2.namedWindow('Draw this!', cv2.WINDOW_NORMAL) cv2.resizeWindow('Draw this!', 640, 480) temp = np.ones((480, 640, 3), dtype=np.uint8) temp *= 255 cv2.putText(temp, "Level" + str(level), (200, 220), cv2.FONT_HERSHEY_SIMPLEX, 2, ( 0, 255, 0, ), 2, cv2.LINE_AA) cv2.imshow('Draw this!', temp) cv2.waitKey(3000) d_char = letters[random.randrange(1, 27, 1)] d = cv2.imread('images/DrawGame/draw_this/draw_' + d_char + '.PNG') prob_dist = [] trials = 0 thresh_t = 5 crs = 0 count = 0 while True: # Grab the current paintWindow try: if level == 1: cv2.imshow('Draw this!', d) elif level == 2: t = np.ones((480, 640, 3), dtype=np.uint8) t *= 255 cv2.putText(t, "Listen to the sound and draw letter.", (70, 220), cv2.FONT_HERSHEY_SIMPLEX, 0.8, ( 0, 255, 0, ), 2, cv2.LINE_AA) cv2.imshow('Draw this!', t) if count == 0: cv2.waitKey(1000) filename = 'audios/' + d_char.upper() + '.wav' playsound(filename) count = 500 (grabbed, frame) = camera.read() if not grabbed: continue frame = cv2.flip(frame, 1) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Determine which pixels fall within the blue boundaries and then blur the binary image blueMask1 = cv2.inRange(hsv, blueLower1, blueUpper1) blueMask2 = cv2.inRange(hsv, blueLower2, blueUpper2) blueMask = blueMask1 | blueMask2 blueMask = cv2.erode(blueMask, kernel, iterations=2) blueMask = cv2.morphologyEx(blueMask, cv2.MORPH_OPEN, kernel) blueMask = cv2.dilate(blueMask, kernel, iterations=1) redMask1 = cv2.inRange(hsv, redLower1, redUpper1) redMask2 = cv2.inRange(hsv, redLower2, redUpper2) redMask = redMask1 | redMask2 redMask = cv2.erode(redMask, kernel, iterations=2) redMask = cv2.morphologyEx(redMask, cv2.MORPH_OPEN, kernel) redMask = cv2.dilate(redMask, kernel, iterations=1) # Find contours (bottle cap in my case) in the image (cnts_blue, _) = cv2.findContours(blueMask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) center = None (cnts_red, _) = cv2.findContours(redMask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnt = getContour(cnts_blue) if cnt is not None: ((x, y), radius) = cv2.minEnclosingCircle(cnt) # Draw the circle around the contour cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) M = cv2.moments(cnt) center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00'])) points.appendleft(center) else: if len(points) != 0: blackboard_gray = cv2.cvtColor(blackboard, cv2.COLOR_BGR2GRAY) blur1 = cv2.medianBlur(blackboard_gray, 15) blur1 = cv2.GaussianBlur(blur1, (5, 5), 0) thresh1 = cv2.threshold( blur1, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] blackboard_cnts = cv2.findContours( thresh1.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0] if len(blackboard_cnts) >= 1: cnt = sorted(blackboard_cnts, key=cv2.contourArea, reverse=True)[0] if cv2.contourArea(cnt) > 1000: x, y, w, h = cv2.boundingRect(cnt) alphabet = blackboard_gray[y - 10:y + h + 10, x - 10:x + w + 10] newImage = cv2.resize(alphabet, (28, 28)) newImage = np.array(newImage) newImage = newImage.astype('float32') / 255 prediction = cnn_model.predict( newImage.reshape(1, 28, 28, 1))[0] prob_dist = prediction prediction = np.argmax(prediction) #trials=trials-1 # Empty the points deque and the blackboard points = deque(maxlen=512) blackboard = np.zeros((480, 640, 3), dtype=np.uint8) if len(cnts_red) > 0: cnt = getContour(cnts_red) if cnt is not None: # Get the radius of the enclosing circle around the found contour ((x, y), radius) = cv2.minEnclosingCircle(cnt) # Draw the circle around the contour center = (int(x), int(y)) cv2.circle(frame, center, int(radius), (0, 255, 255), 2) cv2.circle(blackboard, center, 5, (0, 255, 0), -1) # Connect the points with a line for i in range(1, len(points)): if points[i - 1] is None or points[i] is None: continue #flag=0 #cv2.line(frame, points[i - 1], points[i], (0, 0, 0), 2) cv2.line(blackboard, points[i - 1], points[i], (255, 255, 255), 8) # Put the result on the screen #cv2.putText(frame, "Multilayer Perceptron : " + str(letters[int(prediction1)+1]), (10, 410), cv2.FONT_HERSHEY_SIMPLEX, 0.7,(255, 255, 255), 2) # cv2.putText(frame, "Convolution Neural Network: " + str(letters[int(prediction)+1]), (10, 440), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) predicted_char = str(letters[int(prediction) + 1]) if predicted_char == d_char: rating = '' if prob_dist[prediction] >= 0.95: rating = 'Bravo' elif prob_dist[prediction] >= 0.85: rating = 'Excellent' elif prob_dist[prediction] >= 0.75: rating = 'Very_good' elif prob_dist[prediction] >= 0.50: rating = 'Good' else: rating = 'Fair' if prob_dist[prediction] >= 0.85: crs = crs + 1 filename = 'audios/' + rating + '.wav' wave_obj = sa.WaveObject.from_wave_file(filename) play_obj = wave_obj.play() play_obj.wait_done() cv2.waitKey(33) cv2.namedWindow('Result', cv2.WINDOW_NORMAL) cv2.resizeWindow('Result', 640, 480) x = cv2.imread('images/DrawGame/objects/object_' + d_char + '.jpg') cv2.imshow('Result', x) cv2.waitKey(35) filename = 'audios/audio_' + d_char + '.wav' wave_obj = sa.WaveObject.from_wave_file(filename) play_obj = wave_obj.play() play_obj.wait_done( ) # Wait until sound has finished playing cv2.waitKey(0) prediction = 26 cv2.destroyWindow('Result') cv2.waitKey(33) d_char = letters[random.randrange(1, 27, 1)] d = cv2.imread('images/DrawGame/draw_this/draw_' + d_char + '.PNG') count = 0 thresh_t = thresh_t - 1 trials = trials + 1 elif predicted_char != '-': filename = 'audios/try_again.wav' wave_obj = sa.WaveObject.from_wave_file(filename) play_obj = wave_obj.play() play_obj.wait_done( ) # Wait until sound has finished playing prediction = 26 trials = trials + 1 points = deque(maxlen=512) blackboard = np.zeros((480, 640, 3), dtype=np.uint8) count = 0 # Show the frame cv2.imshow("Board", blackboard) if len(points) == 0: blackboard = np.zeros((480, 640, 3), dtype=np.uint8) if thresh_t == 0: #trials=5 score = float(crs) / trials if score < 0: score = 0 if score >= 0.7: inf_ob.update_scores(level, score) temp = np.ones((480, 640, 3), dtype=np.uint8) temp *= 255 if level < max_level: cv2.putText(temp, "Congrats, Level UP!!", (200, 220), cv2.FONT_HERSHEY_SIMPLEX, 1, ( 0, 255, 0, ), 2, cv2.LINE_AA) else: cv2.putText(temp, "Congrats, all levels completed", (90, 220), cv2.FONT_HERSHEY_SIMPLEX, 1, ( 0, 255, 0, ), 2, cv2.LINE_AA) cv2.imshow('Draw this!', temp) cv2.waitKey(5000) level = level + 1 break else: temp = np.ones((480, 640, 3), dtype=np.uint8) temp *= 255 cv2.putText(temp, "Try again Level " + str(level) + "!!", (200, 220), cv2.FONT_HERSHEY_SIMPLEX, 1, ( 0, 255, 0, ), 2, cv2.LINE_AA) cv2.imshow('Draw this!', temp) cv2.waitKey(5000) break if (level == 2 and count > 0): count = count - 1 except: print('exception occurs') pass # If the 'q' key is pressed, stop the loop if cv2.waitKey(1) & 0xFF == ord("q"): br = False break # Cleanup the camera and close any open windows camera.release() cv2.destroyAllWindows()
# Programa alternativo de cálculo do imposto de renda versão 1 from interface import Interface Interface("nome.db") # inicia interface com nome default do arquivo da agenda ''' Explicação da estrutura de dados: a declaração é uma lista de listas, definida na linha 35 de base_dados.py inicializada na seguinte forma: declaracao = [ [], [], [], [] ,[], [] ] ou seja, cada uma das sublistas agrupa objetos de uma classe. declaracao[0] é para contribuintes declaracao[1] é para dependentes declaracao[2] é para rendimento_tributavel declaracao[3] é para rendimento_exclusiva_definitiva declaracao[4] é para bens declaracao[5] é para dados bancarios '''
def setUpClass(cls): global con con = Interface(username=TEST_USERNAME, password=TEST_PASSWORD)
def game_of_digits(color_point,level): level=int(level) inf_ob=Interface('gameofdigits') max_level=inf_ob.getMaxLevel() if level>max_level: temp = np.ones((480, 640,3), dtype=np.uint8) temp*=255 cv2.putText(temp,"You have completed all levels of this game",(50,220),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,255,0,),2,cv2.LINE_AA) cv2.imshow('Message',temp) cv2.waitKey(5000) cv2.destroyAllWindows() return blueLower1=None blueUpper1=None blueLower2=None blueUpper2=None if color_point=='Blue': blueLower1 = np.array([100, 60, 60]) blueUpper1 = np.array([140, 255, 255]) blueLower2 = np.array([100, 60, 60]) blueUpper2 = np.array([140, 255, 255]) elif color_point=='Red': blueLower1 = np.array([170,70,50]) blueUpper1 = np.array([180,255,255]) blueLower2 = np.array([0,70,50]) blueUpper2 = np.array([10,255,255]) else: #[40,100,50],[75,255,255] blueLower1 = np.array([36, 25, 25]) blueUpper1 = np.array([70, 255, 255]) blueLower2 = np.array([36, 25, 25]) blueUpper2 = np.array([70, 255, 255]) # Load the models built in the previous steps cnn_model = load_model('new_digit.h5') # Letters lookup min_area=1200 max_area=10000 kernel = np.ones((5, 5), np.uint8) camera = cv2.VideoCapture(0) def isLevelUp(scores): total=0 for score in scores: total=total+score avg=total/(len(scores)*100) if avg>=0.75: inf_ob.update_scores(level,avg) return True else: return False def check(img,image,cnt): n_image=image.copy() n_img=img.copy() n_image = cv2.cvtColor(n_image, cv2.COLOR_BGR2GRAY) n_img = cv2.cvtColor(n_img, cv2.COLOR_BGR2GRAY) x, y, w, h = cv2.boundingRect(cnt) img1 =n_img[y+10:y + h - 10, x+10:x + w - 10] img2 =n_image[y+10:y + h - 10, x+10:x + w - 10] img1=np.asarray(img1) img2=np.asarray(img2) return np.array_equal(img1,img2) def preprocess(image,mapping): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray=cv2.bitwise_not(gray) ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for l in range(10): mapping[l]=[] for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) alphabet = gray[y+10:y + h - 10, x+10:x + w - 10] #cv2.imshow("Cropped Letter",alphabet) #cv2.waitKey(0) newImage = cv2.resize(alphabet, (28, 28),interpolation = cv2.INTER_CUBIC) newImage = np.array(newImage) newImage = newImage.astype('float32')/255 prediction = cnn_model.predict(newImage.reshape(1,28,28,1)) prediction = np.argmax(prediction) #cv2.putText(image,str(letters[int(prediction)+1]), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2) predicted_digit=int(prediction) mapping[predicted_digit].append(cnt) # return len(contours) def getContour(cnts): cnt=None cur_area=0 for ct in cnts: area=float(cv2.contourArea(ct)) if area>=min_area and area<=max_area and area>cur_area: cur_area=area cnt=ct return cnt br=True while level<=max_level: temp = np.ones((480, 640,3), dtype=np.uint8) temp*=255 cv2.putText(temp,"Level"+str(level),(200,220),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0,),2,cv2.LINE_AA) temp_2=cv2.resize(temp,(1400,750)) cv2.imshow('Frame',temp_2) cv2.waitKey(5000) img = cv2.imread('images/DigitGame/DigitGameImg'+str(level)+'.jpg') img = cv2.resize(img, (640,480), interpolation = cv2.INTER_AREA) mapping={} preprocess(img,mapping) scores=[] dist_digit=[] for digit in range(10): if len(mapping[digit])==0: continue dist_digit.append(digit) random.shuffle(dist_digit) for d_digit in dist_digit: temp = np.ones((480, 640,3), dtype=np.uint8) temp*=255 cv2.putText(temp,"Pick all '"+str(d_digit)+"'",(200,220),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0,),2,cv2.LINE_AA) temp_2=cv2.resize(temp,(1400,750)) cv2.imshow('Frame',temp_2) cv2.waitKey(5000) count=len(mapping[d_digit]) image=img.copy() cv2.putText(image,"Pick all '"+str(d_digit)+"'",(270,460),cv2.FONT_HERSHEY_SIMPLEX,0.6,(0,255,0,),1,cv2.LINE_AA) cur_score=0 tcount=0 while count>0: # Grab the frame (grabbed, frame) = camera.read() if not grabbed: continue frame = cv2.flip(frame, 1) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blueMask1 = cv2.inRange(hsv, blueLower1, blueUpper1) blueMask2 = cv2.inRange(hsv, blueLower2, blueUpper2) blueMask=blueMask1|blueMask2 blueMask = cv2.erode(blueMask, kernel, iterations=2) blueMask = cv2.morphologyEx(blueMask, cv2.MORPH_OPEN, kernel) blueMask = cv2.dilate(blueMask, kernel, iterations=1) # Find contours (bottle cap in my case) in the image (cnts, _) = cv2.findContours(blueMask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) center=None # Check to see if any contours were found # Sort the contours and find the largest one -- we # will assume this contour correspondes to the area of the bottle cap if len(cnts)>0: cnt =getContour(cnts) if cnt is not None: # Get the radius of the enclosing circle around the found contour ((x, y), radius) = cv2.minEnclosingCircle(cnt) center=(int(x),int(y)) # Draw the circle around the contour cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2) # Get the moments to calculate the center of the contour (in this case Circle) for digit in range(10): flag=True for cnt in mapping[digit]: dist= cv2.pointPolygonTest(cnt,center,True) if dist>=0: if digit==d_digit: if check(img,image,cnt): count=count-1 tcount=tcount+1 cur_score=cur_score+20 cv2.drawContours(image, [cnt], 0, (0, 255, 0), -1) else: if check(img,image,cnt): tcount=tcount+1 cur_score=cur_score-5 cv2.drawContours(image, [cnt], 0, (0, 0, 255), -1) flag=False break if flag==False: break image_up=image.copy() cv2.circle(image_up,center,5,(0,255,255),-1) image_up_2=cv2.resize(image_up,(1400,750)) cv2.imshow("Frame",image_up_2) if count==0: cv2.waitKey(1000) else: image_2=cv2.resize(image,(1400,750)) cv2.imshow("Frame",image_2) #cv2.imshow("o_frame",frame) # If the 'q' key is pressed, stop the loop if cv2.waitKey(1) & 0xFF == ord("q"): br=False break if not br: break x=float(cur_score)*100/(tcount*20) if x<0: x=0 temp = np.ones((480, 640,3), dtype=np.uint8) temp*=255 cv2.putText(temp,"Your Score: "+str(round(x,2))+"%",(200,220),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0,),2,cv2.LINE_AA) temp_2=cv2.resize(temp,(1400,750)) cv2.imshow('Frame',temp_2) cv2.waitKey(5000) scores.append(x) if not br: break if isLevelUp(scores): temp = np.ones((480, 640,3), dtype=np.uint8) temp*=255 if level<max_level: cv2.putText(temp,"Congrats, Level UP!!",(200,220),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0,),2,cv2.LINE_AA) else: cv2.putText(temp,"Congrats, all levels completed",(90,220),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0,),2,cv2.LINE_AA) temp_2=cv2.resize(temp,(1400,750)) cv2.imshow('Frame',temp_2) cv2.waitKey(5000) level=level+1 else: temp = np.ones((480, 640,3), dtype=np.uint8) temp*=255 cv2.putText(temp,"Try again Level "+str(level)+"!!",(200,220),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0,),2,cv2.LINE_AA) temp_2=cv2.resize(temp,(1400,750)) cv2.imshow('Frame',temp_2) cv2.waitKey(5000) # Cleanup the camera and close any open windows camera.release() cv2.destroyAllWindows()
cursor.rect = cursor.image.get_rect() all_sprites.add(cursor) rooms_count = ROOMS_COUNT last_fullscreen = FULLSCREEN MAX_WIN_SIZE = pygame.display.Info().current_w, pygame.display.Info().current_h screen.fill((255, 255, 255)) clock = pygame.time.Clock() difficult_level = 1 level = Level(rooms_count, screen, difficult_level) on_pause = False start_menu = True menu = Menu(screen) interface = Interface(screen) running = True while running: screen.fill((255, 255, 255)) # TODO Back music events = pygame.event.get() for event in events: if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and not start_menu: on_pause = not on_pause if pygame.mouse.get_focused(): pygame.mouse.set_visible(0) cursor.rect.x = pygame.mouse.get_pos()[0] cursor.rect.y = pygame.mouse.get_pos()[1]
#-*- coding: utf-8 -*- """Viewer""" import matplotlib.pyplot as plt from matplotlib import rc, mathtext import time from interface import Interface from config import (REQ_ADDR, PUSH_ADDR) # opcoes de plotagem, usar TeX rc('text', usetex=True) mathtext.fontset = "Computer Modern" # Interface com server interface = Interface(REQ_ADDR, PUSH_ADDR) # eixo X t = [] # variaveis para plotagem var_cmds = ['qf', 'qs', 'P', 'Q', 'L', 'alfa_r'] titles = [r'$q_f$', r'$q_s$', r'$P$', r'$Q$', r'$L$', r'$\alpha_r$'] amt_vars = len(var_cmds) var_ids = range(amt_vars) vals = [[] for x in var_ids] # Indice do sample
#try: #import Tkinter as tk #except: #import tkinter as tk import tkinter as tk from tkinter import ttk from interface import Interface from tkinter import messagebox as mbox from datetime import datetime db = Interface() #initiating app with start frame and App title class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self._frame = None self.switch_frame(StartPage) self.title("Patient Manager") #initiate method to change frame and thus navigate between windows def switch_frame(self, frame_class): new_frame = frame_class(self) if self._frame is not None: self._frame.destroy() self._frame = new_frame self._frame.pack() #create class for the first Frame (Startpage) containing subframes to better allocate widgets with grid
import argparse parser = argparse.ArgumentParser(description="Iterative rom corruptor") parser.add_argument('--rom-path', '-rp', help="Path of the rom to be used") parser.add_argument('--export-path', '-ep', help="Path of the corrupted rom") parser.add_argument('--corruption-level', '-cl', help="The level of corruption each patch causes", type=int, default=5) parser.add_argument('--run-command', '-em', help="The command to run with the corrupted rom", default=None) parser.add_argument('--script', '-s', help="Run in a non-interactive mode, with only one patch", action="store_true") args = parser.parse_args() print(args) if args.script: corruptor = Corruptor(args.rom_path, args.export_path, args.corruption_level) corruptor.create_patch() corruptor.export_rom() else: Interface(args.rom_path, args.export_path, args.run_command)
# Import libraries. from tkinter import * import matplotlib # Import files. from input_generator import Generator from radioactivity_calculator import Calculator from interface import Interface from create_graph import create_graphs generator = Generator() #Generates all starting parameters of the simulation. calculator = Calculator() graphs = create_graphs(calculator) root = Tk() interface = Interface(root, calculator, graphs) root.mainloop()
def list_to_interfaces(l): """ :param l: a list of strings in this format: "<ip> <port> <my_virt_ip> <peer_virt_ip>" :return: a list of Interface objects """ return [Interface(*line.strip().split()) for line in l]