Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in C#.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
using System; using System.Collections.Generic; using System.Text; namespace TheNameGame { class Program { static void PrintVerse(string name) { StringBuilder sb = new StringBuilder(name.ToLower()); sb[0] = Char.ToUpper(sb[0]); string x = sb.ToString(); string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1); string b = "b" + y; string f = "f" + y; string m = "m" + y; switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; } Console.WriteLine("{0}, {0}, bo-{1}", x, b); Console.WriteLine("Banana-fana fo-{0}", f); Console.WriteLine("Fee-fi-mo-{0}", m); Console.WriteLine("{0}!", x); Console.WriteLine(); } static void Main(string[] args) { List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; nameList.ForEach(PrintVerse); } } }
Translate the given REXX code snippet into C# without altering its behavior.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
using System; using System.Collections.Generic; using System.Text; namespace TheNameGame { class Program { static void PrintVerse(string name) { StringBuilder sb = new StringBuilder(name.ToLower()); sb[0] = Char.ToUpper(sb[0]); string x = sb.ToString(); string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1); string b = "b" + y; string f = "f" + y; string m = "m" + y; switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; } Console.WriteLine("{0}, {0}, bo-{1}", x, b); Console.WriteLine("Banana-fana fo-{0}", f); Console.WriteLine("Fee-fi-mo-{0}", m); Console.WriteLine("{0}!", x); Console.WriteLine(); } static void Main(string[] args) { List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; nameList.ForEach(PrintVerse); } } }
Translate the given REXX code snippet into C++ without altering its behavior.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
#include <algorithm> #include <iostream> #include <string> #include <vector> static void printVerse(const std::string& name) { std::string x = name; std::transform(x.begin(), x.end(), x.begin(), ::tolower); x[0] = toupper(x[0]); std::string y; switch (x[0]) { case 'A': case 'E': case 'I': case 'O': case 'U': y = x; std::transform(y.begin(), y.end(), y.begin(), ::tolower); break; default: y = x.substr(1); break; } std::string b("b" + y); std::string f("f" + y); std::string m("m" + y); switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str()); printf("Banana-fana fo-%s\n", f.c_str()); printf("Fee-fi-mo-%s\n", m.c_str()); printf("%s!\n\n", x.c_str()); } int main() { using namespace std; vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; for (auto& name : nameList) { printVerse(name); } return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the REXX version.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
#include <algorithm> #include <iostream> #include <string> #include <vector> static void printVerse(const std::string& name) { std::string x = name; std::transform(x.begin(), x.end(), x.begin(), ::tolower); x[0] = toupper(x[0]); std::string y; switch (x[0]) { case 'A': case 'E': case 'I': case 'O': case 'U': y = x; std::transform(y.begin(), y.end(), y.begin(), ::tolower); break; default: y = x.substr(1); break; } std::string b("b" + y); std::string f("f" + y); std::string m("m" + y); switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str()); printf("Banana-fana fo-%s\n", f.c_str()); printf("Fee-fi-mo-%s\n", m.c_str()); printf("%s!\n\n", x.c_str()); } int main() { using namespace std; vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; for (auto& name : nameList) { printVerse(name); } return 0; }
Convert this REXX snippet to Java and keep its semantics consistent.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
import java.util.stream.Stream; public class NameGame { private static void printVerse(String name) { StringBuilder sb = new StringBuilder(name.toLowerCase()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); String x = sb.toString(); String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1); String b = "b" + y; String f = "f" + y; String m = "m" + y; switch (x.charAt(0)) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } System.out.printf("%s, %s, bo-%s\n", x, x, b); System.out.printf("Banana-fana fo-%s\n", f); System.out.printf("Fee-fi-mo-%s\n", m); System.out.printf("%s!\n\n", x); } public static void main(String[] args) { Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse); } }
Can you help me rewrite this code in Java instead of REXX, keeping it the same logically?
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
import java.util.stream.Stream; public class NameGame { private static void printVerse(String name) { StringBuilder sb = new StringBuilder(name.toLowerCase()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); String x = sb.toString(); String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1); String b = "b" + y; String f = "f" + y; String m = "m" + y; switch (x.charAt(0)) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } System.out.printf("%s, %s, bo-%s\n", x, x, b); System.out.printf("Banana-fana fo-%s\n", f); System.out.printf("Fee-fi-mo-%s\n", m); System.out.printf("%s!\n\n", x); } public static void main(String[] args) { Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse); } }
Can you help me rewrite this code in Python instead of REXX, keeping it the same logically?
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
def print_verse(n): l = ['b', 'f', 'm'] s = n[1:] if str.lower(n[0]) in l: l[l.index(str.lower(n[0]))] = '' elif n[0] in ['A', 'E', 'I', 'O', 'U']: s = str.lower(n) print('{0}, {0}, bo-{2}{1}\nBanana-fana fo-{3}{1}\nFee-fi-mo-{4}{1}\n{0}!\n'.format(n, s, *l)) for n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']: print_verse(n)
Change the following REXX code into Python without altering its purpose.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
def print_verse(n): l = ['b', 'f', 'm'] s = n[1:] if str.lower(n[0]) in l: l[l.index(str.lower(n[0]))] = '' elif n[0] in ['A', 'E', 'I', 'O', 'U']: s = str.lower(n) print('{0}, {0}, bo-{2}{1}\nBanana-fana fo-{3}{1}\nFee-fi-mo-{4}{1}\n{0}!\n'.format(n, s, *l)) for n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']: print_verse(n)
Generate a VB translation of this REXX snippet without changing its computational steps.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
Option Explicit Sub Main() Dim a, r, i As Integer Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^" a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank") r = TheGameName(a, SCHEM) For i = LBound(r) To UBound(r) Debug.Print r(i) Next i End Sub Private Function TheGameName(MyArr, S As String) As String() Dim i As Integer, s1 As String, s2 As String, tp As String, t() As String ReDim t(UBound(MyArr)) For i = LBound(MyArr) To UBound(MyArr) tp = Replace(S, "^", vbCrLf) s2 = LCase(Mid(MyArr(i), 2)): s1 = UCase(Left(MyArr(i), 1)) & s2 Select Case UCase(Left(MyArr(i), 1)) Case "A", "E", "I", "O", "U": tp = Replace(tp, "(Y)", LCase(MyArr(i))) Case "B", "F", "M" tp = Replace(tp, "(Y)", s2) tp = Replace(tp, LCase(MyArr(i)), s2) Case Else: tp = Replace(tp, "(Y)", s2) End Select t(i) = Replace(tp, "(X)", s1) Next TheGameName = t End Function
Produce a language-to-language conversion: from REXX to VB, same semantics.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
Option Explicit Sub Main() Dim a, r, i As Integer Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^" a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank") r = TheGameName(a, SCHEM) For i = LBound(r) To UBound(r) Debug.Print r(i) Next i End Sub Private Function TheGameName(MyArr, S As String) As String() Dim i As Integer, s1 As String, s2 As String, tp As String, t() As String ReDim t(UBound(MyArr)) For i = LBound(MyArr) To UBound(MyArr) tp = Replace(S, "^", vbCrLf) s2 = LCase(Mid(MyArr(i), 2)): s1 = UCase(Left(MyArr(i), 1)) & s2 Select Case UCase(Left(MyArr(i), 1)) Case "A", "E", "I", "O", "U": tp = Replace(tp, "(Y)", LCase(MyArr(i))) Case "B", "F", "M" tp = Replace(tp, "(Y)", s2) tp = Replace(tp, LCase(MyArr(i)), s2) Case Else: tp = Replace(tp, "(Y)", s2) End Select t(i) = Replace(tp, "(X)", s1) Next TheGameName = t End Function
Change the following REXX code into Go without altering its purpose.
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
package main import ( "fmt" "strings" ) func printVerse(name string) { x := strings.Title(strings.ToLower(name)) y := x[1:] if strings.Contains("AEIOU", x[:1]) { y = strings.ToLower(x) } b := "b" + y f := "f" + y m := "m" + y switch x[0] { case 'B': b = y case 'F': f = y case 'M': m = y } fmt.Printf("%s, %s, bo-%s\n", x, x, b) fmt.Printf("Banana-fana fo-%s\n", f) fmt.Printf("Fee-fi-mo-%s\n", m) fmt.Printf("%s!\n\n", x) } func main() { names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} for _, name := range names { printVerse(name) } }
Can you help me rewrite this code in Go instead of REXX, keeping it the same logically?
parse arg $ if $='' then $="gAry, eARL, billy, FeLix, MarY" do j=1 until $=''; $=space($) parse var $ name',' $ call song name end exit song: arg c 2 1 z; @b='b'; @f="f"; @m='m' @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU z=c || translate( substr(z, 2),@abc,@abcU) parse var z f 2 '' 1 z y=substr(z, 2); zl=translate(z, @abc, @abcU) select when pos(f, 'AEIOU')\==0 then do; say z',' z", bo-b"zl say 'Banana-fana fo-f'zl say 'Fee-fi-mo-m'zl end when pos(f, 'BFM' )\==0 then do; if f=='B' then @b= if f=='F' then @f= if f=='M' then @m= say z',' z", bo-"@b || y say 'Banana-fana fo-'@f || y say 'Fee-fi-mo-'@m || y end otherwise say z',' z", bo-b"y say 'Banana-fana fo-f'y say 'Fee-fi-mo-m'y end say z'!'; say return
package main import ( "fmt" "strings" ) func printVerse(name string) { x := strings.Title(strings.ToLower(name)) y := x[1:] if strings.Contains("AEIOU", x[:1]) { y = strings.ToLower(x) } b := "b" + y f := "f" + y m := "m" + y switch x[0] { case 'B': b = y case 'F': f = y case 'M': m = y } fmt.Printf("%s, %s, bo-%s\n", x, x, b) fmt.Printf("Banana-fana fo-%s\n", f) fmt.Printf("Fee-fi-mo-%s\n", m) fmt.Printf("%s!\n\n", x) } func main() { names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} for _, name := range names { printVerse(name) } }
Translate the given Ruby code snippet into C without altering its behavior.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
#include <stdio.h> #include <string.h> void print_verse(const char *name) { char *x, *y; int b = 1, f = 1, m = 1, i = 1; x = strdup(name); x[0] = toupper(x[0]); for (; x[i]; ++i) x[i] = tolower(x[i]); if (strchr("AEIOU", x[0])) { y = strdup(x); y[0] = tolower(y[0]); } else { y = x + 1; } switch(x[0]) { case 'B': b = 0; break; case 'F': f = 0; break; case 'M': m = 0; break; default : break; } printf("%s, %s, bo-%s%s\n", x, x, (b) ? "b" : "", y); printf("Banana-fana fo-%s%s\n", (f) ? "f" : "", y); printf("Fee-fi-mo-%s%s\n", (m) ? "m" : "", y); printf("%s!\n\n", x); } int main() { int i; const char *names[6] = {"gARY", "Earl", "Billy", "Felix", "Mary", "sHIRley"}; for (i = 0; i < 6; ++i) print_verse(names[i]); return 0; }
Rewrite this program in C while keeping its functionality equivalent to the Ruby version.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
#include <stdio.h> #include <string.h> void print_verse(const char *name) { char *x, *y; int b = 1, f = 1, m = 1, i = 1; x = strdup(name); x[0] = toupper(x[0]); for (; x[i]; ++i) x[i] = tolower(x[i]); if (strchr("AEIOU", x[0])) { y = strdup(x); y[0] = tolower(y[0]); } else { y = x + 1; } switch(x[0]) { case 'B': b = 0; break; case 'F': f = 0; break; case 'M': m = 0; break; default : break; } printf("%s, %s, bo-%s%s\n", x, x, (b) ? "b" : "", y); printf("Banana-fana fo-%s%s\n", (f) ? "f" : "", y); printf("Fee-fi-mo-%s%s\n", (m) ? "m" : "", y); printf("%s!\n\n", x); } int main() { int i; const char *names[6] = {"gARY", "Earl", "Billy", "Felix", "Mary", "sHIRley"}; for (i = 0; i < 6; ++i) print_verse(names[i]); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
using System; using System.Collections.Generic; using System.Text; namespace TheNameGame { class Program { static void PrintVerse(string name) { StringBuilder sb = new StringBuilder(name.ToLower()); sb[0] = Char.ToUpper(sb[0]); string x = sb.ToString(); string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1); string b = "b" + y; string f = "f" + y; string m = "m" + y; switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; } Console.WriteLine("{0}, {0}, bo-{1}", x, b); Console.WriteLine("Banana-fana fo-{0}", f); Console.WriteLine("Fee-fi-mo-{0}", m); Console.WriteLine("{0}!", x); Console.WriteLine(); } static void Main(string[] args) { List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; nameList.ForEach(PrintVerse); } } }
Generate an equivalent C# version of this Ruby code.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
using System; using System.Collections.Generic; using System.Text; namespace TheNameGame { class Program { static void PrintVerse(string name) { StringBuilder sb = new StringBuilder(name.ToLower()); sb[0] = Char.ToUpper(sb[0]); string x = sb.ToString(); string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1); string b = "b" + y; string f = "f" + y; string m = "m" + y; switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; } Console.WriteLine("{0}, {0}, bo-{1}", x, b); Console.WriteLine("Banana-fana fo-{0}", f); Console.WriteLine("Fee-fi-mo-{0}", m); Console.WriteLine("{0}!", x); Console.WriteLine(); } static void Main(string[] args) { List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; nameList.ForEach(PrintVerse); } } }
Write the same algorithm in C++ as shown in this Ruby implementation.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
#include <algorithm> #include <iostream> #include <string> #include <vector> static void printVerse(const std::string& name) { std::string x = name; std::transform(x.begin(), x.end(), x.begin(), ::tolower); x[0] = toupper(x[0]); std::string y; switch (x[0]) { case 'A': case 'E': case 'I': case 'O': case 'U': y = x; std::transform(y.begin(), y.end(), y.begin(), ::tolower); break; default: y = x.substr(1); break; } std::string b("b" + y); std::string f("f" + y); std::string m("m" + y); switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str()); printf("Banana-fana fo-%s\n", f.c_str()); printf("Fee-fi-mo-%s\n", m.c_str()); printf("%s!\n\n", x.c_str()); } int main() { using namespace std; vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; for (auto& name : nameList) { printVerse(name); } return 0; }
Port the following code from Ruby to C++ with equivalent syntax and logic.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
#include <algorithm> #include <iostream> #include <string> #include <vector> static void printVerse(const std::string& name) { std::string x = name; std::transform(x.begin(), x.end(), x.begin(), ::tolower); x[0] = toupper(x[0]); std::string y; switch (x[0]) { case 'A': case 'E': case 'I': case 'O': case 'U': y = x; std::transform(y.begin(), y.end(), y.begin(), ::tolower); break; default: y = x.substr(1); break; } std::string b("b" + y); std::string f("f" + y); std::string m("m" + y); switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str()); printf("Banana-fana fo-%s\n", f.c_str()); printf("Fee-fi-mo-%s\n", m.c_str()); printf("%s!\n\n", x.c_str()); } int main() { using namespace std; vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; for (auto& name : nameList) { printVerse(name); } return 0; }
Port the provided Ruby code into Java while preserving the original functionality.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
import java.util.stream.Stream; public class NameGame { private static void printVerse(String name) { StringBuilder sb = new StringBuilder(name.toLowerCase()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); String x = sb.toString(); String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1); String b = "b" + y; String f = "f" + y; String m = "m" + y; switch (x.charAt(0)) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } System.out.printf("%s, %s, bo-%s\n", x, x, b); System.out.printf("Banana-fana fo-%s\n", f); System.out.printf("Fee-fi-mo-%s\n", m); System.out.printf("%s!\n\n", x); } public static void main(String[] args) { Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse); } }
Generate a Java translation of this Ruby snippet without changing its computational steps.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
import java.util.stream.Stream; public class NameGame { private static void printVerse(String name) { StringBuilder sb = new StringBuilder(name.toLowerCase()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); String x = sb.toString(); String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1); String b = "b" + y; String f = "f" + y; String m = "m" + y; switch (x.charAt(0)) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } System.out.printf("%s, %s, bo-%s\n", x, x, b); System.out.printf("Banana-fana fo-%s\n", f); System.out.printf("Fee-fi-mo-%s\n", m); System.out.printf("%s!\n\n", x); } public static void main(String[] args) { Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse); } }
Convert this Ruby block to Python, preserving its control flow and logic.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
def print_verse(n): l = ['b', 'f', 'm'] s = n[1:] if str.lower(n[0]) in l: l[l.index(str.lower(n[0]))] = '' elif n[0] in ['A', 'E', 'I', 'O', 'U']: s = str.lower(n) print('{0}, {0}, bo-{2}{1}\nBanana-fana fo-{3}{1}\nFee-fi-mo-{4}{1}\n{0}!\n'.format(n, s, *l)) for n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']: print_verse(n)
Keep all operations the same but rewrite the snippet in Python.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
def print_verse(n): l = ['b', 'f', 'm'] s = n[1:] if str.lower(n[0]) in l: l[l.index(str.lower(n[0]))] = '' elif n[0] in ['A', 'E', 'I', 'O', 'U']: s = str.lower(n) print('{0}, {0}, bo-{2}{1}\nBanana-fana fo-{3}{1}\nFee-fi-mo-{4}{1}\n{0}!\n'.format(n, s, *l)) for n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']: print_verse(n)
Translate this program into VB but keep the logic exactly as in Ruby.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
Option Explicit Sub Main() Dim a, r, i As Integer Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^" a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank") r = TheGameName(a, SCHEM) For i = LBound(r) To UBound(r) Debug.Print r(i) Next i End Sub Private Function TheGameName(MyArr, S As String) As String() Dim i As Integer, s1 As String, s2 As String, tp As String, t() As String ReDim t(UBound(MyArr)) For i = LBound(MyArr) To UBound(MyArr) tp = Replace(S, "^", vbCrLf) s2 = LCase(Mid(MyArr(i), 2)): s1 = UCase(Left(MyArr(i), 1)) & s2 Select Case UCase(Left(MyArr(i), 1)) Case "A", "E", "I", "O", "U": tp = Replace(tp, "(Y)", LCase(MyArr(i))) Case "B", "F", "M" tp = Replace(tp, "(Y)", s2) tp = Replace(tp, LCase(MyArr(i)), s2) Case Else: tp = Replace(tp, "(Y)", s2) End Select t(i) = Replace(tp, "(X)", s1) Next TheGameName = t End Function
Port the following code from Ruby to VB with equivalent syntax and logic.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
Option Explicit Sub Main() Dim a, r, i As Integer Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^" a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank") r = TheGameName(a, SCHEM) For i = LBound(r) To UBound(r) Debug.Print r(i) Next i End Sub Private Function TheGameName(MyArr, S As String) As String() Dim i As Integer, s1 As String, s2 As String, tp As String, t() As String ReDim t(UBound(MyArr)) For i = LBound(MyArr) To UBound(MyArr) tp = Replace(S, "^", vbCrLf) s2 = LCase(Mid(MyArr(i), 2)): s1 = UCase(Left(MyArr(i), 1)) & s2 Select Case UCase(Left(MyArr(i), 1)) Case "A", "E", "I", "O", "U": tp = Replace(tp, "(Y)", LCase(MyArr(i))) Case "B", "F", "M" tp = Replace(tp, "(Y)", s2) tp = Replace(tp, LCase(MyArr(i)), s2) Case Else: tp = Replace(tp, "(Y)", s2) End Select t(i) = Replace(tp, "(X)", s1) Next TheGameName = t End Function
Write the same code in Go as shown below in Ruby.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
package main import ( "fmt" "strings" ) func printVerse(name string) { x := strings.Title(strings.ToLower(name)) y := x[1:] if strings.Contains("AEIOU", x[:1]) { y = strings.ToLower(x) } b := "b" + y f := "f" + y m := "m" + y switch x[0] { case 'B': b = y case 'F': f = y case 'M': m = y } fmt.Printf("%s, %s, bo-%s\n", x, x, b) fmt.Printf("Banana-fana fo-%s\n", f) fmt.Printf("Fee-fi-mo-%s\n", m) fmt.Printf("%s!\n\n", x) } func main() { names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} for _, name := range names { printVerse(name) } }
Produce a language-to-language conversion: from Ruby to Go, same semantics.
def print_verse(name) first_letter_and_consonants_re = /^.[^aeiyou]*/i full_name = name.capitalize suffixed = case full_name[0] when 'A','E','I','O','U' name.downcase else full_name.sub(first_letter_and_consonants_re, '') end b_name = "b f_name = "f m_name = "m case full_name[0] when 'B' b_name = suffixed when 'F' f_name = suffixed when 'M' m_name = suffixed end puts <<~END_VERSE Banana-fana fo- Fee-fi-mo- END_VERSE end %w[Gary Earl Billy Felix Mary Steve Chris Byron].each do |name| print_verse name end
package main import ( "fmt" "strings" ) func printVerse(name string) { x := strings.Title(strings.ToLower(name)) y := x[1:] if strings.Contains("AEIOU", x[:1]) { y = strings.ToLower(x) } b := "b" + y f := "f" + y m := "m" + y switch x[0] { case 'B': b = y case 'F': f = y case 'M': m = y } fmt.Printf("%s, %s, bo-%s\n", x, x, b) fmt.Printf("Banana-fana fo-%s\n", f) fmt.Printf("Fee-fi-mo-%s\n", m) fmt.Printf("%s!\n\n", x) } func main() { names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} for _, name := range names { printVerse(name) } }
Produce a language-to-language conversion: from Scala to C, same semantics.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
#include <stdio.h> #include <string.h> void print_verse(const char *name) { char *x, *y; int b = 1, f = 1, m = 1, i = 1; x = strdup(name); x[0] = toupper(x[0]); for (; x[i]; ++i) x[i] = tolower(x[i]); if (strchr("AEIOU", x[0])) { y = strdup(x); y[0] = tolower(y[0]); } else { y = x + 1; } switch(x[0]) { case 'B': b = 0; break; case 'F': f = 0; break; case 'M': m = 0; break; default : break; } printf("%s, %s, bo-%s%s\n", x, x, (b) ? "b" : "", y); printf("Banana-fana fo-%s%s\n", (f) ? "f" : "", y); printf("Fee-fi-mo-%s%s\n", (m) ? "m" : "", y); printf("%s!\n\n", x); } int main() { int i; const char *names[6] = {"gARY", "Earl", "Billy", "Felix", "Mary", "sHIRley"}; for (i = 0; i < 6; ++i) print_verse(names[i]); return 0; }
Convert the following code from Scala to C, ensuring the logic remains intact.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
#include <stdio.h> #include <string.h> void print_verse(const char *name) { char *x, *y; int b = 1, f = 1, m = 1, i = 1; x = strdup(name); x[0] = toupper(x[0]); for (; x[i]; ++i) x[i] = tolower(x[i]); if (strchr("AEIOU", x[0])) { y = strdup(x); y[0] = tolower(y[0]); } else { y = x + 1; } switch(x[0]) { case 'B': b = 0; break; case 'F': f = 0; break; case 'M': m = 0; break; default : break; } printf("%s, %s, bo-%s%s\n", x, x, (b) ? "b" : "", y); printf("Banana-fana fo-%s%s\n", (f) ? "f" : "", y); printf("Fee-fi-mo-%s%s\n", (m) ? "m" : "", y); printf("%s!\n\n", x); } int main() { int i; const char *names[6] = {"gARY", "Earl", "Billy", "Felix", "Mary", "sHIRley"}; for (i = 0; i < 6; ++i) print_verse(names[i]); return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Scala version.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
using System; using System.Collections.Generic; using System.Text; namespace TheNameGame { class Program { static void PrintVerse(string name) { StringBuilder sb = new StringBuilder(name.ToLower()); sb[0] = Char.ToUpper(sb[0]); string x = sb.ToString(); string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1); string b = "b" + y; string f = "f" + y; string m = "m" + y; switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; } Console.WriteLine("{0}, {0}, bo-{1}", x, b); Console.WriteLine("Banana-fana fo-{0}", f); Console.WriteLine("Fee-fi-mo-{0}", m); Console.WriteLine("{0}!", x); Console.WriteLine(); } static void Main(string[] args) { List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; nameList.ForEach(PrintVerse); } } }
Rewrite this program in C# while keeping its functionality equivalent to the Scala version.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
using System; using System.Collections.Generic; using System.Text; namespace TheNameGame { class Program { static void PrintVerse(string name) { StringBuilder sb = new StringBuilder(name.ToLower()); sb[0] = Char.ToUpper(sb[0]); string x = sb.ToString(); string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1); string b = "b" + y; string f = "f" + y; string m = "m" + y; switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; } Console.WriteLine("{0}, {0}, bo-{1}", x, b); Console.WriteLine("Banana-fana fo-{0}", f); Console.WriteLine("Fee-fi-mo-{0}", m); Console.WriteLine("{0}!", x); Console.WriteLine(); } static void Main(string[] args) { List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; nameList.ForEach(PrintVerse); } } }
Convert the following code from Scala to C++, ensuring the logic remains intact.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
#include <algorithm> #include <iostream> #include <string> #include <vector> static void printVerse(const std::string& name) { std::string x = name; std::transform(x.begin(), x.end(), x.begin(), ::tolower); x[0] = toupper(x[0]); std::string y; switch (x[0]) { case 'A': case 'E': case 'I': case 'O': case 'U': y = x; std::transform(y.begin(), y.end(), y.begin(), ::tolower); break; default: y = x.substr(1); break; } std::string b("b" + y); std::string f("f" + y); std::string m("m" + y); switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str()); printf("Banana-fana fo-%s\n", f.c_str()); printf("Fee-fi-mo-%s\n", m.c_str()); printf("%s!\n\n", x.c_str()); } int main() { using namespace std; vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; for (auto& name : nameList) { printVerse(name); } return 0; }
Translate the given Scala code snippet into C++ without altering its behavior.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
#include <algorithm> #include <iostream> #include <string> #include <vector> static void printVerse(const std::string& name) { std::string x = name; std::transform(x.begin(), x.end(), x.begin(), ::tolower); x[0] = toupper(x[0]); std::string y; switch (x[0]) { case 'A': case 'E': case 'I': case 'O': case 'U': y = x; std::transform(y.begin(), y.end(), y.begin(), ::tolower); break; default: y = x.substr(1); break; } std::string b("b" + y); std::string f("f" + y); std::string m("m" + y); switch (x[0]) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str()); printf("Banana-fana fo-%s\n", f.c_str()); printf("Fee-fi-mo-%s\n", m.c_str()); printf("%s!\n\n", x.c_str()); } int main() { using namespace std; vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }; for (auto& name : nameList) { printVerse(name); } return 0; }
Transform the following Scala implementation into Java, maintaining the same output and logic.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
import java.util.stream.Stream; public class NameGame { private static void printVerse(String name) { StringBuilder sb = new StringBuilder(name.toLowerCase()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); String x = sb.toString(); String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1); String b = "b" + y; String f = "f" + y; String m = "m" + y; switch (x.charAt(0)) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } System.out.printf("%s, %s, bo-%s\n", x, x, b); System.out.printf("Banana-fana fo-%s\n", f); System.out.printf("Fee-fi-mo-%s\n", m); System.out.printf("%s!\n\n", x); } public static void main(String[] args) { Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse); } }
Generate an equivalent Java version of this Scala code.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
import java.util.stream.Stream; public class NameGame { private static void printVerse(String name) { StringBuilder sb = new StringBuilder(name.toLowerCase()); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); String x = sb.toString(); String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1); String b = "b" + y; String f = "f" + y; String m = "m" + y; switch (x.charAt(0)) { case 'B': b = y; break; case 'F': f = y; break; case 'M': m = y; break; default: break; } System.out.printf("%s, %s, bo-%s\n", x, x, b); System.out.printf("Banana-fana fo-%s\n", f); System.out.printf("Fee-fi-mo-%s\n", m); System.out.printf("%s!\n\n", x); } public static void main(String[] args) { Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse); } }
Produce a language-to-language conversion: from Scala to Python, same semantics.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
def print_verse(n): l = ['b', 'f', 'm'] s = n[1:] if str.lower(n[0]) in l: l[l.index(str.lower(n[0]))] = '' elif n[0] in ['A', 'E', 'I', 'O', 'U']: s = str.lower(n) print('{0}, {0}, bo-{2}{1}\nBanana-fana fo-{3}{1}\nFee-fi-mo-{4}{1}\n{0}!\n'.format(n, s, *l)) for n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']: print_verse(n)
Please provide an equivalent version of this Scala code in Python.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
def print_verse(n): l = ['b', 'f', 'm'] s = n[1:] if str.lower(n[0]) in l: l[l.index(str.lower(n[0]))] = '' elif n[0] in ['A', 'E', 'I', 'O', 'U']: s = str.lower(n) print('{0}, {0}, bo-{2}{1}\nBanana-fana fo-{3}{1}\nFee-fi-mo-{4}{1}\n{0}!\n'.format(n, s, *l)) for n in ['Gary', 'Earl', 'Billy', 'Felix', 'Mary']: print_verse(n)
Translate the given Scala code snippet into VB without altering its behavior.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
Option Explicit Sub Main() Dim a, r, i As Integer Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^" a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank") r = TheGameName(a, SCHEM) For i = LBound(r) To UBound(r) Debug.Print r(i) Next i End Sub Private Function TheGameName(MyArr, S As String) As String() Dim i As Integer, s1 As String, s2 As String, tp As String, t() As String ReDim t(UBound(MyArr)) For i = LBound(MyArr) To UBound(MyArr) tp = Replace(S, "^", vbCrLf) s2 = LCase(Mid(MyArr(i), 2)): s1 = UCase(Left(MyArr(i), 1)) & s2 Select Case UCase(Left(MyArr(i), 1)) Case "A", "E", "I", "O", "U": tp = Replace(tp, "(Y)", LCase(MyArr(i))) Case "B", "F", "M" tp = Replace(tp, "(Y)", s2) tp = Replace(tp, LCase(MyArr(i)), s2) Case Else: tp = Replace(tp, "(Y)", s2) End Select t(i) = Replace(tp, "(X)", s1) Next TheGameName = t End Function
Convert this Scala snippet to VB and keep its semantics consistent.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
Option Explicit Sub Main() Dim a, r, i As Integer Const SCHEM As String = "(X), (X), bo-b(Y)^Banana-fana fo-f(Y)^Fee-fi-mo-m(Y)^(X)!^" a = Array("GaRY", "Earl", "Billy", "Felix", "Mary", "Mike", "Frank") r = TheGameName(a, SCHEM) For i = LBound(r) To UBound(r) Debug.Print r(i) Next i End Sub Private Function TheGameName(MyArr, S As String) As String() Dim i As Integer, s1 As String, s2 As String, tp As String, t() As String ReDim t(UBound(MyArr)) For i = LBound(MyArr) To UBound(MyArr) tp = Replace(S, "^", vbCrLf) s2 = LCase(Mid(MyArr(i), 2)): s1 = UCase(Left(MyArr(i), 1)) & s2 Select Case UCase(Left(MyArr(i), 1)) Case "A", "E", "I", "O", "U": tp = Replace(tp, "(Y)", LCase(MyArr(i))) Case "B", "F", "M" tp = Replace(tp, "(Y)", s2) tp = Replace(tp, LCase(MyArr(i)), s2) Case Else: tp = Replace(tp, "(Y)", s2) End Select t(i) = Replace(tp, "(X)", s1) Next TheGameName = t End Function
Rewrite this program in Go while keeping its functionality equivalent to the Scala version.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
package main import ( "fmt" "strings" ) func printVerse(name string) { x := strings.Title(strings.ToLower(name)) y := x[1:] if strings.Contains("AEIOU", x[:1]) { y = strings.ToLower(x) } b := "b" + y f := "f" + y m := "m" + y switch x[0] { case 'B': b = y case 'F': f = y case 'M': m = y } fmt.Printf("%s, %s, bo-%s\n", x, x, b) fmt.Printf("Banana-fana fo-%s\n", f) fmt.Printf("Fee-fi-mo-%s\n", m) fmt.Printf("%s!\n\n", x) } func main() { names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} for _, name := range names { printVerse(name) } }
Transform the following Scala implementation into Go, maintaining the same output and logic.
fun printVerse(name: String) { val x = name.toLowerCase().capitalize() val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) var b = "b$y" var f = "f$y" var m = "m$y" when (x[0]) { 'B' -> b = "$y" 'F' -> f = "$y" 'M' -> m = "$y" else -> {} } println("$x, $x, bo-$b") println("Banana-fana fo-$f") println("Fee-fi-mo-$m") println("$x!\n") } fun main(args: Array<String>) { listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } }
package main import ( "fmt" "strings" ) func printVerse(name string) { x := strings.Title(strings.ToLower(name)) y := x[1:] if strings.Contains("AEIOU", x[:1]) { y = strings.ToLower(x) } b := "b" + y f := "f" + y m := "m" + y switch x[0] { case 'B': b = y case 'F': f = y case 'M': m = y } fmt.Printf("%s, %s, bo-%s\n", x, x, b) fmt.Printf("Banana-fana fo-%s\n", f) fmt.Printf("Fee-fi-mo-%s\n", m) fmt.Printf("%s!\n\n", x) } func main() { names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} for _, name := range names { printVerse(name) } }
Change the following Ada code into C# without altering its purpose.
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets; use GNAT.Sockets; procedure DNSQuerying is Host : Host_Entry_Type (1, 1); Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); begin Host := Get_Host_By_Name (Name => "www.kame.net"); Inet_Addr_V4 := Addresses (Host); Put ("IPv4: " & Image (Value => Inet_Addr_V4)); end DNSQuerying;
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Translate the given Ada code snippet into C without altering its behavior.
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets; use GNAT.Sockets; procedure DNSQuerying is Host : Host_Entry_Type (1, 1); Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); begin Host := Get_Host_By_Name (Name => "www.kame.net"); Inet_Addr_V4 := Addresses (Host); Put ("IPv4: " & Image (Value => Inet_Addr_V4)); end DNSQuerying;
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Produce a functionally identical C++ code for the snippet given in Ada.
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets; use GNAT.Sockets; procedure DNSQuerying is Host : Host_Entry_Type (1, 1); Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); begin Host := Get_Host_By_Name (Name => "www.kame.net"); Inet_Addr_V4 := Addresses (Host); Put ("IPv4: " & Image (Value => Inet_Addr_V4)); end DNSQuerying;
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Ensure the translated Go code behaves exactly like the original Ada snippet.
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets; use GNAT.Sockets; procedure DNSQuerying is Host : Host_Entry_Type (1, 1); Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); begin Host := Get_Host_By_Name (Name => "www.kame.net"); Inet_Addr_V4 := Addresses (Host); Put ("IPv4: " & Image (Value => Inet_Addr_V4)); end DNSQuerying;
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Rewrite the snippet below in Java so it works the same as the original Ada code.
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets; use GNAT.Sockets; procedure DNSQuerying is Host : Host_Entry_Type (1, 1); Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); begin Host := Get_Host_By_Name (Name => "www.kame.net"); Inet_Addr_V4 := Addresses (Host); Put ("IPv4: " & Image (Value => Inet_Addr_V4)); end DNSQuerying;
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Change the following Ada code into Python without altering its purpose.
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets; use GNAT.Sockets; procedure DNSQuerying is Host : Host_Entry_Type (1, 1); Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); begin Host := Get_Host_By_Name (Name => "www.kame.net"); Inet_Addr_V4 := Addresses (Host); Put ("IPv4: " & Image (Value => Inet_Addr_V4)); end DNSQuerying;
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Preserve the algorithm and functionality while converting the code from Ada to VB.
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Sockets; use GNAT.Sockets; procedure DNSQuerying is Host : Host_Entry_Type (1, 1); Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); begin Host := Get_Host_By_Name (Name => "www.kame.net"); Inet_Addr_V4 := Addresses (Host); Put ("IPv4: " & Image (Value => Inet_Addr_V4)); end DNSQuerying;
Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine If r.Test(line) Then WScript.StdOut.WriteLine "IP Version " &_ ver & ": " & r.Replace(line,"$1") End If Loop End Function Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
Ensure the translated C code behaves exactly like the original AutoHotKey snippet.
Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide FileRead, Contents, %LogFile% FileDelete, %LogFile% RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Translate this program into C# but keep the logic exactly as in AutoHotKey.
Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide FileRead, Contents, %LogFile% FileDelete, %LogFile% RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Keep all operations the same but rewrite the snippet in C++.
Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide FileRead, Contents, %LogFile% FileDelete, %LogFile% RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Translate this program into Java but keep the logic exactly as in AutoHotKey.
Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide FileRead, Contents, %LogFile% FileDelete, %LogFile% RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Change the programming language of this snippet from AutoHotKey to Python without modifying what it does.
Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide FileRead, Contents, %LogFile% FileDelete, %LogFile% RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Keep all operations the same but rewrite the snippet in VB.
Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide FileRead, Contents, %LogFile% FileDelete, %LogFile% RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
Convert this AutoHotKey block to Go, preserving its control flow and logic.
Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log" Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide FileRead, Contents, %LogFile% FileDelete, %LogFile% RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match) MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Transform the following BBC_Basic implementation into C, maintaining the same output and logic.
name$ = "www.kame.net" AF_INET = 2 AF_INET6 = 23 WSASYS_STATUS_LEN = 128 WSADESCRIPTION_LEN = 256 SYS "LoadLibrary", "WS2_32.DLL" TO ws2% SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup` SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup` SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo` DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \ \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \ \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%} DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \ \ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%} DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{} DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)} DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \ \ sin6_addr&(15), sin6_scope_id%} SYS `WSAStartup`, &202, WSAdata{} TO res% IF res% ERROR 102, "WSAStartup failed" addrinfo.ai_family% = AF_INET SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res% IF res% ERROR 103, "getaddrinfo failed" !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr% PRINT "IPv4 address = " ; PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ; PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3) addrinfo.ai_family% = AF_INET6 SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res% IF res% ERROR 104, "getaddrinfo failed" !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr% PRINT "IPv6 address = " ; PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15) SYS `WSACleanup`
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Generate a C# translation of this BBC_Basic snippet without changing its computational steps.
name$ = "www.kame.net" AF_INET = 2 AF_INET6 = 23 WSASYS_STATUS_LEN = 128 WSADESCRIPTION_LEN = 256 SYS "LoadLibrary", "WS2_32.DLL" TO ws2% SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup` SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup` SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo` DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \ \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \ \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%} DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \ \ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%} DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{} DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)} DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \ \ sin6_addr&(15), sin6_scope_id%} SYS `WSAStartup`, &202, WSAdata{} TO res% IF res% ERROR 102, "WSAStartup failed" addrinfo.ai_family% = AF_INET SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res% IF res% ERROR 103, "getaddrinfo failed" !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr% PRINT "IPv4 address = " ; PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ; PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3) addrinfo.ai_family% = AF_INET6 SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res% IF res% ERROR 104, "getaddrinfo failed" !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr% PRINT "IPv6 address = " ; PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15) SYS `WSACleanup`
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Maintain the same structure and functionality when rewriting this code in C++.
name$ = "www.kame.net" AF_INET = 2 AF_INET6 = 23 WSASYS_STATUS_LEN = 128 WSADESCRIPTION_LEN = 256 SYS "LoadLibrary", "WS2_32.DLL" TO ws2% SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup` SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup` SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo` DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \ \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \ \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%} DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \ \ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%} DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{} DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)} DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \ \ sin6_addr&(15), sin6_scope_id%} SYS `WSAStartup`, &202, WSAdata{} TO res% IF res% ERROR 102, "WSAStartup failed" addrinfo.ai_family% = AF_INET SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res% IF res% ERROR 103, "getaddrinfo failed" !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr% PRINT "IPv4 address = " ; PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ; PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3) addrinfo.ai_family% = AF_INET6 SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res% IF res% ERROR 104, "getaddrinfo failed" !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr% PRINT "IPv6 address = " ; PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15) SYS `WSACleanup`
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Produce a language-to-language conversion: from BBC_Basic to Java, same semantics.
name$ = "www.kame.net" AF_INET = 2 AF_INET6 = 23 WSASYS_STATUS_LEN = 128 WSADESCRIPTION_LEN = 256 SYS "LoadLibrary", "WS2_32.DLL" TO ws2% SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup` SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup` SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo` DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \ \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \ \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%} DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \ \ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%} DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{} DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)} DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \ \ sin6_addr&(15), sin6_scope_id%} SYS `WSAStartup`, &202, WSAdata{} TO res% IF res% ERROR 102, "WSAStartup failed" addrinfo.ai_family% = AF_INET SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res% IF res% ERROR 103, "getaddrinfo failed" !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr% PRINT "IPv4 address = " ; PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ; PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3) addrinfo.ai_family% = AF_INET6 SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res% IF res% ERROR 104, "getaddrinfo failed" !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr% PRINT "IPv6 address = " ; PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15) SYS `WSACleanup`
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Ensure the translated Python code behaves exactly like the original BBC_Basic snippet.
name$ = "www.kame.net" AF_INET = 2 AF_INET6 = 23 WSASYS_STATUS_LEN = 128 WSADESCRIPTION_LEN = 256 SYS "LoadLibrary", "WS2_32.DLL" TO ws2% SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup` SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup` SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo` DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \ \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \ \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%} DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \ \ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%} DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{} DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)} DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \ \ sin6_addr&(15), sin6_scope_id%} SYS `WSAStartup`, &202, WSAdata{} TO res% IF res% ERROR 102, "WSAStartup failed" addrinfo.ai_family% = AF_INET SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res% IF res% ERROR 103, "getaddrinfo failed" !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr% PRINT "IPv4 address = " ; PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ; PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3) addrinfo.ai_family% = AF_INET6 SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res% IF res% ERROR 104, "getaddrinfo failed" !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr% PRINT "IPv6 address = " ; PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15) SYS `WSACleanup`
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Convert the following code from BBC_Basic to VB, ensuring the logic remains intact.
name$ = "www.kame.net" AF_INET = 2 AF_INET6 = 23 WSASYS_STATUS_LEN = 128 WSADESCRIPTION_LEN = 256 SYS "LoadLibrary", "WS2_32.DLL" TO ws2% SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup` SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup` SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo` DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \ \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \ \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%} DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \ \ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%} DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{} DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)} DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \ \ sin6_addr&(15), sin6_scope_id%} SYS `WSAStartup`, &202, WSAdata{} TO res% IF res% ERROR 102, "WSAStartup failed" addrinfo.ai_family% = AF_INET SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res% IF res% ERROR 103, "getaddrinfo failed" !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr% PRINT "IPv4 address = " ; PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ; PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3) addrinfo.ai_family% = AF_INET6 SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res% IF res% ERROR 104, "getaddrinfo failed" !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr% PRINT "IPv6 address = " ; PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15) SYS `WSACleanup`
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
Port the provided BBC_Basic code into Go while preserving the original functionality.
name$ = "www.kame.net" AF_INET = 2 AF_INET6 = 23 WSASYS_STATUS_LEN = 128 WSADESCRIPTION_LEN = 256 SYS "LoadLibrary", "WS2_32.DLL" TO ws2% SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup` SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup` SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo` DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \ \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \ \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%} DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \ \ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%} DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{} DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)} DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \ \ sin6_addr&(15), sin6_scope_id%} SYS `WSAStartup`, &202, WSAdata{} TO res% IF res% ERROR 102, "WSAStartup failed" addrinfo.ai_family% = AF_INET SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res% IF res% ERROR 103, "getaddrinfo failed" !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr% PRINT "IPv4 address = " ; PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ; PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3) addrinfo.ai_family% = AF_INET6 SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res% IF res% ERROR 104, "getaddrinfo failed" !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr% PRINT "IPv6 address = " ; PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ; PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15) SYS `WSACleanup`
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Port the provided Clojure code into C while preserving the original functionality.
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address) (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Write a version of this Clojure function in C# with identical behavior.
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address) (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Translate the given Clojure code snippet into C++ without altering its behavior.
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address) (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Translate the given Clojure code snippet into Java without altering its behavior.
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address) (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Port the following code from Clojure to Python with equivalent syntax and logic.
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address) (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Write the same code in VB as shown below in Clojure.
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address) (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
Write the same algorithm in Go as shown in this Clojure implementation.
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address) (doseq [addr (InetAddress/getAllByName "www.kame.net")] (cond (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr)) (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Produce a language-to-language conversion: from Common_Lisp to C, same semantics.
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Transform the following Common_Lisp implementation into C#, maintaining the same output and logic.
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Port the provided Common_Lisp code into C++ while preserving the original functionality.
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Generate a Java translation of this Common_Lisp snippet without changing its computational steps.
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Rewrite this program in Python while keeping its functionality equivalent to the Common_Lisp version.
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Write the same code in VB as shown below in Common_Lisp.
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
Keep all operations the same but rewrite the snippet in Go.
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Please provide an equivalent version of this D code in C.
import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Can you help me rewrite this code in C# instead of D, keeping it the same logically?
import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Generate a C++ translation of this D snippet without changing its computational steps.
import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Convert this D snippet to Java and keep its semantics consistent.
import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Write a version of this D function in Python with identical behavior.
import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Rewrite the snippet below in VB so it works the same as the original D code.
import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
Produce a language-to-language conversion: from D to Go, same semantics.
import std.stdio, std.socket; void main() { auto domain = "www.kame.net", port = "80"; auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address); a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Change the programming language of this snippet from Delphi to C without modifying what it does.
program DNSQuerying; uses IdGlobal, IdStackWindows; const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Generate an equivalent C# version of this Delphi code.
program DNSQuerying; uses IdGlobal, IdStackWindows; const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Transform the following Delphi implementation into C++, maintaining the same output and logic.
program DNSQuerying; uses IdGlobal, IdStackWindows; const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Generate an equivalent Java version of this Delphi code.
program DNSQuerying; uses IdGlobal, IdStackWindows; const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Generate an equivalent Python version of this Delphi code.
program DNSQuerying; uses IdGlobal, IdStackWindows; const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Change the programming language of this snippet from Delphi to VB without modifying what it does.
program DNSQuerying; uses IdGlobal, IdStackWindows; const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
Maintain the same structure and functionality when rewriting this code in Go.
program DNSQuerying; uses IdGlobal, IdStackWindows; const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Translate this program into C but keep the logic exactly as in Erlang.
33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Convert this Erlang block to C#, preserving its control flow and logic.
33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Port the following code from Erlang to C++ with equivalent syntax and logic.
33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Write the same code in Java as shown below in Erlang.
33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }
Convert the following code from Erlang to Python, ensuring the logic remains intact.
33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
Translate this program into VB but keep the logic exactly as in Erlang.
33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]
#include "win\winsock2.bi" Function GetSiteAddress(stuff As String = "www.freebasic.net") As Long Dim As WSADATA _wsadate Dim As in_addr addr Dim As hostent Ptr res Dim As Integer i = 0 WSAStartup(MAKEWORD(2,2),@_wsadate) res = gethostbyname(stuff) If res Then Print !"\nURL: "; stuff While (res->h_addr_list[i] <> 0) addr.s_addr = *(Cast (Ulong Ptr,res->h_addr_list[i])) Print "IPv4 address: ";*inet_ntoa(addr) i+=1 Wend WSACleanup() Return 1 Else Print "website error?" Return 0 End If End Function GetSiteAddress "rosettacode.org" GetSiteAddress "www.kame.net" Sleep
Change the following Erlang code into Go without altering its purpose.
33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
Rewrite the snippet below in C so it works the same as the original Factor code.
USING: dns io kernel sequences ; "www.kame.net" [ dns-A-query ] [ dns-AAAA-query ] bi [ message>names second print ] bi@
#include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo("www.kame.net", NULL, &hints, &res0); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); exit(1); } for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (error) { fprintf(stderr, "%s\n", gai_strerror(error)); } else { printf("%s\n", host); } } freeaddrinfo(res0); return 0; }
Rewrite this program in C# while keeping its functionality equivalent to the Factor version.
USING: dns io kernel sequences ; "www.kame.net" [ dns-A-query ] [ dns-AAAA-query ] bi [ message>names second print ] bi@
private string LookupDns(string s) { try { System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s); string result = ip.AddressList[0].ToString(); for (int i = 1; i < ip.AddressList.Length; ++i) result += ", " + ip.AddressList[i].ToString(); return result; } catch (System.Net.Sockets.SocketException se) { return se.Message; } }
Convert the following code from Factor to C++, ensuring the logic remains intact.
USING: dns io kernel sequences ; "www.kame.net" [ dns-A-query ] [ dns-AAAA-query ] bi [ message>names second print ] bi@
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Transform the following Factor implementation into Java, maintaining the same output and logic.
USING: dns io kernel sequences ; "www.kame.net" [ dns-A-query ] [ dns-AAAA-query ] bi [ message>names second print ] bi@
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException; class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }