Ejemplo n.º 1
0
    def _welcome_window(self):
        sg.theme('Light Blue 2')  # Add a touch of color
        # All the stuff inside your window.
        layout = [[sg.Text('Path (Video or Photo Album): '), ],
            [sg.Button('Video'), sg.Button('Album')],
            [sg.Checkbox('Right-to-Left?')],
            [sg.Text('Which Kind of Application you want? choose one: ')],
            [sg.Button('Refocusing'), sg.Button('Change Viewpoint')]]

        # Create the Window
        window = sg.Window('Welcome!', layout, element_justification='center', text_justification='center')
        # Event Loop to process "events" and get the "values" of the inputs
        self.src = ''
        while True:
            event, values = window.read()
            # self.is_rtl = values[1]
            self.is_rtl = values[0]
            if event == None:  # if user closes window or clicks cancel
                break
            elif event == 'Refocusing':
                if not os.path.exists(self.src):
                    continue
                self.refocus = engine.Engine()
                self.refocus.refocus(self.src)
                self.refocus._interpolate(150)
                b, g, r = cv.split(self.refocus.output_img)
                im = cv.merge((r, g, b))
                im = cv.resize(im, (400, 250))
                plt.imsave(self.output_temp, im)
                self.action = 'Refocus'
                break
            elif event == 'Change Viewpoint':
                if not os.path.exists(self.src):
                    continue
                self.action = 'Viewpoint'
                self.viewpoint = engine.Engine()
                self.viewpoint.src = self.src
                self.viewpoint.load_images()
                self.viewpoint.init_viewpoint()
                break
            elif event == 'Album':
                self.src = sg.popup_get_folder('Choose album directory')
            elif event == 'Video':
                self.src = sg.popup_get_file('Choose video file',
                                             file_types=(("VIDEOS", ".mp4"),("VIDEOS", ".mov"),
                                                         ("VIDEOS", ".flv"),("VIDEOS", ".mpeg") ,
                                                         ("VIDEOS", ".mpg"),("VIDEOS", ".avi")))
        window.close()
Ejemplo n.º 2
0
async def test_2Channels(channel):
    """ Test 2 channels in parallel"""
    channel.ch2.progs = [progdays.Progdays(), progdays.Progdays()]

    channel.ch2.isenable = True
    channel.ch2.progs[0].stime = stime.STime(hour=5, minute=15, duration=30)
    channel.ch2.progs[0].isactive = True
    channel.ch2.progs[0].set_days([True, True, True, True, True, True, True])

    e = engine.Engine([channel.ch1, channel.ch2])
    # Stop scheduler, not used here
    e.stop()

    # Mock engine function to force date and time
    e.get_datetime_now = MagicMock(return_value=datetime(2017, 6, 24, 4, 59))
    e.run()

    assert (not channel.hw1.cmd and not channel.hw2.cmd)

    e.get_datetime_now = MagicMock(return_value=datetime(2017, 6, 24, 5, 10))
    e.run()

    assert (channel.hw1.cmd and not channel.hw2.cmd)

    e.get_datetime_now = MagicMock(return_value=datetime(2017, 6, 24, 5, 20))
    e.run()

    assert (channel.hw1.cmd and channel.hw2.cmd)

    e.get_datetime_now = MagicMock(return_value=datetime(2017, 6, 24, 5, 31))
    e.run()

    assert (not channel.hw1.cmd and channel.hw2.cmd)
Ejemplo n.º 3
0
async def test_7(channel):
    """ Test when time is around midnight """

    channel.ch1.progs[1].stime = stime.STime(hour=23, minute=50, duration=40)
    channel.ch1.progs[1].isactive = True
    channel.ch1.progs[1].set_days([True, True, True, True, True, True, True])

    e = engine.Engine([channel.ch1])
    # Stop scheduler, not used here
    e.stop()

    # Mock engine function to force date and time
    e.get_datetime_now = MagicMock(return_value=datetime(2017, 6, 23, 23, 55))
    e.run()
    assert (channel.hw1.cmd)

    # Mock engine function to force date and time
    e.get_datetime_now = MagicMock(return_value=datetime(2017, 6, 24, 0, 1))
    e.run()
    assert (channel.hw1.cmd)

    # Mock engine function to force date and time
    e.get_datetime_now = MagicMock(return_value=datetime(2017, 6, 24, 0, 31))
    e.run()
    assert (not channel.hw1.cmd)
Ejemplo n.º 4
0
    def create_engine(self, engine_name):
        if engine_name == "xkbc":
            self.__id += 1
            return engine.Engine(self.__bus,
                                 "%s/%d" % (self.ENGINE_PATH, self.__id))

        return super(EngineFactory, self).create_engine(engine_name)
Ejemplo n.º 5
0
    def create_engine(self, engine_name):
        print engine_name
        if engine_name == "googlepinyin":
            self.__id += 1
            return engine.Engine(self.__bus, "%s/%d" % ("/org/freedesktop/IBus/GooglePinyin/Engine", self.__id))

        return super(EngineFactory, self).create_engine(engine_name)
Ejemplo n.º 6
0
def main(unused_argv):
    FLAGS.use_back_engine = "true"
    e = engine.Engine()
    e.initBackEngine()
    with open(FLAGS.csv_out, "w") as csv_out:
        with open(FLAGS.csv_in) as csv_in:
            csv_out.write("fen,best_move,move,evaluation,result_prediction\n")
            line = csv_in.readline()
            while True:
                line = csv_in.readline()
                if line is None or line == "":
                    break
                words = line.split(",")
                fen = words[0].strip()
                board = chess.Board(fen)
                best_move = words[1].strip()
                move = words[2].strip()
                known_eval = 0
                try:
                    known_eval = float(words[3].strip())
                except:
                    m_, score, p_ = e.evaluateStatic(board)
                    known_eval = e.cp_score(score)
                    if board.turn == chess.BLACK:
                        known_eval = -known_eval
                result_pred = inference.predict_result(board)
                if board.turn == chess.BLACK:
                    result_pred = -result_pred
                csv_out.write(fen + "," + best_move + "," + move + "," +
                              str(known_eval) + "," + str(result_pred) + "\n")
Ejemplo n.º 7
0
async def test_long_time(channel):
    """ Long time test, using scheduler function
    """

    e = engine.Engine([channel.ch1])
    assert (not channel.hw1.cmd)

    async def wait_channel_1(timeout):
        nonlocal channel
        starttime = datetime.now()
        while (datetime.now() <
               starttime + timedelta(seconds=timeout)) and not channel.hw1.cmd:
            await asyncio.sleep(10)

    t1 = asyncio.create_task(wait_channel_1(2 * 60))
    await t1
    assert (channel.hw1.cmd)

    async def wait_channel_2(timeout):
        nonlocal channel
        starttime = datetime.now()
        while (datetime.now() <
               starttime + timedelta(seconds=timeout)) and channel.hw1.cmd:
            await asyncio.sleep(10)

    t2 = asyncio.create_task(wait_channel_2(2 * 60))
    await t2
    assert (not channel.hw1.cmd)

    e.stop()
Ejemplo n.º 8
0
    def reset(self):

        # self.eng.reset() to be implemented
        self.eng = engine.Engine(self.dic_traffic_env_conf["INTERVAL"],
                                 self.dic_traffic_env_conf["THREADNUM"],
                                 self.dic_traffic_env_conf["SAVEREPLAY"],
                                 self.dic_traffic_env_conf["RLTRAFFICLIGHT"])
        self.load_roadnet(self.dic_traffic_env_conf["ROADNET_FILE"])
        self.load_flow(self.dic_traffic_env_conf["TRAFFIC_FILE"])

        # initialize intersections (grid)
        self.list_intersection = [
            Intersection((i + 1, j + 1), self.dic_traffic_env_conf, self.eng)
            for i in range(self.dic_traffic_env_conf["NUM_ROW"])
            for j in range(self.dic_traffic_env_conf["NUM_COL"])
        ]
        self.list_inter_log = [
            [] for i in range(self.dic_traffic_env_conf["NUM_ROW"] *
                              self.dic_traffic_env_conf["NUM_COL"])
        ]
        # get lanes list
        self.list_lanes = []
        for inter in self.list_intersection:
            self.list_lanes += inter.list_lanes
        self.list_lanes = np.unique(self.list_lanes).tolist()

        # get new measurements
        for inter in self.list_intersection:
            inter.update_current_measurements()

        state = self.get_state()
        return state
Ejemplo n.º 9
0
    def __init__(self, path_to_log, path_to_work_directory,
                 dic_traffic_env_conf):
        self.path_to_log = path_to_log
        self.path_to_work_directory = path_to_work_directory
        self.dic_traffic_env_conf = dic_traffic_env_conf
        self.simulator_type = self.dic_traffic_env_conf["SIMULATOR_TYPE"]

        self.eng = engine.Engine(self.dic_traffic_env_conf["INTERVAL"],
                                 self.dic_traffic_env_conf["THREADNUM"],
                                 self.dic_traffic_env_conf["SAVEREPLAY"],
                                 self.dic_traffic_env_conf["RLTRAFFICLIGHT"],
                                 False)
        self.load_roadnet(self.dic_traffic_env_conf["ROADNET_FILE"])
        self.load_flow(self.dic_traffic_env_conf["FLOW_FILE"])

        self.list_intersection = None
        self.list_inter_log = None
        self.list_lanes = None

        self.stop_cnt = 0

        # check min action time
        if self.dic_traffic_env_conf[
                "MIN_ACTION_TIME"] <= self.dic_traffic_env_conf["YELLOW_TIME"]:
            print("MIN_ACTION_TIME should include YELLOW_TIME")
            pass
Ejemplo n.º 10
0
    def __init__(self, env_config):
        config = json.load(open(util.ENV_CONFIG_DIR + env_config))
        self.params_template = config["params_template"]
        self.target_params = config["target_params"]
        
        sim_config = config["sim_config"]
        self.probs = sim_config["probs"]
        self.means = sim_config["means"]
        self.stds = sim_config["stds"]
        np.random.seed(sim_config["seed"])
        
        self.setting_dir = util.SETTING_DIR + config["setting_dir"]
        roadnet_file = self.setting_dir + config["roadnet_file"]
        flow_file = self.setting_dir + config["flow_file"]
        signal_file = self.setting_dir + config["signal_file"]
        self.observed_file = self.setting_dir + config["observed_file"]
        self.log = True
        self.f_observed = open(self.observed_file, "w")
        self.gen = Generator(flow_file, signal_file)

        self.proc = Processor()
        self.eng = engine.Engine(1.0, 2, True, True, False)
        self.eng.load_roadnet(roadnet_file)
        
        self.t = 0
Ejemplo n.º 11
0
def test_detect_rstacks():
    """
    Tests the engine detects & records seeing RA packets
    """
    with engine.Engine(80, "") as eng:
        os.system("curl 8.8.8.8:80")
        assert eng.censorship_detected
Ejemplo n.º 12
0
def test_default_args():
    """
    Tests engine can be created without specifying all of the args
    """
    with engine.Engine(80, "") as eng:
        assert eng.output_directory == "trials"
        assert eng.environment_id is not None
Ejemplo n.º 13
0
def make_easy_engine(servant_class, setting=None):
    if len(sys.argv) == 1 and setting is None:
        print 'Usage: python %s config-file.yml' % sys.argv[0]
        sys.exit(1)

    setting = setting if setting is not None else utils.load_yaml(sys.argv[1])
    print(setting)
    env = setting.get('env', 'dev')
    debug = setting.get('debug', False)
    log_level = setting.get('log_level', 'info')
    if debug:
        log_level = 'debug'
    app = AppWrap('cube-rpc', env, log_level)
    cplogger.make_logger_for_app(app)

    # endpoint
    endpoint = setting.get('endpoint', None)
    if not endpoint:
        raise params.EngineError('not endpoint in config')

    service, host, port = proxy.parse_endpoint(endpoint)
    if not service:
        raise engine.EngineError('You must specify the service name.')

    _engine = engine.Engine(setting)

    adapter = engine.Adapter(service, endpoint)
    _engine.add_adpater(adapter)

    servant = servant_class(_engine)

    adapter.add_servant(service, servant)

    return _engine
Ejemplo n.º 14
0
def singleplayer(play_as, code):
    defs.cls()
    b = board.Board()
    eng = engine.Engine()
    b.display_board()

    if play_as == "X":
        AI_color = 1
        first = False
    else:
        AI_color = -1
        first = True

    while (b.winning() == defs.INFINITY):
        while (play_as == b.get_player()):
            defs.human_play(b)
            defs.cls()
            b.display_board()

        if (b.winning() == defs.INFINITY):
            defs.AI_play(b, eng, AI_color, 3, 4, first)
            defs.cls()
            first = False
            b.display_board()

    defs.print_winner(b.winning())
Ejemplo n.º 15
0
def _daemonize():
    """
    Daemonizes the module. Uses pub/sub Redis schema.
    """
    global run_proc
    try:
        print("Persisting process...")
        signal.signal(signal.SIGTERM, _exit)
        signal.signal(signal.SIGINT, _exit)

        if (G.VERBOSE):
            print("Building engine...")
        en = engine.Engine()

        if (G.VERBOSE):
            print("Building wrapper...")
        ps = pubsub.Wrapper(en)

        print("Ready. Waiting for requests...")

        while run_proc:
            ps.heartbeat()
            time.sleep(10)
    except KeyboardInterrupt:
        _exit()
Ejemplo n.º 16
0
    def Go(cls, targets):
        """Builds everything starting with the given targets as the top-level.

        Args:
          targets: List of string specifiers of targets resolved in top-level
                   scope

        Returns: True if all the targets built successfully, False otherwise
        """
        done = set()
        e = engine.Engine()
        target_names = []
        for target in targets:
            holder = cls.Get(TOPLEVEL, target)
            if not holder:
                print >> sys.stderr, "Unknown target", target
                continue
            ret = holder.TopApply(e)
            if ret:
                target_names.append(ret)
        # Make sure to apply all of the Generate targets. Otherwise
        # their out's will never get considered.
        for obj in cls._registered.itervalues():
            if isinstance(obj, Generate):
                obj.Apply(e)
        e.ComputeDependencies()
        for target in target_names:
            e.BuildTarget(e.GetTarget(target))
        return e.Go()
Ejemplo n.º 17
0
def run_pipeline(initial_orders):
    global engine
    global SIMULTION_METHOD
    global service_stations

    SIMULTION_METHOD = 'PIPELINE'
    service_stations = {}
    for type in types:
        service_stations[type] = Station(type, [
            ingredient for ingredient, v in ingredients_dict.iteritems()
            if ingredients_dict[ingredient]['type'] == type
        ])

    # for arrival in initial_orders:
    # print str(arrival.data['order']) + ' at ' + str(arrival.data['order'].start_time)

    engine = eng.Engine(initial_orders)
    start_time = engine.current_time
    engine.run()
    end_time = engine.current_time
    total_time = end_time - start_time

    # orders = len(engine.completed_orders)
    # mean_time = total_time / NUM_ORDERS
    mean_wait = numpy.mean(map(lambda x: x.wait_time, engine.completed_orders))
    # std_dev = numpy.std(map(lambda x: x.wait_time, engine.completed_orders))
    # print '----------PIPELINE----------'
    # print 'Number of orders processed: ' + str(orders)
    # print 'Mean time per sandwich ' + str(mean_time)
    # print "Mean waiting time: " + str(mean_wait)
    # print 'Standard deviation of wait times: ' + str(std_dev)

    return mean_wait
Ejemplo n.º 18
0
    def __init__(self, env_config_file):
        with open(env_config_file) as f:
            config = json.load(f)
        self.observation_space = ObservationSpace(config["observation_space"]["dim"])
        self.action_space = ActionSpace(config["action_space"]["high"])

        self.params_template = config["params_template"]
        self.target_params = config["target_params"]
        
        data_dir = util.SETTING_DIR + config["setting_dir"]
        roadnet_file = data_dir + config["roadnet_file"]
        flow_file = data_dir + config["flow_file"]
        signal_file = data_dir + config["signal_file"]
        self.observed_file = data_dir + config["observed_file"]
        self.f_observed = open(self.observed_file)
        self.gen = Generator(flow_file, signal_file)

        self.proc = Processor()
        self.eng = engine.Engine(1.0, 2, True, True, False)
        self.eng.load_roadnet(roadnet_file)

        self.t = 0
        self.total_reward = 0
        self.d = False
        self.steps = self.gen.steps

        self.reset()
Ejemplo n.º 19
0
    def __init__(self,
                 objects=[],
                 joints=[],
                 key_events=[],
                 control_events=[],
                 obj_to_follow='',
                 render_window=True,
                 render_video=False,
                 video_file=None):
        # Create members
        self.eng = engine.Engine(contact.Hit_body_ground(), render_window,
                                 render_video, video_file)
        self.objects = objects
        self.joints = joints
        self.key_events = key_events
        self.control_events = control_events
        self.obj_to_follow = obj_to_follow

        # Create action space
        for i in range(3):
            for j in range(3):
                for k in range(3):
                    for l in range(3):
                        for m in range(3):
                            self.actions.append(
                                [i, 3 + j, 6 + k, 9 + l, 12 + m])

        # Initialize engine and objects in engine
        self._reset()

        # Run initialization functions
        self._seed()
Ejemplo n.º 20
0
def get_instance(dbname=None,
                 username=None,
                 password=None,
                 static_folder=None):
    app = Flask('relately', static_folder=os.path.join(basedir, 'static'))
    eng = engine.Engine(dbname, username, password)

    @app.route("/select", methods=["POST"])
    def select():
        if request.args.get('mogrify'):
            return eng.select(request.get_json(force=True), mogrify=True)
        return jsonify({"results": eng.select(request.get_json(force=True))})

    @app.route("/select/<schema>/<view>", methods=["GET"])
    def select_get(schema, view):
        return jsonify({
            "results":
            eng.select({
                "columns": "*",
                "target": "{}.{}".format(schema, view)
            })
        })

    @app.route("/info/<schema>/<view>", methods=["GET"])
    def get_info(schema, view):
        return jsonify({"info": eng.info(schema, view)})

    @app.route("/json_schema/<schema>/<view>", methods=["GET"])
    def get_json_schema(schema, view):
        return jsonify(eng.json_schema(request.url, schema, view))

    return app
Ejemplo n.º 21
0
def main():
    PYMUSH_BASE = os.environ["PYMUSH_BASE"]

    game_config = configparser.ConfigParser()
    game_config.read("%s/conf/pymush.conf" % PYMUSH_BASE)
    server_config = game_config["SERVER"]

    loop = asyncio.get_event_loop()

    if cfg_bool(server_config["UseInternalWebServer"]):
        import webserver as pym_webserver
        webserver = pym_webserver.SimpleStaticServer(server_config, "%s/static" % PYMUSH_BASE, loop)
        create_server_coroutine = loop.create_server(webserver.make_handler(), '', int(server_config["InternalWebServerPort"]))
        loop.run_until_complete(create_server_coroutine)

    main_db = pym_db.PyMushDB()
    main_engine = pym_engine.Engine(loop, main_db, game_config)

    factory = pym_server.PyMUSHServerFactory("ws://localhost:%s" % server_config["WebSocketPort"],
                                             main_engine,
                                             debug=cfg_bool(server_config["DebugAutobahn"]))

    factory.protocol = pym_server.PyMUSHServerProtocol

    create_server_coroutine = loop.create_server(factory, '', int(server_config["WebSocketPort"]))

    server = loop.run_until_complete(create_server_coroutine)

    try:
        loop.run_forever()
    except:
        server.close()
        loop.close()
Ejemplo n.º 22
0
 def start(self):
     # turn pipelines into JSON
     pipes = json.dumps([v for k, v in self.pipelines.items()])
     launch = f"{engine.core.DEFAULT_EXEC_PATH} --port {self.port} --pipes-as-json '{pipes}'"
     self.engine = engine.Engine(shlex.split(launch))
     self.engine.start()
     self._on = True
Ejemplo n.º 23
0
def distribution(character='Darthur', figsize=(8,6), bins=50, sims=10000, show=None):
    eng = engine.Engine(character)
    if show is None:
        show = eng.spell_names

    def plot_cdf(data, ax):
        data_sorted = np.sort(data)
        p = 1. * np.arange(len(data)) / (len(data) - 1)
        ax.plot(data_sorted, p)

    def update(dex=STARTING_MOD, con=STARTING_MOD, wis=STARTING_MOD, _str=STARTING_MOD,
               armor_class=STARTING_AC, slot_level=STARTING_SLOT, advantage=STARTING_ADVANTAGE,
               rounds=STARTING_ROUNDS, range_enemies=STARTING_RANGE_ENEMIES, web=STARTING_WEB):
        fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(10, 6))
        e = enemy.create_enemy(dex=dex, con=con, wis=wis, str=_str, armor_class=armor_class)

        sample_list = eng.evaluate_spells_sim(show, enemy=e, slot_level=slot_level, advantage=advantage, sims=sims, rounds=rounds,
                                          range_enemies=range_enemies, web=web)

        ax[0].hist(sample_list, bins, label=show)
        ax[0].legend(loc='upper right')

        ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x / sims))
        ax[0].yaxis.set_major_formatter(ticks_y)

        for spell_samples in sample_list:
            plot_cdf(spell_samples, ax[1])

        fig.tight_layout()
        plt.show()

    return default_interact(update)
Ejemplo n.º 24
0
def expected_damage(character='Darthur', figsize=(8,4), rotate=False, ylim=30, show=None):
    eng = engine.Engine(character)
    if show is None:
        show = eng.spell_names
    fig = plt.figure(figsize=figsize)
    ax = plt.gca()
    ax.set_ylim(top=ylim)

    e = enemy.create_enemy()

    bars = ax.bar(show, eng.evaluate_spells_exp_v(spells=show, enemy=e))
    if rotate:
        ax.set_xticklabels(show, rotation=45, ha="right")
    plt.title('Expected Damage')
    plt.ylabel('Damage')
    plt.show()

    texts = []

    def update(dex=STARTING_MOD, con=STARTING_MOD, wis=STARTING_MOD, _str=STARTING_MOD,
               armor_class=STARTING_AC, slot_level=STARTING_SLOT, advantage=STARTING_ADVANTAGE,
               rounds=STARTING_ROUNDS, range_enemies=STARTING_RANGE_ENEMIES, web=STARTING_WEB):
        e = enemy.create_enemy(dex=dex, con=con, wis=wis, str=_str, armor_class=armor_class)
        calcs = eng.evaluate_spells_exp_v(show, enemy=e, slot_level=slot_level, advantage=advantage, rounds=rounds,
                                          range_enemies=range_enemies, web=web)
        for i in range(len(texts)):
            texts.pop().remove()
        for i, (bar, calc) in enumerate(zip(bars, calcs)):
            bar.set_height(calc)
            texts.append(ax.text(bar.get_x() + bar.get_width() / 2, min(calc + 1, ylim-3), str(calc),
                    ha='center', va='bottom', fontweight='bold'))
        plt.show()

    return default_interact(update)
Ejemplo n.º 25
0
    def do_create_engine(self, engine_name):
        if engine_name == 'anthy':
            self.__id += 1
            return engine.Engine(self.__bus,
                                 '%s/%d' % (self.ENGINE_PATH, self.__id))

        return super(EngineFactory, self).do_create_engine(engine_name)
Ejemplo n.º 26
0
    def __init__(self):
        # Enable logging
        logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            level=logging.INFO)

        self.logger = logging.getLogger(__name__)

        # Systemd journal handler
        self.logger.addHandler(journal.JournaldLogHandler())

        # Initialize engine
        self.engine = engine.Engine()

        self.QUESTION, self.SELECTQUESTION, self.SUPPORTCONFIRM, self.SUPPORTSUBMIT, self.SUPPORT = range(5)

        # Create the Updater and pass it your bot's token.
        # Make sure to set use_context=True to use the new context based callbacks
        # Post version 12 this will no longer be necessary

        # Get the token here
        _pwd = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(_pwd, "../api.token"), 'r') as f:
            botToken = f.readlines()[0].strip()

        self.updater = Updater(botToken, use_context=True)

        # Get the dispatcher to register handlers
        self.dp = self.updater.dispatcher

        # Add conversation handler with states
        self.conv_handler = ConversationHandler(
            entry_points=[CommandHandler('start', self.start)],

            states={
                self.QUESTION:          [MessageHandler(Filters.text, self.question)],
                self.SELECTQUESTION:    [MessageHandler(Filters.text, self.selectQuestion)],
                self.SUPPORTCONFIRM:    [MessageHandler(Filters.regex('^(Yes|No)$'), self.supportConfirm), CommandHandler('skip', self.skip_support)],
                self.SUPPORTSUBMIT:     [MessageHandler(Filters.text, self.supportSubmit)]
            },

            fallbacks=[CommandHandler('support', self.support), CommandHandler('cancel', self.cancel), CommandHandler('help', self.help)]
        )

        self.dp.add_handler(self.conv_handler)

        # log all errors
        self.dp.add_error_handler(self.error)

        # Start the Bot
        self.updater.start_polling()
        print("Ready")
        notify(Notification.READY)

        # Run the bot until you press Ctrl-C or the process receives SIGINT,
        # SIGTERM or SIGABRT. This should be used most of the time, since
        # start_polling() is non-blocking and will stop the bot gracefully.
        self.updater.idle()
        notify(Notification.STOPPING)
        print("Ended")
Ejemplo n.º 27
0
    def do_command(sess, arg):
        if (sess.name == '_default'):
            sess.ui.write("You aren't connected to anything!")
            return

        sess.shutdown.flag_true()
        engine.Engine().rm_session(sess)
        return
Ejemplo n.º 28
0
def main_once():
    # play once
    game = ExampleGame()
    e = engine.Engine(game)
    e.addPlayer('player1', 'stub/bot0.exe')
    e.addPlayer('player2', 'stub/bot0.exe')
    e.start()
    return game.gameResult()
Ejemplo n.º 29
0
    def create_engine(self, engine_name):
        print engine_name
        if engine_name == "tegaki":
            self.__id += 1
            return engine.Engine(self.__bus, "%s/%d" % \
                ("/org/freedesktop/IBus/Tegaki/Engine", self.__id))

        return super(EngineFactory, self).create_engine(engine_name)
Ejemplo n.º 30
0
    def load_initial_state(self):
        player_names = [
            usergame.fetch_user().email for usergame in self.usergames
        ]
        self.game_engine = engine.Engine(player_names)

        initial_game_state_json = json.loads(self.initial_state)
        self.game_engine.start_game_with_initial_state(initial_game_state_json)