Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate the given Forth code snippet into C++ without altering its behavior. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| #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 C++ instead of Forth, keeping it the same logically? |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| #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 Forth code in Java. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| 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) {
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| 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 Forth snippet to Python and keep its semantics consistent. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| 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 Forth to Python, same semantics. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Keep all operations the same but rewrite the snippet in VB. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| 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 Forth to VB. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Port the following code from Forth to Go with equivalent syntax and logic. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Port the provided Forth code into Go while preserving the original functionality. |
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum
0E0 OVER SWAP BOUNDS
?DO
I C@ SEPARATOR =
IF
I TUCK OVER - >FLOAT IF F+ THEN
1+
THEN
LOOP DROP
;
: f>string
FSCALE F*
F>D TUCK DABS <# DECIMALS 0 DO # LOOP [CHAR] . HOLD #S ROT SIGN #>
;
: rowC!+
OVER HERE + C! 1+
;
: row$!+
ROT 2DUP + >R HERE + SWAP MOVE R>
;
: csvsum
2DUP
HERE UNUSED ROT READ-LINE THROW
IF
HERE SWAP
SEPARATOR rowC!+
s
ROT WRITE-LINE THROW
BEGIN
2DUP HERE UNUSED ROT READ-LINE THROW
WHILE
HERE SWAP
SEPARATOR rowC!+
HERE OVER colsum f>string
row$!+
ROT WRITE-LINE THROW
REPEAT
THEN
2DROP 2DROP
;
| 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 Fortran snippet to C# and keep its semantics consistent. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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 Fortran snippet to C# and keep its semantics consistent. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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 Fortran to C++, same semantics. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Transform the following Fortran implementation into C++, maintaining the same output and logic. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| #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 C so it works the same as the original Fortran code. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| #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 Fortran code snippet into C without altering its behavior. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| #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 Fortran code in Java. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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 Fortran. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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) {
}
}
}
|
Ensure the translated Python code behaves exactly like the original Fortran snippet. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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 Fortran code. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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 Fortran to VB with equivalent syntax and logic. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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 Fortran code into VB while preserving the original functionality. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| 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
|
Keep all operations the same but rewrite the snippet in PHP. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| <?php
$handle = fopen('data_in.csv','r');
$handle_output = fopen('data_out.csv','w');
$row = 0;
$arr = array();
while ($line = fgetcsv($handle))
{
$arr[] = $line;
}
$arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17
$arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18
foreach ($arr as $line)
{
if ($row==0)
{
array_push($line,"SUM");
}
else
{
array_push($line,array_sum($line));
}
fputcsv($handle_output, $line);
$row++;
}
?>
|
Translate the given Fortran code snippet into PHP without altering its behavior. | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, file=name, action="read", form="formatted", access="stream")
deallocate(name)
call get_command_argument(2, length=n)
allocate(character(n) :: name)
call get_command_argument(2, name)
open(unit=11, file=name, action="write", form="formatted", access="stream")
deallocate(name)
nrow = 0
ncol = 0
do while (readline(10, line))
nrow = nrow + 1
call split(line, a)
if (nrow == 1) then
ncol = size(a)
write(11, "(A)", advance="no") line
write(11, "(A)") ",Sum"
allocate(v(ncol + 1))
write(fmt, "('(',G0,'(G0,:,''',A,'''))')") ncol + 1, ","
else
if (size(a) /= ncol) then
print "(A,' ',G0)", "Invalid number of values on row", nrow
stop
end if
do i = 1, ncol
read(a(i), *) v(i)
end do
v(ncol + 1) = sum(v(1:ncol))
write(11, fmt) v
end if
end do
close(10)
close(11)
contains
function readline(unit, line)
use iso_fortran_env
logical :: readline
integer :: unit, ios, n
character(:), allocatable :: line
character(10) :: buffer
line = ""
readline = .false.
do
read(unit, "(A)", advance="no", size=n, iostat=ios) buffer
if (ios == iostat_end) return
readline = .true.
line = line // buffer(1:n)
if (ios == iostat_eor) return
end do
end function
subroutine split(line, array, separator)
character(*) line
character(:), allocatable :: array(:)
character, optional :: separator
character :: sep
integer :: n, m, p, i, k
if (present(separator)) then
sep = separator
else
sep = ","
end if
n = len(line)
m = 0
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
p = p + 1
m = max(m, i - k)
k = i + 1
end if
end do
m = max(m, n - k + 1)
if (allocated(array)) deallocate(array)
allocate(character(m) :: array(p))
p = 1
k = 1
do i = 1, n
if (line(i:i) == sep) then
array(p) = line(k:i-1)
p = p + 1
k = i + 1
end if
end do
array(p) = line(k:n)
end subroutine
end program
| <?php
$handle = fopen('data_in.csv','r');
$handle_output = fopen('data_out.csv','w');
$row = 0;
$arr = array();
while ($line = fgetcsv($handle))
{
$arr[] = $line;
}
$arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17
$arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18
foreach ($arr as $line)
{
if ($row==0)
{
array_push($line,"SUM");
}
else
{
array_push($line,array_sum($line));
}
fputcsv($handle_output, $line);
$row++;
}
?>
|
Write a version of this Groovy function in C with identical behavior. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| #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 Groovy implementation into C, maintaining the same output and logic. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| #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 Groovy version. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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 Groovy implementation. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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 Groovy implementation. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| #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 Groovy snippet to C++ and keep its semantics consistent. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| #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 Groovy, keeping it the same logically? | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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 Groovy snippet to Python and keep its semantics consistent. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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='')
|
Please provide an equivalent version of this Groovy code in VB. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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 Groovy. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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 this program in Go while keeping its functionality equivalent to the Groovy version. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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 Groovy block to Go, preserving its control flow and logic. | def csv = []
def loadCsv = { source -> source.splitEachLine(/,/) { csv << it.collect { it } } }
def saveCsv = { target -> target.withWriter { writer -> csv.each { writer.println it.join(',') } } }
loadCsv new File('csv.txt')
csv[0][0] = 'Column0'
(1..4).each { i -> csv[i][i] = i * 100 }
saveCsv new File('csv_out.txt')
| 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 an equivalent C version of this Haskell code. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Convert the following code from Haskell to C, ensuring the logic remains intact. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Port the following code from Haskell to C# with equivalent syntax and logic. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| 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);
}
}
}
|
Change the programming language of this snippet from Haskell to C# without modifying what it does. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| 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 a C++ translation of this Haskell snippet without changing its computational steps. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Change the programming language of this snippet from Haskell to C++ without modifying what it does. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| #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 Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Port the provided Haskell code into Java while preserving the original functionality. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| 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 algorithm in Python as shown in this Haskell implementation. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Write the same code in Python as shown below in Haskell. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Write the same code in VB as shown below in Haskell. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| 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 Haskell to VB. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| 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 Go so it works the same as the original Haskell code. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| 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 Haskell function in Go with identical behavior. | import Data.Array (Array(..), (//), bounds, elems, listArray)
import Data.List (intercalate)
import Control.Monad (when)
import Data.Maybe (isJust)
delimiters :: String
delimiters = ",;:"
fields :: String -> [String]
fields [] = []
fields xs =
let (item, rest) = break (`elem` delimiters) xs
(_, next) = break (`notElem` delimiters) rest
in item : fields next
unfields :: Maybe (Array (Int, Int) String) -> [String]
unfields Nothing = []
unfields (Just a) = every fieldNumber $ elems a
where
((_, _), (_, fieldNumber)) = bounds a
every _ [] = []
every n xs =
let (y, z) = splitAt n xs
in intercalate "," y : every n z
fieldArray :: [[String]] -> Maybe (Array (Int, Int) String)
fieldArray [] = Nothing
fieldArray xs =
Just $ listArray ((1, 1), (length xs, length $ head xs)) $ concat xs
fieldsFromFile :: FilePath -> IO (Maybe (Array (Int, Int) String))
fieldsFromFile = fmap (fieldArray . map fields . lines) . readFile
fieldsToFile :: FilePath -> Maybe (Array (Int, Int) String) -> IO ()
fieldsToFile f = writeFile f . unlines . unfields
someChanges :: Maybe (Array (Int, Int) String)
-> Maybe (Array (Int, Int) String)
someChanges =
fmap (// [((1, 1), "changed"), ((3, 4), "altered"), ((5, 2), "modified")])
main :: IO ()
main = do
a <- fieldsFromFile "example.txt"
when (isJust a) $ fieldsToFile "output.txt" $ someChanges a
| 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)
}
}
|
Preserve the algorithm and functionality while converting the code from J to C. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| #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 J. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Convert the following code from J to C#, ensuring the logic remains intact. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| 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 a C# translation of this J snippet without changing its computational steps. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| 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 J snippet to C++ and keep its semantics consistent. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| #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 this program in C++ while keeping its functionality equivalent to the J version. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| #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 J code into Java without altering its purpose. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Produce a language-to-language conversion: from J to Java, same semantics. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| 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 J to Python, ensuring the logic remains intact. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Translate the given J code snippet into Python without altering its behavior. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| 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 J snippet. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Generate an equivalent VB version of this J code. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| 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 J to Go, same semantics. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| 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 J function in Go with identical behavior. | data=: (','&splitstring);.2 freads 'rc_csv.csv'
data=: (<'"spam"') (<2 3)} data
'rc_outcsv.csv' fwrites~ ;<@(','&joinstring"1) data
| package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
|
Produce a language-to-language conversion: from Julia to C, same semantics. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Produce a language-to-language conversion: from Julia to C, same semantics. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| #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 Julia. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| 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);
}
}
}
|
Please provide an equivalent version of this Julia code in C#. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| #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 Julia. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| #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;
}
|
Ensure the translated Java code behaves exactly like the original Julia snippet. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| 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) {
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| 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 Julia block to Python, preserving its control flow and logic. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Write the same algorithm in VB as shown in this Julia implementation. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| 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 Julia implementation into VB, maintaining the same output and logic. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| 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 Go so it works the same as the original Julia code. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| 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 the following code from Julia to Go, ensuring the logic remains intact. | using DataFrames, CSV
ifn = "csv_data_manipulation_in.dat"
ofn = "csv_data_manipulation_out.dat"
df = CSV.read(ifn, DataFrame)
df.SUM = sum.(eachrow(df))
CSV.write(ofn, df)
| 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 Lua snippet to C and keep its semantics consistent. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| #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 code in C as shown below in Lua. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| #define TITLE "CSV data manipulation"
#define URL "http:
#define _GNU_SOURCE
#define bool int
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
typedef struct {
char * delim;
unsigned int rows;
unsigned int cols;
char ** table;
} CSV;
int trim(char ** str) {
int trimmed;
int n;
int len;
len = strlen(*str);
n = len - 1;
while((n>=0) && isspace((*str)[n])) {
(*str)[n] = '\0';
trimmed += 1;
n--;
}
n = 0;
while((n < len) && (isspace((*str)[0]))) {
(*str)[0] = '\0';
*str = (*str)+1;
trimmed += 1;
n++;
}
return trimmed;
}
int csv_destroy(CSV * csv) {
if (csv == NULL) { return 0; }
if (csv->table != NULL) { free(csv->table); }
if (csv->delim != NULL) { free(csv->delim); }
free(csv);
return 0;
}
CSV * csv_create(unsigned int cols, unsigned int rows) {
CSV * csv;
csv = malloc(sizeof(CSV));
csv->rows = rows;
csv->cols = cols;
csv->delim = strdup(",");
csv->table = malloc(sizeof(char *) * cols * rows);
if (csv->table == NULL) { goto error; }
memset(csv->table, 0, sizeof(char *) * cols * rows);
return csv;
error:
csv_destroy(csv);
return NULL;
}
char * csv_get(CSV * csv, unsigned int col, unsigned int row) {
unsigned int idx;
idx = col + (row * csv->cols);
return csv->table[idx];
}
int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) {
unsigned int idx;
idx = col + (row * csv->cols);
csv->table[idx] = value;
return 0;
}
void csv_display(CSV * csv) {
int row, col;
char * content;
if ((csv->rows == 0) || (csv->cols==0)) {
printf("[Empty table]\n");
return ;
}
printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows);
for (row=0; row<csv->rows; row++) {
printf("[|");
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
printf("%s\t|", content);
}
printf("]\n");
}
printf("\n");
}
int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) {
unsigned int cur_col,
cur_row,
max_cols,
max_rows;
CSV * new_csv;
char * content;
bool in_old, in_new;
new_csv = csv_create(new_cols, new_rows);
if (new_csv == NULL) { goto error; }
new_csv->rows = new_rows;
new_csv->cols = new_cols;
max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols;
max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows;
for (cur_col=0; cur_col<max_cols; cur_col++) {
for (cur_row=0; cur_row<max_rows; cur_row++) {
in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows);
in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows);
if (in_old && in_new) {
content = csv_get(old_csv, cur_col, cur_row);
csv_set(new_csv, cur_col, cur_row, content);
} else if (in_old) {
content = csv_get(old_csv, cur_col, cur_row);
free(content);
} else { }
}
}
free(old_csv->table);
old_csv->rows = new_rows;
old_csv->cols = new_cols;
old_csv->table = new_csv->table;
new_csv->table = NULL;
csv_destroy(new_csv);
return 0;
error:
printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno));
return -1;
}
int csv_open(CSV * csv, char * filename) {
FILE * fp;
unsigned int m_rows;
unsigned int m_cols, cols;
char line[2048];
char * lineptr;
char * token;
fp = fopen(filename, "r");
if (fp == NULL) { goto error; }
m_rows = 0;
m_cols = 0;
while(fgets(line, sizeof(line), fp) != NULL) {
m_rows += 1;
cols = 0;
lineptr = line;
while ((token = strtok(lineptr, csv->delim)) != NULL) {
lineptr = NULL;
trim(&token);
cols += 1;
if (cols > m_cols) { m_cols = cols; }
csv_resize(csv, m_cols, m_rows);
csv_set(csv, cols-1, m_rows-1, strdup(token));
}
}
fclose(fp);
csv->rows = m_rows;
csv->cols = m_cols;
return 0;
error:
fclose(fp);
printf("Unable to open %s for reading.", filename);
return -1;
}
int csv_save(CSV * csv, char * filename) {
FILE * fp;
int row, col;
char * content;
fp = fopen(filename, "w");
for (row=0; row<csv->rows; row++) {
for (col=0; col<csv->cols; col++) {
content = csv_get(csv, col, row);
fprintf(fp, "%s%s", content,
((col == csv->cols-1) ? "" : csv->delim) );
}
fprintf(fp, "\n");
}
fclose(fp);
return 0;
}
int main(int argc, char ** argv) {
CSV * csv;
printf("%s\n%s\n\n",TITLE, URL);
csv = csv_create(0, 0);
csv_open(csv, "fixtures/csv-data-manipulation.csv");
csv_display(csv);
csv_set(csv, 0, 0, "Column0");
csv_set(csv, 1, 1, "100");
csv_set(csv, 2, 2, "200");
csv_set(csv, 3, 3, "300");
csv_set(csv, 4, 4, "400");
csv_display(csv);
csv_save(csv, "tmp/csv-data-manipulation.result.csv");
csv_destroy(csv);
return 0;
}
|
Generate a C# translation of this Lua snippet without changing its computational steps. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| 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 Lua implementation into C#, maintaining the same output and logic. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| 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);
}
}
}
|
Change the following Lua code into C++ without altering its purpose. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| #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 Lua code in C++. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| #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 Lua block to Java, preserving its control flow and logic. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| 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 a version of this Lua function in Java with identical behavior. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
}
|
Port the provided Lua code into Python while preserving the original functionality. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| import fileinput
changerow, changecolumn, changevalue = 2, 4, '"Spam"'
with fileinput.input('csv_data_manipulation.csv', inplace=True) as f:
for line in f:
if fileinput.filelineno() == changerow:
fields = line.rstrip().split(',')
fields[changecolumn-1] = changevalue
line = ','.join(fields) + '\n'
print(line, end='')
|
Preserve the algorithm and functionality while converting the code from Lua to Python. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| 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 VB so it works the same as the original Lua code. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| Sub ReadCSV()
Workbooks.Open Filename:="L:\a\input.csv"
Range("F1").Value = "Sum"
Range("F2:F5").Formula = "=SUM(A2:E2)"
ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV
ActiveWindow.Close
End Sub
|
Translate the given Lua code snippet into VB without altering its behavior. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| 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 Lua implementation into Go, maintaining the same output and logic. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| 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 Lua to Go without modifying what it does. | local csv={}
for line in io.lines('file.csv') do
table.insert(csv, {})
local i=1
for j=1,#line do
if line:sub(j,j) == ',' then
table.insert(csv[#csv], line:sub(i,j-1))
i=j+1
end
end
table.insert(csv[#csv], line:sub(i,j))
end
table.insert(csv[1], 'SUM')
for i=2,#csv do
local sum=0
for j=1,#csv[i] do
sum=sum + tonumber(csv[i][j])
end
if sum>0 then
table.insert(csv[i], sum)
end
end
local newFileData = ''
for i=1,#csv do
newFileData=newFileData .. table.concat(csv[i], ',') .. '\n'
end
local file=io.open('file.csv', 'w')
file:write(newFileData)
| 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)
}
}
|
Ensure the translated C code behaves exactly like the original Mathematica snippet. | 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];
| #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. | 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];
| #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#. | 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];
| 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 Mathematica, keeping it the same logically? | 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];
| 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 Mathematica implementation into C++, 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];
| #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
}
|
Port the provided Mathematica code into C++ while preserving the original functionality. | 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];
| #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;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.