Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following Mathematica implementation into Java, maintaining the same output and logic.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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) { } } }
Preserve the algorithm and functionality while converting the code from Mathematica to Java.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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) { } } }
Please provide an equivalent version of this Mathematica code in Python.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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='')
Produce a language-to-language conversion: from Mathematica to Python, same semantics.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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 Mathematica code into VB without altering its purpose.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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
Change the following Mathematica code into VB without altering its purpose.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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
Please provide an equivalent version of this Mathematica code in Go.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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 Mathematica block to Go, preserving its control flow and logic.
iCSV=Import["test.csv"] ->{{"C1","C2","C3","C4","C5"},{1,5,9,13,17},{2,6,10,14,18},{3,7,11,15,19},{4,8,12,16,20}} iCSV = Transpose@ Append[Transpose[iCSV], Join[{"Sum"}, Total /@ Drop[iCSV, 1]]]; iCSV // MatrixForm Export["test.csv",iCSV];
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 C but keep the logic exactly as in MATLAB.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
#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; }
Transform the following MATLAB implementation into C, maintaining the same output and logic.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
#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 MATLAB code in C#.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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 MATLAB code.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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); } } }
Write the same algorithm in C++ as shown in this MATLAB implementation.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
#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 MATLAB.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
#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; }
Can you help me rewrite this code in Java instead of MATLAB, keeping it the same logically?
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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 the snippet below in Java so it works the same as the original MATLAB code.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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 MATLAB.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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='')
Port the following code from MATLAB to Python with equivalent syntax and logic.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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 MATLAB code into VB without altering its purpose.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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 MATLAB to VB.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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 MATLAB implementation into Go, maintaining the same output and logic.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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) } }
Change the programming language of this snippet from MATLAB to Go without modifying what it does.
filename='data.csv'; fid = fopen(filename); header = fgetl(fid); fclose(fid); X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,' for k=1:size(X,1), fprintf(fid," fprintf(fid," end; fclose(fid);
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 C code for the snippet given in Nim.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
#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 Nim snippet to C and keep its semantics consistent.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
#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 Nim version.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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 Nim code.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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 Nim version.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
#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 Nim block to C++, preserving its control flow and logic.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
#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; }
Keep all operations the same but rewrite the snippet in Java.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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) { } } }
Preserve the algorithm and functionality while converting the code from Nim to Python.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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 Nim snippet without changing its computational steps.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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 Nim to VB, ensuring the logic remains intact.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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
Ensure the translated VB code behaves exactly like the original Nim snippet.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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 algorithm in Go as shown in this Nim implementation.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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 Nim code snippet into Go without altering its behavior.
import strutils, streams let csv = newFileStream("data.csv", fmRead) outf = newFileStream("data-out.csv", fmWrite) var lineNumber = 1 while true: if atEnd(csv): break var line = readLine(csv) if lineNumber == 1: line.add(",SUM") else: var sum = 0 for n in split(line, ","): sum += parseInt(n) line.add(",") line.add($sum) outf.writeLine(line) inc lineNumber
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 OCaml snippet to C and keep its semantics consistent.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
#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; }
Keep all operations the same but rewrite the snippet in C.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
#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 OCaml to C#.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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 OCaml, keeping it the same logically?
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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 language-to-language conversion: from OCaml to C++, same semantics.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
#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; }
Please provide an equivalent version of this OCaml code in C++.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
#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 following OCaml code into Java without altering its purpose.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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 the following code from OCaml to Java, ensuring the logic remains intact.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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) { } } }
Transform the following OCaml implementation into Python, maintaining the same output and logic.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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 this OCaml block to Python, preserving its control flow and logic.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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='')
Port the following code from OCaml to VB with equivalent syntax and logic.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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
Rewrite the snippet below in VB so it works the same as the original OCaml code.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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 OCaml to Go.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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 OCaml code snippet into Go without altering its behavior.
let list_add_last this lst = List.rev (this :: (List.rev lst)) let () = let csv = Csv.load "data.csv" in let fields, data = (List.hd csv, List.tl csv) in let fields = list_add_last "SUM" fields in let sums = List.map (fun row -> let tot = List.fold_left (fun tot this -> tot + int_of_string this) 0 row in list_add_last (string_of_int tot) row ) data in Csv.output_all (Csv.to_channel stdout) (fields :: sums)
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) } }
Keep all operations the same but rewrite the snippet in C.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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; }
Preserve the algorithm and functionality while converting the code from Pascal to C.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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 Pascal code snippet into C# without altering its behavior.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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); } } }
Ensure the translated C# code behaves exactly like the original Pascal snippet.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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); } } }
Convert this Pascal block to C++, preserving its control flow and logic.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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; }
Please provide an equivalent version of this Pascal code in C++.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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; }
Write a version of this Pascal function in Java with identical behavior.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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) { } } }
Write the same code in Java as shown below in Pascal.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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) { } } }
Convert this Pascal block to Python, preserving its control flow and logic.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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='')
Ensure the translated VB code behaves exactly like the original Pascal snippet.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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
Convert this Pascal snippet to VB and keep its semantics consistent.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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
Produce a language-to-language conversion: from Pascal to Go, same semantics.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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) } }
Produce a functionally identical Go code for the snippet given in Pascal.
program CSV_Data_Manipulation; uses Classes, SysUtils; var s: string; ts: tStringList; inFile, outFile: Text; Sum: integer; Number: string; begin Assign(inFile,'input.csv'); Reset(inFile); Assign(outFile,'result.csv'); Rewrite(outFile); ts:=tStringList.Create; ts.StrictDelimiter:=True; ReadLn(inFile,s); ts.CommaText:=s; ts.Add('SUM'); WriteLn(outFile,ts.CommaText); while not eof(inFile) do begin ReadLn(inFile,s); ts.CommaText:=s; Sum:=0; for Number in ts do Sum+=StrToInt(Number); ts.Add('%D',[Sum]); writeln(outFile, ts.CommaText); end; Close(outFile); Close(inFile); ts.Free; 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 Perl code in C.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
#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 this program into C but keep the logic exactly as in Perl.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
#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 Perl implementation.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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 Perl, keeping it the same logically?
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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 Perl implementation into C++, maintaining the same output and logic.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
#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 Perl snippet to C++ and keep its semantics consistent.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
#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 following Perl code into Java without altering its purpose.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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 Java version of this Perl code.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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 Perl.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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='')
Rewrite the snippet below in Python so it works the same as the original Perl code.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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='')
Produce a functionally identical VB code for the snippet given in Perl.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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 Perl.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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 provided Perl code into Go while preserving the original functionality.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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) } }
Write a version of this Perl function in Go with identical behavior.
use warnings; use strict; use List::Util 'sum'; my @header = split /,/, <>; chomp $header[-1]; my %column_number; for my $i (0 .. $ $column_number{$header[$i]} = $i; } my @rows = map [ split /,/ ], <>; chomp $_->[-1] for @rows; $_->[1]++ for @rows; $_->[ $column_number{C4} ] += $_->[ $column_number{C1} ] for @rows; push @header, 'Sum'; $column_number{Sum} = $ push @$_, sum(@$_) for @rows; push @rows, [ map { my $col = $_; sum(map $_->[ $column_number{$col} ], @rows); } @header ]; print join(',' => @header), "\n"; print join(',' => @$_), "\n" for @rows;
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) } }
Write the same algorithm in C as shown in this PowerShell implementation.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
#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 PowerShell code in C.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
#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 PowerShell block to C#, preserving its control flow and logic.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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 this program into C# but keep the logic exactly as in PowerShell.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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 PowerShell code.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
#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 PowerShell to C++, same semantics.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
#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; }
Rewrite the snippet below in Java so it works the same as the original PowerShell code.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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 PowerShell version.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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='')
Maintain the same structure and functionality when rewriting this code in Python.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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='')
Maintain the same structure and functionality when rewriting this code in VB.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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
Rewrite the snippet below in VB so it works the same as the original PowerShell code.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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
Please provide an equivalent version of this PowerShell code in Go.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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 Go translation of this PowerShell snippet without changing its computational steps.
@" C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 "@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force $records = Import-Csv -Path .\Temp.csv $sums = $records | ForEach-Object { [int]$sum = 0 foreach ($field in $_.PSObject.Properties.Name) { $sum += $_.$field } $sum } $records = for ($i = 0; $i -lt $sums.Count; $i++) { $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} } $records | Export-Csv -Path .\Temp.csv -Force $records | Format-Table -AutoSize
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) } }
Keep all operations the same but rewrite the snippet in C.
write.csv(df, file = "foo.csv",row.names = FALSE)
#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 R code snippet into C without altering its behavior.
write.csv(df, file = "foo.csv",row.names = FALSE)
#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 R, keeping it the same logically?
write.csv(df, file = "foo.csv",row.names = FALSE)
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); } } }
Preserve the algorithm and functionality while converting the code from R to C#.
write.csv(df, file = "foo.csv",row.names = FALSE)
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 provided R code into C++ while preserving the original functionality.
write.csv(df, file = "foo.csv",row.names = FALSE)
#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++.
write.csv(df, file = "foo.csv",row.names = FALSE)
#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 the following code from R to Java, ensuring the logic remains intact.
write.csv(df, file = "foo.csv",row.names = FALSE)
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 following code from R to Java with equivalent syntax and logic.
write.csv(df, file = "foo.csv",row.names = FALSE)
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 R code snippet into Python without altering its behavior.
write.csv(df, file = "foo.csv",row.names = FALSE)
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 R snippet without changing its computational steps.
write.csv(df, file = "foo.csv",row.names = FALSE)
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='')