WeixiangYan/CodeTransOcean huggingface dataset:
Task: Interactive programming (repl)





Java: public static void main(String[] args) {
    System.out.println(concat("Rosetta", "Code", ":"));
}

public static String concat(String a, String b, String c) {
   return a + c + c + b;
}

Rosetta::Code



Python: python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(string1, string2, separator):
	return separator.join([string1, '', string2])

>>> f('Rosetta', 'Code', ':')
'Rosetta::Code'
>>>
Task: Index finite lists of positive integers





Java: import java.math.BigInteger;
import static java.util.Arrays.stream;
import java.util.*;
import static java.util.stream.Collectors.*;

public class Test3 {
    static BigInteger rank(int[] x) {
        String s = stream(x).mapToObj(String::valueOf).collect(joining("F"));
        return new BigInteger(s, 16);
    }

    static List<BigInteger> unrank(BigInteger n) {
        BigInteger sixteen = BigInteger.valueOf(16);
        String s = "";
        while (!n.equals(BigInteger.ZERO)) {
            s = "0123456789ABCDEF".charAt(n.mod(sixteen).intValue()) + s;
            n = n.divide(sixteen);
        }
        return stream(s.split("F")).map(x -> new BigInteger(x)).collect(toList());
    }

    public static void main(String[] args) {
        int[] s = {1, 2, 3, 10, 100, 987654321};
        System.out.println(Arrays.toString(s));
        System.out.println(rank(s));
        System.out.println(unrank(rank(s)));
    }
}



Python: def rank(x): return int('a'.join(map(str, [1] + x)), 11)

def unrank(n):
	s = ''
	while n: s,n = "0123456789a"[n%11] + s, n//11
	return map(int, s.split('a'))[1:]

l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l
Task: Make a backup file





Java: import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.*;
 
public class Backup {
	public static void saveWithBackup(String filename, String... data) 
        throws IOException {
		
		Path file = Paths.get(filename).toRealPath();
		File backFile = new File(filename + ".backup");
		if(!backFile.exists()) {
			
			backFile.createNewFile();
		}
		Path back = Paths.get(filename + ".backup").toRealPath();
		Files.move(file, back, StandardCopyOption.REPLACE_EXISTING);
		try(PrintWriter out = new PrintWriter(file.toFile())){
			for(int i = 0; i < data.length; i++) {
				out.print(data[i]);
				if(i < data.length - 1) {
					out.println();
				}
			}
		}
	}

        public static void main(String[] args) {
		try {
			saveWithBackup("original.txt", "fourth", "fifth", "sixth");
		} catch (IOException e) {
			System.err.println(e);
		}
	} 
}



Python: import os
targetfile = "pycon-china"
os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak")
f = open(os.path.realpath(targetfile), "w")
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.close()
Task: Reverse the gender of a string





Java: public class ReallyLameTranslationOfJ {

    public static void main(String[] args) {
        String s = "She was a soul stripper. She took my heart!";
        System.out.println(cheapTrick(s));
        System.out.println(cheapTrick(cheapTrick(s)));
    }

    static String cheapTrick(String s) {
        if (s.contains("She"))
            return s.replaceAll("She", "He");
        else if(s.contains("He"))
            return s.replaceAll("He", "She");
        return s;
    }
}



Python: 

 
import re
male2female=u
 
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
 
switch={}
words=[]
 
 
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
 
def gen_pluralize(m,f):

  yield re_plural.sub("",m),re_plural.sub("",f)
  yield re_ES.sub("es",m),re_ES.sub("es",f)
  yield re_plural.sub("s",m),re_plural.sub("s",f)
 
def gen_capitalize_pluralize(m,f):
  for m,f in gen_pluralize(m,f):
    yield m.capitalize(), f.capitalize()
    yield m,f
 
def gen_switch_role_capitalize_pluralize(m,f):
  for m,f in gen_capitalize_pluralize(m,f):
    yield m,f
    yield f,m
 
for m,f in m2f:
  for xy,xx in gen_switch_role_capitalize_pluralize(m,f):
    if xy not in switch: 
      switch[xy]=xx
      words.append(xy)
 
words="|".join(words)
 
re_word=re.compile(ur"\b("+words+ur")\b")
 
text=u
 
 
def rev_gender(text):
  text=re_word.split(text)
  return "".join([ word+switch[gen] for word,gen in zip(text[::2],text[1::2])])+text[-1]
 
print rev_gender(text)
Task: Audio alarm





Java: import com.sun.javafx.application.PlatformImpl;
import java.io.File;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class AudioAlarm {

    public static void main(String[] args) throws InterruptedException {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number of seconds: ");
        int seconds = Integer.parseInt(input.nextLine());

        System.out.print("Enter a filename (must end with .mp3 or .wav): ");
        String audio = input.nextLine();

        TimeUnit.SECONDS.sleep(seconds);

        Media media = new Media(new File(audio).toURI().toString());
        AtomicBoolean stop = new AtomicBoolean();
        Runnable onEnd = () -> stop.set(true);

        PlatformImpl.startup(() -> {}); 

        MediaPlayer player = new MediaPlayer(media);
        player.setOnEndOfMedia(onEnd);
        player.setOnError(onEnd);
        player.setOnHalted(onEnd);
        player.play();

        while (!stop.get()) {
            Thread.sleep(100);
        }
        System.exit(0); 
    }
}



Python: import time
import os

seconds = input("Enter a number of seconds: ")
sound = input("Enter an mp3 filename: ")

time.sleep(float(seconds))
os.startfile(sound + ".mp3")
Task: Runtime evaluation_In an environment





Java: import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

public class Eval {
    private static final String CLASS_NAME = "TempPleaseDeleteMe";

    private static class StringCompiler
            extends SimpleJavaFileObject {
        final String m_sourceCode;

        private StringCompiler( final String sourceCode ) {
            super( URI.create( "string:
            m_sourceCode = sourceCode;
        }

        @Override
        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
            return m_sourceCode;
        }

        private boolean compile() {
            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();

            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
                null, null, null, Arrays.asList( this )
            ).call();
        }

        private double callEval( final double x )
                throws Exception {
            final Class<?> clarse = Class.forName( CLASS_NAME );
            final Method   eval   = clarse.getMethod( "eval", double.class );

            return ( Double ) eval.invoke( null, x );
        }
    }

    public static double evalWithX( final String code, final double x )
            throws Exception {
        final StringCompiler sc = new StringCompiler(
            "class "
                + CLASS_NAME
                + "{public static double eval(double x){return ("
                + code
                + ");}}"
            );

        if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
        return sc.callEval( x );
    }

    public static void main( final String [] args ) 
            throws Exception  {
        final String expression = args [ 0 ];
        final double x1         = Double.parseDouble( args [ 1 ] );
        final double x2         = Double.parseDouble( args [ 2 ] );

        System.out.println(
            evalWithX( expression, x1 )
            - evalWithX( expression, x2 )
        );
    }
}



Python: >>> def eval_with_x(code, a, b):
	return eval(code, {'x':b}) - eval(code, {'x':a})

>>> eval_with_x('2 ** x', 3, 5)
24
Task: Generate random numbers without repeating a value





Java: import java.util.*;

public class RandomShuffle {
    public static void main(String[] args) {
        Random rand = new Random();
        List<Integer> list = new ArrayList<>();
        for (int j = 1; j <= 20; ++j)
            list.add(j);
        Collections.shuffle(list, rand);
        System.out.println(list);
    }
}



Python: import random

print(random.sample(range(1, 21), 20))
Task: History variables





Java: public class HistoryVariable
{
    private Object value;

    public HistoryVariable(Object v)
    {
        value = v;
    }

    public void update(Object v)
    {
        value = v;
    }

    public Object undo()
    {
        return value;
    }

    @Override
    public String toString()
    {
        return value.toString();
    }

    public void dispose()
    {
    }
}



Python: import sys

HIST = {}

def trace(frame, event, arg):
    for name,val in frame.f_locals.items():
        if name not in HIST:
            HIST[name] = []
        else:
            if HIST[name][-1] is val:
                continue
        HIST[name].append(val)
    return trace

def undo(name):
    HIST[name].pop(-1)
    return HIST[name][-1]

def main():
    a = 10
    a = 20

    for i in range(5):
        c = i

    print "c:", c, "-> undo x3 ->",
    c = undo('c')
    c = undo('c')
    c = undo('c')
    print c
    print 'HIST:', HIST

sys.settrace(trace)
main()
Task: Use a REST API





Java: package src;

import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URI;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;



public class EventGetter {
	

	String city = "";
	String topic = "";
	
	public String getEvent(String path_code,String key) throws Exception{
		String responseString = "";
		
		URI request = new URIBuilder()			
			.setScheme("http")
			.setHost("api.meetup.com")
			.setPath(path_code)
			
			.setParameter("topic", topic)
			.setParameter("city", city)
			
			.setParameter("key", key)
			.build();
		
		HttpGet get = new HttpGet(request);			
		System.out.println("Get request : "+get.toString());
		
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = client.execute(get);
		responseString = EntityUtils.toString(response.getEntity());
		
		return responseString;
	}
	
	public String getApiKey(String key_path){
		String key = "";
		
		try{
			BufferedReader reader = new BufferedReader(new FileReader(key_path));	
			key = reader.readLine().toString();									
			reader.close();
		}
		catch(Exception e){System.out.println(e.toString());}
		
		return key;																
	}
	
}



Python: 
import requests
import json

city = None
topic = None

def getEvent(url_path, key) :
    responseString = ""
    
    params = {'city':city, 'key':key,'topic':topic}
    r = requests.get(url_path, params = params)    
    print(r.url)    
    responseString = r.text
    return responseString


def getApiKey(key_path):
    key = ""
    f = open(key_path, 'r')
    key = f.read()
    return key


def submitEvent(url_path,params):
    r = requests.post(url_path, data=json.dumps(params))        
    print(r.text+" : Event Submitted")
Task: Rosetta Code_Fix code tags





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

public class FixCodeTags 
{
	public static void main(String[] args)
	{
		String sourcefile=args[0];
		String convertedfile=args[1];
		convert(sourcefile,convertedfile);
	}
		static String[] languages = {"abap", "actionscript", "actionscript3",
			"ada", "apache", "applescript", "apt_sources", "asm", "asp",
			"autoit", "avisynth", "bar", "bash", "basic4gl", "bf",
			"blitzbasic", "bnf", "boo", "c", "caddcl", "cadlisp", "cfdg",
			"cfm", "cil", "c_mac", "cobol", "cpp", "cpp-qt", "csharp", "css",
			"d", "delphi", "diff", "_div", "dos", "dot", "eiffel", "email",
			"foo", "fortran", "freebasic", "genero", "gettext", "glsl", "gml",
			"gnuplot", "go", "groovy", "haskell", "hq9plus", "html4strict",
			"idl", "ini", "inno", "intercal", "io", "java", "java5",
			"javascript", "kixtart", "klonec", "klonecpp", "latex", "lisp",
			"lolcode", "lotusformulas", "lotusscript", "lscript", "lua",
			"m68k", "make", "matlab", "mirc", "modula3", "mpasm", "mxml",
			"mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas",
			"oracle11", "oracle8", "pascal", "per", "perl", "php", "php-brief",
			"pic16", "pixelbender", "plsql", "povray", "powershell",
			"progress", "prolog", "providex", "python", "qbasic", "rails",
			"reg", "robots", "ruby", "sas", "scala", "scheme", "scilab",
			"sdlbasic", "smalltalk", "smarty", "sql", "tcl", "teraterm",
			"text", "thinbasic", "tsql", "typoscript", "vb", "vbnet",
			"verilog", "vhdl", "vim", "visualfoxpro", "visualprolog",
			"whitespace", "winbatch", "xml", "xorg_conf", "xpp", "z80"};
	static void convert(String sourcefile,String convertedfile)
	{
		try
		{
			BufferedReader br=new BufferedReader(new FileReader(sourcefile));
			
			StringBuffer sb=new StringBuffer("");
			String line;
			while((line=br.readLine())!=null)
			{
				for(int i=0;i<languages.length;i++)
				{
					String lang=languages[i];
					line=line.replaceAll("<"+lang+">", "<lang "+lang+">");
					line=line.replaceAll("</"+lang+">", "</"+"lang>");
					line=line.replaceAll("<code "+lang+">", "<lang "+lang+">");
					line=line.replaceAll("</code>", "</"+"lang>");
				}
				sb.append(line);
			}
			br.close();
			
			FileWriter fw=new FileWriter(new File(convertedfile));
			
			fw.write(sb.toString());
			fw.close();
		}
		catch (Exception e)
		{
			System.out.println("Something went horribly wrong: "+e.getMessage());
		}
	}
}



Python: 

from re import sub

testtexts = [
,
    ,
    ]

for txt in testtexts:
    text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt)
    text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2)
    text2 = sub(r'</lang\s*>', r'
Task: Permutations with repetitions





Java: import java.util.function.Predicate;

public class PermutationsWithRepetitions {

    public static void main(String[] args) {
        char[] chars = {'a', 'b', 'c', 'd'};
        
        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
    }

    static void permute(char[] a, int k, Predicate<int[]> decider) {
        int n = a.length;
        if (k < 1 || k > n)
            throw new IllegalArgumentException("Illegal number of positions.");

        int[] indexes = new int[n];
        int total = (int) Math.pow(n, k);

        while (total-- > 0) {
            for (int i = 0; i < n - (n - k); i++)
                System.out.print(a[indexes[i]]);
            System.out.println();

            if (decider.test(indexes))
                break;

            for (int i = 0; i < n; i++) {
                if (indexes[i] >= n - 1) {
                    indexes[i] = 0;
                } else {
                    indexes[i]++;
                    break;
                }
            }
        }
    }
}



Python: 

from itertools import product



def replicateM(n):
    
    def rep(m):
        def go(x):
            return [[]] if 1 > x else (
                liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
            )
        return go(n)
    return lambda m: rep(m)




def main():
    
    print(
        fTable(main.__doc__ + ':\n')(repr)(showList)(

            replicateM(2)

        )([[1, 2, 3], 'abc'])
    )





def liftA2List(f):
    
    return lambda xs: lambda ys: [
        f(*xy) for xy in product(xs, ys)
    ]






def fTable(s):
    
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )



def showList(xs):
    
    return '[' + ','.join(
        showList(x) if isinstance(x, list) else repr(x) for x in xs
    ) + ']'



if __name__ == '__main__':
    main()
Task: String interpolation (included)





Java: String original = "Mary had a X lamb";
String little = "little";
String replaced = original.replace("X", little); 
System.out.println(replaced);

System.out.printf("Mary had a %s lamb.", little);

String formatted = String.format("Mary had a %s lamb.", little);
System.out.println(formatted);


PHP: <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
Task: Sorting algorithms_Patience sort





Java: import java.util.*;

public class PatienceSort {
    public static <E extends Comparable<? super E>> void sort (E[] n) {
        List<Pile<E>> piles = new ArrayList<Pile<E>>();
        
        for (E x : n) {
            Pile<E> newPile = new Pile<E>();
            newPile.push(x);
            int i = Collections.binarySearch(piles, newPile);
            if (i < 0) i = ~i;
            if (i != piles.size())
                piles.get(i).push(x);
            else
                piles.add(newPile);
        }
 
        
        PriorityQueue<Pile<E>> heap = new PriorityQueue<Pile<E>>(piles);
        for (int c = 0; c < n.length; c++) {
            Pile<E> smallPile = heap.poll();
            n[c] = smallPile.pop();
            if (!smallPile.isEmpty())
                heap.offer(smallPile);
        }
        assert(heap.isEmpty());
    }
 
    private static class Pile<E extends Comparable<? super E>> extends Stack<E> implements Comparable<Pile<E>> {
        public int compareTo(Pile<E> y) { return peek().compareTo(y.peek()); }
    }

    public static void main(String[] args) {
	Integer[] a = {4, 65, 2, -31, 0, 99, 83, 782, 1};
	sort(a);
	System.out.println(Arrays.toString(a));
    }
}


PHP: <?php
class PilesHeap extends SplMinHeap {
    public function compare($pile1, $pile2) {
        return parent::compare($pile1->top(), $pile2->top());
    }
}

function patience_sort(&$n) {
    $piles = array();

    foreach ($n as $x) {

        $low = 0; $high = count($piles)-1;
        while ($low <= $high) {
            $mid = (int)(($low + $high) / 2);
            if ($piles[$mid]->top() >= $x)
                $high = $mid - 1;
            else
                $low = $mid + 1;
        }
        $i = $low;
        if ($i == count($piles))
            $piles[] = new SplStack();
        $piles[$i]->push($x);
    }

    $heap = new PilesHeap();
    foreach ($piles as $pile)
        $heap->insert($pile);
    for ($c = 0; $c < count($n); $c++) {
        $smallPile = $heap->extract();
        $n[$c] = $smallPile->pop();
        if (!$smallPile->isEmpty())
        $heap->insert($smallPile);
    }
    assert($heap->isEmpty());
}

$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
Task: Count occurrences of a substring





Java: public class CountSubstring {
	public static int countSubstring(String subStr, String str){
		return (str.length() - str.replace(subStr, "").length()) / subStr.length();
	}
	
	public static void main(String[] args){
		System.out.println(countSubstring("th", "the three truths"));
		System.out.println(countSubstring("abab", "ababababab"));
		System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
	}
}


PHP: <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
Task: Take notes on the command line





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();
        }
    }
}


PHP: #!/usr/bin/php
<?php
if ($argc > 1)
    file_put_contents(
        'notes.txt', 
        date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
        FILE_APPEND
    );
else
    @readfile('notes.txt');
Task: Find common directory path





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));
	}
}


PHP: <?php



function _commonPath($dirList)
{
	$arr = array();
	foreach($dirList as $i => $path)
	{
		$dirList[$i]	= explode('/', $path);
		unset($dirList[$i][0]);
		
		$arr[$i] = count($dirList[$i]);
	}
	
	$min = min($arr);
	
	for($i = 0; $i < count($dirList); $i++)
	{
		while(count($dirList[$i]) > $min)
		{
			array_pop($dirList[$i]);
		}
		
		$dirList[$i] = '/' . implode('/' , $dirList[$i]);
	}
	
	$dirList = array_unique($dirList);
	while(count($dirList) !== 1)
	{
		$dirList = array_map('dirname', $dirList);
		$dirList = array_unique($dirList);
	}
	reset($dirList);
	
	return current($dirList);
}

 

$dirs = array(
 '/home/user1/tmp/coverage/test',
 '/home/user1/tmp/covert/operator',
 '/home/user1/tmp/coven/members',
);


if('/home/user1/tmp' !== common_path($dirs))
{
  echo 'test fail';
} else {
  echo 'test success';
}

?>