Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate the given Common_Lisp code snippet into C without altering its behavior. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Please provide an equivalent version of this Common_Lisp code in C. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Common_Lisp. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Common_Lisp code. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Write the same algorithm in C++ as shown in this Common_Lisp implementation. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Change the programming language of this snippet from Common_Lisp to Java without modifying what it does. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Produce a functionally identical Java code for the snippet given in Common_Lisp. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Convert this Common_Lisp block to Python, preserving its control flow and logic. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Preserve the algorithm and functionality while converting the code from Common_Lisp to Python. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Translate the given Common_Lisp code snippet into VB without altering its behavior. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Translate the given Common_Lisp code snippet into VB without altering its behavior. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Write the same code in Go as shown below in Common_Lisp. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Translate this program into Go but keep the logic exactly as in Common_Lisp. | (defun csvfile-to-nested-list (filename delim-char)
"Reads the csv to a nested list, where each sublist represents a line."
(with-open-file (input filename)
(loop :for line := (read-line input nil) :while line
:collect (read-from-string
(substitute #\SPACE delim-char
(format nil "(~a)~%" line))))))
(defun sublist-sum-list (nested-list)
"Return a list with the sum of each list of numbers in a nested list."
(mapcar (lambda (l) (if (every #'numberp l)
(reduce #'+ l) nil))
nested-list))
(defun append-each-sublist (nested-list1 nested-list2)
"Horizontally append the sublists in two nested lists. Used to add columns."
(mapcar #'append nested-list1 nested-list2))
(defun nested-list-to-csv (nested-list delim-string)
"Converts the nested list back into a csv-formatted string."
(format nil (concatenate 'string "~{~{~2,'0d" delim-string "~}~%~}")
nested-list))
(defun main ()
(let* ((csvfile-path #p"projekte/common-lisp/example_comma_csv.txt")
(result-path #p"results.txt")
(data-list (csvfile-to-nested-list csvfile-path #\,))
(list-of-sums (sublist-sum-list data-list))
(result-header "C1,C2,C3,C4,C5,SUM"))
(setf data-list
(rest
(append-each-sublist data-list
(mapcar #'list list-of-sums))))
(with-open-file (output result-path :direction :output :if-exists :supersede)
(format output "~a~%~a"
result-header (nested-list-to-csv data-list ",")))))
(main)
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Produce a language-to-language conversion: from D to C, same semantics. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Please provide an equivalent version of this D code in C. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Generate a C# translation of this D snippet without changing its computational steps. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Produce a functionally identical C# code for the snippet given in D. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Can you help me rewrite this code in C++ instead of D, keeping it the same logically? | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Transform the following D implementation into C++, maintaining the same output and logic. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Translate this program into Java but keep the logic exactly as in D. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Port the provided D code into Java while preserving the original functionality. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Generate an equivalent Python version of this D code. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Preserve the algorithm and functionality while converting the code from D to Python. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Keep all operations the same but rewrite the snippet in VB. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Maintain the same structure and functionality when rewriting this code in VB. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Port the following code from D to Go with equivalent syntax and logic. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Produce a language-to-language conversion: from D to Go, same semantics. | void main() {
import std.stdio, std.csv, std.file, std.typecons, std.array,
std.algorithm, std.conv, std.range;
auto rows = "csv_data_in.csv".File.byLine;
auto fout = "csv_data_out.csv".File("w");
fout.writeln(rows.front);
fout.writef("%(%(%d,%)\n%)", rows.dropOne
.map!(r => r.csvReader!int.front.map!(x => x + 1)));
}
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Port the following code from Delphi to C with equivalent syntax and logic. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Delphi version. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Translate the given Delphi code snippet into C# without altering its behavior. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Generate an equivalent C# version of this Delphi code. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Generate an equivalent C++ version of this Delphi code. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Delphi to C++. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Produce a language-to-language conversion: from Delphi to Java, same semantics. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Produce a language-to-language conversion: from Delphi to Java, same semantics. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Preserve the algorithm and functionality while converting the code from Delphi to Python. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Preserve the algorithm and functionality while converting the code from Delphi to VB. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Translate the given Delphi code snippet into VB without altering its behavior. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Transform the following Delphi implementation into Go, maintaining the same output and logic. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Please provide an equivalent version of this Delphi code in Go. | program CSV_data_manipulation;
uses
System.SysUtils,
System.IoUtils,
System.Types;
type
TStringDynArrayHelper = record helper for TStringDynArray
function Sum: Integer;
end;
function TStringDynArrayHelper.Sum: Integer;
var
value: string;
begin
Result := 0;
for value in self do
Result := Result + StrToIntDef(value, 0);
end;
const
FILENAME = './Data.csv';
var
i: integer;
Input, Row: TStringDynArray;
begin
Input := TFile.ReadAllLines(FILENAME);
for i := 0 to High(Input) do
begin
if i = 0 then
Input[i] := Input[i] + ',SUM'
else
begin
Row := Input[i].Split([',']);
Input[i] := Input[i] + ',' + row.Sum.ToString;
end;
end;
TFile.WriteAllLines(FILENAME, Input);
end.
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Convert this Elixir block to C, preserving its control flow and logic. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Convert the following code from Elixir to C, ensuring the logic remains intact. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Write a version of this Elixir function in C# with identical behavior. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Transform the following Elixir implementation into C#, maintaining the same output and logic. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Write the same code in Java as shown below in Elixir. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Translate the given Elixir code snippet into Java without altering its behavior. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Can you help me rewrite this code in Python instead of Elixir, keeping it the same logically? | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Translate this program into VB but keep the logic exactly as in Elixir. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Generate a VB translation of this Elixir snippet without changing its computational steps. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Generate a Go translation of this Elixir snippet without changing its computational steps. | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Can you help me rewrite this code in Go instead of Elixir, keeping it the same logically? | defmodule Csv do
defstruct header: "", data: "", separator: ","
def from_file(path) do
[header | data] = path
|> File.stream!
|> Enum.to_list
|> Enum.map(&String.trim/1)
%Csv{ header: header, data: data }
end
def sums_of_rows(csv) do
Enum.map(csv.data, fn (row) -> sum_of_row(row, csv.separator) end)
end
def sum_of_row(row, separator) do
row
|> String.split(separator)
|> Enum.map(&String.to_integer/1)
|> Enum.sum
|> to_string
end
def append_column(csv, column_header, column_data) do
header = append_to_row(csv.header, column_header, csv.separator)
data = [csv.data, column_data]
|> List.zip
|> Enum.map(fn ({ row, value }) ->
append_to_row(row, value, csv.separator)
end)
%Csv{ header: header, data: data }
end
def append_to_row(row, value, separator) do
row <> separator <> value
end
def to_file(csv, path) do
body = Enum.join([csv.header | csv.data], "\n")
File.write(path, body)
end
end
csv = Csv.from_file("in.csv")
csv
|> Csv.append_column("SUM", Csv.sums_of_rows(csv))
|> Csv.to_file("out.csv")
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Generate a C translation of this Erlang snippet without changing its computational steps. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Can you help me rewrite this code in C instead of Erlang, keeping it the same logically? | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Change the programming language of this snippet from Erlang to C# without modifying what it does. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Convert this Erlang snippet to C# and keep its semantics consistent. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Can you help me rewrite this code in C++ instead of Erlang, keeping it the same logically? | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Write the same code in C++ as shown below in Erlang. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Produce a functionally identical Java code for the snippet given in Erlang. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Erlang version. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Write the same code in Python as shown below in Erlang. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Generate a Python translation of this Erlang snippet without changing its computational steps. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Write a version of this Erlang function in VB with identical behavior. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Translate this program into VB but keep the logic exactly as in Erlang. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Write the same code in Go as shown below in Erlang. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Port the following code from Erlang to Go with equivalent syntax and logic. | -module( csv_data ).
-export( [change/2, from_binary/1, from_file/1, into_file/2, task/0] ).
change( CSV, Changes ) -> lists:foldl( fun change_foldl/2, CSV, Changes ).
from_binary( Binary ) ->
Lines = binary:split( Binary, <<"\n">>, [global] ),
[binary:split(X, <<",">>, [global]) || X <- Lines].
from_file( Name ) ->
{ok, Binary} = file:read_file( Name ),
from_binary( Binary ).
into_file( Name, CSV ) ->
Binaries = join_binaries( [join_binaries(X, <<",">>) || X <- CSV], <<"\n">> ),
file:write_file( Name, Binaries ).
task() ->
CSV = from_file( "CSV_file.in" ),
New_CSV = change( CSV, [{2,3,<<"23">>}, {4,4,<<"44">>}] ),
into_file( "CSV_file.out", New_CSV ).
change_foldl( {Row_number, Column_number, New}, Acc ) ->
{Row_befores, [Row_columns | Row_afters]} = split( Row_number, Acc ),
{Column_befores, [_Old | Column_afters]} = split( Column_number, Row_columns ),
Row_befores ++ [Column_befores ++ [New | Column_afters]] ++ Row_afters.
join_binaries( Binaries, Binary ) ->
[_Last | Rest] = lists:reverse( lists:flatten([[X, Binary] || X <- Binaries]) ),
lists:reverse( Rest ).
split( 1, List ) -> {[], List};
split( N, List ) -> lists:split( N - 1, List ).
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Transform the following F# implementation into C, maintaining the same output and logic. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Generate an equivalent C version of this F# code. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from F# to C#. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Produce a functionally identical C# code for the snippet given in F#. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Translate the given F# code snippet into C++ without altering its behavior. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Convert this F# snippet to C++ and keep its semantics consistent. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Port the following code from F# to Java with equivalent syntax and logic. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Convert this F# block to Python, preserving its control flow and logic. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Change the following F# code into Python without altering its purpose. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Ensure the translated VB code behaves exactly like the original F# snippet. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Produce a functionally identical VB code for the snippet given in F#. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Generate an equivalent Go version of this F# code. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Produce a functionally identical Go code for the snippet given in F#. | open System.IO
[<EntryPoint>]
let main _ =
let input = File.ReadAllLines "test_in.csv"
let output =
input
|> Array.mapi (fun i line ->
if i = 0 then line + ",SUM"
else
let sum = Array.sumBy int (line.Split(','))
sprintf "%s,%i" line sum)
File.WriteAllLines ("test_out.csv", output)
0
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Convert this Factor snippet to C and keep its semantics consistent. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Port the following code from Factor to C with equivalent syntax and logic. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Produce a language-to-language conversion: from Factor to C#, same semantics. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Port the following code from Factor to C# with equivalent syntax and logic. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Factor version. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Generate an equivalent C++ version of this Factor code. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Generate an equivalent Java version of this Factor code. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Change the following Factor code into Java without altering its purpose. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Write the same code in Python as shown below in Factor. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Convert the following code from Factor to Python, ensuring the logic remains intact. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Ensure the translated VB code behaves exactly like the original Factor snippet. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Produce a language-to-language conversion: from Factor to VB, same semantics. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Preserve the algorithm and functionality while converting the code from Factor to Go. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Translate the given Factor code snippet into Go without altering its behavior. | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Convert this Forth block to C, preserving its control flow and logic. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Write the same algorithm in C as shown in this Forth implementation. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Convert this Forth snippet to C# and keep its semantics consistent. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C#. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.