Print a table with a title and a top border of matching width.
501929
def report(title, columns, rows)
      table = capture_table([columns] + rows)
      title = "=== #{title} "
      title << "=" * [(table.split($/).max{|a,b| a.size <=> b.size }.size - title.size), 3].max
      puts title
      puts table
    end
1120683
def pretty_print_list(lst, name = 'features', repr_format=True):
    
    if not lst or len(lst) < 8:
        if repr_format:
            return lst.__repr__()
        else:
            return ', '.join(map(str, lst))
    else:
        topk = ', '.join(map(str, lst[:3]))
        if repr_format:
            lst_separator = "["
            lst_end_separator = "]"
        else:
            lst_separator = ""
            lst_end_separator = ""

        return "{start}{topk}, ... {last}{end} (total {size} {name})".format(\
                topk = topk, last = lst[-1], name = name, size = len(lst),
                start = lst_separator, end = lst_end_separator)
1372541
def print_border_mb row, col, height, width, color, attr
      # the next is for xterm-256 
      att = get_attrib attr
      len = width
      len = Ncurses.COLS-0 if len == 0
      # print a bar across the screen 
      #attron(Ncurses.COLOR_PAIR(color) | att)
      # this works for newmessagebox but not for old one.
      # Even now in some cases some black shows through, if the widget is printing spaces
      # such as field or textview on a messagebox.
      # 2016-01-14 - replacing 1 with space since junk is showing up in some cases.
      space_char = " ".codepoints.first
      (row-1).upto(row+height-1) do |r|
        # this loop clears the screen, printing spaces does not work since ncurses does not do anything
        mvwhline(r, col, space_char, len)
      end
      #attroff(Ncurses.COLOR_PAIR(color) | att)

      mvwaddch row, col, Ncurses::ACS_ULCORNER
      mvwhline( row, col+1, Ncurses::ACS_HLINE, width-6)
      mvwaddch row, col+width-5, Ncurses::ACS_URCORNER
      mvwvline( row+1, col, Ncurses::ACS_VLINE, height-4)

      mvwaddch row+height-3, col, Ncurses::ACS_LLCORNER
      mvwhline(row+height-3, col+1, Ncurses::ACS_HLINE, width-6)
      mvwaddch row+height-3, col+width-5, Ncurses::ACS_LRCORNER
      mvwvline( row+1, col+width-5, Ncurses::ACS_VLINE, height-4)
    end
294753
def show(self):
        
        print("StringBlock(stringsCount=0x%x, "
              "stringsOffset=0x%x, "
              "stylesCount=0x%x, "
              "stylesOffset=0x%x, "
              "flags=0x%x"
              ")" % (self.stringCount,
                     self.stringsOffset,
                     self.styleCount,
                     self.stylesOffset,
                     self.flags))

        if self.stringCount > 0:
            print()
            print("String Table: ")
            for i, s in enumerate(self):
                print("{:08d} {}".format(i, repr(s)))

        if self.styleCount > 0:
            print()
            print("Styles Table: ")
            for i in range(self.styleCount):
                print("{:08d} {}".format(i, repr(self.getStyle(i))))
1184788
def print_vertical(vertical_rows, labels, color, args):
    """"""
    if color:
        sys.stdout.write(f'\033[{color}m') # Start to write colorized.

    for row in vertical_rows:
        print(*row)

    sys.stdout.write('\033[0m') # End of printing colored

    print("-" * len(row) + "Values" + "-" * len(row))
    # Print Values
    for value in zip_longest(*value_list, fillvalue=' '):
        print("  ".join(value))

    if args['no_labels'] == False:
        print("-" * len(row) + "Labels" + "-" * len(row))
        # Print Labels
        for label in zip_longest(*labels, fillvalue=''):
            print("  ".join(label))
94458
def describe_contents(self):
        
        print('======================================================================')
        print(self)
        print('Table  = ',  str(len(self.header)) + ' cols x ' + str(len(self.arr)) + ' rows')
        print('HEADER = ', self.get_header())
        print('arr    = ', self.arr[0:2])
837175
def display(self, typ, data):
        
        if hasattr(self, 'print_' + typ):
            getattr(self, 'print_' + typ)(data)

        elif not data:
            self._print("%s: %s" % (typ, data))

        elif isinstance(data, collections.Mapping):
            self._print("\n", typ)
            for k, v in data.items():
                self.print(k, v)

        elif isinstance(data, (list, tuple)):
            # tabular data layout for lists of dicts
            if isinstance(data[0], collections.Mapping):
                self.display_set(typ, data, self._get_columns(data[0]))
            else:
                for each in data:
                    self.print(typ, each)
        else:
            self._print("%s: %s" % (typ, data))

        self.fobj.flush()
413083
def print_table(rows, override_headers=None, uppercase_headers=True):
    """"""
    if len(rows) == 0:
        return
    keys = list(rows[0].keys())
    headers = override_headers or keys
    if uppercase_headers:
        rows = [dict(zip(keys,
                         map(lambda x: x.upper(), headers))), None] + rows
    else:
        rows = [dict(zip(keys, headers)), None] + rows

    lengths = [max(len(str(row[k]))
                   for row in rows if hasattr(row, '__iter__')) for k in keys]
    tmp = ['{%s:%i}' % (h, l) for h, l in zip(keys[: -1], lengths[: -1])]
    tmp.append('{%s}' % keys[-1])
    template = (' ' * 4).join(tmp)

    for row in rows:
        if type(row) == str:
            print(row)
        elif row is None:
            print()
        elif isinstance(row, dict): 
            row = {k: v if v is not None else 'None' for k, v in row.items()}
            print(template.format(**row))
        else:
            print("Unhandled row type:", row)
358190
def repaint
      return unless @repaint_required
      bc = $datacolor
      bordercolor = @border_color || bc
      borderatt = @border_attrib || Ncurses::A_NORMAL
      @window.print_border row, col, height, width, bordercolor, borderatt
      #print_borders
      print_title
      @repaint_required = false
    end
790475
def indx_table(node_dict, tbl_mode=False):
    """"""
    nt = PrettyTable()
    nt.header = False
    nt.padding_width = 2
    nt.border = False
    clr_num = C_TI + "NUM"
    clr_name = C_TI + "NAME"
    clr_state = "STATE" + C_NORM
    t_lu = {True: [clr_num, "NAME", "REGION", "CLOUD",
                   "SIZE", "PUBLIC IP", clr_state],
            False: [clr_name, "REGION", "CLOUD", "SIZE",
                    "PUBLIC IP", clr_state]}
    nt.add_row(t_lu[tbl_mode])
    for i, node in node_dict.items():
        state = C_STAT[node.state] + node.state + C_NORM
        inum = C_WARN + str(i) + C_NORM
        if node.public_ips:
            n_ip = node.public_ips
        else:
            n_ip = "-"
        r_lu = {True: [inum, node.name, node.zone, node.cloud,
                       node.size, n_ip, state],
                False: [node.name, node.zone, node.cloud,
                        node.size, n_ip, state]}
        nt.add_row(r_lu[tbl_mode])
    if not tbl_mode:
        print(nt)
    else:
        idx_tbl = nt.get_string()
        return idx_tbl
1304060
def straight_line_show(title, length=100, linestyle="=", pad=0):
        
        print(StrTemplate.straight_line(
            title=title, length=length, linestyle=linestyle, pad=pad))
267525
def print_colored_columns(printer, rows, padding=2):
    
    rows_ = [x[:-1] for x in rows]
    colors = [x[-1] for x in rows]
    for col, line in zip(colors, columnise(rows_, padding=padding)):
        printer(line, col)
952635
def printtable(h, header):
    """"""
    hk = header_fields(h)
    if (header):
        printheader()
    writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore')
    writer.writerow(h)
148674
def _display_runner(rows,
                    labels,
                    title,
                    display=_DEFAULT_DISPLAY,
                    outputter=_DEFAULT_OUTPUTTER):
    '''
    
    '''
    if display:
        if outputter == 'table':
            ret = salt.output.out_format({'rows': rows, 'labels': labels},
                                         'table',
                                         __opts__,
                                         title=title,
                                         rows_key='rows',
                                         labels_key='labels')
        else:
            ret = salt.output.out_format(rows,
                                         outputter,
                                         __opts__)
        print(ret)
    else:
        return rows
313439
def table_abcd():
    """"""
    table_instance = SingleTable([['A', 'B'], ['C', 'D']])

    # Get first table lines.
    table_instance.outer_border = False
    table_inner_borders = table_instance.table.splitlines()

    # Get second table lines.
    table_instance.outer_border = True
    table_instance.inner_heading_row_border = False
    table_instance.inner_column_border = False
    table_outer_borders = table_instance.table.splitlines()

    # Combine.
    smallest, largest = sorted([table_inner_borders, table_outer_borders], key=len)
    smallest += [''] * (len(largest) - len(smallest))  # Make both same size.
    combined = list()
    for i, row in enumerate(largest):
        combined.append(row.ljust(10) + '          ' + smallest[i])
    return '\n'.join(combined)
1363281
def _format_table(fmt, headers, rows, colwidths, colaligns):
    """"""
    lines = []
    hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
    pad = fmt.padding
    headerrow = fmt.headerrow

    padded_widths = [(w + 2*pad) for w in colwidths]
    padded_headers = _pad_row(headers, pad)
    padded_rows = [_pad_row(row, pad) for row in rows]

    if fmt.lineabove and "lineabove" not in hidden:
        lines.append(_build_line(padded_widths, colaligns, fmt.lineabove))

    if padded_headers:
        lines.append(_build_row(padded_headers, padded_widths, colaligns, headerrow))
        if fmt.linebelowheader and "linebelowheader" not in hidden:
            lines.append(_build_line(padded_widths, colaligns, fmt.linebelowheader))

    if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden:
        # initial rows with a line below
        for row in padded_rows[:-1]:
            lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))
            lines.append(_build_line(padded_widths, colaligns, fmt.linebetweenrows))
        # the last row without a line below
        lines.append(_build_row(padded_rows[-1], padded_widths, colaligns, fmt.datarow))
    else:
        for row in padded_rows:
            lines.append(_build_row(row, padded_widths, colaligns, fmt.datarow))

    if fmt.linebelow and "linebelow" not in hidden:
        lines.append(_build_line(padded_widths, colaligns, fmt.linebelow))

    return "\n".join(lines)
843789
def capture_table(table)
      return 'none' if table.size == 1 # the first row is for column titles
      $stdout = StringIO.new  # start capturing the output
      print_table(table.map{ |row| row.map(&:to_s) })
      output = $stdout
      $stdout = STDOUT        # restore normal output
      return output.string
    end