예제 #1
0
def get_report_comparisation_table(reports, score_attrs=SCORE_R2S):
    """ Returns a formatted table which compares a list of reports by one or more attributes.

    Args:
        reports (list[Report]): The reports to compare
        score_attrs (list[str]|str): The attribute (or list of attributes) to compare. Use the SCORE_X constants.

    Returns:
        (Table): A table with the data.
    """
    if type(score_attrs) != list:
        score_attrs = [score_attrs]
    multiple_attrs = len(score_attrs) > 1

    headers = []
    if multiple_attrs:
        headers += [""]
    headers += [report.label for report in reports]

    compare_table = [headers]
    for score_attr in score_attrs:
        values = []
        if multiple_attrs:
            values.append(score_attr)
        values += [
            _format_float(getattr(report, score_attr)) for report in reports
        ]
        compare_table.append(values)
    table = Table(compare_table)

    if multiple_attrs:
        table.title = "Comparisation"
    else:
        table.title = _score_attr_to_string(score_attrs[0]) + " comparisation"
    return table
예제 #2
0
    def handle(self, *args, **options):
        for opt in options['option']:
            if opt == "all":
                table_data = [
                    ["id", "Blocked Name", "Start Time", "End Time", "Span"]
                ]
                for b in Blocked.objects.all().order_by("start_time"):
                    # print("Blocked Name: " + t.name + ", Span: " + str(t.span) + ", Deadline: " + str(t.deadline), ", Priority: ", str(t.priority) + ", Done; " + str(t.done))
                    table_data.append([
                        str(b.id), b.name, str(b.start_time), str(b.end_time), str(b.end_time - b.start_time)
                    ])

                table = AsciiTable(table_data)
                table.title = "All Blocked"
                print (table.table)
            elif opt == "left":
                table_data = [
                    ["id", "Blocked Name", "Start Time", "End Time", "Span"]
                ]
                now = timezone.now()
                print("Time now: " + str(now))
                for b in Blocked.objects.all().filter(end_time__gt=now):
                    # print("Blocked Name: " + t.name + ", Span: " + str(t.span) + ", Deadline: " + str(t.deadline), ", Priority: ", str(t.priority) + ", Done; " + str(t.done))
                    table_data.append([
                        str(b.id), b.name, str(b.start_time), str(b.end_time), str(b.end_time - b.start_time)
                    ])

                table = AsciiTable(table_data)
                table.title = "Left Blocked"
                print (table.table)
            else:
                print("Passed variable didn't match any pattern. Options available: all, left")

        self.stdout.write(self.style.SUCCESS("Successfully displayed task list"))
def callback(msg, has_printed):
    """Callback function called by libnl upon receiving messages from the kernel.

    Positional arguments:
    msg -- nl_msg class instance containing the data sent by the kernel.
    has_printed -- simple pseudo boolean (if list is empty) to keep track of when to print emtpy lines.

    Returns:
    An integer, value of NL_SKIP. It tells libnl to stop calling other callbacks for this message and proceed with
    processing the next kernel message.
    """
    table = AsciiTable([['Data Type', 'Data Value']])
    # First convert `msg` into something more manageable.
    gnlh = genlmsghdr(nlmsg_data(nlmsg_hdr(msg)))

    # Partially parse the raw binary data and place them in the `tb` dictionary.
    tb = dict(
        (i, None)
        for i in range(nl80211.NL80211_ATTR_MAX +
                       1))  # Need to populate dict with all possible keys.
    nla_parse(tb, nl80211.NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
              genlmsg_attrlen(gnlh, 0), None)

    # Now it's time to grab the juicy data!
    if tb[nl80211.NL80211_ATTR_IFNAME]:
        table.title = nla_get_string(
            tb[nl80211.NL80211_ATTR_IFNAME]).decode('ascii')
    else:
        table.title = 'Unnamed Interface'

    if tb[nl80211.NL80211_ATTR_WIPHY]:
        wiphy_num = nla_get_u32(tb[nl80211.NL80211_ATTR_WIPHY])
        wiphy = ('wiphy {0}'
                 if OPTIONS['<interface>'] else 'phy#{0}').format(wiphy_num)
        table.table_data.append(['NL80211_ATTR_WIPHY', wiphy])

    if tb[nl80211.NL80211_ATTR_MAC]:
        mac_address = ':'.join(
            format(x, '02x')
            for x in nla_data(tb[nl80211.NL80211_ATTR_MAC])[:6])
        table.table_data.append(['NL80211_ATTR_MAC', mac_address])

    if tb[nl80211.NL80211_ATTR_IFINDEX]:
        table.table_data.append([
            'NL80211_ATTR_IFINDEX',
            str(nla_get_u32(tb[nl80211.NL80211_ATTR_IFINDEX]))
        ])

    # Print all data.
    if has_printed:
        print()
    else:
        has_printed.append(True)
    print(table.table)
    return NL_SKIP
예제 #4
0
def test_title():
    """Test that table title shows up correctly."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
    ]
    table = AsciiTable(table_data, 'Foods')

    expected = dedent("""\
        +Foods----+-------+-----------+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table

    table.title = 'Foooooooooooooods'
    expected = dedent("""\
        +Foooooooooooooods+-----------+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table

    table.title = 'Foooooooooooooodsssssssssssss'
    expected = dedent("""\
        +Foooooooooooooodsssssssssssss+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table

    table.title = 'Foooooooooooooodssssssssssssss'
    expected = dedent("""\
        +---------+-------+-----------+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table
예제 #5
0
def test_title():
    """Test that table title shows up correctly."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
    ]
    table = AsciiTable(table_data, 'Foods')

    expected = dedent("""\
        +Foods----+-------+-----------+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table

    table.title = 'Foooooooooooooods'
    expected = dedent("""\
        +Foooooooooooooods+-----------+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table

    table.title = 'Foooooooooooooodsssssssssssss'
    expected = dedent("""\
        +Foooooooooooooodsssssssssssss+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table

    table.title = 'Foooooooooooooodssssssssssssss'
    expected = dedent("""\
        +---------+-------+-----------+
        | Name    | Color | Type      |
        +---------+-------+-----------+
        | Avocado | green | nut       |
        | Tomato  | red   | fruit     |
        | Lettuce | green | vegetable |
        +---------+-------+-----------+""")
    assert expected == table.table
예제 #6
0
def print_table(elements, title=None, filename=None):
    # type: (list, str, str) -> None
    if len(elements) > 0:
        if 'version' in elements[0].keys():
            table_data = [['Name', 'Version']]
            table = AsciiTable(table_data)
            table.padding_left = 1
            table.padding_right = 1
            max_width = 80
            if title is not None:
                table.title = title
            for element in elements:
                table_data.append([
                    element['name'],
                    '\n'.join(wrap(element['version'], max_width))
                ])
            print(table.table)
            if isinstance(filename, list):
                filename = filename[0]
            if filename is not None:
                try:
                    with open(filename, 'w') as fp:
                        fp.write(table.table)
                except IOError as e:
                    print_line(
                        "Exception {0} occured while write file {1}.".format(
                            e, filename))
        elif 'description' in elements[0].keys():
            table_data = [['Name', 'Description']]
            table = AsciiTable(table_data)
            table.padding_left = 1
            table.padding_right = 1
            max_width = 80  # table.column_max_width(1)
            if title is not None:
                table.title = title
            for element in elements:
                table_data.append([
                    element['name'],
                    '\n'.join(wrap(element['description'], max_width))
                ])
            print(table.table)
            if isinstance(filename, list):
                filename = filename[0]
            if filename is not None:
                try:
                    with open(filename, 'w') as fp:
                        fp.write(table.table)
                except IOError as e:
                    print_line(
                        "Exception occured while write file {0}.".format(
                            filename))
예제 #7
0
def output_ascii_table_list(table_title=None,
                            table_data=None,
                            table_header=None,
                            inner_heading_row_border=False,
                            inner_row_border=False):
    """
    @type table_title: unicode
    @type table_data: list
    @type inner_heading_row_border: bool
    @type inner_row_border: bool
    @type table_header: list
    """
    console_rows, _ = get_console_dimensions()
    console_rows = int(console_rows)
    full_display_length = len(table_data) + 7
    items_per_page = console_rows - 7
    num_pages = 0
    if full_display_length > console_rows:
        try:
            num_pages = int(
                math.ceil(float(len(table_data)) / float(items_per_page)))
        except ZeroDivisionError:
            exit('Console too small to display.')
    if num_pages:
        running_count = 0
        for page in range(1, num_pages + 1):
            page_table_output = list()
            page_table_output.insert(0, table_header)
            upper = (console_rows + running_count) - 7
            if upper > len(table_data):
                upper = len(table_data)
            for x in range(running_count, upper):
                page_table_output.append(table_data[x])
                running_count += 1
            table = AsciiTable(page_table_output)
            table.inner_heading_row_border = inner_heading_row_border
            table.inner_row_border = inner_row_border
            table.title = table_title
            if page != 1:
                print('')
            print(table.table)
            if page < num_pages:
                input("Press Enter to continue...")
                os.system('clear')
    else:
        table_data.insert(0, table_header)
        table = AsciiTable(table_data)
        table.inner_heading_row_border = inner_heading_row_border
        table.inner_row_border = inner_row_border
        table.title = table_title
        print(table.table)
예제 #8
0
def output_ascii_table_list(table_title=None,
                            table_data=None,
                            table_header=None,
                            inner_heading_row_border=False,
                            inner_row_border=False):
    """
    @type table_title: unicode
    @type table_data: list
    @type inner_heading_row_border: bool
    @type inner_row_border: bool
    @type table_header: list
    """
    console_rows, _ = get_console_dimensions()
    console_rows = int(console_rows)
    full_display_length = len(table_data) + 7
    items_per_page = console_rows - 7
    num_pages = 0
    if full_display_length > console_rows:
        try:
            num_pages = int(math.ceil(float(len(table_data)) / float(items_per_page)))
        except ZeroDivisionError:
            exit('Console too small to display.')
    if num_pages:
        running_count = 0
        for page in range(1, num_pages + 1):
            page_table_output = list()
            page_table_output.insert(0, table_header)
            upper = (console_rows + running_count) - 7
            if upper > len(table_data):
                upper = len(table_data)
            for x in range(running_count, upper):
                page_table_output.append(table_data[x])
                running_count += 1
            table = AsciiTable(page_table_output)
            table.inner_heading_row_border = inner_heading_row_border
            table.inner_row_border = inner_row_border
            table.title = table_title
            if page != 1:
                print('')
            print(table.table)
            if page < num_pages:
                input("Press Enter to continue...")
                os.system('clear')
    else:
        table_data.insert(0, table_header)
        table = AsciiTable(table_data)
        table.inner_heading_row_border = inner_heading_row_border
        table.inner_row_border = inner_row_border
        table.title = table_title
        print(table.table)
예제 #9
0
    def __str__(self):

        table = TermTable(self._table_data())

        table.inner_row_border = False
        table.title = "Dataset " + self.id
        return table.table
예제 #10
0
파일: course.py 프로젝트: hsmohammed/rudaux
    def create_canvas_assignments(self) -> 'Course':
        """Create assignments in Canvas.

    :returns: The course object to allow for method chaining.
    :rtype: Course
    """

        # PRINT BANNER
        print(utils.banner('Creating/updating assignments in Canvas'))

        # Initialize status table that we can push to as we go
        assignment_header = [['Assignment', 'Action']]

        assignment_status = []

        for assignment in tqdm(self.assignments):
            status = assignment.update_or_create_canvas_assignment()
            assignment_status.append([assignment.name, status])

        # Sort statuses
        assignment_status = sorted(assignment_status, key=lambda k: k[0])

        ## Print status for reporting:
        table = AsciiTable(assignment_header + assignment_status)
        table.title = 'Assignments'
        print("\n")
        print(table.table)
        print("\n")

        return self
예제 #11
0
 def print_table(self, data, title=None):
     print("")
     table = AsciiTable(data)
     if title:
         table.title = title
     print(table.table)
     print("")
예제 #12
0
def display_tabled_gads(authors, rendered_gad_months, title, border, width=0):
    """Display a table of gads per author according to gads_render_func."""
    if len(authors) <= 1:
        width = 1
    elif width == 0:
        gad_width = max(
            [non_ansi_len(l) for l in rendered_gad_months[1].splitlines()])
        author_width = max([non_ansi_len(a) for a in authors])
        auto_width = (MAX_WIDTH - 1) / (max(gad_width, author_width) + 3)
        width = max(1, auto_width)

    table_data = list(
        chain.from_iterable(
            izip(
                [authors[i:i + width] for i in xrange(0, len(authors), width)],
                [
                    rendered_gad_months[i:i + width]
                    for i in xrange(0, len(rendered_gad_months), width)
                ])))

    if border == "ascii":
        display_table = AsciiTable(table_data)
    elif border == "single":
        display_table = SingleTable(table_data)
    elif border == "double":
        display_table = DoubleTable(table_data)
    else:
        exit(1)

    display_table.inner_row_border = True
    display_table.inner_column_border = True
    display_table.title = title

    sys.stdout.write(fg(DEFAULT_COLOR))
    print display_table.table.encode('utf-8'), attr(0).encode('utf-8')
예제 #13
0
def get_confusion_matrix(ground_truth, predicted, categories=None, label=None):
    if categories is None:
        categories = [0, 1, 2, 4]
    cat_count = len(categories)
    true_cats = [
        categories.index(get_category(truth, categories))
        for truth in ground_truth
    ]
    predicted_cats = [
        categories.index(get_category(pred, categories)) for pred in predicted
    ]

    cm = __get_confusion_matrix(ground_truth, predicted, categories)

    cat_strings = get_category_strings(categories)

    confusion_table_data = [
        ['Prediction ->'] +
        ['cat ' + cat_strings[i] for i in range(cat_count)]
    ]
    for i in range(cat_count):
        confusion_table_data.append(['cat ' + cat_strings[i]] +
                                    [str(x) for x in cm[i, :].tolist()])
    confusion_table = Table(confusion_table_data)
    confusion_table.title = "Confusion matrix"
    if label:
        confusion_table.title += ": " + label

    report = "Classification report"
    if label:
        report += ": " + label
    report += "\n" + metrics.classification_report(
        true_cats, predicted_cats, labels=cat_strings)

    return confusion_table, report
예제 #14
0
    def __str__(self):
        output_data = [["Value", "Description", "Info"]]

        if self.evs is not None:
            output_data.append([
                _format_float(self.evs), "Explained variance score",
                "Best is 1.0, lower is worse"
            ])
        if self.mse is not None:
            output_data.append([
                _format_float(self.mse), "Mean squared error",
                "Best is 0.0, higher is worse"
            ])
        if self.mae is not None:
            output_data.append([
                _format_float(self.mae), "Mean absolute error",
                "Best is 0.0, higher is worse"
            ])
        if self.mde is not None:
            output_data.append([
                _format_float(self.mde), "Median absolute error",
                "Best is 0.0, higher is worse"
            ])
        if self.r2s is not None:
            output_data.append([
                _format_float(self.r2s), "R2 Score",
                "Best is 1.0, lower is worse"
            ])
        table = Table(output_data)
        table.title = "Report"
        if self.label:
            table.title += ": " + self.label
        return table.table
예제 #15
0
파일: cmedb.py 프로젝트: 0xe7/CrackMapExec
 def print_table(self, data, title=None):
     print ""
     table = AsciiTable(data)
     if title:
         table.title = title
     print table.table
     print ""
예제 #16
0
    async def _print_hosts(self, hosts, table_title=None):
        table_data = [["Id", "IP", "Hostname", "Discovered Services", "Matched Signature(s)"]]

        async with ScanDatabase(connection=self.db) as db:
            for entry in hosts:
                host_id, hostname, ip = entry
                service_count = await db.get_service_count_on_host(host_id)
                matched_sigs = map(
                    lambda x: x[0].split(','), 
                    filter(
                        lambda x: x[0] is not None, 
                        await db.get_matched_sigs_on_host(host_id)
                    )
                )

                table_data.append([
                    host_id,
                    ip,
                    hostname,
                    service_count,
                    ','.join(set(sig_name for result in matched_sigs for sig_name in result))
                ])

        table = AsciiTable(table_data)
        table.inner_row_border = True
        table.title = table_title
        print(table.table)
예제 #17
0
    def handle(self, *args, **options):
        # for task in options['new_task']:
        now = SRRS.roundToNearestHour(timezone.now())
        tasks = crud.readUndoneTasks()
        blocked = crud.readBlocked(now)
        taskList = list()
        for t in tasks:
            taskList.append(t)

        blockedList = list()
        for b in blocked:
            blockedList.append(b)

        current_time = now
        schedule = SRRS.scheduleTasks(taskList, current_time, blockedList)

        table_data = [[
            "id", "Task Name", "Start Time(yyyy-mm-dd HH:MM:SS)",
            "End Time(yyyy-mm-dd HH:MM:SS)", "Duration (minutes)"
        ]]
        for s in schedule:
            table_data.append([
                str(s.id), s.task.name,
                str(s.start_time),
                str(s.end_time),
                str((s.end_time - s.start_time).total_seconds() / 60)
            ])

        table = AsciiTable(table_data)
        table.title = "Schedule"
        print(table.table)

        self.stdout.write(self.style.SUCCESS("Successfully saved task"))
예제 #18
0
 def print_table(self, data, title=None):
     print ""
     table = AsciiTable(data)
     if title:
         table.title = title
     print table.table
     print ""
예제 #19
0
 def __repr__(self):
     table_data = []
     table_data.append(SysCall._repr_header)
     table_data.append(self._get_table_rep_row())
     table = AsciiTable(table_data)
     table.title = 'SysCall ({})'.format(self.start_timestamp)
     return table.table
예제 #20
0
def display_data(data, logger, db_title=None, headers=''):
    # Display data in ascii table format
    if data:
        table = AsciiTable(headers + data)
        if db_title:
            table.title = db_title
        logger.output(table.table)
예제 #21
0
def printToTable(title, datas):
    tableDatas = []
    if ('第一區' in datas[0] and '第二區' in datas[0]):
        tableDatas.append(['期別', '開獎日期', '第一區', '第二區'])
    elif ('獎號' in datas[0] and '特別號' in datas[0]):
        tableDatas.append(['期別', '開獎日期', '獎號', '特別號'])
    else:
        tableDatas.append(['期別', '開獎日期', '獎號'])
    for i in range(len(datas)):
        if ('第一區' in datas[0] and '第二區' in datas[0]):
            tableDatas.append([
                datas[i]['期別'], datas[i]['開獎日期'], datas[i]['第一區'],
                datas[i]['第二區']
            ])
        elif ('獎號' in datas[0] and '特別號' in datas[0]):
            tableDatas.append([
                datas[i]['期別'], datas[i]['開獎日期'], datas[i]['獎號'],
                datas[i]['特別號']
            ])
        else:
            tableDatas.append(
                [datas[i]['期別'], datas[i]['開獎日期'], datas[i]['獎號']])
    table = AsciiTable(tableDatas)
    table.title = title
    print(table.table)
    print('\n')
예제 #22
0
    def v2_playbook_on_stats(self, stats):
        output = ""

        hosts = sorted(stats.processed.keys())
        for h in hosts:
            t = stats.summarize(h)

            output += u"%s : %s %s %s %s %s %s %s %s" % (
                hostcolor(h, t), colorize(u'ok', t['ok'], C.COLOR_OK),
                colorize(u'changed', t['changed'], C.COLOR_CHANGED),
                colorize(u'unreachable', t['unreachable'],
                         C.COLOR_UNREACHABLE),
                colorize(u'failed', t['failures'], C.COLOR_ERROR),
                colorize(u'skipped', t['skipped'], C.COLOR_SKIP),
                colorize(u'rescued', t['rescued'], C.COLOR_OK),
                colorize(u'ignored', t['ignored'],
                         C.COLOR_WARN), self.carriage_return)

            self._display.display(u"%s : %s %s %s %s %s %s %s" % (
                hostcolor(h, t, False),
                colorize(u'ok', t['ok'], None),
                colorize(u'changed', t['changed'], None),
                colorize(u'unreachable', t['unreachable'], None),
                colorize(u'failed', t['failures'], None),
                colorize(u'skipped', t['skipped'], None),
                colorize(u'rescued', t['rescued'], None),
                colorize(u'ignored', t['ignored'], None),
            ),
                                  log_only=True)

        # print custom stats if required
        if False:
            #        if stats.custom: # and self.show_custom_stats:
            self.banner("CUSTOM STATS: ")
            # per host
            # TODO: come up with 'pretty format'
            for k in sorted(stats.custom.keys()):
                if k == '_run':
                    continue
                output += "\t%s: %s %s" % (
                    k, self._dump_results(stats.custom[k], indent=1).replace(
                        '\n', ''), self.carriage_return)

            # print per run custom stats
            if '_run' in stats.custom:
                output += self.carriage_return
                output += "\tRUN: %s %s" % (self._dump_results(
                    stats.custom['_run'], indent=1).replace(
                        '\n', ''), self.carriage_return)
            output += self.carriage_return

        table_data = [
            [output],
        ]
        statsTable = AsciiTable(table_data)
        statsTable.title = "Play Recap"
        self._display.display("")
        self._display.display(statsTable.table, screen_only=True)
        self._display.display("")
예제 #23
0
def display_data(data, logger, db_title=None, headers=''):
    if data:
        table = AsciiTable(headers + data)
        if db_title:
            table.title = db_title
        logger.output(table.table)
    else:
        logger.warning("No data returned, get to work!\n")
예제 #24
0
 def summary(syscalls):
     table_data = []
     table_data.append(SysCall._repr_header)
     for syscall in syscalls:
         table_data.append(syscall._get_table_rep_row())
     table = AsciiTable(table_data)
     table.title = 'System Calls ({})'.format(len(syscalls))
     return table.table
예제 #25
0
    def source_table(self, service_focus=True):

        table_header = ["Dst Zones", "Dst Addresses", "Services", "Action"]
        table_data = [table_header] + self._table_rows(
            self.source_lookup_object, True, service_focus)
        table = AsciiTable(table_data)
        table.title = "Effective Policy: " + self.target + " as source"

        return table.table
예제 #26
0
    def destination_table(self, service_focus=True):

        table_header = ["Src Zones", "Src Addresses", "Services", "Action"]
        table_data = [table_header] + self._table_rows(
            self.destination_lookup_object, False, service_focus)
        table = AsciiTable(table_data)
        table.title = "Effective Policy: " + self.target + " as destination"

        return table.table
예제 #27
0
 def print_results(self, headers, rows):
     limit = self.args.limit if self.args.limit < len(rows) else len(rows)
     data = [headers] + [[getattr(row, x) for x in headers if hasattr(row,x)] for row in rows]
     table = AsciiTable(data)
     table.title = "Possible Matche(s)"
     table.inner_row_border = True
     print(table.table)
     output = 'Total : {0}'.format(len(data) - 1)
     print(output)
예제 #28
0
 def frameTable():
     frameTableP1 = [
     [],['Frame#', 'Process#', 'Page#'],
     [('\n'.join(map(str,range(16)))),('\n'.join(map(str,[j[1][0] for j in zipFrame]))),
     (('\n'.join(map(str,[l[1][1] for l in zipFrame]))))]
     ]
     table1 = AsciiTable(frameTableP1)
     table1.title='--------FRAME TABLE'
     print table1.table
예제 #29
0
파일: cli.py 프로젝트: oracle/oracle-linux
def list_market(ctx):
    oci = ctx.obj['oci']
    listings = oci.list_market()
    if listings:
        table = AsciiTable([('Publisher', 'Name')] + listings)
        table.title = 'Free Marketplace images'
        click.echo(table.table)
    else:
        click.echo('No image found', err=True)
예제 #30
0
파일: cli.py 프로젝트: oracle/oracle-linux
def list_custom(ctx, compartment_id):
    oci = ctx.obj['oci']
    images = oci.list_custom(compartment_id)
    if images:
        table = AsciiTable([('Display name', 'Time created')] + images)
        table.title = 'Custom images'
        click.echo(table.table)
    else:
        click.echo('No image found', err=True)
예제 #31
0
def callback(msg, has_printed):
    """Callback function called by libnl upon receiving messages from the kernel.

    Positional arguments:
    msg -- nl_msg class instance containing the data sent by the kernel.
    has_printed -- simple pseudo boolean (if list is empty) to keep track of when to print emtpy lines.

    Returns:
    An integer, value of NL_SKIP. It tells libnl to stop calling other callbacks for this message and proceed with
    processing the next kernel message.
    """
    table = AsciiTable([['Data Type', 'Data Value']])
    # First convert `msg` into something more manageable.
    gnlh = genlmsghdr(nlmsg_data(nlmsg_hdr(msg)))

    # Partially parse the raw binary data and place them in the `tb` dictionary.
    tb = dict((i, None) for i in range(nl80211.NL80211_ATTR_MAX + 1))  # Need to populate dict with all possible keys.
    nla_parse(tb, nl80211.NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), None)

    # Now it's time to grab the juicy data!
    if tb[nl80211.NL80211_ATTR_IFNAME]:
        table.title = nla_get_string(tb[nl80211.NL80211_ATTR_IFNAME]).decode('ascii')
    else:
        table.title = 'Unnamed Interface'

    if tb[nl80211.NL80211_ATTR_WIPHY]:
        wiphy_num = nla_get_u32(tb[nl80211.NL80211_ATTR_WIPHY])
        wiphy = ('wiphy {0}' if OPTIONS['<interface>'] else 'phy#{0}').format(wiphy_num)
        table.table_data.append(['NL80211_ATTR_WIPHY', wiphy])

    if tb[nl80211.NL80211_ATTR_MAC]:
        mac_address = ':'.join(format(x, '02x') for x in nla_data(tb[nl80211.NL80211_ATTR_MAC])[:6])
        table.table_data.append(['NL80211_ATTR_MAC', mac_address])

    if tb[nl80211.NL80211_ATTR_IFINDEX]:
        table.table_data.append(['NL80211_ATTR_IFINDEX', str(nla_get_u32(tb[nl80211.NL80211_ATTR_IFINDEX]))])

    # Print all data.
    if has_printed:
        print()
    else:
        has_printed.append(True)
    print(table.table)
    return NL_SKIP
예제 #32
0
파일: cli.py 프로젝트: oracle/oracle-linux
def list_platform(ctx, compartment_id):
    oci = ctx.obj['oci']
    images = oci.list_platform(compartment_id)
    if images:
        table = AsciiTable([('Operating System', 'Operating System version')] +
                           images)
        table.title = 'Platform images'
        click.echo(table.table)
    else:
        click.echo('No image found', err=True)
예제 #33
0
파일: program.py 프로젝트: anti4ever/MMP
 def info(self):
     table_data = [
     ['H слоя, м', 'plotn_sk', 'w_tot', 'w_w', 'lambda_t', 'lanbda_m','tfi'],
     [str(self.z), str(self.plotn_sk), str(self.w_tot), str(self.w_w), str(self.lambda_t), str(self.lambda_m), str(self.tfi)],
     ['lambda_ef', 'ps_i', 'tc', 'beta', 'alfa', '-|-','-|-'],
     ['lambda_ef', 'ps_i', 'tc', 'beta', 'alfa', '-|-','-|-']   #Значения
     ]
     table = AsciiTable(table_data)
     table.title = 'Интервал '+str(self.number)
     print (table.table)
예제 #34
0
    async def _print_services(self, services, table_title=None):
        table_data = [["Id", "URL", "Title", "Server", "Matched Signature(s)"]]
        for entry in services:
            service_id, url, _, _, _, title, server, _, _, matched_sigs, _ = entry
            table_data.append([service_id, url, title, server, matched_sigs])

        table = AsciiTable(table_data)
        table.inner_row_border = True
        table.title = table_title
        print(table.table)
예제 #35
0
    def printOut(self):
        # Again we loop over to get the most common(n) values and print this in a table
        for key, value in self.dataList.items():
            collection = collections.Counter(
                self.dataList[key]).most_common(10)

            tableData = AsciiTable(collection)
            tableData.inner_heading_row_border = False
            tableData.title = key
            print(tableData.table)
예제 #36
0
        def pTable5():
            ####process table p5
            pageTableP5 = [[],
            ['Page #', 'Frame#'],
            [('\n'.join(map(str,newP5))),

            ('\n'.join(map(str,([i for i,c in enumerate(zipFrame) if c[1][0]=='P5:'   ]))))]
            ]
            table5 = AsciiTable(pageTableP5)
            table5.title='---P5 Page Table'
            print table5.table
예제 #37
0
        def pTable1():
            ####process table p1
            pageTableP1 = [[],
            ['Page #', 'Frame#'],
            [('\n'.join(map(str,newP1))),

            ('\n'.join(map(str,([i for i,c in enumerate(zipFrame) if c[1][0]=='P1:'   ]))))]
            ]
            table = AsciiTable(pageTableP1)
            table.title='---P1 Page Table'
            print table.table
예제 #38
0
        def pTable2():
            ####process table p2
            pageTableP2 = [[],
            ['Page #', 'Frame#'],
            [('\n'.join(map(str,newP2))),

            ('\n'.join(map(str,([i for i,c in enumerate(zipFrame) if c[1][0]=='P2:'   ]))))]
            ]
            table2 = AsciiTable(pageTableP2)
            table2.title='---P2 Page Table'
            print table2.table
예제 #39
0
        def pTable3():
            ####process table p3
            pageTableP3 = [[],
            ['Page #', 'Frame#'],
            [('\n'.join(map(str,newP3))),

            ('\n'.join(map(str,([i for i,c in enumerate(zipFrame) if c[1][0]=='P3:'   ]))))]
            ]
            table3 = AsciiTable(pageTableP3)
            table3.title='---P3 Page Table'
            print table3.table
예제 #40
0
        def pTable4():
            ####process table p4
            pageTableP4 = [[],
            ['Page #', 'Frame#'],
            [('\n'.join(map(str,newP4))),

            ('\n'.join(map(str,([i for i,c in enumerate(zipFrame) if c[1][0]=='P4:'   ]))))]
            ]
            table4 = AsciiTable(pageTableP4)
            table4.title='---4 Page Table'
            print table4.table
예제 #41
0
def output_ascii_table(table_title=None,
                       table_data=None,
                       inner_heading_row_border=False,
                       inner_footing_row_border=False,
                       inner_row_border=False):
    """
    @type table_title: unicode
    @type table_data: list
    @type inner_heading_row_border: bool
    @type inner_footing_row_border: bool
    @type inner_row_border: bool
    """
    table = AsciiTable(table_data)
    table.inner_heading_row_border = inner_heading_row_border
    table.inner_row_border = inner_row_border
    table.inner_footing_row_border = inner_footing_row_border
    table.title = table_title
    print(table.table)
예제 #42
0
파일: injections.py 프로젝트: sepal/compose
    def info(self, options):
        """
        Display service status information.

        Usage: info
        """

        from terminaltables import AsciiTable
        rows = []

        for key, value in self.project.info().iteritems():
            rows.append([key + ':', value])

        table = AsciiTable(rows)
        table.outer_border = False
        table.inner_column_border = False
        table.inner_heading_row_border = False
        table.title = 'Dork status information'
        print table.table
예제 #43
0
def test_attributes():
    """Test table attributes."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
        ['Watermelon', 'green']
    ]
    table = AsciiTable(table_data)

    table.justify_columns[0] = 'right'
    expected = dedent("""\
        +------------+-------+-----------+
        |       Name | Color | Type      |
        +------------+-------+-----------+
        |    Avocado | green | nut       |
        |     Tomato | red   | fruit     |
        |    Lettuce | green | vegetable |
        | Watermelon | green |           |
        +------------+-------+-----------+""")
    assert expected == table.table

    table.justify_columns[2] = 'center'
    expected = dedent("""\
        +------------+-------+-----------+
        |       Name | Color |    Type   |
        +------------+-------+-----------+
        |    Avocado | green |    nut    |
        |     Tomato | red   |   fruit   |
        |    Lettuce | green | vegetable |
        | Watermelon | green |           |
        +------------+-------+-----------+""")
    assert expected == table.table

    table.inner_heading_row_border = False
    expected = dedent("""\
        +------------+-------+-----------+
        |       Name | Color |    Type   |
        |    Avocado | green |    nut    |
        |     Tomato | red   |   fruit   |
        |    Lettuce | green | vegetable |
        | Watermelon | green |           |
        +------------+-------+-----------+""")
    assert expected == table.table

    table.title = 'Foods'
    table.inner_column_border = False
    expected = dedent("""\
        +Foods-------------------------+
        |       Name  Color     Type   |
        |    Avocado  green     nut    |
        |     Tomato  red      fruit   |
        |    Lettuce  green  vegetable |
        | Watermelon  green            |
        +------------------------------+""")
    assert expected == table.table

    table.outer_border = False
    expected = (
        '       Name  Color     Type   \n'
        '    Avocado  green     nut    \n'
        '     Tomato  red      fruit   \n'
        '    Lettuce  green  vegetable \n'
        ' Watermelon  green            '
    )
    assert expected == table.table

    table.outer_border = True
    table.inner_row_border = True
    expected = dedent("""\
        +Foods-------------------------+
        |       Name  Color     Type   |
        +------------------------------+
        |    Avocado  green     nut    |
        +------------------------------+
        |     Tomato  red      fruit   |
        +------------------------------+
        |    Lettuce  green  vegetable |
        +------------------------------+
        | Watermelon  green            |
        +------------------------------+""")
    assert expected == table.table

    table.title = False
    table.inner_column_border = True
    table.inner_heading_row_border = False  # Ignored due to inner_row_border.
    table.inner_row_border = True
    expected = dedent("""\
        +------------+-------+-----------+
        |       Name | Color |    Type   |
        +------------+-------+-----------+
        |    Avocado | green |    nut    |
        +------------+-------+-----------+
        |     Tomato | red   |   fruit   |
        +------------+-------+-----------+
        |    Lettuce | green | vegetable |
        +------------+-------+-----------+
        | Watermelon | green |           |
        +------------+-------+-----------+""")
    assert expected == table.table

    table.outer_border = False
    expected = (
        '       Name | Color |    Type   \n'
        '------------+-------+-----------\n'
        '    Avocado | green |    nut    \n'
        '------------+-------+-----------\n'
        '     Tomato | red   |   fruit   \n'
        '------------+-------+-----------\n'
        '    Lettuce | green | vegetable \n'
        '------------+-------+-----------\n'
        ' Watermelon | green |           '
    )
    assert expected == table.table
예제 #44
0
            z =  zip(n,x)
            p.append(z)

            print (pageNum, "added to P1 page table")
        frm = map(str,x)


#terminaltable print#
    pageTableP1 = [[],
    ['Page #', 'Frame#'],
    [('\n'.join(map(str,x))),
    ('\n'.join(map(str,(i for i,x in enumerate(frm)))))]
    ]
    table = AsciiTable(pageTableP1)

    table.title='---P1 Page Table'
    print table.table



    frameTableP1 = [
    [],['Frame#', 'Process#', 'Page#'],
    [('\n'.join(map(str,frameTable))),('\n'.join(map(str,n))), (('\n'.join(map(str,x)))) ]
    ]
    table1 = AsciiTable(frameTableP1)
    table1.title='--------FRAME TABLE'
    print table1.table
#    pp.pprint(d['P2:'])
    validBitP2 = [1]*len(d['P2:'])
    resBitP2 = [0]*len(d['P2:'])
    zippedP2 = zip(d['P2:'], validBitP2, resBitP2)
예제 #45
0
        damage, hit, base_delay = parts[2:5]

    # find weapon sizes
    if re.match('.*SIZE_.*SIZE_', line):
        # skip long gone items
        if 'old ' in title[0:4]:
            continue
        parts = [x.strip() for x in line.split(',')]
        double_hand, single_hand = parts[1:3]
        min_delay = calc_min_delay(base_delay)
        skill_required = calc_skill_required(base_delay, min_delay)
        th = parse_2h_size(double_hand, parse_1h_size(single_hand), parts[0])
        table_data.append([title, damage, hit, base_delay, min_delay, skill_required, th])

# table_data = sorted(table_data, key=lambda x: x[0])
table_data.insert(0, header)
table_data.append(header)

table = AsciiTable(table_data)
table.title = table_title
table.inner_footing_row_border = True
table.justify_columns[1] = 'right'
table.justify_columns[2] = 'right'
table.justify_columns[3] = 'right'
table.justify_columns[4] = 'right'
table.justify_columns[5] = 'right'

print(table.table)
print('\r')
print('Last generated on {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))