Esempio n. 1
0
    def show_create_post_select_page(self):
        questions = [
            {
                'type': 'list',
                'name': 'action',
                'message': 'select a topic to post to:',
                'choices': []
            }
        ]        

        for group in self.provider.show_groups():
            questions[0]['choices'].append({'name': '-' + group.groupname, 'value': group.gid})
        
        questions[0]['choices'].append('exit')
        questions[0]['choices'].append('back')

        answers = prompt(questions)
        action = answers['action']

        if action == 'exit':
            self.state = ExitState()
        elif action == 'back':
            self.state = GroupsState()
        else:
            gid = action    
            
            questions = [{'type': 'input','name': 'msg','message': 'message:'}]
            answers = prompt(questions)
            msg = answers['msg']

            self.state = self.state.on_event(self.provider, gid, msg)
Esempio n. 2
0
def run():
    if len(sys.argv) <= 1:
        show_help()
    else:
        command = sys.argv[1].lower()
        if command == "courses":
            print_courses()
        elif command == "setup":
            setup()
        elif command == "download":
            course_ids = get_course_choices("Select courses to download")
            if 3 <= len(sys.argv):
                output_dir = os.path.expanduser(sys.argv[2])
            else:
                output_dir = os.getcwd()
            for course_id in course_ids:
                download_files(course_id, output_dir)
        elif command == "sync":
            config = get_config()
            sync(config)
        elif command == "config":
            verify = [{
                "type":
                "rawlist",
                "message":
                "Select which variables you want to change",
                "name":
                "verification",
                "choices":
                ["Download directory", "Selected courses", "Both", "Exit"]
            }]

            answer = prompt(verify)["verification"]

            if answer == "Exit":
                exit()
            if answer == "Download directory" or answer == "Both":
                directory_question = [({
                    "type": "input",
                    "message":
                    "Enter your preferred download directory. Leave empty to reset.",
                    "name": "directory"
                })]

                directory_answer = prompt(directory_question)
                output_directory = directory_answer["directory"]
                if output_directory == "":
                    output_directory = "~/UforaFileFetcher"

                write_to_config("output_directory", output_directory)

            if answer == "Selected courses" or answer == "Both":
                course_ids = get_course_choices(
                    "Select courses to add to config")
                write_to_config("courses", course_ids)

            print(answer)

        else:
            show_help()
Esempio n. 3
0
def resolve(*, hgclient, bzapi, patch: Patch, validator: Validator):
  repo = hgclient.paths(name=b'default').decode(encoding='UTF-8').split('@')[1]

  bugdata = bzapi.getbug(patch.bug)

  bug_status_check(bugdata=bugdata, patch=patch, validator=validator)

  if patch.type == "backout":
    comment = f"Backed out for {patch.reason}\n"
  else:
    comment = f"https://{repo}rev/{patch.hash.decode(encoding='UTF-8')}\n"

    if hgclient.outgoing(revrange=patch.hash):
      validator.fatal(f"Patch {patch} doesn't appear to have landed.")

  version = get_version(hgclient, rev=patch.hash, validator=validator)
  info(f"Patch {patch} is against {version.component} {version.number}")

  info(f"Adding comment to bug {patch.bug}:")

  if patch.type == 'patch':
    log(comment)

    update = None
    if "leave-open" in bugdata.keywords:
      answers = prompt([{'type': 'confirm', 'message': 'Submit this comment and leave the bug open?',
                        'name': 'leaveopen'}])
      if answers['leaveopen']:
        update = bzapi.build_update(comment=comment,
                                    target_milestone=version.number,
                                    keywords_remove="checkin-needed")

    else:
      answers = prompt([{'type': 'confirm', 'message': 'Submit this comment and resolve the bug?',
                        'name': 'resolve'}])
      if answers['resolve']:
        update = bzapi.build_update(comment=comment, status="RESOLVED",
                                    resolution="FIXED",
                                    target_milestone=version.number,
                                    keywords_remove="checkin-needed")
    #breakpoint()
    if update is not None:
      bzapi.update_bugs([patch.bug], update)
      info(f"Updated {bugdata.weburl}")

  elif patch.type == 'backout':
    log(comment)
    answers = prompt([{'type': 'confirm', 'message': 'Submit this comment and reopen the bug?',
                      'name': 'resolve'}])
    if answers['resolve']:
      update = bzapi.build_update(comment=comment, status="REOPENED",
                                  resolution="---",
                                  target_milestone="---")
      #breakpoint()
      bzapi.update_bugs([patch.bug], update)
      info(f"Reopened {bugdata.weburl}")

  else:
    validator.fatal(f"Unknown patch type: {patch.type}")
Esempio n. 4
0
def chapterSelection():
    """
    :returns array os strings pointing to chapters to be composed
    """

    manga_dir = Manga.directory

    mangas = list(manga_dir.iterdir())
    if len(mangas) <= 0:
        return Path, []

    # manga selection
    manga_options = {
        'type': 'list',
        'name': 'manga',
        'message': 'Pick manga',
        'choices':
        alphabetic_prompt_list(map(lambda path: path.parts[-1], mangas)),
        'filter': lambda val: mangas[mangas.index(Manga.directory / Path(val))]
    }

    manga: Path = Path()
    try:
        manga = prompt(manga_options)['manga']
        manga = Path(manga)
    except KeyError as e:
        print(e)
        return Path, []

    # select chapters
    chapter_option = {
        'type':
        'checkbox',
        'name':
        'chapters',
        'message':
        'Select chapters to compose',
        'choices':
        sorted([{
            'name': i.parts[-1]
        } for i in manga.iterdir() if not is_folder_static(i.parts[-1])],
               key=lambda val: numerical_sort(val['name'])),
    }

    # if no chapters
    if len(chapter_option['choices']) <= 0:
        return manga, []

    try:
        chapters = prompt(chapter_option)['chapters']
        chapters = map(lambda path: manga / Path(path), chapters)
    except KeyError as e:
        print(e)
        return manga, []

    return manga, list(chapters)
Esempio n. 5
0
    def groups_page(self):
        groups = self.provider.show_groups()
        print("Welcome {} \n \nTopics you are currently part of :".format(self.provider.username))
        for group in groups:
            print( '-' + group.groupname)
        print()
        questions = [
            {
                'type': 'list',
                'name': 'action',
                'message': 'What do you want to do?',
                'choices': 
                [
                    'create a post',
                    'view posts from topics you follow',
                    'view posts from users you follow\n',
                    'follow a new topic',
                    'create a topic\n',
                    'view users you are following',
                    'follow a new user',
                    'stop following a user\n',
                    'exit'
                ]
            }
        ]

        answers = prompt(questions)  
        action = answers['action']

        self.state = self.state.on_event(self.provider, action)
Esempio n. 6
0
def run_action_release_manager():

    all_releases = {
        raiden.release: raiden
        for raiden in RAIDEN_CLIENT_DEFAULT_CLASS.get_available_releases()
    }

    release_selection = prompt({
        "name":
        "releases",
        "type":
        "checkbox",
        "message":
        Messages.input_release_manager,
        "choices": [{
            "name": raiden.version,
            "value": raiden,
            "checked": raiden.is_installed
        } for raiden in all_releases.values()],
    })

    to_install = [release for release in release_selection["releases"]]

    for raiden in all_releases.values():
        if raiden.is_installed and raiden.version not in to_install:
            print(f"Uninstalling {raiden.version}")
            raiden.uninstall()
            continue

        if not raiden.is_installed and raiden.version in to_install:
            print(f"Installing {raiden.version}. This might take some time...")
            raiden.install()
            continue

    return main_prompt()
Esempio n. 7
0
def encounter2b():
    prompt(
        {
            'type':
            'list',
            'name':
            'weapon',
            'message':
            'Pick one',
            'choices': [
                'Use the stick', 'Grab a large rock',
                'Try and make a run for it', 'Attack the wolf unarmed'
            ]
        },
        style=style)
    print('The wolf mauls you. You die. The end.')
Esempio n. 8
0
    def show_friends_posts_page(self):
        print("Here all the posts from users you follow\n")

        posts = self.provider.show_friends_posts()

        questions = [
            {
                'type': 'list',
                'name': 'action',
                'message': 'select a post to see likes/comments:',
                'choices': []
            }
        ]

        questions[0]['choices'].append('exit\n')
        questions[0]['choices'].append('back\n')

        for post in posts:
            message ='topic:  ' + post.groupname + '\n   time:  ' + post.timestamp.strftime('%H:%M %b %d %Y') + '\n   user:  '******'\n   ' + self.provider.replace_special_characters(post.msg) + '\n   likes: ' + str(post.likes) + '\n'
            questions[0]['choices'].append({'name': message, 'value': post.pid + ' ' + str(post.gid)})

        if(len(posts) < 1):
            print("there are no posts here. try following more people.")

        answers = prompt(questions)
        self.state = self.state.on_event(answers['action'])
Esempio n. 9
0
    def prompt(self):
        # choose a manga
        manga_title = self._menu.prompt()

        if manga_title == 'Exit':
            return

        # construct new checbox menu for this
        checkbox_choices = [{
            'name': chapter.title
        } for chapter in self.informative[manga_title]]
        selected_names = prompt(
            dict(type='checkbox',
                 name='updates',
                 message=manga_title,
                 choices=checkbox_choices))['updates']

        # nothing selected
        if not selected_names:
            return

        selected = list(
            filter(lambda chapter: chapter.title in selected_names,
                   self.informative[manga_title]))
        manga = list(
            filter(
                lambda key: self.updates[key] == self.informative[manga_title],
                self.updates.keys()))[0]

        with Loader("Parse Info"):
            manga, all_chapters = manga.parse()

        from modules.database.models.manga.download import selective_download
        selective_download(manga, all_chapters, selected, update=True)
Esempio n. 10
0
def __verify_if_session_file_exists(data_filenames, username, question_overwrite):
    if username in data_filenames:
        answer_overwrite = prompt(question_overwrite, style=menu_style)
        if answer_overwrite['overwrite_data']:
            __delete_session_data(str(user_data_folder_path + '/' + username))
        else:
            session_manager()
Esempio n. 11
0
def run_action_release_manager():

    release_selection = prompt({
        "name":
        "releases",
        "type":
        "checkbox",
        "message":
        Messages.input_release_manager,
        "choices": [{
            "name": raiden.version,
            "value": raiden,
            "checked": raiden.is_installed
        } for raiden in RELEASE_MAP.values()],
    })

    to_install = [release for release in release_selection["releases"]]

    for raiden in RELEASE_MAP.values():
        if raiden.is_installed and raiden.version not in to_install:
            print(f"Uninstalling {raiden.version}")
            raiden.uninstall()
            continue

        if not raiden.is_installed and raiden.version in to_install:
            print(f"Installing {raiden.version}. This might take some time...")
            raiden.install()
            continue

    return main_prompt()
Esempio n. 12
0
def websocketSettingsMenu(logger):
    menu = [
        {
            'type': 'input',
            'name': 'websocketPort',
            'message': 'Enter a Websocket-Port [5050]: ',
            'default': str(logger.config['websocket']['port'])
        },
        {
            'type': 'password',
            'name': 'websocketpassword',
            'message':
            'Enter a Websocket-Password (leave blank for unsecured Websocket): ',
            'default': str(logger.config['websocket']['password'])
        },
        {
            'type': 'confirm',
            'name': 'websocketserver',
            'message': 'Enable the Websocket-Server? ',
            'default': str(logger.config['websocket']['active'])
        },
    ]

    main = prompt(menu, style=style)
    logger.config['websocket']['active'] = bool(main['websocketserver'])
    logger.config['websocket']['port'] = int(main['websocketPort'])
    logger.config['websocket']['password'] = str(main['websocketpassword'])
    logger.save_config()
Esempio n. 13
0
def prompt_for_project(ctx, entity):
    """Ask the user for a project, creating one if necessary."""
    result = ctx.invoke(projects, entity=entity, display=False)

    try:
        if len(result) == 0:
            project = click.prompt("Enter a name for your first project")
            #description = editor()
            project = api.upsert_project(project, entity=entity)["name"]
        else:
            project_names = [project["name"] for project in result]
            question = {
                'type': 'list',
                'name': 'project_name',
                'message': "Which project should we use?",
                'choices': project_names + ["Create New"]
            }
            project = whaaaaat.prompt([question])['project_name']

            # TODO: check with the server if the project exists
            if project == "Create New":
                project = click.prompt("Enter a name for your new project",
                                       value_proc=api.format_project)
                #description = editor()
                project = api.upsert_project(project, entity=entity)["name"]

    except wandb.api.CommError as e:
        raise ClickException(str(e))

    return project
Esempio n. 14
0
def select(choices):
    cache = {}
    c = []
    for i in choices:
        x = Choice(
            authors=i['authors'],
            journal=i['journal'],
            title=i['title'],
            filename=i['filename'],
            dbname=i['dbname'],
        )
        choice = {"name": "{}".format(x)}
        cache['{}!{}!1!0'.format(i['filename'], i['dbname'])] = x
        c.append(choice)
    questions = [{
        'type': 'checkbox',
        'name': 'documents',
        'choices': c,
        'message': 'Please select documents you want to export',
    }]
    answers = prompt(questions)
    result = []
    for i in answers["documents"]:
        result.append(cache[i.split("[")[1].split("]")[0]])
    return result
Esempio n. 15
0
def setup():
    parser = argparse.ArgumentParser()
    parser.add_argument("setup")
    parser.add_argument("--username")
    parser.add_argument("--password")
    args = parser.parse_args()
    username = args.username
    password = args.password
    questions = []
    if not username:
        questions.append({
            "type": "input",
            "message": "Enter your Ufora username",
            "name": "username"
        })
    if not password:
        questions.append({
            "type": "password",
            "message": "Enter your Ufora password",
            "name": "password"
        })

        answers = prompt(questions)

        username = answers["username"]
        password = answers["password"]
    session = get_session(username, password)
    if session is None:
        print("Invalid login credentials")
        return
    with open("credentials.json", "w+") as f:
        f.write(json.dumps({"username": username, "password": password}))
    print("Setup complete!")
Esempio n. 16
0
def main():
    ports = []
    actions = [{
        'type': 'list',
        'name': MAIN_ACTION,
        'message': '¿Qué deseas hacer?',
        'choices': [
            ADD_NODE,
            MINE,
            'Cerrar'
        ],
    }]

    keep_open = True
    while keep_open:
        answer = None
        while not answer:
            os.system('cls' if os.name == 'nt' else 'clear')
            answer = prompt(actions).get(MAIN_ACTION)

        if answer == ADD_NODE:
            port, prob = add_node()
            ports.append((port, prob))
        elif answer == MINE:
            mine(ports)
        else:
            keep_open = False
Esempio n. 17
0
def inspectDevicesMenu(logger):
    main = ""
    while not main == 'Back':
        devices = logger.devicenames.keys()
        states = []
        for dev in devices:
            states.append(logger.pluginStatus[dev])

        devicetexts = []
        for idx, dev in enumerate(devices):
            stat = states[idx]
            if stat:
                stat = ": Running"
            else:
                stat = ": Stopped"
            devicetexts.append(dev + stat)
        devicetexts.append('Back')
        menu = [{
            'type': 'list',
            'name': 'menu',
            'message': 'Select a device',
            'choices': devicetexts
        }]
        main = prompt(menu, style=style)
        main = main['menu']
        if not main == 'Back':
            inspectDeviceMenu(main, logger)
    return main
Esempio n. 18
0
    def choose_rigging(rigging=None):
        choices = []
        for c_rigging in rigging:
            rigging_name = c_rigging.get("rigging_name")
            platform = c_rigging.get("platform")
            choices.append("[R] %-15s [P] %-s" % (rigging_name, platform))

        questions = [
            {
                'type': 'list',
                'name': 'rigging_choice',
                'message': 'Which rigging would you like to choose?',
                'choices': choices
            }
        ]
        style = style_from_dict({
            Token.Selected: '#00FFFF bold',
        })
        answers = prompt(questions, style=style)
        choice = answers.get('rigging_choice')

        for c_rigging in rigging:
            rigging_name = c_rigging.get("rigging_name")
            platform = c_rigging.get("platform")
            if choice == "[R] %-15s [P] %-s" % (rigging_name, platform):
                return c_rigging
        return None
Esempio n. 19
0
 def execute(self, *args, **kwargs):
     questions = [{
         'type': 'input',
         'name': 'image_with_tag',
         'message': 'What\'s your image repo ',
     }]
     answers = prompt(questions)
     return answers
Esempio n. 20
0
def prompt(question):
    input_type = (not ('input_type' in question)) or question.pop('input_type')

    answers = whaaaaat.prompt(question)
    if input_type == 'integer' and not answers['value'].isdigit():
        question['input_type'] = input_type
        return prompt(question)
    return answers['value']
Esempio n. 21
0
 def login_page(self):
     questions = [{'type': 'input','name': 'username','message': 'username:'******'type': 'password', 'name': 'password', 'message': 'password:'******'username']
     password = answers['password']
     
     self.state = self.state.on_event(self.provider, username, password)       
Esempio n. 22
0
 def __prompt_continue(self):
     to_continue = [{
         'type': 'confirm',
         'name': 'continue',
         'message': "Continue categorizing?",
         'default': False
     }]
     return prompt(to_continue)["continue"]
Esempio n. 23
0
 def __verify_if_session_file_exists(self):
     if self.username in self.data_filenames:
         answer_overwrite = prompt(self.question_overwrite,
                                   style=menu_style)
         if answer_overwrite['overwrite_data']:
             self.__delete_session_data(user_data_folder_path /
                                        self.username)
         return answer_overwrite['overwrite_data']
     return True
Esempio n. 24
0
def ask_direction():
    directions_prompt = {
        'type': 'list',
        'name': 'direction',
        'message': 'Which direction would you like to go?',
        'choices': ['Forward', 'Right', 'Left', 'Back']
    }
    answers = prompt(directions_prompt)
    return answers['direction']
Esempio n. 25
0
def confirm(message, default=False):
    question = [{
        'type': 'confirm',
        'name': 'answer',
        'message': message,
        'default': default
    }]
    answer = prompt(question)["answer"]
    return answer
Esempio n. 26
0
def main():
    questions = [{
        'type': 'input',
        'name': 'first_name',
        'message': 'What\'s your first name'
    }]

    answers = prompt(questions)
    print_json(answers)
Esempio n. 27
0
def process_patches(*, hgclient, bzapi, revrange: str, patches: list,
                    validator: Validator):
  bug = None

  version = get_version(hgclient, rev=revrange, validator=validator)
  info(f"Patchset {revrange} is against {version.component} {version.number}")

  if len(patches) != 1:
    raise Exception("One at a time right now")

  for patch in patches:
    if patch.type is 'tag':
      continue

    if bug is None:
      bug = patch.bug
    elif bug != patch.bug:
      validator.fatal(f"Multiple bugs in one revrange: {bug}, {patch.bug}")

    bugdata = bzapi.getbug(patch.bug)

    info(bugdata.__str__())
    log(f"Component: {bugdata.component}")
    log(bugdata.weburl)
    log(bugdata.status)
    log(bugdata.type)
    log(f"Version: {bugdata.version}")
    log(f"Target: {bugdata.target_milestone}")

    if bugdata.component != version.component and bugdata.product != version.component:
      validator.fatal(f"Bug component mismatch. Bug is for {bugdata.product}::{bugdata.component}, but we're in {version.component}")

    if bugdata.target_milestone != version.number:
      validator.warn(f"Bug target milestone ({bugdata.target_milestone}) is not set to {version.number}")

    bug_status_check(bugdata=bugdata, patch=patch, validator=validator)

    answers = prompt([{'type': 'confirm', 'message': 'Push and resolve bug?', 'name': 'push'}])
    if answers['push']:
      log("Now run:")
      info(f"  hg push -r {revrange}")

      if prompt([{'type': 'confirm', 'message': 'Was your push successful?', 'name': 'push'}])['push']:
        resolve(hgclient=hgclient, bzapi=bzapi, patch=patch, validator=validator)
Esempio n. 28
0
def validate_prompt(questions, error_message=None):
    is_validated = False
    while not is_validated:
        try:
            answers = prompt(questions)
            is_validated = True
        except (ValidationError, TypeError):
            msg = error_message or "Error validating provided information, try again."
            print(msg)
    return answers
Esempio n. 29
0
def session_manager():
    __create_user_data_folder()
    data_filenames = __get_user_data_filenames()
    questions_menu, question_overwrite = __prepare_questions(data_filenames)
    answers_menu = prompt(questions_menu, style=menu_style)
    try:
        username, save_session = __verify_answers(answers_menu, data_filenames, question_overwrite)
    except KeyError:
        exit()
    return username, save_session
Esempio n. 30
0
    def warn(self, message):
        self.warnings.append(message)

        print(Fore.YELLOW + "[WARN] " + message)
        if self.ask:
            answers = prompt([{
                "type": "confirm",
                "message": "Proceed anyway?",
                "name": "okay"
            }])
            if not answers["okay"]:
                exit()
Esempio n. 31
0
 def execute(self, *args, **kwargs):
     try:
         questions = [
             {
                 'type': 'input',
                 'name': 'image_with_tag',
                 'message': 'What\'s your image repo ',
             }
         ]
         answers = prompt(questions)
     except Exception as e:
         Logger.warn("Failed to detect image repo. Windows console don't support prompt action.")
         Logger.warn("Jenkinsfile and docker-compose.yml may not be generated completely.")
         answers = {"image_with_tag": "[IMAGE_WITH_TAG]"}
     return answers
Esempio n. 32
0
def create_config(config_path, new_config=None):
    logger.debug("default_config: {}".format(new_config))

    if not new_config:
        new_config = default_config

    for section, questions in config_questions.items():
        if not new_config.get(section):
            new_config[section] = prompt(questions)

    logger.debug("Creating Config => {}".format(new_config))

    config = cfgcaddy.config.LinkerConfig(
        config_file_path=config_path, default_config=new_config)
    config.write_config()
    return config
Esempio n. 33
0
def user_confirm(question, default=True):
    """Ask the user to confirm a choice

    Args:
        question (string): a string that is presented to the user.
        default (string): the answer if the user just hits <Enter>.
            It must be True, False or None (meaning
            an answer is required of the user).

    Returns "answer" return value is True for "yes" or False for "no".
    """
    return prompt([{
        "type": "confirm",
        "name": "ok",
        "message": question,
        "default": default
    }]).get("ok")