Configure the CSV format

 For example:

   csv do
     column :name
     column("Author") { |post| post.author.full_name }
   end

   csv col_sep: ";", force_quotes: true do
     column :name
   end
490629
def csv(options = {}, &block)
      options[:resource] = config

      config.csv_builder = CSVBuilder.new(options, &block)
    end
378825
function(csv, options) {
        // cache settings
        var separator = options.separator;
        var delimiter = options.delimiter;

        // set initial state if it's missing
        if(!options.state.rowNum) {
          options.state.rowNum = 1;
        }

        // clear initial state
        var entries = [];
        var state = 0;
        var entry = '';
        var exit = false;

        function endOfLine() {          
          // reset the state
          state = 0;
          
          // if 'start' hasn't been met, don't output
          if(options.start && options.state.rowNum < options.start) {
            // update global state
            entry = '';
            options.state.rowNum++;
            return;
          }
          
          if(options.onParseEntry === undefined) {
            // onParseEntry hook not set
            entries.push(entry);
          } else {
            var hookVal = options.onParseEntry(entry, options.state); // onParseEntry Hook
            // false skips the row, configurable through a hook
            if(hookVal !== false) {
              entries.push(hookVal);
            }
          }

          // cleanup
          entry = '';

          // if 'end' is met, stop parsing
          if(options.end && options.state.rowNum >= options.end) {
            exit = true;
          }
          
          // update global state
          options.state.rowNum++;
        }

        // escape regex-specific control chars
        var escSeparator = RegExp.escape(separator);
        var escDelimiter = RegExp.escape(delimiter);

        // compile the regEx str using the custom delimiter/separator
        var match = /(D|S|\n|\r|[^DS\r\n]+)/;
        var matchSrc = match.source;
        matchSrc = matchSrc.replace(/S/g, escSeparator);
        matchSrc = matchSrc.replace(/D/g, escDelimiter);
        match = RegExp(matchSrc, 'gm');
        
        // put on your fancy pants...
        // process control chars individually, use look-ahead on non-control chars
        csv.replace(match, function (m0) {
          if(exit) {
            return;
          }
          switch (state) {
            // the start of a value/entry
            case 0:
              // null value
              if (m0 === separator) {
                entry += m0;
                state = 0;
                break;
              }
              // opening delimiter
              if (m0 === delimiter) {
                entry += m0;
                state = 1;
                break;
              }
              // end of line
              if (m0 === '\n') {
                endOfLine();
                break;
              }
              // phantom carriage return
              if (/^\r$/.test(m0)) {
                break;
              }
              // un-delimit value
              entry += m0;
              state = 3;
              break;

            // delimited input
            case 1:
              // second delimiter? check further
              if (m0 === delimiter) {
                entry += m0;
                state = 2;
                break;
              }
              // delimited data
              entry += m0;
              state = 1;
              break;

            // delimiter found in delimited input
            case 2:
              // escaped delimiter?
              var prevChar = entry.substr(entry.length - 1);
              if (m0 === delimiter && prevChar === delimiter) {
                entry += m0;
                state = 1;
                break;
              }
              // end of value
              if (m0 === separator) {
                entry += m0;
                state = 0;
                break;
              }
              // end of line
              if (m0 === '\n') {
                endOfLine();
                break;
              }
              // phantom carriage return
              if (m0 === '\r') {
                break;
              }
              // broken paser?
              throw new Error('CSVDataError: Illegal state [Row:' + options.state.rowNum + ']');

            // un-delimited input
            case 3:
              // null value
              if (m0 === separator) {
                entry += m0;
                state = 0;
                break;
              }
              // end of line
              if (m0 === '\n') {
                endOfLine();
                break;
              }
              // phantom carriage return
              if (m0 === '\r') {
                break;
              }
              // non-compliant data
              if (m0 === delimiter) {
                throw new Error('CSVDataError: Illegal quote [Row:' + options.state.rowNum + ']');
              }
              // broken parser?
              throw new Error('CSVDataError: Illegal state [Row:' + options.state.rowNum + ']');
            default:
              // shenanigans
              throw new Error('CSVDataError: Unknown state [Row:' + options.state.rowNum + ']');
          }
          //console.log('val:' + m0 + ' state:' + state);
        });

        // submit the last entry
        // ignore null last line
        if(entry !== '') {
          endOfLine();
        }

        return entries;
      }
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
371195
def to_csv
      CSV.generate do |csv|
        csv << fields
        authors.each do |author|
          csv << fields.map do |f|
            author.send(f)
          end
        end
      end
    end
1052561
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs):
    
    result = None
    c_headers = [] if c_headers is None else c_headers
    r_headers = [] if r_headers is None else r_headers
    rows = [] if rows is None else rows

    result_format = kwargs.get('result_format', ARRAY_RAW_FORMAT)

    # DICT FORMAT
    if result_format == DICT_FORMAT:
        result = csv_dict_format(csv_data, c_headers, r_headers)

    # ARRAY_RAW_FORMAT
    elif result_format == ARRAY_RAW_FORMAT:
        result = rows

    # ARRAY_CLEAN_FORMAT
    elif result_format == ARRAY_CLEAN_FORMAT:
        result = csv_array_clean_format(csv_data, c_headers, r_headers)

    else:
        result = None

    # DEFAULT
    if result and result_format < DICT_FORMAT:
        result = [result]

    return result
758955
def produce_csv(input, output):
    
    '''
    output.write('"model","mean","std"\n')
    for model_data in input:
        output.write('"%s",%f,%f\n' % (model_data['name'], model_data['mean'], model_data['stddev']))
    output.flush()
    output.close()
    print("Wrote as %s" % output.name)
837495
def _format_output(content, typ):
    

    if "csv" in str(typ):
        return _format_csv(content, delimiter=",")

    if "tsv" in str(typ):
        return _format_csv(content, delimiter="\t")

    return content
586268
def savecsv(self, filename):
        ''''''
        f = open(filename, mode='w')
        headers = ["Seq", "Frame", "Cmd", "P1", "P2", "P3", "P4", "X", "Y", "Z"]
        print(self.csv_line(headers))
        f.write(self.csv_line(headers) + "\n")
        for w in self.wploader.wpoints:
            if getattr(w, 'comment', None):
#                f.write("# %s\n" % w.comment)
                pass
            out_list = [ w.seq,
                         self.pretty_enum_value('MAV_FRAME', w.frame),
                         self.pretty_enum_value('MAV_CMD', w.command),
                         self.pretty_parameter_value(w.param1),
                         self.pretty_parameter_value(w.param2),
                         self.pretty_parameter_value(w.param3),
                         self.pretty_parameter_value(w.param4),
                         self.pretty_parameter_value(w.x),
                         self.pretty_parameter_value(w.y),
                         self.pretty_parameter_value(w.z),
                         ]
            print(self.csv_line(out_list))
            f.write(self.csv_line(out_list) + "\n")
        f.close()
872240
def set_col(col, val)
      if !col.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
        raise ArgumentError, 'Illegal argument type'
      elsif val.is_a?(Array) && val.size != row_keys.size
        raise ArgumentError, 'Row size not match'
      end

      case val
      when Array
        if @col_keys[col]
          col = @col_keys[col]
          val.each_with_index { |v, row| @content[row][col] = v }
        else
          col = @col_keys[col] = @col_keys.size
          val.each_with_index { |v, row| @content[row] << v }
        end
      when Hash
        unless @col_keys[col]
          @col_keys[col] = @col_keys.size
          @content.each { |arr| arr << '' }
        end

        col = @col_keys[col]
        val.each do |k, v|
          row = @row_keys[k]
          @content[row][col] = v if row
        end
      end

      self
    end
1342513
def convert(input_file_name, **kwargs):
    """"""
    delimiter = kwargs["delimiter"] or ","
    quotechar = kwargs["quotechar"] or "|"

    if six.PY2:
        delimiter = delimiter.encode("utf-8")
        quotechar = quotechar.encode("utf-8")

    # Read CSV and form a header and rows list
    with open(input_file_name, "rb") as input_file:
        reader = csv.reader(input_file,
                            encoding="utf-8",
                            delimiter=delimiter,
                            quotechar=quotechar)

        csv_headers = []
        if not kwargs.get("no_header"):
            # Read header from first line
            csv_headers = next(reader)

        csv_rows = [row for row in reader if row]

        # Set default column name if header is not present
        if not csv_headers and len(csv_rows) > 0:
            end = len(csv_rows[0]) + 1
            csv_headers = ["Column {}".format(n) for n in range(1, end)]

    # Render csv to HTML
    html = render_template(csv_headers, csv_rows, **kwargs)

    # Freeze all JS files in template
    return freeze_js(html)
1076230
def format_table(table, column_names=None, column_specs=None, max_col_width=32,
                 report_dimensions=False):
    ''' 

    '''
    if len(table) > 0:
        col_widths = [0] * len(list(table)[0])
    elif column_specs is not None:
        col_widths = [0] * (len(column_specs) + 1)
    elif column_names is not None:
        col_widths = [0] * len(column_names)
    my_column_names = []
    if column_specs is not None:
        column_names = ['Row']
        column_names.extend([col['name'] for col in column_specs])
        column_specs = [{'name': 'Row', 'type': 'float'}] + column_specs
    if column_names is not None:
        for i in range(len(column_names)):
            my_col = str(column_names[i])
            if len(my_col) > max_col_width:
                my_col = my_col[:max_col_width-1] + '…'
            my_column_names.append(my_col)
            col_widths[i] = max(col_widths[i], len(my_col))
    my_table = []
    for row in table:
        my_row = []
        for i in range(len(row)):
            my_item = escape_unicode_string(str(row[i]))
            if len(my_item) > max_col_width:
                my_item = my_item[:max_col_width-1] + '…'
            my_row.append(my_item)
            col_widths[i] = max(col_widths[i], len(my_item))
        my_table.append(my_row)

    def border(i):
        return WHITE() + i + ENDC()

    type_colormap = {'boolean': BLUE(),
                     'integer': YELLOW(),
                     'float': WHITE(),
                     'string': GREEN()}
    for i in 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64':
        type_colormap[i] = type_colormap['integer']
    type_colormap['double'] = type_colormap['float']

    def col_head(i):
        if column_specs is not None:
            return BOLD() + type_colormap[column_specs[i]['type']] + column_names[i] + ENDC()
        else:
            return BOLD() + WHITE() + column_names[i] + ENDC()

    formatted_table = [border('┌') + border('┬').join(border('─')*i for i in col_widths) + border('┐')]
    if len(my_column_names) > 0:
        padded_column_names = [col_head(i) + ' '*(col_widths[i]-len(my_column_names[i])) for i in range(len(my_column_names))]
        formatted_table.append(border('│') + border('│').join(padded_column_names) + border('│'))
        formatted_table.append(border('├') + border('┼').join(border('─')*i for i in col_widths) + border('┤'))

    for row in my_table:
        padded_row = [row[i] + ' '*(col_widths[i]-len(row[i])) for i in range(len(row))]
        formatted_table.append(border('│') + border('│').join(padded_row) + border('│'))
    formatted_table.append(border('└') + border('┴').join(border('─')*i for i in col_widths) + border('┘'))

    if report_dimensions:
        return '\n'.join(formatted_table), len(formatted_table), sum(col_widths) + len(col_widths) + 1
    else:
        return '\n'.join(formatted_table)
598878
def csv_writer(csvfile):
        
        if sys.version_info >= (3,):
            writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
        else:
            writer = csv.writer(csvfile, delimiter=b',', lineterminator='\n')

        return writer
582927
def write_to_csv(file_name, mode = "w")
      File.open(file_name, mode) do |file|
        all.copy_csv(file)
      end
    end
815467
def validate_csv(file):
    """"""
    try:
        # Detect encoding and dialect
        with file.open() as fp:
            encoding = detect_encoding(fp, default='utf-8')
            sample = fp.read(
                current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024))
            delimiter = csv.Sniffer().sniff(sample.decode(encoding)).delimiter
            is_valid = True
    except Exception as e:
        current_app.logger.debug(
            'File {0} is not valid CSV: {1}'.format(file.uri, e))
        encoding = ''
        delimiter = ''
        is_valid = False

    return {
        'delimiter': delimiter,
        'encoding': encoding,
        'is_valid': is_valid
    }
181832
def dump_csv(data: List[dict], fieldnames: Sequence[str], with_header: bool = False, crlf: bool = False,
             tsv: bool = False) -> str:
    

    def force_str(v):
        # XXX: Double quotation behaves strangely... so replace (why?)
        return dump_json(v).replace('"', "'") if isinstance(v, (dict, list)) else v

    with io.StringIO() as sio:
        dialect = get_dialect_name(crlf, tsv)
        writer = csv.DictWriter(sio, fieldnames=fieldnames, dialect=dialect, extrasaction='ignore')
        if with_header:
            writer.writeheader()
        for x in data:
            writer.writerow({k: force_str(v) for k, v in x.items()})
        sio.seek(0)
        return sio.read()
460373
function formatCSV(values) {
    if (values instanceof Array) {
        return values.map(v => formatValue(v)).join();
    }
    if (typeof values === 'object' && values !== null) {
        return Object.keys(values).map(v => formatValue(values[v])).join();
    }
    return values === undefined ? '' : formatValue(values);
}
9541
def DumpAsCSV (self, separator=",", file=sys.stdout):
                """"""
                for row in range(1, self.maxRow + 1):
                        sep = ""
                        for column in range(1, self.maxColumn + 1):
                                file.write("%s\"%s\"" % (sep, self.GetCellValue(column, row, "")))
                                sep = separator
                        file.write("\n")