def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        if self._NEW_TOOLBAR_SUPPORT:  #toolbar nuevo
            #self.toolbar_box = sugar.graphics.toolbarbox.ToolbarBox()
            self.toolbar_box = sugar.activity.widgets.ActivityToolbar(self)
            self.toolbar_box.keep.hide()

            #stop_button = sugar.activity.widgets.StopButton(self)
            #stop_button.props.accelerator = '<Ctrl><Shift>Q'
            #self.toolbar_box.toolbar.insert(stop_button, -1)
            #stop_button.show()

            self.set_toolbar_box(self.toolbar_box)
            self.toolbar_box.show()

        else:  #old toolbar
            toolbox = activity.ActivityToolbox(self)

            activity_toolbar = toolbox.get_activity_toolbar()
            activity_toolbar.share.props.visible = False  #Todavia no hay share
            activity_toolbar.show()

            self.set_toolbox(toolbox)
            toolbox.show()

        self.activity = Control()

        self.set_canvas(self.activity.todo)
        self.nomArch = ""

        self.connect('key_press_event', self.activity.onKeyPress)
 def enter():
     global pCount
     value = int(lbl_value["text"])
     text = ""
     text = e1.get()
     wat = ""
     wat = e2.get()
     tim = ""
     tim = e3.get()
     if (text == ""):
         messagebox.showinfo(
             message="Please enter the name before saving!",
             title="Status")
     elif (wat == ""):
         messagebox.showinfo(
             message=
             "Please enter the amout of water before saving!",
             title="Status")
     elif (tim == ""):
         messagebox.showinfo(
             message=
             "Please enter the time for growing in weeks!",
             title="Status")
     else:
         #NEU
         mac = ""
         mac = Control.aLearn.getMACSensor(value)
         Control.new_Plant(text, tim, wat, value)
         messagebox.showinfo(message=Control.getName(value),
                             title="Status")
         lbl_plant["text"] = f"{Control.getName(value)}"
         pCount = pCount + 1
         pfnew.destroy()
Exemple #3
0
def monitormutation():     
    food_total = 10
    reac_total = 70
    metabolites = 80
    food = 8
    reac = 20
    targets = 1
    p = 0.2
    rate = 0.0

    if targets + food > metabolites:
        print 'Tem numero errado...'

    react_list = [x + metabolites for x in range(reac_total)]
    food_list = sorted(rndm.sample(range(food_total), food))
    genes_list = food_list #+ sorted(rndm.sample(react_list, reac))


    primeira_geracao = Control(food_total, metabolites, genes_list, p, reac_total, inicial = True)
    dnap = primeira_geracao.export_code()
    dna = deepcopy(dnap)

    for j in range(50):

        print 'etapa' + str(j)
        gerac_um = Control(food_total, metabolites, [], 0, reac_total, DNA = dna)
        dna = mutate_DNA(dna, rate)
        time.sleep(0.5)


    dnamutante = crossover_DNA(dna, dnap, 2)
    gerac_mutante = Control(food_total, metabolites, [], 0, reac_total, DNA = dnamutante)
 def __init__(self):
     self.processor = Process()
     self.control = Control()
     self.width = 800   
     self.height = 600
     self.fps = 1000 / 60
     self.UI_handler = []
Exemple #5
0
    def __init__( self, app, options=None, parent=None):
        QtCore.QObject.__init__(self, parent)
        self.app = app

        if os.name == 'posix':
            self.label_font_size = 18
        else:
            self.label_font_size = 12
        
        # #################
        # INITIATE
        self.control = Control(self, self.debug)

        # #################
        # LAYOUTS
        self.init_layout()

        self.setGeometry(self.offset_left, self.offset_top, self.width, self.height)
        self.setSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
        self.setMinimumSize(self.width, self.height)
        self.setWindowTitle(self.control.name)

        # for thread in self.control.threads:
        #     print thread

        # #################
        self.control.start_capture()
Exemple #6
0
    def loadGeoJSON(self):
        if len(self.data) > 0:
            geojson = QtWidgets.QFileDialog.getOpenFileName(
                self, "Select GeoJSON format", QtCore.QDir.rootPath(),
                "*.geojson")
            self.gj_loaded = ((os.path.basename(geojson[0])).split("."))[0]
            if os.path.isfile(Control.dirname +
                              "/Output_data/GeoJSON/coords.csv"):
                csv_coords = open(
                    Control.dirname + "/Output_data/GeoJSON/coords.csv", "r")
            else:
                Control.errorMessage("Cannot find coords.csv table.")
                return

            lines = csv_coords.readlines()
            for line in lines:
                if line.startswith(self.gj_loaded + ";"):
                    line_str = line.split(";")[1]
                    coords = ast.literal_eval(line_str)
                    points = []
                    for coord in coords:
                        point = QtCore.QPoint(
                            self.raster.index(coord[0], coord[1])[1],
                            self.raster.index(coord[0], coord[1])[0])
                        points.append(point)
                    self.roi.setPoints(points, True)
                    self.roi_coords = points
            csv_coords.close()
        else:
            Control.errorMessage(
                "No satellite image is loaded. Please select vegetation index and area to display."
            )
Exemple #7
0
    def __init__(self,
                 routePoints,
                 sensorsAlgorithms={'Vision': [VisionDetectSVM]},
                 avoidClass=FixAvoid,
                 comunication=AirSimCommunication,
                 fusionAlgorithm=FusionData_Mean,
                 configPath='config.yml',
                 startPoint=None):
        Thread.__init__(self)
        self.start_point = startPoint
        self.status = 'start'
        # vehicleComunication = comunication.getVehicle()
        # Conectando ao simulador AirSim
        self.vehicleComunication = AirSimCommunication()
        self.control = Control(self.vehicleComunication, routePoints)
        self.unrealControl = UnrealCommunication()
        self.stop = False

        with open(configPath, 'r') as file_config:
            self.config = yaml.full_load(file_config)

        if avoidClass is not None:
            self.avoidThread = avoidClass(self, self.control)
        if sensorsAlgorithms is not None:
            self.detect = Detect(self,
                                 self.vehicleComunication,
                                 sensorsAlgorithms,
                                 self.avoidThread,
                                 fusionAlgorithm=fusionAlgorithm)
Exemple #8
0
class loop_Control(FPS_loop):
    controller = []
    loop_Encoder = []
    command = 0

    def __init__(self, **kwargs):
        super(loop_Control, self).__init__(**kwargs)

        ### Activate encoders
        self.loop_encoder = loop_Encoder(fps=6000,
                                         display_rt=0,
                                         resolution=2048)
        self.loop_encoder.start_loop()

        ### Link Controller with encoders
        self.controller = Control(
            encoder_left=self.loop_encoder.encoder_left,
            encoder_right=self.loop_encoder.encoder_right)

    def start_loop(self):
        print('Initialization')
        FPS_loop.start_loop(self)

    def inner_loop(self):
        self.controller.update()
        self.counter += 1
Exemple #9
0
    def __init__(self, physic_world, config=None):
        logging.info("INIT PLAYER...")
        logging.info("INIT FSM...")
        FSM.__init__(self, "FSM-Player")
        logging.info("INIT CONFIG...")
        Config.__init__(self)
        # additional initial configuration settings set by the outher application
        self.physic_world = physic_world
        logging.info("INIT PHYSICS...")
        Physics.__init__(self)
        logging.info("INIT CONTROLS...")
        Control.__init__(self)
        logging.info("INIT CAMERA...")
        Camera.__init__(self, self.cam_near_clip, self.cam_far_clip,
                        self.cam_fov)
        logging.info("INIT ANIMATOR...")
        Animator.__init__(self)
        logging.info("INIT PLAYER DONE")

        #
        # STATES SETUP
        #
        self.on_ground_states = [
            self.STATE_IDLE, self.STATE_IDLE_TO_WALK, self.STATE_WALK,
            self.STATE_WALK_TO_IDLE, self.STATE_PLANT
        ]
        # set the possible transition in the FSM
        self.defaultTransitions = {
            self.STATE_IDLE: [self.STATE_IDLE_TO_WALK, self.STATE_PLANT],
            self.STATE_IDLE_TO_WALK: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_WALK: [self.STATE_IDLE, self.STATE_WALK_TO_IDLE],
            self.STATE_WALK_TO_IDLE: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_PLANT: [self.STATE_IDLE],
        }

        #
        # ACTOR SETUP
        #
        Actor.__init__(
            self, self.model, {
                self.IDLE: self.anim_idle,
                self.WALK: self.anim_walk,
                self.PLANT: self.anim_plant,
            })
        self.setBlend(frameBlend=self.enable_interpolation)

        alphaSettings = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                              ColorBlendAttrib.OIncomingAlpha,
                                              ColorBlendAttrib.OOne,
                                              (0, 0, 0, 0))
        #self.setAttrib(alphaSettings)
        self.setBin("fixed", 15)
        self.setDepthWrite(False)

        #
        # CONTROLS SETUP
        #
        self.isDown = base.mouseWatcherNode.isButtonDown
        self.mainNode = self
class Main(object):

    def __init__(self):
        self.processor = Process()
        self.control = Control()
        self.width = 800   
        self.height = 600
        self.fps = 1000 / 60
        self.UI_handler = []

    def start(self):
        self.root = Tk()
        self.root.title("Motion Control")
        self.canvas = Canvas(self.root, width=self.width, height=self.height)
        self.canvas.pack()
        self.timerEventListener()
        self.root.mainloop()
        self.closeEvent()

    def timerEventListener(self):
        if (self.fps == None):
            return 
        self.timerEvent()
        self.refreshUI()
        self.canvas.after(self.fps, self.timerEventListener)      

    def timerEvent(self):
        self.processor.process()

    def closeEvent(self):
        self.processor.close()

    def drawRealtimeImages(self):
        for handle in self.UI_handler:
            self.canvas.delete(handle)
        self.UI_handler = []
        view = Process.BGRtoRGBA(self.processor.original_image, self.width / 2, self.height / 2)
        self.view1 = ImageTk.PhotoImage(image=Image.fromarray(view))
        self.processor.paint()
        view = Process.BGRtoRGBA(self.processor.drawing_canvas, self.width / 2, self.height / 2)
        self.view2 = ImageTk.PhotoImage(image=Image.fromarray(view))
        view = Process.GRAYtoRGBA(self.processor.thresholded_image, self.width / 2, self.height / 2)
        self.view3 = ImageTk.PhotoImage(image=Image.fromarray(view))
        self.UI_handler.append(self.canvas.create_image(0, 0, image=self.view1, anchor="nw"))
        self.UI_handler.append(self.canvas.create_image(800, 600, image=self.view2, anchor="se"))
        self.UI_handler.append(self.canvas.create_image(0, 600, image=self.view3, anchor="sw"))
        if hasattr(self.processor, 'defect_point') and len(self.processor.defect_point) != 0 :
            self.UI_handler.append(self.canvas.create_text(750, 20, text="Fingers: " + str(len(self.processor.defect_point) - 2), anchor="ne", font="15"))
        else :
            self.UI_handler.append(self.canvas.create_text(750, 20, text="Fingers: " + str(0), anchor="ne", font="15"))
        if self.control.signal == True :
            self.UI_handler.append(self.canvas.create_text(750, 40, text="Control Mode: On", anchor="ne", font="15"))
        else :
            self.UI_handler.append(self.canvas.create_text(750, 40, text="Control Mode: Off", anchor="ne", font="15"))
        
    def refreshUI(self):
        self.drawRealtimeImages()
        if hasattr(self.processor, 'defect_point') :
            self.control.gestureAnalysis(self.processor.defect_point,self.processor.center)
Exemple #11
0
def down():
    control = Control()
    try:
        steps = int(request.args['steps'])
    except:
        steps = 1
    control.down(steps)
    return "PUT THAT COOKIE DOWN! NOW!"
Exemple #12
0
def up():
    control = Control()
    try:
        steps = int(request.args['steps'])
    except:
        steps = 1
    control.up(steps)
    return "Beam me up Scotty!"
Exemple #13
0
 def __init__(self, media):
     self.titlefont = pygame.font.SysFont('inkfree', 80)
     self.title = self.titlefont.render("Ranking", True, (255, 255, 255))
     self.comment = pygame.font.SysFont('inkfree', 40)
     self.control = Control()
     self.media = media
     self.ranking = []
     self.write_point = 0
Exemple #14
0
 def updateGraph(self):
     self.setCursor(QtCore.Qt.BusyCursor)
     self.clearGraph()
     try:
         if self.x != {}:
             self.drawGraph()
         self.setCursor(QtCore.Qt.ArrowCursor)
     except OSError:
         Control.errorMessage("This graph cannot be loaded.")
 def delete():
     global pCount
     value = int(lbl_value["text"])
     if (Control.getName(value) == ""):
         messagebox.showinfo(message="There is no plant for deleting!",
                             title="Status")
     else:
         Control.clear_Plant(value)
         lbl_plant["text"] = "empty"
         pCount = pCount - 1
Exemple #16
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.build_toolbar()
        self.activity = Control()

        self.set_canvas(self.activity.todo)
        self.nomArch =""
        
        self.connect('key_press_event', self.activity.onKeyPress)
 def __init__(self, media):
     self.titlefont = pygame.font.SysFont('inkfree', 80)
     self.title = self.titlefont.render("Setting", True, (255, 255, 255))
     self.comment = pygame.font.SysFont('inkfree', 40)
     self.choose = [1, 0]  # 現在の選択されている位置
     self.control = Control()
     self.media = media
     self.menu_str = [["SIZE", " SMALL", " NORMAL", " BIG", ""],
                      ["STARS", " FEW", " NORMAL", " MANY", "EXIT"],
                      ["SPEED", " SLOW", " NORMAL", " FAST", ""]]
Exemple #18
0
	def __init__(self, c_instance, selected_track_controller):
		Control.__init__(self, c_instance, selected_track_controller)
		
		self._midi_recording_quantization_labels = ["None", "1/4", "1/8", "1/8T", "1/8 + 1/8T", "1/16", "1/16T", "1/16 + 1/16T", "1/32"]
		
		for key, max_steps in (("clip_trigger_quantizations", 13), ("midi_recording_quantizations", 8)):
			if not key in settings.midi_mapping:
				continue
			mappings = settings.midi_mapping[key]
			for i in range(min(max_steps, len(mappings))):
				if mappings[i]:
					self.setup_quantizations(key[:-1], i, mappings[i])
    def __init__(self, id, largo, alto, ancho, robot):
        if id < 1 or id > 255:
            raise ValueError("El id debe estar entre 1-255.")
        if largo < 1 or largo > 200 or alto < 1 or alto > 200 or ancho < 1 or ancho > 200:
            raise ValueError("Las dimensiones deben tener un valor comprendido entre 1 y 200mm")

        self.id = id
        self.largo = largo
        self.alto = alto
        self.ancho = ancho
        self.robot = robot
        self.control = Control(self)
Exemple #20
0
 def __init__(self, media):
     self.titlefont = pygame.font.SysFont('inkfree', 80)
     self.title = self.titlefont.render("Catch a star game!", True,
                                        (255, 255, 255))
     self.comment = pygame.font.SysFont('inkfree', 40)
     self.title_menu = [
         self.comment.render(st, True, (255, 255, 255))
         for st in ["PLAY", "SETTING", "RANKING", "BYE"]
     ]
     self.choose = 0  # 現在の選択されている位置
     self.control = Control()
     self.media = media
	def __init__(self, c_instance, selected_track_controller):
		Control.__init__(self, c_instance, selected_track_controller)

		self._midi_recording_quantization_labels = ["None", "1/4", "1/8", "1/8T", "1/8 + 1/8T", "1/16", "1/16T", "1/16 + 1/16T", "1/32"]

		for key, max_steps in (("clip_trigger_quantizations", 13), ("midi_recording_quantizations", 8)):
			if not key in settings.midi_mapping:
				continue
			mappings = settings.midi_mapping[key]
			for i in range(min(max_steps, len(mappings))):
				if mappings[i]:
					self.setup_quantizations(key[:-1], i, mappings[i])
Exemple #22
0
    def __init__(self, **kwargs):
        super(loop_Control, self).__init__(**kwargs)

        ### Activate encoders
        self.loop_encoder = loop_Encoder(fps=6000,
                                         display_rt=0,
                                         resolution=2048)
        self.loop_encoder.start_loop()

        ### Link Controller with encoders
        self.controller = Control(
            encoder_left=self.loop_encoder.encoder_left,
            encoder_right=self.loop_encoder.encoder_right)
Exemple #23
0
    def __find_local_controls(self):
        self.notify_observers("FETCH", "Fetching local controls")
        self.local_controls = {}
        for cont_dir in Settings.get_setting('control_dirs'):
            self.local_controls.update( local.get_controls(cont_dir) )

        for d_key in self.local_controls:
            d_data = self.local_controls[d_key]
            d = Control(d_data['name'], '', [])
            d.local_path = d_data['directory']
            #for ver in d_data['versions']:
             #   d.add_version(ver)
            self.add_control(d)
Exemple #24
0
 def __init__(self,
              initialPC=Bus(64),
              IMem=Memory(True),
              DMem=Memory(False)):
     self.ALU = ALU()
     self.IMem = IMem
     self.DMem = DMem
     self.signExtender = SignExtender()
     self.regFile = RegisterFile()
     self.Control = Control()
     self.nextPCLogic = NextPCLogic()
     self.PC = initialPC
     self.aluZero = 0
Exemple #25
0
    def __init__(self, path):
        self.cuteloading = None
        self.asynckey = None
        try:
            self.key = Key()
            self.asynckey = threading.Thread(target=self.key.storechar,
                                             args=(),
                                             daemon=False)
            self.asynckey.start()
            self.time = time.time()

            width, height = shutil.get_terminal_size((80, 20))
            Display.setdisplay(width - 1, height)
            self.skipupdate = False
            self.restart = False

            sys.stdout.write(Display.screen(True))
            sys.stdout.flush()
            self.cuteloading = threading.Thread(target=Display.startloading,
                                                args=(width, ),
                                                daemon=False)
            self.cuteloading.start()

            self.path = path
            self.now = datetime.datetime.now()
            self.control = Control(self)

            self.filedisplay = Display(Display.width, Display.height - 1, 0, 0,
                                       False, False)
            self.infodisplay = Display(Display.width, Display.height, 0, 0,
                                       True, True)
            self.cmddisplay = Display(Display.width, Display.height, 0, 0,
                                      False, True)
            self.currentdisplay = self.filedisplay
            self.currentfile = self.filedisplay
            self.loadfile()

            Display.stoploading(self.cuteloading)
            self.update()

            self.key.settrackkeys(True)
            self.loop()

        finally:
            Display.stoploading(self.cuteloading)
            Key.close()
            self.asynckey.join()
            if not self.restart:
                sys.stdout.write(Display.screen(False))
                sys.stdout.flush()
Exemple #26
0
class BMKSim:
    def __init__(self, range_x=1.2, range_y=1.2):
        self.bluetooth = Bluetooth()
        self.control = Control(range_x, range_y)

        self.max_try = 500

    def run(self):
        self.bluetooth.connect()
        error_count = 0
        # total_num_of_massages = 0
        while True:
            data = self.bluetooth.run()
            if data:
                error_count = 0
                # total_num_of_massages += 1
                if data[0] == MASSAGE_MOVE:
                    self.control.move_mouse(data[1:])
                elif data[0] == MASSAGE_LEFT_CLICK:
                    self.control.left_click()
                elif data[0] == MASSAGE_RIGHT_CLICK:
                    self.control.right_click()
                elif data[0] == MASSAGE_PRESS:  # test:
                    self.control.press(bytes.decode(data[1]))

            else:
                error_count += 1

            if error_count == self.max_try:
                break
        # print('\ntotal_num_of_massages:', total_num_of_massages)
        print('\nDisconnected...')
        self.bluetooth.disconnect()
class Setup():
    def __init__(self):
        #Inicializamos la clase fichero para acceder a las variables de configuracion
        self.iniciar_ficheros()
        self.iniciar_conexion()
        self.verificar_estado_servidor()
        self.iniciar_graficos()
        self.iniciar_controles()
        self.cargar_idioma()
        
    def iniciar_ficheros(self):
        self.Ficheros = Fichero()
        
    def iniciar_conexion(self):
        #Se cargan los valores necesarios del archivo configuracion.txt
        host = self.Ficheros.buscar_valor("configuracion.txt", "HOST_SERVER")
        port = self.Ficheros.buscar_valor("configuracion.txt", "PORT_SERVER")
        self.Cliente = Cliente(host, int(port))
    
    def verificar_estado_servidor(self):
        pass
    
    def iniciar_graficos(self):
        self.Graficos = Graficos()
        
        #Se cargan las frames
        FPS = int(self.Ficheros.buscar_valor("configuracion.txt", "FPS"))
        self.Graficos.establecer_frames(FPS)
        
        #Se cargan los valores de la resolucion del archivo Configuracion.txt
        largo_pantalla = int(self.Ficheros.buscar_valor("configuracion.txt", "LARGO_PANTALLA"))
        ancho_pantalla = int(self.Ficheros.buscar_valor("configuracion.txt", "ANCHO_PANTALLA"))
        fullscreen = int(self.Ficheros.buscar_valor("configuracion.txt", "FULLSCREEN"))
        nombre_app = self.Ficheros.buscar_valor("configuracion.txt", "NOMBRE_APP")
        version_app = self.Ficheros.buscar_valor("configuracion.txt", "VERSION_APP")
        self.Graficos.RESOLUCION = (largo_pantalla, ancho_pantalla)
        
        #Se establece la pantalla y se cargan titulos y demas
        self.Graficos.establecer_pantalla(self.Graficos.RESOLUCION, fullscreen)
        self.Graficos.titulo_ventanta(nombre_app + " " + version_app)
        
        #Pendiente cargar icono
        
    def iniciar_controles(self):
        self.Controles = Control()
        self.Controles.repeat(400, 50)
        
    def cargar_idioma(self):
        #self.idioma = 0 para español y self.idioma = 1 para ingles
        self.idioma = int(self.Ficheros.buscar_valor("configuracion.txt", "IDIOMA"))
Exemple #28
0
def main():
    pygame.init()
    pygame.display.set_caption(GAME_NAME)

    hero = HeroPlane(
        240, 550, screen)  # import module 与 from module import 的区别, 前者调用要先加模块名
    enemy = Enemy(screen)

    while True:
        screen.blit(bg, (0., 0.))
        hero.display()
        enemy.display()
        pygame.display.update()
        Control.key_control(hero)
Exemple #29
0
 def browseDirs(self):
     if self.lineEdit.text() == "":
         dirname = QtWidgets.QFileDialog.getExistingDirectory(
             self, "Select data directory", QtCore.QDir.rootPath())
         dirname = QtCore.QDir.toNativeSeparators(dirname)
         if os.path.isdir(dirname):
             self.lineEdit.setText(dirname)
             Control.dirname = dirname
             S2.dirname = dirname
     else:
         self.lineEdit.setText("")
         Control.deleteInstances()
         self.data_in_table = False
         self.browseDirs()
    def __init__(self):
        QMainWindow.__init__(self)
        self.control = Control()

        self.setMinimumSize(QSize(500, 240))
        self.setWindowTitle('Markov\'s Algorithm')

        self.b = QPlainTextEdit(self)
        self.b.move(10, 10)
        self.b.resize(400, 200)

        button = QPushButton('Enter', self)
        button.clicked.connect(self.enterPressed)
        button.resize(50, 32)
        button.move(420, 180)
Exemple #31
0
class Game():
	def __init__(self):
		self.gameState = 1			#State of game: 1 if playing, 0 if game over
		self.player = 'white'		#Current player: white player always starts
		self.board = Board()		#The board representation
		self.control = Control()	#The control that handles user input
		self.sp = Speech()			#The verbal feedback given by the computer

	def play(self):
		#What happens when the game is started:
		self.sp.engine.say("Welcome to Wizard's Chess!")
		self.sp.engine.runAndWait()	
		print ""
		print "*~*~*~*~*~*~*~*~*~*       Welcome to Wizard's Chess!       *~*~*~*~*~*~*~*~*~*"
		print "*~*~*~*~*~*~*~*~*~*  Input is of the form 'Knight 1 to H3'  *~*~*~*~*~*~*~*~*~*\n"
		self.board.updateBoard()
		self.board.printBoard()  #Print the board so the player can make their first move

		#The game loop: runs continuously until the game is over
		while self.gameState == 1:
			self.board.updatePosMoves(self.player)									#Update the possible moves of the player's pieces
			#move = self.control.getKeyboardInput(self.player.capitalize())			#Get the desired move from user (keyboard) input
			move = self.control.getVoiceInput(self.player.capitalize())
			if move:																#If the user input is valid:
				success = self.board.movePiece(self.player,move)	 				#Try to move the piece
			while not move or not success:											#While the user input isn't valid or the piece can't be moved:
				#move = self.control.getKeyboardInput(self.player.capitalize())		#Get new user input until both conditions are satisfied
				move = self.control.getVoiceInput(self.player.capitalize())
				if move:
					success = self.board.movePiece(self.player,move)
			self.board.updateBoard()												#Once input is valid and piece is successfully moved:
			self.board.printBoard()													#Print the board to the console
			self.board.updatePosMoves(self.player)									#Update the possible moves of the player's pieces
			self.player = self.other(self.player)									#Switch players
			self.gameState = self.board.continuePlay(self.player)					#Check to see if the game is over
			
		#Terminate the program once the game is over
		self.sp.engine.say(self.player + " player loses!")
		self.sp.engine.runAndWait()
		print self.player.capitalize() + " player loses!"
		sys.exit(0)

	def other(self,player):
		#Return the name of the other player
		if player == 'white':
			return 'black'
		if player == 'black':
			return 'white'
class Setting():
    def __init__(self, media):
        self.titlefont = pygame.font.SysFont('inkfree', 80)
        self.title = self.titlefont.render("Setting", True, (255, 255, 255))
        self.comment = pygame.font.SysFont('inkfree', 40)
        self.choose = [1, 0]  # 現在の選択されている位置
        self.control = Control()
        self.media = media
        self.menu_str = [["SIZE", " SMALL", " NORMAL", " BIG", ""],
                         ["STARS", " FEW", " NORMAL", " MANY", "EXIT"],
                         ["SPEED", " SLOW", " NORMAL", " FAST", ""]]

    def main(self, screen, difficulty, rect_player):
        # タイトルと設定情報の描画
        screen.blit(self.title, (20, 50))
        for j, strs in enumerate(self.menu_str):
            for i, st in enumerate(strs):
                if i == difficulty[j]:
                    screen.blit(
                        self.comment.render(st + ' <-', True, (255, 255, 255)),
                        (200 + 300 * j, 150 + 50 * i))
                else:
                    screen.blit(self.comment.render(st, True, (255, 255, 255)),
                                (200 + 300 * j, 150 + 50 * i))

        # コントロール操作
        con = self.control.control()
        if con == 'up':
            if self.choose[Y] > 0:
                self.media.button1.play()
                self.choose[Y] -= 1
        elif con == 'down':
            if self.choose[Y] < len(strs) - 2:
                self.media.button1.play()
                self.choose[Y] += 1
        elif con == 'left':
            if self.choose[X] > 0:
                self.media.button1.play()
                self.choose[X] -= 1
        elif con == 'right':
            if self.choose[X] < len(self.menu_str) - 1:
                self.media.button1.play()
                self.choose[X] += 1
        elif con == 'return':
            if self.choose[Y] == 3:  #Exit
                self.media.kirakira.play()
                return Mode.MENU
            else:
                self.media.button2.play()
                difficulty[self.choose[X]] = self.choose[Y] + 1

        # 最下部を選択していたら中央になるようにする
        if self.choose[Y] == 3:
            self.choose[X] = 1

        # 実際の画面のサイズに応じた位置にカーソルを移動する
        rect_player.center = (150 + self.choose[X] * 300,
                              220 + self.choose[Y] * 50)

        return Mode.SETTING
Exemple #33
0
    def __init__(self, MetNet, inicial = False, control = None, ES = None):
        self.age = 0
        self.record = 'a'
        self.fitness = 0
        self.mother_record = 'a'
        self.species = 'a'
        food_list = range(Constants.food)

        
        if inicial: #verifica se a populacao eh inicial

            #talvez fosse util ter um dicionario que redireciona pra funcoes
            #dependendo do tipo de inicializacao - inicial ou mutacao - e
            #encapsular uma serie de coisas que por enquanto estao no __init__.

            self.chemistry = deepcopy(MetNet) 
            self.control = Control(inicial)   # cria um controle inicial -> genes ligados por acaso e independentemente
            self.change_environment_org(ES)  #agora seta a comida do controle e da quimica
            self.chemistry.update_reactions(self.control.switch_dict)   #manda sinal dos genes ligados para a rede metabolica
            self.biomass = Constants.division_threshold/2.0        #aqui eh a biomassa do organismo inicial.

        else: #caso a populacao seja gerada de uma mutacao...
            self.chemistry = deepcopy(MetNet)  
            self.control = control
            self.change_environment_org(ES)         #informa os recem-nascidos da situacao de comida...
            self.chemistry.update_reactions(self.control.switch_dict)
            self.biomass = Constants.division_threshold/2.0      #aqui deve ser a biomassa do organismo filho mutado.
Exemple #34
0
 def testInputs_nominal(self):
     """Tests creation of Control instance with valid inputs"""
     s = random.uniform(5, 10)
     w = random.uniform(-math.pi / 4, math.pi / 4)
     c = Control(s, w)
     self.assertEqual(c.s, s)
     self.assertEqual(c.omega, w)
Exemple #35
0
    def __init__(self, env, slam, control, sensor, pose, robot_id, v=0.0, color="yellow"):
        self._env = env
        self._slam = slam
        self._control = control
        self._sensor = sensor
        self._pose = pose
        self._id = robot_id
        self._v = v
        self._color = color

        # Radius is 6% of env height
        self._r = int(self._env.h() * 0.06)

        # Create a control, if none was given    
        if not self._control:
            noise = (0.3, 0.3, 0.05)    # (x, y, theta) noise
            self._control = Control(env, v, noise)

        # Create a sensor, if none was given
        if not self._sensor:
            sensor_range = self._r * 4.0
            noise = ((sensor_range * 0.05, 0.01), np.matrix([[0.70, 0.0], [0.0, 0.70]]))
            self._sensor = Sensor(self._env, sensor_range=sensor_range, noise=noise, width=2.0*self._r)

        # Create a SLAM algorithm object, if none was given
        if not self._slam:
            M = 20    # number of particles
            self._slam = FastSLAM(self._control, self._sensor, pose, M, self._env.get_landmark_count())
Exemple #36
0
    def __init__(self, parent=None, flags=0):
        super(TaskEditor, self).__init__(parent=None)
        self.setWindowTitle(u"BLOB Data Extract Tool")
        self.setWindowIcon(QtGui.QIcon('./blobdata_pump.ico'))
        self.globalLayout = QtGui.QGridLayout()
        self.setLayout(self.globalLayout)
        self.setMinimumSize(500, 700)
        self.globalLayout.setVerticalSpacing(4)
        self.globalLayout.setHorizontalSpacing(4)		
        self.globalLayout.setAlignment(Qt.Qt.AlignTop | Qt.Qt.AlignLeft)
        self.setWindowFlags(Qt.Qt.WindowStaysOnTopHint)

        self.dbConnStatus = False
        self.chooseColumnStatus = False
        self.control = Control()
        self.initUI()
    def __init__(self, c_instance, selected_track_controller):
        Control.__init__(self, c_instance, selected_track_controller)

        # arming on track-selection does not work from within the callback
        # see SessionControl for at least auto-arm when using STC to select track
        if settings.auto_arm:
            self.song.view.add_selected_track_listener(self.on_track_selected)

        # use helper-functions to set up callback via lambda-functions
        # a closure inside the lambda-functions is needed, so i is always the current i

        #if "reset_sends" in settings.midi_mapping:
        #	for i in range(len(settings.midi_mapping["reset_sends"])):
        #		self.setup_send_reset(i, settings.midi_mapping["reset_sends"][i])

        if "sends" in settings.midi_mapping:
            for i in range(len(settings.midi_mapping["sends"])):
                self.setup_send_set(i, settings.midi_mapping["sends"][i])
	def __init__(self, c_instance, selected_track_controller):
		Control.__init__(self, c_instance, selected_track_controller)

		self._device = None
		self._locked_to_device = False

		self.bank = 0
		if "device_params" in settings.midi_mapping:
			self.params_per_bank = len(settings.midi_mapping["device_params"])
		else:
			self.params_per_bank = 8
		self.max_banks = int(math.ceil(128.0/self.params_per_bank))


		#if "reset_device_bank" in settings:
		# add listener to receive notifications, if track has changed
		# add listener to track if selected device has changed => reset bank?


		#if settings.auto_select_device:
		self.song.view.add_selected_track_listener(self.auto_select_device)

		if settings.device_bestof:
			# we have best-of parameters for devices => use these parameters first, then the rest
			for device_name, indizes in settings.device_bestof.items():
				new_indizes = [0,] + list(indizes)
				i = 0
				while i < 128:
					if i not in indizes:
						new_indizes.append(i)
					i = i + 1
				settings.device_bestof[device_name] = new_indizes


		if "device_params" in settings.midi_mapping:
			for i in range(len(settings.midi_mapping["device_params"])):
				# begin with parameter 1, as 0 is device-on/off
				self.setup_device_param_set(i+1, settings.midi_mapping["device_params"][i])

		if "reset_device_params" in settings.midi_mapping:
			for i in range(len(settings.midi_mapping["reset_device_params"])):
				# begin with parameter 1, as 0 is device-on/off
				self.setup_device_param_reset(i+1, settings.midi_mapping["reset_device_params"][i])
	def __init__(self, c_instance, selected_track_controller):
		Control.__init__(self, c_instance, selected_track_controller)
		
		
		# arming on track-selection does not work from within the callback
		# see SessionControl for at least auto-arm when using STC to select track
		if settings.auto_arm:
			self.song.view.add_selected_track_listener(self.on_track_selected)
		
		
		# use helper-functions to set up callback via lambda-functions
		# a closure inside the lambda-functions is needed, so i is always the current i
		
		#if "reset_sends" in settings.midi_mapping:
		#	for i in range(len(settings.midi_mapping["reset_sends"])):
		#		self.setup_send_reset(i, settings.midi_mapping["reset_sends"][i])
		
		if "sends" in settings.midi_mapping:
			for i in range(len(settings.midi_mapping["sends"])):
				self.setup_send_set(i, settings.midi_mapping["sends"][i])
Exemple #40
0
    def __init__(self, MetNet, met, reac, number_food, targets, gen, p, inicial = False, control = None):
        #quais sao as caracteristicas em comum entre um organismo gerado from scratch
        #e um organismo proveninente de uma mutacao? Isso tem que estar no __init__
        
        #self.chemistry = MetNet

        self.age = 0
        self.record = 'a'
        self.mother_record = 'a'

        self.number_targets = targets
        food_list = range(number_food)
        
        if inicial: #verifica se a populacao eh inicial
            react_list = [x + met for x in range(MetNet.number_reactions)]
             

            if gen > len(react_list):
                raise GeneNumberException('There are more genes than reactions to be controlled!')

            genes_list = food_list + sorted(rndm.sample(react_list, gen))

            #talvez fosse util ter um dicionario que redireciona pra funcoes
            #dependendo do tipo de inicializacao - inicial ou mutacao - e
            #encapsular uma serie de coisas que por enquanto estao no __init__.

            self.chemistry = self.clean_met_net(MetNet, genes_list, food_list)
##            print 'o dicionario inicial de chemis:'
##            print self.chemistry.node
            self.control = Control(number_food, met, genes_list, p, reac, inicial)
##            print 'dicionario inicial:'
##            print self.control.switch_dict
            self.biomass = self.chemistry.update_reactions(self.control.switch_dict)
##            print 'biomass_init'
##            print self.biomass
        else: #caso a populacao seja gerada de uma mutacao...
            self.control = control
            self.chemistry = self.clean_met_net(MetNet, control.genes_list, food_list)
            self.biomass = self.chemistry.update_reactions(self.control.switch_dict)
Exemple #41
0
    def __init__(self, MetNet, inicial = False, control = None, EnvironmentSituation = None):
        self.age = 0
        self.record = 'a'
        self.mother_record = 'a'
        self.species = 'a'
        self.metabolites = Constants.metabolites
        self.number_targets = Constants.targets
        food_list = range(Constants.food)

        
        if inicial: #verifica se a populacao eh inicial
            react_list = [x + self.metabolites for x in range(Constants.reactions)]
             

            if Constants.genes > len(react_list):
                raise GeneNumberException('There are more genes than reactions to be controlled!')

            genes_list = food_list + sorted(rndm.sample(react_list, Constants.genes))

            #talvez fosse util ter um dicionario que redireciona pra funcoes
            #dependendo do tipo de inicializacao - inicial ou mutacao - e
            #encapsular uma serie de coisas que por enquanto estao no __init__.

            self.chemistry = self.clean_met_net(MetNet, genes_list, food_list, EnvironmentSituation)
##            print 'o dicionario inicial de chemis:'
##            print self.chemistry.node
            self.control = Control(genes_list, inicial)
##            print 'dicionario inicial:'
##            print self.control.switch_dict
            self.chemistry.update_reactions(self.control.switch_dict)
            self.biomass = Constants.division_threshold/2.0        #aqui eh a biomassa do organismo inicial.
##            print 'biomass_init'
##            print self.biomass
        else: #caso a populacao seja gerada de uma mutacao...
            self.control = control
            self.chemistry = self.clean_met_net(MetNet, control.genes_list, food_list, EnvironmentSituation)
            self.chemistry.update_reactions(self.control.switch_dict)
            self.biomass = Constants.division_threshold/2.0      #aqui deve ser a biomassa do organismo filho mutado.
Exemple #42
0
 def __find_remote_controls(self):
     self.notify_observers("FETCH", "Fetching remote controls")
     self.remote_controls = {}
     for (base_url, d_list, d_path, c_list, c_path) in Settings.get_setting('repositories'):
         rds = remote.get_controls(base_url, c_list, 
                                   Settings.get_setting('cache_dir'))
         self.remote_controls.update(rds)
         
         for d_key in rds:
             d_data = rds[d_key]
             d = Control(d_data['name'], d_data['description'], d_data['authors'])
             d.remote_domain = base_url
             
             d.set_available_remotely(True)
             for version_number in d_data['versions']:
                 d.add_version(version_number, d_data['versions'][version_number])
             #for ver in d_data['versions']:
              #   d.add_version(ver)
             self.add_control(d)
	def __init__(self, c_instance, selected_track_controller):
		Control.__init__(self, c_instance, selected_track_controller)
		
		# steps, when ABSOLUTE mode for tempo CC is used
		self.tempo_step = (settings.tempo_max - settings.tempo_min)/127.0
Exemple #44
0
    def __init__(self, physic_world, config=None):
        logging.info("INIT PLAYER...")
        logging.info("INIT FSM...")
        FSM.__init__(self, "FSM-Player")
        logging.info("INIT CONFIG...")
        Config.__init__(self)
        # additional initial configuration settings set by the outher application
        self.physic_world = physic_world
        logging.info("INIT PHYSICS...")
        Physics.__init__(self)
        logging.info("INIT CONTROLS...")
        Control.__init__(self)
        logging.info("INIT CAMERA...")
        Camera.__init__(
            self,
            self.cam_near_clip,
            self.cam_far_clip,
            self.cam_fov)
        logging.info("INIT ANIMATOR...")
        Animator.__init__(self)
        logging.info("INIT PLAYER DONE")

        #
        # STATES SETUP
        #
        self.on_ground_states = [
            self.STATE_IDLE,
            self.STATE_IDLE_TO_WALK,
            self.STATE_WALK,
            self.STATE_WALK_TO_IDLE,
            self.STATE_PLANT]
        # set the possible transition in the FSM
        self.defaultTransitions = {
            self.STATE_IDLE: [self.STATE_IDLE_TO_WALK, self.STATE_PLANT],
            self.STATE_IDLE_TO_WALK: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_WALK: [self.STATE_IDLE, self.STATE_WALK_TO_IDLE],
            self.STATE_WALK_TO_IDLE: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_PLANT: [self.STATE_IDLE],
            }

        #
        # ACTOR SETUP
        #
        Actor.__init__(
            self,
            self.model,
            {
                self.IDLE: self.anim_idle,
                self.WALK: self.anim_walk,
                self.PLANT: self.anim_plant,
            })
        self.setBlend(frameBlend=self.enable_interpolation)

        alphaSettings = ColorBlendAttrib.make(
            ColorBlendAttrib.MAdd,
            ColorBlendAttrib.OIncomingAlpha,
            ColorBlendAttrib.OOne,
            (0, 0, 0, 0))
        #self.setAttrib(alphaSettings)
        self.setBin("fixed", 15)
        self.setDepthWrite(False)

        #
        # CONTROLS SETUP
        #
        self.isDown = base.mouseWatcherNode.isButtonDown
        self.mainNode = self
Exemple #45
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from Synchronizer import Synchronizer
from Control import Control
from View import View
from twisted.python import log
from twisted.internet import task, reactor
from Networking import *
import sys

log.startLogging(sys.stdout)

ctl = Control()
syn = Synchronizer(ctl)

wsfactory = SydroidWebsocketFactory("ws://127.0.0.1:8007/", debug=True,
                                    on_receive=lambda x: ctl.parse_line(x))

listenWS(wsfactory)

locfactory = SydroidLiquidsoapFactory(on_receive=lambda x: ctl.parse_line(x))

reactor.listenUNIX('/tmp/sydroid.sock', locfactory)


def send(mesg):
    global wsfactory
    if mesg["type"] == "status":
        wsfactory.smart_broadcast(mesg)
    else:
    nx.draw_networkx_nodes(graph,positions, nodelist = listadenos, node_color=graph.colors,node_size=150)
    nx.draw_networkx_edges(graph,positions,alpha=0.3)
    plt.draw()

#completar com os estados

on = [True, True, False, True, True, True, False, False, True, False, False, False, False]

fl = [on[j] for j in range(food)]
env_list = [[True, True], [False, True], [True, True], [True, False], [True, True], [False, False]]
period = len(env_list)

index = (env_list.index(fl) + 1)%period


mae = nx.Graph()

for i in range(len(listadenos)):
    mae.add_node(listadenos[i], {'on': on[i]})

control = Control(DNA = D, mother = mae)

for i in range(50):
    draw_BN(control, control.pos, control.genes_list)
    control.change_state()
    time.sleep(1)
    if i%5 == 4:
        control.change_environment(env_list[index])
        index = (index+1)%period

Exemple #47
0
#completar com os estados

on = [False, True, False, False, False, False, False, False, False, True, False]

fl = [on[j] for j in range(food)]
env_list = [[True, True], [True, False], [False, False], [False, True]]
period = len(env_list)

index = (env_list.index(fl) + 1)%period


mae = nx.Graph()


for i in range(len(listadenos)):
    mae.add_node(listadenos[i], {'on': on[i]})



control = Control(DNA = D, mother = mae)


for i in range(50):
    draw_BN(control, control.pos, listadenos) #control.genes_list nao inclui os intermediarios e eles ficam sem o involucro do no
    control.change_state()
    time.sleep(1)
    if i%4 == 3:
        control.change_environment(env_list[index])           #mudar aqui o metodo de atualizacao de comidas
        index = (index+1)%period  #rndm.randint(0,period - 1)

Exemple #48
0
#!/usr/bin/env python3

from FirstSteps import FirstSteps as fs
from Control import Control as cn

if __name__ == '__main__':
    #print (fs.richter_scale())
    #print (fs.calculate_windchill_temperature_index())

    # Control class
    #cn.draw_regular_patterns()
    cn.making_change()
    #cn.menu_making_change()
Exemple #49
0
class TaskEditor(QtGui.QWidget):
    def __init__(self, parent=None, flags=0):
        super(TaskEditor, self).__init__(parent=None)
        self.setWindowTitle(u"BLOB Data Extract Tool")
        self.setWindowIcon(QtGui.QIcon('./blobdata_pump.ico'))
        self.globalLayout = QtGui.QGridLayout()
        self.setLayout(self.globalLayout)
        self.setMinimumSize(500, 700)
        self.globalLayout.setVerticalSpacing(4)
        self.globalLayout.setHorizontalSpacing(4)		
        self.globalLayout.setAlignment(Qt.Qt.AlignTop | Qt.Qt.AlignLeft)
        self.setWindowFlags(Qt.Qt.WindowStaysOnTopHint)

        self.dbConnStatus = False
        self.chooseColumnStatus = False
        self.control = Control()
        self.initUI()

    def initUI(self):
        #数据源
        sourceDBLabel = QtGui.QLabel(u'数据源连接:')
        sourceDBLabel.setFixedWidth(80)
        self.sourceDBText = QtGui.QLineEdit('system/oracle@orcl')
        self.sourceDBText.setMinimumWidth(280)
        self.sourceDBTestButton = QtGui.QPushButton(u'1.测试数据连接')
        self.sourceDBTestButton.clicked.connect(self.on_sourceDBTestButton_clicked)
        self.sourceDBTestLabel = QtGui.QLabel()
        self.sourceDBTestLabel.setFixedHeight(20)

        self.globalLayout.addWidget(sourceDBLabel, 0, 0, 1, 1)
        self.globalLayout.addWidget(self.sourceDBText, 0, 1, 1, 1)
        self.globalLayout.addWidget(self.sourceDBTestButton, 0, 2, 1, 1)
        self.globalLayout.addWidget(self.sourceDBTestLabel, 1, 1, 1, 2)


        #SQL区域
        self.blobIdSQLGroupBox = QtGui.QGroupBox(u"SQL1:填写获取需要抽取的图片的图片ID及其它列的SQL")
        blobIdSQLTipsLabel = QtGui.QLabel(u"图片ID列请指定别名为ImageId;其它列名也最好使用别名,以便程序识别,以下同理。")
        blobIdSQLTipsLabel.setStyleSheet('''QLabel{color:red}''')
        self.blobIdSQLLayout = QtGui.QVBoxLayout()
        self.blobIdSQLGroupBox.setLayout(self.blobIdSQLLayout)
        self.blobIdSQLEditor = QtGui.QTextEdit("select imageid as ImageId,xm from test_base")
        self.blobIdSQLEditor.setFixedHeight(60)
        self.blobIdSQLLayout.addWidget(blobIdSQLTipsLabel, 0, Qt.Qt.AlignTop)
        self.blobIdSQLLayout.addWidget(self.blobIdSQLEditor, 1, Qt.Qt.AlignTop)
        self.globalLayout.addWidget(self.blobIdSQLGroupBox, 2, 0, 1, 3, Qt.Qt.AlignTop)


        self.blobSQLGroupBox = QtGui.QGroupBox(u"SQL2:填写通过图片ID获取唯一图片及其它列的SQL")
        blobSQLTipsLabel = QtGui.QLabel(u"图片列请指定别名Image;同时条件中的图片ID的值请使用'%s'指定,如Where ImageId='%s'。")
        blobSQLTipsLabel.setStyleSheet('''QLabel{color:red}''')
        self.blobSQLLayout = QtGui.QVBoxLayout()
        self.blobSQLGroupBox.setLayout(self.blobSQLLayout)
        self.blobSQLEditor = QtGui.QTextEdit("SELECT zp as Image,sfzhm FROM test_image where imageid='%s'")
        self.blobSQLEditor.setFixedHeight(60)
        self.blobSQLLayout.addWidget(blobSQLTipsLabel, 0, Qt.Qt.AlignTop)
        self.blobSQLLayout.addWidget(self.blobSQLEditor, 1, Qt.Qt.AlignTop)
        self.globalLayout.addWidget(self.blobSQLGroupBox, 3, 0, 1, 3, Qt.Qt.AlignTop)		


        processesLabel = QtGui.QLabel(u"并发进程数:")
        self.processesEditor = QtGui.QLineEdit('6')
        #processesValidator = QtGui.QRegExpValidator(Qt.QRegExp('[0-9]+'))
        self.processesEditor.setValidator(QtGui.QIntValidator(1, 64))

        self.processesEditor.setFixedWidth(110)
        self.sourceTableColumnButton = QtGui.QPushButton(u"2.获取源数据所有列")
        self.sourceTableColumnButton.setEnabled(False)
        self.sourceTableColumnButton.clicked.connect(self.on_sourceTableColumnButton_clicked)
        self.globalLayout.addWidget(processesLabel, 4, 0, 1, 1)
        self.globalLayout.addWidget(self.processesEditor, 4, 1, 1, 1)
        self.globalLayout.addWidget(self.sourceTableColumnButton, 4, 2, 1, 1)

        """选择抽取图片到文件系统还是数据库"""
        self.extractMethodTab = QtGui.QTabWidget()
        self.initBlob2IOTab()
        self.initBlob2DBTab()
        self.globalLayout.addWidget(self.extractMethodTab, 5, 0, 1, 3)

    def initBlob2IOTab(self):
        #第一个TAB页
        self.blob2IOWidget = QtGui.QWidget()
        self.blob2IOLayout = QtGui.QGridLayout()
        self.blob2IOLayout.setVerticalSpacing(20)
        self.blob2IOLayout.setAlignment(Qt.Qt.AlignLeft | Qt.Qt.AlignTop)
        self.blob2IOWidget.setLayout(self.blob2IOLayout)

        #指定图片名称组成列
        blobNameSplitLabel = QtGui.QLabel(u'3.指定图片名分割符:')
        self.blobNameSplitText = QtGui.QLineEdit(u'_')
        self.blobNameSplitText.setFixedWidth(110)
        blobNameColumnLabel = QtGui.QLabel(u'4.指定图片名称列:')
        self.blob2IOLayout.addWidget(blobNameSplitLabel, 0, 0, 1, 1)
        self.blob2IOLayout.addWidget(self.blobNameSplitText, 0, 1, 1, 2)
        self.blob2IOLayout.addWidget(blobNameColumnLabel, 1, 0, 1, 1) 		

        #图片输出位置
        self.ioPathEdit = Qt.QLineEdit("e:\\")
        self.ioPathEdit.setFixedWidth(340)
        self.ioPathEdit.setEnabled(False)
        ioPathButton = Qt.QPushButton(u'5.选择图片输出目录')
        ioPathButton.clicked.connect(self.on_ioPathButton_clicked)
        self.blob2IOLayout.addWidget(ioPathButton, 7, 0, 1, 1)
        self.blob2IOLayout.addWidget(self.ioPathEdit, 7, 1, 1, 3)


        self.runButton1 = QtGui.QPushButton(u"任务开始")
        self.runButton1.setEnabled(False)
        self.runButton1.setObjectName('run1')
        self.runButton1.setFixedSize(110, 40)
        self.runButton1.setStyleSheet('''QPushButton{font-size:12px;font-weight:bold}''')
        self.runButton1.clicked.connect(self.on_runButton_clicked)
        self.blob2IOLayout.addWidget(self.runButton1, 8, 3, 1, 1, Qt.Qt.AlignBottom)


        self.extractMethodTab.addTab(self.blob2IOWidget, u'抽取图片到文件系统')


    def initBlob2DBTab(self):
        self.blob2DBWidget = QtGui.QWidget()
        blob2DBLayout = QtGui.QGridLayout()
        blob2DBLayout.setAlignment(Qt.Qt.AlignLeft | Qt.Qt.AlignTop)
        self.blob2DBWidget.setLayout(blob2DBLayout)

        #目标源
        targetDBLabel = QtGui.QLabel(u'目标库连接:')
        targetDBLabel.setFixedWidth(80)
        self.targetDBText = QtGui.QLineEdit('system/oracle@orcl')
        self.targetDBText.setMinimumWidth(280)
        self.targetDBTestButton = QtGui.QPushButton(u'3、测试目标库连接')
        self.targetDBTestButton.clicked.connect(self.on_targetDBTestButton_clicked)
        self.targetDBTestLabel = QtGui.QLabel()
        self.targetDBTestLabel.setFixedHeight(20)
        blob2DBLayout.addWidget(targetDBLabel, 0, 0, 1, 1)
        blob2DBLayout.addWidget(self.targetDBText, 0, 1, 1, 1)
        blob2DBLayout.addWidget(self.targetDBTestButton, 0, 2, 1, 1)
        blob2DBLayout.addWidget(self.targetDBTestLabel, 1, 1, 1, 2)

        self.extractMethodTab.addTab(self.blob2DBWidget, u'抽取图片到数据库')


        #目标表
        targetTableLabel = QtGui.QLabel(u'目标库表:')
        targetTableLabel.setFixedWidth(80)
        self.targetTableText = QtGui.QLineEdit('test_target')
        self.targetTableText.setMinimumWidth(280)
        self.targetTableColumnButton = QtGui.QPushButton(u'4、获取目标表字段')
        self.targetTableColumnButton.setEnabled(False)
        self.targetTableColumnButton.clicked.connect(self.on_targetTableColumnButton_clicked)
        self.targetTableTestLabel = QtGui.QLabel()
        blob2DBLayout.addWidget(targetTableLabel, 2, 0, 1, 1)
        blob2DBLayout.addWidget(self.targetTableText, 2, 1, 1, 1)
        blob2DBLayout.addWidget(self.targetTableColumnButton, 2, 2, 1, 1)
        blob2DBLayout.addWidget(self.targetTableTestLabel, 3, 1, 1, 2)

        #映射列
        self.mapColumnWidget = QtGui.QGroupBox(u"源表列与目标列映射关系")
        self.mapColumnWidget.setMaximumWidth(365)
        self.mapColumnLayout = QtGui.QGridLayout()
        self.mapColumnLayout.setAlignment(Qt.Qt.AlignLeft | Qt.Qt.AlignCenter)
        self.mapColumnWidget.setLayout(self.mapColumnLayout)
        self.mapColumnLayout.addWidget(QtGui.QLabel(u'源表列'), 0, 0, 1, 1, Qt.Qt.AlignCenter)
        self.mapColumnLayout.addWidget(QtGui.QLabel(u'目标表列'), 0, 1, 1, 1, Qt.Qt.AlignCenter)
        self.mapColumnLayout.setColumnStretch(0, 1)
        self.mapColumnLayout.setColumnStretch(1, 1)
        blob2DBLayout.addWidget(self.mapColumnWidget, 4, 0, 3, 3)

        
        self.runButton2 = QtGui.QPushButton(u"任务开始")
        self.runButton2.setEnabled(False)
        self.runButton2.setObjectName('run2')
        self.runButton2.setFixedSize(110, 40)
        self.runButton2.setStyleSheet('''QPushButton{font-size:12px;font-weight:bold}''')
        self.runButton2.clicked.connect(self.on_runButton_clicked)
        self.mapColumnTipLabel = QtGui.QLabel()
        self.mapColumnTipLabel.setWordWrap(True)
        self.mapColumnTipLabel.setStyleSheet('''QLabel{color:red}''')
        blob2DBLayout.addWidget(self.runButton2, 4, 2, 1, 1, Qt.Qt.AlignTop)
        blob2DBLayout.addWidget(self.mapColumnTipLabel, 5, 2, 2, 1, Qt.Qt.AlignTop)


    def on_sourceDBTestButton_clicked(self):
        dbConnStr = self.sourceDBText.text()
        if not dbConnStr:
            return
        testResult = self.control.getDBConnStatus(str(dbConnStr))

        if testResult:
            self.dbConnStatus = True
            self.sourceDBTestLabel.setText(u"* 源数据库连接成功")
            self.sourceDBTestLabel.setStyleSheet('''QLabel{color:green}''')
            self.sourceTableColumnButton.setEnabled(True)
        else:
            self.dbConnStatus = False
            self.sourceDBTestLabel.setText(u"* 源数据库数据失败")
            self.sourceDBTestLabel.setStyleSheet('''QLabel{color:red}''')
            self.sourceTableColumnButton.setEnabled(False)


    def on_ioPathButton_clicked(self):
        filename = QtGui.QFileDialog.getExistingDirectory(self, u'选择图片输出目录', 'e:\\')
        if filename:
            self.ioPathEdit.setText(filename)

    def on_targetDBTestButton_clicked(self):
        dbConnStr = str(self.targetDBText.text())
        if not dbConnStr:
            return
        testResult = self.control.getDBConnStatus(dbConnStr, 'targetDB')


        if testResult:
            self.dbConnStatus = True
            self.targetDBTestLabel.setText(u"* 源数据库连接成功")
            self.targetDBTestLabel.setStyleSheet('''QLabel{color:green}''')
            self.targetTableColumnButton.setEnabled(True)
        else:
            self.dbConnStatus = False
            self.targetDBTestLabel.setText(u"* 源数据库连接失败")
            self.targetDBTestLabel.setStyleSheet('''QLabel{color:red}''')

    def on_targetTableColumnButton_clicked(self):
        tableName = str(self.targetTableText.text())
        if self.dbConnStatus:
            result = self.control.getTargetTableColumn(tableName)
            self.showMapColumnGrid(result, 'right')
            self.targetTableTestLabel.setText(u"* 获取列信息成功")
            self.targetTableTestLabel.setStyleSheet('''QLabel{color:green}''')
            self.runButton2.setEnabled(True)
        else:
            self.targetTableTestLabel.setText(u"* 获取列信息失败")
            self.targetTableTestLabel.setStyleSheet('''QLabel{color:red}''')



    def showMapColumnGrid(self, columnList, location = 'left'):
        for w in self.mapColumnWidget.findChildren(Qt.QWidget, Qt.QRegExp('.*' + location + '.*')):
            w.deleteLater()
        self.mapColumnWidget.update()
        
        if location == 'right':
            columnList.append('')

        for i in range(len(columnList) - 1):
            mapColumnComboBox = QtGui.QComboBox()
            mapColumnComboBox.setFixedSize(110, 20)
            mapColumnComboBox.setObjectName('mapColumnComboBox-' + location + '-' + str(i))
            for cName in columnList:
                mapColumnComboBox.addItem(Qt.QString(cName), Qt.QVariant(cName))
            if location == 'left':
                self.mapColumnLayout.addWidget(mapColumnComboBox, i + 1, 0, 1, 1, Qt.Qt.AlignCenter)
            else:
                self.mapColumnLayout.addWidget(mapColumnComboBox, i + 1, 1, 1, 1, Qt.Qt.AlignCenter)


    def on_sourceTableColumnButton_clicked(self):
        blobIdSQL = self.blobIdSQLEditor.toPlainText()
        blobSQL = self.blobSQLEditor.toPlainText()
        
        columnList = self.control.getSourceTableColumnName(str(blobIdSQL), str(blobSQL))
        columnList.append('')
        for w in self.blob2IOWidget.findChildren(Qt.QComboBox, Qt.QRegExp('blobNameColumnComboBox.*')):
            w.deleteLater()

        for i in range(len(columnList) - 2):
            blobNameColumnComboBox = QtGui.QComboBox()
            blobNameColumnComboBox.setFixedWidth(110)
            blobNameColumnComboBox.setObjectName("blobNameColumnComboBox-" + str(i + 1))
            
            for c in columnList:
                if c.endswith('.Image'):
                    continue
                blobNameColumnComboBox.addItem(Qt.QString(c), Qt.QVariant(c))
            self.blob2IOLayout.addWidget(blobNameColumnComboBox, i / 4 + 2, i % 4, 1, 1)			

        self.showMapColumnGrid(columnList, 'left')

        self.runButton1.setEnabled(True)


    def genFetchBlobSQL(self):
        BlobSQLText = QtGui.QTextEdit()
        targetTableName = str(self.targetDBText.text())
        targetTableColumn = []
        for w in self.mapColumnWidget.findChildren(Qt.QWidget, Qt.QRegExp('.*right.*')):
            targetTableColumn.append(w.currentText())

        sourceTableColumn = []
        for w in self.mapColumnWidget.findChildren(Qt.QWidget, Qt.QRegExp('.*left.*')):
            sourceTableColumn.append(w.currentText())

    def on_runButton_clicked(self):
        objName = self.sender().objectName()
        processes = str(self.processesEditor.text())
        processes = 0 if not processes else int(processes)        
        blobNameColumn = []
        if objName == 'run1':
            spliter = str(self.blobNameSplitText.text())
            for comboBox in self.blob2IOWidget.findChildren(Qt.QComboBox, Qt.QRegExp('blobNameColumnComboBox.*')):
                columnName = str(comboBox.currentText())
                if columnName:
                    blobNameColumn.append(columnName)
            filePath = str(self.ioPathEdit.text())
            self.control.runBlob2IO(spliter, blobNameColumn, filePath, processes)
        else:            
            mapColumnList = []
            for comboBox in self.blob2DBWidget.findChildren(Qt.QComboBox, Qt.QRegExp('mapColumnComboBox.*')):
                comboBoxName = str(comboBox.objectName())
                comboxNamePre, comboBoxDirec, comboBoxIndex = comboBoxName.split('-')
                comboBoxDirec = 0 if comboBoxDirec == 'left' else 1
                comboBoxIndex = int(comboBoxIndex)
                columnName = str(comboBox.currentText()) \
                    if comboBoxDirec == 0 else str(comboBox.currentText()).split(' ')[0]
                if len(mapColumnList) >= comboBoxIndex + 1:
                    mapColumnList[comboBoxIndex][comboBoxDirec] = columnName
                else:
                    mapColumnList.append([columnName, ''] if comboBoxDirec == 0 else ['', columnName])
             
            newMapColumn = []    
            if [i[0].upper() for i in mapColumnList].count('SQL2.IMAGE') == 0:
                self.mapColumnTipLabel.setText(u"* 请指定图片列的映射关系")
                return
            
            sourceColumn = [i[0] for i in mapColumnList]
            for l, r in mapColumnList:
                if not l or not r:
                    continue
                if mapColumnList.count([l, r]) > 1:
                    self.mapColumnTipLabel.setText(u"* 存在相同的列映射关系")
                    return
                if sourceColumn.count(l) > 1:
                    self.mapColumnTipLabel.setText(u"* 源表列中存在相同的列,请在SQL中使用不同的别名,以便区分")
                    print(mapColumnList, sourceColumn)
                    return

                
                newMapColumn.append([l, r])
            self.mapColumnTipLabel.setText(u"")
            self.control.runBlob2DB(newMapColumn, processes)            
Exemple #50
0
class Organism(nx.DiGraph):
    def __init__(self, MetNet, met, reac, number_food, targets, gen, p, inicial = False, control = None):
        #quais sao as caracteristicas em comum entre um organismo gerado from scratch
        #e um organismo proveninente de uma mutacao? Isso tem que estar no __init__
        
        #self.chemistry = MetNet

        self.age = 0
        self.record = 'a'
        self.mother_record = 'a'

        self.number_targets = targets
        food_list = range(number_food)
        
        if inicial: #verifica se a populacao eh inicial
            react_list = [x + met for x in range(MetNet.number_reactions)]
             

            if gen > len(react_list):
                raise GeneNumberException('There are more genes than reactions to be controlled!')

            genes_list = food_list + sorted(rndm.sample(react_list, gen))

            #talvez fosse util ter um dicionario que redireciona pra funcoes
            #dependendo do tipo de inicializacao - inicial ou mutacao - e
            #encapsular uma serie de coisas que por enquanto estao no __init__.

            self.chemistry = self.clean_met_net(MetNet, genes_list, food_list)
##            print 'o dicionario inicial de chemis:'
##            print self.chemistry.node
            self.control = Control(number_food, met, genes_list, p, reac, inicial)
##            print 'dicionario inicial:'
##            print self.control.switch_dict
            self.biomass = self.chemistry.update_reactions(self.control.switch_dict)
##            print 'biomass_init'
##            print self.biomass
        else: #caso a populacao seja gerada de uma mutacao...
            self.control = control
            self.chemistry = self.clean_met_net(MetNet, control.genes_list, food_list)
            self.biomass = self.chemistry.update_reactions(self.control.switch_dict)
            

    def clean_met_net(self, MetNet, genes_list, food_list):
        #Verificar com mais calma se a delecao de targets nao afeta nada...
        chemis = deepcopy(MetNet)
        #sera que esse objeto vai receber as funcoes da classe MetabolicNetwork?

        for r in [x for x in MetNet.nodes() if MetNet.node[x]['Type'] == 'R']:
            if r not in [reac for reac in genes_list if reac not in food_list]:
                chemis.remove_node(r)
        #Alguns targets podem ser deletados nesse passo:
        chemis.remove_nodes_from([isol for isol in nx.isolates(chemis) if isol not in food_list])

        #chemis.remove_nodes_from([n for n in nx.isolates(chemis) if n not in food_list])????
        #Talvez tenha que verificar se food ou target molecules foram removidos?
        return chemis
    
    def change_environment_org(self, food_list):
        self.control.change_environment(food_list)
        self.chemistry.update_food(self.control.food_dict)

    def mutate(self, rate, MetNet):

        DNAp = self.control.export_code()
        DNAm = mutate_DNA(DNAp, rate)
        control_son = Control(MetNet.number_food, MetNet.number_metabolites, [], 0, MetNet.number_reactions, DNA = DNAm, mother = self.control)
        
        return Organism(MetNet, MetNet.number_metabolites, MetNet.number_reactions, MetNet.number_food, MetNet.number_targets, 0, 0, inicial = False, control = control_son)
Exemple #51
0
 def test_delimiter(self):
    c = Control('testfile.csv')
    c.delimiter = ';'
    self.assertEqual(c.delimiter, ';')
Exemple #52
0
 def test_falseDelimiter(self):
    c = Control('testfile.csv')
    c.delimiter = ' '
    self.assertEqual(c.delimiter, ' ')
	def __init__(self, c_instance, selected_track_controller):
		Control.__init__(self, c_instance, selected_track_controller)
		
		if settings.auto_select_playing_clip:
			self.song.view.add_selected_track_listener(self.on_track_selected)
	def __init__(self, c_instance, selected_track_controller):
		Control.__init__(self, c_instance, selected_track_controller)
		
		self.view = Live.Application.get_application().view
		self.views = self.view.available_main_views()
Exemple #55
0
class Robot(object):

    # Constructor
    # @param env     The Robot's Environment
    # @param slam    SLAM algorithm
    # @param control A Control object
    # @param sensor  A Sensor object
    # @param pose    Initial pose
    # @param v       Translational velocity
    # @param color   Color of the robot (black by default)
    def __init__(self, env, slam, control, sensor, pose, robot_id, v=0.0, color="yellow"):
        self._env = env
        self._slam = slam
        self._control = control
        self._sensor = sensor
        self._pose = pose
        self._id = robot_id
        self._v = v
        self._color = color

        # Radius is 6% of env height
        self._r = int(self._env.h() * 0.06)

        # Create a control, if none was given    
        if not self._control:
            noise = (0.3, 0.3, 0.05)    # (x, y, theta) noise
            self._control = Control(env, v, noise)

        # Create a sensor, if none was given
        if not self._sensor:
            sensor_range = self._r * 4.0
            noise = ((sensor_range * 0.05, 0.01), np.matrix([[0.70, 0.0], [0.0, 0.70]]))
            self._sensor = Sensor(self._env, sensor_range=sensor_range, noise=noise, width=2.0*self._r)

        # Create a SLAM algorithm object, if none was given
        if not self._slam:
            M = 20    # number of particles
            self._slam = FastSLAM(self._control, self._sensor, pose, M, self._env.get_landmark_count())

    def slam(self): return self._slam

    def pose(self): return self._pose

    # Draw the robot at its current pose
    # @param canvas The canvas onto which to draw the robot
    def draw(self, canvas):
        (x, y, theta) = self._pose

        # Lest we forgot to render the sensor "beam"...
        self._sensor.draw(canvas, self._pose)

        # Draw the circle, which is the body of the robot
        canvas.create_oval(
                   x - self._r,
                   y + self._r,
                   x + self._r,
                   y - self._r,
                   outline="black",
                   fill=self._color,
                   width=1,
                   tags=('robot', 'body'))

        # Next, wheel axis
        canvas.create_line(
                   x - int(self._r * sin(theta)), 
                   y + int(self._r * cos(theta)),
                   x + int(self._r * sin(theta)), 
                   y - int(self._r * cos(theta)),
                   fill="black",
                   tags=('robot', 'wheelaxis'))

        # Now comes the wheels
        # TODO (not strictly necessary)

        # Finally, draw the arrow indicating robot direction perpendicular
        # to the wheel axis
        canvas.create_line(
                   x, 
                   y,
                   x + self._r * cos(theta),
                   y + self._r * sin(theta),
                   arrow=LAST,
                   arrowshape=(3,5,3),
                   fill="black",
                   tags=('robot', 'direction'))

    # Update the Robot's pose
    # @param dt Time delta
    def update(self, dt):
        (x, y, theta) = self._pose
      
        # Make the move (might be undone in case of collision) 
        (new_x, new_y, _) = self._control.move(self._pose, dt)
 
        # Take a sensor reading, see if there are any impending collisions
        measurements = self._sensor.sense((new_x, new_y, theta))
        sensed_collision = False
        if len(measurements) > 0:
            # Taking this move will lead to a collision, so stay where we are
            new_x, new_y = x, y
            sensed_collision = True
        
        # Query the control for the new heading
        self._pose = (new_x, new_y, self._control.action(sensed_collision, theta))

        # Finally, run the SLAM algorithm
        self._slam._x = self._pose
        self._slam.run(measurements, dt)
                
        return self
Exemple #56
0
import os
import logging
import time
from gui.MainFrame import MainFrame
from Const import *
from Control import Control
from ConfigUtils import Config
from Log import Log

Config.load()

# pyCurl does not like signal
log = Log()
try:
    import signal
    from signal import SIGPIPE, SIG_IGN

    signal.signal(signal.SIGPIPE, signal.SIG_IGN)
except ImportError, e:
    log.debug("Main ImportError", e)
    print "Cannot handle signal..."

app = wx.PySimpleApp()
app.SetAssertMode(wx.PYAPP_ASSERT_DIALOG)

control = Control()
mainFrame = MainFrame(None, wx.ID_ANY, "Linux Rapidshare Grabber", (0, 0), (800, 600), control)
control.setMainFrame(mainFrame)
control.start()
app.MainLoop()
 def iniciar_controles(self):
     self.Controles = Control()
     self.Controles.repeat(400, 50)
Exemple #58
0
	def __init__(self):
		self.gameState = 1			#State of game: 1 if playing, 0 if game over
		self.player = 'white'		#Current player: white player always starts
		self.board = Board()		#The board representation
		self.control = Control()	#The control that handles user input
		self.sp = Speech()			#The verbal feedback given by the computer
Exemple #59
0
class Organism(nx.DiGraph):
    def __init__(self, MetNet, inicial = False, control = None, EnvironmentSituation = None):
        self.age = 0
        self.record = 'a'
        self.mother_record = 'a'
        self.species = 'a'
        self.metabolites = Constants.metabolites
        self.number_targets = Constants.targets
        food_list = range(Constants.food)

        
        if inicial: #verifica se a populacao eh inicial
            react_list = [x + self.metabolites for x in range(Constants.reactions)]
             

            if Constants.genes > len(react_list):
                raise GeneNumberException('There are more genes than reactions to be controlled!')

            genes_list = food_list + sorted(rndm.sample(react_list, Constants.genes))

            #talvez fosse util ter um dicionario que redireciona pra funcoes
            #dependendo do tipo de inicializacao - inicial ou mutacao - e
            #encapsular uma serie de coisas que por enquanto estao no __init__.

            self.chemistry = self.clean_met_net(MetNet, genes_list, food_list, EnvironmentSituation)
##            print 'o dicionario inicial de chemis:'
##            print self.chemistry.node
            self.control = Control(genes_list, inicial)
##            print 'dicionario inicial:'
##            print self.control.switch_dict
            self.chemistry.update_reactions(self.control.switch_dict)
            self.biomass = Constants.division_threshold/2.0        #aqui eh a biomassa do organismo inicial.
##            print 'biomass_init'
##            print self.biomass
        else: #caso a populacao seja gerada de uma mutacao...
            self.control = control
            self.chemistry = self.clean_met_net(MetNet, control.genes_list, food_list, EnvironmentSituation)
            self.chemistry.update_reactions(self.control.switch_dict)
            self.biomass = Constants.division_threshold/2.0      #aqui deve ser a biomassa do organismo filho mutado.
            

    def clean_met_net(self, MetNet, genes_list, food_list, EnvironmentSituation):
        #Verificar com mais calma se a delecao de targets nao afeta nada...
        chemis = deepcopy(MetNet)
        #sera que esse objeto vai receber as funcoes da classe MetabolicNetwork?

        for r in [x for x in MetNet.nodes() if MetNet.node[x]['Type'] == 'R']:
            if r not in [reac for reac in genes_list if reac not in food_list]:
                chemis.remove_node(r)
        #Alguns targets podem ser deletados nesse passo:
        chemis.remove_nodes_from([isol for isol in nx.isolates(chemis) if isol not in food_list])
        
        if EnvironmentSituation is not None:
            for f in range(Constants.food):
                chemis.node[f]['Flowing'] = EnvironmentSituation[f]

        #chemis.remove_nodes_from([n for n in nx.isolates(chemis) if n not in food_list])????
        #Talvez tenha que verificar se food ou target molecules foram removidos?
        return chemis
    
    def change_environment_org(self, food_list):
        self.control.change_environment(food_list)
        #print 'compare a lista e o dicionario:'
        #print food_list
        #print self.control.food_dict
        self.chemistry.update_food(self.control.food_dict)

    def mutate(self, rate, MetNet, EnvironmentSituation):

        DNAp = self.control.export_code()
        DNAm = mutate_DNA(DNAp, rate)
        control_son = Control(DNA = DNAm, mother = self.control)
        
        return Organism(MetNet, False, control_son, EnvironmentSituation)