WeixiangYan/CodeTransOcean huggingface dataset:
Task: Almkvist-Giullera formula for pi



C#: using System;
using BI = System.Numerics.BigInteger;
using static System.Console;

class Program {

  static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
    q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }

  static string dump(int digs, bool show = false) {
    int gb = 1, dg = ++digs + gb, z;
    BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,
       t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;
    for (BI n = 0; n < dg; n++) {
      if (n > 0) t3 *= BI.Pow(n, 6);
      te = t1 * t2 / t3;
      if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);
      else te /= BI.Pow (10, -z);
      if (show && n < 10)
        WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t);
      su += te; if (te < 10) {
        if (show) WriteLine("\n{0} iterations required for {1} digits " +
        "after the decimal point.\n", n, --digs); break; }
      for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;
      t2 += 126 + 532 * (d += 2);
    }
    string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) /
      su / 32 * 3 * BI.Pow((BI)10, dg + 5)));
    return s[0] + "." + s.Substring(1, digs); }

  static void Main(string[] args) {
    WriteLine(dump(70, true)); }
}






VB: Imports System, BI = System.Numerics.BigInteger, System.Console

Module Module1

    Function isqrt(ByVal x As BI) As BI
        Dim t As BI, q As BI = 1, r As BI = 0
        While q <= x : q <<= 2 : End While
        While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
            If t >= 0 Then x = t : r += q
        End While : Return r
    End Function

    Function dump(ByVal digs As Integer, ByVal Optional show As Boolean = False) As String
        digs += 1
        Dim z As Integer, gb As Integer = 1, dg As Integer = digs + gb
        Dim te As BI, t1 As BI = 1, t2 As BI = 9, t3 As BI = 1, su As BI = 0, t As BI = BI.Pow(10, If(dg <= 60, 0, dg - 60)), d As BI = -1, fn As BI = 1
        For n As BI = 0 To dg - 1
            If n > 0 Then t3 = t3 * BI.Pow(n, 6)
            te = t1 * t2 / t3 : z = dg - 1 - CInt(n) * 6
            If z > 0 Then te = te * BI.Pow(10, z) Else te = te / BI.Pow(10, -z)
            If show AndAlso n < 10 Then WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t)
            su += te : If te < 10 Then
                digs -= 1
                If show Then WriteLine(vbLf & "{0} iterations required for {1} digits " & _
                    "after the decimal point." & vbLf, n, digs)
                Exit For
            End If
            For j As BI = n * 6 + 1 To n * 6 + 6
                t1 = t1 * j : Next
            d += 2 : t2 += 126 + 532 * d
        Next
        Dim s As String = String.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) _
            / su / 32 * 3 * BI.Pow(CType(10, BI), dg + 5)))
        Return s(0) & "." & s.Substring(1, digs)
    End Function

    Sub Main(ByVal args As String())
        WriteLine(dump(70, true))
    End Sub

End Module
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); } }






VB: Imports System.Collections.Generic, System.Linq, System.Console

Module Module1
    Function soas(ByVal n As Integer, ByVal f As IEnumerable(Of Integer)) As Boolean
        If n <= 0 Then Return False Else If f.Contains(n) Then Return True
        Select Case n.CompareTo(f.Sum())
            Case 1 : Return False : Case 0 : Return True
            Case -1 : Dim rf As List(Of Integer) = f.Reverse().ToList() : Dim D as Integer = n - rf(0) 
                rf.RemoveAt(0) : Return soas(d, rf) OrElse soas(n, rf)
        End Select : Return true
    End Function

    Function ip(ByVal n As Integer) As Boolean
        Dim f As IEnumerable(Of Integer) = Enumerable.Range(1, n >> 1).Where(Function(d) n Mod d = 0).ToList()
        Return Enumerable.Range(1, n - 1).ToList().TrueForAll(Function(i) soas(i, f))
    End Function

    Sub Main()
        Dim c As Integer = 0, m As Integer = 333, i As Integer = 1 : While i <= m
            If ip(i) OrElse i = 1 Then c += 1 : Write("{0,3} {1}", i, If(c Mod 10 = 0, vbLf, ""))
            i += If(i = 1, 1, 2) : End While
        Write(vbLf & "Found {0} practical numbers between 1 and {1} inclusive." & vbLf, c, m)
        Do : m = If(m < 500, m << 1, m * 10 + 6)
            Write(vbLf & "{0,5} is a{1}practical number.", m, If(ip(m), " ", "n im")) : Loop While m < 1e4
    End Sub
End Module
Task: Literals_Floating point



C#: double d = 1;
d = 1d;
d = 1D;
d = 1.2; 
d = 1.2d; 
d = .2;
d = 12e-12;
d = 12E-12;
d = 1_234e-1_2; 
float f = 1;
f = 1f;
f = 1F;
f = 1.2f;
f = .2f;
f = 12e-12f;
f = 12E-12f;
f = 1_234e-1_2f;
decimal m = 1;
m = 1m;
m = 1m;
m = 1.2m;
m = .2m;
m = 12e-12m;
m = 12E-12m;
m = 1_234e-1_2m;






VB: Sub Main()
Dim d As Double 
Dim s As Single 
  d = -12.3456
  d = 1000#
  d = 0.00001
  d = 67#
  d = 8.9
  d = 0.33
  d = 0#
  d = 2# * 10 ^ 3
  d = 2E+50
  d = 2E-50
  s = -12.3456!
  s = 1000!
  s = 0.00001!
  s = 67!
  s = 8.9!
  s = 0.33!
  s = 0!
  s = 2! * 10 ^ 3
End Sub
Task: Break OO privacy



C#: using System;
using System.Reflection;

public class MyClass
{
    private int answer = 42;
}

public class Program
{
    public static void Main()
    {
        var myInstance = new MyClass();
        var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
        var answer = fieldInfo.GetValue(myInstance);
        Console.WriteLine(answer);
    }
}






VB: Imports System.Reflection


Public Class MyClazz
    Private answer As Integer = 42
End Class

Public Class Program
    Public Shared Sub Main()
        Dim myInstance = New MyClazz()
        Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim answer = fieldInfo.GetValue(myInstance)
        Console.WriteLine(answer)
    End Sub
End Class
Task: Long year



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

public static class Program
{
    public static void Main()
    {
        WriteLine("Long years in the 21st century:");
        WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
    }
    
    public static IEnumerable<int> To(this int start, int end) {
        for (int i = start; i < end; i++) yield return i;
    }
    
}






VB: DEFINT A-Z

DECLARE FUNCTION p% (Yr AS INTEGER)
DECLARE FUNCTION LongYear% (Yr AS INTEGER)

DIM iYi, iYf, i

CLS
PRINT "This program calculates which are 53-week years in a range."
PRINT
INPUT "Initial year"; iYi
INPUT "Final year (could be the same)"; iYf
IF iYf >= iYi THEN
  FOR i = iYi TO iYf
    IF LongYear(i) THEN
      PRINT i; " ";
    END IF
  NEXT i
END IF
PRINT
PRINT
PRINT "End of program."
END

FUNCTION LongYear% (Yr AS INTEGER)
  LongYear% = (p%(Yr) = 4) OR (p%(Yr - 1) = 3)
END FUNCTION

FUNCTION p% (Yr AS INTEGER)
  p% = (Yr + INT(Yr / 4) - INT(Yr / 100) + INT(Yr / 400)) MOD 7
END FUNCTION
Task: Associative array_Merging



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

public class Program
{
    public static void Main() {
        var baseData = new Dictionary<string, object> {
            ["name"] = "Rocket Skates",
            ["price"] = 12.75,
            ["color"] = "yellow"
        };
        var updateData = new Dictionary<string, object> {
            ["price"] = 15.25,
            ["color"] = "red",
            ["year"] = 1974
        };
        var mergedData = new Dictionary<string, object>();
        foreach (var entry in baseData.Concat(updateData)) {
            mergedData[entry.Key] = entry.Value;
        }
        foreach (var entry in mergedData) {
            Console.WriteLine(entry);
        }
   }
}






VB: Private Type Associative
    Key As String
    Value As Variant
End Type
Sub Main_Array_Associative()
Dim BaseArray(2) As Associative, UpdateArray(2) As Associative
    FillArrays BaseArray, UpdateArray
    ReDim Result(UBound(BaseArray)) As Associative
    MergeArray Result, BaseArray, UpdateArray
    PrintOut Result
End Sub
Private Sub MergeArray(Res() As Associative, Base() As Associative, Update() As Associative)
Dim i As Long, Respons As Long
    Res = Base
    For i = LBound(Update) To UBound(Update)
        If Exist(Respons, Base, Update(i).Key) Then
            Res(Respons).Value = Update(i).Value
        Else
            ReDim Preserve Res(UBound(Res) + 1)
            Res(UBound(Res)).Key = Update(i).Key
            Res(UBound(Res)).Value = Update(i).Value
        End If
    Next
End Sub
Private Function Exist(R As Long, B() As Associative, K As String) As Boolean
Dim i As Long
    Do
        If B(i).Key = K Then
            Exist = True
            R = i
        End If
        i = i + 1
    Loop While i <= UBound(B) And Not Exist
End Function
Private Sub FillArrays(B() As Associative, U() As Associative)
    B(0).Key = "name"
    B(0).Value = "Rocket Skates"
    B(1).Key = "price"
    B(1).Value = 12.75
    B(2).Key = "color"
    B(2).Value = "yellow"
    U(0).Key = "price"
    U(0).Value = 15.25
    U(1).Key = "color"
    U(1).Value = "red"
    U(2).Key = "year"
    U(2).Value = 1974
End Sub
Private Sub PrintOut(A() As Associative)
Dim i As Long
    Debug.Print "Key", "Value"
    For i = LBound(A) To UBound(A)
        Debug.Print A(i).Key, A(i).Value
    Next i
    Debug.Print "-----------------------------"
End Sub
Task: Associative array_Iteration



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

namespace AssocArrays
{
    class Program
    {
        static void Main(string[] args)
        {

            Dictionary<string,int> assocArray = new Dictionary<string,int>();

            assocArray["Hello"] = 1;
            assocArray.Add("World", 2);
            assocArray["!"] = 3;

            foreach (KeyValuePair<string, int> kvp in assocArray)
            {
                Console.WriteLine(kvp.Key + " : " + kvp.Value);
            }

            foreach (string key in assocArray.Keys)
            {
                Console.WriteLine(key);
            }

            foreach (int val in assocArray.Values)
            {
                Console.WriteLine(val.ToString());
            }
        }
    }
}






VB: Option Explicit
Sub Test()
    Dim h As Object, i As Long, u, v, s
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3

    
    For Each s In h.Keys
        Debug.Print s
    Next

    
    For Each s In h.Items
        Debug.Print s
    Next

    
    u = h.Keys
    v = h.Items
    For i = 0 To h.Count - 1
        Debug.Print u(i), v(i)
    Next
End Sub
Task: Closest-pair problem



C#: class Segment
{
    public Segment(PointF p1, PointF p2)
    {
        P1 = p1;
        P2 = p2;
    }

    public readonly PointF P1;
    public readonly PointF P2;

    public float Length()
    {
        return (float)Math.Sqrt(LengthSquared());
    }

    public float LengthSquared()
    {
        return (P1.X - P2.X) * (P1.X - P2.X)
            + (P1.Y - P2.Y) * (P1.Y - P2.Y);
    }
}






VB: Option Explicit

Private Type MyPoint
    X As Single
    Y As Single
End Type

Private Type MyPair
    p1 As MyPoint
    p2 As MyPoint
End Type

Sub Main()
Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long
Dim T#
Randomize Timer
    Nb = 10
    Do
        ReDim points(1 To Nb)
        For i = 1 To Nb
            points(i).X = Rnd * Nb
            points(i).Y = Rnd * Nb
        Next
        d = 1000000000000#
T = Timer
        BF = BruteForce(points, d)
        Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec."
        Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y
        Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y
        Debug.Print "dist : " & d
        Debug.Print "--------------------------------------------------"
        Nb = Nb * 10
    Loop While Nb <= 10000
End Sub

Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair
Dim i As Long, j As Long, d As Single, ClosestPair As MyPair
    For i = 1 To UBound(p) - 1
        For j = i + 1 To UBound(p)
            d = Dist(p(i), p(j))
            If d < mindist Then
                mindist = d
                ClosestPair.p1 = p(i)
                ClosestPair.p2 = p(j)
            End If
        Next
    Next
    BruteForce = ClosestPair
End Function

Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single
    Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2)
End Function
Task: Address of a variable



C#: int i = 5;
int* p = &i;






VB: Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
    MyVar = 10


TheAddress = varptr(MyVar)


MEMSET(TheAddress, 102, SizeOf(byte))


showmessage "MyVar = " + str$(MyVar)


MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))


showmessage "SecVar = " + str$(SecVar)
Task: Inheritance_Single



C#: class Animal
{ 
   
  
}

class Dog : Animal
{ 
   
  
}

class Lab : Dog
{ 
   
  
}

class Collie : Dog
{ 
  
  
}

class Cat : Animal
{ 
  
  
}






VB: Class Animal
  
End Class

Class Dog
  Inherits Animal
  
End Class

Class Lab
  Inherits Dog
  
End Class

Class Collie
  Inherits Dog
  
End Class

Class Cat
  Inherits Animal
  
End Class
Task: Associative array_Creation



C#: System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";






VB: Option Explicit
Sub Test()
    Dim h As Object
    Set h = CreateObject("Scripting.Dictionary")
    h.Add "A", 1
    h.Add "B", 2
    h.Add "C", 3
    Debug.Print h.Item("A")
    h.Item("C") = 4
    h.Key("C") = "D"
    Debug.Print h.exists("C")
    h.Remove "B"
    Debug.Print h.Count
    h.RemoveAll
    Debug.Print h.Count
End Sub
Task: Square root by hand



C#: using System;
using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;

class Program {

    static void Main(string[] args) {
        BI i, j, k, d; i = 2; int n = -1; int n0 = -1;
        j = (BI)Floor(Sqrt((double)i)); k = j; d = j;
        DateTime st = DateTime.Now;
        if (args.Length > 0) int.TryParse(args[0], out n);
        if (n > 0) n0 = n; else n = 1;
        do {
            Write(d); i = (i - k * d) * 100; k = 20 * j;
            for (d = 1; d <= 10; d++)
                if ((k + d) * d > i) { d -= 1; break; }
            j = j * 10 + d; k += d; if (n0 > 0) n--;
        } while (n > 0);
        if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); }

}






VB: Imports System.Math, System.Console, BI = System.Numerics.BigInteger

Module Module1

    Sub Main(ByVal args As String())
        Dim i, j, k, d As BI : i = 2
        j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
        Dim n As Integer = -1, n0 As Integer = -1,
            st As DateTime = DateTime.Now
        If args.Length > 0 Then Integer.TryParse(args(0), n)
        If n > 0 Then n0 = n Else n = 1
        Do
            Write(d) : i = (i - k * d) * 100 : k = 20 * j
            For d = 1 To 10
                If (k + d) * d > i Then d -= 1 : Exit For
            Next
            j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
        Loop While n > 0
        If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
    End Sub
End Module
Task: Reflection_List properties



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

public static class Reflection
{
    public static void Main() {
        var t = new TestClass();
        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        foreach (var prop in GetPropertyValues(t, flags)) {
            Console.WriteLine(prop);
        }
        foreach (var field in GetFieldValues(t, flags)) {
            Console.WriteLine(field);
        }
    }

    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>
        from p in typeof(T).GetProperties(flags)
        where p.GetIndexParameters().Length == 0 
        select (p.Name, p.GetValue(obj, null));
    
    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>
        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));
    
    class TestClass
    {
        private int privateField = 7;
        public int PublicNumber { get; } = 4;
        private int PrivateNumber { get; } = 2;
    }

}






VB: Imports System.Reflection

Module Module1

    Class TestClass
        Private privateField = 7
        Public ReadOnly Property PublicNumber = 4
        Private ReadOnly Property PrivateNumber = 2
    End Class

    Function GetPropertyValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
        Return From p In obj.GetType().GetProperties(flags)
               Where p.GetIndexParameters().Length = 0
               Select New With {p.Name, Key .Value = p.GetValue(obj, Nothing)}
    End Function

    Function GetFieldValues(Of T)(obj As T, flags As BindingFlags) As IEnumerable
        Return obj.GetType().GetFields(flags).Select(Function(f) New With {f.Name, Key .Value = f.GetValue(obj)})
    End Function

    Sub Main()
        Dim t As New TestClass()
        Dim flags = BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.Instance
        For Each prop In GetPropertyValues(t, flags)
            Console.WriteLine(prop)
        Next
        For Each field In GetFieldValues(t, flags)
            Console.WriteLine(field)
        Next
    End Sub

End Module
Task: Find limit of recursion




Go: package main

import (
	"flag"
	"fmt"
	"runtime/debug"
)

func main() {
	stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
	flag.Parse()
	if *stack > 0 {
		debug.SetMaxStack(*stack)
	}
	r(1)
}

func r(l int) {
	if l%1000 == 0 {
		fmt.Println(l)
	}
	r(l + 1)
}




Python: import sys
print(sys.getrecursionlimit())
Task: Carmichael 3 strong pseudoprimes




Go: package main

import "fmt"


func mod(n, m int) int {
    return ((n % m) + m) % m
}

func isPrime(n int) bool {
    if n < 2 { return false }
    if n % 2 == 0 { return n == 2 }
    if n % 3 == 0 { return n == 3 }
    d := 5
    for d * d <= n {
        if n % d == 0 { return false }
        d += 2
        if n % d == 0 { return false }
        d += 4
    }
    return true
}

func carmichael(p1 int) {
    for h3 := 2; h3 < p1; h3++ {
        for d := 1; d < h3 + p1; d++ {
            if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 {
                p2 := 1 + (p1 - 1) * (h3 + p1) / d
                if !isPrime(p2) { continue }
                p3 := 1 + p1 * p2 / h3
                if !isPrime(p3) { continue }
                if p2 * p3 % (p1 - 1) != 1 { continue }
                c := p1 * p2 * p3
                fmt.Printf("%2d   %4d   %5d     %d\n", p1, p2, p3, c)
            }
        }
    }
}

func main() {
    fmt.Println("The following are Carmichael munbers for p1 <= 61:\n")
    fmt.Println("p1     p2      p3     product")
    fmt.Println("==     ==      ==     =======")

    for p1 := 2; p1 <= 61; p1++ {
        if isPrime(p1) { carmichael(p1) }
    }
}




Python: class Isprime():
    
    multiples = {2}
    primes = [2]
    nmax = 2
    
    def __init__(self, nmax):
        if nmax > self.nmax:
            self.check(nmax)

    def check(self, n):
        if type(n) == float:
            if not n.is_integer(): return False
            n = int(n)
        multiples = self.multiples
        if n <= self.nmax:
            return n not in multiples
        else:
            
            primes, nmax = self.primes, self.nmax
            newmax = max(nmax*2, n)
            for p in primes:
                multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p))
            for i in range(nmax+1, newmax+1):
                if i not in multiples:
                    primes.append(i)
                    multiples.update(range(i*2, newmax+1, i))
            self.nmax = newmax
            return n not in multiples

    __call__ = check
            
        
def carmichael(p1):
    ans = []
    if isprime(p1):
        for h3 in range(2, p1):
            g = h3 + p1
            for d in range(1, g):
                if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3:
                    p2 = 1 + ((p1 - 1)* g // d)
                    if isprime(p2):
                        p3 = 1 + (p1 * p2 // h3)
                        if isprime(p3):
                            if (p2 * p3) % (p1 - 1) == 1:
                                
                                ans += [tuple(sorted((p1, p2, p3)))]
    return ans
                
isprime = Isprime(2)
 
ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), []))
print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
Task: Image noise




Go: package main

import (
    "code.google.com/p/x-go-binding/ui/x11"
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "log"
    "os"
    "time"
)

var randcol = genrandcol()

func genrandcol() <-chan color.Color {
    c := make(chan color.Color)

    go func() {
        for {
            select {
            case c <- image.Black:
            case c <- image.White:
            }
        }
    }()

    return c
}

func gennoise(screen draw.Image) {
    for y := 0; y < 240; y++ {
        for x := 0; x < 320; x++ {
            screen.Set(x, y, <-randcol)
        }
    }
}

func fps() chan<- bool {
    up := make(chan bool)

    go func() {
        var frames int64
        var lasttime time.Time
        var totaltime time.Duration

        for {
            <-up
            frames++
            now := time.Now()
            totaltime += now.Sub(lasttime)
            if totaltime > time.Second {
                fmt.Printf("FPS: %v\n", float64(frames)/totaltime.Seconds())
                frames = 0
                totaltime = 0
            }
            lasttime = now
        }
    }()

    return up
}

func main() {
    win, err := x11.NewWindow()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer win.Close()

    go func() {
        upfps := fps()
        screen := win.Screen()

        for {
            gennoise(screen)

            win.FlushImage()

            upfps <- true
        }
    }()

    for _ = range win.EventChan() {
    }
}




Python: black = color(0)
white = color(255)

def setup():
    size(320, 240)
    


def draw():
    loadPixels()
    for i in range(len(pixels)):
        if random(1) < 0.5:
            pixels[i] = black
        else:
            pixels[i] = white

    updatePixels()
    fill(0, 128)
    rect(0, 0, 60, 20)
    fill(255)
    text(frameRate, 5, 15)