Exemple #1
0
def type_chooser(tp, types, completer):
    pt.shortcuts.clear()
    print("Please type everything you'd like to {} "
          "(<space> separated)".format(tp))
    longs = []
    shorts = []
    for i, t in enumerate(types):
        long, short = t
        longs.append("<{color}>{long}</{color}>".format(color=COLORS[i],
                                                        long=long))
        shorts.append("<{color}>{short}</{color}>".format(color=COLORS[i],
                                                          short=short))
    print(pt.HTML("Options are: [" + " ".join(longs) + "]"))
    print(pt.HTML("You can use abbreviations like [" + " ".join(shorts) + "]"))
    print(
        "If you would like to {} multiple different types of the ".format(tp))
    print("same resource, enter it multiple times")
    print("Press ENTER when finished")
    out = session.prompt("> ",
                         default="v ",
                         lexer=pt.lexers.PygmentsLexer(TypeChooserLexer),
                         multiline=False,
                         key_bindings=bindings,
                         completer=completer)
    kwargs = {}
    if tp == "provision":
        kwargs = handle_provision_choice(out)
    elif tp == "clean":
        kwargs = handle_clean_choice(out)
    elif tp == "list":
        kwargs = handle_list_choice(out)
    else:
        print(pt.HTML("Unrecognized choice: [<b>{}</b>]".format(tp)))
    return create_dbmp_command(**kwargs)
Exemple #2
0
def print_header(tp, color):
    print(
        pt.HTML("<u><b>Please fill out the following <{}>{}</{}> attributes"
                "</b></u>".format(color, tp, color)))
    print(
        pt.HTML(
            "<u><i>Press <yellow>S-down</yellow> (Shift-&lt;down-arrow&gt;) "
            "when done</i></u>"))
    print()
Exemple #3
0
def get_rprompt(session: engine.Session):
    """
    Generuje podgląd gałęzi po prawej
    """
    DEF_PROMPT = "Miejsce na twój dowód".split()
    THRESHOLD = 128

    # Proof retrieval
    if session.proof:
        prompt, closed = session.getbranch_strings()
        color = COLORS.get(session.proof.branch, DEFAULT_COLOR)
    else:
        prompt = DEF_PROMPT
        closed = None
        color = DEFAULT_COLOR

    # Formatting
    to_show = []
    max_len = max((len(i) for i in prompt)) + 1
    for i in range(len(prompt)):
        spaces = max_len - len(prompt[i]) - int(log10(i + 1))
        to_show.append("".join((str(i + 1), ". ", prompt[i], " " * spaces)))

    # Adding branch closing symbol
    if closed:
        s = str(closed)
        spaces = max_len - len(s) + int(log10(i + 1)) + 3
        to_show.append(s + spaces * " ")

    # Foreground color calculating
    foreground = "#FFFFFF" if color.text_bright else "#000000"
    new = " \n ".join(to_show)
    return ptk.HTML(
        f'\n<style fg="{foreground}" bg="{color.rgb}"> {escape(new)} </style>')
Exemple #4
0
def handle_list_choice(out):
    args = []
    for choice in out.strip().split():
        choice_lower = choice.lower()
        if choice_lower in VOLS:
            args.append("volumes")
        elif choice_lower in VOLS_D:
            args.append("volumes-detail")
        elif choice_lower in TMPS:
            args.append("templates")
        elif choice_lower in TMPS_D:
            args.append("templates-detail")
        elif choice_lower in MOUNTS:
            args.append("mounts")
        elif choice_lower in ALERTS:
            args.append("alerts")
        elif choice_lower in EVENTS_U:
            args.append("events-user")
        elif choice_lower in EVENTS_S:
            args.append("events-system")
        # elif choice_lower in EVENTS_ID:
        #     args.append("events-id")
        elif choice_lower in PP:
            args.append("placement-policy")
        elif choice_lower in MP:
            args.append("media-policy")
        elif choice_lower in QUIT:
            app_exit(0)
        else:
            print(pt.HTML("Unrecognized choice: [<b>{}</b>]".format(choice)))
    return dict(list=args)
Exemple #5
0
def run() -> int:
    """
    Traktować to podobnie, jak `if __name__=="__main__"`. Funkcja uruchomiona powinna inicjalizować działające UI.
    Obiekt `main.Session` powinien być generowany dla każdego użytkownika. Wystarczy używać metod tego obiektu do interakcji z programem.

    :return: Exit code, -1 restartuje aplikację
    :rtype: int
    """
    session = engine.Session('main', 'config.json')
    ptk.print_formatted_text(
        ptk.HTML("\n".join(
            session.start_help() +
            ['Type ? to get command list; type [command]? to get help'])))
    console = ptk.PromptSession(
        message=lambda:
        f"{session.get_current_branch()+bool(session.get_current_branch())*' '}# ",
        rprompt=lambda: get_rprompt(session),
        complete_in_thread=True,
        complete_while_typing=True,
        completer=Autocomplete(session))
    while True:
        command = console.prompt().strip()
        logger.info(f"Got a command: {command}")
        if command == '':
            logger.debug("Command empty")
            continue
        try:
            to_perform = parser(command, command_dict)
        except ParsingError as e:
            ptk.print_formatted_text(e)
            logger.debug(f"ParingError: {e}")
            continue
        except TypeError as e:
            ptk.print_formatted_text(f"błąd: złe argumenty")
            logger.debug(f"Exception caught: {e}")
            continue

        for procedure in to_perform:
            performed = performer(procedure, session)
            if isinstance(performed, tp.Generator):
                for i in performed:
                    ptk.print_formatted_text(ptk.HTML(i))
            else:
                ptk.print_formatted_text(ptk.HTML(performed))
Exemple #6
0
def interactive(python):
    """ Main entrypoint into dbmp interactive mode """
    args = ''
    if not os.path.exists(HISTORY):
        io.open(HISTORY, 'w+').close()
    try:
        while True:
            pt.shortcuts.clear()
            pt.shortcuts.set_title("Datera Bare-Metal Provisioner")
            print("Welcome to the DBMP Interactive Session")
            print(
                pt.HTML("Would you like to <green>provison</green>, "
                        "or <red>clean</red> up or <blue>list</blue>?"))
            out = session.prompt(pt.HTML(
                "choices: [(<green>p</green>)rovision, "
                "(<red>c</red>)lean, "
                "(<blue>l</blue>)ist]> "),
                                 default="p",
                                 lexer=pt.lexers.PygmentsLexer(WelcomeLexer),
                                 style=dbmp_style,
                                 multiline=False,
                                 key_bindings=bindings,
                                 completer=dbmp_interactive_completer)
            out = out.strip().lower()
            print()
            if out in {"p", "provision"}:
                args = provision()
            if out in {"c", "clean"}:
                args = clean()
            if out in {"l", "list"}:
                args = dlist()
            if out in QUIT:
                if args:
                    print(args)
                app_exit(0)
            if not pt.shortcuts.confirm("Are you using multipath?"):
                args.append("--no-multipath")
            dbmp_exe(python, args)
    except KeyboardInterrupt:
        app_exit(1)
Exemple #7
0
def handle_provision_choice(out):
    volumes = []
    pp = []
    mp = []
    for choice in out.strip().split():
        if choice.lower() in VOLS:
            volumes.append(volume())
        elif choice.lower() in PP:
            pp.append(placement_policy())
        elif choice.lower() in MP:
            mp.append(media_policy())
        elif choice.lower() in QUIT:
            app_exit(0)
        else:
            print(pt.HTML("Unrecognized choice: [<b>{}</b>]".format(choice)))
    return dict(volumes=volumes, placement_policies=pp, media_policies=mp)
Exemple #8
0
def showCourseDetail(courseId: str):
    # print(courseId)
    cursor = connection.cursor()
    cursor.execute(
        """
        select uosName
        from unitofstudy
        where uosCode = %s
    """, (courseId, ))
    courseName, = cursor.fetchall()[0]

    cursor.execute(
        """
        select semester, year, grade
        from transcript
        where studId = %s and uosCode = %s
    """, (profile["id"], courseId))
    semester, year, grade = cursor.fetchall()[0]

    cursor.execute(
        """
        select uosoffering.enrollment, uosoffering.maxEnrollment, faculty.name
        from uosoffering, faculty
        where uosoffering.uosCode = %s and uosoffering.semester = %s and uosoffering.year = %s and uosoffering.instructorId = faculty.id
    """, (courseId, semester, year))
    enrollment, maxEnrollment, instructorName = cursor.fetchall()[0]

    cursor.close()

    answer = pt.shortcuts.message_dialog(title="%s: %s" %
                                         (courseId, courseName),
                                         text=pt.HTML("""
            <b>course id</b> %s \n
            <b>course name</b> %s \n
            <b>year</b> %d \n
            <b>semester</b> %s \n
            <b>enrollment</b> %d \n
            <b>max enrollment</b> %d \n
            <b>instructor name</b> %s \n
            <b>grade</b> %s
        """ % (courseId, courseName, year, semester, enrollment, maxEnrollment,
               instructorName, grade or "N/A")))
    return
Exemple #9
0
def _dprompt(tp, color, prompt, prompt_re):
    dprompt = prompt
    while True:
        pt.shortcuts.clear()
        print_header(tp, color)
        og_data = session.prompt("",
                                 default=dprompt,
                                 multiline=True,
                                 key_bindings=bindings,
                                 lexer=pt.lexers.PygmentsLexer(EditLexer),
                                 completer=dbmp_provision_completer)
        data = "\n".join(list(filter(bool, og_data.splitlines()))).strip()
        opts = {}
        fail = False
        for matcher in prompt_re:
            match = matcher.search(data)
            if not match:
                gi = matcher.groupindex.keys()[0]
                print(
                    pt.HTML(
                        "<red><b>Invalid data for {}</b></red>".format(gi)))
                dprompt = og_data

                session.prompt("Press Enter To Retry",
                               multiline=False,
                               key_bindings=bindings)
                fail = True
                break
            opts.update(match.groupdict())
        if fail:
            continue
        convert_opts(opts)
        print()
        print("-----------------------------")
        print("Recieved the following config")
        print("-----------------------------")
        print_dict(opts)
        print()
        if pt.shortcuts.confirm("Is this correct?"):
            return opts
        dprompt = og_data
Exemple #10
0
def get_toolbar():
    return ptk.HTML('This is a <b><style bg="ansired">Toolbar</style></b>!')
Exemple #11
0
def main():
    global root
    global folder
    def rerender(event):
        global folder
        event.app.current_buffer.set_document(
                pt.document.Document(text = makeDirText(folder)),
                    bypass_readonly = True)
    kb = pt.key_binding.KeyBindings()
    globalKb = pt.key_binding.KeyBindings()
    promptKb = pt.key_binding.KeyBindings()
    folder = root

    @globalKb.add('c-q')
    def exit(event):
        event.app.exit()

    @kb.add('c-m')
    def open(event):
        global folder
        line = event.app.current_buffer.document.current_line
        if line[0] == ' ':
            num = int(line[1:line.find('.')])
            if not num > len(folder.folders) + 1 and folder.folders != list():
                folder = folder.folders[num - 1]
                rerender(event)
            else:
                num -= len(folder.folders) + 2
                openFile(os.path.join(folder.dir, folder.files[num]))

    @kb.add('h')
    def home(event):
        global folder
        global root
        root.Scan()
        folder = root
        rerender(event)

    @kb.add('b')
    def back(event):
        global folder
        if not folder.parent == None:
            folder = folder.parent
            folder.Scan()
            rerender(event)

    @kb.add('m')
    def make(event):
        global folder
        MakeTemplate()
        folder.Scan()
        rerender(event)

    @kb.add('n')
    def new(event):
        global folder
        event.app.layout.focus(prompt)

    @promptKb.add('c-m')
    def AcceptNew(event):
        global folder
        name = event.app.current_buffer.document.current_line
        event.app.current_buffer.set_document(pt.document.Document())
        event.app.layout.focus(displayer)
        newPage(name)
        rerender(event)


    text = pt.document.Document(text = makeDirText(root))
    displayer = pt.buffer.Buffer(read_only = True, multiline = True, document = text)
    prompt = pt.buffer.Buffer(multiline = False)

    bottomText1 = pt.layout.controls.FormattedTextControl(
            text = pt.HTML('<ansigreen>c-q -> exit, enter -> open, h -> go to home dir, b -> go up a dir </ansigreen>'))
    bottomText2 = pt.layout.controls.FormattedTextControl(
            text = pt.HTML('<ansigreen>n -> new dir, m -> make new note file </ansigreen>'))
    aboveText1 = pt.layout.controls.FormattedTextControl(
            text = pt.HTML('<ansigreen>Python Note Manager v.2</ansigreen>'))

    root_container = pt.layout.containers.HSplit([
        pt.layout.containers.Window(content = aboveText1, height = 1),
        pt.layout.containers.Window(
            content = pt.layout.controls.BufferControl(displayer, key_bindings = kb)),
        pt.layout.containers.Window(
            content = pt.layout.controls.BufferControl(prompt, key_bindings = promptKb), height = 1),
        pt.layout.containers.Window(content = bottomText1, height = 1),
        pt.layout.containers.Window(content = bottomText2, height = 1)
        ])

    layout = pt.layout.Layout(root_container)
    app = pt.Application(key_bindings = globalKb, layout = layout, full_screen = True)
    app.run()
Exemple #12
0
def showProfile():
    while True:
        profile.update(getProfile(profile["id"]))  # get latest profile
        text = pt.HTML("""
            <b>student id</b> %s \n
            <b>name</b> %s \n
            <b>address</b> %s \n
            <b>password</b> %s \n
        """ % (profile["id"], profile["username"], profile["address"],
               profile["password"]))
        actions = pt.layout.HSplit([
            pt.widgets.Button("Change  address", lambda: handler("address"),
                              20),
            pt.widgets.Button("Change password", lambda: handler("password"),
                              20),
            pt.widgets.Button("Return", lambda: handler("return")),
        ])
        layout = pt.layout.VSplit([
            pt.widgets.Label(text),
            actions,
        ],
                                  padding=1)
        dialog = pt.shortcuts.dialogs.Dialog(title="Personal Details",
                                             body=layout,
                                             with_background=True)
        answer = pt.shortcuts.dialogs._run_dialog(dialog, None)

        if answer == "address":
            newAddress = pt.shortcuts.input_dialog(
                title="Change Address",
                text="New address",
                cancel_text='Cancel',
            )
            if newAddress == None:  # user pressed cancel
                pass  # do nothing
            else:
                cursor = connection.cursor(
                )  # implicit transaction, defined by PEP 249. See <https://www.python.org/dev/peps/pep-0249/#commit> and <https://stackoverflow.com/questions/52723251/mysql-connector-python-how-to-use-the-start-transaction-method>
                cursor.execute(
                    """
                    update student
                    set address = %s
                    where id = %s
                """, (newAddress, profile["id"]))
                connection.commit()  # commit transaction
                cursor.close()
        elif answer == "password":
            newPassword = pt.shortcuts.input_dialog(
                title="Change Password",
                text="New password",
                cancel_text='Cancel',
            )
            if newPassword == None:  # user pressed cancel
                pass  # do nothing
            else:
                if newPassword == "":  # password is empty
                    pt.shortcuts.message_dialog(
                        title="New Password Failed",
                        text="Password should not be empty!",
                        style=pt.styles.Style.from_dict(
                            {"dialog": "bg:#ff0000"}),
                    )  # give a warning
                else:  # password is not empty
                    cursor = connection.cursor()
                    cursor.execute(
                        """
                        update student
                        set password = %s
                        where id = %s
                    """, (newPassword, profile["id"]))
                    connection.commit()  # commit transaction
                    cursor.close()
        else:  # user pressed return
            return