Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in VB while keeping its functionality equivalent to the Haskell version. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Port the following code from Haskell to Go with equivalent syntax and logic. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Preserve the algorithm and functionality while converting the code from Haskell to Go. | import System.Environment (getArgs)
main = getArgs >>= (\[a, b, c] ->
do contents <- fmap lines $ readFile a
let b1 = read b :: Int
c1 = read c :: Int
putStr $ unlines $ concat [take (b1 - 1) contents, drop c1 $ drop b1 contents]
)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Port the provided Icon code into C while preserving the original functionality. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Produce a functionally identical C code for the snippet given in Icon. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Write the same code in C# as shown below in Icon. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Change the following Icon code into C# without altering its purpose. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Preserve the algorithm and functionality while converting the code from Icon to C++. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Transform the following Icon implementation into C++, maintaining the same output and logic. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Ensure the translated Java code behaves exactly like the original Icon snippet. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Please provide an equivalent version of this Icon code in Java. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Convert this Icon block to Python, preserving its control flow and logic. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Generate a Python translation of this Icon snippet without changing its computational steps. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Preserve the algorithm and functionality while converting the code from Icon to VB. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Produce a functionally identical VB code for the snippet given in Icon. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Convert this Icon block to Go, preserving its control flow and logic. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Write the same algorithm in Go as shown in this Icon implementation. | procedure main()
removelines("foo.bar",3,2) | stop("Failed to remove lines.")
end
procedure removelines(fn,start,skip)
f := open(fn,"r") | fail
every put(F := [],|read(f))
close(f)
if *F < start-1+skip then fail
every F[start - 1 + (1 to skip)] := &null
f := open(fn,"w") | fail
every write(\!F)
close(f)
return
end
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Keep all operations the same but rewrite the snippet in C. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Translate the given J code snippet into C without altering its behavior. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Produce a functionally identical C# code for the snippet given in J. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Write a version of this J function in C# with identical behavior. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Generate an equivalent C++ version of this J code. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Change the programming language of this snippet from J to C++ without modifying what it does. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Rewrite the snippet below in Java so it works the same as the original J code. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Please provide an equivalent version of this J code in Python. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Rewrite the snippet below in Python so it works the same as the original J code. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Port the provided J code into VB while preserving the original functionality. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Please provide an equivalent version of this J code in VB. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Transform the following J implementation into Go, maintaining the same output and logic. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Rewrite the snippet below in Go so it works the same as the original J code. | removeLines=: 4 :0
'count start'=. x
file=. boxxopen y
lines=. <;.2 fread file
(;lines {~ <<< (start-1)+i.count) fwrite file
)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Port the following code from Julia to C with equivalent syntax and logic. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Produce a language-to-language conversion: from Julia to C, same semantics. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Produce a language-to-language conversion: from Julia to C#, same semantics. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Transform the following Julia implementation into C#, maintaining the same output and logic. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Port the provided Julia code into C++ while preserving the original functionality. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Generate an equivalent C++ version of this Julia code. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Write a version of this Julia function in Java with identical behavior. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Generate an equivalent Java version of this Julia code. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Produce a language-to-language conversion: from Julia to Python, same semantics. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Preserve the algorithm and functionality while converting the code from Julia to Python. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Rewrite this program in VB while keeping its functionality equivalent to the Julia version. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Produce a language-to-language conversion: from Julia to VB, same semantics. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Preserve the algorithm and functionality while converting the code from Julia to Go. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Julia version. |
const prgm = basename(Base.source_path())
if length(ARGS) < 2
println("usage: ", prgm, " <file> [line]...")
exit(1)
end
file = ARGS[1]
const numbers = map(x -> begin
try
parse(Uint, x)
catch
println(prgm, ": ", x, ": not a number")
exit(1)
end
end, ARGS[2:end])
f = open(file)
lines = readlines(f)
close(f)
if maximum(numbers) > length(lines)
println(prgm, ": detected extraneous line number")
exit(1)
end
deleteat!(lines, sort(unique(numbers)))
f = open(file, "w")
write(f, join(lines))
close(f)
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Translate the given Lua code snippet into C without altering its behavior. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Write the same algorithm in C as shown in this Lua implementation. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Transform the following Lua implementation into C#, maintaining the same output and logic. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Write a version of this Lua function in C# with identical behavior. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Convert this Lua block to C++, preserving its control flow and logic. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Ensure the translated C++ code behaves exactly like the original Lua snippet. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Produce a functionally identical Java code for the snippet given in Lua. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Translate the given Lua code snippet into Java without altering its behavior. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Port the provided Lua code into Python while preserving the original functionality. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Transform the following Lua implementation into Python, maintaining the same output and logic. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Translate this program into VB but keep the logic exactly as in Lua. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Change the following Lua code into VB without altering its purpose. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Rewrite this program in Go while keeping its functionality equivalent to the Lua version. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Convert this Lua block to Go, preserving its control flow and logic. | function remove( filename, starting_line, num_lines )
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < starting_line or i >= starting_line + num_lines then
content[#content+1] = line
end
i = i + 1
end
if i > starting_line and i < starting_line + num_lines then
print( "Warning: Tried to remove lines after EOF." )
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Write the same code in C as shown below in Mathematica. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Write the same code in C# as shown below in Mathematica. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Preserve the algorithm and functionality while converting the code from Mathematica to C#. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Translate the given Mathematica code snippet into C++ without altering its behavior. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Generate an equivalent C++ version of this Mathematica code. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Keep all operations the same but rewrite the snippet in Java. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Ensure the translated Java code behaves exactly like the original Mathematica snippet. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Convert this Mathematica snippet to Python and keep its semantics consistent. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Translate this program into Python but keep the logic exactly as in Mathematica. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Please provide an equivalent version of this Mathematica code in VB. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Can you help me rewrite this code in VB instead of Mathematica, keeping it the same logically? | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Generate a Go translation of this Mathematica snippet without changing its computational steps. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Port the provided Mathematica code into Go while preserving the original functionality. | f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc},
p = Import[doc, "List"];
If[start + n - 1 <= Length@p,
p = Drop[p, {start, start + n - 1}];
newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}];
Export[newdoc, p, "List"];
,
Print["Too few lines in document. Operation aborted."]
]
]
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Write the same code in C as shown below in Nim. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Write a version of this Nim function in C with identical behavior. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Can you help me rewrite this code in C# instead of Nim, keeping it the same logically? | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Ensure the translated C# code behaves exactly like the original Nim snippet. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Nim version. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Write the same code in C++ as shown below in Nim. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Nim version. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Port the provided Nim code into Java while preserving the original functionality. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Preserve the algorithm and functionality while converting the code from Nim to Python. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Maintain the same structure and functionality when rewriting this code in Python. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Write the same algorithm in VB as shown in this Nim implementation. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Please provide an equivalent version of this Nim code in Go. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Nim version. | import sequtils, strutils
proc removeLines*(filename: string; start, count: Positive) =
var lines = filename.readFile().splitLines(keepEol = true)
if lines[^1].len == 0: lines.setLen(lines.len - 1)
let first = start - 1
let last = first + count - 1
if last >= lines.len:
raise newException(IOError, "trying to delete lines after end of file.")
lines.delete(first, last)
filename.writeFile(lines.join())
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Write a version of this OCaml function in C with identical behavior. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Translate this program into C but keep the logic exactly as in OCaml. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
int start, count, lines = 1;
int dest = 0, src = 0, pos = -1;
if (argc != 4)
ERROR("Usage: %s <file> <start> <count>", argv[0]);
if ((count = atoi(argv[3])) < 1)
return 0;
if ((start = atoi(argv[2])) < 1)
ERROR("Error: <start> (%d) must be positive", start);
if ((fp = fopen(argv[1], "r")) == NULL)
ERROR("No such file: %s", argv[1]);
fseek(fp, 0, SEEK_END);
sz = ftell(fp);
buf = malloc(sz + 1);
rewind(fp);
while ((buf[++pos] = fgetc(fp)) != EOF) {
if (buf[pos] == '\n') {
++lines;
if (lines == start) dest = pos + 1;
if (lines == start + count) src = pos + 1;
}
}
if (start + count > lines) {
free(buf);
fclose(fp);
ERROR("Error: invalid parameters for file with %d lines", --lines);
}
memmove(buf + dest, buf + src, pos - src);
freopen(argv[1], "w", fp);
fwrite(buf, pos - src + dest, 1, fp);
free(buf);
fclose(fp);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from OCaml to C#. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Convert the following code from OCaml to C#, ensuring the logic remains intact. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line, index) => index < start - 1 || index >= start + count - 1));
}
|
Write the same code in C++ as shown below in OCaml. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Produce a language-to-language conversion: from OCaml to C++, same semantics. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| #include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <list>
void deleteLines( const std::string & , int , int ) ;
int main( int argc, char * argv[ ] ) {
if ( argc != 4 ) {
std::cerr << "Error! Invoke with <deletelines filename startline skipnumber>!\n" ;
return 1 ;
}
std::string filename( argv[ 1 ] ) ;
int startfrom = atoi( argv[ 2 ] ) ;
int howmany = atoi( argv[ 3 ] ) ;
deleteLines ( filename , startfrom , howmany ) ;
return 0 ;
}
void deleteLines( const std::string & filename , int start , int skip ) {
std::ifstream infile( filename.c_str( ) , std::ios::in ) ;
if ( infile.is_open( ) ) {
std::string line ;
std::list<std::string> filelines ;
while ( infile ) {
getline( infile , line ) ;
filelines.push_back( line ) ;
}
infile.close( ) ;
if ( start > filelines.size( ) ) {
std::cerr << "Error! Starting to delete lines past the end of the file!\n" ;
return ;
}
if ( ( start + skip ) > filelines.size( ) ) {
std::cerr << "Error! Trying to delete lines past the end of the file!\n" ;
return ;
}
std::list<std::string>::iterator deletebegin = filelines.begin( ) , deleteend ;
for ( int i = 1 ; i < start ; i++ )
deletebegin++ ;
deleteend = deletebegin ;
for( int i = 0 ; i < skip ; i++ )
deleteend++ ;
filelines.erase( deletebegin , deleteend ) ;
std::ofstream outfile( filename.c_str( ) , std::ios::out | std::ios::trunc ) ;
if ( outfile.is_open( ) ) {
for ( std::list<std::string>::const_iterator sli = filelines.begin( ) ;
sli != filelines.end( ) ; sli++ )
outfile << *sli << "\n" ;
}
outfile.close( ) ;
}
else {
std::cerr << "Error! Could not find file " << filename << " !\n" ;
return ;
}
}
|
Translate this program into Java but keep the logic exactly as in OCaml. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Translate the given OCaml code snippet into Java without altering its behavior. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class RemoveLines
{
public static void main(String[] args)
{
String filename="foobar.txt";
int startline=1;
int numlines=2;
RemoveLines now=new RemoveLines();
now.delete(filename,startline,numlines);
}
void delete(String filename, int startline, int numlines)
{
try
{
BufferedReader br=new BufferedReader(new FileReader(filename));
StringBuffer sb=new StringBuffer("");
int linenumber=1;
String line;
while((line=br.readLine())!=null)
{
if(linenumber<startline||linenumber>=startline+numlines)
sb.append(line+"\n");
linenumber++;
}
if(startline+numlines>linenumber)
System.out.println("End of file reached.");
br.close();
FileWriter fw=new FileWriter(new File(filename));
fw.write(sb.toString());
fw.close();
}
catch (Exception e)
{
System.out.println("Something went horribly wrong: "+e.getMessage());
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Rewrite this program in Python while keeping its functionality equivalent to the OCaml version. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
|
import fileinput, sys
fname, start, count = sys.argv[1:4]
start, count = int(start), int(count)
for line in fileinput.input(fname, inplace=1, backup='.orig'):
if start <= fileinput.lineno() < start + count:
pass
else:
print line.rstrip("\n")
fileinput.close()
|
Can you help me rewrite this code in VB instead of OCaml, keeping it the same logically? | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Port the provided OCaml code into VB while preserving the original functionality. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| Option Explicit
Sub Main()
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5
RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5
End Sub
Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long)
Dim Nb As Integer, s As String, count As Long, out As String
Nb = FreeFile
Open StrFile For Input As #Nb
While Not EOF(Nb)
count = count + 1
Line Input #Nb, s
If count < StartLine Or count >= StartLine + NumberOfLines Then
out = out & s & vbCrLf
End If
Wend
Close #Nb
If StartLine >= count Then
MsgBox "The file contains only " & count & " lines"
ElseIf StartLine + NumberOfLines > count Then
MsgBox "You only can remove " & count - StartLine & " lines"
Else
Nb = FreeFile
Open StrFile For Output As #Nb
Print #Nb, out
Close #Nb
End If
End Sub
|
Convert this OCaml snippet to Go and keep its semantics consistent. | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Can you help me rewrite this code in Go instead of OCaml, keeping it the same logically? | let input_line_opt ic =
try Some (input_line ic)
with End_of_file -> None
let delete_lines filename start skip =
if start < 1 || skip < 1 then
invalid_arg "delete_lines";
let tmp_file = filename ^ ".tmp" in
let ic = open_in filename
and oc = open_out tmp_file in
let until = start + skip - 1 in
let rec aux i =
match input_line_opt ic with
| Some line ->
if i < start || i > until
then (output_string oc line; output_char oc '\n');
aux (succ i)
| None ->
close_in ic;
close_out oc;
Sys.remove filename;
Sys.rename tmp_file filename
in
aux 1
let usage () =
Printf.printf "Usage:\n%s <filename> <startline> <skipnumber>\n" Sys.argv.(0);
exit 0
let () =
if Array.length Sys.argv < 4 then usage ();
delete_lines
Sys.argv.(1) (int_of_string Sys.argv.(2)) (int_of_string Sys.argv.(3))
| package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func main() {
if err := removeLines("foobar.txt", 1, 2); err != nil {
fmt.Println(err)
}
}
func removeLines(fn string, start, n int) (err error) {
if start < 1 {
return errors.New("invalid request. line numbers start at 1.")
}
if n < 0 {
return errors.New("invalid request. negative number to remove.")
}
var f *os.File
if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
return
}
defer func() {
if cErr := f.Close(); err == nil {
err = cErr
}
}()
var b []byte
if b, err = ioutil.ReadAll(f); err != nil {
return
}
cut, ok := skip(b, start-1)
if !ok {
return fmt.Errorf("less than %d lines", start)
}
if n == 0 {
return nil
}
tail, ok := skip(cut, n)
if !ok {
return fmt.Errorf("less than %d lines after line %d", n, start)
}
t := int64(len(b) - len(cut))
if err = f.Truncate(t); err != nil {
return
}
if len(tail) > 0 {
_, err = f.WriteAt(tail, t)
}
return
}
func skip(b []byte, n int) ([]byte, bool) {
for ; n > 0; n-- {
if len(b) == 0 {
return nil, false
}
x := bytes.IndexByte(b, '\n')
if x < 0 {
x = len(b)
} else {
x++
}
b = b[x:]
}
return b, true
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.