Esempio n. 1
0
def list_networks(args, nama=None):
    '''List Network'''
    auth = identity.Password(auth_url=auth_url,
                             username=username,
                             password=password,
                             project_name=project_name,
                             project_domain_name=project_domain_name,
                             user_domain_name=user_domain_name)
    sess = session.Session(auth=auth)
    neutron = nwclient.Client(session=sess)
    if nama is None:
        '''JIka nama tidak dimasukkan'''
        ui.info_section(f'== List Network == \n')
        list = neutron.list_networks()
        for list in neutron.list_networks()['networks']:
            print(list['name'])
        # coba = json.dumps(list, sort_keys=True, indent=2)
        # print(coba)
    else:
        '''menampilkan satu list nama'''
        try:
            ui.info_section(f'== Detail Network {nama}== \n')
            neutron = nwclient.Client(session=sess)
            list = neutron.list_networks(name=nama)

            coba = json.dumps(list, sort_keys=True, indent=2)
            print(coba)
        except Exception as e:
            '''jika tidak ada nama'''
            ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
Esempio n. 2
0
def update_project(args, name, nameedit, description=None):
    '''update projects'''
    if description is None:
        try:
            cek = (f'{ks.projects.list(name=name)[0]}')
            baca = cek.strip().split(',')
            result = [i for i in baca if i.startswith(' id')]
            oke = result[0]
            id_project = oke.strip().strip('id=')
            update = ks.projects.update(
                project=id_project, name=nameedit)
            ui.info_3(update, '\n')
            ui.info_3('\n Done ', ui.check)
        except Exception as e:
            '''jika tidak ada nama'''
            ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
    else:
        try:
            cek = (f'{ks.projects.list(name=name)[0]}')
            baca = cek.strip().split(',')
            result = [i for i in baca if i.startswith(' id')]
            oke = result[0]
            id_project = oke.strip().strip('id=')
            update = ks.projects.update(
                project=id_project, name=nameedit, description=description)
            ui.info_3(update, '\n')
            ui.info_3('\n Done ', ui.check)
        except Exception as e:
            '''jika tidak ada nama'''
            ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
Esempio n. 3
0
 def exit_handler(_s, _h):
     """Description: Handle exiting the application."""
     ui.info(ui.yellow, "Exiting..")
     subprocess_net.terminate()
     for i in MATCH_SUBPROCESS:
         i.terminate()
     exit(0)
Esempio n. 4
0
def init():
    """Description: Starts up the application normally by asking the user about
    the server they want to connect to"""
    if ui.ask_yes_no(constants.Strings.server_prompt.value):
        domain = ui.ask_string(constants.Strings.server_ip.value)
        if domain is None:
            ui.fatal(constants.Exceptions.invalid_ip.value)
    else:
        domain = "play.pommerman.com:5050"
    ui.info(
        constants.Strings.server_connecting_p1.value,
        ui.yellow,
        constants.Strings.server_connecting_p2.value,
        ui.reset,
        constants.Strings.server_connecting_p3.value,
    )
    network = Network(domain)
    try:
        status = network.server_status()
    except Exception as e:
        ui.fatal(e)
    signal.signal(signal.SIGINT, _exit_handler)
    ui.info(
        constants.Strings.server_connected.value,
        ui.yellow,
        constants.Strings.server_players.value,
        str(status[0]) + ",",
        constants.Strings.server_matches.value,
        status[1],
    )
    intent(network)
Esempio n. 5
0
def _exit_handler(_s=None, _h=None):
    """Arguments:  
    * _s: Unused argument  
    * _h: Unused argument  
    Description: Handle exiting the application"""
    ui.info(ui.yellow, "Exiting..")
    exit(0)
Esempio n. 6
0
def revoke_role(args, role, user, project):
    '''mencabut role'''
    try:
        '''revoke roles'''
        cek = (f'{ks.roles.list(name=role)[0]}')
        baca = cek.strip().split(',')
        result = [i for i in baca if i.startswith(' id')]
        oke = result[0]
        id_roles = oke.strip().strip('id=')

        cek1 = (f'{ks.projects.list(name=project)[0]}')
        baca1 = cek1.strip().split(',')
        result1 = [i for i in baca1 if i.startswith(' id')]
        oke1 = result1[0]
        id_project = oke1.strip().strip('id=')

        cek2 = (f'{ks.users.list(name=user)[0]}')
        baca2 = cek2.strip().split(',')
        result2 = [i for i in baca2 if i.startswith(' id')]
        oke2 = result2[0]
        id_user = oke2.strip().strip('id=')

        cabut = ks.roles.revoke(
            role=id_roles, user=id_user, project=id_project)
        ui.info_3('revoke role success', ui.check)
        ui.info_3(cabut, '\n')
        ui.info_3('Done ', ui.check)
    except Exception as e:
        '''jika tidak ada nama'''
        ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
Esempio n. 7
0
def grant_role2(args, role, user, project):
    '''grant role berdasarkan nama'''
    '''ex : python test.py grant_role2 roleirvan irvan irvan3'''
    ui.info_section(f'== Grant Role == \n')
    try:
        # mendapatkan id role dr nama
        cek = (f'{ks.roles.list(name=role)[0]}')
        baca = cek.strip().split(',')
        result = [i for i in baca if i.startswith(' id')]
        oke = result[0]
        id_role = oke.strip().strip('id=')

        # mendapatkan id user dr nama
        cek2 = (f'{ks.users.list(name=user)[0]}')
        baca2 = cek2.strip().split(',')
        result2 = [i for i in baca2 if i.startswith(' id')]
        oke2 = result2[0]
        id_user = oke2.strip().strip('id=')

        # mendapaktan id project dr nama
        cek3 = (f'{ks.projects.list(name=project)[0]}')
        baca3 = cek3.strip().split(',')
        result3 = [i for i in baca3 if i.startswith(' id')]
        oke3 = result3[0]
        id_project = oke3.strip().strip('id=')

        ex = ks.roles.grant(role=id_role,
                            user=id_user,
                            system=None,
                            project=id_project)
        ui.info_3(ex)
        ui.info_3('\n Done ', ui.check)
    except Exception as e:
        '''jika tidak ada nama'''
        ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
Esempio n. 8
0
def collect_statuses(workspace):
    errors = list()
    result = list()
    repos = workspace.get_repos()

    if not repos:
        return errors, result

    num_repos = len(repos)
    max_len = max((len(x.src) for x in repos))
    for i, repo, full_path in workspace.enumerate_repos():
        ui.info_count(i, num_repos,
                      "Checking", repo.src.ljust(max_len + 1), end="\r")
        try:
            branch = tsrc.git.get_current_branch(full_path)
        except tsrc.git.GitError as e:
            errors.append((repo.src, e))
            continue

        dirty = tsrc.git.is_dirty(full_path)

        result.append(Status(src=repo.src, branch=branch, dirty=dirty))

    ui.info("")
    return result, errors
Esempio n. 9
0
def target_factory(targets, api_keys):
    target_objs = []
    domains = []
    ui.info_section("\n", ui.darkteal, "Lookup Status")
    for t in targets:
        ui.info_progress("=>> {}".format(t),
                         len(target_objs) + 1, len(targets))
        if t.split("@")[1] not in domains:
            domains.append(
                t.split("@")[1])  # todo remove redundant shodan calls
        current_target = Target(t)
        # Shodan
        if len(current_target.ip) != 0:
            current_target.get_shodan(api_keys['DEFAULT']['shodan'])
        # HaveIBeenPwned
        current_target.get_hibp()
        # WeLeakInfo Public API
        # current_target.get_weleakinfo_public()  # Currently offline
        # Hunter.io Public + Private API
        current_target.get_hunterio_public()
        if len(api_keys['DEFAULT']['hunterio']) != 0:
            current_target.get_hunterio_private(
                (api_keys['DEFAULT']['hunterio']))

        # Snusbase API
        if len(api_keys['DEFAULT']['snusbase_token']) != 0:
            current_target.get_snusbase(api_keys['DEFAULT']['snusbase_url'],
                                        api_keys['DEFAULT']['snusbase_token'])
        ui.dot(last=True)

        target_objs.append(current_target)
    ui.info("\n")
    return target_objs
Esempio n. 10
0
def main(args):
    tsrc_distribution = pkg_resources.get_distribution("tsrc")
    # pylint: disable=no-member
    version = tsrc_distribution.version
    message = "tsrc version %s" % version
    location = path.Path(tsrc_distribution.location)
    message += get_details(location)
    ui.info(message)
Esempio n. 11
0
def display_statuses(statuses):
    if not statuses:
        return
    max_src = max((len(x[0]) for x in statuses))
    for src, status in statuses:
        message = [ui.green, "*", ui.reset, src.ljust(max_src)]
        message += describe(status)
        ui.info(*message)
Esempio n. 12
0
def payment():
    print('* On your mark...')
    while True:
        items = {}

        # parse items
        for item in ui.question("Input items").split("+"):
            its = item.split("*")
            items[its[0]] = int(its[1]) if len(its) == 2 else 1

        item_keys = items.keys()
        itemdata = find_items_by_id(item_keys)

        if (len(item_keys) is not len(itemdata)):
            ui.warn(
                'something went wrong, there are no items that has some IDs. please re-input.'
            )
            continue

        ui.info('\n'.join([
            "'{}' (¥{}) x{}".format(item.name, item.price, items[str(item.id)])
            for item in itemdata
        ]))

        if ui.isok("Is correct?"):
            break

    tran_id = start_transaction()
    ui.info("start transaction (tran_id: {})".format(tran_id))

    tran_item_ids = []
    for k, v in items.items():
        tran_item_ids += [k] * v

    add_items_to_transaction(tran_id, tran_item_ids)

    amount = get_amount_of_transaction(tran_id)
    ui.info("Amount: ¥{}".format(amount))

    while True:
        receipt = int(ui.question("Receipt?"))

        change = receipt - amount

        if (0 > change):
            ui.warn(
                'change is minus or not number, re-input or request re-payment.'
            )
            continue

        ui.info("Change: ¥{}".format(change))

        if ui.isok("receipt amount and give change?"):
            break

    end_transaction(tran_id, amount, receipt, change)

    ui.info('end transaction (tran_id: {})'.format(tran_id))
Esempio n. 13
0
def main(args):
    workspace = tsrc.cli.get_workspace(args)
    workspace.update_manifest()
    workspace.load_manifest()
    workspace.clone_missing()
    workspace.set_remotes()
    workspace.sync()
    workspace.copy_files()
    ui.info("Done", ui.check)
Esempio n. 14
0
def main():
    # coloring:
    ui.info("This is", ui.red, "red", ui.reset, "and this is", ui.bold, "bold")
    ui.info(ui.check)

    # enumerating:
    list_of_things = ["foo", "bar", "baz"]
    for i, thing in enumerate(list_of_things):
        ui.info_count(i, len(list_of_things), thing)
Esempio n. 15
0
 def process(self, repo):
     ui.info(repo.src, "\n",
             ui.lightgray, "$ ",
             ui.reset, ui.bold, self.cmd_as_str,
             sep="")
     full_path = self.workspace.joinpath(repo.src)
     rc = subprocess.call(self.cmd, cwd=full_path, shell=self.shell)
     if rc != 0:
         raise CommandFailed()
Esempio n. 16
0
 def handle_errors(self):
     ui.error(self.task.description(), "failed")
     for item, error in self.errors:
         item_desc = self.task.display_item(item)
         message = [ui.green, "*", " ", ui.reset, ui.bold, item_desc]
         if error.message:
             message.extend([ui.reset, ": ", error.message])
         ui.info(*message, sep="")
     raise ExecutorFailed()
Esempio n. 17
0
def main(args):
    workspace = tsrc.cli.get_workspace(args)
    workspace.load_manifest()
    cmd_runner = CmdRunner(workspace,
                           args.cmd,
                           args.cmd_as_str,
                           shell=args.shell)
    tsrc.executor.run_sequence(workspace.manifest.repos, cmd_runner)
    ui.info("OK", ui.check)
Esempio n. 18
0
    def process(self, repo):
        ui.info(repo.src)
        repo_path = self.workspace.joinpath(repo.src)
        self.check_branch(repo, repo_path)
        self.fetch(repo_path)

        if repo.fixed_ref:
            self.sync_repo_to_ref(repo_path, repo.fixed_ref)
        else:
            self.sync_repo_to_branch(repo_path)
Esempio n. 19
0
 def accept_merge_request(self, merge_request):
     project_id = merge_request["project_id"]
     merge_request_iid = merge_request["iid"]
     ui.info_2("Merging when build succeeds", ui.ellipsis, end="")
     url = "/projects/%s/merge_requests/%s/merge" % (project_id, merge_request_iid)
     data = {
         "merge_when_pipeline_succeeds": True,
     }
     self.make_request("PUT", url, data=data)
     ui.info("done", ui.check)
Esempio n. 20
0
def main(args):
    workspace_path = args.workspace_path or os.getcwd()
    workspace = tsrc.workspace.Workspace(path.Path(workspace_path))
    ui.info_1("Creating new workspace in", ui.bold, workspace_path)
    workspace.init_manifest(args.manifest_url, branch=args.branch)
    workspace.load_manifest()
    workspace.clone_missing()
    workspace.set_remotes()
    workspace.copy_files()
    ui.info("Done", ui.check)
Esempio n. 21
0
def test_info_stdout_is_not_a_tty(dumb_tty):
    ui.info(ui.red,
            "this is red",
            ui.reset,
            ui.green,
            "this is green",
            fileobj=dumb_tty)
    expected = "this is red this is green\n"
    actual = dumb_tty.getvalue()
    assert_equal_strings(actual, expected)
Esempio n. 22
0
def _agent_prompt():
    """Description: Prompt the user to import their agent"""
    sys.path.append(os.getcwd())
    agent = importlib.import_module(ui.ask_string(constants.Strings.match_import.value))
    agent_class = ui.ask_string(constants.Strings.match_class_name.value)
    if agent_class not in agent.__dir__():
        ui.fatal(constants.Strings.error_invalid_class.value)
    agent = getattr(agent, agent_class)
    if getattr(agent, "act"):
        ui.info(ui.green, constants.Strings.match_agent_success.value)
    return agent
Esempio n. 23
0
def test_info_stdout_is_a_tty(smart_tty):
    ui.info(ui.red,
            "this is red",
            ui.reset,
            ui.green,
            "this is green",
            fileobj=smart_tty)
    expected = (RED + "this is red " + RESET + GREEN + "this is green" +
                RESET + "\n")
    actual = smart_tty.getvalue()
    assert_equal_strings(actual, expected)
Esempio n. 24
0
def grant_role(args, role, user, project):
    '''tanpa di grant gk bisa login, grant ke member saja'''
    try:
        ex = ks.roles.grant(role=role,
                            user=user,
                            system=None,
                            project=project)
        ui.info_3(ex)
        ui.info_3('\n Done ', ui.check)
    except Exception as e:
        '''jika tidak ada nama'''
        ui.info(ui.red, ui.bold, 'Error: ', ui.reset, e)
Esempio n. 25
0
def main(args):
    workspace_path = args.workspace_path or os.getcwd()
    workspace = tsrc.workspace.Workspace(path.Path(workspace_path))
    ui.info_1("Configuring workspace in", ui.bold, workspace_path)
    workspace.configure_manifest(url=args.manifest_url,
                                 branch=args.branch,
                                 groups=args.groups)
    workspace.load_manifest()
    workspace.clone_missing()
    workspace.set_remotes()
    workspace.copy_files()
    ui.info("Done", ui.check)
 def ploting(tweets_db=TWEETS_DB, csv_file=CSV_FILE):
     table_name = MyStreamListener.table_name
     plot_question = ui.ask_yes_no("Plot?", default=True)
     if plot_question:
         ui.info(ui.green, "Populating csv file with {}".format(table_name))
         q_four.db_into_csv(TWEETS_DB, CSV_FILE, table_name)
         ui.info_3("Ploting...")
         q_four.frecuency()
         q_four.senti()
     else:
         ui.info(ui.turquoise, "Program Finished")
         exit()
Esempio n. 27
0
def main():
    ui.info_1("Starting CI")
    checks = init_checks()
    for check in checks:
        check.run()
    failed_checks = [check for check in checks if not check.ok]
    if not failed_checks:
        ui.info(ui.green, "CI passed")
        return
    for check in failed_checks:
        ui.error(check.name, "failed")
    sys.exit(1)
Esempio n. 28
0
 def create_merge_request(self, project_id, source_branch, *, title,
                          target_branch="master"):
     ui.info_2("Creating merge request", ui.ellipsis, end="")
     url = "/projects/%i/merge_requests" % project_id
     data = {
         "source_branch": source_branch,
         "target_branch": target_branch,
         "title": title,
         "project_id": project_id,
     }
     result = self.make_request("POST", url, data=data)
     ui.info("done", ui.check)
     return result
def number_rows(
        conn=create_conection(), db_file=TWEETS_DB, table_name=TABLE_NAME):
    """Shows number of rows in Database
    :param conn:
    :param db_file:
    :param table_name:
    """
    cur = conn.cursor()
    select_all = """SELECT COUNT(*) FROM {tn}""".format(tn=table_name)
    count = cur.execute(select_all)
    count_value = count.fetchone()
    count_value = str(count_value).strip('(').strip(')').strip(',')
    ui.info(ui.green, "{} rows in {}".format(count_value, db_file))
Esempio n. 30
0
def print_banner(b_type="intro"):
    if "intro" in b_type:
        banner = """
	._____. ._____.     ;___________;
	| ._. | | ._. |     ; h8mail.py ;
	| !_| |_|_|_! |     ;-----------;
	!___| |_______!  Heartfelt Email OSINT
	.___|_|_| |___.   Use responsibly etc
	| ._____| |_. | ;____________________;
	| !_! | | !_! | ; github.com/khast3x ;
	!_____! !_____! ;--------------------;
	"""
        ui.info(ui.darkred, banner)
Esempio n. 31
0
def main():
    parse_source_tree()

    configuration = configurations.get_selected_configuration()
    if configuration.name != "__default":
        ui.bigstep("configuration", str(configurations.get_selected_configuration()))

    if not _build_some_targets_if_requested():
        ui.info("no target selected\n")

        ui.info(ui.BOLD + "targets:" + ui.RESET)
        for target in targets.targets.values():
            ui.info("  " + str(target))

        ui.info(ui.BOLD + "\nconfigurations:" + ui.RESET)
        for configuration in configurations.configurations:
            ui.info("  " + str(configuration))

        ui.info("\nsee --help for more\n")