WeixiangYan/CodeTransOcean huggingface dataset:
Task: Move-to-front algorithm



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

namespace MoveToFront
{
    class Program
    {
        private static char[] symbolTable;
        private static void setSymbolTable()
        {
            symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
        }

        private static void moveToFront(int charIndex)
        {
            char toFront = symbolTable[charIndex];
            for (int j = charIndex; j > 0; j--)
            {
                symbolTable[j] = symbolTable[j - 1];
            }
            symbolTable[0] = toFront;
        }

        public static int[] Encode(string input)
        {
            setSymbolTable();
            var output = new List<int>();
            foreach (char c in input)
            {
                for (int i = 0; i < 26; i++)
                {
                    if (symbolTable[i] == c)
                    {
                        output.Add(i);
                        moveToFront(i);
                        break;
                    }
                }
            }         
            return output.ToArray();
        }

        public static string Decode(int[] input)
        {
            setSymbolTable();
            var output = new StringBuilder(input.Length);
            foreach (int n in input)
            {
                output.Append(symbolTable[n]);
                moveToFront(n);
            }
            return output.ToString();
        }

        static void Main(string[] args)
        {
            string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" };
            int[] encoding;
            foreach (string s in testInputs) 
            {
                Console.WriteLine($"Encoding for '{s}':");
                encoding = Encode(s);
                foreach (int i in encoding)
                {
                    Console.Write($"{i} ");
                }
                Console.WriteLine($"\nDecoding for '{s}':");
                Console.WriteLine($"{Decode(encoding)}\n");
            }
        }
    }
}





Python: from __future__ import print_function
from string import ascii_lowercase

SYMBOLTABLE = list(ascii_lowercase)

def move2front_encode(strng, symboltable):
    sequence, pad = [], symboltable[::]
    for char in strng:
        indx = pad.index(char)
        sequence.append(indx)
        pad = [pad.pop(indx)] + pad
    return sequence

def move2front_decode(sequence, symboltable):
    chars, pad = [], symboltable[::]
    for indx in sequence:
        char = pad[indx]
        chars.append(char)
        pad = [pad.pop(indx)] + pad
    return ''.join(chars)

if __name__ == '__main__':
    for s in ['broood', 'bananaaa', 'hiphophiphop']:
        encode = move2front_encode(s, SYMBOLTABLE)
        print('%14r encodes to %r' % (s, encode), end=', ')
        decode = move2front_decode(encode, SYMBOLTABLE)
        print('which decodes back to %r' % decode)
        assert s == decode, 'Whoops!'
Task: Sum of first n cubes



C#: using System; using static System.Console;
class Program { static void Main(string[] args) {
    for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6)
      Write("{0,-7}{1}",s, (i+=i==3?-4:1)==0?"\n":" "); } }





Python: def main():
    fila = 0
    lenCubos = 51

    print("Suma de N cubos para n = [0..49]\n")

    for n in range(1, lenCubos):
        sumCubos = 0
        for m in range(1, n):
            sumCubos = sumCubos + (m ** 3)
            
        fila += 1
        print(f'{sumCubos:7} ', end='')
        if fila % 5 == 0:
            print(" ")

    print(f"\nEncontrados {fila} cubos.")

if __name__ == '__main__': main()
Task: Execute a system command



C#: using System.Diagnostics;

namespace Execute
{
    class Program
    {
        static void Main(string[] args)
        {
            Process.Start("cmd.exe", "/c dir");
        }
    }
}





Python: import os
exit_code = os.system('ls')       
output    = os.popen('ls').read()
Task: XML validation



C#: using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;

public class Test
{
	public static void Main()
	{
		
		XmlSchemaSet sc = new XmlSchemaSet();
		sc.Add(null, "http:
		XmlReaderSettings settings = new XmlReaderSettings();
		settings.ValidationType = ValidationType.Schema;
		settings.Schemas = sc;
		settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
		
		XmlReader reader = XmlReader.Create("http:
		
		while (reader.Read()); 
		
		Console.WriteLine("The XML file is valid for the given xsd file");
	}
	
	
	private static void ValidationCallBack(object sender, ValidationEventArgs e) {
		Console.WriteLine("Validation Error: {0}", e.Message);
	}
}





Python: 
from __future__ import print_function
import lxml
from lxml import etree

if __name__=="__main__":

	parser = etree.XMLParser(dtd_validation=True)
	schema_root = etree.XML()
	schema = etree.XMLSchema(schema_root)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5</a>", parser)
		print ("Finished validating good xml")
	except lxml.etree.XMLSyntaxError as err:
		print (err)

	
	parser = etree.XMLParser(schema = schema)
	try:
		root = etree.fromstring("<a>5<b>foobar</b></a>", parser)
	except lxml.etree.XMLSyntaxError as err:
		print (err)
Task: Longest increasing subsequence



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

public static class LIS
{
    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>
        values == null ? throw new ArgumentNullException() :
            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();

    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {
        if (index == values.Count) return current;
        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)
            return FindRecImpl(values, current, index + 1, comparer);
        return Max(
            FindRecImpl(values, current, index + 1, comparer),
            FindRecImpl(values, current + values[index], index + 1, comparer)
        );
    }

    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;

    class Sequence<T> : IEnumerable<T>
    {
        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);

        public Sequence(T value, Sequence<T> tail)
        {
            Value = value;
            Tail = tail;
            Length = tail == null ? 0 : tail.Length + 1;
        }

        public T Value { get; }
        public Sequence<T> Tail { get; }
        public int Length { get; }

        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);

        public IEnumerator<T> GetEnumerator()
        {
            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;
        }

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}





Python: def longest_increasing_subsequence(X):
    
    N = len(X)
    P = [0] * N
    M = [0] * (N+1)
    L = 0
    for i in range(N):
       lo = 1
       hi = L
       while lo <= hi:
           mid = (lo+hi)//2
           if (X[M[mid]] < X[i]):
               lo = mid+1
           else:
               hi = mid-1
    
       newL = lo
       P[i] = M[newL-1]
       M[newL] = i
    
       if (newL > L):
           L = newL
    
    S = []
    k = M[L]
    for i in range(L-1, -1, -1):
        S.append(X[k])
        k = P[k]
    return S[::-1]

if __name__ == '__main__':
    for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
        print('a L.I.S. of %s is %s' % (d, longest_increasing_subsequence(d)))
Task: Scope modifiers



C#: public 
protected 
internal 
protected internal 
private 

private protected 
















Python: >>> x="From global scope"
>>> def outerfunc():
    x = "From scope at outerfunc"

    def scoped_local():
        x = "scope local"
        return "scoped_local scope gives x = " + x
    print(scoped_local())

    def scoped_nonlocal():
        nonlocal x
        return "scoped_nonlocal scope gives x = " + x
    print(scoped_nonlocal())

    def scoped_global():
        global x
        return "scoped_global scope gives x = " + x
    print(scoped_global())

    def scoped_notdefinedlocally():
        return "scoped_notdefinedlocally scope gives x = " + x
    print(scoped_notdefinedlocally())

    
>>> outerfunc()
scoped_local scope gives x = scope local
scoped_nonlocal scope gives x = From scope at outerfunc
scoped_global scope gives x = From global scope
scoped_notdefinedlocally scope gives x = From global scope
>>>
Task: GUI component interaction



C#: using System; 
using System.ComponentModel; 
using System.Windows.Forms; 

class RosettaInteractionForm : Form
{    
    
    
    class NumberModel: INotifyPropertyChanged
    {

        Random rnd = new Random();

        
        public event PropertyChangedEventHandler PropertyChanged = delegate {};

        int _value;
        public int Value
        {
            get { return _value; }
            set 
            { 
                _value = value;
                
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            }
        }

        public void ResetToRandom(){
            Value = rnd.Next(5000);
        }
    }

    NumberModel model = new NumberModel{ Value = 0};
    
    RosettaInteractionForm()    
    {
        
        var tbNumber = new MaskedTextBox
                        { 
                            Mask="0000",            
                            ResetOnSpace = false,   
                            Dock = DockStyle.Top    
                        };
        
        tbNumber.DataBindings.Add("Text", model, "Value");

        var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom};
        btIncrement.Click += delegate
                        {
                            model.Value++;
                        };
        var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom};
        btDecrement.Click += delegate
                        {
                            model.Value--;
                        };
        var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom };
        btRandom.Click += delegate
                        {
                            if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                model.ResetToRandom();
                        };
        Controls.Add(tbNumber);
        Controls.Add(btIncrement);
        Controls.Add(btDecrement);
        Controls.Add(btRandom);
    }
    static void Main()
    {
        Application.Run(new RosettaInteractionForm());
    }
}





Python: import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
    s.set(int(s.get())+1)
def rand():
    if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
        s.set(random.randrange(0,5000))
def update(e):
    if not e.char.isdigit():
        tkMessageBox.showerror('Error', 'Invalid input !') 
        return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
Task: One of n lines in a file



C#:     class Program
    {
        private static Random rnd = new Random();
        public static int one_of_n(int n)
        {
            int currentChoice = 1;
            for (int i = 2; i <= n; i++)
            {
                double outerLimit = 1D / (double)i;
                if (rnd.NextDouble() < outerLimit)
                    currentChoice = i;
            }
            return currentChoice;
        }

        static void Main(string[] args)
        {
            Dictionary<int, int> results = new Dictionary<int, int>();
            for (int i = 1; i < 11; i++)
                results.Add(i, 0);

            for (int i = 0; i < 1000000; i++)
            {
                int result = one_of_n(10);
                results[result] = results[result] + 1;
            }

            for (int i = 1; i < 11; i++)
                Console.WriteLine("{0}\t{1}", i, results[i]);
            Console.ReadLine();
        }
    }





Python: from random import randrange
try:
    range = xrange
except: pass

def one_of_n(lines): 
    choice = None
    for i, line in enumerate(lines):
        if randrange(i+1) == 0:
            choice = line
    return choice
            
def one_of_n_test(n=10, trials=1000000):
    bins = [0] * n
    if n:
        for i in range(trials):
            bins[one_of_n(range(n))] += 1
    return bins

print(one_of_n_test())
Task: Addition chains



C#: using System;

namespace AdditionChains {
    class Program {
        static int[] Prepend(int n, int[] seq) {
            int[] result = new int[seq.Length + 1];
            Array.Copy(seq, 0, result, 1, seq.Length);
            result[0] = n;
            return result;
        }

        static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) {
            if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0);
            if (seq[0] == n) return new Tuple<int, int>(pos, 1);
            if (pos < min_len) return TryPerm(0, pos, seq, n, min_len);
            return new Tuple<int, int>(min_len, 0);
        }

        static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) {
            if (i > pos) return new Tuple<int, int>(min_len, 0);

            Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len);
            Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1);

            if (res2.Item1 < res1.Item1) return res2;
            if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2);

            throw new Exception("TryPerm exception");
        }

        static Tuple<int, int> InitTryPerm(int x) {
            return TryPerm(0, 0, new int[] { 1 }, x, 12);
        }

        static void FindBrauer(int num) {
            Tuple<int, int> res = InitTryPerm(num);
            Console.WriteLine();
            Console.WriteLine("N = {0}", num);
            Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1);
            Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2);
        }

        static void Main(string[] args) {
            int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 };
            Array.ForEach(nums, n => FindBrauer(n));
        }
    }
}





Python: def prepend(n, seq):
    return [n] + seq

def check_seq(pos, seq, n, min_len):
    if pos > min_len or seq[0] > n:
        return min_len, 0
    if seq[0] == n:
        return pos, 1
    if pos < min_len:
        return try_perm(0, pos, seq, n, min_len)
    return min_len, 0

def try_perm(i, pos, seq, n, min_len):
    if i > pos:
        return min_len, 0

    res1 = check_seq(pos + 1, prepend(seq[0] + seq[i], seq), n, min_len)
    res2 = try_perm(i + 1, pos, seq, n, res1[0])

    if res2[0] < res1[0]:
        return res2
    if res2[0] == res1[0]:
        return res2[0], res1[1] + res2[1]
    raise Exception("try_perm exception")

def init_try_perm(x):
    return try_perm(0, 0, [1], x, 12)

def find_brauer(num):
    res = init_try_perm(num)
    print
    print "N = ", num
    print "Minimum length of chains: L(n) = ", res[0]
    print "Number of minimum length Brauer chains: ", res[1]


nums = [7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379]
for i in nums:
    find_brauer(i)
Task: Repeat



C#: using System;

namespace Repeat {
    class Program {
        static void Repeat(int count, Action<int> fn) {
            if (null == fn) {
                throw new ArgumentNullException("fn");
            }
            for (int i = 0; i < count; i++) {
                fn.Invoke(i + 1);
            }
        }

        static void Main(string[] args) {
            Repeat(3, x => Console.WriteLine("Example {0}", x));
        }
    }
}





Python: 
def repeat(f,n):
  for i in range(n):
    f();

def procedure():
  print("Example");

repeat(procedure,3);
Task: Modular inverse



C#: public class Program
{
    static void Main()
    {
        System.Console.WriteLine(42.ModInverse(2017));
    }
}

public static class IntExtensions
{
    public static int ModInverse(this int a, int m)
    {
        if (m == 1) return 0;
        int m0 = m;
        (int x, int y) = (1, 0);

        while (a > 1) {
            int q = a / m;
            (a, m) = (m, a % m);
            (x, y) = (y, x - q * y);
        }
        return x < 0 ? x + m0 : x;
    }
}





Python: >>> def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

>>> def modinv(a, m):
	g, x, y = extended_gcd(a, m)
	if g != 1:
		raise ValueError
	return x % m

>>> modinv(42, 2017)
1969
>>>
Task: Hello world_Web server



C#: using System.Text;
using System.Net.Sockets;
using System.Net;

namespace WebServer
{
    class GoodByeWorld
    {        
        static void Main(string[] args)
        {
            const string msg = "<html>\n<body>\nGoodbye, world!\n</body>\n</html>\n";        
            const int port = 8080;
            bool serverRunning = true;

            TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
            tcpListener.Start();

            while (serverRunning)
            {
                Socket socketConnection = tcpListener.AcceptSocket();
                byte[] bMsg = Encoding.ASCII.GetBytes(msg.ToCharArray(), 0, (int)msg.Length);
                socketConnection.Send(bMsg);
                socketConnection.Disconnect(true);
            }
        }
    }
}





Python: from wsgiref.simple_server import make_server

def app(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    yield b"<h1>Goodbye, World!</h1>"

server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
Task: The sieve of Sundaram



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

class Program
{
    static string fmt(int[] a)
    {
        var sb = new System.Text.StringBuilder();
        for (int i = 0; i < a.Length; i++)
            sb.Append(string.Format("{0,5}{1}",
              a[i], i % 10 == 9 ? "\n" : " "));
        return sb.ToString();
    }

    static void Main(string[] args)
    {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();
        sw.Stop();
        Write("The first 100 odd prime numbers:\n{0}\n",
          fmt(pr.Take(100).ToArray()));
        Write("The millionth odd prime number: {0}", pr.Last());
        Write("\n{0} ms", sw.Elapsed.TotalMilliseconds);
    }
}

class PG
{
    public static IEnumerable<int> Sundaram(int n)
    {
        
        int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;
        var comps = new bool[k + 1];
        for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)
            while ((t += d + 2) < k)
                comps[t] = true;
        for (; v < k; v++)
            if (!comps[v])
                yield return (v << 1) + 1;
    }
}





Python: from numpy import log

def sieve_of_Sundaram(nth, print_all=True):
    
    assert nth > 0, "nth must be a positive integer"
    k = int((2.4 * nth * log(nth)) // 2)  
    integers_list = [True] * k
    for i in range(1, k):
        j = i
        while i + j + 2 * i * j < k:
            integers_list[i + j + 2 * i * j] = False
            j += 1
    pcount = 0
    for i in range(1, k + 1):
        if integers_list[i]:
            pcount += 1
            if print_all:
                print(f"{2 * i + 1:4}", end=' ')
                if pcount % 10 == 0:
                    print()

            if pcount == nth:
                print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n")
                break



sieve_of_Sundaram(100, True)

sieve_of_Sundaram(1000000, False)
Task: Active Directory_Connect



C#: 
var objDE = new System.DirectoryServices.DirectoryEntry("LDAP:





Python: import ldap

l = ldap.initialize("ldap://ldap.example.com")
try:
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)

    bind = l.simple_bind_s("me@example.com", "password")
finally:
    l.unbind()
Task: Pythagorean quadruples



C#: using System;

namespace PythagoreanQuadruples {
    class Program {
        const int MAX = 2200;
        const int MAX2 = MAX * MAX * 2;

        static void Main(string[] args) {
            bool[] found = new bool[MAX + 1]; 
            bool[] a2b2 = new bool[MAX2 + 1]; 
            int s = 3;

            for(int a = 1; a <= MAX; a++) {
                int a2 = a * a;
                for (int b=a; b<=MAX; b++) {
                    a2b2[a2 + b * b] = true;
                }
            }

            for (int c = 1; c <= MAX; c++) {
                int s1 = s;
                s += 2;
                int s2 = s;
                for (int d = c + 1; d <= MAX; d++) {
                    if (a2b2[s1]) found[d] = true;
                    s1 += s2;
                    s2 += 2;
                }
            }

            Console.WriteLine("The values of d <= {0} which can't be represented:", MAX);
            for (int d = 1; d < MAX; d++) {
                if (!found[d]) Console.Write("{0}  ", d);
            }
            Console.WriteLine();
        }
    }
}





Python: def quad(top=2200):
    r = [False] * top
    ab = [False] * (top * 2)**2
    for a in range(1, top):
        for b in range(a, top):
            ab[a * a + b * b] = True
    s = 3
    for c in range(1, top):
        s1, s, s2 = s, s + 2, s + 2
        for d in range(c + 1, top):
            if ab[s1]:
                r[d] = True
            s1 += s2
            s2 += 2
    return [i for i, val in enumerate(r) if not val and i]
    
if __name__ == '__main__':
    n = 2200
    print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")