Esempio n. 1
0
def test_format_pretty_table():

    post1 = Essay(dict(id="1", title="title 1", body="body 1"))

    post2 = Essay(dict(id="2", title="title 2", body="body 2"))

    posts = Essay.Set([post1, post2])

    posts.should.be.a(ModelSet)

    posts.format_pretty_table().should.equal(
        format_pretty_table(
            [["1", "title 1", "body 1"], ["2", "title 2", "body 2"]],
            ["id", "title", "body"],
        )
    )

    posts.format_pretty_table(["title"]).should.equal(
        format_pretty_table([["title 1"], ["title 2"]], ["title"])
    )

    when_called = posts.format_pretty_table.when.called_with(["inexistent"])
    when_called.should.have.raised(
        ValueError,
        "the following columns are not available for <class 'tests.unit.test_set.Essay'>: {'inexistent'}",
    )
Esempio n. 2
0
async def ingame(cmd, message, args):

    games = {}
    online_count = 0
    playing_count = 0
    total_count = 0

    for member in message.guild.members:
        total_count += 1
        status = str(member.status)

        if status != 'offline':
            online_count += 1

        if not member.bot:
            if member.game:
                game_name = str(member.game)
                repl_name = game_name.replace(' ', '')

                if repl_name != '':
                    playing_count += 1
                    if game_name not in games:
                        games.update({game_name: 1})
                    else:
                        curr_count = games[game_name]
                        new_count = curr_count + 1
                        games.update({game_name: new_count})

    embed = discord.Embed(color=0x1ABC9C)
    sorted_games = sorted(games.items(), key=operator.itemgetter(1))
    n = 0
    out_table_list = []
    game_count = len(sorted_games)

    for key, value in reversed(sorted_games):
        if n < 5:
            n += 1
            if len(key) > 32:
                key = key[:32] + '...'
            out_table_list.append([
                str(n),
                key.title(), value,
                str(((value / playing_count) * 10000) // 100).split('.')[0] +
                '%'
            ])

    out = format_pretty_table(out_table_list)
    general_stats_list = [['Online', online_count], ['In-Game', playing_count],
                          ['Unique Games', game_count]]
    general_stats_out = format_pretty_table(general_stats_list)

    embed.add_field(name='👾 Current Gaming Statistics on ' +
                    message.guild.name,
                    value='```haskell\n' + general_stats_out + '\n```',
                    inline=False)
    embed.add_field(name='🎮 By Game...',
                    value='```haskell\n' + out + '\n```',
                    inline=False)
    await message.channel.send(None, embed=embed)
Esempio n. 3
0
	def WPRun(self):
		count = 0
		with Spinner(label="Enumeration") as spinner:
			for i in range(15):
				sleep(0.1)
				spinner.step()
			print ""
			self.WPJson()
			self.WPJson2()
		column_user = ["ID","Username","Login"]
		print format_pretty_table(self.CheckUser(self.users),column_user)
Esempio n. 4
0
    def format_pretty_table(self, columns: Iterable[str] = None):
        """returns a string with a pretty table ready to be printed on a terminal.

        powered by :py:func:`humanfriendly.tables.format_pretty_table`
        """
        columns, rows = self.get_table_columns_and_rows(columns)
        return format_pretty_table(rows, columns)
Esempio n. 5
0
    def _display_thanks(self):
        if self.give_thanks_to:
            cprint('You depend on {} who would {}'.format(
                colored('{} authors'.format(len(self.give_thanks_to)), 'cyan'),
                colored('enjoy donations!', 'green'),
            ),
                   attrs=['bold'])
            colorized_data = [
                ProjectData(
                    name=colored(pd.name, 'cyan'),
                    funding_link=colored(pd.funding_link, 'green'),
                    authors=colored(pd.authors, 'yellow'),
                ) for pd in self.give_thanks_to.values()
            ]

            print(
                format_pretty_table(
                    data=colorized_data,
                    column_names=['Project', 'Where to thank', 'Authors'],
                    horizontal_bar=' ',
                    vertical_bar=' ',
                ))
            cprint(''.join([
                "If you see projects with ",
                colored("MISSING FUNDING INFORMATION ",
                        "red"), "then why not submit a pull request ",
                "the project repository asking the author to ",
                colored("ADD A 'FUNDING' PROJECT_URL ",
                        "yellow"), "to the projects setup.py"
            ]),
                   attrs=['bold'])
Esempio n. 6
0
    def run(self):
        while True:
            login = False
            table = ['Username', 'Passowrd']
            passwd = self.queue.get()
            sys.stdout.write("[ * ] ")
            sys.stdout.write("%s\r\r" % passwd)
            sys.stdout.flush()
            post = """<methodCall><methodName>wp.getUsersBlogs</methodName>
			<params><param><value><string>%s</string></value></param><param>
			<value><string>%s</string></value></param></params></methodCall>""" % (
                self.user, passwd)
            resp = self.request.send(url=self.target, method="POST", data=post)
            if search(
                    decode('<name>isAdmin</name><value><boolean>0</boolean>'),
                    resp.content):
                login = True
            elif search(
                    decode('<name>isAdmin</name><value><boolean>1</boolean>'),
                    resp.content):
                login = True
            if login is True:
                plus('Valid Credentials: ')
                normal('')
                print(format_pretty_table([[self.user, passwd]], table))
                self.queue.task_done()
                self.queue.join()
Esempio n. 7
0
def show_output():
	count = 0
	header = ["MAC", "Vendor", "Time", "Sig", "SSID"]
	current_output = []
	nice_ssids = ""


	for i in range(0,17):
 		current_output.append([])

	for i in range(0, len(observed_clients)):
		if count < 17:
			nice_ssids = ""	
			for s in observed_clients[i].ssid:	
				if s is not "" and s not in nice_ssids:
					nice_ssids = nice_ssids + s + " "
					nice_ssids = nice_ssids[:30]
			nice_time = str(observed_clients[i].last_seen.hour) + ":" + str(observed_clients[i].last_seen.minute) + ":" + str(observed_clients[i].last_seen.second)
			if observed_clients[i].host == True:
				nice_time = colored(nice_time, 'red')
				nice_ssids = colored(nice_ssids, 'red')
				current_output[i] = ([    colored(str(observed_clients[i].mac[9:]), 'red')  , colored(observed_clients[i].vendor, 'red'), nice_time,  colored(str(observed_clients[i].strength), 'red'), nice_ssids])
			else:				
				current_output[i] = ([ str(observed_clients[i].mac[9:])    , observed_clients[i].vendor, nice_time,str(observed_clients[i].strength), nice_ssids])
			
		count += 1
		
	os.system('clear')

	
			
	print (format_pretty_table( current_output, header))
	print "Clients:", unique_clients,"  Hosts:", unique_hosts
	sys.stdout.softspace=0
Esempio n. 8
0
 def find_package_roles(self, requirements_file):
     with open(requirements_file, 'r') as reqs:
         print("Scanning your requirements file...")
         for req in requirements.parse(reqs):
             self.update_give_thanks(req.name)
         if req.name in self.local_installs:
             for package in self.local_installs[req.name].requires():
                 self.update_give_thanks(package.key)
         if self.give_thanks_to:
             print("Found the following contributors to support:")
             table_data = []
             for contributor in self.give_thanks_to:
                 table_data.append(
                     [
                         colored(contributor, 'blue'),
                         colored(self.give_thanks_to[contributor]['url'], 'green'),
                         colored(", ".join(self.give_thanks_to[contributor]['packages']), 'red'),
                     ]
                 )
             print(format_pretty_table(
                 data=table_data,
                 column_names=['Author', 'Where to thank', 'Packages'],
                 horizontal_bar=' ',
                 vertical_bar=' ',
             ))
Esempio n. 9
0
    def preload(self):
        # sort by priority
        self._preload_funcs.sort(key=lambda f: f[0])
        logger.debug(
            f"{len(self._preload_funcs)} preload functions registered")

        if logger.getEffectiveLevel() <= logging.DEBUG:
            # dump all the preload functions
            prev_priority = -1
            table = []
            for priority, func in self.preload_funcs:
                if priority != prev_priority:
                    prev_priority = priority
                    prefix_str = int(priority)
                else:
                    prefix_str = " "
                func_name = func.__name__.strip("_")
                table.append([prefix_str, func_name])
            print(format_pretty_table(table, ["Priority", "Function"]))

        logger.info("start preloading")
        for _, func in self.preload_funcs:
            try:
                func()
            except UnsupportedDatasetError:
                # shunt
                raise
            except Exception as e:
                func_name = func.__name__.strip("_")
                raise PreloadError(f'failed at "{func_name}": {str(e)}')
Esempio n. 10
0
File: cli.py Progetto: hackprime/yom
 def render_output(self, context):
     if 'json' in context:
         print context['json']
     elif 'table' in context:
         print "\n", context['header']
         table_params = {'data': context['table']}
         print format_pretty_table(**table_params), "\n"
     elif 'robust_table' in context:
         print "\n", context['header']
         table_params = {'data': context['robust_table'],
                         'column_names': ['code', '']}
         print format_robust_table(**table_params), "\n"
     elif 'header' in context:
         self.render_message(context['header'])
     else:
         raise YomError('Not enough parameters for output formatting')
Esempio n. 11
0
 def report_job_completed(self, run_ids):
     self._ui.output(
         "\n\n" + format_pretty_table(self._generate_all_output(run_ids), [
             'Benchmark', 'VM', 'Suite', 'Extra', 'Core', 'Size', 'Var',
             '#Samples', 'Mean (ms)'
         ],
                                      vertical_bar=' '))
Esempio n. 12
0
def draw_rpn_build_table(rpn_stages):
    print("R P N  S T A G E S")
    data = [["\\n" if s.lexeme == "\n" else s.lexeme, s.stack, s.rpn]
            for s in rpn_stages]
    print(
        tbls.format_pretty_table(data, column_names=["Lexeme", "Stack",
                                                     "RPN"]))
Esempio n. 13
0
async def wfacolytes(cmd: SigmaCommand, message: discord.Message, args: list):
    try:
        api_url = 'https://api.tenno.tools/worldstate/pc'
        async with aiohttp.ClientSession() as session:
            async with session.get(api_url) as tools_session:
                tool_data = await tools_session.read()
                world_data = json.loads(tool_data)
    except aiohttp.ClientPayloadError:
        world_data = {}
    acolytes = world_data.get('acolytes')
    if acolytes:
        acolytes = acolytes.get('data')
    else:
        acolytes = []
    if not acolytes:
        response = discord.Embed(color=0x990000, title='No data on the acolytes.')
    else:
        data_list = []
        headers = ['Name', 'Health', 'Location']
        for acolyte in acolytes:
            name = acolyte.get('name')
            health = f"{round(acolyte.get('health') * 100, 2)}%"
            if acolyte.get('discovered'):
                location = acolyte.get('location')
            else:
                location = 'Unknown'
            entry = [name, health, location]
            data_list.append(entry)
        data_table = format_pretty_table(data_list, headers)
        response = discord.Embed(color=0xcc0000)
        response.set_author(name='Warframe Acolyte Data', icon_url=stalker_icon)
        response.description = f'```hs\n{data_table}\n```'
    await message.channel.send(embed=response)
Esempio n. 14
0
async def servers(cmd, message, args):
    if message.author.id in permitted_id:
        serv_lst = []
        column_lst = ['Server Name', 'Server ID', 'Members']
        for server in cmd.bot.servers:
            temp_lst = []
            n = len(server.members)
            temp_lst.append(str(server))
            temp_lst.append(str(server.id))
            temp_lst.append(str(n))
            serv_lst.append(temp_lst)
        server_list = format_pretty_table(serv_lst, column_lst)
        out_text = 'List of servers:\n```'
        out_text += server_list
        if len(out_text) > 1950:
            out_text = out_text[:1950]
            out_text += '...'
        out_text += '\n```'
        await cmd.bot.send_message(message.channel, out_text)
    else:
        error_msg = await cmd.bot.send_message(message.channel,
                                               'Insufficient permissions.')
        await asyncio.sleep(5)
        await cmd.bot.delete_message(error_msg)
        await cmd.bot.delete_message(message)
Esempio n. 15
0
async def wfacolytes(_cmd, pld):
    """
    :param _cmd: The command object referenced in the command.
    :type _cmd: sigma.core.mechanics.command.SigmaCommand
    :param pld: The payload with execution data and details.
    :type pld: sigma.core.mechanics.payload.CommandPayload
    """
    acolytes = await WorldState().acolytes
    if acolytes:
        data_list = []
        headers = ['Name', 'Health', 'Location']
        for acolyte in acolytes:
            name = acolyte.get('name')
            health = f"{round(acolyte.get('health') * 100, 2)}%"
            if acolyte.get('discovered'):
                location = acolyte.get('location')
            else:
                location = 'Unknown'
            entry = [name, health, location]
            data_list.append(entry)
        data_table = format_pretty_table(data_list, headers)
        response = discord.Embed(color=0xcc0000)
        response.set_author(name='Warframe Acolytes Data', icon_url=stalker_icon)
        response.description = f'```hs\n{data_table}\n```'
    else:
        response = error('No data on the Acolytes.')
    await pld.msg.channel.send(embed=response)
Esempio n. 16
0
def print_formatted_table(delimiter):
    """Read tabular data from standard input and print a table."""
    data = []
    for line in sys.stdin:
        line = line.rstrip()
        data.append(line.split(delimiter))
    output(format_pretty_table(data))
Esempio n. 17
0
 def Info(self, smb):
     print('[+] Showing folders..')
     names = []
     column = ['Name', 'Type', 'Comments']
     shares = smb.listShares()
     for share in shares:
         names.append([share.name, share.type, share.comments])
     print(format_pretty_table(names, column))
Esempio n. 18
0
def list_builds(version=None,
                product="houdini",
                platform="linux",
                only_production=False):
    """Display a table of builds available to download.

    Dates which care colored green indicate they are today's build.

    :param version: The major.minor version to download.
    :type version: str
    :param product: The name of the product to download.
    :type product: str
    :param platform: The platform to download for.
    :type platform: str
    :param only_production: Only consider production builds.
    :type only_production: bool
    :return:

    """
    service = _Service()

    # Get a list of builds which match the criteria.
    releases_list = service.get_available_builds(
        product,
        version=version,
        platform=platform,
        only_production=only_production)

    headers = ["Build", "Date", "Type"]

    # A filtered list of builds.
    rows = []

    today = datetime.datetime.now().date()

    # Filter the builds based on additional settings.
    for release in releases_list:
        release_type, release_color = _RELEASE_TYPE_MAP[release["release"]]

        build_date = datetime.datetime.strptime(release["date"],
                                                "%Y/%m/%d").date()

        if build_date == today:
            build_date = colored(build_date, "green")

        row = [
            colored(
                "{}.{}".format(release["version"], release["build"]),
                _STATUS_MAP[release["status"]],
            ),
            build_date,
            colored(release_type, release_color),
        ]

        rows.append(row)

    cprint(format_pretty_table(rows, headers))
Esempio n. 19
0
	def run(self):
		info('Enumerating users...')
		users = []
		users = self.wpjson()
		users += self.wpjson2()
		users += self.wpfeed()
		users += self.wpauthor()
		text_table = ['ID', 'Username', 'Login']
		print(format_pretty_table(self.r_user(users), text_table))
Esempio n. 20
0
def test_format_pretty_table_without_explicit_visible_attributes():
    chuck = Person(
        {"age": 42, "name": "Chuck Norris", "email": "*****@*****.**"}
    )
    chuck.get_table_columns().should.equal(["name", "age"])
    chuck.get_table_rows().should.equal([["Chuck Norris", 42]])

    chuck.format_pretty_table().should.equal(
        format_pretty_table([["Chuck Norris", 42]], ["name", "age"])
    )
Esempio n. 21
0
 def render(self):
     data = []
     column_names = ('Name', 'Type', 'Default', 'Doc Text')
     for field in field_iter(self.resource):
         data.append([
             field.name,
             field.__class__.__name__,
             '' if field is not NOT_PROVIDED else str(field.default),
             field.doc_text
         ])
     self.print(tables.format_pretty_table(data, column_names))
Esempio n. 22
0
    def handle(self, *args, **options):
        """Query all the entries from the catalog model."""
        if args:
            raise CommandError("infocatalog takes no arguments")
        column_names = ['Catalog Name']
        # [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
        catalog = [cat.name for cat in Catalog.objects.all()]

        self.stdout.write(format_pretty_table([
            catalog,
        ], column_names))
Esempio n. 23
0
 def test_pretty_tables(self):
     """Test :func:`humanfriendly.tables.format_pretty_table()`."""
     # The simplest case possible :-).
     data = [['Just one column']]
     assert format_pretty_table(data) == dedent("""
         -------------------
         | Just one column |
         -------------------
     """).strip()
     # A bit more complex: two rows, three columns, varying widths.
     data = [['One', 'Two', 'Three'], ['1', '2', '3']]
     assert format_pretty_table(data) == dedent("""
         ---------------------
         | One | Two | Three |
         | 1   | 2   | 3     |
         ---------------------
     """).strip()
     # A table including column names.
     column_names = ['One', 'Two', 'Three']
     data = [['1', '2', '3'], ['a', 'b', 'c']]
     assert ansi_strip(format_pretty_table(data,
                                           column_names)) == dedent("""
         ---------------------
         | One | Two | Three |
         ---------------------
         | 1   | 2   | 3     |
         | a   | b   | c     |
         ---------------------
     """).strip()
     # A table that contains a column with only numeric data (will be right aligned).
     column_names = ['Just a label', 'Important numbers']
     data = [['Row one', '15'], ['Row two', '300']]
     assert ansi_strip(format_pretty_table(data,
                                           column_names)) == dedent("""
         ------------------------------------
         | Just a label | Important numbers |
         ------------------------------------
         | Row one      |                15 |
         | Row two      |               300 |
         ------------------------------------
     """).strip()
Esempio n. 24
0
 def test_pretty_tables(self):
     """Test :func:`humanfriendly.tables.format_pretty_table()`."""
     # The simplest case possible :-).
     data = [['Just one column']]
     assert format_pretty_table(data) == dedent("""
         -------------------
         | Just one column |
         -------------------
     """).strip()
     # A bit more complex: two rows, three columns, varying widths.
     data = [['One', 'Two', 'Three'], ['1', '2', '3']]
     assert format_pretty_table(data) == dedent("""
         ---------------------
         | One | Two | Three |
         | 1   | 2   | 3     |
         ---------------------
     """).strip()
     # A table including column names.
     column_names = ['One', 'Two', 'Three']
     data = [['1', '2', '3'], ['a', 'b', 'c']]
     assert ansi_strip(format_pretty_table(data, column_names)) == dedent("""
         ---------------------
         | One | Two | Three |
         ---------------------
         | 1   | 2   | 3     |
         | a   | b   | c     |
         ---------------------
     """).strip()
     # A table that contains a column with only numeric data (will be right aligned).
     column_names = ['Just a label', 'Important numbers']
     data = [['Row one', '15'], ['Row two', '300']]
     assert ansi_strip(format_pretty_table(data, column_names)) == dedent("""
         ------------------------------------
         | Just a label | Important numbers |
         ------------------------------------
         | Row one      |                15 |
         | Row two      |               300 |
         ------------------------------------
     """).strip()
Esempio n. 25
0
def get(forced, only_one):
    '''attiva il programma'''

    if forced:
        click.echo('\nAggiorno il database\n')
    else:
        click.echo('\nAggiorno il database se necessario\n')
    try:
        update_db(forced)
        stocks = session.query(Stock).all()
        bonds = session.query(Bond).all()
        notification_s = check_thresholds(stocks)
        notification_b = check_thresholds(bonds)

        if notification_s is not None:
            table = stock_table(stocks)
            pretty_s = format_pretty_table(table[1:], column_names=table[0])
            text_s = '{}\n{}\n\n'.format(notification_s.format('azione'),
                                         pretty_s)
        else:
            text_s = '\nATTENZIONE nessuna azione inserita nel database'

        if notification_b is not None:
            table = bond_table(bonds)
            pretty_b = format_pretty_table(table[1:], column_names=table[0])
            text_b = '{}\n{}\n\n'.format(notification_b.format('obbligazione'),
                                         pretty_b)
        else:
            text_b = '\nATTENZIONE nessuna obbligazione inserita nel database'

        if only_one == 'stock':
            click.echo(text_s)
        elif only_one == 'bond':
            click.echo(text_b)
        else:
            click.echo(''.join([text_s, text_b]))
    except SystemExit:
        click.echo('\nATTENZIONE nessuna connessione internet')
Esempio n. 26
0
def main(argv):
    if argv == '-h' or argv == '--help':
        print(text.Text("ady", color='#0099ff', shadow=True, skew=5))
        print("ady -- Bakı -> Sumqayıt -> Bakı hərəkət cədvəli")
        print("ady ['-b', '--baku', '--bakı'] -- bakı üçün hərəkət cədvəli")
        print(
            "ady ['-s', '--sum', '--sumgait', '--sumqayıt'] -- sumqayıt üçün hərəkət cədvəli"
        )
        print(
            "ady ['-a', '--all', '--ha', '--hamısı'] -- hər iki hərəkət cədvəli"
        )
    else:
        getTable()
        if argv == "-b" or argv == "--baku" or argv == "--bakı":
            print(format_pretty_table(baku_table, baku_header))
            sys.exit()
        elif argv == "-s" or argv == "--sum" or argv == "--sumgait" or argv == "--sumqayıt":
            print(format_pretty_table(sum_table, sum_header))
            sys.exit()
        elif argv == "-a" or argv == "--all" or argv == "--ha" or argv == "--hamısı":
            print(format_pretty_table(baku_table, baku_header))
            print(format_pretty_table(sum_table, sum_header))
            sys.exit()
Esempio n. 27
0
    def render(self):
        mapping = self.mapping
        self.title("{}.{}".format(mapping.__module__, mapping.__name__))
        self.print('')
        self.print("From:", resource_reference(mapping.from_obj))
        self.print("To:  ", resource_reference(mapping.to_obj))
        self.print('')

        # Build mapping summary
        data = []
        column_names = ('From', 'Action', 'To', 'Options')
        for from_fields, action, to_fields, to_list, bind, skip_if_none in mapping._mapping_rules:
            # Dereference
            from_fields = from_fields or ['*Assigned*']
            to_fields = to_fields or list()
            row_count = max(len(from_fields), len(to_fields))

            # Normalise
            if len(from_fields) < row_count:
                from_fields += [
                    '' for _ in range(row_count - len(from_fields))
                ]
            if len(to_fields) < row_count:
                to_fields += ['' for _ in range(row_count - len(to_fields))]

            if action:
                if not isinstance(action, six.string_types):
                    action = str(action)
            else:
                action = '-->'

            options = []
            if bind:
                options.append('bound')
            if skip_if_none:
                options.append('skip if None')
            options = ', '.join(options)

            for idx in range(row_count):
                from_field = from_fields[idx]
                to_field = to_fields[idx]
                if to_list:
                    to_field = '[{}]'.format(to_field)
                if idx == 0:
                    data.append([from_field, action, to_field, options])
                else:
                    data.append([from_field, '+->', to_field, options])

        self.print(tables.format_pretty_table(data, column_names))
Esempio n. 28
0
    def render(self):
        mapping = self.mapping
        self.title("{}.{}".format(mapping.__module__, mapping.__name__))
        self.print('')
        self.print("From:", resource_reference(mapping.from_obj))
        self.print("To:  ", resource_reference(mapping.to_obj))
        self.print('')

        # Build mapping summary
        data = []
        column_names = ('From', 'Action', 'To', 'Options')
        for from_fields, action, to_fields, to_list, bind, skip_if_none in mapping._mapping_rules:
            # Dereference
            from_fields = from_fields or ['*Assigned*']
            to_fields = to_fields or []
            from_fields_len = len(from_fields)
            to_fields_len = len(to_fields)
            row_count = max(from_fields_len, to_fields_len)

            # Normalise
            if len(from_fields) < row_count:
                from_fields += ['' for _ in range(row_count - from_fields_len)]
            if len(to_fields) < row_count:
                to_fields += ['' for _ in range(row_count - to_fields_len)]

            if action:
                if not isinstance(action, six.string_types):
                    action = str(action)
            else:
                action = '-->'

            options = []
            if bind:
                options.append('bound')
            if skip_if_none:
                options.append('skip if None')
            options = ', '.join(options)

            for idx in range(row_count):
                from_field = from_fields[idx]
                to_field = to_fields[idx]
                if to_list:
                    to_field = '[{}]'.format(to_field)
                if idx == 0:
                    data.append([from_field, action, to_field, options])
                else:
                    data.append([from_field, '+->', to_field, options])

        self.print(tables.format_pretty_table(data, column_names))
Esempio n. 29
0
 def showFolder(self, smb, path):
     print('[+] Show %s Files...' % (path))
     names = []
     column = ['Filename', 'ReadOnly']
     try:
         dir_ = smb.listPath(path, '/')
     except Exception as e:
         print(
             '[!] Failed to list \ on %s: Unable to connect to shared device'
             % path)
         exit(0)
     for file in dir_:
         names.append([file.filename, file.isReadOnly])
     print(format_pretty_table(names, column))
     exit(0)
Esempio n. 30
0
def test_format_pretty_table():

    post1 = BlogPost(dict(id=1, title="title 1", body="body 1"))

    post2 = BlogPost(dict(id=2, title="title 2", body="body 2"))

    posts = BlogPost.List([post1, post2])

    posts.should.be.a(ModelList)

    posts.format_pretty_table().should.equal(
        format_pretty_table(
            [[1, "title 1", "body 1"], [2, "title 2", "body 2"]],
            ["id", "title", "body"],
        ))

    posts.format_pretty_table(["title"]).should.equal(
        format_pretty_table([["title 1"], ["title 2"]], ["title"]))

    when_called = posts.format_pretty_table.when.called_with(["inexistent"])
    when_called.should.have.raised(
        ValueError,
        "the following columns are not available for <class 'tests.unit.test_list.BlogPost'>: {'inexistent'}",
    )
Esempio n. 31
0
def test_format_pretty_table():
    chuck = User({
        "id": 1,
        "username": "******",
        "email": "*****@*****.**"
    })
    chuck.get_table_columns().should.equal(["id", "username", "email"])
    chuck.get_table_rows().should.equal(
        [[1, "chucknorris", "*****@*****.**"]])

    chuck.format_pretty_table().should.equal(
        format_pretty_table(
            [[1, "chucknorris", "*****@*****.**"]],
            ["id", "username", "email"],
        ))
Esempio n. 32
0
	def testFile(self,file):
		res = []
		code = readfile(file)
		res += self.csrf(code)
		res += self.ope(code)
		res += self.pce(code)
		res += self.com(code)
		res += self.auth(code)
		res += self.php(code)
		res += self.fin(code)
		res += self.fid(code)
		res += self.sql(code)
		res += self.xss(code)
		if res != []:
			print(format_pretty_table(res,self.table))
		else: plus('Not found vulnerabilities')
Esempio n. 33
0
def draw_lexeme_table(tokens):
    print("L E X E M S")
    data = []
    for t in tokens:
        row = [t.row_num, t.tag]
        if hasattr(t, "payload"):
            str_value = "\\n" if t.payload == "\n" else t.payload
            row.append(str_value)
        elif t.tag in cmn.SYMBOLS.values():
            row.append(get_string_repr(cmn.SYMBOLS, t.tag))
        elif t.tag in cmn.WORDS.values():
            row.append(get_string_repr(cmn.WORDS, t.tag))
        row.append(t.index) if hasattr(t, "index") else row.append("")
        data.append(row)
    print(
        tbls.format_pretty_table(
            data, column_names=["Row", "Tag", "Payload", "Index"]))
Esempio n. 34
0
    def _generate_output(self, colored_output=True):
        def _uncolored(text, *args, **kwargs):
            return text

        colored = termcolor.colored if colored_output else _uncolored

        lines = []
        lines.append(
            colored('You depend on {} who would {}'.format(
                colored('{} authors'.format(len(self.give_thanks_to)), 'cyan'),
                colored('enjoy donations!', 'green'),
                ),
                attrs=['bold']
            )
        )

        colorized_data = [
            ProjectData(
                name=colored(pd.name, 'cyan'),
                funding_link=colored(pd.funding_link, 'green'),
                authors=colored(pd.authors, 'yellow'),
            )
            for pd in self.give_thanks_to.values()
        ]

        lines.append(format_pretty_table(
            data=colorized_data,
            column_names=['Project', 'Where to thank', 'Authors'],
            horizontal_bar=' ',
            vertical_bar=' ',
        ))

        lines.append(
            ''.join([
                "See projects without ",
                colored("FUNDING INFORMATION", "red"),
                "? Why not submit a pull request to ",
                "the project asking the author to add a ",
                colored("'FUNDING' PROJECT_URL ", "yellow"),
                "to the project's setup.py. ",
                "https://packaging.python.org/guides/",
                "distributing-packages-using-setuptools/#project-urls\n"
            ]),
        )

        return '\n'.join(lines)
Esempio n. 35
0
async def rolepopulation(cmd, message, args):
    
    if args:
        rl_qry = ' '.join(args)
        role_search = discord.utils.find(lambda x: x.name.lower() == rl_qry.lower(), message.guild.roles)
        if not role_search:
            response = discord.Embed(color=0x696969, title=f'🔍 {rl_qry} not found.')
            await message.channel.send(embed=response)
            return

        counter = 0
        for member in message.guild.members:
            member_role_search = discord.utils.find(lambda x: x.id == role_search.id, member.roles)
            if member_role_search:
                counter += 1
        response = discord.Embed(color=role_search.color)
        response.set_author(name=message.guild.name, icon_url=message.guild.icon_url)
        response.add_field(name=f'{role_search.name} Population', value=f'```[y\n{counter}\n```')
        await message.channel.send(embed=response)
            
    else:
        role_dict = {}
        for role in message.guild.roles:
            if role.name == '@everyone': continue
            role_key = role.name
            role_count = 0
            for member in message.guild.members:
                member_role_search = discord.utils.find(lambda x: x.id == role.id, member.roles)
                if member_role_search:
                    role_count += 1
            role_dict.update({role_key: role_count})
        
        sorted_roles = sorted(role_dict.items(), key=operator.itemgetter(1), reverse=True)
        output = []
        
        for srole in sorted_roles[:20]:
            output.append([srole[0], srole[1], f'{str(percentify(srole[1], len(message.guild.members)))}%'])
        
        out_text = format_pretty_table(output)
        
        response = discord.Embed(color=0x0099FF)
        response.set_author(name=message.guild.name, icon_url=message.guild.icon_url)
        response.add_field(name='Statistics', value=f'```py\nShowing {len(output)} roles out of {len(message.guild.roles)}\n```', inline=False)
        response.add_field(name=f'Role Population', value=f'```haskell\n{out_text}\n```', inline=False)
        await message.channel.send(embed=response)
Esempio n. 36
0
def show():
    '''mostra le azioni e obbligazioni inserite'''
    table_s, table_b = show_assets()
    pretty_table_s = format_pretty_table(table_s[1:], table_s[0])
    pretty_table_b = format_pretty_table(table_b[1:], table_b[0])
    click.echo_via_pager('{}\n{}'.format(pretty_table_s, pretty_table_b))