Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Preserve the algorithm and functionality while converting the code from Swift to C. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
| #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 the following code from Swift to C#, ensuring the logic remains intact. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
| 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;
}
}
|
Ensure the translated C++ code behaves exactly like the original Swift snippet. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
| #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 ;
}
}
|
Please provide an equivalent version of this Swift code in Java. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
| 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);
}
}
}
|
Translate this program into Python but keep the logic exactly as in Swift. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
| 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 Swift block to VB, preserving its control flow and logic. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
|
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 Swift. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
| 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 code in C as shown below in Tcl. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
| #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 Tcl implementation into C#, maintaining the same output and logic. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
| 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 Tcl to C++. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
| #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 ;
}
}
|
Preserve the algorithm and functionality while converting the code from Tcl to Java. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
| 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);
}
}
}
|
Port the provided Tcl code into Python while preserving the original functionality. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
| 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 Tcl block to VB, preserving its control flow and logic. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
|
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
|
Rewrite this program in Go while keeping its functionality equivalent to the Tcl version. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
| 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 PHP. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
| 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() {
}
" ) . "'";
|
Transform the following AutoHotKey implementation into PHP, maintaining the same output and logic. | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
| 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() {
}
" ) . "'";
|
Keep all operations the same but rewrite the snippet in PHP. |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
| 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() {
}
" ) . "'";
|
Port the provided BBC_Basic code into PHP while preserving the original functionality. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
| 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() {
}
" ) . "'";
|
Keep all operations the same but rewrite the snippet in PHP. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
| 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() {
}
" ) . "'";
|
Translate this program into PHP but keep the logic exactly as in D. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
| 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() {
}
" ) . "'";
|
Preserve the algorithm and functionality while converting the code from Delphi to PHP. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
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() {
}
" ) . "'";
|
Ensure the translated PHP code behaves exactly like the original F# snippet. | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
| 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 functionally identical PHP code for the snippet given in Factor. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
| 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() {
}
" ) . "'";
|
Rewrite the snippet below in PHP so it works the same as the original Fortran code. | 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() {
}
" ) . "'";
|
Maintain the same structure and functionality when rewriting this code in PHP. | def code = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
println ((code =~ "(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?:
| 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() {
}
" ) . "'";
|
Translate this program into PHP but keep the logic exactly as in Haskell. | test = "This {- is not the beginning of a block comment"
| 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() {
}
" ) . "'";
|
Preserve the algorithm and functionality while converting the code from Icon to PHP. | 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
| 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() {
}
" ) . "'";
|
Please provide an equivalent version of this J code in PHP. | 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
)
| 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 Julia to PHP, same semantics. | 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()
| 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() {
}
" ) . "'";
|
Rewrite this program in PHP 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 )
| 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() {
}
" ) . "'";
|
Convert the following code from Mathematica to PHP, ensuring the logic remains intact. | StringReplace[a,"/*"~~Shortest[___]~~"*/" -> ""]
->
function subroutine() {
a = b + c ;
}
function something() {
}
| 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() {
}
" ) . "'";
|
Write a version of this MATLAB function in PHP with identical behavior. | 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;
| 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() {
}
" ) . "'";
|
Port the provided Nim code into PHP while preserving the original functionality. | 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() {
}""")
| 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() {
}
" ) . "'";
|
Write the same algorithm in PHP as shown in this Perl implementation. |
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" ;
| 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 Racket to PHP, 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() {
}
})
| 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() {
}
" ) . "'";
|
Can you help me rewrite this code in PHP instead of REXX, keeping it the same logically? |
* 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)
| 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() {
}
" ) . "'";
|
Write the same code in PHP as shown below 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
| 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() {
}
" ) . "'";
|
Ensure the translated PHP code behaves exactly like the original Scala snippet. |
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, "``{", "``}"))
}
| 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() {
}
" ) . "'";
|
Translate this program into PHP but keep the logic exactly as in Swift. | import Foundation
func stripBlocks(from str: String, open: String = "") -> String {
guard !open.isEmpty && !close.isEmpty else {
return str
}
var ret = str
while let begin = ret.range(of: open), let end = ret[begin.upperBound...].range(of: close) {
ret.replaceSubrange(Range(uncheckedBounds: (begin.lowerBound, end.upperBound)), with: "")
}
return ret
}
let test = """
function subroutine() {
a = b + c ;
}
function something() {
}
"""
print(stripBlocks(from: test))
| 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() {
}
" ) . "'";
|
Rewrite this program in PHP while keeping its functionality equivalent to the Tcl version. | proc stripBlockComment {string {openDelimiter "/*"} {closeDelimiter "*/"}} {
set openAsRE [regsub -all {\W} $openDelimiter {\\&}]
set closeAsRE [regsub -all {\W} $closeDelimiter {\\&}]
regsub -all "$openAsRE.*?$closeAsRE" $string ""
}
| 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() {
}
" ) . "'";
|
Translate this program into C# but keep the logic exactly as in Ada. | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
No_Of_Workers: constant Positive := 6;
type Activity_Array is array(Character) of Boolean;
protected Checkpoint is
entry Deliver;
entry Join (Label : out Character; Tolerance: out Float);
entry Leave(Label : in Character);
private
Signaling : Boolean := False;
Ready_Count : Natural := 0;
Worker_Count : Natural := 0;
Unused_Label : Character := 'A';
Likelyhood_To_Quit: Float := 1.0;
Active : Activity_Array := (others => false);
entry Lodge;
end Checkpoint;
protected body Checkpoint is
entry Join (Label : out Character; Tolerance: out Float)
when not Signaling and Worker_Count < No_Of_Cubicles is
begin
Label := Unused_Label;
Active(Label):= True;
Unused_Label := Character'Succ (Unused_Label);
Worker_Count := Worker_Count + 1;
Likelyhood_To_Quit := Likelyhood_To_Quit / 2.0;
Tolerance := Likelyhood_To_Quit;
end Join;
entry Leave(Label: in Character) when not Signaling is
begin
Worker_Count := Worker_Count - 1;
Active(Label) := False;
end Leave;
entry Deliver when not Signaling is
begin
Ready_Count := Ready_Count + 1;
requeue Lodge;
end Deliver;
entry Lodge when Ready_Count = Worker_Count or Signaling is
begin
if Ready_Count = Worker_Count then
Put("
for C in Character loop
if Active(C) then
Put(C);
end if;
end loop;
Put_Line("]
end if;
Ready_Count := Ready_Count - 1;
Signaling := Ready_Count /= 0;
end Lodge;
end Checkpoint;
task type Worker;
task body Worker is
Dice : FR.Generator;
Label : Character;
Tolerance : Float;
Shift_End : Time := Clock + 2.0;
begin
FR.Reset (Dice);
Checkpoint.Join (Label, Tolerance);
Put_Line(Label & " joins the team");
loop
Put_Line (Label & " is working");
delay Duration (FR.Random (Dice) * 0.500);
Put_Line (Label & " is ready");
Checkpoint.Deliver;
if FR.Random(Dice) < Tolerance then
Put_Line(Label & " leaves the team");
exit;
elsif Clock >= Shift_End then
Put_Line(Label & " ends shift");
exit;
end if;
end loop;
Checkpoint.Leave(Label);
end Worker;
Set : array (1..No_Of_Workers) of Worker;
begin
null;
end Test_Checkpoint;
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C. | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
No_Of_Workers: constant Positive := 6;
type Activity_Array is array(Character) of Boolean;
protected Checkpoint is
entry Deliver;
entry Join (Label : out Character; Tolerance: out Float);
entry Leave(Label : in Character);
private
Signaling : Boolean := False;
Ready_Count : Natural := 0;
Worker_Count : Natural := 0;
Unused_Label : Character := 'A';
Likelyhood_To_Quit: Float := 1.0;
Active : Activity_Array := (others => false);
entry Lodge;
end Checkpoint;
protected body Checkpoint is
entry Join (Label : out Character; Tolerance: out Float)
when not Signaling and Worker_Count < No_Of_Cubicles is
begin
Label := Unused_Label;
Active(Label):= True;
Unused_Label := Character'Succ (Unused_Label);
Worker_Count := Worker_Count + 1;
Likelyhood_To_Quit := Likelyhood_To_Quit / 2.0;
Tolerance := Likelyhood_To_Quit;
end Join;
entry Leave(Label: in Character) when not Signaling is
begin
Worker_Count := Worker_Count - 1;
Active(Label) := False;
end Leave;
entry Deliver when not Signaling is
begin
Ready_Count := Ready_Count + 1;
requeue Lodge;
end Deliver;
entry Lodge when Ready_Count = Worker_Count or Signaling is
begin
if Ready_Count = Worker_Count then
Put("
for C in Character loop
if Active(C) then
Put(C);
end if;
end loop;
Put_Line("]
end if;
Ready_Count := Ready_Count - 1;
Signaling := Ready_Count /= 0;
end Lodge;
end Checkpoint;
task type Worker;
task body Worker is
Dice : FR.Generator;
Label : Character;
Tolerance : Float;
Shift_End : Time := Clock + 2.0;
begin
FR.Reset (Dice);
Checkpoint.Join (Label, Tolerance);
Put_Line(Label & " joins the team");
loop
Put_Line (Label & " is working");
delay Duration (FR.Random (Dice) * 0.500);
Put_Line (Label & " is ready");
Checkpoint.Deliver;
if FR.Random(Dice) < Tolerance then
Put_Line(Label & " leaves the team");
exit;
elsif Clock >= Shift_End then
Put_Line(Label & " ends shift");
exit;
end if;
end loop;
Checkpoint.Leave(Label);
end Worker;
Set : array (1..No_Of_Workers) of Worker;
begin
null;
end Test_Checkpoint;
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Ada to C++. | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
No_Of_Workers: constant Positive := 6;
type Activity_Array is array(Character) of Boolean;
protected Checkpoint is
entry Deliver;
entry Join (Label : out Character; Tolerance: out Float);
entry Leave(Label : in Character);
private
Signaling : Boolean := False;
Ready_Count : Natural := 0;
Worker_Count : Natural := 0;
Unused_Label : Character := 'A';
Likelyhood_To_Quit: Float := 1.0;
Active : Activity_Array := (others => false);
entry Lodge;
end Checkpoint;
protected body Checkpoint is
entry Join (Label : out Character; Tolerance: out Float)
when not Signaling and Worker_Count < No_Of_Cubicles is
begin
Label := Unused_Label;
Active(Label):= True;
Unused_Label := Character'Succ (Unused_Label);
Worker_Count := Worker_Count + 1;
Likelyhood_To_Quit := Likelyhood_To_Quit / 2.0;
Tolerance := Likelyhood_To_Quit;
end Join;
entry Leave(Label: in Character) when not Signaling is
begin
Worker_Count := Worker_Count - 1;
Active(Label) := False;
end Leave;
entry Deliver when not Signaling is
begin
Ready_Count := Ready_Count + 1;
requeue Lodge;
end Deliver;
entry Lodge when Ready_Count = Worker_Count or Signaling is
begin
if Ready_Count = Worker_Count then
Put("
for C in Character loop
if Active(C) then
Put(C);
end if;
end loop;
Put_Line("]
end if;
Ready_Count := Ready_Count - 1;
Signaling := Ready_Count /= 0;
end Lodge;
end Checkpoint;
task type Worker;
task body Worker is
Dice : FR.Generator;
Label : Character;
Tolerance : Float;
Shift_End : Time := Clock + 2.0;
begin
FR.Reset (Dice);
Checkpoint.Join (Label, Tolerance);
Put_Line(Label & " joins the team");
loop
Put_Line (Label & " is working");
delay Duration (FR.Random (Dice) * 0.500);
Put_Line (Label & " is ready");
Checkpoint.Deliver;
if FR.Random(Dice) < Tolerance then
Put_Line(Label & " leaves the team");
exit;
elsif Clock >= Shift_End then
Put_Line(Label & " ends shift");
exit;
end if;
end loop;
Checkpoint.Leave(Label);
end Worker;
Set : array (1..No_Of_Workers) of Worker;
begin
null;
end Test_Checkpoint;
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Rewrite this program in Go while keeping its functionality equivalent to the Ada version. | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
No_Of_Workers: constant Positive := 6;
type Activity_Array is array(Character) of Boolean;
protected Checkpoint is
entry Deliver;
entry Join (Label : out Character; Tolerance: out Float);
entry Leave(Label : in Character);
private
Signaling : Boolean := False;
Ready_Count : Natural := 0;
Worker_Count : Natural := 0;
Unused_Label : Character := 'A';
Likelyhood_To_Quit: Float := 1.0;
Active : Activity_Array := (others => false);
entry Lodge;
end Checkpoint;
protected body Checkpoint is
entry Join (Label : out Character; Tolerance: out Float)
when not Signaling and Worker_Count < No_Of_Cubicles is
begin
Label := Unused_Label;
Active(Label):= True;
Unused_Label := Character'Succ (Unused_Label);
Worker_Count := Worker_Count + 1;
Likelyhood_To_Quit := Likelyhood_To_Quit / 2.0;
Tolerance := Likelyhood_To_Quit;
end Join;
entry Leave(Label: in Character) when not Signaling is
begin
Worker_Count := Worker_Count - 1;
Active(Label) := False;
end Leave;
entry Deliver when not Signaling is
begin
Ready_Count := Ready_Count + 1;
requeue Lodge;
end Deliver;
entry Lodge when Ready_Count = Worker_Count or Signaling is
begin
if Ready_Count = Worker_Count then
Put("
for C in Character loop
if Active(C) then
Put(C);
end if;
end loop;
Put_Line("]
end if;
Ready_Count := Ready_Count - 1;
Signaling := Ready_Count /= 0;
end Lodge;
end Checkpoint;
task type Worker;
task body Worker is
Dice : FR.Generator;
Label : Character;
Tolerance : Float;
Shift_End : Time := Clock + 2.0;
begin
FR.Reset (Dice);
Checkpoint.Join (Label, Tolerance);
Put_Line(Label & " joins the team");
loop
Put_Line (Label & " is working");
delay Duration (FR.Random (Dice) * 0.500);
Put_Line (Label & " is ready");
Checkpoint.Deliver;
if FR.Random(Dice) < Tolerance then
Put_Line(Label & " leaves the team");
exit;
elsif Clock >= Shift_End then
Put_Line(Label & " ends shift");
exit;
end if;
end loop;
Checkpoint.Leave(Label);
end Worker;
Set : array (1..No_Of_Workers) of Worker;
begin
null;
end Test_Checkpoint;
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Preserve the algorithm and functionality while converting the code from Ada to Java. | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
No_Of_Workers: constant Positive := 6;
type Activity_Array is array(Character) of Boolean;
protected Checkpoint is
entry Deliver;
entry Join (Label : out Character; Tolerance: out Float);
entry Leave(Label : in Character);
private
Signaling : Boolean := False;
Ready_Count : Natural := 0;
Worker_Count : Natural := 0;
Unused_Label : Character := 'A';
Likelyhood_To_Quit: Float := 1.0;
Active : Activity_Array := (others => false);
entry Lodge;
end Checkpoint;
protected body Checkpoint is
entry Join (Label : out Character; Tolerance: out Float)
when not Signaling and Worker_Count < No_Of_Cubicles is
begin
Label := Unused_Label;
Active(Label):= True;
Unused_Label := Character'Succ (Unused_Label);
Worker_Count := Worker_Count + 1;
Likelyhood_To_Quit := Likelyhood_To_Quit / 2.0;
Tolerance := Likelyhood_To_Quit;
end Join;
entry Leave(Label: in Character) when not Signaling is
begin
Worker_Count := Worker_Count - 1;
Active(Label) := False;
end Leave;
entry Deliver when not Signaling is
begin
Ready_Count := Ready_Count + 1;
requeue Lodge;
end Deliver;
entry Lodge when Ready_Count = Worker_Count or Signaling is
begin
if Ready_Count = Worker_Count then
Put("
for C in Character loop
if Active(C) then
Put(C);
end if;
end loop;
Put_Line("]
end if;
Ready_Count := Ready_Count - 1;
Signaling := Ready_Count /= 0;
end Lodge;
end Checkpoint;
task type Worker;
task body Worker is
Dice : FR.Generator;
Label : Character;
Tolerance : Float;
Shift_End : Time := Clock + 2.0;
begin
FR.Reset (Dice);
Checkpoint.Join (Label, Tolerance);
Put_Line(Label & " joins the team");
loop
Put_Line (Label & " is working");
delay Duration (FR.Random (Dice) * 0.500);
Put_Line (Label & " is ready");
Checkpoint.Deliver;
if FR.Random(Dice) < Tolerance then
Put_Line(Label & " leaves the team");
exit;
elsif Clock >= Shift_End then
Put_Line(Label & " ends shift");
exit;
end if;
end loop;
Checkpoint.Leave(Label);
end Worker;
Set : array (1..No_Of_Workers) of Worker;
begin
null;
end Test_Checkpoint;
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Write the same code in Python as shown below in Ada. | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
No_Of_Workers: constant Positive := 6;
type Activity_Array is array(Character) of Boolean;
protected Checkpoint is
entry Deliver;
entry Join (Label : out Character; Tolerance: out Float);
entry Leave(Label : in Character);
private
Signaling : Boolean := False;
Ready_Count : Natural := 0;
Worker_Count : Natural := 0;
Unused_Label : Character := 'A';
Likelyhood_To_Quit: Float := 1.0;
Active : Activity_Array := (others => false);
entry Lodge;
end Checkpoint;
protected body Checkpoint is
entry Join (Label : out Character; Tolerance: out Float)
when not Signaling and Worker_Count < No_Of_Cubicles is
begin
Label := Unused_Label;
Active(Label):= True;
Unused_Label := Character'Succ (Unused_Label);
Worker_Count := Worker_Count + 1;
Likelyhood_To_Quit := Likelyhood_To_Quit / 2.0;
Tolerance := Likelyhood_To_Quit;
end Join;
entry Leave(Label: in Character) when not Signaling is
begin
Worker_Count := Worker_Count - 1;
Active(Label) := False;
end Leave;
entry Deliver when not Signaling is
begin
Ready_Count := Ready_Count + 1;
requeue Lodge;
end Deliver;
entry Lodge when Ready_Count = Worker_Count or Signaling is
begin
if Ready_Count = Worker_Count then
Put("
for C in Character loop
if Active(C) then
Put(C);
end if;
end loop;
Put_Line("]
end if;
Ready_Count := Ready_Count - 1;
Signaling := Ready_Count /= 0;
end Lodge;
end Checkpoint;
task type Worker;
task body Worker is
Dice : FR.Generator;
Label : Character;
Tolerance : Float;
Shift_End : Time := Clock + 2.0;
begin
FR.Reset (Dice);
Checkpoint.Join (Label, Tolerance);
Put_Line(Label & " joins the team");
loop
Put_Line (Label & " is working");
delay Duration (FR.Random (Dice) * 0.500);
Put_Line (Label & " is ready");
Checkpoint.Deliver;
if FR.Random(Dice) < Tolerance then
Put_Line(Label & " leaves the team");
exit;
elsif Clock >= Shift_End then
Put_Line(Label & " ends shift");
exit;
end if;
end loop;
Checkpoint.Leave(Label);
end Worker;
Set : array (1..No_Of_Workers) of Worker;
begin
null;
end Test_Checkpoint;
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Rewrite this program in C while keeping its functionality equivalent to the BBC_Basic version. | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
DEF PROCworker3 : PROCtask(3) : ENDPROC
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask(worker%)
PRIVATE cnt%()
DIM cnt%(nWorkers%)
CASE cnt%(worker%) OF
WHEN 0:
cnt%(worker%) = RND(30)
PRINT "Worker "; worker% " starting (" ;cnt%(worker%) " ticks)"
WHEN -1:
OTHERWISE:
cnt%(worker%) -= 1
IF cnt%(worker%) = 0 THEN
PRINT "Worker "; worker% " ready and waiting"
cnt%(worker%) = -1
PROCcheckpoint
cnt%(worker%) = 0
ENDIF
ENDCASE
ENDPROC
DEF PROCcheckpoint
PRIVATE checked%, sync%
IF checked% = 0 sync% = FALSE
checked% += 1
WHILE NOT sync%
WAIT 0
IF checked% = nWorkers% THEN
sync% = TRUE
PRINT "--Sync Point--"
ENDIF
ENDWHILE
checked% -= 1
ENDPROC
DEF PROCcleanup
LOCAL I%
FOR I% = 1 TO nWorkers%
PROC_killtimer(tID%(I%))
NEXT
ENDPROC
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Translate this program into C# but keep the logic exactly as in BBC_Basic. | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
DEF PROCworker3 : PROCtask(3) : ENDPROC
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask(worker%)
PRIVATE cnt%()
DIM cnt%(nWorkers%)
CASE cnt%(worker%) OF
WHEN 0:
cnt%(worker%) = RND(30)
PRINT "Worker "; worker% " starting (" ;cnt%(worker%) " ticks)"
WHEN -1:
OTHERWISE:
cnt%(worker%) -= 1
IF cnt%(worker%) = 0 THEN
PRINT "Worker "; worker% " ready and waiting"
cnt%(worker%) = -1
PROCcheckpoint
cnt%(worker%) = 0
ENDIF
ENDCASE
ENDPROC
DEF PROCcheckpoint
PRIVATE checked%, sync%
IF checked% = 0 sync% = FALSE
checked% += 1
WHILE NOT sync%
WAIT 0
IF checked% = nWorkers% THEN
sync% = TRUE
PRINT "--Sync Point--"
ENDIF
ENDWHILE
checked% -= 1
ENDPROC
DEF PROCcleanup
LOCAL I%
FOR I% = 1 TO nWorkers%
PROC_killtimer(tID%(I%))
NEXT
ENDPROC
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
DEF PROCworker3 : PROCtask(3) : ENDPROC
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask(worker%)
PRIVATE cnt%()
DIM cnt%(nWorkers%)
CASE cnt%(worker%) OF
WHEN 0:
cnt%(worker%) = RND(30)
PRINT "Worker "; worker% " starting (" ;cnt%(worker%) " ticks)"
WHEN -1:
OTHERWISE:
cnt%(worker%) -= 1
IF cnt%(worker%) = 0 THEN
PRINT "Worker "; worker% " ready and waiting"
cnt%(worker%) = -1
PROCcheckpoint
cnt%(worker%) = 0
ENDIF
ENDCASE
ENDPROC
DEF PROCcheckpoint
PRIVATE checked%, sync%
IF checked% = 0 sync% = FALSE
checked% += 1
WHILE NOT sync%
WAIT 0
IF checked% = nWorkers% THEN
sync% = TRUE
PRINT "--Sync Point--"
ENDIF
ENDWHILE
checked% -= 1
ENDPROC
DEF PROCcleanup
LOCAL I%
FOR I% = 1 TO nWorkers%
PROC_killtimer(tID%(I%))
NEXT
ENDPROC
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Transform the following BBC_Basic implementation into Java, maintaining the same output and logic. | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
DEF PROCworker3 : PROCtask(3) : ENDPROC
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask(worker%)
PRIVATE cnt%()
DIM cnt%(nWorkers%)
CASE cnt%(worker%) OF
WHEN 0:
cnt%(worker%) = RND(30)
PRINT "Worker "; worker% " starting (" ;cnt%(worker%) " ticks)"
WHEN -1:
OTHERWISE:
cnt%(worker%) -= 1
IF cnt%(worker%) = 0 THEN
PRINT "Worker "; worker% " ready and waiting"
cnt%(worker%) = -1
PROCcheckpoint
cnt%(worker%) = 0
ENDIF
ENDCASE
ENDPROC
DEF PROCcheckpoint
PRIVATE checked%, sync%
IF checked% = 0 sync% = FALSE
checked% += 1
WHILE NOT sync%
WAIT 0
IF checked% = nWorkers% THEN
sync% = TRUE
PRINT "--Sync Point--"
ENDIF
ENDWHILE
checked% -= 1
ENDPROC
DEF PROCcleanup
LOCAL I%
FOR I% = 1 TO nWorkers%
PROC_killtimer(tID%(I%))
NEXT
ENDPROC
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Write a version of this BBC_Basic function in Python with identical behavior. | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
DEF PROCworker3 : PROCtask(3) : ENDPROC
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask(worker%)
PRIVATE cnt%()
DIM cnt%(nWorkers%)
CASE cnt%(worker%) OF
WHEN 0:
cnt%(worker%) = RND(30)
PRINT "Worker "; worker% " starting (" ;cnt%(worker%) " ticks)"
WHEN -1:
OTHERWISE:
cnt%(worker%) -= 1
IF cnt%(worker%) = 0 THEN
PRINT "Worker "; worker% " ready and waiting"
cnt%(worker%) = -1
PROCcheckpoint
cnt%(worker%) = 0
ENDIF
ENDCASE
ENDPROC
DEF PROCcheckpoint
PRIVATE checked%, sync%
IF checked% = 0 sync% = FALSE
checked% += 1
WHILE NOT sync%
WAIT 0
IF checked% = nWorkers% THEN
sync% = TRUE
PRINT "--Sync Point--"
ENDIF
ENDWHILE
checked% -= 1
ENDPROC
DEF PROCcleanup
LOCAL I%
FOR I% = 1 TO nWorkers%
PROC_killtimer(tID%(I%))
NEXT
ENDPROC
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Preserve the algorithm and functionality while converting the code from BBC_Basic to Go. | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
DEF PROCworker3 : PROCtask(3) : ENDPROC
ON ERROR PROCcleanup : REPORT : PRINT : END
ON CLOSE PROCcleanup : QUIT
REPEAT
WAIT 0
UNTIL FALSE
END
DEF PROCtask(worker%)
PRIVATE cnt%()
DIM cnt%(nWorkers%)
CASE cnt%(worker%) OF
WHEN 0:
cnt%(worker%) = RND(30)
PRINT "Worker "; worker% " starting (" ;cnt%(worker%) " ticks)"
WHEN -1:
OTHERWISE:
cnt%(worker%) -= 1
IF cnt%(worker%) = 0 THEN
PRINT "Worker "; worker% " ready and waiting"
cnt%(worker%) = -1
PROCcheckpoint
cnt%(worker%) = 0
ENDIF
ENDCASE
ENDPROC
DEF PROCcheckpoint
PRIVATE checked%, sync%
IF checked% = 0 sync% = FALSE
checked% += 1
WHILE NOT sync%
WAIT 0
IF checked% = nWorkers% THEN
sync% = TRUE
PRINT "--Sync Point--"
ENDIF
ENDWHILE
checked% -= 1
ENDPROC
DEF PROCcleanup
LOCAL I%
FOR I% = 1 TO nWorkers%
PROC_killtimer(tID%(I%))
NEXT
ENDPROC
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Generate an equivalent C version of this Clojure code. | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000))
(loop [members {}, received {}]
(let [rcvd-count (count received)
release #(doseq [outch (vals members)] (go (>! outch %)))
received (if (and (pos? rcvd-count) (= rcvd-count (count members)))
(do (-> received vals combine release) {})
received)
[v ch] (alts! (cons ctl-ch (keys members)))]
(if (= ch ctl-ch)
(let [[op inch outch] v]
(condp = op
:join (do (>! resp-ch :ok)
(recur (assoc members inch outch) received))
:part (do (>! resp-ch :ok)
(close! inch) (close! outch)
(recur (dissoc members inch) (dissoc received inch)))
:exit :exit))
(if (nil? v)
(do
(close! (get members ch))
(recur (dissoc members ch) (dissoc received ch)))
(recur members (assoc received ch v))))))))
(defprotocol ICheckpoint
(join [this])
(part [this inch outch]))
(deftype Checkpoint [ctl-ch resp-ch sync]
ICheckpoint
(join [this]
(let [inch (async/chan), outch (async/chan 1)]
(go
(>! ctl-ch [:join inch outch])
(<! resp-ch)
[inch outch])))
(part [this inch outch]
(go
(>! ctl-ch [:part inch outch]))))
(defn checkpoint [combine]
(let [ctl-ch (async/chan), resp-ch (async/chan 1)]
(->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine))))
(defn worker
([ckpt repeats] (worker ckpt repeats (fn [& args] nil)))
([ckpt repeats mon]
(go
(let [[send recv] (<! (join ckpt))]
(doseq [n (range repeats)]
(<! (async/timeout (rand-int 5000)))
(>! send n) (mon "sent" n)
(<! recv) (mon "recvd"))
(part ckpt send recv)))))
(defn -main
[& args]
(let [ckpt (checkpoint identity)
monitor (fn [id]
(fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))]
(worker ckpt 10 (monitor 1))
(worker ckpt 10 (monitor 2))))
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Translate the given Clojure code snippet into C# without altering its behavior. | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000))
(loop [members {}, received {}]
(let [rcvd-count (count received)
release #(doseq [outch (vals members)] (go (>! outch %)))
received (if (and (pos? rcvd-count) (= rcvd-count (count members)))
(do (-> received vals combine release) {})
received)
[v ch] (alts! (cons ctl-ch (keys members)))]
(if (= ch ctl-ch)
(let [[op inch outch] v]
(condp = op
:join (do (>! resp-ch :ok)
(recur (assoc members inch outch) received))
:part (do (>! resp-ch :ok)
(close! inch) (close! outch)
(recur (dissoc members inch) (dissoc received inch)))
:exit :exit))
(if (nil? v)
(do
(close! (get members ch))
(recur (dissoc members ch) (dissoc received ch)))
(recur members (assoc received ch v))))))))
(defprotocol ICheckpoint
(join [this])
(part [this inch outch]))
(deftype Checkpoint [ctl-ch resp-ch sync]
ICheckpoint
(join [this]
(let [inch (async/chan), outch (async/chan 1)]
(go
(>! ctl-ch [:join inch outch])
(<! resp-ch)
[inch outch])))
(part [this inch outch]
(go
(>! ctl-ch [:part inch outch]))))
(defn checkpoint [combine]
(let [ctl-ch (async/chan), resp-ch (async/chan 1)]
(->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine))))
(defn worker
([ckpt repeats] (worker ckpt repeats (fn [& args] nil)))
([ckpt repeats mon]
(go
(let [[send recv] (<! (join ckpt))]
(doseq [n (range repeats)]
(<! (async/timeout (rand-int 5000)))
(>! send n) (mon "sent" n)
(<! recv) (mon "recvd"))
(part ckpt send recv)))))
(defn -main
[& args]
(let [ckpt (checkpoint identity)
monitor (fn [id]
(fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))]
(worker ckpt 10 (monitor 1))
(worker ckpt 10 (monitor 2))))
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000))
(loop [members {}, received {}]
(let [rcvd-count (count received)
release #(doseq [outch (vals members)] (go (>! outch %)))
received (if (and (pos? rcvd-count) (= rcvd-count (count members)))
(do (-> received vals combine release) {})
received)
[v ch] (alts! (cons ctl-ch (keys members)))]
(if (= ch ctl-ch)
(let [[op inch outch] v]
(condp = op
:join (do (>! resp-ch :ok)
(recur (assoc members inch outch) received))
:part (do (>! resp-ch :ok)
(close! inch) (close! outch)
(recur (dissoc members inch) (dissoc received inch)))
:exit :exit))
(if (nil? v)
(do
(close! (get members ch))
(recur (dissoc members ch) (dissoc received ch)))
(recur members (assoc received ch v))))))))
(defprotocol ICheckpoint
(join [this])
(part [this inch outch]))
(deftype Checkpoint [ctl-ch resp-ch sync]
ICheckpoint
(join [this]
(let [inch (async/chan), outch (async/chan 1)]
(go
(>! ctl-ch [:join inch outch])
(<! resp-ch)
[inch outch])))
(part [this inch outch]
(go
(>! ctl-ch [:part inch outch]))))
(defn checkpoint [combine]
(let [ctl-ch (async/chan), resp-ch (async/chan 1)]
(->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine))))
(defn worker
([ckpt repeats] (worker ckpt repeats (fn [& args] nil)))
([ckpt repeats mon]
(go
(let [[send recv] (<! (join ckpt))]
(doseq [n (range repeats)]
(<! (async/timeout (rand-int 5000)))
(>! send n) (mon "sent" n)
(<! recv) (mon "recvd"))
(part ckpt send recv)))))
(defn -main
[& args]
(let [ckpt (checkpoint identity)
monitor (fn [id]
(fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))]
(worker ckpt 10 (monitor 1))
(worker ckpt 10 (monitor 2))))
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Keep all operations the same but rewrite the snippet in Java. | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000))
(loop [members {}, received {}]
(let [rcvd-count (count received)
release #(doseq [outch (vals members)] (go (>! outch %)))
received (if (and (pos? rcvd-count) (= rcvd-count (count members)))
(do (-> received vals combine release) {})
received)
[v ch] (alts! (cons ctl-ch (keys members)))]
(if (= ch ctl-ch)
(let [[op inch outch] v]
(condp = op
:join (do (>! resp-ch :ok)
(recur (assoc members inch outch) received))
:part (do (>! resp-ch :ok)
(close! inch) (close! outch)
(recur (dissoc members inch) (dissoc received inch)))
:exit :exit))
(if (nil? v)
(do
(close! (get members ch))
(recur (dissoc members ch) (dissoc received ch)))
(recur members (assoc received ch v))))))))
(defprotocol ICheckpoint
(join [this])
(part [this inch outch]))
(deftype Checkpoint [ctl-ch resp-ch sync]
ICheckpoint
(join [this]
(let [inch (async/chan), outch (async/chan 1)]
(go
(>! ctl-ch [:join inch outch])
(<! resp-ch)
[inch outch])))
(part [this inch outch]
(go
(>! ctl-ch [:part inch outch]))))
(defn checkpoint [combine]
(let [ctl-ch (async/chan), resp-ch (async/chan 1)]
(->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine))))
(defn worker
([ckpt repeats] (worker ckpt repeats (fn [& args] nil)))
([ckpt repeats mon]
(go
(let [[send recv] (<! (join ckpt))]
(doseq [n (range repeats)]
(<! (async/timeout (rand-int 5000)))
(>! send n) (mon "sent" n)
(<! recv) (mon "recvd"))
(part ckpt send recv)))))
(defn -main
[& args]
(let [ckpt (checkpoint identity)
monitor (fn [id]
(fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))]
(worker ckpt 10 (monitor 1))
(worker ckpt 10 (monitor 2))))
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Generate an equivalent Python version of this Clojure code. | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000))
(loop [members {}, received {}]
(let [rcvd-count (count received)
release #(doseq [outch (vals members)] (go (>! outch %)))
received (if (and (pos? rcvd-count) (= rcvd-count (count members)))
(do (-> received vals combine release) {})
received)
[v ch] (alts! (cons ctl-ch (keys members)))]
(if (= ch ctl-ch)
(let [[op inch outch] v]
(condp = op
:join (do (>! resp-ch :ok)
(recur (assoc members inch outch) received))
:part (do (>! resp-ch :ok)
(close! inch) (close! outch)
(recur (dissoc members inch) (dissoc received inch)))
:exit :exit))
(if (nil? v)
(do
(close! (get members ch))
(recur (dissoc members ch) (dissoc received ch)))
(recur members (assoc received ch v))))))))
(defprotocol ICheckpoint
(join [this])
(part [this inch outch]))
(deftype Checkpoint [ctl-ch resp-ch sync]
ICheckpoint
(join [this]
(let [inch (async/chan), outch (async/chan 1)]
(go
(>! ctl-ch [:join inch outch])
(<! resp-ch)
[inch outch])))
(part [this inch outch]
(go
(>! ctl-ch [:part inch outch]))))
(defn checkpoint [combine]
(let [ctl-ch (async/chan), resp-ch (async/chan 1)]
(->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine))))
(defn worker
([ckpt repeats] (worker ckpt repeats (fn [& args] nil)))
([ckpt repeats mon]
(go
(let [[send recv] (<! (join ckpt))]
(doseq [n (range repeats)]
(<! (async/timeout (rand-int 5000)))
(>! send n) (mon "sent" n)
(<! recv) (mon "recvd"))
(part ckpt send recv)))))
(defn -main
[& args]
(let [ckpt (checkpoint identity)
monitor (fn [id]
(fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))]
(worker ckpt 10 (monitor 1))
(worker ckpt 10 (monitor 2))))
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Change the following Clojure code into Go without altering its purpose. | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000))
(loop [members {}, received {}]
(let [rcvd-count (count received)
release #(doseq [outch (vals members)] (go (>! outch %)))
received (if (and (pos? rcvd-count) (= rcvd-count (count members)))
(do (-> received vals combine release) {})
received)
[v ch] (alts! (cons ctl-ch (keys members)))]
(if (= ch ctl-ch)
(let [[op inch outch] v]
(condp = op
:join (do (>! resp-ch :ok)
(recur (assoc members inch outch) received))
:part (do (>! resp-ch :ok)
(close! inch) (close! outch)
(recur (dissoc members inch) (dissoc received inch)))
:exit :exit))
(if (nil? v)
(do
(close! (get members ch))
(recur (dissoc members ch) (dissoc received ch)))
(recur members (assoc received ch v))))))))
(defprotocol ICheckpoint
(join [this])
(part [this inch outch]))
(deftype Checkpoint [ctl-ch resp-ch sync]
ICheckpoint
(join [this]
(let [inch (async/chan), outch (async/chan 1)]
(go
(>! ctl-ch [:join inch outch])
(<! resp-ch)
[inch outch])))
(part [this inch outch]
(go
(>! ctl-ch [:part inch outch]))))
(defn checkpoint [combine]
(let [ctl-ch (async/chan), resp-ch (async/chan 1)]
(->Checkpoint ctl-ch resp-ch (coordinate ctl-ch resp-ch combine))))
(defn worker
([ckpt repeats] (worker ckpt repeats (fn [& args] nil)))
([ckpt repeats mon]
(go
(let [[send recv] (<! (join ckpt))]
(doseq [n (range repeats)]
(<! (async/timeout (rand-int 5000)))
(>! send n) (mon "sent" n)
(<! recv) (mon "recvd"))
(part ckpt send recv)))))
(defn -main
[& args]
(let [ckpt (checkpoint identity)
monitor (fn [id]
(fn [& args] (println (apply str "worker" id ":" (string/join " " args)))))]
(worker ckpt 10 (monitor 1))
(worker ckpt 10 (monitor 2))))
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Write the same algorithm in C as shown in this D implementation. | import std.stdio;
import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;
void buildMechanism(uint nparts) {
auto details = new uint[nparts];
foreach (i, ref detail; taskPool.parallel(details)) {
writeln("Build detail ", i);
detail = i;
}
writeln("Checkpoint reached. Assemble details ...");
uint sum = 0;
foreach (immutable detail; details)
sum += detail;
writeln("Mechanism with ", nparts, " parts finished: ", sum);
}
void main() {
defaultPoolThreads = totalCPUs + 1;
buildMechanism(42);
buildMechanism(11);
}
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Translate the given D code snippet into C# without altering its behavior. | import std.stdio;
import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;
void buildMechanism(uint nparts) {
auto details = new uint[nparts];
foreach (i, ref detail; taskPool.parallel(details)) {
writeln("Build detail ", i);
detail = i;
}
writeln("Checkpoint reached. Assemble details ...");
uint sum = 0;
foreach (immutable detail; details)
sum += detail;
writeln("Mechanism with ", nparts, " parts finished: ", sum);
}
void main() {
defaultPoolThreads = totalCPUs + 1;
buildMechanism(42);
buildMechanism(11);
}
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Generate an equivalent C++ version of this D code. | import std.stdio;
import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;
void buildMechanism(uint nparts) {
auto details = new uint[nparts];
foreach (i, ref detail; taskPool.parallel(details)) {
writeln("Build detail ", i);
detail = i;
}
writeln("Checkpoint reached. Assemble details ...");
uint sum = 0;
foreach (immutable detail; details)
sum += detail;
writeln("Mechanism with ", nparts, " parts finished: ", sum);
}
void main() {
defaultPoolThreads = totalCPUs + 1;
buildMechanism(42);
buildMechanism(11);
}
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Port the following code from D to Java with equivalent syntax and logic. | import std.stdio;
import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;
void buildMechanism(uint nparts) {
auto details = new uint[nparts];
foreach (i, ref detail; taskPool.parallel(details)) {
writeln("Build detail ", i);
detail = i;
}
writeln("Checkpoint reached. Assemble details ...");
uint sum = 0;
foreach (immutable detail; details)
sum += detail;
writeln("Mechanism with ", nparts, " parts finished: ", sum);
}
void main() {
defaultPoolThreads = totalCPUs + 1;
buildMechanism(42);
buildMechanism(11);
}
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Preserve the algorithm and functionality while converting the code from D to Python. | import std.stdio;
import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;
void buildMechanism(uint nparts) {
auto details = new uint[nparts];
foreach (i, ref detail; taskPool.parallel(details)) {
writeln("Build detail ", i);
detail = i;
}
writeln("Checkpoint reached. Assemble details ...");
uint sum = 0;
foreach (immutable detail; details)
sum += detail;
writeln("Mechanism with ", nparts, " parts finished: ", sum);
}
void main() {
defaultPoolThreads = totalCPUs + 1;
buildMechanism(42);
buildMechanism(11);
}
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Convert this D block to Go, preserving its control flow and logic. | import std.stdio;
import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;
void buildMechanism(uint nparts) {
auto details = new uint[nparts];
foreach (i, ref detail; taskPool.parallel(details)) {
writeln("Build detail ", i);
detail = i;
}
writeln("Checkpoint reached. Assemble details ...");
uint sum = 0;
foreach (immutable detail; details)
sum += detail;
writeln("Mechanism with ", nparts, " parts finished: ", sum);
}
void main() {
defaultPoolThreads = totalCPUs + 1;
buildMechanism(42);
buildMechanism(11);
}
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Translate this program into C but keep the logic exactly as in Erlang. | -module( checkpoint_synchronization ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ),
[erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)],
erlang:exit( Pid, normal ).
checkpoint_loop( Assemblings, Completes ) ->
receive
{starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes );
{done, Worker} ->
New_assemblings = lists:delete( Worker, Assemblings ),
New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ),
checkpoint_loop( New_assemblings, New_completes )
end.
checkpoint_loop_release( [], Completes ) ->
[X ! all_complete || X <- Completes],
[];
checkpoint_loop_release( _Assemblings, Completes ) -> Completes.
worker_loop( _Worker, 0, _Checkpoint ) -> ok;
worker_loop( Worker, N, Checkpoint ) ->
Checkpoint ! {starting, erlang:self()},
io:fwrite( "Worker ~p ~p~n", [Worker, N] ),
timer:sleep( random:uniform(100) ),
Checkpoint ! {done, erlang:self()},
receive
all_complete -> ok
end,
worker_loop( Worker, N - 1, Checkpoint ).
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Erlang snippet. | -module( checkpoint_synchronization ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ),
[erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)],
erlang:exit( Pid, normal ).
checkpoint_loop( Assemblings, Completes ) ->
receive
{starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes );
{done, Worker} ->
New_assemblings = lists:delete( Worker, Assemblings ),
New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ),
checkpoint_loop( New_assemblings, New_completes )
end.
checkpoint_loop_release( [], Completes ) ->
[X ! all_complete || X <- Completes],
[];
checkpoint_loop_release( _Assemblings, Completes ) -> Completes.
worker_loop( _Worker, 0, _Checkpoint ) -> ok;
worker_loop( Worker, N, Checkpoint ) ->
Checkpoint ! {starting, erlang:self()},
io:fwrite( "Worker ~p ~p~n", [Worker, N] ),
timer:sleep( random:uniform(100) ),
Checkpoint ! {done, erlang:self()},
receive
all_complete -> ok
end,
worker_loop( Worker, N - 1, Checkpoint ).
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Write the same algorithm in C++ as shown in this Erlang implementation. | -module( checkpoint_synchronization ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ),
[erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)],
erlang:exit( Pid, normal ).
checkpoint_loop( Assemblings, Completes ) ->
receive
{starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes );
{done, Worker} ->
New_assemblings = lists:delete( Worker, Assemblings ),
New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ),
checkpoint_loop( New_assemblings, New_completes )
end.
checkpoint_loop_release( [], Completes ) ->
[X ! all_complete || X <- Completes],
[];
checkpoint_loop_release( _Assemblings, Completes ) -> Completes.
worker_loop( _Worker, 0, _Checkpoint ) -> ok;
worker_loop( Worker, N, Checkpoint ) ->
Checkpoint ! {starting, erlang:self()},
io:fwrite( "Worker ~p ~p~n", [Worker, N] ),
timer:sleep( random:uniform(100) ),
Checkpoint ! {done, erlang:self()},
receive
all_complete -> ok
end,
worker_loop( Worker, N - 1, Checkpoint ).
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Convert this Erlang snippet to Java and keep its semantics consistent. | -module( checkpoint_synchronization ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ),
[erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)],
erlang:exit( Pid, normal ).
checkpoint_loop( Assemblings, Completes ) ->
receive
{starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes );
{done, Worker} ->
New_assemblings = lists:delete( Worker, Assemblings ),
New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ),
checkpoint_loop( New_assemblings, New_completes )
end.
checkpoint_loop_release( [], Completes ) ->
[X ! all_complete || X <- Completes],
[];
checkpoint_loop_release( _Assemblings, Completes ) -> Completes.
worker_loop( _Worker, 0, _Checkpoint ) -> ok;
worker_loop( Worker, N, Checkpoint ) ->
Checkpoint ! {starting, erlang:self()},
io:fwrite( "Worker ~p ~p~n", [Worker, N] ),
timer:sleep( random:uniform(100) ),
Checkpoint ! {done, erlang:self()},
receive
all_complete -> ok
end,
worker_loop( Worker, N - 1, Checkpoint ).
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | -module( checkpoint_synchronization ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ),
[erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)],
erlang:exit( Pid, normal ).
checkpoint_loop( Assemblings, Completes ) ->
receive
{starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes );
{done, Worker} ->
New_assemblings = lists:delete( Worker, Assemblings ),
New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ),
checkpoint_loop( New_assemblings, New_completes )
end.
checkpoint_loop_release( [], Completes ) ->
[X ! all_complete || X <- Completes],
[];
checkpoint_loop_release( _Assemblings, Completes ) -> Completes.
worker_loop( _Worker, 0, _Checkpoint ) -> ok;
worker_loop( Worker, N, Checkpoint ) ->
Checkpoint ! {starting, erlang:self()},
io:fwrite( "Worker ~p ~p~n", [Worker, N] ),
timer:sleep( random:uniform(100) ),
Checkpoint ! {done, erlang:self()},
receive
all_complete -> ok
end,
worker_loop( Worker, N - 1, Checkpoint ).
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Preserve the algorithm and functionality while converting the code from Erlang to Go. | -module( checkpoint_synchronization ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ),
[erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)],
erlang:exit( Pid, normal ).
checkpoint_loop( Assemblings, Completes ) ->
receive
{starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes );
{done, Worker} ->
New_assemblings = lists:delete( Worker, Assemblings ),
New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ),
checkpoint_loop( New_assemblings, New_completes )
end.
checkpoint_loop_release( [], Completes ) ->
[X ! all_complete || X <- Completes],
[];
checkpoint_loop_release( _Assemblings, Completes ) -> Completes.
worker_loop( _Worker, 0, _Checkpoint ) -> ok;
worker_loop( Worker, N, Checkpoint ) ->
Checkpoint ! {starting, erlang:self()},
io:fwrite( "Worker ~p ~p~n", [Worker, N] ),
timer:sleep( random:uniform(100) ),
Checkpoint ! {done, erlang:self()},
receive
all_complete -> ok
end,
worker_loop( Worker, N - 1, Checkpoint ).
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Write the same algorithm in C as shown in this Haskell implementation. | import Control.Parallel
data Task a = Idle | Make a
type TaskList a = [a]
type Results a = [a]
type TaskGroups a = [TaskList a]
type WorkerList a = [Worker a]
type Worker a = [Task a]
runTasks :: TaskList a -> Results a
runTasks [] = []
runTasks (x:[]) = x : []
runTasks (x:y:[]) = y `par` x : y : []
runTasks (x:y:ys) = y `par` x : y : runTasks ys
groupTasks :: WorkerList a -> TaskGroups a
groupTasks [] = []
groupTasks xs
| allWorkersIdle xs = []
| otherwise =
concatMap extractTask xs : groupTasks (map removeTask xs)
extractTask :: Worker a -> [a]
extractTask [] = []
extractTask (Idle:_) = []
extractTask (Make a:_) = [a]
removeTask :: Worker a -> Worker a
removeTask = drop 1
allWorkersIdle :: WorkerList a -> Bool
allWorkersIdle = all null . map extractTask
worker1 :: Worker Integer
worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ]
worker2 :: Worker Integer
worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ]
worker3 :: Worker Integer
worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ]
worker4 :: Worker Integer
worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ]
worker5 :: Worker Integer
worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ]
tasks :: TaskGroups Integer
tasks = groupTasks [worker1, worker2, worker3, worker4, worker5]
workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO ()
workshop func a = mapM_ doWork $ zip [1..length a] a
where
doWork (x, y) = do
putStrLn $ "Doing task " ++ show x ++ "."
putStrLn $ "There are " ++ show (length y) ++ " workers for this task."
putStrLn "Waiting for all workers..."
print $ func $ runTasks y
putStrLn $ "Task " ++ show x ++ " done."
main = workshop sum tasks
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Convert the following code from Haskell to C#, ensuring the logic remains intact. | import Control.Parallel
data Task a = Idle | Make a
type TaskList a = [a]
type Results a = [a]
type TaskGroups a = [TaskList a]
type WorkerList a = [Worker a]
type Worker a = [Task a]
runTasks :: TaskList a -> Results a
runTasks [] = []
runTasks (x:[]) = x : []
runTasks (x:y:[]) = y `par` x : y : []
runTasks (x:y:ys) = y `par` x : y : runTasks ys
groupTasks :: WorkerList a -> TaskGroups a
groupTasks [] = []
groupTasks xs
| allWorkersIdle xs = []
| otherwise =
concatMap extractTask xs : groupTasks (map removeTask xs)
extractTask :: Worker a -> [a]
extractTask [] = []
extractTask (Idle:_) = []
extractTask (Make a:_) = [a]
removeTask :: Worker a -> Worker a
removeTask = drop 1
allWorkersIdle :: WorkerList a -> Bool
allWorkersIdle = all null . map extractTask
worker1 :: Worker Integer
worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ]
worker2 :: Worker Integer
worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ]
worker3 :: Worker Integer
worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ]
worker4 :: Worker Integer
worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ]
worker5 :: Worker Integer
worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ]
tasks :: TaskGroups Integer
tasks = groupTasks [worker1, worker2, worker3, worker4, worker5]
workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO ()
workshop func a = mapM_ doWork $ zip [1..length a] a
where
doWork (x, y) = do
putStrLn $ "Doing task " ++ show x ++ "."
putStrLn $ "There are " ++ show (length y) ++ " workers for this task."
putStrLn "Waiting for all workers..."
print $ func $ runTasks y
putStrLn $ "Task " ++ show x ++ " done."
main = workshop sum tasks
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Change the following Haskell code into C++ without altering its purpose. | import Control.Parallel
data Task a = Idle | Make a
type TaskList a = [a]
type Results a = [a]
type TaskGroups a = [TaskList a]
type WorkerList a = [Worker a]
type Worker a = [Task a]
runTasks :: TaskList a -> Results a
runTasks [] = []
runTasks (x:[]) = x : []
runTasks (x:y:[]) = y `par` x : y : []
runTasks (x:y:ys) = y `par` x : y : runTasks ys
groupTasks :: WorkerList a -> TaskGroups a
groupTasks [] = []
groupTasks xs
| allWorkersIdle xs = []
| otherwise =
concatMap extractTask xs : groupTasks (map removeTask xs)
extractTask :: Worker a -> [a]
extractTask [] = []
extractTask (Idle:_) = []
extractTask (Make a:_) = [a]
removeTask :: Worker a -> Worker a
removeTask = drop 1
allWorkersIdle :: WorkerList a -> Bool
allWorkersIdle = all null . map extractTask
worker1 :: Worker Integer
worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ]
worker2 :: Worker Integer
worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ]
worker3 :: Worker Integer
worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ]
worker4 :: Worker Integer
worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ]
worker5 :: Worker Integer
worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ]
tasks :: TaskGroups Integer
tasks = groupTasks [worker1, worker2, worker3, worker4, worker5]
workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO ()
workshop func a = mapM_ doWork $ zip [1..length a] a
where
doWork (x, y) = do
putStrLn $ "Doing task " ++ show x ++ "."
putStrLn $ "There are " ++ show (length y) ++ " workers for this task."
putStrLn "Waiting for all workers..."
print $ func $ runTasks y
putStrLn $ "Task " ++ show x ++ " done."
main = workshop sum tasks
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Write a version of this Haskell function in Java with identical behavior. | import Control.Parallel
data Task a = Idle | Make a
type TaskList a = [a]
type Results a = [a]
type TaskGroups a = [TaskList a]
type WorkerList a = [Worker a]
type Worker a = [Task a]
runTasks :: TaskList a -> Results a
runTasks [] = []
runTasks (x:[]) = x : []
runTasks (x:y:[]) = y `par` x : y : []
runTasks (x:y:ys) = y `par` x : y : runTasks ys
groupTasks :: WorkerList a -> TaskGroups a
groupTasks [] = []
groupTasks xs
| allWorkersIdle xs = []
| otherwise =
concatMap extractTask xs : groupTasks (map removeTask xs)
extractTask :: Worker a -> [a]
extractTask [] = []
extractTask (Idle:_) = []
extractTask (Make a:_) = [a]
removeTask :: Worker a -> Worker a
removeTask = drop 1
allWorkersIdle :: WorkerList a -> Bool
allWorkersIdle = all null . map extractTask
worker1 :: Worker Integer
worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ]
worker2 :: Worker Integer
worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ]
worker3 :: Worker Integer
worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ]
worker4 :: Worker Integer
worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ]
worker5 :: Worker Integer
worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ]
tasks :: TaskGroups Integer
tasks = groupTasks [worker1, worker2, worker3, worker4, worker5]
workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO ()
workshop func a = mapM_ doWork $ zip [1..length a] a
where
doWork (x, y) = do
putStrLn $ "Doing task " ++ show x ++ "."
putStrLn $ "There are " ++ show (length y) ++ " workers for this task."
putStrLn "Waiting for all workers..."
print $ func $ runTasks y
putStrLn $ "Task " ++ show x ++ " done."
main = workshop sum tasks
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Generate an equivalent Python version of this Haskell code. | import Control.Parallel
data Task a = Idle | Make a
type TaskList a = [a]
type Results a = [a]
type TaskGroups a = [TaskList a]
type WorkerList a = [Worker a]
type Worker a = [Task a]
runTasks :: TaskList a -> Results a
runTasks [] = []
runTasks (x:[]) = x : []
runTasks (x:y:[]) = y `par` x : y : []
runTasks (x:y:ys) = y `par` x : y : runTasks ys
groupTasks :: WorkerList a -> TaskGroups a
groupTasks [] = []
groupTasks xs
| allWorkersIdle xs = []
| otherwise =
concatMap extractTask xs : groupTasks (map removeTask xs)
extractTask :: Worker a -> [a]
extractTask [] = []
extractTask (Idle:_) = []
extractTask (Make a:_) = [a]
removeTask :: Worker a -> Worker a
removeTask = drop 1
allWorkersIdle :: WorkerList a -> Bool
allWorkersIdle = all null . map extractTask
worker1 :: Worker Integer
worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ]
worker2 :: Worker Integer
worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ]
worker3 :: Worker Integer
worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ]
worker4 :: Worker Integer
worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ]
worker5 :: Worker Integer
worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ]
tasks :: TaskGroups Integer
tasks = groupTasks [worker1, worker2, worker3, worker4, worker5]
workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO ()
workshop func a = mapM_ doWork $ zip [1..length a] a
where
doWork (x, y) = do
putStrLn $ "Doing task " ++ show x ++ "."
putStrLn $ "There are " ++ show (length y) ++ " workers for this task."
putStrLn "Waiting for all workers..."
print $ func $ runTasks y
putStrLn $ "Task " ++ show x ++ " done."
main = workshop sum tasks
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Convert this Haskell snippet to Go and keep its semantics consistent. | import Control.Parallel
data Task a = Idle | Make a
type TaskList a = [a]
type Results a = [a]
type TaskGroups a = [TaskList a]
type WorkerList a = [Worker a]
type Worker a = [Task a]
runTasks :: TaskList a -> Results a
runTasks [] = []
runTasks (x:[]) = x : []
runTasks (x:y:[]) = y `par` x : y : []
runTasks (x:y:ys) = y `par` x : y : runTasks ys
groupTasks :: WorkerList a -> TaskGroups a
groupTasks [] = []
groupTasks xs
| allWorkersIdle xs = []
| otherwise =
concatMap extractTask xs : groupTasks (map removeTask xs)
extractTask :: Worker a -> [a]
extractTask [] = []
extractTask (Idle:_) = []
extractTask (Make a:_) = [a]
removeTask :: Worker a -> Worker a
removeTask = drop 1
allWorkersIdle :: WorkerList a -> Bool
allWorkersIdle = all null . map extractTask
worker1 :: Worker Integer
worker1 = map Make [ sum [1..n*1000000] | n <- [1..5] ]
worker2 :: Worker Integer
worker2 = map Make [ sum [1..n*100000] | n <- [1..4] ]
worker3 :: Worker Integer
worker3 = map Make [ sum [1..n*1000000] | n <- [1..3] ]
worker4 :: Worker Integer
worker4 = map Make [ sum [1..n*300000] | n <- [1..5] ]
worker5 :: Worker Integer
worker5 = [Idle] ++ map Make [ sum [1..n*400000] | n <- [1..4] ]
tasks :: TaskGroups Integer
tasks = groupTasks [worker1, worker2, worker3, worker4, worker5]
workshop :: (Show a, Num a, Show b, Num b) => ([a] -> b) -> [[a]] -> IO ()
workshop func a = mapM_ doWork $ zip [1..length a] a
where
doWork (x, y) = do
putStrLn $ "Doing task " ++ show x ++ "."
putStrLn $ "There are " ++ show (length y) ++ " workers for this task."
putStrLn "Waiting for all workers..."
print $ func $ runTasks y
putStrLn $ "Task " ++ show x ++ " done."
main = workshop sum tasks
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Write a version of this J function in C with identical behavior. | {{for. y do. 0 T.'' end.}} 0>.4-1 T.''
ts=: 6!:0
dl=: 6!:3
{{r=.EMPTY for. i.y do. dl 1[ r=.r,3}.ts'' end. r}} t. ''"0(3 5)
┌────────────┬────────────┐
│12 53 53.569│12 53 53.569│
│12 53 54.578│12 53 54.578│
│12 53 55.587│12 53 55.587│
│ │12 53 56.603│
│ │12 53 57.614│
└────────────┴────────────┘
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original J code. | {{for. y do. 0 T.'' end.}} 0>.4-1 T.''
ts=: 6!:0
dl=: 6!:3
{{r=.EMPTY for. i.y do. dl 1[ r=.r,3}.ts'' end. r}} t. ''"0(3 5)
┌────────────┬────────────┐
│12 53 53.569│12 53 53.569│
│12 53 54.578│12 53 54.578│
│12 53 55.587│12 53 55.587│
│ │12 53 56.603│
│ │12 53 57.614│
└────────────┴────────────┘
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Generate a C++ translation of this J snippet without changing its computational steps. | {{for. y do. 0 T.'' end.}} 0>.4-1 T.''
ts=: 6!:0
dl=: 6!:3
{{r=.EMPTY for. i.y do. dl 1[ r=.r,3}.ts'' end. r}} t. ''"0(3 5)
┌────────────┬────────────┐
│12 53 53.569│12 53 53.569│
│12 53 54.578│12 53 54.578│
│12 53 55.587│12 53 55.587│
│ │12 53 56.603│
│ │12 53 57.614│
└────────────┴────────────┘
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Write a version of this J function in Java with identical behavior. | {{for. y do. 0 T.'' end.}} 0>.4-1 T.''
ts=: 6!:0
dl=: 6!:3
{{r=.EMPTY for. i.y do. dl 1[ r=.r,3}.ts'' end. r}} t. ''"0(3 5)
┌────────────┬────────────┐
│12 53 53.569│12 53 53.569│
│12 53 54.578│12 53 54.578│
│12 53 55.587│12 53 55.587│
│ │12 53 56.603│
│ │12 53 57.614│
└────────────┴────────────┘
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Port the following code from J to Python with equivalent syntax and logic. | {{for. y do. 0 T.'' end.}} 0>.4-1 T.''
ts=: 6!:0
dl=: 6!:3
{{r=.EMPTY for. i.y do. dl 1[ r=.r,3}.ts'' end. r}} t. ''"0(3 5)
┌────────────┬────────────┐
│12 53 53.569│12 53 53.569│
│12 53 54.578│12 53 54.578│
│12 53 55.587│12 53 55.587│
│ │12 53 56.603│
│ │12 53 57.614│
└────────────┴────────────┘
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Convert this J snippet to Go and keep its semantics consistent. | {{for. y do. 0 T.'' end.}} 0>.4-1 T.''
ts=: 6!:0
dl=: 6!:3
{{r=.EMPTY for. i.y do. dl 1[ r=.r,3}.ts'' end. r}} t. ''"0(3 5)
┌────────────┬────────────┐
│12 53 53.569│12 53 53.569│
│12 53 54.578│12 53 54.578│
│12 53 55.587│12 53 55.587│
│ │12 53 56.603│
│ │12 53 57.614│
└────────────┴────────────┘
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Transform the following Julia implementation into C, maintaining the same output and logic. | function runsim(numworkers, runs)
for count in 1:runs
@sync begin
for worker in 1:numworkers
@async begin
tasktime = rand()
sleep(tasktime)
println("Worker $worker finished after $tasktime seconds")
end
end
end
println("Checkpoint reached for run $count.")
end
println("Finished all runs.\n")
end
const trials = [[3, 2], [4, 1], [2, 5], [7, 6]]
for trial in trials
runsim(trial[1], trial[2])
end
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Convert this Julia block to C#, preserving its control flow and logic. | function runsim(numworkers, runs)
for count in 1:runs
@sync begin
for worker in 1:numworkers
@async begin
tasktime = rand()
sleep(tasktime)
println("Worker $worker finished after $tasktime seconds")
end
end
end
println("Checkpoint reached for run $count.")
end
println("Finished all runs.\n")
end
const trials = [[3, 2], [4, 1], [2, 5], [7, 6]]
for trial in trials
runsim(trial[1], trial[2])
end
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Convert this Julia block to C++, preserving its control flow and logic. | function runsim(numworkers, runs)
for count in 1:runs
@sync begin
for worker in 1:numworkers
@async begin
tasktime = rand()
sleep(tasktime)
println("Worker $worker finished after $tasktime seconds")
end
end
end
println("Checkpoint reached for run $count.")
end
println("Finished all runs.\n")
end
const trials = [[3, 2], [4, 1], [2, 5], [7, 6]]
for trial in trials
runsim(trial[1], trial[2])
end
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Change the programming language of this snippet from Julia to Java without modifying what it does. | function runsim(numworkers, runs)
for count in 1:runs
@sync begin
for worker in 1:numworkers
@async begin
tasktime = rand()
sleep(tasktime)
println("Worker $worker finished after $tasktime seconds")
end
end
end
println("Checkpoint reached for run $count.")
end
println("Finished all runs.\n")
end
const trials = [[3, 2], [4, 1], [2, 5], [7, 6]]
for trial in trials
runsim(trial[1], trial[2])
end
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Generate a Python translation of this Julia snippet without changing its computational steps. | function runsim(numworkers, runs)
for count in 1:runs
@sync begin
for worker in 1:numworkers
@async begin
tasktime = rand()
sleep(tasktime)
println("Worker $worker finished after $tasktime seconds")
end
end
end
println("Checkpoint reached for run $count.")
end
println("Finished all runs.\n")
end
const trials = [[3, 2], [4, 1], [2, 5], [7, 6]]
for trial in trials
runsim(trial[1], trial[2])
end
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Maintain the same structure and functionality when rewriting this code in Go. | function runsim(numworkers, runs)
for count in 1:runs
@sync begin
for worker in 1:numworkers
@async begin
tasktime = rand()
sleep(tasktime)
println("Worker $worker finished after $tasktime seconds")
end
end
end
println("Checkpoint reached for run $count.")
end
println("Finished all runs.\n")
end
const trials = [[3, 2], [4, 1], [2, 5], [7, 6]]
for trial in trials
runsim(trial[1], trial[2])
end
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Convert this Nim block to C, preserving its control flow and logic. | import locks
import os
import random
import strformat
const
NWorkers = 3
NTasks = 4
StopOrder = 0
var
randLock: Lock
orders: array[1..NWorkers, Channel[int]]
responses: Channel[int]
working: int
threads: array[1..NWorkers, Thread[int]]
proc worker(num: int) {.thread.} =
while true:
let order = orders[num].recv
if order == StopOrder: break
var time: int
withLock(randLock): time = rand(200..1000)
echo fmt"Worker {num}: starting task number {order}"
sleep(time)
echo fmt"Worker {num}: task number {order} terminated after {time} ms"
responses.send(num)
randomize()
randLock.initLock()
for num in 1..NWorkers:
orders[num].open()
responses.open()
for num in 1..NWorkers:
createThread(threads[num], worker, num)
for task in 1..NTasks:
echo fmt"Sending order to start task number {task}"
for num in 1..NWorkers:
orders[num].send(task)
working = NWorkers
while working > 0:
discard responses.recv()
dec working
echo "Sending stop order to workers."
for num in 1..NWorkers:
orders[num].send(StopOrder)
joinThreads(threads)
echo "All workers stopped."
for num in 1..NWorkers:
orders[num].close()
responses.close()
deinitLock(randLock)
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Can you help me rewrite this code in C# instead of Nim, keeping it the same logically? | import locks
import os
import random
import strformat
const
NWorkers = 3
NTasks = 4
StopOrder = 0
var
randLock: Lock
orders: array[1..NWorkers, Channel[int]]
responses: Channel[int]
working: int
threads: array[1..NWorkers, Thread[int]]
proc worker(num: int) {.thread.} =
while true:
let order = orders[num].recv
if order == StopOrder: break
var time: int
withLock(randLock): time = rand(200..1000)
echo fmt"Worker {num}: starting task number {order}"
sleep(time)
echo fmt"Worker {num}: task number {order} terminated after {time} ms"
responses.send(num)
randomize()
randLock.initLock()
for num in 1..NWorkers:
orders[num].open()
responses.open()
for num in 1..NWorkers:
createThread(threads[num], worker, num)
for task in 1..NTasks:
echo fmt"Sending order to start task number {task}"
for num in 1..NWorkers:
orders[num].send(task)
working = NWorkers
while working > 0:
discard responses.recv()
dec working
echo "Sending stop order to workers."
for num in 1..NWorkers:
orders[num].send(StopOrder)
joinThreads(threads)
echo "All workers stopped."
for num in 1..NWorkers:
orders[num].close()
responses.close()
deinitLock(randLock)
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Port the following code from Nim to C++ with equivalent syntax and logic. | import locks
import os
import random
import strformat
const
NWorkers = 3
NTasks = 4
StopOrder = 0
var
randLock: Lock
orders: array[1..NWorkers, Channel[int]]
responses: Channel[int]
working: int
threads: array[1..NWorkers, Thread[int]]
proc worker(num: int) {.thread.} =
while true:
let order = orders[num].recv
if order == StopOrder: break
var time: int
withLock(randLock): time = rand(200..1000)
echo fmt"Worker {num}: starting task number {order}"
sleep(time)
echo fmt"Worker {num}: task number {order} terminated after {time} ms"
responses.send(num)
randomize()
randLock.initLock()
for num in 1..NWorkers:
orders[num].open()
responses.open()
for num in 1..NWorkers:
createThread(threads[num], worker, num)
for task in 1..NTasks:
echo fmt"Sending order to start task number {task}"
for num in 1..NWorkers:
orders[num].send(task)
working = NWorkers
while working > 0:
discard responses.recv()
dec working
echo "Sending stop order to workers."
for num in 1..NWorkers:
orders[num].send(StopOrder)
joinThreads(threads)
echo "All workers stopped."
for num in 1..NWorkers:
orders[num].close()
responses.close()
deinitLock(randLock)
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Change the following Nim code into Java without altering its purpose. | import locks
import os
import random
import strformat
const
NWorkers = 3
NTasks = 4
StopOrder = 0
var
randLock: Lock
orders: array[1..NWorkers, Channel[int]]
responses: Channel[int]
working: int
threads: array[1..NWorkers, Thread[int]]
proc worker(num: int) {.thread.} =
while true:
let order = orders[num].recv
if order == StopOrder: break
var time: int
withLock(randLock): time = rand(200..1000)
echo fmt"Worker {num}: starting task number {order}"
sleep(time)
echo fmt"Worker {num}: task number {order} terminated after {time} ms"
responses.send(num)
randomize()
randLock.initLock()
for num in 1..NWorkers:
orders[num].open()
responses.open()
for num in 1..NWorkers:
createThread(threads[num], worker, num)
for task in 1..NTasks:
echo fmt"Sending order to start task number {task}"
for num in 1..NWorkers:
orders[num].send(task)
working = NWorkers
while working > 0:
discard responses.recv()
dec working
echo "Sending stop order to workers."
for num in 1..NWorkers:
orders[num].send(StopOrder)
joinThreads(threads)
echo "All workers stopped."
for num in 1..NWorkers:
orders[num].close()
responses.close()
deinitLock(randLock)
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Produce a functionally identical Python code for the snippet given in Nim. | import locks
import os
import random
import strformat
const
NWorkers = 3
NTasks = 4
StopOrder = 0
var
randLock: Lock
orders: array[1..NWorkers, Channel[int]]
responses: Channel[int]
working: int
threads: array[1..NWorkers, Thread[int]]
proc worker(num: int) {.thread.} =
while true:
let order = orders[num].recv
if order == StopOrder: break
var time: int
withLock(randLock): time = rand(200..1000)
echo fmt"Worker {num}: starting task number {order}"
sleep(time)
echo fmt"Worker {num}: task number {order} terminated after {time} ms"
responses.send(num)
randomize()
randLock.initLock()
for num in 1..NWorkers:
orders[num].open()
responses.open()
for num in 1..NWorkers:
createThread(threads[num], worker, num)
for task in 1..NTasks:
echo fmt"Sending order to start task number {task}"
for num in 1..NWorkers:
orders[num].send(task)
working = NWorkers
while working > 0:
discard responses.recv()
dec working
echo "Sending stop order to workers."
for num in 1..NWorkers:
orders[num].send(StopOrder)
joinThreads(threads)
echo "All workers stopped."
for num in 1..NWorkers:
orders[num].close()
responses.close()
deinitLock(randLock)
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Write a version of this Nim function in Go with identical behavior. | import locks
import os
import random
import strformat
const
NWorkers = 3
NTasks = 4
StopOrder = 0
var
randLock: Lock
orders: array[1..NWorkers, Channel[int]]
responses: Channel[int]
working: int
threads: array[1..NWorkers, Thread[int]]
proc worker(num: int) {.thread.} =
while true:
let order = orders[num].recv
if order == StopOrder: break
var time: int
withLock(randLock): time = rand(200..1000)
echo fmt"Worker {num}: starting task number {order}"
sleep(time)
echo fmt"Worker {num}: task number {order} terminated after {time} ms"
responses.send(num)
randomize()
randLock.initLock()
for num in 1..NWorkers:
orders[num].open()
responses.open()
for num in 1..NWorkers:
createThread(threads[num], worker, num)
for task in 1..NTasks:
echo fmt"Sending order to start task number {task}"
for num in 1..NWorkers:
orders[num].send(task)
working = NWorkers
while working > 0:
discard responses.recv()
dec working
echo "Sending stop order to workers."
for num in 1..NWorkers:
orders[num].send(StopOrder)
joinThreads(threads)
echo "All workers stopped."
for num in 1..NWorkers:
orders[num].close()
responses.close()
deinitLock(randLock)
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Port the provided Perl code into C while preserving the original functionality. |
use warnings;
use strict;
use v5.10;
use Socket;
my $nr_items = 3;
sub short_sleep($) {
(my $seconds) = @_;
select undef, undef, undef, $seconds;
}
sub be_worker($$) {
my ($socket, $value) = @_;
for (1 .. $nr_items) {
sysread $socket, my $dummy, 1;
short_sleep rand 0.5;
syswrite $socket, $value;
++$value;
}
exit;
}
sub fork_worker($) {
(my $value) = @_;
socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC
or die "socketpair: $!";
if (fork // die "fork: $!") {
close $dadsock;
return $kidsock;
}
else {
close $kidsock;
be_worker $dadsock, $value;
}
}
my $alpha_sock = fork_worker 'A';
my $digit_sock = fork_worker 1;
for (1 .. $nr_items) {
syswrite $_, 'x' for $alpha_sock, $digit_sock;
sysread $alpha_sock, my $alpha, 1;
sysread $digit_sock, my $digit, 1;
say $alpha, $digit;
}
wait; wait;
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
#pragma omp barrier
if (!jobs) break;
printf("%d: taking job %d\n", tid, jobs--);
usleep(100000 + rand() / (double) RAND_MAX * 3000000);
printf("%d: done job\n", tid);
}
printf("[%d] leaving\n", tid);
#pragma omp barrier
}
return 0;
}
|
Write a version of this Perl function in C# with identical behavior. |
use warnings;
use strict;
use v5.10;
use Socket;
my $nr_items = 3;
sub short_sleep($) {
(my $seconds) = @_;
select undef, undef, undef, $seconds;
}
sub be_worker($$) {
my ($socket, $value) = @_;
for (1 .. $nr_items) {
sysread $socket, my $dummy, 1;
short_sleep rand 0.5;
syswrite $socket, $value;
++$value;
}
exit;
}
sub fork_worker($) {
(my $value) = @_;
socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC
or die "socketpair: $!";
if (fork // die "fork: $!") {
close $dadsock;
return $kidsock;
}
else {
close $kidsock;
be_worker $dadsock, $value;
}
}
my $alpha_sock = fork_worker 'A';
my $digit_sock = fork_worker 1;
for (1 .. $nr_items) {
syswrite $_, 'x' for $alpha_sock, $digit_sock;
sysread $alpha_sock, my $alpha, 1;
sysread $digit_sock, my $digit, 1;
say $alpha, $digit;
}
wait; wait;
| using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Rosetta.CheckPointSync;
public class Program
{
public async Task Main()
{
RobotBuilder robotBuilder = new RobotBuilder();
Task work = robotBuilder.BuildRobots(
"Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
"Bender", "Number Six", "C3-PO", "Dolores");
await work;
}
public class RobotBuilder
{
static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
static readonly Random rng = new Random();
static readonly object key = new object();
public Task BuildRobots(params string[] robots)
{
int r = 0;
Barrier checkpoint = new Barrier(parts.Length, b => {
Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
Console.WriteLine();
r++;
});
var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
return Task.WhenAll(tasks);
}
private static int GetTime()
{
lock (key) {
return rng.Next(100, 1000);
}
}
private async Task BuildPart(Barrier barrier, string part, string[] robots)
{
foreach (var robot in robots) {
int time = GetTime();
Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
await Task.Delay(time);
Console.WriteLine($"{part} for {robot} finished.");
barrier.SignalAndWait();
}
}
}
}
|
Convert this Perl snippet to C++ and keep its semantics consistent. |
use warnings;
use strict;
use v5.10;
use Socket;
my $nr_items = 3;
sub short_sleep($) {
(my $seconds) = @_;
select undef, undef, undef, $seconds;
}
sub be_worker($$) {
my ($socket, $value) = @_;
for (1 .. $nr_items) {
sysread $socket, my $dummy, 1;
short_sleep rand 0.5;
syswrite $socket, $value;
++$value;
}
exit;
}
sub fork_worker($) {
(my $value) = @_;
socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC
or die "socketpair: $!";
if (fork // die "fork: $!") {
close $dadsock;
return $kidsock;
}
else {
close $kidsock;
be_worker $dadsock, $value;
}
}
my $alpha_sock = fork_worker 'A';
my $digit_sock = fork_worker 1;
for (1 .. $nr_items) {
syswrite $_, 'x' for $alpha_sock, $digit_sock;
sysread $alpha_sock, my $alpha, 1;
sysread $digit_sock, my $digit, 1;
say $alpha, $digit;
}
wait; wait;
| #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
std::this_thread::yield();
}
};
struct Worker
{
static void do_work(int how_long, Latch& barrier, std::string name)
{
std::this_thread::sleep_for(std::chrono::milliseconds(how_long));
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished work\n"; }
barrier.wait();
{ std::lock_guard<std::mutex> lock(cout_lock);
std::cout << "Worker " << name << " finished assembly\n"; }
}
};
int main()
{
Latch latch(5);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<> dist(300, 3000);
std::thread threads[] {
std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"),
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"},
std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"},
};
for(auto& t: threads) t.join();
std::cout << "Assembly is finished";
}
|
Ensure the translated Java code behaves exactly like the original Perl snippet. |
use warnings;
use strict;
use v5.10;
use Socket;
my $nr_items = 3;
sub short_sleep($) {
(my $seconds) = @_;
select undef, undef, undef, $seconds;
}
sub be_worker($$) {
my ($socket, $value) = @_;
for (1 .. $nr_items) {
sysread $socket, my $dummy, 1;
short_sleep rand 0.5;
syswrite $socket, $value;
++$value;
}
exit;
}
sub fork_worker($) {
(my $value) = @_;
socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC
or die "socketpair: $!";
if (fork // die "fork: $!") {
close $dadsock;
return $kidsock;
}
else {
close $kidsock;
be_worker $dadsock, $value;
}
}
my $alpha_sock = fork_worker 'A';
my $digit_sock = fork_worker 1;
for (1 .. $nr_items) {
syswrite $_, 'x' for $alpha_sock, $digit_sock;
sysread $alpha_sock, my $alpha, 1;
sysread $digit_sock, my $digit, 1;
say $alpha, $digit;
}
wait; wait;
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Convert this Perl snippet to Python and keep its semantics consistent. |
use warnings;
use strict;
use v5.10;
use Socket;
my $nr_items = 3;
sub short_sleep($) {
(my $seconds) = @_;
select undef, undef, undef, $seconds;
}
sub be_worker($$) {
my ($socket, $value) = @_;
for (1 .. $nr_items) {
sysread $socket, my $dummy, 1;
short_sleep rand 0.5;
syswrite $socket, $value;
++$value;
}
exit;
}
sub fork_worker($) {
(my $value) = @_;
socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC
or die "socketpair: $!";
if (fork // die "fork: $!") {
close $dadsock;
return $kidsock;
}
else {
close $kidsock;
be_worker $dadsock, $value;
}
}
my $alpha_sock = fork_worker 'A';
my $digit_sock = fork_worker 1;
for (1 .. $nr_items) {
syswrite $_, 'x' for $alpha_sock, $digit_sock;
sysread $alpha_sock, my $alpha, 1;
sysread $digit_sock, my $digit, 1;
say $alpha, $digit;
}
wait; wait;
|
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
|
Ensure the translated Go code behaves exactly like the original Perl snippet. |
use warnings;
use strict;
use v5.10;
use Socket;
my $nr_items = 3;
sub short_sleep($) {
(my $seconds) = @_;
select undef, undef, undef, $seconds;
}
sub be_worker($$) {
my ($socket, $value) = @_;
for (1 .. $nr_items) {
sysread $socket, my $dummy, 1;
short_sleep rand 0.5;
syswrite $socket, $value;
++$value;
}
exit;
}
sub fork_worker($) {
(my $value) = @_;
socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC
or die "socketpair: $!";
if (fork // die "fork: $!") {
close $dadsock;
return $kidsock;
}
else {
close $kidsock;
be_worker $dadsock, $value;
}
}
my $alpha_sock = fork_worker 'A';
my $digit_sock = fork_worker 1;
for (1 .. $nr_items) {
syswrite $_, 'x' for $alpha_sock, $digit_sock;
sysread $alpha_sock, my $alpha, 1;
sysread $digit_sock, my $digit, 1;
say $alpha, $digit;
}
wait; wait;
| package main
import (
"log"
"math/rand"
"sync"
"time"
)
func worker(part string) {
log.Println(part, "worker begins part")
time.Sleep(time.Duration(rand.Int63n(1e6)))
log.Println(part, "worker completes part")
wg.Done()
}
var (
partList = []string{"A", "B", "C", "D"}
nAssemblies = 3
wg sync.WaitGroup
)
func main() {
rand.Seed(time.Now().UnixNano())
for c := 1; c <= nAssemblies; c++ {
log.Println("begin assembly cycle", c)
wg.Add(len(partList))
for _, part := range partList {
go worker(part)
}
wg.Wait()
log.Println("assemble. cycle", c, "complete")
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.