Write a file of tab-separated table data
349172
def wr_tsv(fout_tsv, tsv_data, **kws):
    """"""
    items_str = "items" if "items" not in kws else kws["items"]
    if tsv_data:
        ifstrm = sys.stdout if fout_tsv is None else open(fout_tsv, 'w')
        num_items = prt_tsv(ifstrm, tsv_data, **kws)
        if fout_tsv is not None:
            sys.stdout.write("  {N:>5} {ITEMS} WROTE: {FOUT}\n".format(
                N=num_items, ITEMS=items_str, FOUT=fout_tsv))
            ifstrm.close()
    else:
        sys.stdout.write("      0 {ITEMS}. NOT WRITING {FOUT}\n".format(
            ITEMS=items_str, FOUT=fout_tsv))
781980
def export_to_html(
    table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs
):
    """"""

    serialized_table = serialize(table, *args, **kwargs)
    fields = next(serialized_table)
    result = ["<table>\n\n"]
    if caption and table.name:
        result.extend(["  <caption>", table.name, "</caption>\n\n"])
    result.extend(["  <thead>\n", "    <tr>\n"])
    # TODO: set @name/@id if self.meta["name"] is set
    header = ["      <th> {} </th>\n".format(field) for field in fields]
    result.extend(header)
    result.extend(["    </tr>\n", "  </thead>\n", "\n", "  <tbody>\n", "\n"])
    for index, row in enumerate(serialized_table, start=1):
        css_class = "odd" if index % 2 == 1 else "even"
        result.append('    <tr class="{}">\n'.format(css_class))
        for value in row:
            result.extend(["      <td> ", escape(value), " </td>\n"])
        result.append("    </tr>\n\n")
    result.append("  </tbody>\n\n</table>\n")
    html = "".join(result).encode(encoding)

    return export_data(filename_or_fobj, html, mode="wb")
373092
function write(writer, ttf) {
            var table = ttf[this.name];

            if (!table) {
                error.raise(10203, this.name);
            }

            this.struct.forEach(function (item) {
                var name = item[0];
                var type = item[1];

                switch (type) {
                    case struct.Int8:
                    case struct.Uint8:
                    case struct.Int16:
                    case struct.Uint16:
                    case struct.Int32:
                    case struct.Uint32:
                        var typeName = struct.names[type];
                        writer.write(typeName, table[name]);
                        break;

                    case struct.Fixed:
                        writer.writeFixed(table[name]);
                        break;

                    case struct.LongDateTime:
                        writer.writeLongDateTime(table[name]);
                        break;

                    case struct.Bytes:
                        writer.writeBytes(table[name], item[2] || 0);
                        break;

                    case struct.Char:
                        writer.writeChar(table[name]);
                        break;

                    case struct.String:
                        writer.writeString(table[name], item[2] || 0);
                        break;

                    default:
                        error.raise(10003, name, type);
                }
            });

            return writer;
        }
812472
private static File writePartToFile(File splitDir, List<String> data) {
        BufferedWriter writer = null;
        File splitFile;
        try {
            splitFile = File.createTempFile("split-", ".part", splitDir);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(splitFile.getAbsoluteFile(), false),
                    DataUtilDefaults.charSet));
            for(String item : data) {
                writer.write(item + DataUtilDefaults.lineTerminator);
            }
            writer.flush();
            writer.close();
            writer = null;
        } catch (UnsupportedEncodingException e) {
            throw new DataUtilException(e);
        } catch (FileNotFoundException e) {
            throw new DataUtilException(e);
        } catch (IOException e) {
            throw new DataUtilException(e);
        } finally {
            if(writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // Intentionally we're doing nothing here
                }
            }
        }
        return splitFile;
    }
420776
def _tabulate(rows, headers, spacing=5):
    """"""
    if len(rows) == 0:
        return "None\n"
    assert len(rows[0]) == len(headers)
    count = len(rows[0])
    widths = [0 for _ in range(count)]
    rows = [headers] + rows

    for row in rows:
        for index, field in enumerate(row):
            if len(str(field)) > widths[index]:
                widths[index] = len(str(field))

    output = ""
    for row in rows:
        for index, field in enumerate(row):
            field = str(field)
            output += field + (widths[index] - len(field) + spacing) * " "
        output += "\n"
    return output
506604
def tabulate(lol, headers, eol='\n'):
    """"""
    yield '| %s |' % ' | '.join(headers) + eol
    yield '| %s:|' % ':| '.join(['-' * len(w) for w in headers]) + eol
    for row in lol:
        yield '| %s |' % '  |  '.join(str(c) for c in row) + eol
608201
def write_data(data):
    

    sorted_dict = sort_recursive(data)

    with open(_datafile, 'w') as file:
        _json.dump(sorted_dict, file, indent=2)
615110
def write(self, ulBuffer, pSrc, unBytes):
        """"""

        fn = self.function_table.write
        result = fn(ulBuffer, pSrc, unBytes)
        return result
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")
430828
def table_for_data( data )
    buf = ""
    buf << "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body>\n"
    buf << "<table>\n"
    data.each do |rec|
      buf << "  <tr>"
      rec.values.each do |value|
        buf << "<td>#{value}</td>"
      end
      buf << "</tr>\n"
    end
    buf << "</table>\n"
    buf << "</body></html>"
    buf
  end
1121068
def format_to_example(table, tabspace=2, indent=2):
    
    from io import StringIO
    output = StringIO()

    caption, rows = table

    # output caption line
    output.write(u'{0}Examples: {1}\n'.format(' ' * indent * tabspace,
                                              caption))

    # calculate max length for each column, for aligning
    cols = zip(*rows)
    col_lengths = []
    for col in cols:
        max_length = max([len(format_item(row)) for row in col])
        col_lengths.append(max_length)

    # output each row
    for r, row in enumerate(rows):
        output.write(u' ' * (indent + 1) * tabspace)
        output.write(u'|')
        for c in range(len(col_lengths)):
            output.write(u' ')
            output.write(format_item(row[c], r))
            output.write(u' ' * (col_lengths[c] - len(format_item(row[c], r))))
            output.write(u' |')
        output.write(u'\n')

    example = output.getvalue()
    output.close()
    return example
976603
def write_table(self, d):
        
        # HACK: encoding of AMQP tables is broken because it requires the
        # length of the /encoded/ data instead of the number of items. To
        # support streaming, fiddle with cursor position, rewinding to write
        # the real length of the data. Generally speaking, I'm not a fan of
        # the AMQP encoding scheme, it could be much faster.
        table_len_pos = len(self._output_buffer)
        self.write_long(0)
        table_data_pos = len(self._output_buffer)

        for key, value in d.iteritems():
            self._write_item(key, value)

        table_end_pos = len(self._output_buffer)
        table_len = table_end_pos - table_data_pos

        self.write_long_at(table_len, table_len_pos)
        return self
214615
def write_table(self, d):
        
        self._flushbits()
        table_data = AMQPWriter()
        for k, v in d.items():
            table_data.write_shortstr(k)
            if isinstance(v, basestring):
                if isinstance(v, unicode):
                    v = v.encode('utf-8')
                table_data.write(byte(83)) # 'S'
                table_data.write_longstr(v)
            elif isinstance(v, (int, long)):
                table_data.write(byte(73)) # 'I'
                table_data.write(pack('>i', v))
            elif isinstance(v, Decimal):
                table_data.write(byte(68)) # 'D'
                sign, digits, exponent = v.as_tuple()
                v = 0
                for d in digits:
                    v = (v * 10) + d
                if sign:
                    v = -v
                table_data.write_octet(-exponent)
                table_data.write(pack('>i', v))
            elif isinstance(v, datetime):
                table_data.write(byte(84)) # 'T'
                table_data.write_timestamp(v)
                ## FIXME: timezone ?
            elif isinstance(v, dict):
                table_data.write(byte(70)) # 'F'
                table_data.write_table(v)
            else:
                raise ValueError('%s not serializable in AMQP' % repr(v))
        table_data = table_data.getvalue()
        self.write_long(len(table_data))
        self.out.write(table_data)
1208026
def tabulate(data, header=True, headers=None, accessors=None,
             **table_options):
    
    if header and not headers:
        data = iter(data)
        try:
            headers = next(data)
        except StopIteration:
            pass
    if headers and hasattr(headers, 'items') and accessors is None:
        # Dict mode; Build accessors and headers from keys of data.
        data = itertools.chain([headers], data)
        accessors = list(headers)
        headers = [' '.join(map(str.capitalize, x.replace('_', ' ').split()))
                   for x in accessors]
    t = Table(headers=headers, accessors=accessors, **table_options)
    try:
        t.print(data)
    except RowsNotFound:
        pass
    return t
754716
def write_table_to_file(self, dtype, custom_name=None, append=False, dir_path=None):
        
        if custom_name:
            fname = custom_name
        else:
            fname = self.filenames[dtype]
        if not dir_path:
            dir_path=self.directory
        if dtype in self.tables:
            write_df = self.remove_names(dtype)
            outfile = self.tables[dtype].write_magic_file(custom_name=fname,
                                                          dir_path=dir_path,
                                                          append=append, df=write_df)
        return outfile
1284040
def write_tabular(obj, filepath):
    
    _, fn, ext = splitext2(filepath)
    if ext == '.h5':
        _write_tabular_h5(obj, filepath)
    elif ext == '.pkl':
        _write_tabular_pickle(obj, filepath)
    else:
        raise NotImplementedError
1311999
private void writeAllBufferedData()
        throws IOException
    {
        writeBytes(_user_output_stream);

        clearFieldName();
        clearAnnotations();

        _in_struct = false;
        _patch_count = 0;
        _patch_symbol_table_count = 0;
        _top = 0;
        try {
            _writer.setPosition(0);
            _writer.truncate();
        }
        catch (IOException e) {
            throw new IonException(e);
        }
    }