WeixiangYan/CodeTransOcean huggingface dataset:
Task: Longest increasing subsequence





Java: import java.util.*;

public class LIS {
    public static <E extends Comparable<? super E>> List<E> lis(List<E> n) {
        List<Node<E>> pileTops = new ArrayList<Node<E>>();
        
        for (E x : n) {
	    Node<E> node = new Node<E>();
	    node.value = x;
            int i = Collections.binarySearch(pileTops, node);
            if (i < 0) i = ~i;
	    if (i != 0)
		node.pointer = pileTops.get(i-1);
            if (i != pileTops.size())
                pileTops.set(i, node);
            else
                pileTops.add(node);
        }
	
	List<E> result = new ArrayList<E>();
	for (Node<E> node = pileTops.size() == 0 ? null : pileTops.get(pileTops.size()-1);
                node != null; node = node.pointer)
	    result.add(node.value);
	Collections.reverse(result);
	return result;
    }

    private static class Node<E extends Comparable<? super E>> implements Comparable<Node<E>> {
	public E value;
	public Node<E> pointer;
        public int compareTo(Node<E> y) { return value.compareTo(y.value); }
    }

    public static void main(String[] args) {
	List<Integer> d = Arrays.asList(3,2,6,4,5,1);
	System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
        d = Arrays.asList(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15);
	System.out.printf("an L.I.S. of %s is %s\n", d, lis(d));
    }
}


PHP: <?php
class Node {
    public $val;
    public $back = NULL;
}

function lis($n) {
    $pileTops = array();

    foreach ($n as $x) {

        $low = 0; $high = count($pileTops)-1;
        while ($low <= $high) {
            $mid = (int)(($low + $high) / 2);
            if ($pileTops[$mid]->val >= $x)
                $high = $mid - 1;
            else
                $low = $mid + 1;
        }
        $i = $low;
        $node = new Node();
        $node->val = $x;
        if ($i != 0)
            $node->back = $pileTops[$i-1];
        $pileTops[$i] = $node;
    }
    $result = array();
    for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
         $node != NULL; $node = $node->back)
        $result[] = $node->val;

    return array_reverse($result);
}

print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>
Task: Self-describing numbers





Java: public class SelfDescribingNumbers{
    public static boolean isSelfDescribing(int a){
        String s = Integer.toString(a);
        for(int i = 0; i < s.length(); i++){
            String s0 = s.charAt(i) + "";
            int b = Integer.parseInt(s0); 
            int count = 0;
            for(int j = 0; j < s.length(); j++){
                int temp = Integer.parseInt(s.charAt(j) + "");
                if(temp == i){
                    count++;
                }
                if (count > b) return false;
            }
            if(count != b) return false;
        }
        return true;
    }

    public static void main(String[] args){
        for(int i = 0; i < 100000000; i++){
            if(isSelfDescribing(i)){
                System.out.println(i);
             }
        }
    }
}


PHP: <?php

function is_describing($number) {
    foreach (str_split((int) $number) as $place => $value) {
        if (substr_count($number, $place) != $value) { 
            return false;
        }
    }    
    return true;
}

for ($i = 0; $i <= 50000000; $i += 10) {
    if (is_describing($i)) {
        echo $i . PHP_EOL;
    }
}

?>
Task: Modular inverse





Java: System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017)));


PHP: <?php
function invmod($a,$n){
        if ($n < 0) $n = -$n;
        if ($a < 0) $a = $n - (-$a % $n);
	$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
	while ($nr != 0) {
		$quot= intval($r/$nr);
		$tmp = $nt;  $nt = $t - $quot*$nt;  $t = $tmp;
		$tmp = $nr;  $nr = $r - $quot*$nr;  $r = $tmp;
	}
	if ($r > 1) return -1;
	if ($t < 0) $t += $n;
	return $t;
}
	printf("%d\n", invmod(42, 2017));
?>
Task: Hello world_Web server





Java: import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HelloWorld{
  public static void main(String[] args) throws IOException{
    ServerSocket listener = new ServerSocket(8080);
    while(true){
      Socket sock = listener.accept();
      new PrintWriter(sock.getOutputStream(), true).
                println("Goodbye, World!");
      sock.close();
    }
  }
}


PHP: <?php

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');

socket_bind($socket, 0,                                        8080);
socket_listen($socket);

$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';

for (;;) {

    if ($client = @socket_accept($socket)) {
        socket_write($client, "HTTP/1.1 200 OK\r\n" .
               "Content-length: " . strlen($msg) . "\r\n" .
               "Content-Type: text/html; charset=UTF-8\r\n\r\n" .
               $msg);
    }
    else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?>
Task: Active Directory_Connect





Java: import java.io.IOException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;

public class LdapConnectionDemo {

    public static void main(String[] args) throws LdapException, IOException {
        try (LdapConnection connection = new LdapNetworkConnection("localhost", 10389)) {
            connection.bind();
            connection.unBind();
        }
    }
}


PHP: <?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password);
Task: Literals_Floating point





Java: 1. 
1.0 
2432311.7567374 
1.234E-10 
1.234e-10 
758832d 
728832f 
1.0f 
758832D 
728832F 
1.0F 
1 / 2. 
1 / 2 


PHP: .12
0.1234
1.2e3
7E-10
Task: Church numerals





Java: package lvijay;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

public class Church {
    public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
    }

    public static ChurchNum zero() {
        return f -> x -> x;
    }

    public static ChurchNum next(ChurchNum n) {
        return f -> x -> f.apply(n.apply(f).apply(x));
    }

    public static ChurchNum plus(ChurchNum a) {
        return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
    }

    public static ChurchNum pow(ChurchNum m) {
        return n -> m.apply(n);
    }

    public static ChurchNum mult(ChurchNum a) {
        return b -> f -> x -> b.apply(a.apply(f)).apply(x);
    }

    public static ChurchNum toChurchNum(int n) {
        if (n <= 0) {
            return zero();
        }
        return next(toChurchNum(n - 1));
    }

    public static int toInt(ChurchNum c) {
        AtomicInteger counter = new AtomicInteger(0);
        ChurchNum funCounter = f -> {
            counter.incrementAndGet();
            return f;
        };

        plus(zero()).apply(c).apply(funCounter).apply(x -> x);

        return counter.get();
    }

    public static void main(String[] args) {
        ChurchNum zero  = zero();
        ChurchNum three = next(next(next(zero)));
        ChurchNum four  = next(next(next(next(zero))));

        System.out.println("3+4=" + toInt(plus(three).apply(four))); 
        System.out.println("4+3=" + toInt(plus(four).apply(three))); 

        System.out.println("3*4=" + toInt(mult(three).apply(four))); 
        System.out.println("4*3=" + toInt(mult(four).apply(three))); 

        
        System.out.println("3^4=" + toInt(pow(four).apply(three))); 
        System.out.println("4^3=" + toInt(pow(three).apply(four))); 

        System.out.println("  8=" + toInt(toChurchNum(8))); 
    }
}


PHP: <?php
$zero = function($f) { return function ($x) { return $x; }; };

$succ = function($n) { 
  return function($f) use (&$n) { 
    return function($x) use (&$n, &$f) {
      return $f( ($n($f))($x) );
    };
  };
};

$add = function($n, $m) {
  return function($f) use (&$n, &$m) {
    return function($x) use (&$f, &$n, &$m) {
      return ($m($f))(($n($f))($x));
    };
  };
};

$mult = function($n, $m) {
  return function($f) use (&$n, &$m) {
    return function($x) use (&$f, &$n, &$m) {
      return ($m($n($f)))($x);
    };
  };
};

$power = function($b,$e) {
  return $e($b);
};

$to_int = function($f) {
  $count_up = function($i) { return $i+1; };
  return ($f($count_up))(0);
};

$from_int = function($x) {
  $countdown = function($i) use (&$countdown) { 
    global $zero, $succ;
    if ( $i == 0 ) {
      return $zero;
    } else {
      return $succ($countdown($i-1));
    };
  };
  return $countdown($x);
};

$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
	       $power($three,$four), $power($four,$three)) as $ch) {
  print($to_int($ch));
  print("\n");
}
?>
Task: Break OO privacy





Java: module BreakOO
    {
    
    class Exposed
        {
        public    String pub = "public";
        protected String pro = "protected";
        private   String pri = "private";

        @Override
        String toString()
            {
            return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
            }
        }

    void run()
        {
        @Inject Console console;

        Exposed expo = new Exposed();
        console.print($"before: {expo}");

        
        expo.pub = $"this was {expo.pub}";
     
     

        
        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
        expoPro.pro = $"this was {expoPro.pro}";
     

        
        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
        expoPri.pri = $"this was {expoPri.pri}";

        
        
        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
        expoStr.pub = $"{expoStr.pub}!!!";
        expoStr.pro = $"{expoStr.pro}!!!";
        expoStr.pri = $"{expoStr.pri}!!!";

        console.print($"after: {expo}");
        }
    }


PHP: <?php
class SimpleClass {
    private $answer = "hello\"world\nforever :)";
}
 
$class = new SimpleClass;
ob_start();



var_export($class);
$class_content = ob_get_clean();
 
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);

$new_class = eval($class_content);
echo $new_class['answer'];
Task: Object serialization





Java: import java.io.*;


class Entity implements Serializable {
    
    
    static final long serialVersionUID = 3504465751164822571L;
    String name = "Entity";
    public String toString() { return name; }
}

class Person extends Entity implements Serializable {
    static final long serialVersionUID = -9170445713373959735L;
    Person() { name = "Cletus"; }
}

public class SerializationTest {
    public static void main(String[] args) {
        Person instance1 = new Person();
        System.out.println(instance1);

        Entity instance2 = new Entity();
        System.out.println(instance2);

        
        try {
            ObjectOutput out = new ObjectOutputStream(new FileOutputStream("objects.dat")); 

            out.writeObject(instance1); 
            out.writeObject(instance2);
            out.close();
            System.out.println("Serialized...");
        } catch (IOException e) {
            System.err.println("Something screwed up while serializing");
            e.printStackTrace();
            System.exit(1);
        }

        
        try {
            ObjectInput in = new ObjectInputStream(new FileInputStream("objects.dat")); 

            Object readObject1 = in.readObject(); 
            Object readObject2 = in.readObject(); 
            in.close();
            System.out.println("Deserialized...");

            System.out.println(readObject1);
            System.out.println(readObject2);
        } catch (IOException e) {
            System.err.println("Something screwed up while deserializing");
            e.printStackTrace();
            System.exit(1);
        } catch (ClassNotFoundException e) {
            System.err.println("Unknown class for deserialized object");
            e.printStackTrace();
            System.exit(1);
        }
    }
}


PHP: $myObj = new Object();
$serializedObj = serialize($myObj);
Task: Long year





Java: import java.time.LocalDate;
import java.time.temporal.WeekFields;

public class LongYear {

    public static void main(String[] args) {
        System.out.printf("Long years this century:%n");
        for (int year = 2000 ; year < 2100 ; year++ ) {
            if ( longYear(year) ) {
                System.out.print(year + "  ");
            }
        }
    }
    
    private static boolean longYear(int year) {
        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;
    }

}


PHP: function isLongYear($year) {
  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}

for ($y=1995; $y<=2045; ++$y) {
  if (isLongYear($y)) {
    printf("%s\n", $y);
  }
}
Task: Associative array_Merging





Java: import java.util.*;

class MergeMaps {
    public static void main(String[] args) {
        Map<String, Object> base = new HashMap<>();
        base.put("name", "Rocket Skates");
        base.put("price", 12.75);
        base.put("color", "yellow");
        Map<String, Object> update = new HashMap<>();
        update.put("price", 15.25);
        update.put("color", "red");
        update.put("year", 1974);

        Map<String, Object> result = new HashMap<>(base);
        result.putAll(update);

        System.out.println(result);
    }
}


PHP: <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);

$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
Task: Associative array_Iteration





Java: Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);


for (Map.Entry<String, Integer> e : map.entrySet()) {
    String key = e.getKey();
    Integer value = e.getValue();
    System.out.println("key = " + key + ", value = " + value);
}


for (String key : map.keySet()) {
    System.out.println("key = " + key);
}


for (Integer value : map.values()) {
    System.out.println("value = " + value);
}


PHP: <?php
$pairs = array( "hello" => 1,
		"world" => 2,
		"!"     => 3 );

foreach($pairs as $k => $v) {
  echo "(k,v) = ($k, $v)\n";
}

foreach(array_keys($pairs) as $key) {
  echo "key = $key, value = $pairs[$key]\n";
}

foreach($pairs as $value) {
  echo "values = $value\n";
}
?>
Task: Here document





Java: package rosettacode.heredoc;
public class MainApp {
	public static void main(String[] args) {
		String hereDoc = """
				This is a multiline string.
				It includes all of this text,
				but on separate lines in the code.
				 """;
		System.out.println(hereDoc);
	}
}


PHP: $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
Task: Hash join





Java: import java.util.*;

public class HashJoin {

    public static void main(String[] args) {
        String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
        {"18", "Popeye"}, {"28", "Alan"}};

        String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
        {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
        {"Bob", "foo"}};

        hashJoin(table1, 1, table2, 0).stream()
                .forEach(r -> System.out.println(Arrays.deepToString(r)));
    }

    static List<String[][]> hashJoin(String[][] records1, int idx1,
            String[][] records2, int idx2) {

        List<String[][]> result = new ArrayList<>();
        Map<String, List<String[]>> map = new HashMap<>();

        for (String[] record : records1) {
            List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
            v.add(record);
            map.put(record[idx1], v);
        }

        for (String[] record : records2) {
            List<String[]> lst = map.get(record[idx2]);
            if (lst != null) {
                lst.stream().forEach(r -> {
                    result.add(new String[][]{r, record});
                });
            }
        }

        return result;
    }
}


PHP: <?php
function hashJoin($table1, $index1, $table2, $index2) {

    foreach ($table1 as $s)
        $h[$s[$index1]][] = $s;

    foreach ($table2 as $r)
    	foreach ($h[$r[$index2]] as $s)
	    $result[] = array($s, $r);
    return $result;
}

$table1 = array(array(27, "Jonah"),
           array(18, "Alan"),
           array(28, "Glory"),
           array(18, "Popeye"),
           array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
           array("Jonah", "Spiders"),
           array("Alan", "Ghosts"),
           array("Alan", "Zombies"),
           array("Glory", "Buffy"),
           array("Bob", "foo"));

foreach (hashJoin($table1, 1, $table2, 0) as $row)
    print_r($row);
?>
Task: Inheritance_Single





Java: public class Animal{
   
}


PHP: class Animal {

}

class Dog extends Animal {

}

class Cat extends Animal {

}

class Lab extends Dog {

}

class Collie extends Dog {

}
Task: Associative array_Creation





Java: Map<String, Int> map = new HashMap();
map["foo"] = 5;      
map["bar"] = 10;
map["baz"] = 15;
map["foo"] = 6;      


PHP: $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';

echo($array['foo']); // bar
echo($array['moo']); // Undefined index

$array2 = array('fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green');

$array2 = ['fruit' => 'apple',
                'price' => 12.96,
                'colour' => 'green'];

echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
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();     
  }
}


PHP: class Point
{
  protected $_x;

  protected $_y;
  
  public function __construct()
  {
    switch( func_num_args() )
    {
      case 1:
        $point = func_get_arg( 0 );
        $this->setFromPoint( $point );
        break;
      case 2:
        $x = func_get_arg( 0 );
        $y = func_get_arg( 1 );
        $this->setX( $x );
        $this->setY( $y );
        break;
      default:
        throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
    }
  }
  
  public function setFromPoint( Point $point )
  {
    $this->setX( $point->getX() );
    $this->setY( $point->getY() );
  }
  
  public function getX()
  {
    return $this->_x;
  }
  
  public function setX( $x )
  {
    if( !is_numeric( $x ) )
    {
      throw new InvalidArgumentException( 'expecting numeric value' );
    }
    
    $this->_x = (float) $x;
  }
  
  public function getY()
  {
    return $this->_y;
  }
  
  public function setY( $y )
  {
    if( !is_numeric( $y ) )
    {
      throw new InvalidArgumentException( 'expecting numeric value' );
    }
    
    $this->_y = (float) $y;
  }
  
  public function output()
  {
    echo $this->__toString();
  }
  
  public function __toString()
  {
    return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
  }
}
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));
        }
    }
}


PHP: <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;

var_dump(get_object_vars($obj));
?>
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);
        }
    }
}


PHP: <?php

$urls = array(
    'foo://example.com:8042/over/there?name=ferret#nose',
    'urn:example:animal:ferret:nose',
    'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true',
    'ftp://ftp.is.co.za/rfc/rfc1808.txt',
    'http://www.ietf.org/rfc/rfc2396.txt#header1',
    'ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two',
    'mailto:John.Doe@example.com',
    'news:comp.infosystems.www.servers.unix',
    'tel:+1-816-555-1212',
    'telnet://192.0.2.16:80/',
    'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
);

foreach ($urls AS $url) {
    $p = parse_url($url);
    echo $url, PHP_EOL;
    print_r($p);
    echo PHP_EOL;
}
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));
}


PHP: <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>