Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Convert the following code from Delphi to Go, ensuring the logic remains intact. | program Walk_a_directory;
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory;
Files := TDirectory.GetFiles(Directory, '*.*', TSearchOption.soAllDirectories);
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Keep all operations the same but rewrite the snippet in C. | defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
IO.puts fname = "
if File.dir?(fname), do: recursive(fname)
end)
end
end
Walk_directory.recursive
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
IO.puts fname = "
if File.dir?(fname), do: recursive(fname)
end)
end
end
Walk_directory.recursive
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Produce a language-to-language conversion: from Elixir to C++, same semantics. | defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
IO.puts fname = "
if File.dir?(fname), do: recursive(fname)
end)
end
end
Walk_directory.recursive
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Port the following code from Elixir to Java with equivalent syntax and logic. | defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
IO.puts fname = "
if File.dir?(fname), do: recursive(fname)
end)
end
end
Walk_directory.recursive
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Generate a Python translation of this Elixir snippet without changing its computational steps. | defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
IO.puts fname = "
if File.dir?(fname), do: recursive(fname)
end)
end
end
Walk_directory.recursive
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Translate this program into VB but keep the logic exactly as in Elixir. | defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
IO.puts fname = "
if File.dir?(fname), do: recursive(fname)
end)
end
end
Walk_directory.recursive
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Write the same algorithm in Go as shown in this Elixir implementation. | defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
IO.puts fname = "
if File.dir?(fname), do: recursive(fname)
end)
end
end
Walk_directory.recursive
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Transform the following Erlang implementation into C, maintaining the same output and logic. | walk_dir(Path, Pattern) ->
filelib:fold_files(
Path,
Pattern,
true,
fun(File, Accumulator) -> [File|Accumulator] end,
[]
)
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Erlang to C#. | walk_dir(Path, Pattern) ->
filelib:fold_files(
Path,
Pattern,
true,
fun(File, Accumulator) -> [File|Accumulator] end,
[]
)
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Preserve the algorithm and functionality while converting the code from Erlang to C++. | walk_dir(Path, Pattern) ->
filelib:fold_files(
Path,
Pattern,
true,
fun(File, Accumulator) -> [File|Accumulator] end,
[]
)
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Port the provided Erlang code into Java while preserving the original functionality. | walk_dir(Path, Pattern) ->
filelib:fold_files(
Path,
Pattern,
true,
fun(File, Accumulator) -> [File|Accumulator] end,
[]
)
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Write a version of this Erlang function in Python with identical behavior. | walk_dir(Path, Pattern) ->
filelib:fold_files(
Path,
Pattern,
true,
fun(File, Accumulator) -> [File|Accumulator] end,
[]
)
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Produce a functionally identical VB code for the snippet given in Erlang. | walk_dir(Path, Pattern) ->
filelib:fold_files(
Path,
Pattern,
true,
fun(File, Accumulator) -> [File|Accumulator] end,
[]
)
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Transform the following Erlang implementation into Go, maintaining the same output and logic. | walk_dir(Path, Pattern) ->
filelib:fold_files(
Path,
Pattern,
true,
fun(File, Accumulator) -> [File|Accumulator] end,
[]
)
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Write a version of this F# function in C with identical behavior. | open System.IO
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Transform the following F# implementation into C#, maintaining the same output and logic. | open System.IO
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Convert this F# block to C++, preserving its control flow and logic. | open System.IO
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Can you help me rewrite this code in Java instead of F#, keeping it the same logically? | open System.IO
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Generate an equivalent Python version of this F# code. | open System.IO
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Produce a language-to-language conversion: from F# to VB, same semantics. | open System.IO
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Translate the given F# code snippet into Go without altering its behavior. | open System.IO
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Produce a language-to-language conversion: from Factor to C, same semantics. | USE: io.directories.search
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Write a version of this Factor function in C# with identical behavior. | USE: io.directories.search
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Can you help me rewrite this code in C++ instead of Factor, keeping it the same logically? | USE: io.directories.search
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Generate an equivalent Java version of this Factor code. | USE: io.directories.search
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Port the following code from Factor to Python with equivalent syntax and logic. | USE: io.directories.search
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Convert this Factor snippet to VB and keep its semantics consistent. | USE: io.directories.search
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Please provide an equivalent version of this Factor code in Go. | USE: io.directories.search
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Rewrite this program in C while keeping its functionality equivalent to the Forth version. | "*.c" f:rglob
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Generate a C# translation of this Forth snippet without changing its computational steps. | "*.c" f:rglob
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Change the programming language of this snippet from Forth to C++ without modifying what it does. | "*.c" f:rglob
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Convert this Forth block to Java, preserving its control flow and logic. | "*.c" f:rglob
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Write the same code in VB as shown below in Forth. | "*.c" f:rglob
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Produce a functionally identical Go code for the snippet given in Forth. | "*.c" f:rglob
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Ensure the translated C code behaves exactly like the original Groovy snippet. | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Translate this program into C# but keep the logic exactly as in Groovy. | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Port the provided Groovy code into C++ while preserving the original functionality. | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Change the programming language of this snippet from Groovy to Java without modifying what it does. | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Write the same code in VB as shown below in Groovy. | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Translate this program into Go but keep the logic exactly as in Groovy. | new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Translate the given Haskell code snippet into C without altering its behavior. | import System.Environment
import System.Directory
import System.FilePath.Find
search pat = find always (fileName ~~? pat)
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Translate this program into C# but keep the logic exactly as in Haskell. | import System.Environment
import System.Directory
import System.FilePath.Find
search pat = find always (fileName ~~? pat)
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Convert this Haskell block to C++, preserving its control flow and logic. | import System.Environment
import System.Directory
import System.FilePath.Find
search pat = find always (fileName ~~? pat)
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Produce a functionally identical Java code for the snippet given in Haskell. | import System.Environment
import System.Directory
import System.FilePath.Find
search pat = find always (fileName ~~? pat)
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Write the same code in Python as shown below in Haskell. | import System.Environment
import System.Directory
import System.FilePath.Find
search pat = find always (fileName ~~? pat)
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Generate a VB translation of this Haskell snippet without changing its computational steps. | import System.Environment
import System.Directory
import System.FilePath.Find
search pat = find always (fileName ~~? pat)
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Ensure the translated Go code behaves exactly like the original Haskell snippet. | import System.Environment
import System.Directory
import System.FilePath.Find
search pat = find always (fileName ~~? pat)
main = do
[pat] <- getArgs
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Can you help me rewrite this code in C instead of J, keeping it the same logically? | require 'dir'
>{."1 dirtree '*.html'
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Generate a C# translation of this J snippet without changing its computational steps. | require 'dir'
>{."1 dirtree '*.html'
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Change the programming language of this snippet from J to C++ without modifying what it does. | require 'dir'
>{."1 dirtree '*.html'
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Convert this J snippet to Java and keep its semantics consistent. | require 'dir'
>{."1 dirtree '*.html'
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Convert this J block to Python, preserving its control flow and logic. | require 'dir'
>{."1 dirtree '*.html'
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Write the same algorithm in VB as shown in this J implementation. | require 'dir'
>{."1 dirtree '*.html'
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Transform the following J implementation into Go, maintaining the same output and logic. | require 'dir'
>{."1 dirtree '*.html'
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Port the provided Julia code into C while preserving the original functionality. | rootpath = "/home/user/music"
pattern = r".mp3$"
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Can you help me rewrite this code in C# instead of Julia, keeping it the same logically? | rootpath = "/home/user/music"
pattern = r".mp3$"
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Write a version of this Julia function in C++ with identical behavior. | rootpath = "/home/user/music"
pattern = r".mp3$"
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Produce a functionally identical Java code for the snippet given in Julia. | rootpath = "/home/user/music"
pattern = r".mp3$"
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | rootpath = "/home/user/music"
pattern = r".mp3$"
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Port the following code from Julia to VB with equivalent syntax and logic. | rootpath = "/home/user/music"
pattern = r".mp3$"
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Can you help me rewrite this code in Go instead of Julia, keeping it the same logically? | rootpath = "/home/user/music"
pattern = r".mp3$"
for (root, dirs, files) in walkdir(rootpath)
for file in files
if occursin(pattern, file) println(file) end
end
end
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Convert the following code from Lua to C, ensuring the logic remains intact. | local lfs = require("lfs")
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
for f in find("directory") do
print(f)
end
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Translate this program into C# but keep the logic exactly as in Lua. | local lfs = require("lfs")
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
for f in find("directory") do
print(f)
end
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Write the same algorithm in C++ as shown in this Lua implementation. | local lfs = require("lfs")
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
for f in find("directory") do
print(f)
end
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Change the programming language of this snippet from Lua to Java without modifying what it does. | local lfs = require("lfs")
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
for f in find("directory") do
print(f)
end
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Write the same code in Python as shown below in Lua. | local lfs = require("lfs")
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
for f in find("directory") do
print(f)
end
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Generate a VB translation of this Lua snippet without changing its computational steps. | local lfs = require("lfs")
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
for f in find("directory") do
print(f)
end
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Preserve the algorithm and functionality while converting the code from Lua to Go. | local lfs = require("lfs")
function find(self, fn)
return coroutine.wrap(function()
for f in lfs.dir(self) do
if f ~= "." and f ~= ".." then
local _f = self .. "/" .. f
if not fn or fn(_f) then
coroutine.yield(_f)
end
if lfs.attributes(_f, "mode") == "directory" then
for n in find(_f, fn) do
coroutine.yield(n)
end
end
end
end
end)
end
for f in find("directory") do
print(f)
end
for f in find("directory", function(self) return self:match("%.lua$") end) do
print(f)
end
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Preserve the algorithm and functionality while converting the code from Mathematica to C. | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Translate this program into C# but keep the logic exactly as in Mathematica. | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Ensure the translated C++ code behaves exactly like the original Mathematica snippet. | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Change the following Mathematica code into Java without altering its purpose. | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Port the provided Mathematica code into Python while preserving the original functionality. | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Port the following code from Mathematica to VB with equivalent syntax and logic. | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Keep all operations the same but rewrite the snippet in Go. | FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Translate the given MATLAB code snippet into C without altering its behavior. | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end;
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original MATLAB code. | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end;
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Produce a functionally identical C++ code for the snippet given in MATLAB. | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end;
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Translate this program into Java but keep the logic exactly as in MATLAB. | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end;
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Write a version of this MATLAB function in Python with identical behavior. | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end;
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Convert the following code from MATLAB to VB, ensuring the logic remains intact. | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end;
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Produce a functionally identical Go code for the snippet given in MATLAB. | function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
fprintf('
end;
f = dir(d);
n = find([f.isdir]);
for k=n(:)'
if any(f(k).name~='.')
walk_a_directory_recursively(fullfile(d,f(k).name), pattern);
end;
end;
end;
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Change the programming language of this snippet from Nim to C without modifying what it does. | import os, re
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Write a version of this Nim function in C# with identical behavior. | import os, re
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Port the provided Nim code into C++ while preserving the original functionality. | import os, re
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Transform the following Nim implementation into Java, maintaining the same output and logic. | import os, re
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Nim version. | import os, re
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Produce a language-to-language conversion: from Nim to VB, same semantics. | import os, re
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Change the programming language of this snippet from Nim to Go without modifying what it does. | import os, re
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Generate an equivalent C version of this OCaml code. | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files)
| S_DIR -> (f::dirs, files)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Can you help me rewrite this code in C# instead of OCaml, keeping it the same logically? | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files)
| S_DIR -> (f::dirs, files)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Write a version of this OCaml function in C++ with identical behavior. | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files)
| S_DIR -> (f::dirs, files)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the OCaml version. | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files)
| S_DIR -> (f::dirs, files)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;
| import java.io.File;
public class MainEntry {
public static void main(String[] args) {
walkin(new File("/home/user"));
}
public static void walkin(File dir) {
String pattern = ".mp3";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i=0; i<listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if (listFile[i].getName().endsWith(pattern)) {
System.out.println(listFile[i].getPath());
}
}
}
}
}
}
|
Produce a functionally identical Python code for the snippet given in OCaml. | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files)
| S_DIR -> (f::dirs, files)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;
| from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
|
Write the same code in VB as shown below in OCaml. | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files)
| S_DIR -> (f::dirs, files)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;
| Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
printFiles(parentDir.Item(i), pattern)
Else
Dim rg as New RegEx
Dim myMatch as RegExMatch
rg.SearchPattern = pattern
myMatch = rg.search(parentDir.Item(i).Name)
If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
End If
Next
End Sub
|
Convert this OCaml block to Go, preserving its control flow and logic. | #!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
open Unix
let walk_directory_tree dir pattern =
let re = Str.regexp pattern in
let select str = Str.string_match re str 0 in
let rec walk acc = function
| [] -> (acc)
| dir::tail ->
let contents = Array.to_list (Sys.readdir dir) in
let contents = List.rev_map (Filename.concat dir) contents in
let dirs, files =
List.fold_left (fun (dirs,files) f ->
match (stat f).st_kind with
| S_REG -> (dirs, f::files)
| S_DIR -> (f::dirs, files)
| _ -> (dirs, files)
) ([],[]) contents
in
let matched = List.filter (select) files in
walk (matched @ acc) (dirs @ tail)
in
walk [] [dir]
;;
let () =
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;
| package main
import (
"fmt"
"os"
"path/filepath"
)
func VisitFile(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
matched, err := filepath.Match("*.mp3", fi.Name())
if err != nil {
fmt.Println(err)
return err
}
if matched {
fmt.Println(fp)
}
return nil
}
func main() {
filepath.Walk("/", VisitFile)
}
|
Translate the given Perl code snippet into C without altering its behavior. | use File::Find qw(find);
my $dir = '.';
my $pattern = 'foo';
my $callback = sub { print $File::Find::name, "\n" if /$pattern/ };
find $callback, $dir;
| #include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <err.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_NAMETOOLONG,
WALK_BADIO,
};
#define WS_NONE 0
#define WS_RECURSIVE (1 << 0)
#define WS_DEFAULT WS_RECURSIVE
#define WS_FOLLOWLINK (1 << 1)
#define WS_DOTFILES (1 << 2)
#define WS_MATCHDIRS (1 << 3)
int walk_recur(char *dname, regex_t *reg, int spec)
{
struct dirent *dent;
DIR *dir;
struct stat st;
char fn[FILENAME_MAX];
int res = WALK_OK;
int len = strlen(dname);
if (len >= FILENAME_MAX - 1)
return WALK_NAMETOOLONG;
strcpy(fn, dname);
fn[len++] = '/';
if (!(dir = opendir(dname))) {
warn("can't open %s", dname);
return WALK_BADIO;
}
errno = 0;
while ((dent = readdir(dir))) {
if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.')
continue;
if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
continue;
strncpy(fn + len, dent->d_name, FILENAME_MAX - len);
if (lstat(fn, &st) == -1) {
warn("Can't stat %s", fn);
res = WALK_BADIO;
continue;
}
if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK))
continue;
if (S_ISDIR(st.st_mode)) {
if ((spec & WS_RECURSIVE))
walk_recur(fn, reg, spec);
if (!(spec & WS_MATCHDIRS)) continue;
}
if (!regexec(reg, fn, 0, 0, 0)) puts(fn);
}
if (dir) closedir(dir);
return res ? res : errno ? WALK_BADIO : WALK_OK;
}
int walk_dir(char *dname, char *pattern, int spec)
{
regex_t r;
int res;
if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
res = walk_recur(dname, &r, spec);
regfree(&r);
return res;
}
int main()
{
int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS);
switch(r) {
case WALK_OK: break;
case WALK_BADIO: err(1, "IO error");
case WALK_BADPATTERN: err(1, "Bad pattern");
case WALK_NAMETOOLONG: err(1, "Filename too long");
default:
err(1, "Unknown error?");
}
return 0;
}
|
Write the same algorithm in C# as shown in this Perl implementation. | use File::Find qw(find);
my $dir = '.';
my $pattern = 'foo';
my $callback = sub { print $File::Find::name, "\n" if /$pattern/ };
find $callback, $dir;
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RosettaRecursiveDirectory
{
class Program
{
static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern)
{
var directoryStack = new Stack<DirectoryInfo>();
directoryStack.Push(new DirectoryInfo(rootPath));
while (directoryStack.Count > 0)
{
var dir = directoryStack.Pop();
try
{
foreach (var i in dir.GetDirectories())
directoryStack.Push(i);
}
catch (UnauthorizedAccessException) {
continue;
}
foreach (var f in dir.GetFiles().Where(Pattern))
yield return f;
}
}
static void Main(string[] args)
{
foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv"))
Console.WriteLine(file.FullName);
Console.WriteLine("Done.");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.