WeixiangYan/CodeTransOcean huggingface dataset:
Task: Take notes on the command line



C#: using System;
using System.IO;
using System.Text;

namespace RosettaCode
{
  internal class Program
  {
    private const string FileName = "NOTES.TXT";

    private static void Main(string[] args)
    {
      if (args.Length==0)
      {
        string txt = File.ReadAllText(FileName);
        Console.WriteLine(txt);
      }
      else
      {
        var sb = new StringBuilder();
        sb.Append(DateTime.Now).Append("\n\t");
        foreach (string s in args)
          sb.Append(s).Append(" ");
        sb.Append("\n");

        if (File.Exists(FileName))
          File.AppendAllText(FileName, sb.ToString());
        else
          File.WriteAllText(FileName, sb.ToString());
      }
    }
  }
}



Java: import java.io.*;
import java.nio.channels.*;
import java.util.Date;

public class TakeNotes {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
            ps.println(new Date());
            ps.print("\t" + args[0]);
            for (int i = 1; i < args.length; i++)
                ps.print(" " + args[i]);
            ps.println();
            ps.close();
        } else {
            FileChannel fc = new FileInputStream("notes.txt").getChannel();
            fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
            fc.close();
        }
    }
}
Task: Find common directory path



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RosettaCodeTasks
{

	class Program
	{
		static void Main ( string[ ] args )
		{
			FindCommonDirectoryPath.Test ( );
		}

	}

	class FindCommonDirectoryPath
	{
		public static void Test ( )
		{
			Console.WriteLine ( "Find Common Directory Path" );
			Console.WriteLine ( );
			List<string> PathSet1 = new List<string> ( );
			PathSet1.Add ( "/home/user1/tmp/coverage/test" );
			PathSet1.Add ( "/home/user1/tmp/covert/operator" );
			PathSet1.Add ( "/home/user1/tmp/coven/members" );
			Console.WriteLine("Path Set 1 (All Absolute Paths):");
			foreach ( string path in PathSet1 )
			{
				Console.WriteLine ( path );
			}
			Console.WriteLine ( "Path Set 1 Common Path: {0}", FindCommonPath ( "/", PathSet1 ) );
		}
		public static string FindCommonPath ( string Separator, List<string> Paths )
		{
			string CommonPath = String.Empty;
			List<string> SeparatedPath = Paths
				.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )
				.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )
				.ToList ( );

			foreach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )
			{
				if ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )
				{
					CommonPath = PathSegment;
				}
				else if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )
				{
					CommonPath += Separator + PathSegment;
				}
				else
				{
					break;
				}
			}
			
			return CommonPath;
		}
	}
}



Java: public class CommonPath {
	public static String commonPath(String... paths){
		String commonPath = "";
		String[][] folders = new String[paths.length][];
		for(int i = 0; i < paths.length; i++){
			folders[i] = paths[i].split("/"); 
		}
		for(int j = 0; j < folders[0].length; j++){
			String thisFolder = folders[0][j]; 
			boolean allMatched = true; 
			for(int i = 1; i < folders.length && allMatched; i++){ 
				if(folders[i].length < j){ 
					allMatched = false; 
					break; 
				}
				
				allMatched &= folders[i][j].equals(thisFolder); 
			}
			if(allMatched){ 
				commonPath += thisFolder + "/"; 
			}else{
				break;
			}
		}
		return commonPath;
	}
	
	public static void main(String[] args){
		String[] paths = { "/home/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths));
		
		String[] paths2 = { "/hame/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths2));
	}
}
Task: Recaman's sequence



C#: using System;
using System.Collections.Generic;

namespace RecamanSequence {
    class Program {
        static void Main(string[] args) {
            List<int> a = new List<int>() { 0 };
            HashSet<int> used = new HashSet<int>() { 0 };
            HashSet<int> used1000 = new HashSet<int>() { 0 };
            bool foundDup = false;
            int n = 1;
            while (n <= 15 || !foundDup || used1000.Count < 1001) {
                int next = a[n - 1] - n;
                if (next < 1 || used.Contains(next)) {
                    next += 2 * n;
                }
                bool alreadyUsed = used.Contains(next);
                a.Add(next);
                if (!alreadyUsed) {
                    used.Add(next);
                    if (0 <= next && next <= 1000) {
                        used1000.Add(next);
                    }
                }
                if (n == 14) {
                    Console.WriteLine("The first 15 terms of the Recaman sequence are: [{0}]", string.Join(", ", a));
                }
                if (!foundDup && alreadyUsed) {
                    Console.WriteLine("The first duplicated term is a[{0}] = {1}", n, next);
                    foundDup = true;
                }
                if (used1000.Count == 1001) {
                    Console.WriteLine("Terms up to a[{0}] are needed to generate 0 to 1000", n);
                }
                n++;
            }
        }
    }
}



Java: import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RecamanSequence {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>();
        a.add(0);

        Set<Integer> used = new HashSet<>();
        used.add(0);

        Set<Integer> used1000 = new HashSet<>();
        used1000.add(0);

        boolean foundDup = false;
        int n = 1;
        while (n <= 15 || !foundDup || used1000.size() < 1001) {
            int next = a.get(n - 1) - n;
            if (next < 1 || used.contains(next)) {
                next += 2 * n;
            }
            boolean alreadyUsed = used.contains(next);
            a.add(next);
            if (!alreadyUsed) {
                used.add(next);
                if (0 <= next && next <= 1000) {
                    used1000.add(next);
                }
            }
            if (n == 14) {
                System.out.printf("The first 15 terms of the Recaman sequence are : %s\n", a);
            }
            if (!foundDup && alreadyUsed) {
                System.out.printf("The first duplicate term is a[%d] = %d\n", n, next);
                foundDup = true;
            }
            if (used1000.size() == 1001) {
                System.out.printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n);
            }
            n++;
        }
    }
}
Task: Memory allocation



C#: using System;
using System.Runtime.InteropServices;

public unsafe class Program
{
    public static unsafe void HeapMemory()
    {
        const int HEAP_ZERO_MEMORY = 0x00000008;
        const int size = 1000;
        int ph = GetProcessHeap();
        void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
        if (pointer == null)
            throw new OutOfMemoryException();
        Console.WriteLine(HeapSize(ph, 0, pointer));
        HeapFree(ph, 0, pointer);
    }

    public static unsafe void StackMemory()
    {
        byte* buffer = stackalloc byte[1000];
        
    }
    public static void Main(string[] args)
    {
        HeapMemory();
        StackMemory();
    }
    [DllImport("kernel32")]
    static extern void* HeapAlloc(int hHeap, int flags, int size);
    [DllImport("kernel32")]
    static extern bool HeapFree(int hHeap, int flags, void* block);
    [DllImport("kernel32")]
    static extern int GetProcessHeap();
    [DllImport("kernel32")]
    static extern int HeapSize(int hHeap, int flags, void* block);

}



Java: 

Object foo = new Object(); 
int[] fooArray = new int[size]; 
int x = 0;
Task: Integer sequence



C#: using System;
using System.Numerics;

class Program
{
    static void Main()
    {
        BigInteger i = 1;
        while (true)
        {
            Console.WriteLine(i++);
        }
    }
}



Java: public class Count{
    public static void main(String[] args){
        for(long i = 1; ;i++) System.out.println(i);
    }
}
Task: DNS query



C#:         private string LookupDns(string s)
        {
            try
            {
                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);

                string result = ip.AddressList[0].ToString();

                for (int i = 1; i < ip.AddressList.Length; ++i)
                    result += ", " + ip.AddressList[i].ToString();

                return result;
            }
            catch (System.Net.Sockets.SocketException se)
            {
                return se.Message;
            }
        }



Java: import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;

class DnsQuery {
    public static void main(String[] args) {
        try {
            InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net");
            for(int i=0; i < ipAddr.length ; i++) {
                if (ipAddr[i] instanceof Inet4Address) {
                    System.out.println("IPv4 : " + ipAddr[i].getHostAddress());
                } else if (ipAddr[i] instanceof Inet6Address) {
                    System.out.println("IPv6 : " + ipAddr[i].getHostAddress());
                }
            }
        } catch (UnknownHostException uhe) {
            System.err.println("unknown host");
        }
    }
}
Task: Seven-sided dice from five-sided dice



C#: using System;

public class SevenSidedDice
{
    Random random = new Random();
		
        static void Main(string[] args)
		{
			SevenSidedDice sevenDice = new SevenSidedDice();
			Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
            Console.Read();
		}
		
		int seven()
		{
			int v=21;
			while(v>20)
				v=five()+five()*5-6;
			return 1+v%7;
		}
		
		int five()
		{
        return 1 + random.Next(5);
		}
}



Java: import java.util.Random;
public class SevenSidedDice 
{
	private static final Random rnd = new Random();
	public static void main(String[] args)
	{
		SevenSidedDice now=new SevenSidedDice();
		System.out.println("Random number from 1 to 7: "+now.seven());
	}
	int seven()
	{
		int v=21;
		while(v>20)
			v=five()+five()*5-6;
		return 1+v%7;
	}
	int five()
	{
		return 1+rnd.nextInt(5);
	}
}
Task: Create a two-dimensional array at runtime



C#: class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter two integers. Space delimited please: ");
            string s = Console.ReadLine();
            
            int[,] myArray=new int[(int)s[0],(int)s[2]];
            myArray[0, 0] = 2;
            Console.WriteLine(myArray[0, 0]);

            Console.ReadLine();
        }
    }



Java: import java.util.Scanner;

public class twoDimArray {
  public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        int nbr1 = in.nextInt();
        int nbr2 = in.nextInt();
        
        double[][] array = new double[nbr1][nbr2];
        array[0][0] = 42.0;
        System.out.println("The number at place [0 0] is " + array[0][0]);
  }
}
Task: Bitwise operations




Go: package main

import "fmt"

func bitwise(a, b int16) {
	fmt.Printf("a:   %016b\n", uint16(a))
	fmt.Printf("b:   %016b\n", uint16(b))

	
	fmt.Printf("and: %016b\n", uint16(a&b))
	fmt.Printf("or:  %016b\n", uint16(a|b))
	fmt.Printf("xor: %016b\n", uint16(a^b))
	fmt.Printf("not: %016b\n", uint16(^a))

	if b < 0 {
		fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).")
		return
	}
	ua := uint16(a)
	ub := uint32(b)

	
	fmt.Printf("shl: %016b\n", uint16(ua<<ub))
	fmt.Printf("shr: %016b\n", uint16(ua>>ub))

	
	fmt.Printf("las: %016b\n", uint16(a<<ub))
	fmt.Printf("ras: %016b\n", uint16(a>>ub))

	
	fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub))))
	fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))
}

func main() {
	var a, b int16 = -460, 6
	bitwise(a, b)
}


Java: module BitwiseOps
    {
    @Inject Console console;
    void run()
        {
        for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF])  
            {
            static String hex(Int64 n)   
                {
                
                return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString();
                }

            console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}):
                           |  {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)}
                           |  {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)}
                           |  {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)}
                           |  NOT {hex(n1)} = {hex(~n1)}
                           |  left shift {hex(n1)} by {n2} = {hex(n1 << n2)}
                           |  right shift {hex(n1)} by {n2} = {hex(n1 >> n2)}
                           |  right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)}
                           |  left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))}
                           |  right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))}
                           |  leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)}
                           |  rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)}
                           |  leading zero count of {hex(n1)} = {n1.leadingZeroCount}
                           |  trailing zero count of {hex(n1)} = {n1.trailingZeroCount}
                           |  bit count (aka "population") of {hex(n1)} = {n1.bitCount}
                           |  reversed bits of {hex(n1)} = {hex(n1.reverseBits())}
                           |  reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())}
                           |
                         );
            }
        }
    }
Task: Read a file line by line




Go: package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

func init() {
	log.SetFlags(log.Lshortfile)
}

func main() {
	
	inputFile, err := os.Open("byline.go")
	if err != nil {
		log.Fatal("Error opening input file:", err)
	}

	
	
	
	defer inputFile.Close()

	scanner := bufio.NewScanner(inputFile)

	
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}

	
	
	if err := scanner.Err(); err != nil {
		log.Fatal(scanner.Err())
	}
}


Java: import java.io.BufferedReader;
import java.io.FileReader;


public class ReadFileByLines {
    private static void processLine(int lineNo, String line) {
        
    }

    public static void main(String[] args) {
        for (String filename : args) {
            BufferedReader br = null;
            FileReader fr = null;
            try {
                fr = new FileReader(filename);
                br = new BufferedReader(fr);
                String line;
                int lineNo = 0;
                while ((line = br.readLine()) != null) {
                    processLine(++lineNo, line);
                }
            }
            catch (Exception x) {
                x.printStackTrace();
            }
            finally {
                if (fr != null) {
                    try {br.close();} catch (Exception ignoreMe) {}
                    try {fr.close();} catch (Exception ignoreMe) {}
                }
            }
        }
    }
}
Task: Doubly-linked list_Element insertion




Go: package main

import "fmt"

type dlNode struct {
    string
    next, prev *dlNode
}

type dlList struct {
    head, tail *dlNode
}

func (list *dlList) String() string {
    if list.head == nil {
        return fmt.Sprint(list.head)
    }
    r := "[" + list.head.string
    for p := list.head.next; p != nil; p = p.next {
        r += " " + p.string
    }
    return r + "]"
}

func (list *dlList) insertTail(node *dlNode) {
    if list.tail == nil {
        list.head = node
    } else {
        list.tail.next = node
    }
    node.next = nil
    node.prev = list.tail
    list.tail = node
}

func (list *dlList) insertAfter(existing, insert *dlNode) {
    insert.prev = existing
    insert.next = existing.next
    existing.next.prev = insert
    existing.next = insert
    if existing == list.tail {
        list.tail = insert
    }
}

func main() {
    dll := &dlList{}
    fmt.Println(dll)
    a := &dlNode{string: "A"}
    dll.insertTail(a)
    dll.insertTail(&dlNode{string: "B"})
    fmt.Println(dll)
    dll.insertAfter(a, &dlNode{string: "C"})
    fmt.Println(dll)
}


Java: import java.util.LinkedList;

@SuppressWarnings("serial")
public class DoublyLinkedListInsertion<T> extends LinkedList<T> {
   
    public static void main(String[] args) {
        DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>();
        list.addFirst("Add First 1");
        list.addFirst("Add First 2");
        list.addFirst("Add First 3");
        list.addFirst("Add First 4");
        list.addFirst("Add First 5");
        traverseList(list);
        
        list.addAfter("Add First 3", "Add New");
        traverseList(list);
    }
    
    
    public void addAfter(T after, T element) {
        int index = indexOf(after);
        if ( index >= 0 ) {
            add(index + 1, element);
        }
        else {
            addLast(element);
        }
    }
    
    private static void traverseList(LinkedList<String> list) {
        System.out.println("Traverse List:");
        for ( int i = 0 ; i < list.size() ; i++ ) {
            System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
        }
        System.out.println();
    }
    
}
Task: Quickselect algorithm




Go: package main

import "fmt"

func quickselect(list []int, k int) int {
    for {
        
        px := len(list) / 2
        pv := list[px]
        last := len(list) - 1
        list[px], list[last] = list[last], list[px]
        i := 0
        for j := 0; j < last; j++ {
            if list[j] < pv {
                list[i], list[j] = list[j], list[i]
                i++
            }
        }
        
        if i == k {
            return pv
        }
        if k < i {
            list = list[:i]
        } else {
            list[i], list[last] = list[last], list[i]
            list = list[i+1:]
            k -= i + 1
        }
    }
}

func main() {
    for i := 0; ; i++ {
        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
        if i == len(v) {
            return
        }
        fmt.Println(quickselect(v, i))
    }
}


Java: import java.util.Random;

public class QuickSelect {

	private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
		E pivotVal = arr[pivot];
		swap(arr, pivot, right);
		int storeIndex = left;
		for (int i = left; i < right; i++) {
			if (arr[i].compareTo(pivotVal) < 0) {
				swap(arr, i, storeIndex);
				storeIndex++;
			}
		}
		swap(arr, right, storeIndex);
		return storeIndex;
	}
	
	private static <E extends Comparable<? super E>> E select(E[] arr, int n) {
		int left = 0;
		int right = arr.length - 1;
		Random rand = new Random();
		while (right >= left) {
			int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
			if (pivotIndex == n) {
				return arr[pivotIndex];
			} else if (pivotIndex < n) {
				left = pivotIndex + 1;
			} else {
				right = pivotIndex - 1;
			}
		}
		return null;
	}
	
	private static void swap(Object[] arr, int i1, int i2) {
		if (i1 != i2) {
			Object temp = arr[i1];
			arr[i1] = arr[i2];
			arr[i2] = temp;
		}
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
			System.out.print(select(input, i));
			if (i < 9) System.out.print(", ");
		}
		System.out.println();
	}

}
Task: Non-decimal radices_Convert




Go: package main

import (
    "fmt"
    "math/big"
    "strconv"
)

func main () {
    s := strconv.FormatInt(26, 16) 
    fmt.Println(s)

    i, err := strconv.ParseInt("1a", 16, 64) 
    if err == nil {
        fmt.Println(i)
    }
    b, ok := new(big.Int).SetString("1a", 16) 
    if ok {
        fmt.Println(b)
    }
}


Java: public static long backToTen(String num, int oldBase){
   return Long.parseLong(num, oldBase); 
}

public static String tenToBase(long num, int newBase){
   return Long.toString(num, newBase);
}
Task: Walk a directory_Recursively




Go: 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)
}


Java: 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());
                    }
                }
            }
        }
    }
}
Task: CRC-32




Go: package main

import (
    "fmt"
    "hash/crc32"
)

func main() {
    s := []byte("The quick brown fox jumps over the lazy dog")
    result := crc32.ChecksumIEEE(s)
    fmt.Printf("%X\n", result)
}


Java: import java.util.zip.* ;

public class CRCMaker {
   public static void main( String[ ] args ) {
      String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ;
      CRC32 myCRC = new CRC32( ) ;
      myCRC.update( toBeEncoded.getBytes( ) ) ;
      System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ;
   }
}
Task: CSV to HTML translation




Go: package main

import (
    "bytes"
    "encoding/csv"
    "fmt"
    "html/template"
    "strings"
)

var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`

func main() {
    if h, err := csvToHtml(c); err != nil {
        fmt.Println(err)
    } else {
        fmt.Print(h)
    }
}

func csvToHtml(c string) (string, error) {
    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
    if err != nil {
        return "", err
    }
    var b strings.Builder
    err = template.Must(template.New("").Parse(`<table>
{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
    return b.String(), err
}


Java: 

grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body   : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row    : field ',' field '\r'? '\n';
field  : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");};
Field  : ~[,\n\r]+;