WeixiangYan/CodeTransOcean huggingface dataset:
Task: Mian-Chowla sequence





Java: import java.util.Arrays;

public class MianChowlaSequence {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println("First 30 terms of the Mian–Chowla sequence.");
        mianChowla(1, 30);
        System.out.println("Terms 91 through 100 of the Mian–Chowla sequence.");
        mianChowla(91, 100);
        long end = System.currentTimeMillis();
        System.out.printf("Elapsed = %d ms%n", (end-start));
    }

    private static void mianChowla(int minIndex, int maxIndex) {
        int [] sums = new int[1];
        int [] chowla = new int[maxIndex+1];
        sums[0] = 2;
        chowla[0] = 0;
        chowla[1] = 1;
        if ( minIndex == 1 ) {
            System.out.printf("%d ", 1);
        }
        int chowlaLength = 1;
        for ( int n = 2 ; n <= maxIndex ; n++ ) {

            
            int test = chowla[n - 1];
            
            int[] sumsNew = Arrays.copyOf(sums, sums.length + n);
            int sumNewLength = sums.length;
            int savedsSumNewLength = sumNewLength;
            
            
            boolean found = false;
            while ( ! found ) {
                test++;
                found = true;
                sumNewLength = savedsSumNewLength;
                
                for ( int j = 0 ; j <= chowlaLength ; j++ ) {
                    int testSum = (j == 0 ? test : chowla[j]) + test;
                    boolean duplicate = false;
                    
                    
                    for ( int k = 0 ; k < sumNewLength ; k++ ) {
                        if ( sumsNew[k] == testSum ) {
                            duplicate = true;
                            break;
                        }
                    }
                    if ( ! duplicate ) {
                        
                        sumsNew[sumNewLength] = testSum;
                        sumNewLength++;
                    }
                    else {
                        
                        found = false;
                        break;
                    }
                }
            }
            
            
            chowla[n] = test;
            chowlaLength++;            
            sums = sumsNew;
            if ( n >= minIndex ) {
                System.out.printf("%d %s", chowla[n], (n==maxIndex ? "\n" : ""));
            }
        }
    }

}
Task: Water collected between towers





Java: public class WaterBetweenTowers {
    public static void main(String[] args) {
        int i = 1;
        int[][] tba = new int[][]{
            new int[]{1, 5, 3, 7, 2},
            new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2},
            new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1},
            new int[]{5, 5, 5, 5},
            new int[]{5, 6, 7, 8},
            new int[]{8, 7, 7, 6},
            new int[]{6, 7, 10, 7, 6}
        };

        for (int[] tea : tba) {
            int rht, wu = 0, bof;
            do {
                for (rht = tea.length - 1; rht >= 0; rht--) {
                    if (tea[rht] > 0) {
                        break;
                    }
                }

                if (rht < 0) {
                    break;
                }

                bof = 0;
                for (int col = 0; col <= rht; col++) {
                    if (tea[col] > 0) {
                        tea[col]--;
                        bof += 1;
                    } else if (bof > 0) {
                        wu++;
                    }
                }
                if (bof < 2) {
                    break;
                }
            } while (true);

            System.out.printf("Block %d", i++);
            if (wu == 0) {
                System.out.print(" does not hold any");
            } else {
                System.out.printf(" holds %d", wu);
            }
            System.out.println(" water units.");
        }
    }
}
Task: FASTA format





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

public class ReadFastaFile {

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

        boolean first = true;

        try (Scanner sc = new Scanner(new File("test.fasta"))) {
            while (sc.hasNextLine()) {
                String line = sc.nextLine().trim();
                if (line.charAt(0) == '>') {
                    if (first)
                        first = false;
                    else
                        System.out.println();
                    System.out.printf("%s: ", line.substring(1));
                } else {
                    System.out.print(line);
                }
            }
        }
        System.out.println();
    }
}
Task: MAC vendor lookup





Java: package com.jamesdonnell.MACVendor;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class Lookup {
	
	private static final String baseURL = "http:

	
	public static void main(String[] args) {
		for (String arguments : args)
			System.out.println(arguments + ": " + get(arguments));
	}

	
	private static String get(String macAddress) {
		try {
			StringBuilder result = new StringBuilder();
			URL url = new URL(baseURL + macAddress);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				result.append(line);
			}
			rd.close();
			return result.toString();
		} catch (FileNotFoundException e) {
			
			return "N/A";
		} catch (IOException e) {
			
			return null;
		}
	}
}
Task: Magic 8-ball





Java: import java.util.Random;
import java.util.Scanner;

public class MagicEightBall {

    public static void main(String[] args) {
        new MagicEightBall().run();
    }
    
    private static String[] ANSWERS = new String[] {"It is certain.", "It is decidedly so.", "Without a doubt.", "Yes - definitely.",
            "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
            "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
            "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful. "};

    public void run() {
        Random random = new Random();
        System.out.printf("Hello.  The Magic 8 Ball knows all.  Type your question.%n%n");
        try ( Scanner in = new Scanner(System.in); ) {
            System.out.printf("?  ");
            while ( (in.nextLine()).length() > 0 ) {
                System.out.printf("8 Ball Response:  %s%n", ANSWERS[random.nextInt(ANSWERS.length)]);
                System.out.printf("?  ");
            }
        }
        System.out.printf("%n8 Ball Done.  Bye.");
    }
}
Task: Validate International Securities Identification Number





Java: public class ISIN {
 
    public static void main(String[] args) {
        String[] isins = {
            "US0378331005", 
            "US0373831005", 
            "U50378331005", 
            "US03378331005",
            "AU0000XVGZA3", 
            "AU0000VXGZA3", 
            "FR0000988040"
        };
        for (String isin : isins)
            System.out.printf("%s is %s\n", isin, ISINtest(isin) ? "valid" : "not valid");
    }
 
    static boolean ISINtest(String isin) {
        isin = isin.trim().toUpperCase();
 
        if (!isin.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$"))
            return false;
 
        StringBuilder sb = new StringBuilder();
        for (char c : isin.substring(0, 12).toCharArray())
            sb.append(Character.digit(c, 36));
 
        return luhnTest(sb.toString());
    }

    static boolean luhnTest(String number) {
        int s1 = 0, s2 = 0;
        String reverse = new StringBuffer(number).reverse().toString();
        for (int i = 0; i < reverse.length(); i++){
            int digit = Character.digit(reverse.charAt(i), 10);
            
            if (i % 2 == 0){
                s1 += digit;
            } else { 
                s2 += 2 * digit;
                if(digit >= 5){
                    s2 -= 9;
                }
            }
        }
        return (s1 + s2) % 10 == 0;
    }
}
Task: Orbital elements





Java: public class OrbitalElements {
    private static class Vector {
        private double x, y, z;
 
        public Vector(double x, double y, double z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }
 
        public Vector plus(Vector rhs) {
            return new Vector(x + rhs.x, y + rhs.y, z + rhs.z);
        }
 
        public Vector times(double s) {
            return new Vector(s * x, s * y, s * z);
        }
 
        public Vector div(double d) {
            return new Vector(x / d, y / d, z / d);
        }
 
        public double abs() {
            return Math.sqrt(x * x + y * y + z * z);
        }
 
        @Override
        public String toString() {
            return String.format("(%.16f, %.16f, %.16f)", x, y, z);
        }
    }
 
    private static Vector mulAdd(Vector v1, Double x1, Vector v2, Double x2) {
        return v1.times(x1).plus(v2.times(x2));
    }
 
    private static Vector[] rotate(Vector i, Vector j, double alpha) {
        return new Vector[]{
            mulAdd(i, Math.cos(alpha), j, Math.sin(alpha)),
            mulAdd(i, -Math.sin(alpha), j, Math.cos(alpha))
        };
    }
 
    private static Vector[] orbitalStateVectors(
        double semimajorAxis, double eccentricity, 
        double inclination, double longitudeOfAscendingNode, 
        double argumentOfPeriapsis, double trueAnomaly
    ) {
        Vector i = new Vector(1, 0, 0);
        Vector j = new Vector(0, 1, 0);
        Vector k = new Vector(0, 0, 1);
 
        Vector[] p = rotate(i, j, longitudeOfAscendingNode);
        i = p[0];
        j = p[1];
        p = rotate(j, k, inclination);
        j = p[0];
        p = rotate(i, j, argumentOfPeriapsis);
        i = p[0];
        j = p[1];
 
        double l = (eccentricity == 1.0) ? 2.0 : 1.0 - eccentricity * eccentricity;
        l *= semimajorAxis;
        double c = Math.cos(trueAnomaly);
        double s = Math.sin(trueAnomaly);
        double r = l / (1.0 + eccentricity * c);
        double rprime = s * r * r / l;
        Vector position = mulAdd(i, c, j, s).times(r);
        Vector speed = mulAdd(i, rprime * c - r * s, j, rprime * s + r * c);
        speed = speed.div(speed.abs());
        speed = speed.times(Math.sqrt(2.0 / r - 1.0 / semimajorAxis));
 
        return new Vector[]{position, speed};
    }
 
    public static void main(String[] args) {
        Vector[] ps = orbitalStateVectors(1.0, 0.1, 0.0, 355.0 / (113.0 * 6.0), 0.0, 0.0);
        System.out.printf("Position : %s\n", ps[0]);
        System.out.printf("Speed : %s\n", ps[1]);
    }
}
Task: Cycle detection





Java: import java.util.function.*;
import static java.util.stream.IntStream.*;

public class CycleDetection {

    public static void main(String[] args) {
        brent(i -> (i * i + 1) % 255, 3);
    }

    static void brent(IntUnaryOperator f, int x0) {
        int cycleLength;
        int hare = x0;
        FOUND:
        for (int power = 1; ; power *= 2) {
            int tortoise = hare;
            for (int i = 1; i <= power; i++) {
                hare = f.applyAsInt(hare);
                 if (tortoise == hare) {
                    cycleLength = i;
                    break FOUND;
                }
            }
        }

        hare = x0;
        for (int i = 0; i < cycleLength; i++)
            hare = f.applyAsInt(hare);

        int cycleStart = 0;
        for (int tortoise = x0; tortoise != hare; cycleStart++) {
            tortoise = f.applyAsInt(tortoise);
            hare = f.applyAsInt(hare);
        }

        printResult(x0, f, cycleLength, cycleStart);
    }

    static void printResult(int x0, IntUnaryOperator f, int len, int start) {
        System.out.printf("Cycle length: %d%nCycle: ", len);
        iterate(x0, f).skip(start).limit(len)
                .forEach(n -> System.out.printf("%s ", n));
    }
}
Task: Input_Output for pairs of numbers





Java: import java.util.Scanner;

public class Main {

	public static int doStuff(int a, int b){
	    int sum = a+b;
	    return sum;
	}

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

		int n = in.nextInt();
		for(int i=0; i<n; i++){
			int a = in.nextInt();
			int b= in.nextInt();
			int result = doStuff(a, b);
			System.out.println(result);
		}
	}
}
Task: Kahan summation





Java: public class KahanSummation {
    private static float kahanSum(float... fa) {
        float sum = 0.0f;
        float c = 0.0f;
        for (float f : fa) {
            float y = f - c;
            float t = sum + y;
            c = (t - sum) - y;
            sum = t;
        }
        return sum;
    }

    private static float epsilon() {
        float eps = 1.0f;
        while (1.0f + eps != 1.0f) eps /= 2.0f;
        return eps;
    }

    public static void main(String[] args) {
        float a = 1.0f;
        float b = epsilon();
        float c = -b;
        System.out.println("Epsilon      = " + b);
        System.out.println("(a + b) + c  = " + ((a + b) + c));
        System.out.println("Kahan sum    = " + kahanSum(a, b, c));
    }
}
Task: ABC words





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

public class AbcWords {
    public static void main(String[] args) {
        String fileName = "unixdict.txt";
        String chars = "abc";
        for (int i = 0; i + 1 < args.length
                && args[i].length() > 1
                && args[i].charAt(0) == '-'; ++i) {
            switch (args[i].charAt(1)) {
            case 'f':
                fileName = args[++i];
                break;
            case 'c':
                chars = args[++i];
                break;
            }
        }
        
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            int n = 0;
            while ((line = reader.readLine()) != null) {
                if (match(line, chars)) {
                    ++n;
                    System.out.printf("%3d: %-20s", n, line);
                    if (n % 3 == 0)
                        System.out.println();
                }
            }
            if (n > 0 && n % 3 != 0)
                System.out.println();
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }

    
    
    private static boolean match(String word, String chars) {
        int length = chars.length();
        boolean[] seen = new boolean[length];
        int wordLength = word.length();
        for (int w = 0; w < wordLength; ++w) {
            char ch = word.charAt(w);
            int index = -1;
            for (int c = 0; c < length; ++c) {
                if (ch == chars.charAt(c) && !seen[c]) {
                    index = c;
                    break;
                }
            }
            if (index == -1)
                continue;
            if (index + 1 == length)
                return index == 0 ? true : seen[index - 1];
            if (index > 0 && !seen[index - 1])
                return false;
            seen[index] = true;
        }
        return false;
    }
}
Task: Text between





Java: public class textBetween
{
    
    static String textBetween(String thisText, String startString, String endString)
    {
    	String returnText = "";
    	int startIndex = 0;
    	int endIndex = 0;
    	
    	if (startString.equals("start"))
    	{
    		startIndex = 0;
    	} else {
	    	startIndex = thisText.indexOf(startString);
	    	
	    	if (startIndex < 0) 
	        {
	        	return "";	        	
	        } else {
	        	startIndex = startIndex + startString.length();
	        }
    	}
        
    	if (endString.equals("end"))
    	{
    		endIndex = thisText.length();
    	} else {
    		endIndex = thisText.indexOf(endString);
            
            if (endIndex <= 0) 
            {
            	return "";
            } else {

            }	
    	}
    	
    	returnText = thisText.substring(startIndex,endIndex);
    	
    	return returnText;
    } 

    
    public static void main(String[] args)
    {
    	String thisText = args[0];
    	String startDelimiter = args[1];
    	String endDelimiter = args[2];
    	
    	String returnText = "";
    	returnText = textBetween(thisText, startDelimiter, endDelimiter);
    	
        System.out.println(returnText);

    } 
    
}
Task: Two identical strings





Java: public class TwoIdenticalStrings {
    public static void main(String[] args) {
        System.out.println("Decimal Binary");
        for (int i = 0; i < 1_000; i++) {
            String binStr = Integer.toBinaryString(i);
            if (binStr.length() % 2 == 0) {
                int len = binStr.length() / 2;
                if (binStr.substring(0, len).equals(binStr.substring(len))) {
                    System.out.printf("%7d %s%n", i, binStr);
                }
            }
        }
    }
}
Task: Pentagram





Java: import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;

public class Pentagram extends JPanel {

    final double degrees144 = Math.toRadians(144);

    public Pentagram() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);
    }

    private void drawPentagram(Graphics2D g, int len, int x, int y,
            Color fill, Color stroke) {
        double angle = 0;

        Path2D p = new Path2D.Float();
        p.moveTo(x, y);

        for (int i = 0; i < 5; i++) {
            int x2 = x + (int) (Math.cos(angle) * len);
            int y2 = y + (int) (Math.sin(-angle) * len);
            p.lineTo(x2, y2);
            x = x2;
            y = y2;
            angle -= degrees144;
        }
        p.closePath();

        g.setColor(fill);
        g.fill(p);

        g.setColor(stroke);
        g.draw(p);
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g.setStroke(new BasicStroke(5, BasicStroke.CAP_ROUND, 0));

        drawPentagram(g, 500, 70, 250, new Color(0x6495ED), Color.darkGray);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Pentagram");
            f.setResizable(false);
            f.add(new Pentagram(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}
Task: Verify distribution uniformity_Chi-squared test





Java: import static java.lang.Math.pow;
import java.util.Arrays;
import static java.util.Arrays.stream;
import org.apache.commons.math3.special.Gamma;

public class Test {

    static double x2Dist(double[] data) {
        double avg = stream(data).sum() / data.length;
        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));
        return sqs / avg;
    }

    static double x2Prob(double dof, double distance) {
        return Gamma.regularizedGammaQ(dof / 2, distance / 2);
    }

    static boolean x2IsUniform(double[] data, double significance) {
        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;
    }

    public static void main(String[] a) {
        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},
        {522573, 244456, 139979, 71531, 21461}};

        System.out.printf(" %4s %12s  %12s %8s   %s%n",
                "dof", "distance", "probability", "Uniform?", "dataset");

        for (double[] ds : dataSets) {
            int dof = ds.length - 1;
            double dist = x2Dist(ds);
            double prob = x2Prob(dof, dist);
            System.out.printf("%4d %12.3f  %12.8f    %5s    %6s%n",
                    dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO",
                    Arrays.toString(ds));
        }
    }
}
Task: CSV to HTML translation





Java: 

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





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

public class AlternadeWords {
    public static void main(String[] args) {
        try {
            Set<String> dictionary = new TreeSet<>();
            try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
                String line;
                while ((line = reader.readLine()) != null)
                    dictionary.add(line);
            }
            StringBuilder word1 = new StringBuilder();
            StringBuilder word2 = new StringBuilder();
            for (String word : dictionary) {
                int length = word.length();
                if (length < 6)
                    continue;
                word1.setLength(0);
                word2.setLength(0);
                for (int i = 0; i < length; i += 2) {
                    word1.append(word.charAt(i));
                    if (i + 1 < length)
                        word2.append(word.charAt(i + 1));
                }
                String w1 = word1.toString();
                String w2 = word2.toString();
                if (dictionary.contains(w1) && dictionary.contains(w2))
                    System.out.printf("%-10s%-6s%s\n", word, w1, w2);
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }
}
Task: Pythagorean triples





Java: import java.math.BigInteger;
import static java.math.BigInteger.ONE;

public class PythTrip{

    public static void main(String[] args){
        long tripCount = 0, primCount = 0;

        
        BigInteger periLimit = BigInteger.valueOf(100),
                peri2 = periLimit.divide(BigInteger.valueOf(2)),
                peri3 = periLimit.divide(BigInteger.valueOf(3));

        for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){
            BigInteger aa = a.multiply(a);
            
            for(BigInteger b = a.add(ONE);
                    b.compareTo(peri2) < 0; b = b.add(ONE)){
                BigInteger bb = b.multiply(b);
                BigInteger ab = a.add(b);
                BigInteger aabb = aa.add(bb);
                
                for(BigInteger c = b.add(ONE);
                        c.compareTo(peri2) < 0; c = c.add(ONE)){

                    int compare = aabb.compareTo(c.multiply(c));
                    
                    if(ab.add(c).compareTo(periLimit) > 0){
                        break;
                    }
                    
                    if(compare < 0){
                        break;
                    }else if (compare == 0){
                        tripCount++;
                        System.out.print(a + ", " + b + ", " + c);

                        
                        if(a.gcd(b).equals(ONE)){
                            System.out.print(" primitive");
                            primCount++;
                        }
                        System.out.println();
                    }
                }
            }
        }
        System.out.println("Up to a perimeter of " + periLimit + ", there are "
                + tripCount + " triples, of which " + primCount + " are primitive.");
    }
}
Task: Call a foreign-language function





Java: public class JNIDemo
{
  static
  {  System.loadLibrary("JNIDemo");  }
  
  public static void main(String[] args)
  {
    System.out.println(callStrdup("Hello World!"));
  }
  
  private static native String callStrdup(String s);
}