WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Cycle sort




Go: package main

import (
	"fmt"
	"math/rand"
	"time"
)

func cyclesort(ints []int) int {
	writes := 0

	for cyclestart := 0; cyclestart < len(ints)-1; cyclestart++ {
		item := ints[cyclestart]

		pos := cyclestart

		for i := cyclestart + 1; i < len(ints); i++ {
			if ints[i] < item {
				pos++
			}
		}

		if pos == cyclestart {
			continue
		}

		for item == ints[pos] {
			pos++
		}

		ints[pos], item = item, ints[pos]

		writes++

		for pos != cyclestart {
			pos = cyclestart
			for i := cyclestart + 1; i < len(ints); i++ {
				if ints[i] < item {
					pos++
				}
			}

			for item == ints[pos] {
				pos++
			}

			ints[pos], item = item, ints[pos]
			writes++
		}
	}

	return writes
}

func main() {
	rand.Seed(time.Now().Unix())

	ints := rand.Perm(10)

	fmt.Println(ints)
	fmt.Printf("writes %d\n", cyclesort(ints))
	fmt.Println(ints)
}
Task: Polyspiral



C#: using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Windows.Threading;

namespace Polyspiral
{
    public partial class Form1 : Form
    {
        private double inc;

        public Form1()
        {
            Width = Height = 640;
            StartPosition = FormStartPosition.CenterScreen;
            SetStyle(
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.UserPaint |
                ControlStyles.DoubleBuffer,
                true);

            var timer = new DispatcherTimer();
            timer.Tick += (s, e) => { inc = (inc + 0.05) % 360; Refresh(); };
            timer.Interval = new TimeSpan(0, 0, 0, 0, 40);
            timer.Start();
        }

        private void DrawSpiral(Graphics g, int len, double angleIncrement)
        {
            double x1 = Width / 2;
            double y1 = Height / 2;
            double angle = angleIncrement;

            for (int i = 0; i < 150; i++)
            {
                double x2 = x1 + Math.Cos(angle) * len;
                double y2 = y1 - Math.Sin(angle) * len;
                g.DrawLine(Pens.Blue, (int)x1, (int)y1, (int)x2, (int)y2);
                x1 = x2;
                y1 = y2;

                len += 3;

                angle = (angle + angleIncrement) % (Math.PI * 2);
            }
        }

        protected override void OnPaint(PaintEventArgs args)
        {
            var g = args.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.Clear(Color.White);

            DrawSpiral(g, 5, ToRadians(inc));
        }

        private double ToRadians(double angle)
        {
            return Math.PI * angle / 180.0;
        }
    }
}
Task: Angles (geometric), normalization and conversion



C#: using System;

public static class Angles
{
    public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000);

    public static void Print(params double[] angles) {
        string[] names = { "Degrees", "Gradians", "Mils", "Radians" };
        Func<double, double> rnd = a => Math.Round(a, 4);
        Func<double, double>[] normal = { NormalizeDeg, NormalizeGrad, NormalizeMil, NormalizeRad };

        Func<double, double>[,] convert = {
            { a => a, DegToGrad, DegToMil, DegToRad },
            { GradToDeg, a => a, GradToMil, GradToRad },
            { MilToDeg, MilToGrad, a => a, MilToRad },
            { RadToDeg, RadToGrad, RadToMil, a => a }
        };

        Console.WriteLine($@"{"Angle",-12}{"Normalized",-12}{"Unit",-12}{
            "Degrees",-12}{"Gradians",-12}{"Mils",-12}{"Radians",-12}");

        foreach (double angle in angles) {
            for (int i = 0; i < 4; i++) {
                double nAngle = normal[i](angle);

                Console.WriteLine($@"{
                    rnd(angle),-12}{
                    rnd(nAngle),-12}{
                    names[i],-12}{
                    rnd(convert[i, 0](nAngle)),-12}{
                    rnd(convert[i, 1](nAngle)),-12}{
                    rnd(convert[i, 2](nAngle)),-12}{
                    rnd(convert[i, 3](nAngle)),-12}");
            }
        }
    }

    public static double NormalizeDeg(double angle) => Normalize(angle, 360);
    public static double NormalizeGrad(double angle) => Normalize(angle, 400);
    public static double NormalizeMil(double angle) => Normalize(angle, 6400);
    public static double NormalizeRad(double angle) => Normalize(angle, 2 * Math.PI);

    private static double Normalize(double angle, double N) {
        while (angle <= -N) angle += N;
        while (angle >= N) angle -= N;
        return angle;
    }

    public static double DegToGrad(double angle) => angle * 10 / 9;
    public static double DegToMil(double angle) => angle * 160 / 9;
    public static double DegToRad(double angle) => angle * Math.PI / 180;
    
    public static double GradToDeg(double angle) => angle * 9 / 10;
    public static double GradToMil(double angle) => angle * 16;
    public static double GradToRad(double angle) => angle * Math.PI / 200;
    
    public static double MilToDeg(double angle) => angle * 9 / 160;
    public static double MilToGrad(double angle) => angle / 16;
    public static double MilToRad(double angle) => angle * Math.PI / 3200;
    
    public static double RadToDeg(double angle) => angle * 180 / Math.PI;
    public static double RadToGrad(double angle) => angle * 200 / Math.PI;
    public static double RadToMil(double angle) => angle * 3200 / Math.PI;
}
Task: HTTPS_Authenticated



C#: using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        var client = new WebClient();

        
        client.Credentials = CredentialCache.DefaultCredentials;
        
        client.Credentials = new NetworkCredential("User", "Password");

        var data = client.DownloadString("https:

        Console.WriteLine(data);
    }
}
Task: Naming conventions



C#: public enum Planet {
    Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

[Flags]
public enum Days {
    None = 0,
    Sunday = 1,
    Monday = 2,
    Tuesday = 4,
    Wednesday = 8,
    Thursday = 16,
    Friday = 32,
    Saturday = 64,
    Workdays = Monday | Tuesday | Wednesday | Thursday | Friday
    AllWeek = Sunday | Saturday | Workdays
}
Task: Strong and weak primes



C#: using static System.Console;
using static System.Linq.Enumerable;
using System;

public static class StrongAndWeakPrimes
{
    public static void Main() {
        var primes = PrimeGenerator(10_000_100).ToList();
        var strongPrimes = from i in Range(1, primes.Count - 2) where primes[i] > (primes[i-1] + primes[i+1]) / 2 select primes[i];
        var weakPrimes = from i in Range(1, primes.Count - 2) where primes[i] < (primes[i-1] + primes[i+1]) / 2.0 select primes[i];
        WriteLine($"First 36 strong primes: {string.Join(", ", strongPrimes.Take(36))}");
        WriteLine($"There are {strongPrimes.TakeWhile(p => p < 1_000_000).Count():N0} strong primes below {1_000_000:N0}");
        WriteLine($"There are {strongPrimes.TakeWhile(p => p < 10_000_000).Count():N0} strong primes below {10_000_000:N0}");
        WriteLine($"First 37 weak primes: {string.Join(", ", weakPrimes.Take(37))}");
        WriteLine($"There are {weakPrimes.TakeWhile(p => p < 1_000_000).Count():N0} weak primes below {1_000_000:N0}");
        WriteLine($"There are {weakPrimes.TakeWhile(p => p < 10_000_000).Count():N0} weak primes below {1_000_000:N0}");
    }
   
}
Task: Linux CPU utilization



C#: var prevIdle = 0f;
var prevTotal = 0f;

while (true)
{
    var cpuLine = File
        .ReadAllLines("/proc/stat")
        .First()
        .Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .Skip(1)
        .Select(float.Parse)
        .ToArray();

    var idle = cpuLine[3];
    var total = cpuLine.Sum();

    var percent = 100.0 * (1.0 - (idle - prevIdle) / (total - prevTotal));
    Console.WriteLine($"{percent:0.00}%");

    prevIdle = idle;
    prevTotal = total;

    Thread.Sleep(1000);
}
Task: Speech synthesis



C#: using SpeechLib;

namespace Speaking_Computer
{
  public class Program
  {
    private static void Main()
    {
      var voice = new SpVoice();
      voice.Speak("This is an example of speech synthesis.");
    }
  }
}
Task: Canonicalize CIDR



C#: using System;
using System.Net;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        string[] tests = {
            "87.70.141.1/22",
            "36.18.154.103/12",
            "62.62.197.11/29",
            "67.137.119.181/4",
            "161.214.74.21/24",
            "184.232.176.184/18"
        };
        
        foreach (string t in tests) Console.WriteLine($"{t}   =>   {Canonicalize(t)}");
    }
    
    static string Canonicalize(string cidr) => CIDR.Parse(cidr).Canonicalize().ToString();
}

readonly struct CIDR
{
    public readonly IPAddress ip;
    public readonly int length;
    
    public static CIDR Parse(string cidr)
    {
        string[] parts = cidr.Split('/');
        return new CIDR(IPAddress.Parse(parts[0]), int.Parse(parts[1]));
    }
    
    public CIDR(IPAddress ip, int length) => (this.ip, this.length) = (ip, length);
    
    public CIDR Canonicalize() =>
        new CIDR(
            new IPAddress(
                ToBytes(
                    ToInt(
                        ip.GetAddressBytes()
                    )
                    & ~((1 << (32 - length)) - 1)
                )
            ),
            length
        );
    
    private int ToInt(byte[] bytes) => bytes.Aggregate(0, (n, b) => (n << 8) | b);
    
    private byte[] ToBytes(int n)
    {
        byte[] bytes = new byte[4];
        for (int i = 3; i >= 0; i--) {
            bytes[i] = (byte)(n & 0xFF);
            n >>= 8;
        }
        return bytes;
    }
    
    public override string ToString() => $"{ip}/{length}";
}
Task: Special divisors



C#: using System;

namespace SpecialDivisors {
    class Program {
        static int Reverse(int n) {
            int result = 0;
            while (n > 0) {
                result = 10 * result + n % 10;
                n /= 10;
            }
            return result;
        }

        static void Main() {
            const int LIMIT = 200;

            int row = 0;
            int num = 0;

            for (int n = 1; n < LIMIT; n++) {
                bool flag = true;
                int revNum = Reverse(n);

                for (int m = 1; m < n / 2; m++) {
                    int revDiv = Reverse(m);
                    if (n % m == 0) {
                        if (revNum % revDiv == 0) {
                            flag = true;
                        } else {
                            flag = false;
                            break;
                        }
                    }
                }

                if (flag) {
                    num++;
                    row++;
                    Console.Write("{0,4}", n);
                    if (row % 10 == 0) {
                        Console.WriteLine();
                    }
                }
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Found {0} special divisors N that reverse(D) divides reverse(N) for all divisors D of N, where N < 200", num);
        }
    }
}
Task: Polynomial synthetic division



C#: using System;
using System.Collections.Generic;
using System.Linq;

namespace SyntheticDivision
{
    class Program
    {
        static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor)
        {
            List<int> output = dividend.ToList();
            int normalizer = divisor[0];

            for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++)
            {
                output[i] /= normalizer;

                int coef = output[i];
                if (coef != 0)
                {
                    for (int j = 1; j < divisor.Count(); j++)
                        output[i + j] += -divisor[j] * coef;
                }
            }

            int separator = output.Count() - (divisor.Count() - 1);

            return (
                output.GetRange(0, separator),
                output.GetRange(separator, output.Count() - separator)
            );
        }

        static void Main(string[] args)
        {
            List<int> N = new List<int>{ 1, -12, 0, -42 };
            List<int> D = new List<int> { 1, -3 };

            var (quotient, remainder) = extendedSyntheticDivision(N, D);
            Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" ,
                string.Join(",", N),
                string.Join(",", D),
                string.Join(",", quotient),
                string.Join(",", remainder)
            );
        }
    }
}
Task: Color wheel



C#: 

public MainWindow()
{
    InitializeComponent();
    RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality);
    imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null);
    
    DrawHue(100);
}

void DrawHue(int saturation)
{
    var bmp = (WriteableBitmap)imgMain.Source;

    int centerX = (int)bmp.Width / 2;
    int centerY = (int)bmp.Height / 2;
    int radius = Math.Min(centerX, centerY);
    int radius2 = radius - 40;

    bmp.Lock();
    unsafe{
        var buf = bmp.BackBuffer;
        IntPtr pixLineStart;
        for(int y=0; y < bmp.Height; y++){
            pixLineStart = buf + bmp.BackBufferStride * y;
            double dy = (y - centerY);
            for(int x=0; x < bmp.Width; x++){
                double dx = (x - centerX);
                double dist = Math.Sqrt(dx * dx + dy * dy);
                if (radius2 <= dist && dist <= radius) {
                    double theta = Math.Atan2(dy, dx);
                    double hue = (theta + Math.PI) / (2.0 * Math.PI);
                    *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100);
                }
            }
        }
    }
    bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480));
    bmp.Unlock();
}

static int HSB_to_RGB(int h, int s, int v)
{
    var rgb = new int[3];

    var baseColor = (h + 60) % 360 / 120;
    var shift = (h + 60) % 360 - (120 * baseColor + 60 );
    var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3;

    
    rgb[baseColor] = 255;
    rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f);

    
    for (var i = 0; i < 3; i++)
        rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f));

    
    for (var i = 0; i < 3; i++)
        rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f);

    return RGB2int(rgb[0], rgb[1], rgb[2]);
}

public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
Task: Fibonacci matrix-exponentiation



C#: using System;
using System.IO;
using System.Numerics;
using System.Threading;
using System.Diagnostics;
using System.Globalization;

namespace Fibonacci {
    class Program
    {
        private static readonly BigInteger[,] F = { { BigInteger.One, BigInteger.One }, { BigInteger.One, BigInteger.Zero } };
        private static NumberFormatInfo nfi  = new NumberFormatInfo { NumberGroupSeparator = "_" };
        private static BigInteger[,] Multiply(in BigInteger[,] A, in BigInteger[,] B)
        {
            if (A.GetLength(1) != B.GetLength(0))
            {
                throw new ArgumentException("Illegal matrix dimensions for multiplication.");
            }
            var C = new BigInteger[A.GetLength(0), B.GetLength(1)];
            for (int i = 0; i < A.GetLength(0); ++i)
            {
                for (int j = 0; j < B.GetLength(1); ++j)
                {
                    for (int k = 0; k < A.GetLength(1); ++k)
                    {
                        C[i, j] +=  A[i, k] * B[k, j];
                    }
                }
            }
            return C;
        }
        private static BigInteger[,] Power(in BigInteger[,] A, ulong n)
        {
            if (A.GetLength(1) != A.GetLength(0))
            {
                throw new ArgumentException("Not a square matrix.");
            }
            var C = new BigInteger[A.GetLength(0), A.GetLength(1)];
            for (int i = 0; i < A.GetLength(0); ++i)
            {
                C[i, i] = BigInteger.One;
            }
            if (0 == n) return C;
            var S = new BigInteger[A.GetLength(0), A.GetLength(1)];
            for (int i = 0; i < A.GetLength(0); ++i)
            {
                for (int j = 0; j < A.GetLength(1); ++j)
                {
                    S[i, j] = A[i, j];
                }
            }
            while (0 < n)
            {
                if (1 == n % 2) C = Multiply(C, S);
                S = Multiply(S,S);
                n /= 2;
            }
            return C;
        }
        public static BigInteger Fib(in ulong n)
        {
            var C = Power(F, n);
            return C[0, 1];
        }
        public static void Task(in ulong p)
        {
            var ans = Fib(p).ToString();
            var sp = p.ToString("N0", nfi);
            if (ans.Length <= 40)
            {
                Console.WriteLine("Fibonacci({0}) = {1}", sp, ans);
            }
            else
            {
                Console.WriteLine("Fibonacci({0}) = {1} ... {2}", sp, ans[0..19], ans[^20..]);
            }
        }
        public static void Main()
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            for (ulong p = 10; p <= 10_000_000; p *= 10) {
                Task(p);
            }
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            Console.WriteLine("Took " + elapsedTime);
        }
    }
}
Task: Practical numbers



C#: using System.Collections.Generic; using System.Linq; using static System.Console;

class Program {

    static bool soas(int n, IEnumerable<int> f) {
        if (n <= 0) return false; if (f.Contains(n)) return true;
        switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true;
            case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0);
                return soas(d, rf) || soas(n, rf); } return true; }

    static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList();
        return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f));  }

    static void Main() {
        int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2)
            if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : ""); 
        Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m);
        do Write("\n{0,5} is a{1}practical number.",
            m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
Task: HTTPS_Client-authenticated



C#: using System;
using System.Net;

class Program
{
    class MyWebClient : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.ClientCertificates.Add(new X509Certificate());
            return request;
        }
    }
    static void Main(string[] args)
    {
        var client = new MyWebClient();

        var data = client.DownloadString("https:

        Console.WriteLine(data);
    }
}
Task: SQL-based authentication



C#: using System.Security.Cryptography;
using System.Text;

namespace rosettaMySQL
{
    class Hasher
    {
        private static string _BytesToHex(byte[] input)
        {
            var strBuilder = new StringBuilder();
            foreach (byte _byte in input)
            {
                strBuilder.Append(_byte.ToString("x2"));
            }
            return strBuilder.ToString();
        }

        public static string Hash(string salt, string input)
        {
            using (MD5 md5 = new MD5CryptoServiceProvider())
            {
                var bytes = Encoding.Default.GetBytes(salt + input);
                var data = md5.ComputeHash(bytes);
                return _BytesToHex(data);
            }
        }

        public static string GenSalt()
        {
            using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
            {
                var salt = new byte[16];
                rng.GetBytes(salt);
                return _BytesToHex(salt);
            }
        }
    }
}
Task: Tarjan



C#: using System;
using System.Collections.Generic;

class Node
{
    public int LowLink { get; set; }
    public int Index { get; set; }
    public int N { get; }

    public Node(int n)
    {
        N = n;
        Index = -1;
        LowLink = 0;
    }
}

class Graph
{
    public HashSet<Node> V { get; }
    public Dictionary<Node, HashSet<Node>> Adj { get; }

    
    
    
    public void Tarjan()
    {
        var index = 0; 
        var S = new Stack<Node>();

        Action<Node> StrongConnect = null;
        StrongConnect = (v) =>
        {
            
            v.Index = index;
            v.LowLink = index;

            index++;
            S.Push(v);

            
            foreach (var w in Adj[v])
                if (w.Index < 0)
                {
                    
                    StrongConnect(w);
                    v.LowLink = Math.Min(v.LowLink, w.LowLink);
                }
                else if (S.Contains(w))
                    
                    v.LowLink = Math.Min(v.LowLink, w.Index);

            
            if (v.LowLink == v.Index)
            {
                Console.Write("SCC: ");

                Node w;
                do
                {
                    w = S.Pop();
                    Console.Write(w.N + " ");
                } while (w != v);

                Console.WriteLine();
            }
        };

        foreach (var v in V)
            if (v.Index < 0)
                StrongConnect(v);
    }
}
Task: Multidimensional Newton-Raphson method



C#: using System;

namespace Rosetta
{
    internal interface IFun
    {
        double F(int index, Vector x);
        double df(int index, int derivative, Vector x);
        double[] weights();
    }

    class Newton
    {                
        internal Vector Do(int size, IFun fun, Vector start)
        {
            Vector X = start.Clone();
            Vector F = new Vector(size);
            Matrix J = new Matrix(size, size);
            Vector D;
            do
            {
                for (int i = 0; i < size; i++)
                    F[i] = fun.F(i, X);
                for (int i = 0; i < size; i++)
                    for (int j = 0; j < size; j++)
                        J[i, j] = fun.df(i, j, X);
                J.ElimPartial(F);
                X -= F;
                
            } while (F.norm(fun.weights()) > 1e-12);
            return X;
        }       
    }
}