WeixiangYan/CodeTransOcean huggingface dataset:
Task: Fractran




Go: package main

import (
    "fmt"
    "log"
    "math/big"
    "os"
    "strconv"
    "strings"
)

func compile(src string) ([]big.Rat, bool) {
    s := strings.Fields(src)
    r := make([]big.Rat, len(s))
    for i, s1 := range s {
        if _, ok := r[i].SetString(s1); !ok {
            return nil, false
        }
    }
    return r, true
}

func exec(p []big.Rat, n *big.Int, limit int) {
    var q, r big.Int
rule:
    for i := 0; i < limit; i++ {
        fmt.Printf("%d ", n)
        for j := range p {
            q.QuoRem(n, p[j].Denom(), &r)
            if r.BitLen() == 0 {
                n.Mul(&q, p[j].Num())
                continue rule
            }
        }
        break
    }
    fmt.Println()
}

func usage() {
    log.Fatal("usage: ft <limit> <n> <prog>")
}

func main() {
    if len(os.Args) != 4 {
        usage()
    }
    limit, err := strconv.Atoi(os.Args[1])
    if err != nil {
        usage()
    }
    var n big.Int
    _, ok := n.SetString(os.Args[2], 10)
    if !ok {
        usage()
    }
    p, ok := compile(os.Args[3])
    if !ok {
        usage()
    }
    exec(p, &n, limit)
}








Ada: with Ada.Text_IO;

procedure Fractan is
   
   type Fraction is record Nom: Natural; Denom: Positive; end record;
   type Frac_Arr is array(Positive range <>) of Fraction;
   
   function "/" (N: Natural; D: Positive) return Fraction is
      Frac: Fraction := (Nom => N, Denom => D);
   begin
      return Frac;
   end "/";
   
   procedure F(List: Frac_Arr; Start: Positive; Max_Steps: Natural) is
      N: Positive := Start;
      J: Positive;
   begin
      Ada.Text_IO.Put(" 0:" & Integer'Image(N) & "   ");
      for I in 1 .. Max_Steps loop
	 J := List'First;
	 loop
	    if N mod List(J).Denom = 0 then
	       N := (N/List(J).Denom) * List(J).Nom;
	       exit; 
	    elsif J >= List'Last then
	       return; 
	    else
	       J := J + 1; 
	    end if;
	 end loop;
	 Ada.Text_IO.Put(Integer'Image(I) & ":" & Integer'Image(N) & "   ");
      end loop;
   end F;
   
begin
   
   

   F((17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 
      77/19,  1/17, 11/13, 13/11, 15/14,  15/2, 55/1), 
     2, 15);
   
end Fractan;
Task: Substring_Top and tail




Go: package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    
    s := "ASCII"
    fmt.Println("String:                ", s)
    fmt.Println("First byte removed:    ", s[1:])
    fmt.Println("Last byte removed:     ", s[:len(s)-1])
    fmt.Println("First and last removed:", s[1:len(s)-1])
    
    u := "Δημοτική"
    fmt.Println("String:                ", u)
    _, sizeFirst := utf8.DecodeRuneInString(u)
    fmt.Println("First rune removed:    ", u[sizeFirst:])
    _, sizeLast := utf8.DecodeLastRuneInString(u)
    fmt.Println("Last rune removed:     ", u[:len(u)-sizeLast])
    fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}








Ada: with Ada.Text_IO;

procedure Remove_Characters is
   S: String := "upraisers";
   use Ada.Text_IO;
begin
   Put_Line("Full String:   """ & S & """");
   Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """");
   Put_Line("Without_Last:  """ & S(S'First   .. S'Last-1) & """");
   Put_Line("Without_Both:  """ & S(S'First+1 .. S'Last-1) & """");
end Remove_Characters;
Task: Boolean values




Go:  
package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var n bool = true
	fmt.Println(n)        
	fmt.Printf("%T\n", n) 
	n = !n
	fmt.Println(n) 

	x := 5
	y := 8
	fmt.Println("x == y:", x == y) 
	fmt.Println("x < y:", x < y)   

	fmt.Println("\nConvert String into Boolean Data type\n")
	str1 := "japan"
	fmt.Println("Before :", reflect.TypeOf(str1)) 
	bolStr, _ := strconv.ParseBool(str1)
	fmt.Println("After :", reflect.TypeOf(bolStr)) 
}








Ada:    type Boolean is (False, True);
Task: Multiline shebang




Go: #!/bin/bash
sed -n -e '12,$p' < "$0" > ttmmpp.go
go build ttmmpp.go
rm ttmmpp.go
binfile="${0%.*}"
mv ttmmpp $binfile
$binfile "$@"
STATUS=$?
rm $binfile
exit $STATUS
######## Go Code start on line 12
package main
import (
  "fmt"
  "os"
)
 
func main() {
  for i, x := range os.Args {
    if i == 0 {
      fmt.Printf("This program is named %s.\n", x)
    } else {
      fmt.Printf("the argument #%d is %s\n", i, x)
    }
  }
}








Ada: #!/bin/bash
sed -n -e '7,$p' < "$0" > mulshbang.adb
gnatmake -q mulshbang
./mulshbang $*
rm mulshbang*
exit 
with Ada.Text_IO, Ada.Command_Line; 

procedure Mulshbang is
  use Ada.Text_IO;
begin
  Put_Line("Name: " & Ada.Command_Line.Command_Name);
  for I in 1 .. Ada.Command_Line.Argument_Count loop
    Put_Line("  Arg" & Integer'Image(I) & ": " &
             Ada.Command_Line.Argument(I));
  end loop;
end Mulshbang;
Task: Bitmap_Histogram




Go: package raster

import "math"

func (g *Grmap) Histogram(bins int) []int {
    if bins <= 0 {
        bins = g.cols
    }
    h := make([]int, bins)
    for _, p := range g.px {
        h[int(p)*(bins-1)/math.MaxUint16]++
    }
    return h
}

func (g *Grmap) Threshold(t uint16) {
    for i, p := range g.px {
        if p < t {
            g.px[i] = 0
        } else {
            g.px[i] = math.MaxUint16
        }
    }
}








Ada: type Pixel_Count is mod 2**64;
type Histogram is array (Luminance) of Pixel_Count;
   
function Get_Histogram (Picture : Grayscale_Image) return Histogram is
   Result : Histogram := (others => 0);
begin
   for I in Picture'Range (1) loop
      for J in Picture'Range (2) loop
         declare
            Count : Pixel_Count renames Result (Picture (I, J));
         begin
            Count := Count + 1;
         end;
      end loop;
   end loop;
   return Result;
end Get_Histogram;
Task: Plot coordinate pairs




Go: package main

import (
  "fmt"
  "log"
  "os/exec"
)

var (
  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)

func main() {
  g := exec.Command("gnuplot", "-persist")
  w, err := g.StdinPipe()
  if err != nil {
    log.Fatal(err)
  }
  if err = g.Start(); err != nil {
    log.Fatal(err)
  }
  fmt.Fprintln(w, "unset key; plot '-'")
  for i, xi := range x {
    fmt.Fprintf(w, "%d %f\n", xi, y[i])
  }
  fmt.Fprintln(w, "e")
  w.Close()
  g.Wait()
}








Ada: with Gtk.Main;
with Gtk.Window;  use Gtk.Window;
with Gtk.Widget;  use Gtk.Widget;
with Gtk.Handlers;  use Gtk.Handlers;
with Glib;  use Glib;
with Gtk.Extra.Plot;  use Gtk.Extra.Plot;
with Gtk.Extra.Plot_Data;  use Gtk.Extra.Plot_Data;
with Gtk.Extra.Plot_Canvas;  use Gtk.Extra.Plot_Canvas;
with Gtk.Extra.Plot_Canvas.Plot;  use Gtk.Extra.Plot_Canvas.Plot;

procedure PlotCoords is
   package Handler is new Callback (Gtk_Widget_Record);

   Window : Gtk_Window;
   Plot : Gtk_Plot;
   PCP : Gtk_Plot_Canvas_Plot;
   Canvas : Gtk_Plot_Canvas;
   PlotData : Gtk_Plot_Data;
   x, y, dx, dy : Gdouble_Array_Access;

   procedure ExitMain (Object : access Gtk_Widget_Record'Class) is
   begin
      Destroy (Object);  Gtk.Main.Main_Quit;
   end ExitMain;

begin
   x := new Gdouble_Array'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);
   y := new Gdouble_Array'(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0);
   Gtk.Main.Init;
   Gtk_New (Window);
   Set_Title (Window, "Plot coordinate pairs with GtkAda");
   Gtk_New (PlotData);
   Set_Points (PlotData, x, y, dx, dy);
   Gtk_New (Plot);
   Add_Data (Plot, PlotData);
   Autoscale (Plot);  Show (PlotData);
   Hide_Legends (Plot);
   Gtk_New (PCP, Plot);  Show (Plot);
   Gtk_New (Canvas, 500, 500);  Show (Canvas);
   Put_Child (Canvas, PCP, 0.15, 0.15, 0.85, 0.85);
   Add (Window, Canvas);
   Show_All (Window);
   Handler.Connect (Window, "destroy",
      Handler.To_Marshaller (ExitMain'Access));
   Gtk.Main.Main;
end PlotCoords;
Task: LZW compression




Go: package main

import (
	"fmt"
	"log"
	"strings"
)


func compress(uncompressed string) []int {
	
	dictSize := 256
	
	
	dictionary := make(map[string]int, dictSize)
	for i := 0; i < dictSize; i++ {
		
		
		dictionary[string([]byte{byte(i)})] = i
	}

	var result []int
	var w []byte
	for i := 0; i < len(uncompressed); i++ {
		c := uncompressed[i]
		wc := append(w, c)
		if _, ok := dictionary[string(wc)]; ok {
			w = wc
		} else {
			result = append(result, dictionary[string(w)])
			
			dictionary[string(wc)] = dictSize
			dictSize++
			
			wc[0] = c
			w = wc[:1]
		}
	}

	if len(w) > 0 {
		
		result = append(result, dictionary[string(w)])
	}
	return result
}

type BadSymbolError int

func (e BadSymbolError) Error() string {
	return fmt.Sprint("Bad compressed symbol ", int(e))
}


func decompress(compressed []int) (string, error) {
	
	dictSize := 256
	dictionary := make(map[int][]byte, dictSize)
	for i := 0; i < dictSize; i++ {
		dictionary[i] = []byte{byte(i)}
	}

	var result strings.Builder
	var w []byte
	for _, k := range compressed {
		var entry []byte
		if x, ok := dictionary[k]; ok {
			
			entry = x[:len(x):len(x)]
		} else if k == dictSize && len(w) > 0 {
			entry = append(w, w[0])
		} else {
			return result.String(), BadSymbolError(k)
		}
		result.Write(entry)

		if len(w) > 0 {
			
			w = append(w, entry[0])
			dictionary[dictSize] = w
			dictSize++
		}
		w = entry
	}
	return result.String(), nil
}

func main() {
	compressed := compress("TOBEORNOTTOBEORTOBEORNOT")
	fmt.Println(compressed)
	decompressed, err := decompress(compressed)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(decompressed)
}








Ada: package LZW is

   MAX_CODE : constant := 4095;

   type Codes is new Natural range 0 .. MAX_CODE;
   type Compressed_Data is array (Positive range <>) of Codes;

   function Compress (Cleartext : in String) return Compressed_Data;
   function Decompress (Data : in Compressed_Data) return String;

end LZW;
Task: Check input device is a terminal




Go: package main

import (
    "golang.org/x/crypto/ssh/terminal"
    "fmt"
    "os"
)

func main() {
    if terminal.IsTerminal(int(os.Stdin.Fd())) {
        fmt.Println("Hello terminal")
    } else {
        fmt.Println("Who are you?  You're not a terminal.")
    }
}








Ada: with Ada.Text_IO;          use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;

procedure Test_tty is
begin
   if Isatty(Fileno(Stdin)) = 0 then
      Put_Line(Standard_Error, "stdin is not a tty.");
   else
      Put_Line(Standard_Error, "stdin is a tty.");
   end if;
end Test_tty;
Task: First 9 prime Fibonacci number




Go: package main

import "fmt"

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

func main() {
    f1 := uint64(1)
    f2 := f1
    count := 0
    limit := 12 
    fmt.Printf("The first %d prime Fibonacci numbers are:\n", limit)
    for count < limit {
        f3 := f1 + f2
        if isPrime(f3) {
            fmt.Printf("%d ", f3)
            count++
        }
        f1 = f2
        f2 = f3
    }
    fmt.Println()
}








Ada: with Ada.Text_IO;

procedure Prime_Fibonacci is

   function Is_Prime (A : Natural) return Boolean is
      D : Natural;
   begin
      if A < 2       then return False; end if;
      if A in 2 .. 3 then return True;  end if;
      if A mod 2 = 0 then return False; end if;
      if A mod 3 = 0 then return False; end if;
      D := 5;
      while D * D <= A loop
         if A mod D = 0 then
            return False;
         end if;
         D := D + 2;
         if A mod D = 0 then
            return False;
         end if;
         D := D + 4;
      end loop;
      return True;
   end Is_Prime;

   F_1   : Natural := 0;
   F_2   : Natural := 1;

   function Fibonacci return Natural is
      R : Natural := F_1 + F_2;
   begin
      F_1 := F_2;
      F_2 := R;
      return R;
   end Fibonacci;

   Count : Natural := 0;
   Fib   : Natural;
begin
   while Count < 9 loop
      Fib := Fibonacci;
      if Is_Prime (Fib) then
         Count := Count + 1;
         Ada.Text_IO.Put_Line (Fib'Image);
      end if;
   end loop;
end Prime_Fibonacci;
Task: Terminal control_Inverse video




Go: package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    tput("rev")
    fmt.Print("Rosetta")
    tput("sgr0")
    fmt.Println(" Code")
}

func tput(arg string) error {
    cmd := exec.Command("tput", arg)
    cmd.Stdout = os.Stdout
    return cmd.Run()
}








Ada: with Ada.Text_IO; use  Ada.Text_IO;

procedure Reverse_Video is 

   Rev_Video  : String := Ascii.ESC & "[7m";
   Norm_Video : String := Ascii.ESC & "[m";

begin
   Put (Rev_Video & "Reversed");
   Put (Norm_Video & " Normal");
end Reverse_Video;
Task: Ulam spiral (for primes)




Go: package main

import (
	"math"
	"fmt"
)

type Direction byte

const (
	RIGHT Direction = iota
	UP
	LEFT
	DOWN
)

func generate(n,i int, c byte) {
	s := make([][]string, n)
	for i := 0; i < n; i++ { s[i] = make([]string, n) }
	dir := RIGHT
	y := n / 2
	var x int
	if (n % 2 == 0) { x = y - 1 } else { x = y } 

	for j := i; j <= n * n - 1 + i; j++ {
		if (isPrime(j)) {
			if (c == 0) { s[y][x] = fmt.Sprintf("%3d", j) } else { s[y][x] = fmt.Sprintf("%2c ", c) }
		} else { s[y][x] = "---" }

		switch dir {
		case RIGHT : if (x <= n - 1 && s[y - 1][x] == "" && j > i) { dir = UP }
		case UP : if (s[y][x - 1] == "") { dir = LEFT }
		case LEFT : if (x == 0 || s[y + 1][x] == "") { dir = DOWN }
		case DOWN : if (s[y][x + 1] == "") { dir = RIGHT }
		}

		switch dir {
		case RIGHT : x += 1
		case UP : y -= 1
		case LEFT : x -= 1
		case DOWN : y += 1
		}
	}

	for _, row := range s { fmt.Println(fmt.Sprintf("%v", row)) }
	fmt.Println()
}

func isPrime(a int) bool {
	if (a == 2) { return true }
	if (a <= 1 || a % 2 == 0) { return false }
	max := int(math.Sqrt(float64(a)))
	for n := 3; n <= max; n += 2 { if (a % n == 0) { return false } }
	return true
}

func main() {
	generate(9, 1, 0) 
	generate(9, 1, '*') 
}








Ada: generic
   Size: Positive; 
      
   with function Represent(N: Natural) return String;
      
      
      
      
   with procedure Put_String(S: String);
      
   with procedure New_Line;
      
package Generic_Ulam is
   
   procedure Print_Spiral;
   
   
   
end Generic_Ulam;
Task: Fibonacci word




Go: package main

import (
	"fmt"
	"math"
)


func entropy(s string) float64 {
	m := map[rune]float64{}
	for _, r := range s {
		m[r]++
	}
	hm := 0.
	for _, c := range m {
		hm += c * math.Log2(c)
	}
	l := float64(len(s))
	return math.Log2(l) - hm/l
}

const F_Word1 = "1"
const F_Word2 = "0"

func FibonacciWord(n int) string {
	a, b := F_Word1, F_Word2
	for ; n > 1; n-- {
		a, b = b, b+a
	}
	return a
}

func FibonacciWordGen() <-chan string {
	ch := make(chan string)
	go func() {
		a, b := F_Word1, F_Word2
		for {
			ch <- a
			a, b = b, b+a
		}
	}()
	return ch
}

func main() {
	fibWords := FibonacciWordGen()
	fmt.Printf("%3s %9s  %-18s  %s\n", "N", "Length", "Entropy", "Word")
	n := 1
	for ; n < 10; n++ {
		s := <-fibWords
		
		if s2 := FibonacciWord(n); s != s2 {
			fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
		}
		fmt.Printf("%3d %9d  %.16f  %s\n", n, len(s), entropy(s), s)
	}
	for ; n <= 37; n++ {
		s := <-fibWords
		fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s))
	}
}








Ada: with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
  Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions,
  Ada.Long_Float_Text_IO;
use  Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
  Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions,
  Ada.Long_Float_Text_IO;

procedure Fibonacci_Words is

   function Entropy (S : Unbounded_String) return Long_Float is
      CF    : array (Character) of Natural := (others => 0);
      Len   : constant Natural             := Length (S);
      H     : Long_Float                   := 0.0;
      Ratio : Long_Float;
   begin
      for I in 1 .. Len loop
         CF (Element (S, I)) := CF (Element (S, I)) + 1;
      end loop;
      for C in Character loop
         Ratio := Long_Float (CF (C)) / Long_Float (Len);
         if Ratio /= 0.0 then
            H := H - Ratio * Log (Ratio, 2.0);
         end if;
      end loop;
      return H;
   end Entropy;

   procedure Print_Line (Word : Unbounded_String; Number : Integer) is
   begin
      Put (Number, 4);
      Put (Length (Word), 10);
      Put (Entropy (Word), 2, 15, 0);
      if Length (Word) < 35 then
         Put ("  " & Word);
      end if;
      New_Line;
   end Print_Line;

   First, Second, Result : Unbounded_String;

begin
   Set_Col (4);  Put ("N");
   Set_Col (9);  Put ("Length");
   Set_Col (16); Put ("Entropy");
   Set_Col (35); Put_Line ("Word");
   First := To_Unbounded_String ("1");
   Print_Line (First, 1);
   Second := To_Unbounded_String ("0");
   Print_Line (Second, 2);
   for N in 3 .. 37 loop
      Result := Second & First;
      Print_Line (Result, N);
      First  := Second;
      Second := Result;
   end loop;
end Fibonacci_Words;
Task: Bitmap_Bézier curves_Cubic




Go: package raster

const b3Seg = 30

func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {
    var px, py [b3Seg + 1]int
    fx1, fy1 := float64(x1), float64(y1)
    fx2, fy2 := float64(x2), float64(y2)
    fx3, fy3 := float64(x3), float64(y3)
    fx4, fy4 := float64(x4), float64(y4)
    for i := range px {
        d := float64(i) / b3Seg
        a := 1 - d
        b, c := a * a, d * d
        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d
        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)
        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)
    }
    x0, y0 := px[0], py[0]
    for i := 1; i <= b3Seg; i++ {
        x1, y1 := px[i], py[i]
        b.Line(x0, y0, x1, y1, p)
        x0, y0 = x1, y1
    }
}

func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {
    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())
}








Ada: procedure Cubic_Bezier
          (  Picture        : in out Image;
             P1, P2, P3, P4 : Point;
             Color          : Pixel;
             N              : Positive := 20
          )  is
   Points : array (0..N) of Point;
begin
   for I in Points'Range loop
      declare
         T : constant Float := Float (I) / Float (N);
         A : constant Float := (1.0 - T)**3;
         B : constant Float := 3.0 * T * (1.0 - T)**2;
         C : constant Float := 3.0 * T**2 * (1.0 - T);
         D : constant Float := T**3;
      begin
         Points (I).X := Positive (A * Float (P1.X) + B * Float (P2.X) + C * Float (P3.X) + D * Float (P4.X));
         Points (I).Y := Positive (A * Float (P1.Y) + B * Float (P2.Y) + C * Float (P3.Y) + D * Float (P4.Y));
      end;
   end loop;
   for I in Points'First..Points'Last - 1 loop
      Line (Picture, Points (I), Points (I + 1), Color);
   end loop;
end Cubic_Bezier;
Task: Rendezvous




Go: package main

import (
    "errors"
    "fmt"
    "strings"
    "sync"
)

var hdText = `Humpty Dumpty sat on a wall.
Humpty Dumpty had a great fall.
All the king's horses and all the king's men,
Couldn't put Humpty together again.`

var mgText = `Old Mother Goose,
When she wanted to wander,
Would ride through the air,
On a very fine gander.
Jack's mother came in,
And caught the goose soon,
And mounting its back,
Flew up to the moon.`

func main() {
    reservePrinter := startMonitor(newPrinter(5), nil)
    mainPrinter := startMonitor(newPrinter(5), reservePrinter)
    var busy sync.WaitGroup
    busy.Add(2)
    go writer(mainPrinter, "hd", hdText, &busy)
    go writer(mainPrinter, "mg", mgText, &busy)
    busy.Wait()
}




type printer func(string) error





func newPrinter(ink int) printer {
    return func(line string) error {
        if ink == 0 {
            return eOutOfInk
        }
        for _, c := range line {
            fmt.Printf("%c", c)
        }
        fmt.Println()
        ink--
        return nil
    }
}

var eOutOfInk = errors.New("out of ink")















type rSync struct {
    call     chan string
    response chan error
}






func (r *rSync) print(data string) error {
    r.call <- data      
    return <-r.response 
}




func monitor(hardPrint printer, entry, reserve *rSync) {
    for {
        
        
        data := <-entry.call
        
        
        

        
        switch err := hardPrint(data); {

        
        case err == nil:
            entry.response <- nil 

        case err == eOutOfInk && reserve != nil:
            
            
            
            
            entry.response <- reserve.print(data)

        default:
            entry.response <- err 
        }
        
    }
}






func startMonitor(p printer, reservePrinter *rSync) *rSync {
    entry := &rSync{make(chan string), make(chan error)}
    go monitor(p, entry, reservePrinter)
    return entry
}






func writer(printMonitor *rSync, id, text string, busy *sync.WaitGroup) {
    for _, line := range strings.Split(text, "\n") {
        if err := printMonitor.print(line); err != nil {
            fmt.Printf("**** writer task %q terminated: %v ****\n", id, err)
            break
        }
    }
    busy.Done()
}








Ada: select
   Server.Wake_Up (Parameters);
or delay 5.0;
   
   ...
end select;
Task: Draw a sphere




Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/png"
    "math"
    "os"
)

type vector [3]float64

func normalize(v *vector) {
    invLen := 1 / math.Sqrt(dot(v, v))
    v[0] *= invLen
    v[1] *= invLen
    v[2] *= invLen
}

func dot(x, y *vector) float64 {
    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}

func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
    w, h := r*4, r*3
    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
    vec := new(vector)
    for x := -r; x < r; x++ {
        for y := -r; y < r; y++ {
            if z := r*r - x*x - y*y; z >= 0 {
                vec[0] = float64(x)
                vec[1] = float64(y)
                vec[2] = math.Sqrt(float64(z))
                normalize(vec)
                s := dot(dir, vec)
                if s < 0 {
                    s = 0
                }
                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
                if lum < 0 {
                    lum = 0
                } else if lum > 255 {
                    lum = 255
                }
                img.SetGray(x, y, color.Gray{uint8(lum)})
            }
        }
    }
    return img
}

func main() {
    dir := &vector{-30, -30, 50}
    normalize(dir)
    img := drawSphere(200, 1.5, .2, dir)
    f, err := os.Create("sphere.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, img); err != nil {
        fmt.Println(err)
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
}








Ada: with Glib;                use Glib;
with Cairo;               use Cairo;
with Cairo.Png;           use Cairo.Png;
with Cairo.Pattern;       use Cairo.Pattern;
with Cairo.Image_Surface; use Cairo.Image_Surface;
with Ada.Numerics;

procedure Sphere is
   subtype Dub is Glib.Gdouble;

   Surface    : Cairo_Surface;
   Cr         : Cairo_Context;
   Pat        : Cairo_Pattern;
   Status_Out : Cairo_Status;
   M_Pi       : constant Dub := Dub (Ada.Numerics.Pi);

begin
   Surface := Create (Cairo_Format_ARGB32, 512, 512);
   Cr      := Create (Surface);
   Pat     :=
      Cairo.Pattern.Create_Radial (230.4, 204.8, 51.1, 204.8, 204.8, 256.0);
   Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 0.0, 1.0, 1.0, 1.0, 1.0);
   Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 1.0, 0.0, 0.0, 0.0, 1.0);
   Cairo.Set_Source (Cr, Pat);
   Cairo.Arc (Cr, 256.0, 256.0, 153.6, 0.0, 2.0 * M_Pi);
   Cairo.Fill (Cr);
   Cairo.Pattern.Destroy (Pat);
   Status_Out := Write_To_Png (Surface, "SphereAda.png");
   pragma Assert (Status_Out = Cairo_Status_Success);
end Sphere;