class Controller(threading.Thread): def __init__(self): threading.Thread.__init__(self) #是否更新 #False表示下载url_queue的链接,True表示更新, self.run_list=[False,True] self.run_sqe=0 self.engine_is_running=False def run(self): '''循环运行''' self.is_running=True #设置运行类型 self.is_update=self.run_list[self.run_sqe] settings.S_is_update=self.is_update self.eng=Engine(settings.S_target_website) self.eng.start() self.run_sqe+=1 if self.run_sqe>=len(self.run_list): self.run_sqe=0 self.engine_is_running=True self.eng.join() if self.is_running: self.run() def stop(self): self.eng.is_running=False self.is_running=False
class EnigmaX(): def __init__(self): self.builder = Gtk.Builder() self.builder.add_from_file(gtk_builder_file) self.engine = Engine() self.window = self.builder.get_object('windowMain') self.textBox = self.builder.get_object('entry') self.label = self.builder.get_object('label') self.label2 = self.builder.get_object('enigma') self.engineToString() self.textBox.connect('activate', self.signal_text_activate) self.textBox.connect('changed', self.signal_text_changed) self.window.connect('destroy', self.signal_window_destroy) self.ciphertext = '' self.window.show_all() def signal_window_destroy(self, _): self.window.destroy() Gtk.main_quit() def signal_text_activate(self, *args): self.label.set_text(self.engine.run(self.textBox.get_text())) self.engineToString() def signal_text_changed(self, *args): newChar = self.textBox.get_text()[-1] if len(self.textBox.get_text()) else '' self.ciphertext += self.engine.translate(newChar.upper()) self.label.set_text(self.ciphertext) self.engineToString() def engineToString(self): self.label2.set_text(self.engine.toString())
def on_err_disconnect(self): """ The engine node disconnected from the message bus. This will emit a SigDisconnect signal. """ Engine.on_err_disconnect(self) self.parent.emit(QtCore.SIGNAL(SigDisconnect))
def start_engine(args): if not (args.name and args.engine_cfg): LOG.error('Need name and engine cfg') return utils.create_files([engine_cfg]) if args.purge: utils.purge_disabled(engine_cfg) if utils.check_exists_and_enabled(args.name, engine_cfg): LOG.error("An engine of the same name %s is already " "registered and running", args.name) return if utils.check_exists_and_disabled(args.name, engine_cfg): LOG.error("And engine of the same name %s is already " "registered, but disabled. Run with purge?", args.name) return try: cfg_data = dict(utils.load_yaml(args.engine_cfg))[args.name] cfg = { args.name: { 'cfg': os.path.join(os.getcwd(), args.engine_cfg), 'pid': os.getpid(), 'backend': cfg_data['backend'], 'enabled': True } } utils.write_yaml(cfg, engine_cfg) LOG.info('Added %s to engine cfg', args.name) entropy_engine = Engine(args.name, **cfg_data) entropy_engine.run() except Exception: LOG.exception("Could not start engine %s", args.name) return
def main(): parser = ArgumentParser() parser.add_argument('name', help='name of language configuration') parser.add_argument( '-v', '--verbose', action='store_true', help='show intermediate sound changes' ) parser.add_argument( '-r', '--repeat', type=int, default=1, help='generate multiple words' ) parser.add_argument( '-p', '--phonetic', action='store_true', help='show phonetic transcriptions' ) parser.add_argument( '-R', '--raw', action='store_true', help='show raw state machine output' ) parser.add_argument( '-w', '--words', nargs='+', help='use given words instead of state machine output' ) engine = Engine(parser) engine.run()
class TestEngine(unittest.TestCase): def setUp(self): self.x = Engine(simple_lesson) def test_new(self): self.assertIsNotNone(self.x) def test_process_first(self): new_state, messages = self.x.process_message() self.assertEqual(new_state, 1) self.assertEqual(messages, ["First prompt", "The first question."]) def test_process_correct_answer(self): new_state, messages = self.x.process_message(1, "a") self.assertEqual(new_state, 2) self.assertEqual(messages, ["That is correct.", "The second question."]) def test_process_incorrect_answer(self): new_state, messages = self.x.process_message(2, "b") self.assertEqual(new_state, 2) self.assertEqual(messages, ["Wrong!"]) def test_process_last_correct_answer(self): new_state, messages = self.x.process_message(2, "a") self.assertEqual(new_state, -1) self.assertEqual(messages, ["That is correct.", "Quiz Complete!"]) def test_process_invalid_response(self): new_state, messages = self.x.process_message(1, "x") self.assertEqual(new_state, 1) self.assertEqual(messages, ["Invalid response, try again."])
def __init__(self, host_device, engine_id, config_source): """ """ Engine.__init__(self, host_device, engine_id, config_source) # check that we have all the required attributes for an f-engine assert hasattr(self, 'vacc_len'), 'x-engine must have a vector accumulator length'
class Test(unittest.TestCase): #-------------------------------------------------------------------------- def setUp(self): self.eng = Engine() self.que = Queuer() self.gen = TaskerGenerator(self.eng, 'taskerGen', self.que, timeStart=1.0, timeEnd=1000.0, taskStart=1.0, taskEnd=500.0, limit=100) self.svc = Servicer(self.que, self.eng) #-------------------------------------------------------------------------- def tearDown(self): pass #-------------------------------------------------------------------------- def test_init(self): pass #-------------------------------------------------------------------------- def test_run(self): # Test self.gen.start() self.svc.start() self.eng.runEngine() # Expectations self.svc.reportStats()
def main(): os.environ["SDL_VIDEO_CENTERED"] = "1" pygame.init() game_data = { TITLE: "Crazy Ant", SIZE: (640, 480), FONT: Font(None, 32), LEVELS: [ "level1", "level2", "level3", ], LEVEL_DATA: { "level1": { FILE: "level1.lvl", }, "level2": { FILE: "level2.lvl", }, "level3": { FILE: "level3.lvl", }, }, CONTROLS: { LEFT: K_a, RIGHT: K_d, JUMP: K_s }, } engine = Engine(game_data) engine.run()
def on_init(self): Engine.on_init(self) self.winner_text = Text(self.width/4, 80, str(""), 30) self.add(self.winner_text) self.start_game_text = Text(self.width/3, 120, str("Press START"), 30) self.add(self.start_game_text) self.scoreP1_text = Text(self.width/4, 30, str(self.scoreP1), 50) self.scoreP2_text = Text(self.width - self.width/4, 30, str(self.scoreP2), 50) self.add(self.scoreP1_text) self.add(self.scoreP2_text) self.fps_text = Text(280, 220, "30") self.add(self.fps_text) self.ball = Ball(self.width/2, self.height/2, "ball.png") self.add(self.ball) self.playerOne = Paddle(20, self.height/2, "paddle.png") self.add(self.playerOne) self.playerTwo = Paddle(320 - 20, self.height/2, "paddle.png") self.add(self.playerTwo) self.sfx_padOne = soundEffect("blip1.wav") self.sfx_padTwo = soundEffect("blip2.wav") self.music_bg = musicPlayer("UGH1.wav", -1) self.music_bg.play() self.start_game(False)
def __init__(self, autoConnect = False): Application.__init__(self) Engine.__init__(self) #ip, port = "cradle.dyndns.org", "10001" ip, port = "127.0.0.1", "10001" if not autoConnect: address = raw_input("server ('%s:%s') :> " % (ip, port)) if address != "": split = address.split(":") ip = split[0] if len(split) == 2: port = split[1] self.chat = gamenet.NetCode("cradle", "cradle.dyndns.org", "AV", "enter", "-".join([ip, port])) self.chat.registerMessageListener(self.messageListener) self.timeBetweenChatUpdates = 0.5 self.timeUntilNextChatUpdate = 0.0 self.network = networkclient.NetworkClient(ip, int(port)) self.timeBetweenNetworkUpdates = 0.02 self.timeUntilNextNetworkUpdate = 0.0 self.serverRoundTripTime = 0.0 self.lastServerUpdate = time.time() self.player = None
def on_message(self, sender=None, message=None): logging.info("Recieved message from %s: %s", sender, message) if sender is None or message is None or message == "": raise Error("Invalid sender or message.") # Admin start command requires 10 digit phone NOT prefixed with "+1" if message.split(' ')[0].lower() == "start": sender = "+1" + message.split(' ')[1] logging.info("AdminStart for #: %s", sender) message = "AdminStart" student = Student.ensure_student(phone=sender) try: student.totalMsgReceived except: student.totalMsgReceived = 1 else: student.totalMsgReceived += 1 student.put() session = Session.ensure_session(student.get_id()) lesson = self.lessons.get(session.lesson_id) if lesson is None: raise Error("No such lesson: %s" % session.lesson_id) json_data = open('hiragana.json') data = json.load(json_data) json_data.close() eng = Engine(data) messages = eng.process_message_dev(message, student) #logging.info("Student's foo: %s" % student.questionHistory['foo']) if session.state == -1: session.key.delete() else: session.put() self.send_SMS_replies(sender, messages)
def on_err_disconnect(self): """ Called automatically when the engine messagebus node exits/closes. This will emit a EvtDisconnect event. """ Engine.on_err_disconnect(self) self.parent.event_generate(EvtDisconnect, when='tail')
class IndexerThread(threading.Thread): def __init__(self, queue, index_directory, log_rate, log_file): self.search_engine = Engine(index_directory) self.buffered_writer = self.search_engine.new_buffered_writer(120, 100 , 512) self.queue = queue self.log_count = 0 self.log_rate = log_rate self.log_file = log_file threading.Thread.__init__(self) # needed for thread to be instantiated def run(self): while True: while not self.queue.empty(): path, add_or_delete = self.queue.get_nowait() time_taken, successful = self.add_or_remove(path, add_or_delete) if successful: if self.log_count % self.log_rate == 0: if add_or_delete: log(self.log_file, ("time taken to index path: ", [time_taken, path, str(datetime.now())])) else: log(self.log_file, ("time taken to un-index path: ", [time_taken, path, str(datetime.now())])) else: log(self.log_file,("index/ un-index of path was unsuccessful: ", [path, str(datetime.now())])) self.log_count += 1 """ This method indexes/ removes an index of 'path', and returns the time taken to do so. params: - path: the path to index/ remove from index - add_or_delete: True for add/ False for delete return: - time_taken (0.0 if unsuccessful; i.e. directory, not file) - boolean of successful or not (whether file or directory) """ def add_or_remove(self, path, add_or_delete): if os.path.isdir(path): return [0.0, False] t0 = time.time() if add_or_delete: self.search_engine.add_document(path, self.buffered_writer) else: self.search_engine.remove_document(path, self.buffered_writer) t1 = time.time() time_taken = t1 - t0 return [time_taken, True]
def main(): dimension = int(input("Type the dimension of the game: ")) grid = int(input("Type the grid of the game: ")) food_score = int(input("Type the score for each food: ")) bonus_score =int(input("Type the score for each bonus: ")) snake_color = input("Type the snake color (green, blue, red, yellow, purple or orange): ") engine = Engine(dimension, grid, food_score, bonus_score, snake_color) #, pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) engine._exec_()
def on_disconnect(self): """ Overloaded on_disconnect method of client to preform engine tasks """ Engine.on_disconnect(self) # stop any running user code self.stop_code(quiet=True)
def on_err_disconnect(self): """ Overloaded on_err_disconnect method to call both base classes """ Engine.on_err_disconnect(self) # stop any running user code self.stop_code(quiet=True)
def main(): Engine.initialize(APP_NAME, APP_VERSION) device = GraphicsDevice() mainloop(device) Engine.finalize() return 0
def on_err_disconnect(self): """ The engine node disconnected from the message bus. This will emit a "engine_disconnect" signal after preforming standard engine disconnect tasks """ Engine.on_err_disconnect(self) gobject.idle_add(self.parent.emit, "engine_disconnect")
def messageCB(session,mess): text = mess.getBody() user = mess.getFrom() logging.debug("MSG: %s from %s" % (text, user)) if text is None: return logging.debug("dispatching to parser engine") engine = Engine(user.getStripped()) msg = engine.parse(text) session.send(xmpp.Message(user,msg))
def main(): fn = sys.argv[1] # TODO : use getopt? db_print ('user folder is :',fn) if os.path.exists(fn): db_print (os.path.basename(fn),'exists') # file exists parse_folder(fn) e = Engine(actors=Actor.registry) e.run()
def frameEnded(self, frameTime): self.timeUntilNextNetworkUpdate -= frameTime if self.timeUntilNextNetworkUpdate <= 0.0: self.networkUpdate() Engine.frameEnded(self, frameTime) self.sleep() return self.network.reactor.running
def __init__(self, englabel=None, userdict={}, timeout=10): Engine.__init__(self, englabel, userdict, timeout) #---setup an event to indicate code to run------------------------------ self._codeevent = threading.Event() #event to indicate code to run self._code = None #code object to run in mainloop as the user self._exit = False #exit flag
def update(self): if not self.pause: super(PlayState, self).update() self.collisions() # if Engine.just_pressed(K_ESCAPE): Engine.post(QUIT) elif Engine.just_pressed(K_p): self.pause = not self.pause
def on_err_disconnect(self): """ The engine node disconnected from the message bus. This will wake the main loop. """ Engine.on_err_disconnect(self) log.info('Exiting process') self._exit = True self.stop_code(quiet=True) self._codeevent.set() #trigger the event to wake up the mainloop
def parse(self): if not os.path.exists(self._filename): print("no file %s" % self._filename) return False engine = untangle.parse(self._filename) engine_attributes = engine.engine_database.engine_list.engine data_points = [(dp["t"],dp["f"], dp["m"]) for dp in engine.engine_database.engine_list.engine.data.eng_data] engine = Engine(**engine_attributes._attributes) engine.data_points = data_points return engine
def main(): pygame.init() game_data = { SIZE: (640, 480), FONT: Font(None, 32) } engine = Engine(game_data) engine.run()
def parse(self): if not os.path.exists(self._filename): return False lines = [] code = "" dia = 0.0 length = 0.0 mfg = "" delays="" mass = 0.0 prop_mass = 0.0 data_points = [] with open(self._filename) as f: lines = f.readlines() for line in lines: if line.startswith(";"): self._comment += line tokens = line.split() kwargs = {} if len(tokens) == 7: code = tokens[0] dia = float(tokens[1]) length = float(tokens[2]) delays = tokens[3] prop_mass = float(tokens[4]) * 1000.0 mass = float(tokens[5]) * 1000.0 mfg = tokens[6] if len(tokens) == 2: tokens = line.split() # TODO calculate the mass curve on each iteration timestamp = tokens[0] force = tokens[1] data_points.append([float(timestamp), float(force),0.0]) if len(data_points): mass_increment = mass/len(data_points) for i in range(0,len(data_points)): data_points[i][2] = i*mass_increment kwargs['code'] = code kwargs['len'] = length kwargs['comment'] = self._comment kwargs['dia'] = dia kwargs['propWt'] = prop_mass kwargs['initWt'] = mass kwargs['mfg'] = mfg engine = Engine(**kwargs) engine.data_points = data_points return engine
def main(args): parser = OptionParser(conflict_handler="resolve") parser.add_option("-h", "--host", action="store", type="string", dest="host", default="localhost") parser.add_option("-p", "--port", action="store", type="int", dest="port", default=9876) parser.add_option("-c", "--config", action="store", type="string", dest="config") parser.add_option("-q", "--query", action="store", type="string", dest="query") parser.add_option("-s", "--server", action="store_true", dest="server", default=False) parser.add_option("-u", "--mydigurl", action="store", type="string", dest="mydigurl") parser.add_option("-j", "--project", action="store", type="string", dest="project") parser.add_option("-e", "--endpoint", action="store", type="string", dest="endpoint") parser.add_option("-i", "--index", action="store", type="string", dest="index") parser.add_option("-m", "--sample", action="store_true", dest="sample", default=False) (c_options, args) = parser.parse_args() query_file = c_options.query config_file = c_options.config server = c_options.server host = c_options.host port = c_options.port mydigurl = c_options.mydigurl project = c_options.project endpoint = c_options.endpoint index = c_options.index sample = c_options.sample if not config_file: parser.error('Config file not specified. Use -c or --config') config = load_json_file(config_file) engine = Engine(config) if server: search_server.set_engine(engine) if mydigurl and project: search_server.apply_config_from_project(mydigurl, project, endpoint, index, sample=sample) if not host and not port: search_server.app.run() else: search_server.app.run(host, port, threaded=True) else: query = load_json_file(query_file) result = engine.execute(query) print result
def load(self, id): """ загружает данные нейросети с идентификатором id из базы данных """ d = self.__data = nn.Data() d._id = id (d._extra_data["parent_id"], d._hash, d._effective_deepness, d._response_time, d._resolving_ability, d._quality, d._adaptability) = Engine.db().load_species(id) self._load_neuron_bodies(id) self._load_neuron_inputs(id) self._load_neuron_outputs(id) self._load_synapses(id) # todo: Нужно выполнять корректировку рецепторов/индикторов под текущие входные и выходные данные (возможно придется пересортировать) # По сути это означает, что основным открытым интерфейсом становится nn.Builder. т.е. стек вызовов будет такой: # NeuralNetwork.__init__(...) # --> Builder.load(...) # --> SaveLoad.load(...) # data = self.__data self.clear() return data
def OnInit(self): self.SetAppName("PyggyBank") self.engine = Engine() sys.excepthook = ExceptionHook #control app istance self.instance = wx.SingleInstanceChecker('client_lock', os.getcwd()) if self.instance.IsAnotherRunning(): msg = "Okay, Houston, we've had a problem here.\nAnother instance is running" wx.MessageBox(msg, wx.GetApp().GetAppName(), style=wx.ICON_ERROR | wx.OK) return False try: obj = frames.main.MainFrame() self.SetTopWindow(obj) obj.OnOpen() obj.Show() return True except: print sys.exc_info()[0] print sys.exc_info()[1] print sys.exc_info()[2] return False
class runner(): engine = Engine() def __init__(self): # prompt = PromptWindow() graphics = Graphics(self.engine)
def get_engine(): kit = MotorKit() motor1 = Motor(kit.motor1, 1) motor2 = Motor(kit.motor2, -1) motor3 = Motor(kit.motor3, -1) motor4 = Motor(kit.motor4, 1) return Engine(motor1, motor2, motor3, motor4)
def run_detection(engine_type): """Run wake-word detection for a given engine. :param engine_type: type of the engine. :return: dictionary of false alarms and miss-detections. """ res = [] for sensitivity in Engine.sensitivity_range(engine_type): executor = WakeWordExecutor(engine_type, sensitivity, keyword, dataset, noise_dataset=noise_dataset) # Measure the execution time. start_time = time.process_time() fa, md = executor.execute() end_time = time.process_time() logging.info('[%s][%s] took %s minutes to finish', engine_type.value, sensitivity, (end_time - start_time) / 60) res.append({ 'engine': engine_type.value, 'sensitivity': sensitivity, 'false_alarm': fa, 'miss_detection': md }) executor.release() return res
def __init__(self, engine_type, sensitivity, keyword, dataset, noise_dataset=None): """Executor for running different wake-word engines under different environments. :param engine_type: type of the wake-word engine. :param sensitivity: sensitivity to use in the wake-word engine. :param keyword: keyword to use in the wake word engine. :param dataset: dataset containing both background and keyword datasets. :param noise_dataset: dataset used as a source for mixing noise into clean data. """ self._keyword = keyword self._sensitivity = sensitivity self._dataset = dataset # Initialize the engine. self._engine = Engine.create(engine_type, keyword, sensitivity) self._audio_reader = AudioReader(self._engine.sample_rate, self._engine.channels, self._engine.bits_per_sample) self._noise_mixer = None if noise_dataset: self._noise_mixer = NoiseMixer(noise_dataset, self._audio_reader, self._engine.frame_length)
def regression(): """ Run all stories """ StoryCollection( pathquery(DIR.key).ext("story"), Engine(DIR) ).ordered_by_name().play()
def do_p4fetch(self, component_name): action_name = self.do_p4fetch.__name__ engine = Engine() if component_name is not None and len(component_name.strip()) > 0: logger.info("Fetch P4 source code for component [%s]" % component_name) build_result = engine.p4_fetch(component_name) self.__check_result(component_name, self.do_p4fetch.__name__, build_result) self.__print_final_status() return for c_name in engine.components.keys(): logger.info("Fetch P4 source code for component [%s]" % c_name) build_result = engine.p4_fetch(c_name) self.__check_result(c_name, action_name, build_result) self.__print_final_status()
def main(): application = Application([ (r'/', web_handlers.MainPageHandler), (r'/s/([a-z,0-9,\-,_]+)/*([a-z]*)', web_handlers.ContainerActions), (r'/admin/*', web_handlers.AdminPageHandler), (r'/(.*)', web_handlers.MassActionHandler), ]) params = { 'domain_name': '172.17.0.1', 'image': 'tandemservice/test-tools', 'max_active_stands': 6, 'stop_timeout': '480', 'log_level': 'INFO' } for key, val in params.items(): if key in os.environ: params[key] = os.environ[key] if params['domain_name'] in ('localhost', '127.0.0.1'): raise RuntimeError( 'Do not use localhost cause docker host is not localhost for container. ' 'Usually ip of eth0 is correct') logging.config.dictConfig(default_logging(params.pop('log_level'))) application.engine = Engine(**params) application.listen(8888) IOLoop.instance().start()
def __init__(self, engine: Engine): super().__init__(engine) player = self.engine.player # convert from map-space back to viewport-space engine.mouse_location = self.engine.game_map.map_to_viewport_coord( (player.x, player.y) )
def bdd(*keywords): """ Run story with name containing keywords. """ StoryCollection(pathquery(DIR.key).ext("story"), Engine(DIR)).shortcut( *keywords ).play()
def _load_synapses(self, nnid): synapses_data = Engine.db().load_synapses_data(nnid) self.__data._synapses = [ nn.Synapse(self._map_neuron_id2ind[neuron_in_id], self._map_neuron_id2ind[neuron_owner_id], weight) for weight, neuron_in_id, neuron_owner_id in synapses_data ]
def test3(): # 初始化棋盘 chessboard = ChessBoard() chessboard.initBoard() # 初始化棋子类 chessman = ChessMan() chessman.Color = 'o' # 初始化引擎类 engine = Engine(chessboard) # 获取电脑随机下棋位置 engine.computerGo(chessman) # 放置电脑下棋位置 chessboard.setChessMan(chessman) # 打印棋盘 chessboard.printBoard()
def main(): # setting up the env game = Environment(800, 600, False, 'Resources Example') # now we are loading resources game.load_complete(Engine(), '../data') game.gInstance.main_loop() game.destroy()
def save(self, data: nn.Data): db = Engine.db() # сохраняем id родительской нейросети и получаем (создаем) id текущей # todo: реализовать вычисление времени отклика, качества и приспособленности НС data._id = db.save_species(data.extra_data["parent_id"], data.hash, data.effective_deepness, data.response_time, data.resolving_ability, data.quality, data.adaptability) neurons = data.neurons # сохраняем параметры нейронов и получаем их идентификаторы for o in neurons: o.id = db.save_neuron_body(data.id, o.transfer_function_type, json.dumps(o.transfer_function_params), o.bias, len(o.axon)) # сохраняем информацию о синапсах ... for o in data.synapses: db.save_synapse(data.id, neurons[o.src].id, neurons[o.own].id, o.weight) # ... входных ... for ind, sid in zip(data.input_neurons_inds, data.extra_data["input_sids"]): db.save_nn_inputs(data.id, neurons[ind].id, sid) # ... и выходных нейронах for ind, sid in zip(data.output_neurons_inds, data.extra_data["output_sids"]): db.save_nn_outputs(data.id, neurons[ind].id, sid) db.sqldb.commit() return data.id
def awe(): target_url = request.args.get("url", default="", type=str) engine = Engine(target_url=target_url) asyncio.set_event_loop(loop) loop.run_until_complete(engine.run_engine()) return ( send_file( engine.accessible_site, as_attachment=True, attachment_filename="awe_site.html", ), 200, )
def __init__(self): from engine import Engine self.engine = Engine(100, 100, 50) self.engine.key_manager.register_hotkey(self.g_exit, True) self.cli_test_graphic = self.Cli_graphic(self.engine) self.engine.threads_manager.start_new_thread( self.cli_test_graphic.game_view.test_print)
def start(self): self.engine = Engine() self.engine.new_game() self.engine.set_start_position() if self.side == 'WHITE': self.step_side = 'w' move = self.engine.calulate() print 'game start' print move print 'game go' self.steps.append(move) self.go(move) self.change_step_side() self.change_position(move) else: self.step_side = 'b'
def main(): print("Program starting...") arg = sys.argv[1] eng = Engine(arg) print("Program stopped running.")
def main(): demo = Environment(600, 480, False, 'Rainy night') # with no resources, just call your main engine. demo.load_complete(Engine()) # particles simulation demo.gInstance.main_loop() demo.destroy()
def run(self): """ run """ engine = Engine(None, None) engine.set_config(self.config) engine.run() engine.report_strategy()
def mainThread(): # 初始化棋盘 chessboard = ChessBoard() chessboard.initBoard() # 初始化引擎类 engine = Engine(chessboard) userchessman = ChessMan() userchessman.Color = 'x' computerchessman = ChessMan() computerchessman.Color = 'o' # 创建线程和开启线程 tU = UserGoThread(userchessman, engine) tC = ComputerGoThread(computerchessman, engine) # z设置守护线程,主线程退出,子线程自动退出 tU.setDaemon(True) tC.setDaemon(True) tU.start() tC.start() while 1: #1.用户wait userchessman.WAIT() #2.用户下子 # 放置用户下棋位置 chessboard.setChessMan(userchessman) # 打印棋盘 chessboard.printBoard() # 判断用户是否赢 if engine.isWonMan(userchessman): print("u win") break #3.电脑notify computerchessman.NOTIFY() # 电脑子线程自动完成 #4.1电脑wait computerchessman.WAIT() #5.1电脑下子 # 放置电脑下棋位置 chessboard.setChessMan(computerchessman) # 打印棋盘 chessboard.printBoard() # 判断电脑是否赢 if engine.isWonMan(computerchessman): print("c win") break #6.1用户notify userchessman.NOTIFY()
def main() -> None: screen_width = 80 screen_height = 50 map_width = 80 map_height = 43 room_max_size = 10 room_min_size = 6 max_rooms = 30 max_monsters_per_room = 2 #Sets file for tileset tileset = tcod.tileset.load_tilesheet("dejavu10x10_gs_tc.png", 32, 8, tcod.tileset.CHARMAP_TCOD) player = copy.deepcopy(entity_factories.player) engine = Engine(player=player) engine.game_map = generate_dungeon( max_rooms=max_rooms, room_min_size=room_min_size, room_max_size=room_max_size, map_width=map_width, map_height=map_height, max_monsters_per_room=max_monsters_per_room, engine=engine) engine.update_fov() engine.message_log.add_message( "Hello and welcome, adventurer, to yet another dungeon!", color.welcome_text) with tcod.context.new_terminal(screen_width, screen_height, tileset=tileset, title="Tepis", vsync=True) as context: root_console = tcod.Console(screen_width, screen_height, order="F") while True: root_console.clear() engine.event_handler.on_render(console=root_console) context.present(root_console) engine.event_handler.handle_events(context)
def _adapt_for_inputs_and_outputs(self): """ Модифицируем нейронную сеть так, что бы она могла принимать на вход имеющиеся и выдавать требуемые данные. В результате работы функции будут добавлены: * недостающие нейроны-рецепторы и -индикаторы * связи между добавленными рецепторами и индикаторами по типу все-со-всеми """ current_inputs_set = set(Engine.training_data().inputs) current_outputs_set = set(Engine.training_data().outputs) have_inputs_set = set(self._temp_data._map_input_sid2ind.keys()) have_outputs_set = set(self._temp_data._map_output_sid2ind.keys()) inputs_to_add = current_inputs_set.difference(have_inputs_set) inputs_to_delete = have_inputs_set.difference(current_inputs_set) outputs_to_add = current_outputs_set.difference(have_outputs_set) outputs_to_delete = have_outputs_set.difference(current_outputs_set) # На каждый новый вход и на каждый новый выход добавляем по одному нейрону # между ними делаем связки все-со-всеми # todo: думаю в дальнейшем, когда тестовые данные будут усложняться эта логика изменится for data_name in inputs_to_add: self.__add_receptor(data_name) for data_name in outputs_to_add: self.__add_indicator(data_name) # рассматриваем связи все-со-всеми for src in (self._temp_data._map_input_sid2ind[src_sid] for src_sid in inputs_to_add): for own in (self._temp_data._map_output_sid2ind[own_sid] for own_sid in outputs_to_add): self._data._synapses.append(nn.Synapse( src, own, 1)) # todo: вынести значение веса по-умолчанию в настройки # todo: добавить реализацию для удаления рецепторов и/или индикаторов # todo: добавить сортировку рецепторов и индикаторов в соответствии с порядком Engine.training_data().in/out # Note: сейчас сортировка выполняется в SaveLoad._load_neuron_inputs() self.data._input_neurons_inds = self._temp_data.input_neurons self.data._output_neurons_inds = self._temp_data.output_neurons self.data.extra_data["input_sids"] = Engine.training_data( ).inputs.copy() self.data.extra_data["output_sids"] = Engine.training_data( ).outputs.copy()
def new_game() -> Engine: """Return a brand new game session as an Engine instance.""" map_width = 80 map_height = 43 room_max_size = 10 room_min_size = 6 max_rooms = 30 max_monsters_per_room = 2 max_items_per_room = 2 player = copy.deepcopy(entity_factories.player) engine = Engine(player=player) engine.game_world = GameWorld( engine=engine, max_rooms=max_rooms, room_min_size=room_min_size, room_max_size=room_max_size, map_width=map_width, map_height=map_height, max_monsters_per_room=max_monsters_per_room, max_items_per_room=max_items_per_room, ) engine.game_world.generate_floor() engine.update_fov() engine.message_log.add_message( "Hello and welcome, adventurer, to yet another dungeon!", color.welcome_text ) dagger = copy.deepcopy(entity_factories.dagger) leather_armor = copy.deepcopy(entity_factories.leather_armor) dagger.parent = player.inventory leather_armor.parent = player.inventory player.inventory.items.append(dagger) player.equipment.toggle_equip(dagger, add_message=False) player.inventory.items.append(leather_armor) player.equipment.toggle_equip(leather_armor, add_message=False) return engine
class App(tk.Tk): """Biovarase Main Application start here""" def __init__(self): super().__init__() self.engine = Engine() self.protocol("WM_DELETE_WINDOW", self.on_exit) self.set_style() self.set_title("Biovarase") self.set_icon() self.set_info() self.engine.title = self.title() w = Biovarase(self) w.on_open() w.pack(fill=tk.BOTH, expand=1) def set_title(self, title): s = "{0}".format(title) self.title(s) def set_info(self, ): msg = "{0}\nauthor: {1}\ncopyright: {2}\ncredits: {3}\nlicense: {4}\nversion: {5}\ \nmaintainer: {6}\nemail: {7}\ndate: {8}\nstatus: {9}" info = msg.format(self.title(), __author__, __copyright__, __credits__, __license__, __version__, __maintainer__, __email__, __date__, __status__) self.info = info def set_style(self): self.style = ttk.Style() self.style.theme_use("clam") self.style.configure(".", background=self.engine.get_rgb(240, 240, 237)) def set_icon(self): icon = tk.PhotoImage(data=self.engine.get_icon()) self.call("wm", "iconphoto", self._w, "-default", icon) def on_exit(self): """Close all""" if messagebox.askokcancel(self.title(), "Do you want to quit?", parent=self): self.engine.con.close() self.quit()
def main(): args = parser.parse_args() use_gpu = torch.cuda.is_available() # define dataset input_transform = Compose( [ToTensor(), Normalize([.485, .456, .406], [.229, .224, .225])]) train_dataset = TrainDataLoader(os.path.join(args.data, 'image_list_train.txt'), img_transform=input_transform) val_dataset = TrainDataLoader(os.path.join(args.data, 'image_list_val.txt'), img_transform=input_transform) # load model model = Seg2DNet(model=models.resnet101(True), num_classes=12) # define loss function (criterion) cri_weights = torch.FloatTensor([0.0001, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) criterion = nn.CrossEntropyLoss(weight=cri_weights / torch.sum(cri_weights)) # define optimizer optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) state = { 'batch_size': args.batch_size, 'workers': args.workers, 'start_epoch': args.start_epoch, 'max_epochs': args.epochs, 'evaluate': args.evaluate, 'resume': args.resume, 'multi_gpu': False, 'device_ids': [0, 1], 'use_gpu': use_gpu, 'save_iter': 1200, 'print_freq': args.print_freq, 'epoch_step': [20, 40, 60] } state['save_model_path'] = './save_models/seg_RGB_suncg' engine = Engine(state) engine.learning(model, criterion, train_dataset, val_dataset, optimizer)
def __init__(self): # очереди нейросетей. Содержат кортежи с данными вида: # (id, adaptability) # adaptability=0 означает наиболее приспособленную сеть self._nn_queue_active = Engine.db().get_alive_species() self._nn_queue_pending = [] if len(self._nn_queue_active) == 0: self._nn_queue_active = [(0, 0)]
def v_8_FP(): return Engine(idle_rpm=800, limiter_rpm=7000, strokes=4, cylinders=8, timing=[180] * 8, fire_snd=_fire_snd, between_fire_snd=synth.silence(1))
def v_8_LS(): return Engine(idle_rpm=600, limiter_rpm=7000, strokes=4, cylinders=8, timing=[180, 270, 180, 90, 180, 270, 180, 90], fire_snd=_fire_snd, between_fire_snd=synth.silence(1))
def __init__(self, parent, englabel=None, userdict={}, timeout=10): """ The PTK engine class for embedding in gtk applications. To use create an instance of this or a subclass. It uses the parent object for signals. engine.disconnect() should also be called before the application exits. Important. It uses the a the gtk mainloop to post/bind events and starts a communications thread, therefore gtk.gdk.threads_init() must be called before the main loop is started! gtk.gdk.threads_init() gtk.main() Signals to use: 'engine_disconnect' - sent went the engine disconnects. Methods/attributes you might want to overload: _get_welcome() - Returns a string welcome message. self.eng_prompts - these are the prompts used by the controlling console. """ self.parent = parent #add the engine disconnect signal if gobject.signal_lookup("engine_disconnect", self.parent) == 0: gobject.signal_new("engine_disconnect", self.parent, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,()) Engine.__init__(self, englabel, userdict, timeout)