Converts a data collection to a CSV file.
354760
protected function processExportData($columns, $results, $options)
    {
        /*
         * Validate
         */
        if (!$results) {
            throw new ApplicationException(Lang::get('backend::lang.import_export.empty_error'));
        }

        /*
         * Parse options
         */
        $defaultOptions = [
            'firstRowTitles' => true,
            'useOutput' => false,
            'fileName' => 'export.csv',
            'delimiter' => null,
            'enclosure' => null,
            'escape' => null
        ];

        $options = array_merge($defaultOptions, $options);
        $columns = $this->exportExtendColumns($columns);

        /*
         * Prepare CSV
         */
        $csv = CsvWriter::createFromFileObject(new SplTempFileObject);
        
        $csv->setOutputBOM(CsvWriter::BOM_UTF8);

        if ($options['delimiter'] !== null) {
            $csv->setDelimiter($options['delimiter']);
        }

        if ($options['enclosure'] !== null) {
            $csv->setEnclosure($options['enclosure']);
        }

        if ($options['escape'] !== null) {
            $csv->setEscape($options['escape']);
        }

        /*
         * Add headers
         */
        if ($options['firstRowTitles']) {
            $headers = $this->getColumnHeaders($columns);
            $csv->insertOne($headers);
        }

        /*
         * Add records
         */
        foreach ($results as $result) {
            $data = $this->matchDataToColumns($result, $columns);
            $csv->insertOne($data);
        }

        /*
         * Output
         */
        if ($options['useOutput']) {
            $csv->output($options['fileName']);
        }

        /*
         * Save for download
         */
        $csvName = uniqid('oc');
        $csvPath = temp_path().'/'.$csvName;
        $output = $csv->__toString();

        File::put($csvPath, $output);

        return $csvName;
    }
668838
def save_dataset(self, dataset, filename=None, fill_value=None, **kwargs):
        """"""
        return self.save_datasets([dataset], filename, **kwargs)
181111
def csv_to_map(fields, delimiter=','):
    

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

        :param csv_input:
        :return:
        """
        io_file = io.StringIO(csv_input)
        return next(csv.reader(io_file, delimiter=delimiter))

    def _app(current_tuple, e=None):
        if current_tuple is None or len(current_tuple) == 0:
            return None, "no input"
        csv_list = _csv_to_list(current_tuple)
        if len(csv_list) != len(fields):
            e = {"input": "unexpected number of fields {} obtained {} expected".format(len(csv_list), len(fields))}
            return None, e
        return {k: v for (k, v) in zip(fields, csv_list)}, e
    if fields is None or len(fields) == 0:
        return fixed_input(None, "no fields provided, cannot proceed without order")
    return _app
525746
def from_csv(self, input_data):
        
        reformatted_data = []
        for (i,row) in enumerate(input_data):
            if i==0:
                headers = row
            else:
                data_row = {}
                for (j,h) in enumerate(headers):
                    data_row.update({h : row[j]})
                reformatted_data.append(data_row)
        return reformatted_data
925273
def to_csv(format = :long)
      output = ''
      
      columns = []
      # only output
      case format
      when :long
        columns.concat([@id, @updated, @title])
      end
      
      # output all dimensions
      columns.concat(@dimensions.map {|d| d.value})
      
      # output all metrics
      columns.concat(@metrics.map {|m| m.value})

      output = CSV.generate_line(columns)      
      return output
    end
1034693
def csv(ctx, dst):
    
    sm = Smother.load(ctx.obj['report'])
    semantic = ctx.obj['semantic']
    writer = _csv.writer(dst, lineterminator='\n')
    dst.write("source_context, test_context\n")
    writer.writerows(sm.iter_records(semantic=semantic))
1234416
def csv(self, output):
        """"""
        import csv
        csvwriter = csv.writer(self.outfile)
        csvwriter.writerows(output)
1190277
def record_to_objects(self):
        """"""
        from ambry.orm.exc import NotFoundError

        fr = self.record

        contents = fr.unpacked_contents

        if not contents:
            return

        # Zip transposes an array when in the form of a list of lists, so this transposes so
        # each row starts with the heading and the rest of the row are the values
        # for that row. The bool and filter return false when none of the values
        # are non-empty. Then zip again to transpose to original form.

        non_empty_rows = drop_empty(contents)

        s = self._dataset._database.session

        for i, row in enumerate(non_empty_rows):

            if i == 0:
                header = row
            else:
                d = dict(six.moves.zip(header, row))

                if 'widths' in d:
                    del d['widths']  # Obsolete column in old spreadsheets.

                if 'table' in d:
                    d['dest_table_name'] = d['table']
                    del d['table']

                if 'order' in d:
                    d['stage'] = d['order']
                    del d['order']

                if 'dest_table' in d:
                    d['dest_table_name'] = d['dest_table']
                    del d['dest_table']

                if 'source_table' in d:
                    d['source_table_name'] = d['source_table']
                    del d['source_table']

                d['d_vid'] = self._dataset.vid

                d['state'] = 'synced'

                try:
                    ds = self._dataset.source_file(str(d['name']))
                    ds.update(**d)
                except NotFoundError:
                    name = d['name']
                    del d['name']

                    try:
                        ds = self._dataset.new_source(name, **d)
                    except:
                        print(name, d)
                        import pprint
                        pprint.pprint(d)
                        raise
                except:  # Odd error with 'none' in keys for d
                    print('!!!', header)
                    print('!!!', row)
                    raise

                s.merge(ds)

        self._dataset._database.commit()
1325996
def gen_csv(sc, filename, field_list, source, filters):
    '''
    '''

    # First thing we need to do is initialize the csvfile and build the header
    # for the file.
    datafile = open(filename, 'wb')
    csvfile = csv.writer(datafile)
    header = []
    for field in field_list:
        header.append(fields.fields[field]['name'])
    csvfile.writerow(header)

    debug.write('Generating %s: ' % filename)
    # Next we will run the Security Center query.  because this could be a
    # potentially very large dataset that is returned, we don't want to run out
    # of memory.  To get around this, we will pass the query function the writer
    # function with the appropriate fields so that it is parsed inline.
    fparams = {'fobj': csvfile, 'flist': field_list}
    sc.query('vulndetails', source=source, 
             func=writer, func_params=fparams, **filters)
    debug.write('\n')

    # Lastly we need to close the datafile.
    datafile.close()
580650
def to_csvline(self, with_header=False):
        """"""
        string = ""

        if with_header:
            string += "# " + " ".join(at for at in AbinitTimerSection.FIELDS) + "\n"

        string += ", ".join(str(v) for v in self.to_tuple()) + "\n"
        return string
56867
def populateCsv(self):
    
    workingDirPath = createDir(self._workingDir)
    csvPath = os.path.join(workingDirPath, "data.csv")
    self.writeCsv(csvPath)
    return csvPath, workingDirPath
1294726
def save_csv(data,  # type: Iterable[Tuple[Union[str, int], ...]]
             headers,  # type: Iterable[str]
             file  # type: TextIO
             ):
    # type: (...) -> None
    

    print(','.join(headers), file=file)
    writer = csv.writer(file)
    writer.writerows(data)
1088083
def csv_response(self):
        """"""
        def stream():
            """Create data stream generator"""
            stream_file = io.StringIO()
            csvwriter = csv.writer(stream_file, delimiter=',', quotechar='"')

            csvwriter.writerow(self.get_current_fields())

            for index, item in enumerate(self.items()):
                csvwriter.writerow([value for index, value in item.items()])
                stream_file.seek(0)
                data = stream_file.read()
                stream_file.seek(0)
                stream_file.truncate()
                yield data

        response = StreamingHttpResponse(stream(), content_type="text/csv")
        response["Content-Disposition"] = "attachment; filename={}.csv".format(self.get_model_config().model_name.lower())
        return response
938632
def to_csv(options={})
      CSV.generate(options) do |csv|
        csv << scope.attributes
        csv << attributes_hash.values
      end
    end
871767
def bucketCSVs(csvFile, bucketIdx=2):
  """"""
  try:
    with open(csvFile, "rU") as f:
      reader = csv.reader(f)
      headers = next(reader, None)
      dataDict = OrderedDict()
      for lineNumber, line in enumerate(reader):
        if line[bucketIdx] in dataDict:
          dataDict[line[bucketIdx]].append(line)
        else:
          # new bucket
          dataDict[line[bucketIdx]] = [line]
  except IOError as e:
    print e

  filePaths = []
  for i, (_, lines) in enumerate(dataDict.iteritems()):
    bucketFile = csvFile.replace(".", "_"+str(i)+".")
    writeCSV(lines, headers, bucketFile)
    filePaths.append(bucketFile)

  return filePaths
951474
def to_csv(columns: nil)
      attributes = members
      attributes = columns & attributes if columns

      row = attributes.map! { |column| to_csv_value(column) }

      ::CSV.generate_line(row)
    end
278453
def to_csv(self, fileobj=sys.stdout):
        """"""
        openclose = is_string(fileobj)

        if openclose:
            fileobj = open(fileobj, "w")

        for idx, section in enumerate(self.sections):
            fileobj.write(section.to_csvline(with_header=(idx == 0)))
        fileobj.flush()

        if openclose:
            fileobj.close()