Format table to print out
435524
def format(self):
        ''' 
        '''
        self.max_lengths = []
        for row in self.rows:
            if len(self.max_lengths) < len(row):
                self.max_lengths += [0] * (len(row) - len(self.max_lengths))
            for idx, val in enumerate(row):
                len_cell = len(str(val)) if val else 0
                if self.max_lengths[idx] < len_cell:
                    self.max_lengths[idx] = len_cell
        return self.max_lengths
157544
def print_table(columns, formatter)
      columns.transpose.each { |row| puts sprintf(formatter, *row) }
    end
378091
def _format_cell(val, colkeywords):
    
    out=""

    # String arrays are returned as dict, undo that for printing
    if isinstance(val, dict):
        tmpdict=numpy.array(val['array'])
        tmpdict.reshape(val['shape'])
        # Leave out quotes around strings
        numpy.set_printoptions(formatter={'all':lambda x: str(x)})
        out+=numpy.array2string(tmpdict, separator=', ')
        # Revert previous numpy print options
        numpy.set_printoptions(formatter=None)
    else:
        valtype='other'

        # Check if the column unit is like 'm' or ['m','m','m']
        singleUnit=('QuantumUnits' in colkeywords and
                    (numpy.array(colkeywords['QuantumUnits'])==numpy.array(colkeywords['QuantumUnits'])[0]).all())
        if colkeywords.get('MEASINFO',{}).get('type')=='epoch' and singleUnit:
            # Format a date/time. Use quanta for scalars, use numpy for array logic around it
            # (quanta does not support higher dimensional arrays)
            valtype='epoch'
            if isinstance(val, numpy.ndarray):
                numpy.set_printoptions(formatter={'all':lambda x: _format_date(x,colkeywords['QuantumUnits'][0])})
                out+=numpy.array2string(val,separator=', ')
                numpy.set_printoptions(formatter=None)
            else:
                out+=_format_date(val,colkeywords['QuantumUnits'][0])
        elif colkeywords.get('MEASINFO',{}).get('type')=='direction' and singleUnit and val.shape==(1,2):
                # Format one direction. TODO: extend to array of directions
                valtype='direction'
                out+="["
                part=quantity(val[0,0],'rad').formatted("TIME",precision=9)
                part=re.sub(r'(\d+):(\d+):(.*)',r'\1h\2m\3',part)
                out+=part+", "
                part=quantity(val[0,1],'rad').formatted("ANGLE",precision=9)
                part=re.sub(r'(\d+)\.(\d+)\.(.*)',r'\1d\2m\3',part)
                out+=part+"]"
        elif isinstance(val, numpy.ndarray) and singleUnit:
            # Format any array with units
            valtype='quanta'
            numpy.set_printoptions(formatter={'all':lambda x: _format_quantum(x, colkeywords['QuantumUnits'][0])})
            out+=numpy.array2string(val,separator=', ')
            numpy.set_printoptions(formatter=None)
        elif isinstance(val, numpy.ndarray):
            valtype='other'
            # Undo quotes around strings
            numpy.set_printoptions(formatter={'all':lambda x: str(x)})
            out+=numpy.array2string(val,separator=', ')
            numpy.set_printoptions(formatter=None)
        elif singleUnit:
            valtype='onequantum'
            out+=_format_quantum(val, colkeywords['QuantumUnits'][0])
        else:
            valtype='other'
            out+=str(val)

    if 'QuantumUnits' in colkeywords and valtype=='other':
        # Print units if they haven't been taken care of
        if not (numpy.array(colkeywords['QuantumUnits'])==numpy.array(colkeywords['QuantumUnits'])[0]).all():
            # Multiple different units for element in an array.
            # For now, just print the units and let the user figure out what it means
            out+=" "+str(colkeywords['QuantumUnits'])
        else:
            out+=" "+colkeywords['QuantumUnits'][0]

    # Numpy sometimes adds double newlines, don't do that
    out=out.replace('\n\n','\n')
    return out
460930
def print_code_table(self, out=sys.stdout):
        
        out.write(u'bits  code       (value)  symbol\n')
        for symbol, (bitsize, value) in sorted(self._table.items()):
            out.write(u'{b:4d}  {c:10} ({v:5d})  {s!r}\n'.format(
                b=bitsize, v=value, s=symbol, c=bin(value)[2:].rjust(bitsize, '0')
            ))
272819
def print_out(self, value, indent=None, format_options=None, asap=False):
        
        if indent is None:
            indent = '>   '

        text = indent + str(value)

        if format_options is None:
            format_options = 'gray'

        if self._style_prints and format_options:

            if not isinstance(format_options, dict):
                format_options = {'color_fg': format_options}

            text = format_print_text(text, **format_options)

        command = 'iprint' if asap else 'print'
        self._set(command, text, multi=True)

        return self
17664
def output(*args, **kwargs):
    '''
    '''
    indent = kwargs.pop('indent', 0)
    sep = kwargs.pop('sep', None)
    kwargs['sep'] = u''  # Sanity
    if sep is None:
        sep = u' '
    indent_str = u' ' * (indent * tab_width)
    text = sep.join(map(str_, args))
    color = kwargs.pop('color', None)
    if color:
        color.bright = kwargs.pop('bright', None)
        text = ColorText(text, color)
    print(indent_str + text, **kwargs)
268091
def do_ls(self, table=None):
        
        if table is None:
            fields = OrderedDict(
                [
                    ("Name", "name"),
                    ("Status", "status"),
                    ("Read", "total_read_throughput"),
                    ("Write", "total_write_throughput"),
                ]
            )
            tables = self.engine.describe_all()
            # Calculate max width of all items for each column
            sizes = [
                1 + max([len(str(getattr(t, f))) for t in tables] + [len(title)])
                for title, f in iteritems(fields)
            ]
            # Print the header
            for size, title in zip(sizes, fields):
                print(title.ljust(size), end="")
            print()
            # Print each table row
            for row_table in tables:
                for size, field in zip(sizes, fields.values()):
                    print(str(getattr(row_table, field)).ljust(size), end="")
                print()
        else:
            print(self.engine.describe(table, refresh=True, metrics=True).pformat())
1132749
def format_output(instances, flag):
    """"""
    out = []
    line_format = '{0}\t{1}\t{2}\t{3}'
    name_len = _get_max_name_len(instances) + 3
    if flag:
        line_format = '{0:<' + str(name_len+5) + '}{1:<16}{2:<65}{3:<16}'

    for i in instances:
        endpoint = "{0}:{1}".format(i['Endpoint']['Address'], i['Endpoint']['Port'])
        out.append(
            line_format.format(i['DBInstanceIdentifier'], i['DBInstanceStatus'], endpoint, i['Engine']))
    return out
804097
def printCols(strlist,cols=5,width=80):

    """"""

    # This may exist somewhere in the Python standard libraries?
    # Should probably rewrite this, it is pretty crude.

    nlines = (len(strlist)+cols-1)//cols
    line = nlines*[""]
    for i in range(len(strlist)):
        c, r = divmod(i,nlines)
        nwid = c*width//cols - len(line[r])
        if nwid>0:
            line[r] = line[r] + nwid*" " + strlist[i]
        else:
            line[r] = line[r] + " " + strlist[i]
    for s in line:
        print(s)
556659
def print_(rows, limit=15, sort='size', order='descending'):
    
    localrows = []
    for row in rows:
        localrows.append(list(row))
    # input validation
    sortby = ['type', '#', 'size']
    if sort not in sortby:
        raise ValueError("invalid sort, should be one of" + str(sortby))
    orders = ['ascending', 'descending']
    if order not in orders:
        raise ValueError("invalid order, should be one of" + str(orders))
    # sort rows
    if sortby.index(sort) == 0:
        if order == "ascending":
            localrows.sort(key=lambda x: _repr(x[0]))
        elif order == "descending":
            localrows.sort(key=lambda x: _repr(x[0]), reverse=True)
    else:
        if order == "ascending":
            localrows.sort(key=lambda x: x[sortby.index(sort)])
        elif order == "descending":
            localrows.sort(key=lambda x: x[sortby.index(sort)], reverse=True)
    # limit rows
    localrows = localrows[0:limit]
    for row in localrows:
        row[2] = stringutils.pp(row[2])
    # print rows
    localrows.insert(0,["types", "# objects", "total size"])
    _print_table(localrows)
1022663
def pretty_print(self):
        """"""
        pt = PrettyTable()
        if len(self) == 0:
            pt._set_field_names(['Sorry,'])
            pt.add_row([TRAIN_NOT_FOUND])
        else:
            pt._set_field_names(self.headers)
            for train in self.trains:
                pt.add_row(train)
        print(pt)
277044
def print_table(document, *columns):
    
    headers = []
    for _, header in columns:
        headers.append(header)
    table = []
    for element in document:
        row = []
        for item, _ in columns:
            if item in element:
                row.append(element[item])
            else:
                row.append(None)
        table.append(row)
    print(tabulate.tabulate(table, headers))
1119804
def table_print(classes, table):
    
    classes_len = len(classes)
    table_list = []
    for key in classes:
        table_list.extend(list(table[key].values()))
    table_list.extend(classes)
    table_max_length = max(map(len, map(str, table_list)))
    shift = "%-" + str(7 + table_max_length) + "s"
    result = shift % "Predict" + shift * \
        classes_len % tuple(map(str, classes)) + "\n"
    result = result + "Actual\n"
    classes.sort()
    for key in classes:
        row = [table[key][i] for i in classes]
        result += shift % str(key) + \
            shift * classes_len % tuple(map(str, row)) + "\n\n"
    if classes_len >= CLASS_NUMBER_THRESHOLD:
        result += "\n" + "Warning : " + CLASS_NUMBER_WARNING + "\n"
    return result
483852
def format_output(instances, flag):
    """"""
    out = []
    line_format = '{0}\t{1}\t{2}\t{3}\t{4}'
    name_len = _get_max_name_len(instances) + 3
    if flag:
        line_format = '{0:<' + str(name_len) + '}{1:<16}{2:<21}{3:<16}{4:<16}'

    for i in instances:
        tag_name = get_tag_value(i.tags, 'Name')
        out.append(line_format.format(
            tag_name, i.state['Name'], i.id, i.private_ip_address, str(i.public_ip_address)))
    return out
34419
def display(self):
        """"""

        table_list = []
        table_list.append(("Text","Orig. Text","Start time","End time", "Phonetic"))
        for unit in self.unit_list:
            table_list.append((unit.text,
                               "/".join(unit.original_text),
                               unit.start_time,
                               unit.end_time,
                               unit.phonetic_representation))
        print_table(table_list)
1035233
def print(self, indent=0):
        """"""
        text = (
            '{indent}{magenta}{name}{none} ({dim}{cls}{none}, '
            'default {dim}{default}{none})'
        ).format(
            indent=' ' * indent,
            dim=Style.DIM,
            magenta=Fore.MAGENTA,
            none=Style.RESET_ALL,
            name=self.name,
            cls=self.cls,
            default=self.default
        )

        if self.description:
            text += ':\n' + pretty_description(self.description,
                                               indent=indent + 2)

        print(text)
833142
def table(*columns, &_block)
      rows = []
      yield(rows)

      # determine maximum cell widths
      max_cell_widths = rows.reduce(Array.new(columns.length, 0)) do |result, row|
        lengths = row.map { |column| column.to_s.length }
        result.each_with_index { |length, index| result[index] = ([length, lengths[index]].max rescue length) }
      end
      columns.each_with_index { |col, index| col[:actual_width] ||= max_cell_widths[index] }

      # determine actual column width
      column_widths = columns.map do |column|
        if column[:width] == :rest
          nil
        elsif column[:width]
          column[:width]
        elsif column[:min_width]
          [column[:min_width], column[:actual_width]].max
        elsif column[:max_width]
          [column[:max_width], column[:actual_width]].min
        else
          column[:actual_width]
        end
      end

      if column_widths.include?(nil)
        width_left = options[:width] - ((columns.length - 1) * (style[:cell_separator] ? 3 : 1)) - column_widths.compact.reduce(0) { |sum, col| sum + col }
        column_widths[column_widths.index(nil)] = width_left
      end

      line(:green) if @style[:top_line]

      # Print table header
      if table_has_header?(columns)
        column_titles = []
        columns.each_with_index do |column, index|
          width = column_widths[index]
          alignment = (column[:align] == :right ? '' : '-')
          column_titles.push(colorize("%#{alignment}#{width}s" % column[:title].to_s[0...width], :bold))
        end

        puts column_titles.join(style[:cell_separator] ? " #{characters[:vertical_line]} " : ' ')
        line(:green)
      end

      # Print the rows
      rows.each do |row|
        row_values = []
        columns.each_with_index do |column, index|
          width = column_widths[index]
          case column[:type]
          when :ratio
            if width > 4
              if column[:treshold] && column[:treshold] < row[index].to_f
                bar = ''
                bar << characters[:block] * (width.to_f * column[:treshold]).round
                bar << colorize(characters[:block] * (width.to_f * (row[index].to_f - column[:treshold])).round, :red)
                row_values.push(bar)
              else
                # Create a bar by combining block characters
                row_values.push(characters[:block] * (width.to_f * row[index].to_f).round)
              end
            else
              # Too few characters for a ratio bar. Display nothing
              row_values.push('')
            end
          else
            alignment = (columns[index][:align] == :right ? '' : '-')
            cell_value = "%#{alignment}#{width}s" % row[index].to_s[0...width]
            cell_value = colorize(cell_value, :bold, :brown) if columns[index][:highlight]
            row_values.push(cell_value)
          end
        end
        puts row_values.join(style[:cell_separator] ? " #{characters[:vertical_line]} " : ' ')
      end
    end