Output a nicely formatted ascii table
349254
def generate_table_from(data):
    ""
    table = Texttable(max_width=120)
    table.add_row(["view", "method", "status", "count", "minimum", "maximum", "mean", "stdev", "queries", "querytime"]) 
    table.set_cols_align(["l", "l", "l", "r", "r", "r", "r", "r", "r", "r"])

    for item in sorted(data):
        mean = round(sum(data[item]['times'])/data[item]['count'], 3)

        mean_sql = round(sum(data[item]['sql'])/data[item]['count'], 3)
        mean_sqltime = round(sum(data[item]['sqltime'])/data[item]['count'], 3)
        
        sdsq = sum([(i - mean) ** 2 for i in data[item]['times']])
        try:
            stdev = '%.2f' % ((sdsq / (len(data[item]['times']) - 1)) ** .5)
        except ZeroDivisionError:
            stdev = '0.00'

        minimum = "%.2f" % min(data[item]['times'])
        maximum = "%.2f" % max(data[item]['times'])
        table.add_row([data[item]['view'], data[item]['method'], data[item]['status'], data[item]['count'], minimum, maximum, '%.3f' % mean, stdev, mean_sql, mean_sqltime])

    return table.draw()
291358
def pretty_print(self):
        
        return u"%s\t%.3f\t%.3f\t%s" % (
            (self.identifier or u""),
            (self.begin if self.begin is not None else TimeValue("-2.000")),
            (self.end if self.end is not None else TimeValue("-1.000")),
            (self.text or u"")
        )
301265
def format_output(data, fmt='table'):  # pylint: disable=R0911,R0912
    
    if isinstance(data, utils.string_types):
        if fmt in ('json', 'jsonraw'):
            return json.dumps(data)
        return data

    # responds to .prettytable()
    if hasattr(data, 'prettytable'):
        if fmt == 'table':
            return str(format_prettytable(data))
        elif fmt == 'raw':
            return str(format_no_tty(data))

    # responds to .to_python()
    if hasattr(data, 'to_python'):
        if fmt == 'json':
            return json.dumps(
                format_output(data, fmt='python'),
                indent=4,
                cls=CLIJSONEncoder)
        elif fmt == 'jsonraw':
            return json.dumps(format_output(data, fmt='python'),
                              cls=CLIJSONEncoder)
        elif fmt == 'python':
            return data.to_python()

    # responds to .formatted
    if hasattr(data, 'formatted'):
        if fmt == 'table':
            return data.formatted

    # responds to .separator
    if hasattr(data, 'separator'):
        output = [format_output(d, fmt=fmt) for d in data if d]
        return str(SequentialOutput(data.separator, output))

    # is iterable
    if isinstance(data, list) or isinstance(data, tuple):
        output = [format_output(d, fmt=fmt) for d in data]
        if fmt == 'python':
            return output
        return format_output(listing(output, separator=os.linesep))

    # fallback, convert this odd object to a string
    return data
946158
def truthtable(inputs, outputs):
    """"""
    def items():
        """Convert all outputs to PC notation."""
        for output in outputs:
            if isinstance(output, boolfunc.Function):
                output = output.unbox()
            if output in (0, '0'):
                yield PC_ZERO
            elif output in (1, '1'):
                yield PC_ONE
            elif output in "-xX":
                yield PC_DC
            else:
                fstr = "expected output in [01-xX], got {}"
                raise ValueError(fstr.format(output))
    inputs = [ttvar(v.names, v.indices) for v in inputs]
    pcdata = PCData(items())
    if len(pcdata) != (1 << len(inputs)):
        fstr = "expected {} outputs, got {}"
        raise ValueError(fstr.format(1 << len(inputs), len(pcdata)))
    return _truthtable(inputs, pcdata)
488660
def pretty(self,verbose=0):
        """"""
        # split prompt lines and add blanks in later lines to align them
        plines = self.prompt.split('\n')
        for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1]
        plines = '\n'.join(plines)
        namelen = min(len(self.name), 12)
        pvalue = self.get(prompt=0,lpar=1)
        alwaysquoted = ['s', 'f', '*gcur', '*imcur', '*ukey', 'pset']
        if self.type in alwaysquoted and self.value is not None: pvalue = '"' + pvalue + '"'
        if self.mode == "h":
            s = "%13s = %-15s %s" % ("("+self.name[:namelen],
                                    pvalue+")", plines)
        else:
            s = "%13s = %-15s %s" % (self.name[:namelen],
                                    pvalue, plines)
        if not verbose: return s

        if self.choice is not None:
            s = s + "\n" + 32*" " + "|"
            nline = 33
            for i in range(len(self.choice)):
                sch = str(self.choice[i]) + "|"
                s = s + sch
                nline = nline + len(sch) + 1
                if nline > 80:
                    s = s + "\n" + 32*" " + "|"
                    nline = 33
        elif self.min not in [None, INDEF] or self.max not in [None, INDEF]:
            s = s + "\n" + 32*" "
            if self.min not in [None, INDEF]:
                s = s + str(self.min) + " <= "
            s = s + self.name
            if self.max not in [None, INDEF]:
                s = s + " <= " + str(self.max)
        return s
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
735066
def _get_table_as_string(self):
        """"""
        tablelist = []
        tablelist.append("!%s_table_begin" % self.geotype.lower())
        tablelist.append("\t".join(self.table.columns))
        for idx, row in self.table.iterrows():
            tablelist.append("\t".join(map(str, row)))
        tablelist.append("!%s_table_end" % self.geotype.lower())
        return "\n".join(tablelist)
1062859
def prettyprint(self):
        """"""
        return json.dumps(self.asJSON(), sort_keys=True, indent=4, separators=(',', ': '))
1342490
def colformat(strings, num_sep_spaces=1, terminal_width=None):
    """"""
    if terminal_width is None:
        terminal_width = get_terminal_size().columns

    if not strings:
        return

    num_items = len(strings)
    max_len = max([len(strip_ansi_escapes(s)) for s in strings])

    num_columns = min(
        int((terminal_width + num_sep_spaces) / (max_len + num_sep_spaces)),
        num_items)
    num_columns = max(1, num_columns)

    num_lines = int(math.ceil(float(num_items) / num_columns))
    num_columns = int(math.ceil(float(num_items) / num_lines))

    num_elements_last_column = num_items % num_lines
    if num_elements_last_column == 0:
        num_elements_last_column = num_lines

    lines = []
    for i in range(num_lines):
        line_size = num_columns
        if i >= num_elements_last_column:
            line_size -= 1
        lines.append([None] * line_size)

    for i, line in enumerate(lines):
        line_size = len(line)
        for j in range(line_size):
            k = i + num_lines * j
            item = strings[k]
            if j % line_size != line_size - 1:
                item_len = len(strip_ansi_escapes(item))
                item = item + ' ' * (max_len - item_len)
            line[j] = item

    sep = ' ' * num_sep_spaces
    for line in lines:
        yield sep.join(line)
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)
1093175
def filter_ascii(lst):
    '''
    
    '''
    return [word for word in lst if all(ord(c) < 128 for c in word)]
889818
def ascii(self):
        """"""
        comments = ''
        if self.version == 'v3':
            for comment in self.comments:
                if not comment.startswith(' '):
                    comment = ' ' + comment
                comments += "#" + comment + "\n"

        if self.version == 'v1':
            header = "{det.det_id} {det.n_doms}".format(det=self)
        else:
            header = "{det.det_id} {det.version}".format(det=self)
            header += "\n{0} {1}".format(self.valid_from, self.valid_until)
            header += "\n" + str(self.utm_info) + "\n"
            header += str(self.n_doms)

        doms = ""
        for dom_id, (line, floor, n_pmts) in self.doms.items():
            doms += "{0} {1} {2} {3}\n".format(dom_id, line, floor, n_pmts)
            for channel_id in range(n_pmts):
                pmt_idx = self._pmt_index_by_omkey[(line, floor, channel_id)]
                pmt = self.pmts[pmt_idx]
                doms += " {0} {1} {2} {3} {4} {5} {6} {7}".format(
                    pmt.pmt_id, pmt.pos_x, pmt.pos_y, pmt.pos_z, pmt.dir_x,
                    pmt.dir_y, pmt.dir_z, pmt.t0
                )
                if self.version == 'v3':
                    doms += " {0}".format(pmt.status)
                doms += "\n"
        return comments + header + "\n" + doms
650167
def pretty_print(n):
    """"""
    if type(n) != int:
        return n

    ret = []
    n = str(n)
    for i in range(len(n) - 1, -1, -1):
        ret.append(n[i])
        if (len(n) - i) % 3 == 0:
            ret.append(',')
    ret.reverse()
    return ''.join(ret[1:]) if ret[0] == ',' else ''.join(ret)
519980
def print_table(table):
    
    table = [[str(cell) for cell in row] for row in table]
    column_widths = [len(cell) for cell in table[0]]
    for row in table:
        for x, cell in enumerate(row):
            column_widths[x] = max(column_widths[x], len(cell))

    formatters = []
    for width in column_widths:
        formatters.append('{:>' + str(width) + '}')
    formatter = '  '.join(formatters)
    for row in table:
        print(formatter.format(*row))
1315955
def _output_format(out,
                   operation):
    '''
    
    '''
    return [s.split()[1:] for s in out
            if s.startswith(operation)]
117048
def gen_posix(output, is_bytes=False, append=False, prefix=""):
    """"""

    posix_table = {}

    # `Alnum: [a-zA-Z0-9]`
    s = set([x for x in range(0x30, 0x39 + 1)])
    s |= set([x for x in range(0x41, 0x5a + 1)])
    s |= set([x for x in range(0x61, 0x7a + 1)])
    posix_table["alnum"] = list(s)

    # `Alpha: [a-zA-Z]`
    s = set([x for x in range(0x41, 0x5a)])
    s |= set([x for x in range(0x61, 0x7a)])
    posix_table["alpha"] = list(s)

    # `ASCII: [\x00-\x7F]`
    s = set([x for x in range(0, 0x7F + 1)])
    posix_table["ascii"] = list(s)

    # `Blank: [ \t]`
    s = set([0x20, 0x09])
    posix_table["blank"] = list(s)

    # `Cntrl: [\x00-\x1F\x7F]`
    s = set([x for x in range(0, 0x1F + 1)] + [0x7F])
    posix_table["cntrl"] = list(s)

    # `Digit: [0-9]`
    s = set([x for x in range(0x30, 0x39 + 1)])
    posix_table["digit"] = list(s)

    # `Graph: [\x21-\x7E]`
    s = set([x for x in range(0x21, 0x7E + 1)])
    posix_table["graph"] = list(s)

    # `Lower: [a-z]`
    s = set([x for x in range(0x61, 0x7a + 1)])
    posix_table["lower"] = list(s)

    # `Print: [\x20-\x7E]`
    s = set([x for x in range(0x20, 0x7E + 1)])
    posix_table["print"] = list(s)

    # `Punct: [!\"\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]`
    s = set([x for x in range(0x21, 0x2f + 1)])
    s |= set([x for x in range(0x3a, 0x40 + 1)])
    s |= set([x for x in range(0x5b, 0x60 + 1)])
    s |= set([x for x in range(0x7b, 0x7e + 1)])
    posix_table["punct"] = list(s)

    # `Space: [ \t\r\n\v\f]`
    s = set([x for x in range(0x09, 0x0d + 1)] + [0x20])
    posix_table["space"] = list(s)

    # `Upper: [A-Z]`
    s = set([x for x in range(0x41, 0x5a + 1)])
    posix_table["upper"] = list(s)

    # `XDigit: [A-Fa-f0-9]`
    s = set([x for x in range(0x30, 0x39 + 1)])
    s |= set([x for x in range(0x41, 0x46 + 1)])
    s |= set([x for x in range(0x61, 0x66 + 1)])
    posix_table["xdigit"] = list(s)

    # Convert characters values to ranges
    char2range(posix_table, is_bytes=is_bytes)

    with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
        if not append:
            f.write(HEADER)
        # Write out the Unicode properties
        f.write('%s_posix_properties = {\n' % prefix)
        count = len(posix_table) - 1
        i = 0
        for k1, v1 in sorted(posix_table.items()):
            f.write('    "%s": "%s"' % (k1, v1))
            if i == count:
                f.write('\n}\n')
            else:
                f.write(',\n')
            i += 1
725134
def write_moc_ascii(moc, filename=None, file=None):
    

    orders = []

    for (order, cells) in moc:
        ranges = []
        rmin = rmax = None

        for cell in sorted(cells):
            if rmin is None:
                rmin = rmax = cell
            elif rmax == cell - 1:
                rmax = cell
            else:
                ranges.append(_format_range(rmin, rmax))
                rmin = rmax = cell

        ranges.append(_format_range(rmin, rmax))

        orders.append('{0}'.format(order) + '/' + ','.join(ranges))

    if file is not None:
        _write_ascii(orders, file)
    else:
        with open(filename, 'w') as f:
            _write_ascii(orders, f)