method csv_for_data
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
1160084
def as_csv(self):
        """"""

        from io import StringIO

        s = StringIO()
        w = csv.writer(s)
        for row in self.rows:
            w.writerow(row)

        return s.getvalue()
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
1052345
def csv(self, **kwargs):
        
        out = StringIO()
        writer = csv.DictWriter(out, self.columns, **kwargs)
        writer.writerow(dict(zip(self.columns, self.columns)))
        writer.writerows(dict(row.items()) for row in self.rows)
        
        return out
1033939
def _get_results(csv_reader, fieldnames):
    
    fieldnames_count = len(fieldnames)
    results = []
    for row in csv_reader:
        for col in row:
            if col:
                break
        else:
            # empty row, skip it
            continue
        record = OrderedDict(list(zip(fieldnames, row)))
        # skip rows that were already exported
        if record.get("exported") == "yes":
            continue
        row_len = len(row)
        if fieldnames_count > row_len:
            for key in fieldnames[row_len:]:
                record[key] = None
        results.append(record)

    return results
73664
def hash_csv(csv_string)
      require 'csv'

      csv = CSV.parse(csv_string)
      headers = csv.shift
      output = []

      csv.each do |row|
        hash = {}
        headers.each do |header|
          hash[header] = row.shift.to_s
        end
        output << hash
      end

      return output
    end
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);
      }
    }
  }
639229
def print_csv(self, items, fields):
        
        writer = csv.writer(sys.stdout)
        writer.writerow(fields)
        for i in items:
            i_fields = [self.string(getattr(i, f)) for f in fields]
            writer.writerow(i_fields)
1293687
def csv_from_items(items, stream=None):
        
        items = iter(items)
        first = next(items)
        cls = first.__class__
        if stream is None:
            stream = sys.stdout
        fields = [f.name for f in attr.fields(cls)]
        writer = csv.DictWriter(stream, fieldnames=fields)
        writer.writeheader()
        writer.writerow(attr.asdict(first))
        writer.writerows((attr.asdict(x) for x in items))
1012969
def write_csv(path, data):
    """"""

    fd = _try_open_file(path, 'w',
                        'The first argument must be a pathname or an object that supports write() method')
    for v in data:
        fd.write(",".join([str(x) for x in v]))
        fd.write("\n")
    _try_close_file(fd, path)
1005774
private static String[] getSeriesDataFromCSVRows(File csvFile) {

    String[] xAndYData = new String[3];

    BufferedReader bufferedReader = null;
    try {
      int counter = 0;
      String line;
      bufferedReader = new BufferedReader(new FileReader(csvFile));
      while ((line = bufferedReader.readLine()) != null) {
        xAndYData[counter++] = line;
      }
    } catch (Exception e) {
      System.out.println("Exception while reading csv file: " + e);
    } finally {
      if (bufferedReader != null) {
        try {
          bufferedReader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return xAndYData;
  }
673931
def _write_csv(f, table_):
    
    fieldnames = table_[0].keys()
    set_fieldname = set(table_[0].keys())
    # go through all the fields and find all the field names
    for row in table_:
        set_fieldname.update(set(row.keys()))

    # append the additonal fields sorted onto the end
    additional_fields = sorted(set_fieldname - set(table_[0].keys()))
    fieldnames += additional_fields

    writer = unicodecsv.DictWriter(f, fieldnames, encoding='utf-8')
    writer.writeheader()

    # Change lists into comma-separated strings.
    for dict_ in table_:
        for key, value in dict_.items():
            if type(value) in (list, tuple):
                dict_[key] = ', '.join([unicode(v) for v in value])

    writer.writerows(table_)
663354
def ingest_csv(csv_data, message_set):
    
    records = csv.DictReader(csv_data)
    for line in records:
        for key in line:
            # Ignore non-content keys and empty keys
            if key not in ["message_id", "safe"] and line[key] != "":
                try:
                    with transaction.atomic():
                        message = Message()
                        message.message_set = message_set
                        message.sequence_number = line["message_id"]
                        message.lang = key
                        message.content = line[key]
                        message.save()
                except (IntegrityError, ValueError) as e:
                    message = None
                    # crappy CSV data
                    standard_logger.error(e)
915597
def map_to_csv(fields, delimiter=","):
    

    def _list_to_csv(l):
        """
        Util function to overcome the use of files by in-memory io buffer

        :param l:
        :return:
        """
        io_file = io.StringIO()
        writer = csv.writer(io_file, quoting=csv.QUOTE_NONNUMERIC, lineterminator='', delimiter=delimiter)
        writer.writerow(l)
        return io_file.getvalue()

    def _app(current_tuple, e=None):
        if e is not None:
            return None, e
        csv_list = []
        for f in fields:
            if f in current_tuple:
                csv_list.append(current_tuple[f])
            else:
                e.update({"output": "expected field {} not found".format(f)})
                return None, e
        return _list_to_csv(csv_list), e
    if fields is None or len(fields) == 0:
        return fixed_input(None, "no fields provided, cannot proceed without order")
    return _app
866382
def makeCSVFileForReport(filename,dbid=@dbid,query=nil,qid=nil,qname=nil)
      csv = getCSVForReport(dbid,query,qid,qname)
      File.open(filename,"w"){|f|f.write(csv || "")}
   end
1181543
def results_to_csv(query_name, **kwargs):
    
    query = get_result_set(query_name, **kwargs)
    result = query.result
    columns = list(result[0].keys())
    data = [tuple(row.values()) for row in result]
    frame = tablib.Dataset()
    frame.headers = columns
    for row in data:
        frame.append(row)
    csvs = frame.export('csv')
    return csvs
763439
def rows(self, csv=False):
        

        # Store the index of each field against its ID for building each
        # entry row with columns in the correct order. Also store the IDs of
        # fields with a type of FileField or Date-like for special handling of
        # their values.
        field_indexes = {}
        file_field_ids = []
        date_field_ids = []
        for field in self.form_fields:
            if self.cleaned_data["field_%s_export" % field.id]:
                field_indexes[field.id] = len(field_indexes)
                if field.is_a(fields.FILE):
                    file_field_ids.append(field.id)
                elif field.is_a(*fields.DATES):
                    date_field_ids.append(field.id)
        num_columns = len(field_indexes)
        include_entry_time = self.cleaned_data["field_0_export"]
        if include_entry_time:
            num_columns += 1

        # Get the field entries for the given form and filter by entry_time
        # if specified.
        field_entries = FieldEntry.objects.filter(
            entry__form=self.form).order_by(
            "-entry__id").select_related("entry")
        if self.cleaned_data["field_0_filter"] == FILTER_CHOICE_BETWEEN:
            time_from = self.cleaned_data["field_0_from"]
            time_to = self.cleaned_data["field_0_to"]
            if time_from and time_to:
                field_entries = field_entries.filter(
                    entry__entry_time__range=(time_from, time_to))

        # Loop through each field value ordered by entry, building up each
        # entry as a row. Use the ``valid_row`` flag for marking a row as
        # invalid if it fails one of the filtering criteria specified.
        current_entry = None
        current_row = None
        valid_row = True
        for field_entry in field_entries:
            if field_entry.entry_id != current_entry:
                # New entry, write out the current row and start a new one.
                if valid_row and current_row is not None:
                    if not csv:
                        current_row.insert(0, current_entry)
                    yield current_row
                current_entry = field_entry.entry_id
                current_row = [""] * num_columns
                valid_row = True
                if include_entry_time:
                    current_row[-1] = field_entry.entry.entry_time
            field_value = field_entry.value or ""
            # Check for filter.
            field_id = field_entry.field_id
            filter_type = self.cleaned_data.get("field_%s_filter" % field_id)
            filter_args = None
            if filter_type:
                if filter_type == FILTER_CHOICE_BETWEEN:
                    f, t = "field_%s_from" % field_id, "field_%s_to" % field_id
                    filter_args = [self.cleaned_data[f], self.cleaned_data[t]]
                else:
                    field_name = "field_%s_contains" % field_id
                    filter_args = self.cleaned_data[field_name]
                    if filter_args:
                        filter_args = [filter_args]
            if filter_args:
                # Convert dates before checking filter.
                if field_id in date_field_ids:
                    y, m, d = field_value.split(" ")[0].split("-")
                    dte = date(int(y), int(m), int(d))
                    filter_args.append(dte)
                else:
                    filter_args.append(field_value)
                filter_func = FILTER_FUNCS[filter_type]
                if not filter_func(*filter_args):
                    valid_row = False
            # Create download URL for file fields.
            if field_entry.value and field_id in file_field_ids:
                url = reverse("admin:form_file", args=(field_entry.id,))
                field_value = self.request.build_absolute_uri(url)
                if not csv:
                    parts = (field_value, split(field_entry.value)[1])
                    field_value = mark_safe("<a href=\"%s\">%s</a>" % parts)
            # Only use values for fields that were selected.
            try:
                current_row[field_indexes[field_id]] = field_value
            except KeyError:
                pass
        # Output the final row.
        if valid_row and current_row is not None:
            if not csv:
                current_row.insert(0, current_entry)
            yield current_row