Esempio n. 1
0
def prompt(s):        
    """Prompts the user for either a file or an OpenMath xml string to send to the server

    :param s: the socket to be passed into the send_msg function
    :return true or false depending on if the user wishes to quit
    """
    choice = input("Do you want to enter a file or enter manually? (f/m/q)"
                   + " \n> ")
    
    if(choice == 'f'):
        str_ = input("Enter in a file \n>")
        try:
            with open(str_,"r") as file:
                msg = file.read()
                send_msg(msg,s)

        except FileNotFoundError as err:
            log('File not Found')

    elif(choice == 'm'):
        msg = input("Enter in an OpenMath expression "
                    + " \n> ")
        send_msg(msg,s)

    elif(choice == 'q'):
        return True
    else: prompt(s)

        
    return False
async def focus_item(page, item):
    server.log(str(item))
    for cmp, serialized_item in page["currentRecipePage"]:
        if item.name == serialized_item["name"]:
            await menu_utils.focus_component(cmp)
            return True
    return False
Esempio n. 3
0
def create_socket(host='localhost', port=54345):
    """Creates a socket with the given host name and port
    
    :param host: the host of the server. Defaults to 'localhost' if no argument specified
    :param port: the port to connect to. Defaults to '54345' if no argument specified
    """
    try:
        # create an AF_INET, STREAM socket (TCP)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        
    except socket.error as msg:
        log( 'Failed to create socket. Error code: '
             + str(msg[0]) + ', Error message: ' + msg[1])
        sys.exit();
    
    log('Socket created')
       
    try:
        remote_ip = socket.gethostbyname(host)
    
    except socket.gaierror:
        # Could not resolve
        log('Hostname could not be resolved. Exiting')
        sys.exit();
    
    log('IP address of ' + host + ' is ' + remote_ip)
    
    # Connect to remote server
    s.connect((remote_ip, port))
    
    log ('Socket connected to ' + host + ' on ip ' + remote_ip)
    return s    
Esempio n. 4
0
async def move_cursor_to_next_component(menu, direction, n=1):
    current_position = None
    target_components = []
    clickable = list(menu_utils.yield_clickable_components(menu))
    for cmp in menu_utils.yield_clickable_components(menu):
        center = cmp["center"]
        if cmp["containsMouse"]:
            current_position = cmp
        else:
            target_components.append(cmp)
    if not target_components:
        return
    if current_position is None:
        cx, cy = await server.get_mouse_position()
        current_position = {"center": (cx, cy), 'visible': True}
    if direction == constants.NORTH:
        direction_index, multiplier = 1, -1
    elif direction == constants.EAST:
        direction_index, multiplier = 0, 1
    elif direction == constants.SOUTH:
        direction_index, multiplier = 1, 1
    elif direction == constants.WEST:
        direction_index, multiplier = 0, -1
    for i in range(n):
        sort_key = functools.partial(sort_fn, current_position, direction_index, multiplier)
        res = min(target_components, key=sort_key)
        right_direction = sort_fn(current_position, direction_index, multiplier, res)[0] == 0
        if not right_direction:
            break
        current_position = res
    server.log(current_position)
    await menu_utils.focus_component(current_position)
Esempio n. 5
0
async def move_to_location(location: str, stream: server.Stream):
    server.log(f"moving to {location}")
    await ensure_not_moving()
    route = await request_route(location)
    for i, location in enumerate(route[:-1]):
        next_location = route[i + 1]
        server.log(f"Getting path to next location {next_location}")
        await pathfind_to_next_location(next_location, stream)
Esempio n. 6
0
def load_all_grammars():
    import server

    menu_modules = list_imported_modules()
    for module in menu_modules:
        grammar = module.get_grammar()
        server.log(f"Loading grammar from module {module.__name__}")
        grammar.load()
Esempio n. 7
0
 async def to_call(self, kwargs):
     import server
     if self.format_args:
         args = await self.get_formatted_args(kwargs)
         kwargs = {}
     else:
         args = []
     try:
         await self.async_fn(*args, **kwargs)
     except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e:
         server.log(traceback.format_exc(), level=1)
Esempio n. 8
0
 def read_thread(self):
   while True:
     try:
       output = os.read(self.master_fd, 1024)
     except OSError as e:
       import server
       server.log('read thread error: {0}'.format(str(e)))
       break
     if len(output) == 0:
       break
     if self.available():
       identifier = self.old_id
     else:
       identifier = self.identifier
     self.process_server._send_message('task_output', {
       "output": output.decode('utf-8'), "identifier": identifier })
Esempio n. 9
0
async def gather_items_on_ground(radius):
    """
    Wood, coal, sap, stone etc.
    """
    async with server.player_status_stream() as stream:
        player_status = await stream.next()
        location = player_status["location"]
        start_tile = player_status["tileX"], player_status["tileY"]
        tile_blacklist = set([start_tile])
        while True:
            items_to_gather = collections.defaultdict(int)
            debris = await server.request("GET_DEBRIS",
                                          {"location": "location"})
            test_tiles_set = set()
            for item in debris:
                within_radius = distance_between_points(
                    start_tile, (item["tileX"], item["tileY"])) < radius
                if within_radius:
                    debris_tile = item["tileX"], item["tileY"]
                    for tile in get_adjacent_tiles(debris_tile) + [
                            debris_tile
                    ]:
                        items_to_gather[tile] += 1
                        if tile not in tile_blacklist:
                            test_tiles_set.add(tile)
            if not test_tiles_set:
                return
            player_status = await stream.next()
            current_tile = player_status["tileX"], player_status["tileY"]
            test_tiles = sort_test_tiles(test_tiles_set, start_tile,
                                         current_tile, items_to_gather)
            path, invalid = await pathfind_to_resource(test_tiles,
                                                       location,
                                                       stream,
                                                       cutoff=250)
            if path is None:
                server.log(
                    f"Unable to gather {len(test_tiles)} in radius {radius}")
                return
            for tile in path.tiles:
                tile_blacklist.add(tile)
            for tile in invalid:
                tile_blacklist.add(tile)
Esempio n. 10
0
 async def wrap_run(self):
     name = self.__class__.__name__
     server.log(f"Starting objective {name}", level=1)
     self.run_task = server.TaskWrapper(self.run())
     await self.run_task.task
     if self.run_task.exception:
         if isinstance(self.run_task.exception,
                       (Exception, ObjectiveFailedError)):
             server.log(
                 f"Objective {name} errored: \n{self.run_task.exception_trace}",
                 level=1)
         elif isinstance(self.run_task.exception, asyncio.CancelledError):
             server.log(f"Canceling objective {name}", level=1)
         await game.release_all_keys()
     else:
         server.log(f"Successfully completed objective {name}", level=1)
     for task_wrapper in self.tasks:
         await task_wrapper.cancel()
Esempio n. 11
0
def processToDatabase(data, ARGO_PER_HOUR):
    '''data = plat mobil
    argo per hour = bisa di tentukan di main code'''
    #preparing the data
    waktu = getDateTime()
    platNomor = str(data)

    #writing to database

    #checking if the car already inside
    databaseChecker = checkDatabase(platNomor)

    #if not exist in database, then the car is going in
    if not platNomor == "":
        if databaseChecker == "not exist":
            db.session.add(log(plat=str(platNomor), waktu=waktu))
            db.session.commit()
            return "Welcome " + str(
                platNomor) + ". Successfully write to database"
        else:
            #if exist in database, then the car is going out
            tempIndex = log.query.filter_by(plat=platNomor).first()
            waktuMasuk = datetime.strptime(tempIndex.waktu,
                                           '%Y-%m-%d %H:%M:%S.%f')
            waktuKeluar = waktu
            argo = calculateParkingPrice(waktuMasuk, waktuKeluar,
                                         ARGO_PER_HOUR)
            log.query.filter_by(plat=str(platNomor)).delete()
            db.session.add(
                history(plat=str(platNomor),
                        waktuMasuk=waktuMasuk,
                        waktuKeluar=waktu,
                        argo=argo))
            db.session.commit()
            return str(platNomor) + " has paid " + str(
                int(argo)) + "." + " History Successfully Updated!!"
Esempio n. 12
0
async def on_speech_mimicked(data):
    engine = get_engine()
    try:
        engine.mimic(data['said'].lower())
    except dragonfly.engines.base.engine.MimicFailure as e:
        server.log(str(e), level=2)
Esempio n. 13
0
def disallow_previous_item(previous, current):
    server.log(previous, current, level=2)
    return not previous or previous == current
Esempio n. 14
0
 def write_input(self, input):
   import server
   try:
     n = os.write(self.master_fd, bytes.fromhex(input))
   except OSError as e:
     server.log('error writing bytes: {0}'.format(str(e)))
Esempio n. 15
0
    def on_recognition(self, words):
        import server

        server.log("Recognized:", " ".join(words), level=1)
Esempio n. 16
0
def main():
    import server

    logging.basicConfig(level=logging.INFO)
    try:
        ensure_exclusive_mode_disabled_for_default_mic()
    except Exception as e:
        server.log(
            f"Unable to disable exclusive mode for default audio device: {traceback.format_exc()}",
            level=2,
        )
    model_dir = os.path.join(MODELS_DIR, "kaldi_model")
    engine = setup_engine(300, model_dir)

    # Register a recognition observer
    observer = Observer()
    observer.register()

    sleep.load_sleep_wake_grammar(True)
    stardew_context = AppContext(title="stardew")
    server.setup_async_loop()
    menus.load_all_grammars()
    any_context.load_grammar()
    new_game_menu.load_grammar()
    shop_menu.load_grammar()
    container_menu.load_grammar()
    game_menu.load_grammar()
    crafting_page.load_grammar()
    inventory_page.load_grammar()
    exit_page.load_grammar()
    skills_page.load_grammar()
    title_menu.load_grammar()
    load_game_menu.load_grammar()
    dialogue_menu.load_grammar()
    no_menu.load_grammar()
    any_menu.load_grammar()
    shipping_bin_menu.load_grammar()
    carpenter_menu.load_grammar()
    billboard_menu.load_grammar()
    geode_menu.load_grammar()
    museum_menu.load_grammar()
    letter_viewer_menu.load_grammar()
    quest_log_menu.load_grammar()
    animal_query_menu.load_grammar()
    coop_menu.load_grammar()
    title_text_input_menu.load_grammar()
    locations.load_grammar()
    cutscene.load_grammar()
    level_up_menu.load_grammar()
    shipped_items_menu.load_grammar()
    fishing_menu.load_grammar()
    mine_elevator_menu.load_grammar()
    purchase_animals_menu.load_grammar()
    # copy back user lexicon to speech-client root. May want to rethink this approach.
    if not IS_FROZEN:
        src = os.path.join(model_dir, "user_lexicon.txt")
        dst = os.path.abspath(
            os.path.join(os.path.abspath(__file__), "..", "..",
                         "user_lexicon.txt"))
        shutil.copyfile(src, dst)
    run_engine()