Return a table that writes rows to a text file as they are iterated over.
556750
def teetext(table, source=None, encoding=None, errors='strict', template=None,
            prologue=None, epilogue=None):
    

    assert template is not None, 'template is required'
    return TeeTextView(table, source=source, encoding=encoding, errors=errors,
                       template=template, prologue=prologue, epilogue=epilogue)
844111
def table_format(self, columns, content):
        
        result = []
        textw = TextWidget()
        for row in content:
            i = 0
            result_row = []
            for cell in row:
                result_row.append(textw.render(cell, **columns[i]))
                i += 1
            result.append(result_row)
        return (columns, result)
135232
def as_text(self, max_rows=0, sep=" | "):
        """"""
        if not max_rows or max_rows > self.num_rows:
            max_rows = self.num_rows
        omitted = max(0, self.num_rows - max_rows)
        labels = self._columns.keys()
        fmts = self._get_column_formatters(max_rows, False)
        rows = [[fmt(label, label=True) for fmt, label in zip(fmts, labels)]]
        for row in itertools.islice(self.rows, max_rows):
            rows.append([f(v, label=False) for v, f in zip(row, fmts)])
        lines = [sep.join(row) for row in rows]
        if omitted:
            lines.append('... ({} rows omitted)'.format(omitted))
        return '\n'.join([line.rstrip() for line in lines])
1167365
def gen_table(contents):
    
    xlengths = []
    ylengths = []
    for column in contents:
        col_len = 0
        for entry in column:
            lines = entry.split('\n')
            for line in lines:
                col_len = max(len(line) + 2, col_len)
        xlengths.append(col_len)
    for i in range(len(contents[0])):
        ymax = 0
        for j in range(len(contents)):
            ymax = max(ymax, len(contents[j][i].split('\n')))
        ylengths.append(ymax)

    table_divider = '+' + ''.join(['-' * i + '+' for i in xlengths]) + '\n'
    table = table_divider
    for i in range(len(ylengths)):
        row = [column[i] for column in contents]
        row = [entry + '\n' * (ylengths[i]-len(entry.split('\n'))) for entry in row]
        row = [entry.split('\n') for entry in row]
        for j in range(ylengths[i]):
            k = 0
            for entry in row:
                width = xlengths[k]
                table += ''.join(['| {:{}}'.format(entry[j], width - 1)])
                k += 1
            table += '|\n'
        table += table_divider
    return table + '\n'
859875
def make_table(headers=None, rows=None):
    """"""
    if callable(headers):
        headers = headers()
    if callable(rows):
        rows = rows()
    assert isinstance(headers, list)
    assert isinstance(rows, list)
    assert all(len(row) == len(headers) for row in rows)

    plain_headers = [strip_ansi(six.text_type(v)) for v in headers]
    plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]]

    plain_headers = []
    column_widths = []

    for k, v in enumerate(headers):
        v = six.text_type(v)
        plain = strip_ansi(v)
        plain_headers.append(plain)
        column_widths.append(len(plain))

        if len(v) == len(plain):
            # Value was unstyled, make it bold
            v = click.style(v, bold=True)

        headers[k] = v

    plain_rows = []
    for row in rows:
        plain_row = []
        for k, v in enumerate(row):
            v = six.text_type(v)
            plain = strip_ansi(v)
            plain_row.append(plain)
            column_widths[k] = max(column_widths[k], len(plain))

        plain_rows.append(plain_row)

    return Table(
        headers=headers,
        plain_headers=plain_headers,
        rows=rows,
        plain_rows=plain_rows,
        column_widths=column_widths,
    )
761636
def tablify(*args):
    
    """
    table = []
    args = [listify(arg) for arg in args]
    for row in zip(*args):
        r = []
        for x in row:
            r += listify(x)
        table += [r]
    return table
    return [sum([listify(el) for el in row]) for row in zip(*args)]
1173510
def rows(self):
        
        with self.input().open('r') as fobj:
            for line in fobj:
                yield line.strip('\n').split('\t')
877706
def format_table(columns, rows):
    
    rows = [tuple(str(i) for i in r) for r in rows]
    columns = tuple(str(i).upper() for i in columns)
    if rows:
        widths = tuple(max(max(map(len, x)), len(c))
                       for x, c in zip(zip(*rows), columns))
    else:
        widths = tuple(map(len, columns))
    row_template = ('    '.join('%%-%ds' for _ in columns)) % widths
    header = (row_template % tuple(columns)).strip()
    if rows:
        data = '\n'.join((row_template % r).strip() for r in rows)
        return '\n'.join([header, data])
    else:
        return header
192946
def write_row(dictionary, card, log):
    
    rowhdr = {'card': card, 'log': log}

    # Do this as a list of 1-char strings.
    # Can't use a string b/c strings are immutable.
    row = [' '] * 80

    # Make the row header.
    for e in ['log', 'card']:
        strt, stop, item = _put_field(cols(0), e, rowhdr[e])
        if item is not None:
            row[strt:stop] = list(item)

    # Now make the rest of the row.
    for field in cols(card):
        strt, stop, item = _put_field(cols(card), field, dictionary.get(field))
        if item is not None:
            row[strt:stop] = list(item)

    return ''.join(row) + '\n'
1365681
def iter_rows(self, start=None, end=None):
        """"""
        start = start or 0
        end = end or self.nrows
        for i in range(start, end):
            yield self.iloc[i, :]
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
217398
def write_data_chunk(self, rows, indexes, mask, values):
        

        # 0 len
        for v in values:
            if not np.prod(v.shape):
                return

        try:
            nrows = indexes[0].shape[0]
            if nrows != len(rows):
                rows = np.empty(nrows, dtype=self.dtype)
            names = self.dtype.names
            nindexes = len(indexes)

            # indexes
            for i, idx in enumerate(indexes):
                rows[names[i]] = idx

            # values
            for i, v in enumerate(values):
                rows[names[i + nindexes]] = v

            # mask
            if mask is not None:
                m = ~mask.ravel().astype(bool, copy=False)
                if not m.all():
                    rows = rows[m]

        except Exception as detail:
            raise Exception(
                "cannot create row-data -> {detail}".format(detail=detail))

        try:
            if len(rows):
                self.table.append(rows)
                self.table.flush()
        except Exception as detail:
            raise TypeError(
                "tables cannot write this data -> {detail}".format(
                    detail=detail))
730306
def print_table(lines, separate_head=True):
	""""""
	#Count the column width
	widths = []
	for line in lines:
			for i,size in enumerate([len(x) for x in line]):
					while i >= len(widths):
							widths.append(0)
					if size > widths[i]:
							widths[i] = size
	   
	#Generate the format string to pad the columns
	print_string = ""
	for i,width in enumerate(widths):
			print_string += "{" + str(i) + ":" + str(width) + "} | "
	if (len(print_string) == 0):
			return
	print_string = print_string[:-3]
	   
	#Print the actual data
	for i,line in enumerate(lines):
			print(print_string.format(*line))
			if (i == 0 and separate_head):
					print("-"*(sum(widths)+3*(len(widths)-1)))
700282
private void writeRowsToCSV(List<String[]> rows) throws BindException
  {
    int numBytes;
    int rowNum = 0;
    int fileCount = 0;

    while (rowNum < rows.size())
    {
      File file = getFile(++fileCount);

      try (OutputStream out = openFile(file))
      {
        // until we reach the last row or the file is too big, write to the file
        numBytes = 0;
        while (numBytes < fileSize && rowNum < rows.size())
        {
          byte[] csv = createCSVRecord(rows.get(rowNum));
          numBytes += csv.length;
          out.write(csv);
          rowNum++;
        }
      }
      catch (IOException ex)
      {
        throw new BindException(
            String.format("Exception encountered while writing to file: %s", ex.getMessage()), BindException.Type.SERIALIZATION);
      }
    }
  }
782171
def write(self, data, method='w'):
        
        # Create list of lists from flat list
        data = data if isinstance(data[0], (list, set, tuple)) else [[d] for d in data]

        # Open file and write rows
        with open(self.file_path, method) as write:
            wr = csv_builtin.writer(write)
            wr.writerows(data)
        return self.file_path
1276962
def write_table(page, headers, data, cl=''):

    

    page.table(class_=cl)

    # list
    if cl=='list':
        for i in range(len(headers)):

            page.tr()
            page.th()
            page.add('%s' % headers[i])
            page.th.close()
            page.td()
            page.add('%s' % data[i])
            page.td.close()
            page.tr.close()

    else:
        page.tr()
        for n in headers:
            page.th()
            page.add('%s' % n)
            page.th.close()
        page.tr.close()

        if data and not re.search('list',str(type(data[0]))):
            data = [data]

        for row in data:
            page.tr()
            for item in row:
                page.td()
                page.add('%s' % item)
                page.td.close()
            page.tr.close()

    page.table.close()

    return page
112953
def _table_to_csv(table_):
    
    f = cStringIO.StringIO()
    try:
        _write_csv(f, table_)
        return f.getvalue()
    finally:
        f.close()