Formats a basic impacted resources table
178313
def impacted_table(event):
    """"""
    table = formatting.Table([
        "Type", "Id", "Hostname", "PrivateIp", "Label"
    ])
    for item in event.get('impactedResources', []):
        table.add_row([
            item.get('resourceType'),
            item.get('resourceTableId'),
            item.get('hostname'),
            item.get('privateIp'),
            item.get('filterLabel')
        ])
    return table
12322
def dos_from_table(table, header=None):
    
    start_row = 0
    if not table:
        return table
    if not header:
        header = table[0]
        start_row = 1
    header_list = header
    if header and isinstance(header, basestring):
        header_list = header.split('\t')
        if len(header_list) != len(table[0]):
            header_list = header.split(',')
        if len(header_list) != len(table[0]):
            header_list = header.split(' ')
    ans = {}
    for i, k in enumerate(header):
        ans[k] = [row[i] for row in table[start_row:]]
    return ans
475837
def update_table(event):
    """"""
    update_number = 0
    for update in event.get('updates', []):
        header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate')))
        click.secho(header, fg='green')
        update_number = update_number + 1
        text = update.get('contents')
        # deals with all the \r\n from the API
        click.secho(utils.clean_splitlines(text))
588505
def table_repr(columns, rows, data, padding=2):
    """"""
    padding = ' ' * padding
    column_lengths = [len(column) for column in columns]
    for row in rows:
        for i, column in enumerate(columns):
            item = str(data[row][column])
            column_lengths[i] = max(len(item), column_lengths[i])
    max_row_length = max(len(row) for row in rows) if len(rows) else 0
    table_row = ' ' * max_row_length
    for i, column in enumerate(columns):
        table_row += padding + column.rjust(column_lengths[i])
    table_rows = [table_row]
    for row in rows:
        table_row = row.rjust(max_row_length)
        for i, column in enumerate(columns):
            item = str(data[row][column])
            table_row += padding + item.rjust(column_lengths[i])
        table_rows.append(table_row)
    return '\n'.join(table_rows)
492976
def __format_row(self, row: AssetAllocationViewModel):
        
        output = ""
        index = 0

        # Name
        value = row.name
        # Indent according to depth.
        for _ in range(0, row.depth):
            value = f"   {value}"
        output += self.append_text_column(value, index)

        # Set Allocation
        value = ""
        index += 1
        if row.set_allocation > 0:
            value = f"{row.set_allocation:.2f}"
        output += self.append_num_column(value, index)

        # Current Allocation
        value = ""
        index += 1
        if row.curr_allocation > Decimal(0):
            value = f"{row.curr_allocation:.2f}"
        output += self.append_num_column(value, index)

        # Allocation difference, percentage
        value = ""
        index += 1
        if row.alloc_diff_perc.copy_abs() > Decimal(0):
            value = f"{row.alloc_diff_perc:.0f} %"
        output += self.append_num_column(value, index)

        # Allocated value
        index += 1
        value = ""
        if row.set_value:
            value = f"{row.set_value:,.0f}"
        output += self.append_num_column(value, index)

        # Current Value
        index += 1
        value = f"{row.curr_value:,.0f}"
        output += self.append_num_column(value, index)

        # Value in security's currency. Show only if displaying full model, with stocks.
        index += 1
        if self.full:
            value = ""
            if row.curr_value_own_currency:
                value = f"({row.curr_value_own_currency:,.0f}"
                value += f" {row.own_currency}"
                value += ")"
            output += self.append_num_column(value, index)

        # https://en.wikipedia.org/wiki/ANSI_escape_code
        # CSI="\x1B["
        # red = 31, green = 32
        # output += CSI+"31;40m" + "Colored Text" + CSI + "0m"

        # Value diff
        index += 1
        value = ""
        if row.diff_value:
            value = f"{row.diff_value:,.0f}"
            # Color the output
            # value = f"{CSI};40m{value}{CSI};40m"
        output += self.append_num_column(value, index)

        return output
671344
def _format_list(result):
    """"""

    if not result:
        return result

    if isinstance(result[0], dict):
        return _format_list_objects(result)

    table = Table(['value'])
    for item in result:
        table.add_row([iter_to_table(item)])
    return table
500491
def table_dump(self, table):
        """"""
        if not table: raise ValueError("no table")

        cmds = []
        logger.info('------- dumping table {}'.format(table))
        cmd = self._get_args(
            "pg_dump",
            "--table={}".format(table),
            #"--data-only",
            "--clean",
            "--no-owner",
            "--column-inserts",
        )
        cmds.append((cmd, {}))

        outfile_path = self._get_outfile_path(table)
        cmds.append(('gzip > "{}"'.format(outfile_path), {"shell": True}))

        #cmd += ' | {}'.format(' | '.join(pipes))
        #cmd += ' > {}'.format(outfile_path)

        self._run_cmds(cmds)
        logger.info('------- dumped table {}'.format(table))
        return True
918541
def aks_upgrades_table_format(result):
    """"""
    # pylint: disable=import-error
    from jmespath import compile as compile_jmes, Options

    # This expression assumes there is one node pool, and that the master and nodes upgrade in lockstep.
    parsed = compile_jmes("""{
        name: name,
        resourceGroup: resourceGroup,
        masterVersion: controlPlaneProfile.kubernetesVersion || `unknown`,
        nodePoolVersion: agentPoolProfiles[0].kubernetesVersion || `unknown`,
        upgrades: controlPlaneProfile.upgrades || [`None available`] | sort_versions(@) | join(`, `, @)
    }""")
    # use ordered dicts so headers are predictable
    return parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions()))
1080188
def _format_host(host, data, indent_level=1):
    '''
    
    '''
    host = salt.utils.data.decode(host)

    colors = salt.utils.color.get_colors(
            __opts__.get('color'),
            __opts__.get('color_theme'))
    tabular = __opts__.get('state_tabular', False)
    rcounts = {}
    rdurations = []
    hcolor = colors['GREEN']
    hstrs = []
    nchanges = 0
    strip_colors = __opts__.get('strip_colors', True)

    if isinstance(data, int) or isinstance(data, six.string_types):
        # Data in this format is from saltmod.function,
        # so it is always a 'change'
        nchanges = 1
        hstrs.append(('{0}    {1}{2[ENDC]}'
                      .format(hcolor, data, colors)))
        hcolor = colors['CYAN']  # Print the minion name in cyan
    if isinstance(data, list):
        # Errors have been detected, list them in RED!
        hcolor = colors['LIGHT_RED']
        hstrs.append(('    {0}Data failed to compile:{1[ENDC]}'
                      .format(hcolor, colors)))
        for err in data:
            if strip_colors:
                err = salt.output.strip_esc_sequence(
                    salt.utils.data.decode(err)
                )
            hstrs.append(('{0}----------\n    {1}{2[ENDC]}'
                          .format(hcolor, err, colors)))
    if isinstance(data, dict):
        # Verify that the needed data is present
        data_tmp = {}
        for tname, info in six.iteritems(data):
            if isinstance(info, dict) and tname is not 'changes' and info and '__run_num__' not in info:
                err = ('The State execution failed to record the order '
                       'in which all states were executed. The state '
                       'return missing data is:')
                hstrs.insert(0, pprint.pformat(info))
                hstrs.insert(0, err)
            if isinstance(info, dict) and 'result' in info:
                data_tmp[tname] = info
        data = data_tmp
        # Everything rendered as it should display the output
        for tname in sorted(
                data,
                key=lambda k: data[k].get('__run_num__', 0)):
            ret = data[tname]
            # Increment result counts
            rcounts.setdefault(ret['result'], 0)
            rcounts[ret['result']] += 1
            rduration = ret.get('duration', 0)
            try:
                rdurations.append(float(rduration))
            except ValueError:
                rduration, _, _ = rduration.partition(' ms')
                try:
                    rdurations.append(float(rduration))
                except ValueError:
                    log.error('Cannot parse a float from duration %s', ret.get('duration', 0))

            tcolor = colors['GREEN']
            if ret.get('name') in ['state.orch', 'state.orchestrate', 'state.sls']:
                nested = output(ret['changes']['return'], indent_level=indent_level+1)
                ctext = re.sub('^', ' ' * 14 * indent_level, '\n'+nested, flags=re.MULTILINE)
                schanged = True
                nchanges += 1
            else:
                schanged, ctext = _format_changes(ret['changes'])
                nchanges += 1 if schanged else 0

            # Skip this state if it was successful & diff output was requested
            if __opts__.get('state_output_diff', False) and \
               ret['result'] and not schanged:
                continue

            # Skip this state if state_verbose is False, the result is True and
            # there were no changes made
            if not __opts__.get('state_verbose', False) and \
               ret['result'] and not schanged:
                continue

            if schanged:
                tcolor = colors['CYAN']
            if ret['result'] is False:
                hcolor = colors['RED']
                tcolor = colors['RED']
            if ret['result'] is None:
                hcolor = colors['LIGHT_YELLOW']
                tcolor = colors['LIGHT_YELLOW']

            state_output = __opts__.get('state_output', 'full').lower()
            comps = tname.split('_|-')

            if state_output.endswith('_id'):
                # Swap in the ID for the name. Refs #35137
                comps[2] = comps[1]

            if state_output.startswith('filter'):
                # By default, full data is shown for all types. However, return
                # data may be excluded by setting state_output_exclude to a
                # comma-separated list of True, False or None, or including the
                # same list with the exclude option on the command line. For
                # now, this option must include a comma. For example:
                #     exclude=True,
                # The same functionality is also available for making return
                # data terse, instead of excluding it.
                cliargs = __opts__.get('arg', [])
                clikwargs = {}
                for item in cliargs:
                    if isinstance(item, dict) and '__kwarg__' in item:
                        clikwargs = item.copy()

                exclude = clikwargs.get(
                    'exclude', __opts__.get('state_output_exclude', [])
                )
                if isinstance(exclude, six.string_types):
                    exclude = six.text_type(exclude).split(',')

                terse = clikwargs.get(
                    'terse', __opts__.get('state_output_terse', [])
                )
                if isinstance(terse, six.string_types):
                    terse = six.text_type(terse).split(',')

                if six.text_type(ret['result']) in terse:
                    msg = _format_terse(tcolor, comps, ret, colors, tabular)
                    hstrs.append(msg)
                    continue
                if six.text_type(ret['result']) in exclude:
                    continue

            elif any((
                state_output.startswith('terse'),
                state_output.startswith('mixed') and ret['result'] is not False,  # only non-error'd
                state_output.startswith('changes') and ret['result'] and not schanged  # non-error'd non-changed
            )):
                # Print this chunk in a terse way and continue in the loop
                msg = _format_terse(tcolor, comps, ret, colors, tabular)
                hstrs.append(msg)
                continue

            state_lines = [
                '{tcolor}----------{colors[ENDC]}',
                '    {tcolor}      ID: {comps[1]}{colors[ENDC]}',
                '    {tcolor}Function: {comps[0]}.{comps[3]}{colors[ENDC]}',
                '    {tcolor}  Result: {ret[result]!s}{colors[ENDC]}',
                '    {tcolor} Comment: {comment}{colors[ENDC]}',
            ]
            if __opts__.get('state_output_profile', True) and 'start_time' in ret:
                state_lines.extend([
                    '    {tcolor} Started: {ret[start_time]!s}{colors[ENDC]}',
                    '    {tcolor}Duration: {ret[duration]!s}{colors[ENDC]}',
                ])
            # This isn't the prettiest way of doing this, but it's readable.
            if comps[1] != comps[2]:
                state_lines.insert(
                    3, '    {tcolor}    Name: {comps[2]}{colors[ENDC]}')
            # be sure that ret['comment'] is utf-8 friendly
            try:
                if not isinstance(ret['comment'], six.text_type):
                    ret['comment'] = six.text_type(ret['comment'])
            except UnicodeDecodeError:
                # If we got here, we're on Python 2 and ret['comment'] somehow
                # contained a str type with unicode content.
                ret['comment'] = salt.utils.stringutils.to_unicode(ret['comment'])
            try:
                comment = salt.utils.data.decode(ret['comment'])
                comment = comment.strip().replace(
                        '\n',
                        '\n' + ' ' * 14)
            except AttributeError:  # Assume comment is a list
                try:
                    comment = ret['comment'].join(' ').replace(
                        '\n',
                        '\n' + ' ' * 13)
                except AttributeError:
                    # Comment isn't a list either, just convert to string
                    comment = six.text_type(ret['comment'])
                    comment = comment.strip().replace(
                        '\n',
                        '\n' + ' ' * 14)
            # If there is a data attribute, append it to the comment
            if 'data' in ret:
                if isinstance(ret['data'], list):
                    for item in ret['data']:
                        comment = '{0} {1}'.format(comment, item)
                elif isinstance(ret['data'], dict):
                    for key, value in ret['data'].items():
                        comment = '{0}\n\t\t{1}: {2}'.format(comment, key, value)
                else:
                    comment = '{0} {1}'.format(comment, ret['data'])
            for detail in ['start_time', 'duration']:
                ret.setdefault(detail, '')
            if ret['duration'] != '':
                ret['duration'] = '{0} ms'.format(ret['duration'])
            svars = {
                'tcolor': tcolor,
                'comps': comps,
                'ret': ret,
                'comment': salt.utils.data.decode(comment),
                # This nukes any trailing \n and indents the others.
                'colors': colors
            }
            hstrs.extend([sline.format(**svars) for sline in state_lines])
            changes = '     Changes:   ' + ctext
            hstrs.append(('{0}{1}{2[ENDC]}'
                          .format(tcolor, changes, colors)))

            if 'warnings' in ret:
                rcounts.setdefault('warnings', 0)
                rcounts['warnings'] += 1
                wrapper = textwrap.TextWrapper(
                    width=80,
                    initial_indent=' ' * 14,
                    subsequent_indent=' ' * 14
                )
                hstrs.append(
                    '   {colors[LIGHT_RED]} Warnings: {0}{colors[ENDC]}'.format(
                        wrapper.fill('\n'.join(ret['warnings'])).lstrip(),
                        colors=colors
                    )
                )

        # Append result counts to end of output
        colorfmt = '{0}{1}{2[ENDC]}'
        rlabel = {True: 'Succeeded', False: 'Failed', None: 'Not Run', 'warnings': 'Warnings'}
        count_max_len = max([len(six.text_type(x)) for x in six.itervalues(rcounts)] or [0])
        label_max_len = max([len(x) for x in six.itervalues(rlabel)] or [0])
        line_max_len = label_max_len + count_max_len + 2  # +2 for ': '
        hstrs.append(
            colorfmt.format(
                colors['CYAN'],
                '\nSummary for {0}\n{1}'.format(host, '-' * line_max_len),
                colors
            )
        )

        def _counts(label, count):
            return '{0}: {1:>{2}}'.format(
                label,
                count,
                line_max_len - (len(label) + 2)
            )

        # Successful states
        changestats = []
        if None in rcounts and rcounts.get(None, 0) > 0:
            # test=True states
            changestats.append(
                colorfmt.format(
                    colors['LIGHT_YELLOW'],
                    'unchanged={0}'.format(rcounts.get(None, 0)),
                    colors
                )
            )
        if nchanges > 0:
            changestats.append(
                colorfmt.format(
                    colors['GREEN'],
                    'changed={0}'.format(nchanges),
                    colors
                )
            )
        if changestats:
            changestats = ' ({0})'.format(', '.join(changestats))
        else:
            changestats = ''
        hstrs.append(
            colorfmt.format(
                colors['GREEN'],
                _counts(
                    rlabel[True],
                    rcounts.get(True, 0) + rcounts.get(None, 0)
                ),
                colors
            ) + changestats
        )

        # Failed states
        num_failed = rcounts.get(False, 0)
        hstrs.append(
            colorfmt.format(
                colors['RED'] if num_failed else colors['CYAN'],
                _counts(rlabel[False], num_failed),
                colors
            )
        )

        num_warnings = rcounts.get('warnings', 0)
        if num_warnings:
            hstrs.append(
                colorfmt.format(
                    colors['LIGHT_RED'],
                    _counts(rlabel['warnings'], num_warnings),
                    colors
                )
            )
        totals = '{0}\nTotal states run: {1:>{2}}'.format('-' * line_max_len,
                                               sum(six.itervalues(rcounts)) - rcounts.get('warnings', 0),
                                               line_max_len - 7)
        hstrs.append(colorfmt.format(colors['CYAN'], totals, colors))

        if __opts__.get('state_output_profile', True):
            sum_duration = sum(rdurations)
            duration_unit = 'ms'
            # convert to seconds if duration is 1000ms or more
            if sum_duration > 999:
                sum_duration /= 1000
                duration_unit = 's'
            total_duration = 'Total run time: {0} {1}'.format(
                '{0:.3f}'.format(sum_duration).rjust(line_max_len - 5),
                duration_unit)
            hstrs.append(colorfmt.format(colors['CYAN'], total_duration, colors))

    if strip_colors:
        host = salt.output.strip_esc_sequence(host)
    hstrs.insert(0, ('{0}{1}:{2[ENDC]}'.format(hcolor, host, colors)))
    return '\n'.join(hstrs), nchanges > 0
160748
def _format_list_objects(result):
    """"""

    all_keys = set()
    for item in result:
        all_keys = all_keys.union(item.keys())

    all_keys = sorted(all_keys)
    table = Table(all_keys)

    for item in result:
        values = []
        for key in all_keys:
            value = iter_to_table(item.get(key))
            values.append(value)

        table.add_row(values)

    return table
1207518
def create_tables(name, runSetResults, rows, rowsDiff, outputPath, outputFilePattern, options):
    '''
    
    '''

    # get common folder of sourcefiles
    common_prefix = os.path.commonprefix([r.filename for r in rows]) # maybe with parts of filename
    common_prefix = common_prefix[: common_prefix.rfind('/') + 1] # only foldername
    for row in rows:
        Row.set_relative_path(row, common_prefix, outputPath)

    # compute nice name of each run set for displaying
    firstBenchmarkName = Util.prettylist(runSetResults[0].attributes['benchmarkname'])
    allBenchmarkNamesEqual = all(Util.prettylist(r.attributes['benchmarkname']) == firstBenchmarkName for r in runSetResults)
    for r in runSetResults:
        if not r.attributes['name']:
            r.attributes['niceName'] = r.attributes['benchmarkname']
        elif allBenchmarkNamesEqual:
            r.attributes['niceName'] = r.attributes['name']
        else:
            r.attributes['niceName'] = [Util.prettylist(r.attributes['benchmarkname']) + '.' + Util.prettylist(r.attributes['name'])]

    template_values = lambda: None # dummy object as dict replacement for simpler syntax
    template_values.head = get_table_head(runSetResults, common_prefix)
    template_values.run_sets = [runSetResult.attributes for runSetResult in runSetResults]
    template_values.columns = [[column for column in runSet.columns] for runSet in runSetResults]
    template_values.columnTitles =\
        [[column.format_title() for column in runSet.columns] for runSet in runSetResults]

    template_values.relevant_id_columns = select_relevant_id_columns(rows)
    template_values.count_id_columns = template_values.relevant_id_columns.count(True)

    template_values.lib_url = options.lib_url
    template_values.base_dir = outputPath
    template_values.href_base = os.path.dirname(options.xmltablefile) if options.xmltablefile else None
    template_values.version = __version__

    futures = []

    def write_table(table_type, title, rows, use_local_summary):
        # calculate statistics if necessary
        if not options.format == ['csv']:
            local_summary = get_summary(runSetResults) if use_local_summary else None
            stats, stats_columns = get_stats(rows, local_summary, options.correct_only)
        else:
            stats = stats_columns = None

        for template_format in (options.format or TEMPLATE_FORMATS):
            if outputFilePattern == '-':
                outfile = None
                logging.info('Writing %s to stdout...', template_format.upper().ljust(4))
            else:
                outfile = os.path.join(outputPath, outputFilePattern.format(name=name, type=table_type, ext=template_format))
                logging.info('Writing %s into %s ...', template_format.upper().ljust(4), outfile)

            this_template_values = dict(title=title, body=rows, foot=stats, foot_columns=stats_columns)
            this_template_values.update(template_values.__dict__)

            futures.append(parallel.submit(
                write_table_in_format,
                template_format, outfile, this_template_values,
                options.show_table and template_format == 'html',
                ))

    # write normal tables
    write_table("table", name, rows,
                use_local_summary=(not options.correct_only and not options.common))

    # write difference tables
    if rowsDiff:
        write_table("diff", name + " differences", rowsDiff, use_local_summary=False)

    return futures
238243
def _handle_table_style(self, end_token):
        """"""
        data = _TagOpenData()
        data.context = _TagOpenData.CX_ATTR_READY
        while True:
            this = self._read()
            can_exit = (not data.context & data.CX_QUOTED or
                        data.context & data.CX_NOTE_SPACE)
            if this == end_token and can_exit:
                if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
                    self._push_tag_buffer(data)
                if this.isspace():
                    data.padding_buffer["first"] += this
                return data.padding_buffer["first"]
            elif this is self.END or this == end_token:
                if self._context & contexts.TAG_ATTR:
                    if data.context & data.CX_QUOTED:
                        # Unclosed attribute quote: reset, don't die
                        data.context = data.CX_ATTR_VALUE
                        self._memoize_bad_route()
                        self._pop()
                        self._head = data.reset
                        continue
                    self._pop()
                self._fail_route()
            else:
                self._handle_tag_data(data, this)
            self._head += 1
1221457
def _pretty_format(self, statement, result):
        
        if result is None:
            return "Success"
        ret = result
        if statement.action in ("SELECT", "SCAN"):
            if statement.save_file:
                filename = statement.save_file[0]
                if filename[0] in ['"', "'"]:
                    filename = unwrap(filename)
                ret = "Saved %d record%s to %s" % (result, plural(result), filename)
            elif isinstance(result, int):
                if result == result.scanned_count:
                    ret = "%d" % result
                else:
                    ret = "%d (scanned count: %d)" % (result, result.scanned_count)
        elif statement.action == "UPDATE":
            if isinstance(result, int):
                ret = "Updated %d item%s" % (result, plural(result))
        elif statement.action == "DELETE":
            ret = "Deleted %d item%s" % (result, plural(result))
        elif statement.action == "CREATE":
            if result:
                ret = "Created table %r" % statement.table
            else:
                ret = "Table %r already exists" % statement.table
        elif statement.action == "INSERT":
            ret = "Inserted %d item%s" % (result, plural(result))
        elif statement.action == "DROP":
            if result:
                ret = "Dropped table %r" % statement.table
            else:
                ret = "Table %r does not exist" % statement.table
        elif statement.action == "ANALYZE":
            ret = self._pretty_format(statement[1], result)
        elif statement.action == "LOAD":
            ret = "Loaded %d item%s" % (result, plural(result))
        return ret
1125431
def format_prettytable(table):
    """"""
    for i, row in enumerate(table.rows):
        for j, item in enumerate(row):
            table.rows[i][j] = format_output(item)

    ptable = table.prettytable()
    ptable.hrules = prettytable.FRAME
    ptable.horizontal_char = '.'
    ptable.vertical_char = ':'
    ptable.junction_char = ':'
    return ptable
131546
def show_formats():
    
    fmts = {
        "ann": "Kvis annotation",
        "reg": "DS9 regions file",
        "fits": "FITS Binary Table",
        "csv": "Comma separated values",
        "tab": "tabe separated values",
        "tex": "LaTeX table format",
        "html": "HTML table",
        "vot": "VO-Table",
        "xml": "VO-Table",
        "db": "Sqlite3 database",
        "sqlite": "Sqlite3 database"}
    supported = get_table_formats()
    print("Extension |     Description       | Supported?")
    for k in sorted(fmts.keys()):
        print("{0:10s} {1:24s} {2}".format(k, fmts[k], k in supported))
    return
809190
static String getStatsHTML(Database db, long requiredHeap, ArrayList<Feedback> warnings) {
        StringBuilder sb = new StringBuilder();
        sb.append("<table class='table table-condensed'>\n");

        // count things
        int indexes = 0, views = 0, statements = 0;
        int partitionedTables = 0, replicatedTables = 0;
        int partitionedProcs = 0, replicatedProcs = 0;
        int readProcs = 0, writeProcs = 0;
        for (Table t : db.getTables()) {
            if (t.getMaterializer() != null) {
                views++;
            }
            else {
                if (t.getIsreplicated()) {
                    replicatedTables++;
                }
                else {
                    partitionedTables++;
                }
            }

            indexes += t.getIndexes().size();
        }
        for (Procedure p : db.getProcedures()) {
            // skip auto-generated crud procs
            if (p.getDefaultproc()) {
                continue;
            }

            if (p.getSinglepartition()) {
                partitionedProcs++;
            }
            else {
                replicatedProcs++;
            }

            if (p.getReadonly()) {
                readProcs++;
            }
            else {
                writeProcs++;
            }

            statements += p.getStatements().size();
        }

        // version
        sb.append("<tr><td>Generated by VoltDB Version</td><td>");
        sb.append(VoltDB.instance().getVersionString()).append("</td></tr>\n");

        // timestamp
        sb.append("<tr><td>Last Schema Update on</td><td>");
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
        sb.append(sdf.format(m_timestamp)).append("</td></tr>\n");

        // tables
        sb.append("<tr><td>Table Count</td><td>");
        sb.append(String.format("%d (%d partitioned / %d replicated)",
                partitionedTables + replicatedTables, partitionedTables, replicatedTables));
        sb.append("</td></tr>\n");

        // views
        sb.append("<tr><td>Materialized View Count</td><td>").append(views).append("</td></tr>\n");

        // indexes
        sb.append("<tr><td>Index Count</td><td>").append(indexes).append("</td></tr>\n");

        // procedures
        sb.append("<tr><td>Procedure Count</td><td>");
        sb.append(String.format("%d (%d partitioned / %d replicated) (%d read-only / %d read-write)",
                partitionedProcs + replicatedProcs, partitionedProcs, replicatedProcs,
                readProcs, writeProcs));
        sb.append("</td></tr>\n");

        // statements
        sb.append("<tr><td>SQL Statement Count</td><td>").append(statements).append("</td></tr>\n");

        //heap
        sb.append("<tr><td>Required Java Heap</td><td>").append(requiredHeap).append(" Megabytes").append("</td></tr>\n");

        long megabytes = 1024 * 1024;
        long configuredHeap = Runtime.getRuntime().maxMemory() / megabytes;
        if (configuredHeap > requiredHeap) {
            sb.append("<tr><td>Configured Java Heap</td><td>").append(configuredHeap).append(" Megabytes").append("</td></tr>\n");
        } else {
            sb.append("<tr><td>Configured Java Heap</td><td><font color=\"red\">").append(configuredHeap).append("<font color=\"black\">").append(" Megabytes").append("</td></tr>\n");
        }

        sb.append("</table>\n\n");

        // warnings, add warning section if any
        if (warnings.size() > 0){
            sb.append("<h4>Warnings</h4>");
            sb.append("<table class='table table-condensed'>\n");
            for (Feedback warning : warnings) {
                String procName = warning.getFileName().replace(".class", "");
                String nameLink = "";
                // not a warning during compiling procedures, must from the schema
                if (procName.compareToIgnoreCase("null") == 0) {
                    String schemaName = "";
                    String warningMsg = warning.getMessage().toLowerCase();
                    if (warningMsg.contains("table ")) {
                        int begin = warningMsg.indexOf("table ") + 6;
                        int end = (warningMsg.substring(begin)).indexOf(" ");
                        schemaName = warningMsg.substring(begin, begin + end);
                    }
                    nameLink = "<a href='#s-" + schemaName + "'>" + schemaName.toUpperCase() + "</a>";
                } else {
                    nameLink = "<a href='#p-" + procName.toLowerCase() + "'>" + procName + "</a>";
                }
                sb.append("<tr><td>").append(nameLink).append("</td><td>").append(escapeHtml4(warning.getMessage())).append("</td></tr>\n");
            }
            sb.append("</table>\n").append("</td></tr>\n");
        }

        return sb.toString();
    }
1329015
def __dumptable(self, table):
        
        for x in table.table.keys():
            sys.stdout.write("{0}\t<--- {1} {2}".format(x, table[x], type(table[x])))
            if isinstance(table[x], ID):
                sys.stdout(" {0}".format(table[x].value)),
            sys.stdout.write("\n")