WeixiangYan/CodeTransOcean huggingface dataset:
Task: Move-to-front algorithm





Java: import java.util.LinkedList;
import java.util.List;

public class MTF{
	public static List<Integer> encode(String msg, String symTable){
		List<Integer> output = new LinkedList<Integer>();
		StringBuilder s = new StringBuilder(symTable);
		for(char c : msg.toCharArray()){
			int idx = s.indexOf("" + c);
			output.add(idx);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output;
	}
	
	public static String decode(List<Integer> idxs, String symTable){
		StringBuilder output = new StringBuilder();
		StringBuilder s = new StringBuilder(symTable);
		for(int idx : idxs){
			char c = s.charAt(idx);
			output = output.append(c);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output.toString();
	}
	
	private static void test(String toEncode, String symTable){
		List<Integer> encoded = encode(toEncode, symTable);
		System.out.println(toEncode + ": " + encoded);
		String decoded = decode(encoded, symTable);
		System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
	}
	
	public static void main(String[] args){
		String symTable = "abcdefghijklmnopqrstuvwxyz";
		test("broood", symTable);
		test("bananaaa", symTable);
		test("hiphophiphop", symTable);
	}
}
Task: Move-to-front algorithm







Python: from __future__ import print_function
from string import ascii_lowercase

SYMBOLTABLE = list(ascii_lowercase)

def move2front_encode(strng, symboltable):
    sequence, pad = [], symboltable[::]
    for char in strng:
        indx = pad.index(char)
        sequence.append(indx)
        pad = [pad.pop(indx)] + pad
    return sequence

def move2front_decode(sequence, symboltable):
    chars, pad = [], symboltable[::]
    for indx in sequence:
        char = pad[indx]
        chars.append(char)
        pad = [pad.pop(indx)] + pad
    return ''.join(chars)

if __name__ == '__main__':
    for s in ['broood', 'bananaaa', 'hiphophiphop']:
        encode = move2front_encode(s, SYMBOLTABLE)
        print('%14r encodes to %r' % (s, encode), end=', ')
        decode = move2front_decode(encode, SYMBOLTABLE)
        print('which decodes back to %r' % decode)
        assert s == decode, 'Whoops!'
Task: Move-to-front algorithm








VB: Function mtf_encode(s)
	
	Set symbol_table = CreateObject("System.Collections.ArrayList")
	For j = 97 To 122 
		symbol_table.Add Chr(j)
	Next
	output = ""
	For i = 1 To Len(s)
		char = Mid(s,i,1)
		If i = Len(s) Then
			output = output & symbol_table.IndexOf(char,0)
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		Else
			output = output & symbol_table.IndexOf(char,0) & " "
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		End If
	Next
	mtf_encode = output
End Function

Function mtf_decode(s)
	
	code = Split(s," ")
	
	Set symbol_table = CreateObject("System.Collections.ArrayList")
	For j = 97 To 122 
		symbol_table.Add Chr(j)
	Next
	output = ""
	For i = 0 To UBound(code)
		char = symbol_table(code(i))
		output = output & char
		If code(i) <> 0 Then
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		End If
	Next
	mtf_decode = output	
End Function


wordlist = Array("broood","bananaaa","hiphophiphop")
For Each word In wordlist
	WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_
		mtf_decode(mtf_encode(word)) & "."
	WScript.StdOut.WriteBlankLines(1)
Next
Task: Move-to-front algorithm




Go: package main

import (
	"bytes"
	"fmt"
)

type symbolTable string

func (symbols symbolTable) encode(s string) []byte {
	seq := make([]byte, len(s))
	pad := []byte(symbols)
	for i, c := range []byte(s) {
		x := bytes.IndexByte(pad, c)
		seq[i] = byte(x)
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return seq
}

func (symbols symbolTable) decode(seq []byte) string {
	chars := make([]byte, len(seq))
	pad := []byte(symbols)
	for i, x := range seq {
		c := pad[x]
		chars[i] = c
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return string(chars)
}

func main() {
	m := symbolTable("abcdefghijklmnopqrstuvwxyz")
	for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
		enc := m.encode(s)
		dec := m.decode(enc)
		fmt.Println(s, enc, dec)
		if dec != s {
			panic("Whoops!")
		}
	}
}
Task: Move-to-front algorithm






PHP: <?php

function symbolTable() {
    $symbol = array();
    for ($c = ord('a') ; $c <= ord('z') ; $c++) {
        $symbol[$c - ord('a')] = chr($c);
    }
    return $symbol;
}

function mtfEncode($original, $symbol) {
    $encoded = array();
    for ($i = 0 ; $i < strlen($original) ; $i++) {
        $char = $original[$i];
        $position = array_search($char, $symbol);
        $encoded[] = $position;
        $mtf = $symbol[$position];
        unset($symbol[$position]);
        array_unshift($symbol, $mtf);
    }
    return $encoded;
}

function mtfDecode($encoded, $symbol) {
    $decoded = '';
    foreach ($encoded AS $position) {
        $char = $symbol[$position];
        $decoded .= $char;
        unset($symbol[$position]);
        array_unshift($symbol, $char);
    }
    return $decoded;
}

foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
    $encoded = mtfEncode($original, symbolTable());
    $decoded = mtfDecode($encoded, symbolTable());
    echo
        $original,
        ' -> [', implode(',', $encoded), ']',
        ' -> ', $decoded,
        ' : ', ($original === $decoded ? 'OK' : 'Error'),
        PHP_EOL;
}
Task: Get system command output



C#: using System;

namespace GetSystemCommandOutput {
    class Program {
        static void Main(string[] args) {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/c echo Hello World";
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            process.StartInfo = startInfo;
            process.Start();

            string output = process.StandardOutput.ReadToEnd();
            Console.WriteLine("Output is {0}", output);
        }
    }
}









Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;
   
begin
   Args := Argument_String_To_List (Command);
   
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;
Task: Get system command output

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) return 1;

    FILE *fd;
    fd = popen(argv[1], "r");
    if (!fd) return 1;

    char   buffer[256];
    size_t chread;
    
    size_t comalloc = 256;
    size_t comlen   = 0;
    char  *comout   = malloc(comalloc);

    
    while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) {
        if (comlen + chread >= comalloc) {
            comalloc *= 2;
            comout = realloc(comout, comalloc);
        }
        memmove(comout + comlen, buffer, chread);
        comlen += chread;
    }

    
    fwrite(comout, 1, comlen, stdout);
    free(comout);
    pclose(fd);
    return 0;
}











Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;
   
begin
   Args := Argument_String_To_List (Command);
   
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;
Task: Get system command output


C++: #include <fstream>
#include <iostream>

std::string execute(const std::string& command) {
    system((command + " > temp.txt").c_str());

    std::ifstream ifs("temp.txt");
    std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
    ifs.close(); 
    if (std::remove("temp.txt") != 0) {
        perror("Error deleting temporary file");
    }
    return ret;
}

int main() {
    std::cout << execute("whoami") << '\n';
}










Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;
   
begin
   Args := Argument_String_To_List (Command);
   
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;
Task: Get system command output




Go: package main

import (
  "fmt"
  "log"
  "os/exec"
)

func main() {
  output, err := exec.Command("ls", "-l").CombinedOutput()
  if err != nil {
    log.Fatal(err)
  }
  fmt.Print(string(output))
}








Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;
   
begin
   Args := Argument_String_To_List (Command);
   
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;
Task: Get system command output





Java: import java.io.*;
import java.util.*;

public class SystemCommand {

    public static void main(String args[]) throws IOException {

        String command = "cmd /c dir";
        Process p = Runtime.getRuntime().exec(command);

        try (Scanner sc = new Scanner(p.getInputStream())) {

            System.out.printf("Output of the command: %s %n%n", command);
            while (sc.hasNext()) {
                System.out.println(sc.nextLine());
            }
        }
    }
}







Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;
   
begin
   Args := Argument_String_To_List (Command);
   
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;
Task: Get system command output







Python: >>> import subprocess
>>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
>>> type(returned_text)
<class 'str'>
>>> print(returned_text)
 Volume in drive C is Windows
 Volume Serial Number is 44X7-73CE

 Directory of C:\Python33

04/07/2013  06:40    <DIR>          .
04/07/2013  06:40    <DIR>          ..
27/05/2013  07:10    <DIR>          DLLs
27/05/2013  07:10    <DIR>          Doc
27/05/2013  07:10    <DIR>          include
27/05/2013  07:10    <DIR>          Lib
27/05/2013  07:10    <DIR>          libs
16/05/2013  00:15            33,326 LICENSE.txt
15/05/2013  22:49           214,554 NEWS.txt
16/05/2013  00:03            26,624 python.exe
16/05/2013  00:03            27,136 pythonw.exe
15/05/2013  22:49             6,701 README.txt
27/05/2013  07:10    <DIR>          tcl
27/05/2013  07:10    <DIR>          Tools
16/05/2013  00:02            43,008 w9xpopen.exe
               6 File(s)        351,349 bytes
               9 Dir(s)  46,326,947,840 bytes free

>>> 





Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;
   
begin
   Args := Argument_String_To_List (Command);
   
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;
Task: Get system command output








VB: For Each line In ExecCmd("ipconfig /all")
    Wscript.Echo line
Next


Function ExecCmd(cmd)

    
    Dim wso : Set wso = CreateObject("Wscript.Shell")
    Dim exec : Set exec = wso.Exec(cmd)
    Dim res : res = ""

    
    Do
        res = res & VbLf & exec.StdOut.ReadLine
    Loop Until exec.StdOut.AtEndOfStream

    
    ExecCmd = Split(Mid(res,2),vbLf)
End Function




Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with GNAT.Expect;            use GNAT.Expect;
with GNAT.OS_Lib;            use GNAT.OS_Lib;
with GNAT.String_Split;      use GNAT.String_Split;

procedure System_Command is
   Command    : String          := "ls -l";
   Args       : Argument_List_Access;
   Status     : aliased Integer;
   Separators : constant String := LF & CR;
   Reply_List : Slice_Set;
   
begin
   Args := Argument_String_To_List (Command);
   
   declare
      Response : String :=
        Get_Command_Output
          (Command   => Args (Args'First).all,
           Arguments => Args (Args'First + 1 .. Args'Last),
           Input     => "",
           Status    => Status'Access);
   begin
      Free (Args);
      
      if Status = 0 then
         Create (S          => Reply_List,
                 From       => Response,
                 Separators => Separators,
                 Mode       => Multiple);
      end if;
   end;
   
   for I in 1 .. Slice_Count (Reply_List) loop
      Put_Line (Slice (Reply_List, I));
   end loop;

end System_Command;
Task: Get system command output

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) return 1;

    FILE *fd;
    fd = popen(argv[1], "r");
    if (!fd) return 1;

    char   buffer[256];
    size_t chread;
    
    size_t comalloc = 256;
    size_t comlen   = 0;
    char  *comout   = malloc(comalloc);

    
    while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) {
        if (comlen + chread >= comalloc) {
            comalloc *= 2;
            comout = realloc(comout, comalloc);
        }
        memmove(comout + comlen, buffer, chread);
        comlen += chread;
    }

    
    fwrite(comout, 1, comlen, stdout);
    free(comout);
    pclose(fd);
    return 0;
}
Task: Get system command output



C#: using System;

namespace GetSystemCommandOutput {
    class Program {
        static void Main(string[] args) {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/c echo Hello World";
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            process.StartInfo = startInfo;
            process.Start();

            string output = process.StandardOutput.ReadToEnd();
            Console.WriteLine("Output is {0}", output);
        }
    }
}
Task: Get system command output


C++: #include <fstream>
#include <iostream>

std::string execute(const std::string& command) {
    system((command + " > temp.txt").c_str());

    std::ifstream ifs("temp.txt");
    std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
    ifs.close(); 
    if (std::remove("temp.txt") != 0) {
        perror("Error deleting temporary file");
    }
    return ret;
}

int main() {
    std::cout << execute("whoami") << '\n';
}
Task: Get system command output





Java: import java.io.*;
import java.util.*;

public class SystemCommand {

    public static void main(String args[]) throws IOException {

        String command = "cmd /c dir";
        Process p = Runtime.getRuntime().exec(command);

        try (Scanner sc = new Scanner(p.getInputStream())) {

            System.out.printf("Output of the command: %s %n%n", command);
            while (sc.hasNext()) {
                System.out.println(sc.nextLine());
            }
        }
    }
}
Task: Get system command output







Python: >>> import subprocess
>>> returned_text = subprocess.check_output("dir", shell=True, universal_newlines=True)
>>> type(returned_text)
<class 'str'>
>>> print(returned_text)
 Volume in drive C is Windows
 Volume Serial Number is 44X7-73CE

 Directory of C:\Python33

04/07/2013  06:40    <DIR>          .
04/07/2013  06:40    <DIR>          ..
27/05/2013  07:10    <DIR>          DLLs
27/05/2013  07:10    <DIR>          Doc
27/05/2013  07:10    <DIR>          include
27/05/2013  07:10    <DIR>          Lib
27/05/2013  07:10    <DIR>          libs
16/05/2013  00:15            33,326 LICENSE.txt
15/05/2013  22:49           214,554 NEWS.txt
16/05/2013  00:03            26,624 python.exe
16/05/2013  00:03            27,136 pythonw.exe
15/05/2013  22:49             6,701 README.txt
27/05/2013  07:10    <DIR>          tcl
27/05/2013  07:10    <DIR>          Tools
16/05/2013  00:02            43,008 w9xpopen.exe
               6 File(s)        351,349 bytes
               9 Dir(s)  46,326,947,840 bytes free

>>>
Task: Get system command output








VB: For Each line In ExecCmd("ipconfig /all")
    Wscript.Echo line
Next


Function ExecCmd(cmd)

    
    Dim wso : Set wso = CreateObject("Wscript.Shell")
    Dim exec : Set exec = wso.Exec(cmd)
    Dim res : res = ""

    
    Do
        res = res & VbLf & exec.StdOut.ReadLine
    Loop Until exec.StdOut.AtEndOfStream

    
    ExecCmd = Split(Mid(res,2),vbLf)
End Function
Task: Get system command output




Go: package main

import (
  "fmt"
  "log"
  "os/exec"
)

func main() {
  output, err := exec.Command("ls", "-l").CombinedOutput()
  if err != nil {
    log.Fatal(err)
  }
  fmt.Print(string(output))
}