def main(args):
    print(c.GROUP_NAME, "Attendance Tracker Version", c.VERSION)
    # Init textMode
    textMode = 1 #1 for text, 0 for UI
    # Process the arguments
    if len(args) > 1:
        arg = args[1].lower()
        if arg == "--help":
            showHelp()
            sys.exit(0)
        elif arg == "--version":
            showVersion()
            sys.exit(0)
        elif arg == "--nogui":
            textMode = 1
        else:
            print("Invalid argument:", args[1])
            sys.exit(0)

    # Start the program into either textmode or GUI mode
    if textMode == 0:
        global app
        app = UI(args)
        app.exec_()
    else:
        TextUI().start()

    # Exit normally
    sys.exit(0)
Exemplo n.º 2
0
    def filter(self):
        """
        Filter the list of apartments on specific criteria
        """
        self._validate_parsed_command(["greater", "type"])

        # filter by type
        if self._parsed_command["type"]:
            expense_type = self._parsed_command["type"]
            filtered_bloc_dict = {}
            for apartment_id in self._bloc_dict.keys():
                if self._bloc_dict[apartment_id].expenses[expense_type]:
                    filtered_bloc_dict[apartment_id] = self._bloc_dict[apartment_id]

            self._bloc_dict = filtered_bloc_dict

        # filter by total greater than
        if self._parsed_command["greater"]:
            amount_greater = float(self._parsed_command["greater"])
            filtered_bloc_dict = {}
            for apartment_id in self._bloc_dict.keys():
                if self._bloc_dict[apartment_id].get_total_expenses() > amount_greater:
                    filtered_bloc_dict[apartment_id] = self._bloc_dict[apartment_id]

            self._bloc_dict = filtered_bloc_dict

        # print(filtered_bloc_dict)
        if not filtered_bloc_dict:
            UI.set_message("No apartment fits the criteria")
        else:
            UI.set_message("Apartments filtered successfully")
Exemplo n.º 3
0
class DandelionApp:
    def __init__(self, config_file=None):
        self._config_manager = ConfigurationManager(config_file)

    def start_server(self):
        self._server = Server(
            self._config_manager.local_address,
            self._config_manager.local_port,
            self._config_manager.server,  # info_dict
            self._config_manager.content_db,
        )
        self._server.start()

    def start_content_synchronizer(self):
        self._synchronizer = Synchronizer(
            self._config_manager.local_address,
            self._config_manager.local_port,
            self._config_manager.type,
            self._config_manager.content_db,
        )
        self._synchronizer.start()

    def run_ui(self):

        self._ui = UI(
            self._config_manager.ui, self._config_manager.content_db, self._server, self._synchronizer  # dict
        )
        self._ui.run()

    def exit(self):
        self._synchronizer.stop()
        self._server.stop()
Exemplo n.º 4
0
def reset(keep_player=False):
    global SCREEN_SIZE, RANDOM_SEED, MAP, PLAYER

    RANDOM_SEED += 1
    UI.clear_all()
    TurnTaker.clear_all()

    if keep_player:
        PLAYER.refresh_turntaker()
        PLAYER.levels_seen += 1

    else:

        if not PLAYER is None:
            print("Game Over")
            print("%d evidence in %d turns; %d levels seen" %(len(PLAYER.evidence),PLAYER.turns,PLAYER.levels_seen))

        PLAYER = Player()

    if not MAP is None:
        MAP.close()
        del MAP

    MAP = Map.random(RANDOM_SEED,SCREEN_SIZE-(0,4),PLAYER)
    MAP.generate()
Exemplo n.º 5
0
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        logging.info('Stopping ShakeCast Server...')
        self.stop_requested = True

        ui = UI()
        ui.send('shutdown')
Exemplo n.º 6
0
    def list_total_apartment(self):
        """
        Displays the total expenses for an apartment
        """
        self._validate_parsed_command(["id"])

        apartment_id = self._parsed_command["id"]
        UI.set_message("Total expenses = " + str(self._bloc_dict[apartment_id].get_total_expenses()))
Exemplo n.º 7
0
 def start(self):
     while True:
         command = UI.get_input("> ")
         if command == 'start':
             self.ask()
         elif command == 'highscores':
             UI.display(self.show_highscores())
         elif command == 'help':
             UI.display(self.__HELP_MESSAGE)
         elif command == 'exit':
             return
Exemplo n.º 8
0
    def stat_total_type(self):
        """
        Displays the total for an expense type
        """
        self._validate_parsed_command(["expense_type"])

        sum_type = self._parsed_command["expense_type"]
        total = sum([self._bloc_dict[i].expenses[sum_type] for i in self._bloc_dict])
        # for apartment_id in self._bloc_dict:
        #    total += self._bloc_dict[apartment_id].expenses[sum_type]

        UI.set_message("Total expenses for " + sum_type + " = " + str(total))
Exemplo n.º 9
0
    def stat_max_apartment(self):
        """
        Displays the biggest expense in an apartment
        """
        self._validate_parsed_command(["id"])

        apartment_id = self._parsed_command["id"]
        biggest_types = self._bloc_dict[apartment_id].get_max_expenses_type()

        if biggest_types:
            UI.set_message("Biggest expense is " + biggest_types.__str__() + " = " + str(
                self._bloc_dict[apartment_id].expenses[biggest_types[0]]))
        else:
            UI.set_message("Apartment has all expenses = 0")
Exemplo n.º 10
0
    def redraw_screen(self,t=0):
        # draw and flush screen
        if not UI.need_update(t):
            # clearly one of the libtcod functions here causes the wait for the next frame
            sleep(1.0/Player.LIMIT_FPS)
            return

        self.map.draw()
        self.draw_ui(Position(0,Player.SCREEN_SIZE.y-3))
        UI.draw_all(t)

        libtcod.console_flush()

        # clear screen
        libtcod.console_clear(0)
Exemplo n.º 11
0
Arquivo: menu.py Projeto: ahonn/nada
    def __init__(self):
        reload(sys)
        sys.setdefaultencoding('UTF-8')

        self.title = 'Nada'
        self.model = ['最新期刊', '分类期刊', '搜索期刊', '收藏夹', '关于']
        self.view = 'menu'
        self.ctrl = 'menu'

        self.offset = 0
        self.index = 0
        self.step = 10
        self.play_id = -1
        self.play_vol = -1

        self.present = []
        self.stack = []

        self.player = Player()
        self.ui = UI()
        self.luoo = Luoo()
        self.downloader = Downloader()

        self.database = Database()
        self.database.load()
        self.collections = self.database.data['collections'][0]

        self.screen = curses.initscr()
        self.screen.keypad(1)
Exemplo n.º 12
0
    def __init__(self, config_file_path):
        config = ConfigParser.RawConfigParser()
        config.read(config_file_path)

        self._logger = logging.getLogger(__name__)
        self._ui = UI("lazzormanagement\nbooting...")

        user_config_file_path = os.path.dirname(config_file_path) + \
                os.path.sep + config.get('Users', 'users_file')
        self._user_manager = UserManager(user_config_file_path)
        self._lazzor = Lazzor()
 
        while True:
            try:
                self._upay_session_manager = nupay.SessionManager(config)
                break
            except nupay.SessionConnectionError as e:
                self._logger.warning("Can not reach the database")
                self._ui.warning_database_connection(timeout = 5)
            except nupay.TimeoutError as e:
                self._logger.warning("Timeout while connection to the database")
                self._ui.warning_database_connection(timeout = 5)

            self._ui.notify_try_again()


        self._token_reader = nupay.USBTokenReader()
Exemplo n.º 13
0
    def list_by_type(self):
        """
        Displays only the apartments having a specific expense type
        """
        self._validate_parsed_command(["expense_type"])

        expense_type = self._parsed_command["expense_type"]
        filtered_bloc_dict = {}
        for apartment_id in self._bloc_dict.keys():
            if self._bloc_dict[apartment_id].expenses[expense_type] != 0:
                filtered_bloc_dict[apartment_id] = self._bloc_dict[apartment_id]

        if filtered_bloc_dict:
            UI.set_message(UI.get_bloc_table(filtered_bloc_dict))
        else:
            UI.set_message("There are no apartments with " + expense_type)
Exemplo n.º 14
0
 def ui ( self, context, parent        = None, 
                         kind          = None, 
                         view_elements = None, 
                         handler       = None ):
     """ Creates a UI user interface object.
     """
     if type( context ) is not dict:
         context = { 'object': context }
     ui = UI( view          = self,
              context       = context,
              handler       = handler or self.handler or default_handler(),
              view_elements = view_elements )
     if kind is None:
         kind = self.kind
     ui.ui( parent, kind )
     return ui
Exemplo n.º 15
0
 def __init__(self, current=0):
     State.__init__(self)
     self.ui = UI(self, Jules_UIContext)
     self.nextState = GameStart
     logo_duration = 20 * 1000
     scores_duration = 5 * 1000
     self.displays = [(logo_duration, self.draw_logo),
                     (scores_duration, self.draw_high_scores)]
     self.eventid = TimerEvents.SplashScreen
     self.current = current
     self.draw = self.displays[self.current][1]
     self.instructions = ['Can you think fast and react faster?',
                          'This game will test both.',
                          'Your job is to destroy the bonus blocks.',
                          'Sounds easy, right?... Wrong!',
                          'There are several problems.',
                          'If you destroy a penalty block you lose 200 pts.',
                          'If you get 3 penalties, you lose a life.',
                          'If you lose 3 lives, the game is over.',
                          'The bonus and penalty blocks',
                          'change colors every 5 seconds.',
                          'And on top of that, if you do not destroy a',
                          'random non-bonus, non-penalty block every',
                          'couple of seconds, that will give you a',
                          'penalty too. Think you got all that?']
Exemplo n.º 16
0
    def _initme(self, userdata=None):
        #the main classes
        self.m = Model(self)
        self.capture = Capture(self)
        self.ui = UI(self)

        return False
Exemplo n.º 17
0
    def run(self):
        self.player = Monster(name='Player')
        self._load_history(self.player)

        monster = random.choice(list(monsters.viewkeys()))
        self.monster = Monster(monsters[monster][0], monster, description=monsters[monster][1])
        self.ui = UI(self.player)
        self.ui.monster = self.monster

        self.ui.welcome()
        
        a = 1
        while a != 0:
            self._load_history(self.monster)

            a = self.run_loop()

            if a != 0:
                self.ui.update_display()

            self._save_history(self.player)
            self._save_history(self.monster)
            
            monster = random.choice(list(monsters.viewkeys()))
            self.monster = Monster(monsters[monster][0], monster, description=monsters[monster][1])
            self.ui.monster = self.monster
Exemplo n.º 18
0
class Cuadraditos(activity.Activity):

    log = logging.getLogger('cuadraditos-activity')

    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        #flags for controlling the writing to the datastore
        self.I_AM_CLOSING = False
        self.I_AM_SAVED = False
        self.props.enable_fullscreen_mode = False
        self.ui = None
        Constants(self)
        #self.modify_bg(gtk.STATE_NORMAL, Constants.color_black.gColor)

        #wait a moment so that our debug console capture mistakes
        gobject.idle_add(self._initme, None)

    def _initme(self, userdata=None):
        #the main classes
        self.m = Model(self)
        self.capture = Capture(self)
        self.ui = UI(self)

        return False

    def stop_pipes(self):
        self.capture.stop()

    def restart_pipes(self):
        self.capture.stop()
        self.capture.play()

    def close(self):
        self.I_AM_CLOSING = True
        self.m.UPDATING = False
        if (self.ui != None):
            self.ui.hide_all_windows()
        if (self.capture != None):
            self.capture.stop()

        #this calls write_file
        activity.Activity.close(self)

    def destroy(self):
        if self.I_AM_SAVED:
            activity.Activity.destroy(self)
Exemplo n.º 19
0
    def list_greater_than(self):
        """
        Displays only the apartments with an overall expense greater than the given amount
        """
        self._validate_parsed_command(["greater"])

        greater_than = float(self._parsed_command["greater"])
        filtered_bloc_dict = {}
        for apartment_id in self._bloc_dict.keys():
            if self._bloc_dict[apartment_id].get_total_expenses() > greater_than:
                filtered_bloc_dict[apartment_id] = self._bloc_dict[apartment_id]

        # check if empty
        if filtered_bloc_dict:
            UI.set_message(UI.get_bloc_table(filtered_bloc_dict))
        else:
            UI.set_message("There are no apartments with overall expenses greater than " + str(greater_than))
Exemplo n.º 20
0
def main():
    """
    The main method of the nuncium application will initialize the execution of
    the program. Threads will be used to query for user input. Each window has
    its own thread to manage the update of its own interface.
    """

    # UI object: The user interface of the nuncium application.
    ui = UI()

    # Integer: The height will consist of the entire screen and the width will
    #          consist of approximately 1/5 of the screen's width.
    height = curses.LINES
    width = int(curses.COLS / 5)

    # String: The default news category that is displayed on startup.
    category = "Top Stories"

    # Window object: The window that will render the menu interface.
    menu_window = ui.window(height, width)
    ui.display_menu(menu_window, category, color=curses.COLOR_BLUE)

    # Integer: The starting position in the x-coordinate of the news window will
    #          be rendered where the last window left off. The width of the news
    #          window will consist of the remaining free space.
    x = width
    width = curses.COLS - width

    # Window object: The window that will render the news content.
    news_window = ui.window(height, width, x, y=0)

    # News object: The news aggregator of the nunicum application.
    news = News()
    news.fetch_news(ui, news_window)

    ui.cursor(menu_window, x=1, y=1, y2=1, current="Top Stories")

    # Thread object: A thread used for updating the menu and news content.
    menu_thread = Thread(target=update, args=(menu_window,), daemon=True)
    news_thread = Thread(target=update, args=(news_window,), daemon=True)

    menu_thread.start()
    news_thread.start()

    # Wait for the threads to finish working.
    while running:
        pass

    ui.cleanup()
Exemplo n.º 21
0
Arquivo: player.py Projeto: ahonn/nada
    def __init__(self):
        self.ui = UI()

        self.popen_handler = None
        self.play = False
        self.pause = False
        self.songs = []
        self.play_vol = -1
        self.play_id = -1
        self.view = 'songs'
Exemplo n.º 22
0
    def list_greater_than_parse(self, command):
        """
        Parses and validates the 'list greater than' command
        Input:
            command - the user command
        Return:
            True on valid and False otherwise
        """
        # list greater than <amount>
        self.set_command(command)
        pattern_greater = self._regex_search(self._PATTERN_LIST_GREATER)
        if pattern_greater:
            greater = pattern_greater.group(1)

            self._parsed_command = {"greater": greater}
            return True

        UI.set_message(UI.get_error("list greater than <amount>"))
        return False
Exemplo n.º 23
0
Arquivo: main.py Projeto: aarmea/mumei
def main(name="", levelName=None):
    """Create and run the UI."""
    ui = UI()
    if levelName is None:
        ui.pushState(WelcomeScreen(ui))
    else:
        print "Directly loading %s" % levelName
        ui.pushState(LevelSplashScreen(ui, levelName))
    ui.run()
Exemplo n.º 24
0
 def start(self):
     self.s_termin_io.bind(('localhost', self.io_port))
     self.s_termin_io.listen(1)
     self.client_socket.connect(("localhost", self.port))
     self.interrupt_socket.bind('client_interrupt.sock')
     self.interrupt_socket.listen(1)
     self.ui = UI(self.c_termin_io, self.io_port, True) 
     client_run = self.run
     ui_run = self.ui.run
     threading.Thread(target=ui_run).start()
     client_run()
Exemplo n.º 25
0
 def __init__(self, lives=3, score=0):
     State.__init__(self)
     self.ui = UI(self, Jules_UIContext)
     self.lives = lives
     self.score = score
     self.nextState = lambda: Playing(self.lives, self.score)
     self.prompt = "Ready?"
     self.countdown_step = 500
     self.count = 3
     self.text = self.prompt
     self.eventid = TimerEvents.GameStart
Exemplo n.º 26
0
    def list_less_than(self):
        """
        Displays only the apartments with an overall expense less than the given amount
        """
        self._validate_parsed_command(["less"])

        less_than = float(self._parsed_command["less"])
        upper_id_limit = self._parsed_command["upper_id_limit"]
        filtered_bloc_dict = {}
        for apartment_id in range(1, int(upper_id_limit) + 1):
            apartment_id = str(apartment_id)
            if self.is_apartment(apartment_id):
                if self._bloc_dict[apartment_id].get_total_expenses() < less_than:
                    filtered_bloc_dict[apartment_id] = self._bloc_dict[apartment_id]

        # check if empty
        if filtered_bloc_dict:
            UI.set_message(UI.get_bloc_table(filtered_bloc_dict))
        else:
            UI.set_message("There are no apartments with overall expenses less than " + str(less_than))
Exemplo n.º 27
0
    def list_less_than_parse(self, command):
        """
        Parses and validates the 'list less than' command
        Input:
            command - the user command
        Return:
            True on valid and False otherwise
        """
        # less than <amount> before <id>
        self.set_command(command)
        pattern_less = self._regex_search(self._PATTERN_LIST_LESS)
        if pattern_less:
            less = pattern_less.group(1)
            upper_id_limit = pattern_less.group(2)

            self._parsed_command = {"less": less, "upper_id_limit": upper_id_limit}
            return True

        UI.set_message(UI.get_error("list less than <amount> before <apartment_id>"))
        return False
def main():
    setproctitle('desktop-security-assistant')
    args = parse_args()
    setup_logging(args.debug)

    conf = load_configuration_files()

    checks_to_be_displayed = []
    for c in scan_and_run_config_blocks(conf):
        if c.status != 'disabled' and not c.hidden:
            checks_to_be_displayed.append(c)

    if args.cli:
        print_out_checks(checks_to_be_displayed)
        return

    ui = UI()
    for c in checks_to_be_displayed:
        ui.add_check_tab(c)

    ui.main()
Exemplo n.º 29
0
    def filter_parse(self, command):
        """
        Parses and validates the filter command
        Input:
            command - the user command
        Return:
            True on valid and False otherwise
        """
        self.set_command(command)

        # filter by total amount greater than
        pattern_total_greater = self._regex_search(self._PATTERN_FILTER_GREATER_THAN_TOTAL)
        if pattern_total_greater:
            greater = pattern_total_greater.group(1)
            self._parsed_command = {"greater": greater, "type": None}
            return True

        # filter by only apartments having that type
        pattern_by_type = self._regex_search(self._PATTERN_FILTER_BY_TYPE)
        if pattern_by_type:
            expense_type = pattern_by_type.group(1)
            if not Apartment.is_expense_type(expense_type):
                UI.set_message(UI.get_error_types())
                return False

            self._parsed_command = {"greater": None, "type": expense_type}
            return True

        UI.set_message(UI.get_error_filter())
        return False
Exemplo n.º 30
0
    def sort_parse(self, command, reverse=False):
        """
        Parses and validates the sort command
        Input:
            command - the user command
            reverse - the order of the sort
        Return:
            True on valid and False otherwise
        """
        self.set_command(command)

        # simple sort no type use total expense
        pattern_sort = self._regex_search(self._PATTERN_SORT)
        if pattern_sort:
            self._parsed_command = {"type": None, "reverse": reverse}
            return True

        # use an expense type for the sort
        pattern_sort_by_type = self._regex_search(self._PATTERN_SORT_BY_TYPE)
        if pattern_sort_by_type:
            expense_type = pattern_sort_by_type.group(1)
            if not Apartment.is_expense_type(expense_type):
                UI.set_message(UI.get_error_types())
                return False

            self._parsed_command = {"type": expense_type, "reverse": reverse}
            return True

        UI.set_message(UI.get_error_sort())
        return False
import wx
from ui import UI
import logging

logging.basicConfig(filename="app.log",
                    filemode="w",
                    level=logging.INFO,
                    format='%(asctime)s - %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p')
logging.info("Running: ")

try:
    if __name__ == "__main__":
        app = wx.App()
        frm = UI()
        frm.Show()
        app.MainLoop()

except Exception as e:
    logging.error(f"main_ui, {e}")
Exemplo n.º 32
0
def lc(image_path):
    ui = UI()
    ui.load_img(image_path)
    ui.create_lumi_scale()
    ui.create_cont_scale()
    ui.start()
Exemplo n.º 33
0
 def __init__(self):
     """Create a reference to the UI, and establish the default nextState."""
     self.ui = UI(self)
     self.nextState = None
Exemplo n.º 34
0
def main():
    ui = UI(_callback, UISpecs())
    # show(ui.layout)
    curdoc().add_root(ui.layout)
Exemplo n.º 35
0
def main(stdscr):
    test = UI(stdscr, Config())
    test.start()
Exemplo n.º 36
0
 def switch_to_scene(self):
     self.root.add_widget(self.context.scene)
     self.root.add_widget(UI())
     self.root.remove_widget(self.context.loader)
     self.context.game.start_round()
Exemplo n.º 37
0
from tkinter import *
from gui import GUI
from ui import UI

name = input("Enter your name here: ")
uiTYPE = input("Which type of UI would you like(c -> console; g -> gui): ")
if uiTYPE == "c":
    ui = UI(name)
elif uiTYPE == "g":
    root = Tk()
    my_gui = GUI(root, name)
    root.mainloop()
else:
    print("If you can't even choose between c and g, I feel bad for you ;)")
Exemplo n.º 38
0
        def get_random_persons_uids():
            person_uids = []
            length = random.randrange(1, len(persons))

            for i in range(length):
                person = persons[random.randrange(0, len(persons))]
                person_uids.append(person.uid)

            return person_uids

        activities_len = 10
        count = 0

        while count < activities_len:
            try:
                activity_service.add_activity(
                    Activity(activity_repo.generate_uid(),
                             get_random_persons_uids(), get_random_date(),
                             get_random_time(), get_random_description()))

                count += 1

            except ActivityServiceError:
                continue

    ui = UI(person_service, activity_service)
    ui.run()

    person_repo.save_data(file=settings.persons)
    activity_repo.save_data(file=settings.activities)
Exemplo n.º 39
0
 def stop():
     ui = UI()
     ui.send('shutdown')
Exemplo n.º 40
0
def main():
    ui = UI()
    ui.run()
Exemplo n.º 41
0
class Game(DirectObject):
    def __init__(self, app):
        self.app = app
        builtins.get_local_file = get_local_file

        #insert the game into buildins for easy gui callback
        builtins.game = self

        #stats
        self.stats = Stats()
        builtins.stats = self.stats

        with loading():
            #database
            self.db = Database('save.db')
            #init the gui system
            self.gui = UI()
            self.gui.software_cursor()
            #make the main menu
            self.gui.load_from_file(get_local_file('ui/layout.json'))
            self.gui.show_hide([
                'special_frame', 'trait_frame', 'perk_frame', 'skill_frame',
                'stats_frame', 'level_up', 'level_down', 'level_node', 'items',
                'paypal', 'shader', 'save', 'exit'
            ])
            self.stats.update_ui()

    def toggle_shader(self):
        if getattr(self, "shader_quad", None) is None:
            winprops = WindowProperties()
            winprops.set_size(1024, 600)
            props = FrameBufferProperties()
            props.set_rgb_color(True)
            props.set_rgba_bits(8, 8, 8, 8)
            props.set_depth_bits(0)
            props.set_aux_rgba(False)
            props.set_srgb_color(False)
            self.fbo = base.graphicsEngine.make_output(
                base.pipe, 'fbo', -2, props, winprops,
                GraphicsPipe.BFSizeTrackHost | GraphicsPipe.BFCanBindEvery
                | GraphicsPipe.BFRttCumulative | GraphicsPipe.BFRefuseWindow,
                base.win.get_gsg(), base.win)

            self.fbo.set_clear_color((0, 0, 0, 0))
            self.color = Texture()
            self.color.set_wrap_u(Texture.WM_clamp)
            self.color.set_wrap_v(Texture.WM_clamp)
            self.fbo.add_render_texture(tex=self.color,
                                        mode=GraphicsOutput.RTMBindOrCopy,
                                        bitplane=GraphicsOutput.RTPColor)
            self.fbo_cam = base.makeCamera2d(self.fbo)
            cm = CardMaker("quad")
            cm.set_frame_fullscreen_quad()

            self.shader_quad = NodePath(cm.generate())
            self.shader_quad.set_shader(
                Shader.load(Shader.SLGLSL, "shaders/crt_v.glsl",
                            "shaders/crt_f.glsl"), 1)
            self.shader_quad.set_shader_input('color_tex', self.color)
            self.shader_quad.reparent_to(render2dp)
        else:
            if self.shader_quad.is_hidden():
                self.shader_quad.show()
                self.fbo.set_active(True)
            else:
                self.shader_quad.hide()
                self.fbo.set_active(False)

    def show_preview(self, name):
        txt = self.db.get_preview(name)
        self.gui['load_preview'].set_text(txt)
        self.gui.show_hide('preview_frame')
        self.last_name = name

    def load_from_db(self):
        self.db.load(self.last_name, self.stats)
        self.toggle_database()
        self.gui['feedback'].set_text('Character loaded!')
        self.gui['feedback_node'].show()

    def save_to_db(self):
        name = self.gui['name_input'].get()
        keys = self.gui['tag_input'].get()
        self.db.save(name, keys, self.stats)
        self.search(True)

    def search(self, show_all=False):
        #remove old buttons
        names_to_remove = []
        for name, element in self.gui.elements.items():
            if name.startswith('charater_load_'):
                names_to_remove.append(name)
        for name in names_to_remove:
            self.gui.remove_button(name)
        #find characters
        if show_all:
            records = self.db.search()
        else:
            records = self.db.search(self.gui['search_input'].get())

        #create buttons
        for name, keys, s, p, e, c, i, a, l in records:

            txt = '{name:<38}{keys:<59}{s:<8}{p:<8}{e:<8}{c:<8}{i:<8}{a:<8}{l:<8}'.format(
                name=name, keys=keys, s=s, p=p, e=e, c=c, i=i, a=a, l=l)
            self.gui.button(txt=txt,
                            sort_dict={
                                "name": name,
                                "tag": keys,
                                "s": s,
                                "p": p,
                                "e": e,
                                "c": c,
                                "i": i,
                                "a": a,
                                "l": l
                            },
                            cmd="game.show_preview('" + name + "')",
                            parent="database_frame_canvas",
                            width=1000,
                            pos=[3, i * 32],
                            mono_font=1,
                            center=0,
                            name='charater_load_' +
                            name.lower().replace(' ', '_'))
        self.gui.sort_buttons('database_frame_canvas', 'name')

    def toggle_database(self):
        if self.gui['trait_frame'].is_hidden():
            self.toggle_inventory()
        popup = ['database_frame', 'save_frame']
        editor = [
            'special_frame', 'trait_frame', 'perk_frame', 'skill_frame',
            'stats_frame', 'level_up', 'level_down', 'items', 'paypal',
            'shader', 'save', 'exit', 'level_node'
        ]
        if self.gui['database_frame'].is_hidden():
            self.gui.show_hide(popup, editor)
            self.search(True)
        else:
            self.gui.show_hide(editor, popup)
        self.gui.show_hide(None, 'preview_frame')

    def toggle_inventory(self):
        if self.gui['trait_frame'].is_hidden():
            self.gui.show_hide(
                ['trait_frame', 'perk_frame', 'skill_frame'],
                ['bonus_frame', 'weapon_frame', 'target_frame', 'hit_frame'])
            self.gui['items']['text'] = 'INVENTORY'
        else:
            if self.stats.level == 1:
                self.gui['feedback'].set_text('Level up first!')
            return
            self.gui.show_hide(
                ['bonus_frame', 'weapon_frame', 'target_frame', 'hit_frame'],
                ['trait_frame', 'perk_frame', 'skill_frame'])
            self.gui['items']['text'] = 'CHARACTER'

    def support(self, hide=False):
        popup = 'support_frame'
        editor = [
            'special_frame', 'trait_frame', 'perk_frame', 'skill_frame',
            'stats_frame', 'level_up', 'level_down', 'items', 'paypal',
            'shader', 'save', 'exit', 'level_node'
        ]
        if hide:
            self.gui.show_hide(editor, popup)
            self.gui['items']['text'] = 'INVENTORY'
        else:
            self.gui.show_hide(popup, editor)
            self.gui.show_hide(
                [],
                ['bonus_frame', 'weapon_frame', 'target_frame', 'hit_frame'])

    def do_nill(self):
        pass

    def save_screen(self):
        base.screenshot('character')

    def exit_game(self):
        with open('config.ini', 'w') as config_filename:
            Config.write(config_filename)
        self.app.final_exit()
Exemplo n.º 42
0
"""
__Author__: Romain Maillard
__Date__: 27.09.2017
__Name__: startLiveDisplay.py
__Description__: Load configuration, start UI

"""

import config
import time

from ui import UI
print("Start LiveDisplay")

#create and start the usre interface
userInterface = UI()
userInterface.start()

print("Stop LiveDisplay")

Exemplo n.º 43
0
 def runWizard(self):
   print('Ports.runWizard()')
   #myself = Ports()
   self.print_map()
   return UI.ask_integer('What port would you like to assign to this domain?')
Exemplo n.º 44
0
from board import Board
from ui import UI
board = Board()
ui = UI(board)
ui.read()
Exemplo n.º 45
0
 def __init__(self):
     self.ui = UI(DataManager())
Exemplo n.º 46
0
def register():
    UI.register()
Exemplo n.º 47
0
def unregister():
    UI.unregister()
Exemplo n.º 48
0
    def __init__(self):
        question_bank = QuestionBank(DataManager(), Question).generate()
        quiz = Quiz(question_bank)

        self.ui = UI(quiz)
Exemplo n.º 49
0
arena_size = 10

game_count = 10

try:
    if (len(sys.argv) == 4):
        gladiator_count = int(sys.argv[1])
        arena_size = int(sys.argv[2])
        game_count = int(sys.argv[3])
except Exception as e:
    print(e)
    print("Invalied arguments. Default parameters will be set.")
    sleep(2)

ui = UI(space_length)

for i in range(game_count):
    battleground = Battleground(arena_size, arena_size)

    gladiators = []

    for i in range(gladiator_count):
        gladiators.append(Gladiator(battleground,ascii_uppercase[i],random.randint(1,3),random.randint(1,5),100))

    while True:
        os.system("cls")

        for gladiator in gladiators:
            if gladiator in battleground.gladiators:
                if len(battleground.gladiators) > 1:
Exemplo n.º 50
0
from sys import exit, argv
from PyQt5.QtWidgets import QApplication
from ui import UI
from pack import Pack

pack = Pack(512, 512, False)
pack.insert(256, 256)
pack.insert(128, 128)
pack.insert(64, 64)
pack.insert(32, 32)
pack.insert(16, 16)
pack.insert(8, 8)
pack.insert(4, 4)
pack.insert(2, 2)
pack.insert(100, 100)
pack.insert(200, 50)
pack.insert(400, 25)
pack.insert(50, 200)
pack.insert(25, 400)
pack.insert(100, 100)
pack.insert(200, 50)
pack.insert(400, 25)
pack.insert(50, 200)
pack.insert(25, 400)

app = QApplication(argv)
ui = UI(pack)
ui.show()
exit(app.exec_())
Exemplo n.º 51
0
class KVStore:
    def __init__(self, evloop, nodeslist):
        self.evloop = evloop

        self.network = AsyncNetwork(self.evloop, nodeslist)
        self.ui = UI(self.evloop)
        self.ui.output('=============================')
        self.ui.output('==== Distributed KVStore ====')
        self.ui.output('=============================')
        self.ui.output(f'ID: {AsyncNetwork.OWN_ID + 1:02d}')
        self.ui.output(f'IP ADDR: {AsyncNetwork.OWN_IP}')

    async def main(self):
        await self.network.create_server()
        await self.network.connect_to_peers()

        try:
            while True:
                command = await self.ui.input()
                if command == '':
                    continue

                cmd = command.split()[0]
                data = command.split()[1:]

                cmd_handler = getattr(self, f'cmd_{cmd.lower()}', None)
                if cmd_handler is None:
                    self.ui.output(f'Unknown command "{cmd}"...')
                else:
                    await cmd_handler(data)

        except asyncio.CancelledError:
            self.network.close()
            self.ui.output('\nBYE!')

    async def cmd_set(self, data):
        if len(data) < 2:
            self.ui.output(f'Invalid! Usage: SET <key> <value>')
            return

        key = data[0]
        value = ' '.join(data[1:])

        hashed_key = Store.hash(key)
        logging.info(f'Key {key} hashed to {hashed_key}')
        dest = AsyncNetwork.placement(hashed_key)
        msg = SetMsg(key, value)

        if dest is None:
            logging.info('Storing in self!')
            self.network.handle_SetMsg(msg)
            self.ui.output('SET OK')
        else:
            # dest is a Peer object
            event = asyncio.Event()
            AsyncNetwork.requests[msg.uid] = (event, None)

            try:
                await asyncio.wait_for(dest.send(msg), 2, loop=self.evloop)
                await asyncio.wait_for(event.wait(), 3, loop=self.evloop)
            except asyncio.TimeoutError:
                # TODO: try sending to another peer
                logging.error('Failed to send SetMsg!')
                self.ui.output('SET FAILED')
            else:
                self.ui.output('SET OK')
            finally:
                del AsyncNetwork.requests[msg.uid]

        # sendlist = []
        # reqlist = []
        # for node, peer in AsyncNetwork.nodes.items():
        #     if peer is not None:
        #         msg = SetMsg(key, value)
        #         event = asyncio.Event()
        #
        #         sendlist.append(peer.send(msg))
        #         AsyncNetwork.requests[msg.uid] = (event, None)
        #         reqlist.append(msg.uid)
        #
        # await asyncio.wait(sendlist, loop=self.evloop, timeout=3)
        # done, pending = await asyncio.wait(
        #     [AsyncNetwork.requests[uid][0].wait() for uid in reqlist],
        #     loop=self.evloop, timeout=3
        # )
        #
        # if len(done) >= 1:
        #     self.ui.output('SET OK')
        # else:
        #     self.ui.output('SET FAILED')
        # # clean up the requests
        # for uid in reqlist:
        #     del AsyncNetwork.requests[uid]

    async def cmd_get(self, data):
        if len(data) != 1:
            self.ui.output(f'Invalid! Usage: GET <key>')
            return

        key = data[0]
        curr_id = AsyncNetwork.placement(key, return_id=True)
        succ_id = (curr_id + 1) % 10
        pred_id = 9 if curr_id == 0 else (curr_id - 1)
        # get successor ID
        while True:
            if succ_id == AsyncNetwork.OWN_ID:
                break
            if AsyncNetwork.nodes[AsyncNetwork.ids[succ_id]] is not None:
                break
            succ_id = (succ_id + 1) % 10
        # get predecessor ID
        while True:
            if pred_id == AsyncNetwork.OWN_ID:
                break
            if AsyncNetwork.nodes[AsyncNetwork.ids[pred_id]] is not None:
                break
            pred_id = 9 if pred_id == 0 else (pred_id - 1)

        try_ids = [curr_id, succ_id, pred_id]
        msg = GetMsg(key)

        for tryid in try_ids:
            logging.info(f'Trying to GetMsg from ID: {tryid+1}')
            if tryid == AsyncNetwork.OWN_ID:
                # get key from self
                value = self.network.handle_GetMsg(msg, ret=True)
                if value is not None:
                    self.ui.output(f'Found: {value}')
                    return
            else:
                dest = AsyncNetwork.nodes[AsyncNetwork.ids[tryid]]
                if dest is None:  # succ or pred is not alive
                    continue
                event = asyncio.Event()
                AsyncNetwork.requests[msg.uid] = (event, None)

                try:
                    await asyncio.wait_for(dest.send(msg), 2, loop=self.evloop)
                    await asyncio.wait_for(event.wait(), 3, loop=self.evloop)
                except asyncio.TimeoutError:
                    logging.error('Failed to send GetMsg!')
                else:
                    value = AsyncNetwork.requests[msg.uid][1].value
                    if value is not None:
                        self.ui.output(f'Found: {value}')
                        del AsyncNetwork.requests[msg.uid]
                        return
                finally:
                    if msg.uid in AsyncNetwork.requests:
                        del AsyncNetwork.requests[msg.uid]

        # none of the try_ids worked
        self.ui.output('Not found')

        # sendlist = []
        # reqlist = []
        # for node, peer in AsyncNetwork.nodes.items():
        #     if peer is not None:
        #         msg = GetMsg(key)
        #         event = asyncio.Event()
        #
        #         sendlist.append(peer.send(msg))
        #         AsyncNetwork.requests[msg.uid] = (event, None)
        #         reqlist.append(msg.uid)
        #
        # # TODO: add check for empty sendlist
        # await asyncio.wait(sendlist, loop=self.evloop, timeout=3)
        # done, pending = await asyncio.wait(
        #     [AsyncNetwork.requests[uid][0].wait() for uid in reqlist],
        #     loop=self.evloop, timeout=3
        # )
        #
        # if len(done) >= 1:
        #     values = [AsyncNetwork.requests[uid][1].value for uid in reqlist]
        #     for val in values:
        #         if val is not None:
        #             self.ui.output(f'Found: {val}')
        #             # clean up the requests
        #             for uid in reqlist:
        #                 del AsyncNetwork.requests[uid]
        #             return
        # # if we reach here, we could not find the key
        # self.ui.output('Not found')
        # # clean up the requests
        # for uid in reqlist:
        #     del AsyncNetwork.requests[uid]

    async def cmd_owners(self, data):
        if len(data) != 1:
            self.ui.output(f'Invalid! Usage: OWNERS <key>')
            return

        key = data[0]
        curr_id = AsyncNetwork.placement(key, return_id=True)
        succ_id = (curr_id + 1) % 10
        pred_id = 9 if curr_id == 0 else (curr_id - 1)
        # get successor ID
        while True:
            if succ_id == AsyncNetwork.OWN_ID:
                break
            if AsyncNetwork.nodes[AsyncNetwork.ids[succ_id]] is not None:
                break
            succ_id = (succ_id + 1) % 10
        # get predecessor ID
        while True:
            if pred_id == AsyncNetwork.OWN_ID:
                break
            if AsyncNetwork.nodes[AsyncNetwork.ids[pred_id]] is not None:
                break
            pred_id = 9 if pred_id == 0 else (pred_id - 1)

        try_ids = [curr_id, succ_id, pred_id]
        msg = GetOwners(key)
        owners = []

        for tryid in try_ids:
            logging.info(f'Trying to GetOwners from ID: {tryid+1}')
            if tryid == AsyncNetwork.OWN_ID:
                # get key from self
                is_owner = self.network.handle_GetOwners(msg, ret=True)
                if is_owner:
                    owners.append(tryid)
            else:
                dest = AsyncNetwork.nodes[AsyncNetwork.ids[tryid]]
                if dest is None:  # succ or pred is not alive
                    continue
                event = asyncio.Event()
                AsyncNetwork.requests[msg.uid] = (event, None)

                try:
                    await asyncio.wait_for(dest.send(msg), 2, loop=self.evloop)
                    await asyncio.wait_for(event.wait(), 3, loop=self.evloop)
                except asyncio.TimeoutError:
                    logging.error('Failed to send GetOwners!')
                else:
                    is_owner = AsyncNetwork.requests[msg.uid][1].is_owner
                    if is_owner:
                        owners.append(tryid)
                        del AsyncNetwork.requests[msg.uid]
                finally:
                    if msg.uid in AsyncNetwork.requests:
                        del AsyncNetwork.requests[msg.uid]

        outstr = ['{:02d}'.format(owner + 1) for owner in owners]
        self.ui.output(' '.join(outstr))

    async def cmd_list_local(self, data):
        if len(data) != 0:
            self.ui.output(f'Invalid! Usage: LIST_LOCAL')
            return

        keys = []
        keys.extend(Store.hash_table.keys())
        for replica in Store.replicas.keys():
            keys.extend(Store.replicas[replica].keys())
        for key in sorted(keys):
            self.ui.output(f'{key}')
        self.ui.output('END LIST')

    async def cmd_batch(self, data):
        if len(data) != 2:
            self.ui.output(f'Invalid! Usage: BATCH <file1> <file2>')
            return

        infile = open(data[0], 'r')
        outfile = open(data[1], 'w')

        self.ui.set_output_to_return(True, outfile=outfile)

        for line in infile:
            if line.strip() == '':
                continue

            cmd = line.split()[0]
            data = line.split()[1:]

            cmd_handler = getattr(self, f'cmd_{cmd.lower()}', None)
            if cmd_handler is None:
                self.ui.output(f'Unknown command "{cmd}"...')
            else:
                await cmd_handler(data)
                await asyncio.sleep(0.2, loop=self.evloop)

        infile.close()
        outfile.close()

        self.ui.set_output_to_return(False)

    ####### CUSTOM COMMANDS #######

    async def cmd_connected(self, data):
        connected = [
            ip for ip, peer in AsyncNetwork.nodes.items() if peer != None
        ]
        self.ui.output('\n'.join(connected))

    async def cmd_pending(self, data):
        pending = len(AsyncNetwork.requests.keys())
        self.ui.output(f'{pending} pending requests...')

    async def cmd_time(self, data):
        self.ui.output(str(time.time()))
Exemplo n.º 52
0
'''
    Created on Nov 7, 2015

    @author: aflorea
'''

from ui.UI import *
from repository.repo import *
from controller.controller import *

pRepository = PersonsRepository()
aRepository = ActivityRepository()
mRepository = mapRepository()
pController = PersonController(pRepository, mRepository)
aController = ActivityController(aRepository)
aUI = UI(pController, aController)

aUI.mainMenu()
from repository import Repository
from service import Service
from ui import UI

path = r"C:\Users\Andreea\Desktop\Facultate\Anul_II\Sem2\AI\GA_TSP\data\berlin.in"
repo = Repository(path)
service = Service(repo)
ui = UI(service)
ui.main()
Exemplo n.º 54
0
from get_char import Switch
from rockdb import RockDB
from check import Check
from ui import UI
from random_fill import RandomFillDB
from pprint import pprint

db = RockDB()
ui = UI()


def add_entity(name):
    if name == "band":
        band = ui.band_input()
        db.insert_band(band)

    elif name == "album":
        db.insert_album(ui.album_input())

    elif name == "song":
        db.insert_song(ui.song_input())


def update_entity(name):
    if name == "band":
        band_entity = ui.band_update()
        if band_entity is not None:
            db.update_band(band_entity)
            return True

    elif name == "album":
Exemplo n.º 55
0
 def play_game(self):
     table = Table()
     game = Game(table, self.player, lives=self.max_lives)
     ui = UI(game)
     ui.start()
 def wait_for_menu_input(self):
     return UI.menu_input()
Exemplo n.º 57
0
def hm(image_path_1, image_path_2):
    if (image_path_2 == ''):
        ui = UI()
        ui.load_img(image_path_1, label="source", row=1, col=0)
        ui.create_hm_single_buttons(row=4, col=1)
        ui.load_img(image_path_1, label="result", row=4, col=0)
        ui.start()
    else:
        ui = UI()
        ui.load_img(image_path_1, label="source", row=1, col=0)
        ui.load_img(image_path_2, label="target", row=1, col=1)
        ui.create_hm_buttons(row=4, col=1)
        ui.load_img(image_path_1, label="result", row=4, col=0)
        ui.start()
 def display_menu(self):
     UI.display_menu(self.menu.make_menu_text())
Exemplo n.º 59
0
#!/usr/bin/env python3

from ui import UI
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Run an infection simulation.")
    parser.add_argument('-v',
                        '--verbose',
                        help='Be verbose',
                        action='store_true')
    parser.add_argument('-s',
                        '--seed',
                        help='Set seed for the random generator',
                        type=int)
    args = vars(parser.parse_args())

    ui = UI(args['verbose'], args['seed'])

    ui.initSimulation()

    input("Press Enter to start simulation")
    ui.startSimulation()
Exemplo n.º 60
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from ui import UI

from sys import argv

if __name__ == '__main__':
    testmode = len(argv) > 1 and argv[1] == 'test'
    UI(testmode).start()