Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert the following code from Fortran to VB, ensuring the logic remains intact. | SUBROUTINE UNBLOCK(THIS,THAT)
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT
INTEGER LOTS
PARAMETER (LOTS = 6666)
CHARACTER*(LOTS) ACARD,ALINE
INTEGER LC,LL,L
INTEGER L1,L2
INTEGER NC,NL
LOGICAL BLAH
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
NC = 0
NL = 0
BLAH = .FALSE.
Chug through the input.
10 READ(INF,11,END = 100) LC,ACARD(1:MIN(LC,LOTS))
11 FORMAT (Q,A)
NC = NC + 1
IF (LC.GT.LOTS) THEN
WRITE (MSG,12) NC,LC,LOTS
12 FORMAT ("Record ",I0," has length ",I0,"
LC = LOTS
END IF
Chew through ACARD according to mood.
LL = 0
L2 = 0
20 L1 = L2 + 1
IF (L1.LE.LC) THEN
L2 = L1
IF (BLAH) THEN
21 IF (L2 + LEN(THAT) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THAT) - 1).EQ.THAT) THEN
BLAH = .FALSE.
L2 = L2 + LEN(THAT) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 21
END IF
ELSE
22 IF (L2 + LEN(THIS) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THIS) - 1).EQ.THIS) THEN
BLAH = .TRUE.
L = L2 - L1
ALINE(LL + 1:LL + L) = ACARD(L1:L2 - 1)
LL = LL + L
L2 = L2 + LEN(THIS) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 22
END IF
L = LC - L1 + 1
ALINE(LL + 1:LL + L) = ACARD(L1:LC)
LL = LL + L
END IF
END IF
Cast forth some output.
IF (LL.GT.0) THEN
WRITE (OUT,23) ALINE(1:LL)
23 FORMAT (">",A,"<")
NL = NL + 1
END IF
GO TO 10
Completed.
100 WRITE (MSG,101) NC,NL
101 FORMAT (I0," read, ",I0," written.")
END
PROGRAM TEST
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
KBD = 5
MSG = 6
INF = 10
OUT = 11
OPEN (INF,FILE="Source.txt",STATUS="OLD",ACTION="READ")
OPEN (OUT,FILE="Src.txt",STATUS="REPLACE",ACTION="WRITE")
CALL UNBLOCK("/*","*/")
END
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Convert this Fortran block to PHP, preserving its control flow and logic. | SUBROUTINE UNBLOCK(THIS,THAT)
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT
INTEGER LOTS
PARAMETER (LOTS = 6666)
CHARACTER*(LOTS) ACARD,ALINE
INTEGER LC,LL,L
INTEGER L1,L2
INTEGER NC,NL
LOGICAL BLAH
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
NC = 0
NL = 0
BLAH = .FALSE.
Chug through the input.
10 READ(INF,11,END = 100) LC,ACARD(1:MIN(LC,LOTS))
11 FORMAT (Q,A)
NC = NC + 1
IF (LC.GT.LOTS) THEN
WRITE (MSG,12) NC,LC,LOTS
12 FORMAT ("Record ",I0," has length ",I0,"
LC = LOTS
END IF
Chew through ACARD according to mood.
LL = 0
L2 = 0
20 L1 = L2 + 1
IF (L1.LE.LC) THEN
L2 = L1
IF (BLAH) THEN
21 IF (L2 + LEN(THAT) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THAT) - 1).EQ.THAT) THEN
BLAH = .FALSE.
L2 = L2 + LEN(THAT) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 21
END IF
ELSE
22 IF (L2 + LEN(THIS) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THIS) - 1).EQ.THIS) THEN
BLAH = .TRUE.
L = L2 - L1
ALINE(LL + 1:LL + L) = ACARD(L1:L2 - 1)
LL = LL + L
L2 = L2 + LEN(THIS) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 22
END IF
L = LC - L1 + 1
ALINE(LL + 1:LL + L) = ACARD(L1:LC)
LL = LL + L
END IF
END IF
Cast forth some output.
IF (LL.GT.0) THEN
WRITE (OUT,23) ALINE(1:LL)
23 FORMAT (">",A,"<")
NL = NL + 1
END IF
GO TO 10
Completed.
100 WRITE (MSG,101) NC,NL
101 FORMAT (I0," read, ",I0," written.")
END
PROGRAM TEST
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
KBD = 5
MSG = 6
INF = 10
OUT = 11
OPEN (INF,FILE="Source.txt",STATUS="OLD",ACTION="READ")
OPEN (OUT,FILE="Src.txt",STATUS="REPLACE",ACTION="WRITE")
CALL UNBLOCK("/*","*/")
END
| function strip_block_comments( $test_string ) {
$pattern = "/^.*?(\K\/\*.*?\*\/)|^.*?(\K\/\*.*?^.*\*\/)$/mXus";
return preg_replace( $pattern, '', $test_string );
}
echo "Result: '" . strip_block_comments( "
function subroutine() {
a = b + c ;
}
function something() {
}
" ) . "'";
|
Produce a language-to-language conversion: from Groovy to C, same semantics. | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Write the same code in C# as shown below in Groovy. | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Port the provided Groovy code into C++ while preserving the original functionality. | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Can you help me rewrite this code in Java instead of Groovy, keeping it the same logically? | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write a version of this Groovy function in Python with identical behavior. | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Port the provided Groovy code into VB while preserving the original functionality. | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Keep all operations the same but rewrite the snippet in Go. | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Can you help me rewrite this code in C instead of Haskell, keeping it the same logically? | test = "This {- is not the beginning of a block comment"
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Convert this Haskell snippet to C# and keep its semantics consistent. | test = "This {- is not the beginning of a block comment"
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Haskell code. | test = "This {- is not the beginning of a block comment"
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Produce a language-to-language conversion: from Haskell to Java, same semantics. | test = "This {- is not the beginning of a block comment"
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write the same algorithm in Python as shown in this Haskell implementation. | test = "This {- is not the beginning of a block comment"
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Rewrite this program in VB while keeping its functionality equivalent to the Haskell version. | test = "This {- is not the beginning of a block comment"
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Translate this program into Go but keep the logic exactly as in Haskell. | test = "This {- is not the beginning of a block comment"
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Write the same algorithm in C as shown in this Icon implementation. | procedure main()
every (unstripped := "") ||:= !&input || "\n"
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3)
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0)
move(*s3)
}
return result || tab(0)
}
end
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Produce a language-to-language conversion: from Icon to C#, same semantics. | procedure main()
every (unstripped := "") ||:= !&input || "\n"
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3)
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0)
move(*s3)
}
return result || tab(0)
}
end
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Icon code. | procedure main()
every (unstripped := "") ||:= !&input || "\n"
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3)
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0)
move(*s3)
}
return result || tab(0)
}
end
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Can you help me rewrite this code in Java instead of Icon, keeping it the same logically? | procedure main()
every (unstripped := "") ||:= !&input || "\n"
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3)
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0)
move(*s3)
}
return result || tab(0)
}
end
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | procedure main()
every (unstripped := "") ||:= !&input || "\n"
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3)
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0)
move(*s3)
}
return result || tab(0)
}
end
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Can you help me rewrite this code in VB instead of Icon, keeping it the same logically? | procedure main()
every (unstripped := "") ||:= !&input || "\n"
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3)
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0)
move(*s3)
}
return result || tab(0)
}
end
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Produce a language-to-language conversion: from Icon to Go, same semantics. | procedure main()
every (unstripped := "") ||:= !&input || "\n"
write(stripBlockComment(unstripped,"/*","*/"))
end
procedure stripBlockComment(s1,s2,s3)
result := ""
s1 ? {
while result ||:= tab(find(s2)) do {
move(*s2)
tab(find(s3)|0)
move(*s3)
}
return result || tab(0)
}
end
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Please provide an equivalent version of this J code in C. | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
)
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Change the following J code into C# without altering its purpose. | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
)
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Keep all operations the same but rewrite the snippet in C++. | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
)
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Convert this J block to Java, preserving its control flow and logic. | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
)
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write the same algorithm in Python as shown in this J implementation. | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
)
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Convert this J snippet to VB and keep its semantics consistent. | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
)
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Translate the given J code snippet into Go without altering its behavior. | strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;:
1 0 0
0 2 0
2 3 2
0 2 2
)
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Write the same algorithm in C as shown in this Julia implementation. | function _stripcomments(txt::AbstractString, dlm::Tuple{String,String})
"Strips first nest of block comments"
dlml, dlmr = dlm
indx = searchindex(txt, dlml)
if indx > 0
out = IOBuffer()
write(out, txt[1:indx-1])
txt = txt[indx+length(dlml):end]
txt = _stripcomments(txt, dlm)
indx = searchindex(txt, dlmr)
@assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt")
write(out, txt[indx+length(dlmr):end])
else
out = txt
end
return String(out)
end
function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/"))
"Strips nests of block comments"
dlml, dlmr = dlm
while contains(txt, dlml)
txt = _stripcomments(txt, dlm)
end
return txt
end
function main()
println("\nNON-NESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
println("\nNESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
end
main()
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Generate an equivalent C# version of this Julia code. | function _stripcomments(txt::AbstractString, dlm::Tuple{String,String})
"Strips first nest of block comments"
dlml, dlmr = dlm
indx = searchindex(txt, dlml)
if indx > 0
out = IOBuffer()
write(out, txt[1:indx-1])
txt = txt[indx+length(dlml):end]
txt = _stripcomments(txt, dlm)
indx = searchindex(txt, dlmr)
@assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt")
write(out, txt[indx+length(dlmr):end])
else
out = txt
end
return String(out)
end
function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/"))
"Strips nests of block comments"
dlml, dlmr = dlm
while contains(txt, dlml)
txt = _stripcomments(txt, dlm)
end
return txt
end
function main()
println("\nNON-NESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
println("\nNESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
end
main()
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Write the same code in C++ as shown below in Julia. | function _stripcomments(txt::AbstractString, dlm::Tuple{String,String})
"Strips first nest of block comments"
dlml, dlmr = dlm
indx = searchindex(txt, dlml)
if indx > 0
out = IOBuffer()
write(out, txt[1:indx-1])
txt = txt[indx+length(dlml):end]
txt = _stripcomments(txt, dlm)
indx = searchindex(txt, dlmr)
@assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt")
write(out, txt[indx+length(dlmr):end])
else
out = txt
end
return String(out)
end
function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/"))
"Strips nests of block comments"
dlml, dlmr = dlm
while contains(txt, dlml)
txt = _stripcomments(txt, dlm)
end
return txt
end
function main()
println("\nNON-NESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
println("\nNESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
end
main()
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Julia version. | function _stripcomments(txt::AbstractString, dlm::Tuple{String,String})
"Strips first nest of block comments"
dlml, dlmr = dlm
indx = searchindex(txt, dlml)
if indx > 0
out = IOBuffer()
write(out, txt[1:indx-1])
txt = txt[indx+length(dlml):end]
txt = _stripcomments(txt, dlm)
indx = searchindex(txt, dlmr)
@assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt")
write(out, txt[indx+length(dlmr):end])
else
out = txt
end
return String(out)
end
function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/"))
"Strips nests of block comments"
dlml, dlmr = dlm
while contains(txt, dlml)
txt = _stripcomments(txt, dlm)
end
return txt
end
function main()
println("\nNON-NESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
println("\nNESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
end
main()
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Change the following Julia code into Python without altering its purpose. | function _stripcomments(txt::AbstractString, dlm::Tuple{String,String})
"Strips first nest of block comments"
dlml, dlmr = dlm
indx = searchindex(txt, dlml)
if indx > 0
out = IOBuffer()
write(out, txt[1:indx-1])
txt = txt[indx+length(dlml):end]
txt = _stripcomments(txt, dlm)
indx = searchindex(txt, dlmr)
@assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt")
write(out, txt[indx+length(dlmr):end])
else
out = txt
end
return String(out)
end
function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/"))
"Strips nests of block comments"
dlml, dlmr = dlm
while contains(txt, dlml)
txt = _stripcomments(txt, dlm)
end
return txt
end
function main()
println("\nNON-NESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
println("\nNESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
end
main()
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Convert the following code from Julia to VB, ensuring the logic remains intact. | function _stripcomments(txt::AbstractString, dlm::Tuple{String,String})
"Strips first nest of block comments"
dlml, dlmr = dlm
indx = searchindex(txt, dlml)
if indx > 0
out = IOBuffer()
write(out, txt[1:indx-1])
txt = txt[indx+length(dlml):end]
txt = _stripcomments(txt, dlm)
indx = searchindex(txt, dlmr)
@assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt")
write(out, txt[indx+length(dlmr):end])
else
out = txt
end
return String(out)
end
function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/"))
"Strips nests of block comments"
dlml, dlmr = dlm
while contains(txt, dlml)
txt = _stripcomments(txt, dlm)
end
return txt
end
function main()
println("\nNON-NESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
println("\nNESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
end
main()
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Convert this Julia block to Go, preserving its control flow and logic. | function _stripcomments(txt::AbstractString, dlm::Tuple{String,String})
"Strips first nest of block comments"
dlml, dlmr = dlm
indx = searchindex(txt, dlml)
if indx > 0
out = IOBuffer()
write(out, txt[1:indx-1])
txt = txt[indx+length(dlml):end]
txt = _stripcomments(txt, dlm)
indx = searchindex(txt, dlmr)
@assert(indx > 0, "cannot find a closer delimiter \"$dlmr\" in $txt")
write(out, txt[indx+length(dlmr):end])
else
out = txt
end
return String(out)
end
function stripcomments(txt::AbstractString, dlm::Tuple{String,String}=("/*", "*/"))
"Strips nests of block comments"
dlml, dlmr = dlm
while contains(txt, dlml)
txt = _stripcomments(txt, dlm)
end
return txt
end
function main()
println("\nNON-NESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
println("\nNESTED BLOCK COMMENT EXAMPLE:")
smpl = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}
"""
println(stripcomments(smpl))
end
main()
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Translate this program into C but keep the logic exactly as in Lua. | filename = "Text1.txt"
fp = io.open( filename, "r" )
str = fp:read( "*all" )
fp:close()
stripped = string.gsub( str, "/%*.-%*/", "" )
print( stripped )
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Lua version. | filename = "Text1.txt"
fp = io.open( filename, "r" )
str = fp:read( "*all" )
fp:close()
stripped = string.gsub( str, "/%*.-%*/", "" )
print( stripped )
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Produce a language-to-language conversion: from Lua to C++, same semantics. | filename = "Text1.txt"
fp = io.open( filename, "r" )
str = fp:read( "*all" )
fp:close()
stripped = string.gsub( str, "/%*.-%*/", "" )
print( stripped )
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Port the following code from Lua to Java with equivalent syntax and logic. | filename = "Text1.txt"
fp = io.open( filename, "r" )
str = fp:read( "*all" )
fp:close()
stripped = string.gsub( str, "/%*.-%*/", "" )
print( stripped )
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write the same algorithm in Python as shown in this Lua implementation. | filename = "Text1.txt"
fp = io.open( filename, "r" )
str = fp:read( "*all" )
fp:close()
stripped = string.gsub( str, "/%*.-%*/", "" )
print( stripped )
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Ensure the translated VB code behaves exactly like the original Lua snippet. | filename = "Text1.txt"
fp = io.open( filename, "r" )
str = fp:read( "*all" )
fp:close()
stripped = string.gsub( str, "/%*.-%*/", "" )
print( stripped )
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Ensure the translated Go code behaves exactly like the original Lua snippet. | filename = "Text1.txt"
fp = io.open( filename, "r" )
str = fp:read( "*all" )
fp:close()
stripped = string.gsub( str, "/%*.-%*/", "" )
print( stripped )
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Convert the following code from Mathematica to C, ensuring the logic remains intact. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Mathematica snippet. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Please provide an equivalent version of this Mathematica code in C++. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Transform the following Mathematica implementation into Java, maintaining the same output and logic. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Produce a functionally identical Python code for the snippet given in Mathematica. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Produce a functionally identical VB code for the snippet given in Mathematica. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Write the same algorithm in Go as shown in this Mathematica implementation. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Port the provided MATLAB code into C while preserving the original functionality. | function str = stripblockcomment(str,startmarker,endmarker)
while(1)
ix1 = strfind(str, startmarker);
if isempty(ix1) return; end;
ix2 = strfind(str(ix1+length(startmarker):end),endmarker);
if isempty(ix2)
str = str(1:ix1(1)-1);
return;
else
str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)];
end;
end;
end;
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Please provide an equivalent version of this MATLAB code in C#. | function str = stripblockcomment(str,startmarker,endmarker)
while(1)
ix1 = strfind(str, startmarker);
if isempty(ix1) return; end;
ix2 = strfind(str(ix1+length(startmarker):end),endmarker);
if isempty(ix2)
str = str(1:ix1(1)-1);
return;
else
str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)];
end;
end;
end;
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the MATLAB version. | function str = stripblockcomment(str,startmarker,endmarker)
while(1)
ix1 = strfind(str, startmarker);
if isempty(ix1) return; end;
ix2 = strfind(str(ix1+length(startmarker):end),endmarker);
if isempty(ix2)
str = str(1:ix1(1)-1);
return;
else
str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)];
end;
end;
end;
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Translate this program into Java but keep the logic exactly as in MATLAB. | function str = stripblockcomment(str,startmarker,endmarker)
while(1)
ix1 = strfind(str, startmarker);
if isempty(ix1) return; end;
ix2 = strfind(str(ix1+length(startmarker):end),endmarker);
if isempty(ix2)
str = str(1:ix1(1)-1);
return;
else
str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)];
end;
end;
end;
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Convert the following code from MATLAB to Python, ensuring the logic remains intact. | function str = stripblockcomment(str,startmarker,endmarker)
while(1)
ix1 = strfind(str, startmarker);
if isempty(ix1) return; end;
ix2 = strfind(str(ix1+length(startmarker):end),endmarker);
if isempty(ix2)
str = str(1:ix1(1)-1);
return;
else
str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)];
end;
end;
end;
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Port the following code from MATLAB to VB with equivalent syntax and logic. | function str = stripblockcomment(str,startmarker,endmarker)
while(1)
ix1 = strfind(str, startmarker);
if isempty(ix1) return; end;
ix2 = strfind(str(ix1+length(startmarker):end),endmarker);
if isempty(ix2)
str = str(1:ix1(1)-1);
return;
else
str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)];
end;
end;
end;
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Change the programming language of this snippet from MATLAB to Go without modifying what it does. | function str = stripblockcomment(str,startmarker,endmarker)
while(1)
ix1 = strfind(str, startmarker);
if isempty(ix1) return; end;
ix2 = strfind(str(ix1+length(startmarker):end),endmarker);
if isempty(ix2)
str = str(1:ix1(1)-1);
return;
else
str = [str(1:ix1(1)-1),str(ix1(1)+ix2(1)+length(endmarker)+1:end)];
end;
end;
end;
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Rewrite this program in C while keeping its functionality equivalent to the Nim version. | import strutils
proc commentStripper(txt: string; delim: tuple[l, r: string] = ("/*", "*/")): string =
let i = txt.find(delim.l)
if i < 0: return txt
result = if i > 0: txt[0 ..< i] else: ""
let tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)
let j = tmp.find(delim.r)
assert j >= 0
result &= tmp[j+delim.r.len .. tmp.high]
echo "NON-NESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper("""/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}""")
echo "\nNESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper(""" /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}""")
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Write a version of this Nim function in C# with identical behavior. | import strutils
proc commentStripper(txt: string; delim: tuple[l, r: string] = ("/*", "*/")): string =
let i = txt.find(delim.l)
if i < 0: return txt
result = if i > 0: txt[0 ..< i] else: ""
let tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)
let j = tmp.find(delim.r)
assert j >= 0
result &= tmp[j+delim.r.len .. tmp.high]
echo "NON-NESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper("""/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}""")
echo "\nNESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper(""" /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}""")
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Change the programming language of this snippet from Nim to C++ without modifying what it does. | import strutils
proc commentStripper(txt: string; delim: tuple[l, r: string] = ("/*", "*/")): string =
let i = txt.find(delim.l)
if i < 0: return txt
result = if i > 0: txt[0 ..< i] else: ""
let tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)
let j = tmp.find(delim.r)
assert j >= 0
result &= tmp[j+delim.r.len .. tmp.high]
echo "NON-NESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper("""/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}""")
echo "\nNESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper(""" /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}""")
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Rewrite the snippet below in Java so it works the same as the original Nim code. | import strutils
proc commentStripper(txt: string; delim: tuple[l, r: string] = ("/*", "*/")): string =
let i = txt.find(delim.l)
if i < 0: return txt
result = if i > 0: txt[0 ..< i] else: ""
let tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)
let j = tmp.find(delim.r)
assert j >= 0
result &= tmp[j+delim.r.len .. tmp.high]
echo "NON-NESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper("""/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}""")
echo "\nNESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper(""" /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}""")
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write the same code in Python as shown below in Nim. | import strutils
proc commentStripper(txt: string; delim: tuple[l, r: string] = ("/*", "*/")): string =
let i = txt.find(delim.l)
if i < 0: return txt
result = if i > 0: txt[0 ..< i] else: ""
let tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)
let j = tmp.find(delim.r)
assert j >= 0
result &= tmp[j+delim.r.len .. tmp.high]
echo "NON-NESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper("""/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}""")
echo "\nNESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper(""" /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}""")
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Write the same algorithm in VB as shown in this Nim implementation. | import strutils
proc commentStripper(txt: string; delim: tuple[l, r: string] = ("/*", "*/")): string =
let i = txt.find(delim.l)
if i < 0: return txt
result = if i > 0: txt[0 ..< i] else: ""
let tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)
let j = tmp.find(delim.r)
assert j >= 0
result &= tmp[j+delim.r.len .. tmp.high]
echo "NON-NESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper("""/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}""")
echo "\nNESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper(""" /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}""")
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Transform the following Nim implementation into Go, maintaining the same output and logic. | import strutils
proc commentStripper(txt: string; delim: tuple[l, r: string] = ("/*", "*/")): string =
let i = txt.find(delim.l)
if i < 0: return txt
result = if i > 0: txt[0 ..< i] else: ""
let tmp = commentStripper(txt[i+delim.l.len .. txt.high], delim)
let j = tmp.find(delim.r)
assert j >= 0
result &= tmp[j+delim.r.len .. tmp.high]
echo "NON-NESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper("""/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}""")
echo "\nNESTED BLOCK COMMENT EXAMPLE:"
echo commentStripper(""" /**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*//*
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
*/
/**
* Another comment.
*/
function something() {
}""")
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Can you help me rewrite this code in C instead of Perl, keeping it the same logically? |
use strict ;
use warnings ;
open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ;
my $code = "" ;
{
local $/ ;
$code = <FH> ;
}
close FH ;
$code =~ s,/\*.*?\*/,,sg ;
print $code . "\n" ;
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Change the following Perl code into C# without altering its purpose. |
use strict ;
use warnings ;
open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ;
my $code = "" ;
{
local $/ ;
$code = <FH> ;
}
close FH ;
$code =~ s,/\*.*?\*/,,sg ;
print $code . "\n" ;
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Preserve the algorithm and functionality while converting the code from Perl to C++. |
use strict ;
use warnings ;
open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ;
my $code = "" ;
{
local $/ ;
$code = <FH> ;
}
close FH ;
$code =~ s,/\*.*?\*/,,sg ;
print $code . "\n" ;
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Port the following code from Perl to Java with equivalent syntax and logic. |
use strict ;
use warnings ;
open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ;
my $code = "" ;
{
local $/ ;
$code = <FH> ;
}
close FH ;
$code =~ s,/\*.*?\*/,,sg ;
print $code . "\n" ;
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Ensure the translated Python code behaves exactly like the original Perl snippet. |
use strict ;
use warnings ;
open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ;
my $code = "" ;
{
local $/ ;
$code = <FH> ;
}
close FH ;
$code =~ s,/\*.*?\*/,,sg ;
print $code . "\n" ;
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Preserve the algorithm and functionality while converting the code from Perl to VB. |
use strict ;
use warnings ;
open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ;
my $code = "" ;
{
local $/ ;
$code = <FH> ;
}
close FH ;
$code =~ s,/\*.*?\*/,,sg ;
print $code . "\n" ;
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Port the provided Perl code into Go while preserving the original functionality. |
use strict ;
use warnings ;
open( FH , "<" , "samplecode.txt" ) or die "Can't open file!$!\n" ;
my $code = "" ;
{
local $/ ;
$code = <FH> ;
}
close FH ;
$code =~ s,/\*.*?\*/,,sg ;
print $code . "\n" ;
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Write a version of this Racket function in C with identical behavior. | #lang at-exp racket
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1 displayln strip-comments)
@~a{/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
})
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Generate an equivalent C# version of this Racket code. | #lang at-exp racket
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1 displayln strip-comments)
@~a{/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
})
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Convert the following code from Racket to C++, ensuring the logic remains intact. | #lang at-exp racket
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1 displayln strip-comments)
@~a{/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
})
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Can you help me rewrite this code in Java instead of Racket, keeping it the same logically? | #lang at-exp racket
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1 displayln strip-comments)
@~a{/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
})
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write the same code in Python as shown below in Racket. | #lang at-exp racket
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1 displayln strip-comments)
@~a{/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
})
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Rewrite the snippet below in VB so it works the same as the original Racket code. | #lang at-exp racket
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1 displayln strip-comments)
@~a{/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
})
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Produce a language-to-language conversion: from Racket to Go, same semantics. | #lang at-exp racket
(define comment-start-str "/*")
(define comment-end-str "*/")
(define (strip-comments text [rx1 comment-start-str] [rx2 comment-end-str])
(regexp-replace* (~a (regexp-quote rx1) ".*?" (regexp-quote rx2))
text ""))
((compose1 displayln strip-comments)
@~a{/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
})
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Preserve the algorithm and functionality while converting the code from REXX to C. |
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667
* courtesy GS discussion!
* 12.07.2013 Walter Pachl
**********************************************************************/
fid='in.txt'
oic='oc.txt'; 'erase' oic
oip='op.txt'; 'erase' oip
oim='om.txt'; 'erase' oim
cmt=0
str=''
Do ri=1 By 1 While lines(fid)>0
l=linein(fid)
oc=''
op=''
i=1
Do While i<=length(l)
If cmt=0 Then Do
If str<>'' Then Do
If substr(l,i,1)=str Then Do
If substr(l,i+1,1)=str Then Do
Call app 'P',substr(l,i,2)
i=i+2
Iterate
End
Else Do
Call app 'P',substr(l,i,1)
str=' '
i=i+1
Iterate
End
End
End
End
Select
When str='' &,
substr(l,i,2)='
cmt=cmt+1
Call app 'C','
i=i+2
End
When cmt=0 Then Do
If str=' ' Then Do
If pos(substr(l,i,1),'''"')>0 Then
str=substr(l,i,1)
End
Call app 'P',substr(l,i,1)
i=i+1
End
When substr(l,i,2)='*/' Then Do
cmt=cmt-1
Call app 'C','*/'
i=i+2
End
Otherwise Do
Call app 'C',substr(l,i,1)
i=i+1
End
End
End
Call oc
Call op
End
Call lineout oic
Call lineout oip
Do ri=1 To ri-1
op=linein(oip)
oc=linein(oic)
Do i=1 To length(oc)
If substr(oc,i,1)<>'' Then
op=overlay(substr(oc,i,1),op,i,1)
End
Call lineout oim,op
End
Call lineout oic
Call lineout oip
Call lineout oim
Exit
app: Parse Arg which,string
If which='C' Then Do
oc=oc||string
op=op||copies(' ',length(string))
End
Else Do
op=op||string
oc=oc||copies(' ',length(string))
End
Return
oc: Return lineout(oic,oc)
op: Return lineout(oip,op)
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. |
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667
* courtesy GS discussion!
* 12.07.2013 Walter Pachl
**********************************************************************/
fid='in.txt'
oic='oc.txt'; 'erase' oic
oip='op.txt'; 'erase' oip
oim='om.txt'; 'erase' oim
cmt=0
str=''
Do ri=1 By 1 While lines(fid)>0
l=linein(fid)
oc=''
op=''
i=1
Do While i<=length(l)
If cmt=0 Then Do
If str<>'' Then Do
If substr(l,i,1)=str Then Do
If substr(l,i+1,1)=str Then Do
Call app 'P',substr(l,i,2)
i=i+2
Iterate
End
Else Do
Call app 'P',substr(l,i,1)
str=' '
i=i+1
Iterate
End
End
End
End
Select
When str='' &,
substr(l,i,2)='
cmt=cmt+1
Call app 'C','
i=i+2
End
When cmt=0 Then Do
If str=' ' Then Do
If pos(substr(l,i,1),'''"')>0 Then
str=substr(l,i,1)
End
Call app 'P',substr(l,i,1)
i=i+1
End
When substr(l,i,2)='*/' Then Do
cmt=cmt-1
Call app 'C','*/'
i=i+2
End
Otherwise Do
Call app 'C',substr(l,i,1)
i=i+1
End
End
End
Call oc
Call op
End
Call lineout oic
Call lineout oip
Do ri=1 To ri-1
op=linein(oip)
oc=linein(oic)
Do i=1 To length(oc)
If substr(oc,i,1)<>'' Then
op=overlay(substr(oc,i,1),op,i,1)
End
Call lineout oim,op
End
Call lineout oic
Call lineout oip
Call lineout oim
Exit
app: Parse Arg which,string
If which='C' Then Do
oc=oc||string
op=op||copies(' ',length(string))
End
Else Do
op=op||string
oc=oc||copies(' ',length(string))
End
Return
oc: Return lineout(oic,oc)
op: Return lineout(oip,op)
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Port the provided REXX code into C++ while preserving the original functionality. |
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667
* courtesy GS discussion!
* 12.07.2013 Walter Pachl
**********************************************************************/
fid='in.txt'
oic='oc.txt'; 'erase' oic
oip='op.txt'; 'erase' oip
oim='om.txt'; 'erase' oim
cmt=0
str=''
Do ri=1 By 1 While lines(fid)>0
l=linein(fid)
oc=''
op=''
i=1
Do While i<=length(l)
If cmt=0 Then Do
If str<>'' Then Do
If substr(l,i,1)=str Then Do
If substr(l,i+1,1)=str Then Do
Call app 'P',substr(l,i,2)
i=i+2
Iterate
End
Else Do
Call app 'P',substr(l,i,1)
str=' '
i=i+1
Iterate
End
End
End
End
Select
When str='' &,
substr(l,i,2)='
cmt=cmt+1
Call app 'C','
i=i+2
End
When cmt=0 Then Do
If str=' ' Then Do
If pos(substr(l,i,1),'''"')>0 Then
str=substr(l,i,1)
End
Call app 'P',substr(l,i,1)
i=i+1
End
When substr(l,i,2)='*/' Then Do
cmt=cmt-1
Call app 'C','*/'
i=i+2
End
Otherwise Do
Call app 'C',substr(l,i,1)
i=i+1
End
End
End
Call oc
Call op
End
Call lineout oic
Call lineout oip
Do ri=1 To ri-1
op=linein(oip)
oc=linein(oic)
Do i=1 To length(oc)
If substr(oc,i,1)<>'' Then
op=overlay(substr(oc,i,1),op,i,1)
End
Call lineout oim,op
End
Call lineout oic
Call lineout oip
Call lineout oim
Exit
app: Parse Arg which,string
If which='C' Then Do
oc=oc||string
op=op||copies(' ',length(string))
End
Else Do
op=op||string
oc=oc||copies(' ',length(string))
End
Return
oc: Return lineout(oic,oc)
op: Return lineout(oip,op)
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Ensure the translated Java code behaves exactly like the original REXX snippet. |
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667
* courtesy GS discussion!
* 12.07.2013 Walter Pachl
**********************************************************************/
fid='in.txt'
oic='oc.txt'; 'erase' oic
oip='op.txt'; 'erase' oip
oim='om.txt'; 'erase' oim
cmt=0
str=''
Do ri=1 By 1 While lines(fid)>0
l=linein(fid)
oc=''
op=''
i=1
Do While i<=length(l)
If cmt=0 Then Do
If str<>'' Then Do
If substr(l,i,1)=str Then Do
If substr(l,i+1,1)=str Then Do
Call app 'P',substr(l,i,2)
i=i+2
Iterate
End
Else Do
Call app 'P',substr(l,i,1)
str=' '
i=i+1
Iterate
End
End
End
End
Select
When str='' &,
substr(l,i,2)='
cmt=cmt+1
Call app 'C','
i=i+2
End
When cmt=0 Then Do
If str=' ' Then Do
If pos(substr(l,i,1),'''"')>0 Then
str=substr(l,i,1)
End
Call app 'P',substr(l,i,1)
i=i+1
End
When substr(l,i,2)='*/' Then Do
cmt=cmt-1
Call app 'C','*/'
i=i+2
End
Otherwise Do
Call app 'C',substr(l,i,1)
i=i+1
End
End
End
Call oc
Call op
End
Call lineout oic
Call lineout oip
Do ri=1 To ri-1
op=linein(oip)
oc=linein(oic)
Do i=1 To length(oc)
If substr(oc,i,1)<>'' Then
op=overlay(substr(oc,i,1),op,i,1)
End
Call lineout oim,op
End
Call lineout oic
Call lineout oip
Call lineout oim
Exit
app: Parse Arg which,string
If which='C' Then Do
oc=oc||string
op=op||copies(' ',length(string))
End
Else Do
op=op||string
oc=oc||copies(' ',length(string))
End
Return
oc: Return lineout(oic,oc)
op: Return lineout(oip,op)
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write a version of this REXX function in Python with identical behavior. |
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667
* courtesy GS discussion!
* 12.07.2013 Walter Pachl
**********************************************************************/
fid='in.txt'
oic='oc.txt'; 'erase' oic
oip='op.txt'; 'erase' oip
oim='om.txt'; 'erase' oim
cmt=0
str=''
Do ri=1 By 1 While lines(fid)>0
l=linein(fid)
oc=''
op=''
i=1
Do While i<=length(l)
If cmt=0 Then Do
If str<>'' Then Do
If substr(l,i,1)=str Then Do
If substr(l,i+1,1)=str Then Do
Call app 'P',substr(l,i,2)
i=i+2
Iterate
End
Else Do
Call app 'P',substr(l,i,1)
str=' '
i=i+1
Iterate
End
End
End
End
Select
When str='' &,
substr(l,i,2)='
cmt=cmt+1
Call app 'C','
i=i+2
End
When cmt=0 Then Do
If str=' ' Then Do
If pos(substr(l,i,1),'''"')>0 Then
str=substr(l,i,1)
End
Call app 'P',substr(l,i,1)
i=i+1
End
When substr(l,i,2)='*/' Then Do
cmt=cmt-1
Call app 'C','*/'
i=i+2
End
Otherwise Do
Call app 'C',substr(l,i,1)
i=i+1
End
End
End
Call oc
Call op
End
Call lineout oic
Call lineout oip
Do ri=1 To ri-1
op=linein(oip)
oc=linein(oic)
Do i=1 To length(oc)
If substr(oc,i,1)<>'' Then
op=overlay(substr(oc,i,1),op,i,1)
End
Call lineout oim,op
End
Call lineout oic
Call lineout oip
Call lineout oim
Exit
app: Parse Arg which,string
If which='C' Then Do
oc=oc||string
op=op||copies(' ',length(string))
End
Else Do
op=op||string
oc=oc||copies(' ',length(string))
End
Return
oc: Return lineout(oic,oc)
op: Return lineout(oip,op)
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Translate the given REXX code snippet into VB without altering its behavior. |
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667
* courtesy GS discussion!
* 12.07.2013 Walter Pachl
**********************************************************************/
fid='in.txt'
oic='oc.txt'; 'erase' oic
oip='op.txt'; 'erase' oip
oim='om.txt'; 'erase' oim
cmt=0
str=''
Do ri=1 By 1 While lines(fid)>0
l=linein(fid)
oc=''
op=''
i=1
Do While i<=length(l)
If cmt=0 Then Do
If str<>'' Then Do
If substr(l,i,1)=str Then Do
If substr(l,i+1,1)=str Then Do
Call app 'P',substr(l,i,2)
i=i+2
Iterate
End
Else Do
Call app 'P',substr(l,i,1)
str=' '
i=i+1
Iterate
End
End
End
End
Select
When str='' &,
substr(l,i,2)='
cmt=cmt+1
Call app 'C','
i=i+2
End
When cmt=0 Then Do
If str=' ' Then Do
If pos(substr(l,i,1),'''"')>0 Then
str=substr(l,i,1)
End
Call app 'P',substr(l,i,1)
i=i+1
End
When substr(l,i,2)='*/' Then Do
cmt=cmt-1
Call app 'C','*/'
i=i+2
End
Otherwise Do
Call app 'C',substr(l,i,1)
i=i+1
End
End
End
Call oc
Call op
End
Call lineout oic
Call lineout oip
Do ri=1 To ri-1
op=linein(oip)
oc=linein(oic)
Do i=1 To length(oc)
If substr(oc,i,1)<>'' Then
op=overlay(substr(oc,i,1),op,i,1)
End
Call lineout oim,op
End
Call lineout oic
Call lineout oip
Call lineout oim
Exit
app: Parse Arg which,string
If which='C' Then Do
oc=oc||string
op=op||copies(' ',length(string))
End
Else Do
op=op||string
oc=oc||copies(' ',length(string))
End
Return
oc: Return lineout(oic,oc)
op: Return lineout(oip,op)
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Write the same algorithm in Go as shown in this REXX implementation. |
* Split comments
* This program ignores comment delimiters within literal strings
* such as, e.g., in b = "--' O'Connor's widow --";
* it does not (yet) take care of -- comments (ignore rest of line)
* also it does not take care of say 667
* courtesy GS discussion!
* 12.07.2013 Walter Pachl
**********************************************************************/
fid='in.txt'
oic='oc.txt'; 'erase' oic
oip='op.txt'; 'erase' oip
oim='om.txt'; 'erase' oim
cmt=0
str=''
Do ri=1 By 1 While lines(fid)>0
l=linein(fid)
oc=''
op=''
i=1
Do While i<=length(l)
If cmt=0 Then Do
If str<>'' Then Do
If substr(l,i,1)=str Then Do
If substr(l,i+1,1)=str Then Do
Call app 'P',substr(l,i,2)
i=i+2
Iterate
End
Else Do
Call app 'P',substr(l,i,1)
str=' '
i=i+1
Iterate
End
End
End
End
Select
When str='' &,
substr(l,i,2)='
cmt=cmt+1
Call app 'C','
i=i+2
End
When cmt=0 Then Do
If str=' ' Then Do
If pos(substr(l,i,1),'''"')>0 Then
str=substr(l,i,1)
End
Call app 'P',substr(l,i,1)
i=i+1
End
When substr(l,i,2)='*/' Then Do
cmt=cmt-1
Call app 'C','*/'
i=i+2
End
Otherwise Do
Call app 'C',substr(l,i,1)
i=i+1
End
End
End
Call oc
Call op
End
Call lineout oic
Call lineout oip
Do ri=1 To ri-1
op=linein(oip)
oc=linein(oic)
Do i=1 To length(oc)
If substr(oc,i,1)<>'' Then
op=overlay(substr(oc,i,1),op,i,1)
End
Call lineout oim,op
End
Call lineout oic
Call lineout oip
Call lineout oim
Exit
app: Parse Arg which,string
If which='C' Then Do
oc=oc||string
op=op||copies(' ',length(string))
End
Else Do
op=op||string
oc=oc||copies(' ',length(string))
End
Return
oc: Return lineout(oic,oc)
op: Return lineout(oip,op)
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Maintain the same structure and functionality when rewriting this code in C. | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/')
remove_comments!(str.dup, comment_start, comment_end)
end
example = <<END_OF_STRING
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
END_OF_STRING
puts remove_comments example
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Transform the following Ruby implementation into C#, maintaining the same output and logic. | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/')
remove_comments!(str.dup, comment_start, comment_end)
end
example = <<END_OF_STRING
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
END_OF_STRING
puts remove_comments example
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Produce a functionally identical C++ code for the snippet given in Ruby. | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/')
remove_comments!(str.dup, comment_start, comment_end)
end
example = <<END_OF_STRING
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
END_OF_STRING
puts remove_comments example
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Write a version of this Ruby function in Java with identical behavior. | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/')
remove_comments!(str.dup, comment_start, comment_end)
end
example = <<END_OF_STRING
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
END_OF_STRING
puts remove_comments example
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/')
remove_comments!(str.dup, comment_start, comment_end)
end
example = <<END_OF_STRING
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
END_OF_STRING
puts remove_comments example
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Convert the following code from Ruby to VB, ensuring the logic remains intact. | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/')
remove_comments!(str.dup, comment_start, comment_end)
end
example = <<END_OF_STRING
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
END_OF_STRING
puts remove_comments example
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Translate the given Ruby code snippet into Go without altering its behavior. | def remove_comments!(str, comment_start='/*', comment_end='*/')
while start_idx = str.index(comment_start)
end_idx = str.index(comment_end, start_idx + comment_start.length) + comment_end.length - 1
str[start_idx .. end_idx] = ""
end
str
end
def remove_comments(str, comment_start='/*', comment_end='*/')
remove_comments!(str.dup, comment_start, comment_end)
end
example = <<END_OF_STRING
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
*/
function something() {
}
END_OF_STRING
puts remove_comments example
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Generate an equivalent C version of this Scala code. |
val sample = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
val sample2 = """
``{
` Some comments
` longer comments here that we can parse.
`
` Rahoo
``}
function subroutine2() {
d = ``{ inline comment ``} e + f ;
}
``{ / <-- tricky comments ``}
``{
` Another comment.
``}
function something2() {
}
"""
fun stripBlockComments(text: String, del1: String = ""): String {
val d1 = Regex.escape(del1)
val d2 = Regex.escape(del2)
val r = Regex("""(?s)$d1.*?$d2""")
return text.replace(r, "")
}
fun main(args: Array<String>) {
println(stripBlockComments(sample))
println(stripBlockComments(sample2, "``{", "``}"))
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Change the programming language of this snippet from Scala to C# without modifying what it does. |
val sample = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
val sample2 = """
``{
` Some comments
` longer comments here that we can parse.
`
` Rahoo
``}
function subroutine2() {
d = ``{ inline comment ``} e + f ;
}
``{ / <-- tricky comments ``}
``{
` Another comment.
``}
function something2() {
}
"""
fun stripBlockComments(text: String, del1: String = ""): String {
val d1 = Regex.escape(del1)
val d2 = Regex.escape(del2)
val r = Regex("""(?s)$d1.*?$d2""")
return text.replace(r, "")
}
fun main(args: Array<String>) {
println(stripBlockComments(sample))
println(stripBlockComments(sample2, "``{", "``}"))
}
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Change the programming language of this snippet from Scala to C++ without modifying what it does. |
val sample = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
val sample2 = """
``{
` Some comments
` longer comments here that we can parse.
`
` Rahoo
``}
function subroutine2() {
d = ``{ inline comment ``} e + f ;
}
``{ / <-- tricky comments ``}
``{
` Another comment.
``}
function something2() {
}
"""
fun stripBlockComments(text: String, del1: String = ""): String {
val d1 = Regex.escape(del1)
val d2 = Regex.escape(del2)
val r = Regex("""(?s)$d1.*?$d2""")
return text.replace(r, "")
}
fun main(args: Array<String>) {
println(stripBlockComments(sample))
println(stripBlockComments(sample2, "``{", "``}"))
}
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Change the following Scala code into Java without altering its purpose. |
val sample = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
val sample2 = """
``{
` Some comments
` longer comments here that we can parse.
`
` Rahoo
``}
function subroutine2() {
d = ``{ inline comment ``} e + f ;
}
``{ / <-- tricky comments ``}
``{
` Another comment.
``}
function something2() {
}
"""
fun stripBlockComments(text: String, del1: String = ""): String {
val d1 = Regex.escape(del1)
val d2 = Regex.escape(del2)
val r = Regex("""(?s)$d1.*?$d2""")
return text.replace(r, "")
}
fun main(args: Array<String>) {
println(stripBlockComments(sample))
println(stripBlockComments(sample2, "``{", "``}"))
}
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Convert this Scala block to Python, preserving its control flow and logic. |
val sample = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
val sample2 = """
``{
` Some comments
` longer comments here that we can parse.
`
` Rahoo
``}
function subroutine2() {
d = ``{ inline comment ``} e + f ;
}
``{ / <-- tricky comments ``}
``{
` Another comment.
``}
function something2() {
}
"""
fun stripBlockComments(text: String, del1: String = ""): String {
val d1 = Regex.escape(del1)
val d2 = Regex.escape(del2)
val r = Regex("""(?s)$d1.*?$d2""")
return text.replace(r, "")
}
fun main(args: Array<String>) {
println(stripBlockComments(sample))
println(stripBlockComments(sample2, "``{", "``}"))
}
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Convert this Scala block to VB, preserving its control flow and logic. |
val sample = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
val sample2 = """
``{
` Some comments
` longer comments here that we can parse.
`
` Rahoo
``}
function subroutine2() {
d = ``{ inline comment ``} e + f ;
}
``{ / <-- tricky comments ``}
``{
` Another comment.
``}
function something2() {
}
"""
fun stripBlockComments(text: String, del1: String = ""): String {
val d1 = Regex.escape(del1)
val d2 = Regex.escape(del2)
val r = Regex("""(?s)$d1.*?$d2""")
return text.replace(r, "")
}
fun main(args: Array<String>) {
println(stripBlockComments(sample))
println(stripBlockComments(sample2, "``{", "``}"))
}
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Produce a functionally identical Go code for the snippet given in Scala. |
val sample = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
val sample2 = """
``{
` Some comments
` longer comments here that we can parse.
`
` Rahoo
``}
function subroutine2() {
d = ``{ inline comment ``} e + f ;
}
``{ / <-- tricky comments ``}
``{
` Another comment.
``}
function something2() {
}
"""
fun stripBlockComments(text: String, del1: String = ""): String {
val d1 = Regex.escape(del1)
val d2 = Regex.escape(del2)
val r = Regex("""(?s)$d1.*?$d2""")
return text.replace(r, "")
}
fun main(args: Array<String>) {
println(stripBlockComments(sample))
println(stripBlockComments(sample2, "``{", "``}"))
}
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.