WeixiangYan/CodeTransOcean huggingface dataset:
Task: Polymorphism





Java: class Point {
   protected int x, y;
   public Point() { this(0); }
   public Point(int x) { this(x, 0); }
   public Point(int x, int y) { this.x = x; this.y = y; }
   public Point(Point p) { this(p.x, p.y); }
   public int getX() { return this.x; }
   public int getY() { return this.y; }
   public void setX(int x) { this.x = x; }
   public void setY(int y) { this.y = y; }
   public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); }
}

class Circle extends Point {
   private int r;
   public Circle(Point p) { this(p, 0); }
   public Circle(Point p, int r) { super(p); this.r = r; }
   public Circle() { this(0); }
   public Circle(int x) { this(x, 0); }
   public Circle(int x, int y) { this(x, y, 0); }
   public Circle(int x, int y, int r) { super(x, y); this.r = r; }
   public Circle(Circle c) { this(c.x, c.y, c.r); }
   public int getR() { return this.r; }
   public void setR(int r) { this.r = r; }
   public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); }
}

public class test {
  public static void main(String args[]) {
    Point p = new Point();
    Point c = new Circle();
    p.print();
    c.print();     
  }
}



Python: class Point(object):
    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y
    def __repr__(self):
        return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y)

class Circle(object):
    def __init__(self, center=None, radius=1.0):
        self.center = center or Point()
        self.radius = radius
    def __repr__(self):
        return '<Circle 0x%x x: %f y: %f radius: %f>' % (
            id(self), self.center.x, self.center.y, self.radius)
Task: Wagstaff primes





Java: import java.math.BigInteger; 

public class Main {
  public static void main(String[] args) {
    BigInteger d = new BigInteger("3"), a;
    int lmt = 25, sl, c = 0;
    for (int i = 3; i < 5808; ) {
      a = BigInteger.ONE.shiftLeft(i).add(BigInteger.ONE).divide(d);
      if (a.isProbablePrime(1)) {
        System.out.printf("%2d %4d ", ++c, i);
        String s = a.toString(); sl = s.length();
        if (sl < lmt) System.out.println(a);
        else System.out.println(s.substring(0, 11) + ".." + s.substring(sl - 11, sl) + " " + sl + " digits");
      }
      i = BigInteger.valueOf(i).nextProbablePrime().intValue();
    }
  }
}



Python: 

from sympy import isprime

def wagstaff(N):
    
    pri, wcount = 1, 0
    while wcount < N:
        pri += 2
        if isprime(pri):
            wag = (2**pri + 1) // 3
            if isprime(wag):
                wcount += 1
                print(f'{wcount: 3}: {pri: 5} => ', 
                      f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')


wagstaff(24)
Task: Special variables





Java: import java.util.Arrays;

public class SpecialVariables {

    public static void main(String[] args) {

        
        
        System.out.println(Arrays.toString(args));

        
        
        System.out.println(SpecialVariables.class);


        

        
        System.out.println(System.getenv());

        
        
        System.out.println(System.getProperties());

        
        
        System.out.println(Runtime.getRuntime().availableProcessors());

    }
}



Python: names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
Task: Execute CopyPasta Language





Java: import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;

public class Copypasta
{
	
	public static void fatal_error(String errtext)
	{
		StackTraceElement[] stack = Thread.currentThread().getStackTrace();
		StackTraceElement main = stack[stack.length - 1];
		String mainClass = main.getClassName();
		System.out.println("%" + errtext);
		System.out.println("usage: " + mainClass + " [filename.cp]");
		System.exit(1);
	}
	public static void main(String[] args)
	{
		
		String fname = null;
		String source = null;
		try
		{
			fname = args[0];
			source = new String(Files.readAllBytes(new File(fname).toPath()));
		}
		catch(Exception e)
		{
			fatal_error("error while trying to read from specified file");
		}

		
		ArrayList<String> lines = new ArrayList<String>(Arrays.asList(source.split("\n")));
		
		
		String clipboard = "";
		
		
		int loc = 0;
		while(loc < lines.size())
		{
			
			String command = lines.get(loc).trim();

			try
			{
				if(command.equals("Copy"))
					clipboard += lines.get(loc + 1);
				else if(command.equals("CopyFile"))
				{
					if(lines.get(loc + 1).equals("TheF*ckingCode"))
						clipboard += source;
					else
					{
						String filetext = new String(Files.readAllBytes(new File(lines.get(loc + 1)).toPath()));
						clipboard += filetext;
					}
				}
				else if(command.equals("Duplicate"))
				{
					String origClipboard = clipboard;

					int amount = Integer.parseInt(lines.get(loc + 1)) - 1;
					for(int i = 0; i < amount; i++)
						clipboard += origClipboard;
				}
				else if(command.equals("Pasta!"))
				{
					System.out.println(clipboard);
					System.exit(0);
				}
				else
					fatal_error("unknown command '" + command + "' encountered on line " + new Integer(loc + 1).toString());
			}
			catch(Exception e)
			{
				fatal_error("error while executing command '" + command + "' on line " + new Integer(loc + 1).toString());
			}

			
			loc += 2;
		}
	}
}



Python: import sys


def fatal_error(errtext):
	print("%" + errtext)
	print("usage: " + sys.argv[0] + " [filename.cp]")
	sys.exit(1)


fname = None
source = None
try:
	fname = sys.argv[1]
	source = open(fname).read()
except:
	fatal_error("error while trying to read from specified file")


lines = source.split("\n")


clipboard = ""


loc = 0
while(loc < len(lines)):
	
	command = lines[loc].strip()

	try:
		if(command == "Copy"):
			clipboard += lines[loc + 1]
		elif(command == "CopyFile"):
			if(lines[loc + 1] == "TheF*ckingCode"):
				clipboard += source
			else:
				filetext = open(lines[loc+1]).read()
				clipboard += filetext
		elif(command == "Duplicate"):
			clipboard += clipboard * ((int(lines[loc + 1])) - 1)
		elif(command == "Pasta!"):
			print(clipboard)
			sys.exit(0)
		else:
			fatal_error("unknown command '" + command + "' encountered on line " + str(loc + 1))
	except Exception as e:
		fatal_error("error while executing command '" + command + "' on line " + str(loc + 1) + ": " + e)

	
	loc += 2
Task: Reflection_List properties





Java: import java.lang.reflect.Field;

public class ListFields {
    public int examplePublicField = 42;
    private boolean examplePrivateField = true;
    
    public static void main(String[] args) throws IllegalAccessException {
        ListFields obj = new ListFields();
        Class clazz = obj.getClass();

        System.out.println("All public fields (including inherited):");
        for (Field f : clazz.getFields()) {
            System.out.printf("%s\t%s\n", f, f.get(obj));
        }
        System.out.println();
        System.out.println("All declared fields (excluding inherited):");
        for (Field f : clazz.getDeclaredFields()) {
            System.out.printf("%s\t%s\n", f, f.get(obj));
        }
    }
}



Python: class Parent(object):
    __priv = 'private'
    
    def __init__(self, name):
        self.name = name
    
    def __repr__(self):
        return '%s(%s)' % (type(self).__name__, self.name)
    
    def doNothing(self):
        pass

import re

class Child(Parent):
    
    __rePrivate = re.compile('^_(Child|Parent)__')
    
    __reBleh = re.compile('\Wbleh$')
    @property
    def reBleh(self):
        return self.__reBleh
    
    def __init__(self, name, *args):
        super(Child, self).__init__(name)
        self.args = args
    
    def __dir__(self):
        myDir = filter(
            
            lambda p: not self.__rePrivate.match(p),
            list(set( \
                sum([dir(base) for base in type(self).__bases__], []) \
                + type(self).__dict__.keys() \
                + self.__dict__.keys() \
            )))
        return myDir + map(
            
            lambda p: p + '_bleh',
            filter(
                
                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),
                myDir))
    
    def __getattr__(self, name):
        if name[-5:] == '_bleh':
            
            return str(getattr(self, name[:-5])) + ' bleh'
        if hasattr(super(Child, chld), '__getattr__'):
            return super(Child, self).__getattr__(name)
        raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
    
    def __setattr__(self, name, value):
        if name[-5:] == '_bleh':
            
            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):
                setattr(self, name[:-5], self.reBleh.sub('', value))
        elif hasattr(super(Child, self), '__setattr__'):
            super(Child, self).__setattr__(name, value)
        elif hasattr(self, '__dict__'):
            self.__dict__[name] = value
    
    def __repr__(self):
        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))
    
    def doStuff(self):
        return (1+1.0/1e6) ** 1e6

par = Parent('par')
par.parent = True
dir(par)

inspect.getmembers(par)


chld = Child('chld', 0, 'I', 'two')
chld.own = "chld's own"
dir(chld)

inspect.getmembers(chld)
Task: URL parser





Java: import java.net.URI;
import java.net.URISyntaxException;
public class WebAddressParser{
    public static void main(String[] args){
        parseAddress("foo:
        parseAddress("urn:example:animal:ferret:nose");
    }

    static void parseAddress(String a){
        System.out.println("Parsing " + a);
        try{

            
            URI u = new URI(a);

            System.out.println("\tscheme = " + u.getScheme());
            System.out.println("\tdomain = " + u.getHost());
            System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort()));
            System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath()));
            System.out.println("\tquery = " + u.getQuery());
            System.out.println("\tfragment = " + u.getFragment());
        }
        catch (URISyntaxException x){
            System.err.println("Oops: " + x);
        }
    }
}



Python: import urllib.parse as up 

url = up.urlparse('http://user:pass@example.com:8081/path/file.html;params?query1=1

print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
print('url.query = ', url.query)
print('url.fragment = ', url.fragment)
print('url.username = ', url.username)
print('url.password = ', url.password)
Task: Base58Check encoding





Java: import java.math.BigInteger;
import java.util.List;

public class Base58CheckEncoding {
    private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    private static final BigInteger BIG0 = BigInteger.ZERO;
    private static final BigInteger BIG58 = BigInteger.valueOf(58);

    private static String convertToBase58(String hash) {
        return convertToBase58(hash, 16);
    }

    private static String convertToBase58(String hash, int base) {
        BigInteger x;
        if (base == 16 && hash.substring(0, 2).equals("0x")) {
            x = new BigInteger(hash.substring(2), 16);
        } else {
            x = new BigInteger(hash, base);
        }

        StringBuilder sb = new StringBuilder();
        while (x.compareTo(BIG0) > 0) {
            int r = x.mod(BIG58).intValue();
            sb.append(ALPHABET.charAt(r));
            x = x.divide(BIG58);
        }

        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        String s = "25420294593250030202636073700053352635053786165627414518";
        String b = convertToBase58(s, 10);
        System.out.printf("%s -> %s\n", s, b);

        List<String> hashes = List.of(
            "0x61",
            "0x626262",
            "0x636363",
            "0x73696d706c792061206c6f6e6720737472696e67",
            "0x516b6fcd0f",
            "0xbf4f89001e670274dd",
            "0x572e4794",
            "0xecac89cad93923c02321",
            "0x10c8511e"
        );
        for (String hash : hashes) {
            String b58 = convertToBase58(hash);
            System.out.printf("%-56s -> %s\n", hash, b58);
        }
    }
}



Python: ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

def convertToBase58(num):
    sb = ''
    while (num > 0):
        r = num % 58
        sb = sb + ALPHABET[r]
        num = num // 58;
    return sb[::-1]

s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("%-56d -> %s" % (s, b))

hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]
for num in hash_arr:
    b = convertToBase58(num)
    print("0x%-54x -> %s" % (num, b))
Task: Dynamic variable names





Java: public static void main(String... args){
        HashMap<String, Integer> vars = new HashMap<String, Integer>();
        
        
        
        vars.put("Variable name", 3); 
        vars.put("Next variable name", 5);
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        vars.put(str, sc.nextInt()); 
        
        System.out.println(vars.get("Variable name")); 
        System.out.println(vars.get(str));
}



Python: >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
Task: Commatizing numbers





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

public class CommatizingNumbers {

    public static void main(String[] args) throws Exception {
        commatize("pi=3.14159265358979323846264338327950288419716939937510582"
                + "097494459231", 6, 5, " ");

        commatize("The author has two Z$100000000000000 Zimbabwe notes (100 "
                + "trillion).", 0, 3, ".");

        try (Scanner sc = new Scanner(new File("input.txt"))) {
            while(sc.hasNext())
                commatize(sc.nextLine());
        }
    }

    static void commatize(String s) {
        commatize(s, 0, 3, ",");
    }

    static void commatize(String s, int start, int step, String ins) {
        if (start < 0 || start > s.length() || step < 1 || step > s.length())
            return;

        Matcher m = Pattern.compile("([1-9][0-9]*)").matcher(s.substring(start));
        StringBuffer result = new StringBuffer(s.substring(0, start));

        if (m.find()) {
            StringBuilder sb = new StringBuilder(m.group(1)).reverse();
            for (int i = step; i < sb.length(); i += step)
                sb.insert(i++, ins);
            m.appendReplacement(result, sb.reverse().toString());
        }

        System.out.println(m.appendTail(result));
    }
}



Python: import re as RegEx


def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
	outString = ""
	strPos = 0
	matches = RegEx.findall( "[0-9]*", _string )

	for match in matches[:-1]:
		if not match:
			outString += _string[ strPos ]
			strPos += 1
		else:
			if len(match) > _periodLen:
				leadIn = match[:_startPos]
				periods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]
				outString += leadIn + _separator.join( periods )
			else:
				outString += match

			strPos += len( match )

	return outString



print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) )
print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." ))
print ( Commatize( "\"-in Aus$+1411.8millions\"" ))
print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" ))
print ( Commatize( "123.e8000 is pretty big." ))
print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." ))
print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." ))
print ( Commatize( "James was never known as 0000000007" ))
print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." ))
print ( Commatize( "␢␢␢$-140000±100 millions." ))
print ( Commatize( "6/9/1946 was a good year for some." ))
Task: Kosaraju





Java: import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;

public class Kosaraju {
    static class Recursive<I> {
        I func;
    }

    private static List<Integer> kosaraju(List<List<Integer>> g) {
        
        int size = g.size();
        boolean[] vis = new boolean[size];
        int[] l = new int[size];
        AtomicInteger x = new AtomicInteger(size);

        List<List<Integer>> t = new ArrayList<>();
        for (int i = 0; i < size; ++i) {
            t.add(new ArrayList<>());
        }

        Recursive<IntConsumer> visit = new Recursive<>();
        visit.func = (int u) -> {
            if (!vis[u]) {
                vis[u] = true;
                for (Integer v : g.get(u)) {
                    visit.func.accept(v);
                    t.get(v).add(u);
                }
                int xval = x.decrementAndGet();
                l[xval] = u;
            }
        };

        
        for (int i = 0; i < size; ++i) {
            visit.func.accept(i);
        }
        int[] c = new int[size];

        Recursive<BiConsumer<Integer, Integer>> assign = new Recursive<>();
        assign.func = (Integer u, Integer root) -> {
            if (vis[u]) {  
                vis[u] = false;
                c[u] = root;
                for (Integer v : t.get(u)) {
                    assign.func.accept(v, root);
                }
            }
        };

        
        for (int u : l) {
            assign.func.accept(u, u);
        }

        return Arrays.stream(c).boxed().collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<List<Integer>> g = new ArrayList<>();
        for (int i = 0; i < 8; ++i) {
            g.add(new ArrayList<>());
        }
        g.get(0).add(1);
        g.get(1).add(2);
        g.get(2).add(0);
        g.get(3).add(1);
        g.get(3).add(2);
        g.get(3).add(4);
        g.get(4).add(3);
        g.get(4).add(5);
        g.get(5).add(2);
        g.get(5).add(6);
        g.get(6).add(5);
        g.get(7).add(4);
        g.get(7).add(6);
        g.get(7).add(7);

        List<Integer> output = kosaraju(g);
        System.out.println(output);
    }
}



Python: def kosaraju(g):
    class nonlocal: pass

    
    size = len(g)

    vis = [False]*size 
    l = [0]*size
    nonlocal.x = size
    t = [[]]*size   

    def visit(u):
        if not vis[u]:
            vis[u] = True
            for v in g[u]:
                visit(v)
                t[v] = t[v] + [u]
            nonlocal.x = nonlocal.x - 1
            l[nonlocal.x] = u

    
    for u in range(len(g)):
        visit(u)
    c = [0]*size

    def assign(u, root):
        if vis[u]:
            vis[u] = False
            c[u] = root
            for v in t[u]:
                assign(v, root)

    
    for u in l:
        assign(u, u)

    return c

g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g)
Task: Reflection_List methods





Java: import java.lang.reflect.Method;

public class ListMethods {
    public int examplePublicInstanceMethod(char c, double d) {
        return 42;
    }

    private boolean examplePrivateInstanceMethod(String s) {
        return true;
    }
    
    public static void main(String[] args) {
        Class clazz = ListMethods.class;

        System.out.println("All public methods (including inherited):");
        for (Method m : clazz.getMethods()) {
            System.out.println(m);
        }
        System.out.println();
        System.out.println("All declared methods (excluding inherited):");
        for (Method m : clazz.getDeclaredMethods()) {
            System.out.println(m);
        }
    }
}



Python: import inspect


class Super(object):
  def __init__(self, name):
    self.name = name
  
  def __str__(self):
    return "Super(%s)" % (self.name,)
  
  def doSup(self):
    return 'did super stuff'
  
  @classmethod
  def cls(cls):
    return 'cls method (in sup)'
  
  @classmethod
  def supCls(cls):
    return 'Super method'
  
  @staticmethod
  def supStatic():
    return 'static method'

class Other(object):
  def otherMethod(self):
    return 'other method'

class Sub(Other, Super):
  def __init__(self, name, *args):
    super(Sub, self).__init__(name);
    self.rest = args;
    self.methods = {}
  
  def __dir__(self):
    return list(set( \
        sum([dir(base) for base in type(self).__bases__], []) \
        + type(self).__dict__.keys() \
        + self.__dict__.keys() \
        + self.methods.keys() \
      ))
  
  def __getattr__(self, name):
    if name in self.methods:
      if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
        if self.methods[name].__code__.co_varnames[0] == 'self':
          return self.methods[name].__get__(self, type(self))
        if self.methods[name].__code__.co_varnames[0] == 'cls':
          return self.methods[name].__get__(type(self), type)
      return self.methods[name]
    raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
  
  def __str__(self):
    return "Sub(%s)" % self.name
  
  def doSub():
    return 'did sub stuff'
  
  @classmethod
  def cls(cls):
    return 'cls method (in Sub)'
  
  @classmethod
  def subCls(cls):
    return 'Sub method'
  
  @staticmethod
  def subStatic():
    return 'Sub method'

sup = Super('sup')
sub = Sub('sub', 0, 'I', 'two')
sub.methods['incr'] = lambda x: x+1
sub.methods['strs'] = lambda self, x: str(self) * x


[method for method in dir(sub) if callable(getattr(sub, method))]

[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]


[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]


[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]



inspect.getmembers(sub, predicate=inspect.ismethod)

map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
Task: Comments





Java: 
Int i = 0;     



Python: 

var x = 0 

var y = 0 


There are also multi-line comments
Everything inside of 
]



discard
Task: Send an unknown method call





Java: import java.lang.reflect.Method;

class Example {
  public int foo(int x) {
    return 42 + x;
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    Object example = new Example();
    String name = "foo";
    Class<?> clazz = example.getClass();
    Method meth = clazz.getMethod(name, int.class);
    Object result = meth.invoke(example, 5); 
    System.out.println(result);        
  }
}



Python: class Example(object):
     def foo(self, x):
             return 42 + x

name = "foo"
getattr(Example(), name)(5)
Task: Variables





Java: int a;
double b;
AClassNameHere c;



Python: 
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"


example1 = "goodbye"