WeixiangYan/CodeTransOcean huggingface dataset:
Task: Linux CPU utilization


C++: #include <fstream>
#include <iostream>
#include <numeric>
#include <unistd.h>
#include <vector>

std::vector<size_t> get_cpu_times() {
    std::ifstream proc_stat("/proc/stat");
    proc_stat.ignore(5, ' '); 
    std::vector<size_t> times;
    for (size_t time; proc_stat >> time; times.push_back(time));
    return times;
}

bool get_cpu_times(size_t &idle_time, size_t &total_time) {
    const std::vector<size_t> cpu_times = get_cpu_times();
    if (cpu_times.size() < 4)
        return false;
    idle_time = cpu_times[3];
    total_time = std::accumulate(cpu_times.begin(), cpu_times.end(), 0);
    return true;
}

int main(int, char *[]) {
    size_t previous_idle_time=0, previous_total_time=0;
    for (size_t idle_time, total_time; get_cpu_times(idle_time, total_time); sleep(1)) {
        const float idle_time_delta = idle_time - previous_idle_time;
        const float total_time_delta = total_time - previous_total_time;
        const float utilization = 100.0 * (1.0 - idle_time_delta / total_time_delta);
        std::cout << utilization << '%' << std::endl;
        previous_idle_time = idle_time;
        previous_total_time = total_time;
    }
}









Fortran: Program CPUusage
    implicit none
    integer :: ios, i
    integer :: oldidle, oldsum, sumtimes = 0
    real :: percent = 0.
    character(len = 4) lineID 
    integer, dimension(9) :: times = 0

    write(*, *) 'CPU Usage'
    write(*, *) 'Press Ctrl<C> to end'
    do while (.true.)
        open(unit = 7, file = '/proc/stat', status = 'old', action = 'read', iostat = ios)
        if (ios /= 0) then
            print *, 'Error opening /proc/stat'
            stop
        else
            read(unit = 7, fmt = *, iostat = ios) lineID, (times(i), i = 1, 9)
            close(7)
            if (lineID /= 'cpu ') then
                print *, 'Error reading /proc/stat'
                stop
            end if
            sumtimes = sum(times)
            percent = (1. - real((times(4) - oldidle)) / real((sumtimes - oldsum))) * 100.
            write(*, fmt = '(F6.2,A2)') percent, '%'
            oldidle = times(4)
            oldsum = sumtimes
            call sleep(1)
        end if
    end do
end program CPUusage
Task: Type detection


C++: #include <iostream>

template <typename T>
auto typeString(const T&) {
    return typeid(T).name();
}

class C {};
struct S {};

int main() {
    std::cout << typeString(1) << '\n';
    std::cout << typeString(1L) << '\n';
    std::cout << typeString(1.0f) << '\n';
    std::cout << typeString(1.0) << '\n';
    std::cout << typeString('c') << '\n';
    std::cout << typeString("string") << '\n';
    std::cout << typeString(C{}) << '\n';
    std::cout << typeString(S{}) << '\n';
    std::cout << typeString(nullptr) << '\n';
}









Fortran: program input_type_detection_demo
  implicit none

  type text_block_t
     character(len = 10000), allocatable :: lines(:)
  end type text_block_t

  type(text_block_t) :: text_block
  integer :: i

  call print_text ('Print me.')

  allocate (text_block%lines(1:10))
  do i = 1, 10
     write (text_block%lines(i), '("i = ", I0)') i
  end do
  call print_text (text_block)

  open (100, file = 'type_detection-fortran.f90', action = 'read')
  call print_text (100)
  close (100)

contains

  subroutine print_text (source)
    class(*), intent(in) :: source

    select type (source)

    type is (character(len = *))
       
       write (*, '(A)') source

    class is (text_block_t)
       
       block
         integer :: i
         do i = lbound (source%lines, 1), ubound (source%lines, 1)
            write (*, '(A)') trim (source%lines(i))
         end do
       end block

    type is (integer)
       
       block
         character(len = 10000) :: line_buffer
         integer :: stat
         read (source, '(A)', iostat = stat) line_buffer
         do while (stat == 0)
            write (*, '(A)') trim (line_buffer)
            read (source, '(A)', iostat = stat) line_buffer
         end do
       end block

    class default
       
       error stop

    end select
  end subroutine print_text

end program input_type_detection_demo
Task: Special variables


C++: #include <iostream>

struct SpecialVariables
{
    int i = 0;

    SpecialVariables& operator++()
    {
        
        
        
        this->i++;  

        
        return *this;
    }

};

int main()
{
    SpecialVariables sv;
    auto sv2 = ++sv;     
    std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n";
}









Fortran:            INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST,	
     1      ERR = 666,IOSTAT = IOSTAT) 		
           IF (EXIST) THEN	
           ...etc.
Task: Arithmetic-geometric mean_Calculate Pi


C++: #include <gmpxx.h>
#include <chrono>

using namespace std;
using namespace chrono;
 
void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1,
        const mpf_class& op2)
{
    rop1 = (op1 + op2) / 2;
    rop2 = op1 * op2;
    mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t());
}
 
int main(void)
{
    auto st = steady_clock::now();
    mpf_set_default_prec(300000);
    mpf_class x0, y0, resA, resB, Z;
 
    x0 = 1;
    y0 = 0.5;
    Z  = 0.25;
    mpf_sqrt(y0.get_mpf_t(), y0.get_mpf_t());
 
    int n = 1;
    for (int i = 0; i < 8; i++) {
        agm(resA, resB, x0, y0);
        Z -= n * (resA - x0) * (resA - x0);
        n *= 2;
 
        agm(x0, y0, resA, resB);
        Z -= n * (x0 - resA) * (x0 - resA);
        n *= 2;
    }
 
    x0 = x0 * x0 / Z;
    printf("Took %f ms for computation.\n", duration<double>(steady_clock::now() - st).count() * 1000.0);
    st = steady_clock::now();
    gmp_printf ("%.89412Ff\n", x0.get_mpf_t());
    printf("Took %f ms for output.\n", duration<double>(steady_clock::now() - st).count() * 1000.0);
    return 0;
}









Fortran: program CalcPi
    
    use iso_fortran_env, only: rf => real128
    implicit none
    real(rf) :: a,g,s,old_pi,new_pi
    real(rf) :: a1,g1,s1
    integer :: k,k1,i

    old_pi = 0.0_rf;
    a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0

    do i=1,100
        call approx_pi_step(a,g,s,k,a1,g1,s1,k1)
        new_pi = 4.0_rf * (a1**2.0_rf) / (1.0_rf - s1)
        if (abs(new_pi - old_pi).lt.(2.0_rf*epsilon(new_pi))) then
            
            
            exit
        end if
        write(*,*) 'Iteration:',k1,' Diff:',abs(new_pi - old_pi),' Pi:',new_pi
        old_pi = new_pi
        a = a1; g = g1; s = s1; k = k1
    end do

    contains

    subroutine approx_pi_step(x,y,z,n,a,g,s,k)
        real(rf), intent(in) :: x,y,z
        integer, intent(in) :: n
        real(rf), intent(out) :: a,g,s
        integer, intent(out) :: k

        a = 0.5_rf*(x+y)
        g = sqrt(x*y)
        k = n + 1
        s = z + (2.0_rf)**(real(k)+1.0_rf) * (a**(2.0_rf) - g**(2.0_rf))
    end subroutine
end program CalcPi
Task: Primorial numbers


C++: using System;

class Program {

    static int l;

    static int[] gp(int n) {
        var c = new bool[n]; var r = new int[(int)(1.28 * n)];
        l = 0; r[l++] = 2; r[l++] = 3; int j, d, lim = (int)Math.Sqrt(n);
        for (int i = 9; i < n; i += 6) c[i] = true; 
        for (j = 5, d = 4; j < lim; j += (d = 6 - d)) if (!c[j]) { r[l++] = j;
            for (int k = j * j, ki = j << 1; k < n; k += ki) c[k] = true; }
        for ( ; j < n; j += (d = 6 - d)) if (!c[j]) r[l++] = j; return r; }

    static void Main(string[] args) {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        var res = gp(15485864); sw.Stop();
        double gpt = sw.Elapsed.TotalMilliseconds, tt;
        var s = new string[19]; int si = 0;
        s[si++] = String.Format("primes gen time: {0} ms", gpt); sw.Restart();
        s[si++] = "    Nth Primorial";
        double y = 0; int x = 1, i = 0, lmt = 10;
        s[si++] = String.Format("{0,7} {1}", 0, x);
        while (true) {
            if (i < 9) s[si++] = String.Format("{0,7} {1}", i + 1, x *= res[i]);
            if (i == 8) s[si++] = "    Nth Digits     Time";
            y += Math.Log10(res[i]);
            if (++i == lmt) {
                s[si++] = String.Format("{0,7} {1,-7}  {2,7} ms", lmt, 1 + (int)y,
                    sw.Elapsed.TotalMilliseconds);
                if ((lmt *= 10) > (int)1e6) break;    }    }
        sw.Stop();
        Console.WriteLine("{0}\n     Tabulation: {1} ms", string.Join("\n", s),
            tt = sw.Elapsed.TotalMilliseconds);
        Console.Write("          Total:{0} ms", gpt + tt);    }    }









Fortran:       B.DIGIT(I) = MOD(D,BIGBASE)
      C = D/BIGBASE
Task: Random number generator (included)


C++: #include <iostream>
#include <string>
#include <random>
 
int main()
{
    std::random_device rd;
    std::uniform_int_distribution<int> dist(1, 10);
    std::mt19937 mt(rd());
    
    std::cout << "Random Number (hardware): " << dist(rd) << std::endl;
    std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl;
}









Fortran: program rosetta_random
   implicit none

   integer, parameter :: rdp = kind(1.d0)
   real(rdp) :: num
   integer, allocatable :: seed(:)
   integer :: un,n, istat

   call random_seed(size = n)
   allocate(seed(n))

   
   open(newunit=un, file="/dev/urandom", access="stream", &
   form="unformatted", action="read", status="old", iostat=istat)
   if (istat == 0) then
      read(un) seed
      close(un)
   end if
   call random_seed (put=seed)
   call random_number(num)
   write(*,'(E24.16)') num
end program rosetta_random
Task: Prime conspiracy


C++: #include <vector>
#include <iostream>
#include <cmath>
#include <utility>
#include <map>
#include <iomanip>

bool isPrime( int i ) {
   int stop = std::sqrt( static_cast<double>( i ) ) ;
   for ( int d = 2 ; d <= stop ; d++ )
      if ( i % d == 0 )
	 return false ;
   return true ;
}

class Compare {
public :
   Compare( ) {
   }

   bool operator( ) ( const std::pair<int , int> & a , const std::pair<int, int> & b ) {
      if ( a.first != b.first ) 
	 return a.first < b.first ;
      else
	 return a.second < b.second ;
   }
};

int main( ) {
   std::vector<int> primes {2} ;
   int current = 3 ;
   while ( primes.size( ) < 1000000 ) {
      if ( isPrime( current ) ) 
	 primes.push_back( current ) ;
      current += 2 ;
   }
   Compare myComp ;
   std::map<std::pair<int, int>, int , Compare> conspiracy (myComp) ;
   for ( int i = 0 ; i < primes.size( ) -1 ; i++ ) {
      int a = primes[i] % 10 ;
      int b = primes[ i + 1 ] % 10 ;
      std::pair<int , int> numbers { a , b} ;
      conspiracy[numbers]++ ;
   }
   std::cout << "1000000 first primes. Transitions prime % 10 → next-prime % 10.\n" ;
   for ( auto it = conspiracy.begin( ) ; it != conspiracy.end( ) ; it++ ) {
      std::cout << (it->first).first << " -> " << (it->first).second << " count:" ;
      int frequency = it->second ;
      std::cout << std::right << std::setw( 15 ) << frequency << " frequency: " ;
      std::cout.setf(std::ios::fixed, std::ios::floatfield ) ;
      std::cout.precision( 2 ) ;
      std::cout << (static_cast<double>(frequency) / 1000000.0) * 100 << " %\n" ;
   }
   return 0 ;
}









Fortran:       PROGRAM INHERIT	
      USE PRIMEBAG	
      INTEGER MBASE,P0,NHIC	
      PARAMETER (MBASE = 13, P0 = 2, NHIC = 100000000)	
      INTEGER N(0:MBASE - 1,0:MBASE - 1,2:MBASE)	
      INTEGER I,B,D1,D2	
      INTEGER P,PP	

      MSG = 6		
      WRITE (MSG,1) MBASE,P0,NHIC	
    1 FORMAT ("Working in base 2 to ",I0," count the transitions "
     1 "from the low-order digit of one prime number ",/,
     2 "to the low-order digit of its successor. Starting with ",I0,
     3 " and making ",I0," advances.")
      IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file

Chug through the primes.
   10 N = 0	
      P = P0	
      DO I = 1,NHIC	
        PP = P			
        P = NEXTPRIME(P)	
        DO B = 2,MBASE		
          D1 = MOD(PP,B)		
          D2 = MOD(P,B)			
          N(D1,D2,B) = N(D1,D2,B) + 1	
        END DO			
      END DO		
      WRITE (MSG,11) P	
   11 FORMAT ("Ending with ",I0)	

Cast forth the results.
   20 DO B = 2,MBASE	
        WRITE (MSG,21) B		
   21   FORMAT (/,"For base ",I0)	
        WRITE (MSG,22) (D1, D1 = 0,B - 1)	
   22   FORMAT (" Last digit ending  ",I2,66I9)	
        DO D2 = 0,B - 1		
          IF (ALL(N(0:B - 1,D2,B).EQ.0)) CYCLE	
          WRITE (MSG,23) D2,N(0:B - 1,D2,B)	
   23     FORMAT (" next prime ends",I3,":",I2,66I9)	
        END DO			
      END DO		
      END
Task: Statistics_Normal distribution


C++: #include <random>
#include <map>
#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>

int main( ) {
   std::random_device myseed ;
   std::mt19937 engine ( myseed( ) ) ;
   std::normal_distribution<> normDistri ( 2 , 3 ) ;
   std::map<int , int> normalFreq ;
   int sum = 0 ; 
   double mean = 0.0 ;
   double stddev = 0.0 ;
   for ( int i = 1 ; i < 10001 ; i++ ) 
      ++normalFreq[ normDistri ( engine ) ] ;
   for ( auto MapIt : normalFreq ) {
      sum += MapIt.first * MapIt.second ;
   }
   mean = sum / 10000 ;
   stddev = sqrt( sum / 10000 ) ;
   std::cout << "The mean of the distribution is " << mean << " , the " ;
   std::cout << "standard deviation " << stddev << " !\n" ;
   std::cout << "And now the histogram:\n" ;
   for ( auto MapIt : normalFreq ) {
      std::cout << std::left << std::setw( 4 ) << MapIt.first << 
	 std::string( MapIt.second / 100 , '*' ) << std::endl ;
   }
   return 0 ;
}









Fortran: program Normal_Distribution
  implicit none

  integer, parameter :: i64 = selected_int_kind(18)
  integer, parameter :: r64 = selected_real_kind(15)
  integer(i64), parameter :: samples = 1000000_i64
  real(r64) :: mean, stddev
  real(r64) :: sumn = 0, sumnsq = 0
  integer(i64) :: n = 0 
  integer(i64) :: bin(-50:50) = 0
  integer :: i, ind
  real(r64) :: ur1, ur2, nr1, nr2, s
  
  n = 0
  do while(n <= samples)
    call random_number(ur1)
    call random_number(ur2)
    ur1 = ur1 * 2.0 - 1.0
    ur2 = ur2 * 2.0 - 1.0
    
    s = ur1*ur1 + ur2*ur2  
    if(s >= 1.0_r64) cycle
      
    nr1 = ur1 * sqrt(-2.0*log(s)/s)
    ind = floor(5.0*nr1)
    bin(ind) = bin(ind) + 1_i64
    sumn = sumn + nr1
    sumnsq = sumnsq + nr1*nr1
    
    nr2 = ur2 * sqrt(-2.0*log(s)/s)
    ind = floor(5.0*nr2)
    bin(ind) = bin(ind) + 1_i64
    sumn = sumn + nr2
    sumnsq = sumnsq + nr2*nr2
    n = n + 2_i64
  end do
 
  mean = sumn / n
  stddev = sqrt(sumnsq/n - mean*mean)
  
  write(*, "(a, i0)") "sample size = ", samples
  write(*, "(a, f17.15)") "Mean :   ", mean,
  write(*, "(a, f17.15)") "Stddev : ", stddev
  
  do i = -15, 15 
    write(*, "(f4.1, a, a)") real(i)/5.0, ": ", repeat("=", int(bin(i)*500/samples))
  end do
       
end program
Task: Singly-linked list_Element removal


C++: #include <iostream>


struct link
{
  link* next;
  int data;

  link(int newItem, link* head)
  : next{head}, data{newItem}{}
};

void PrintList(link* head)
{
    if(!head) return;
    std::cout << head->data << " ";
    PrintList(head->next);
}

link* RemoveItem(int valueToRemove, link*&head)
{
    
    
    for(link** node = &head; *node; node = &((*node)->next))
    {
        if((*node)->data == valueToRemove)
        {
            
            link* removedNode = *node;
            *node = removedNode->next;
            removedNode->next = nullptr;
            return removedNode;
        }
    }

    
    return nullptr;
}

int main()
{
    
    link link33{33, nullptr};
    link link42{42, &link33};
    link link99{99, &link42};
    link link55{55, &link99};
    link* head = &link55;

    std::cout << "Full list: ";
    PrintList(head);

    std::cout << "\nRemove 55: ";
    auto removed = RemoveItem(55, head);
    PrintList(head);
    std::cout << "\nThe removed item: ";
    PrintList(removed);

    std::cout << "\nTry to remove -3: ";
    auto removed2 = RemoveItem(-3, head);
    PrintList(head);
    if (!removed2) std::cout << "\nItem not found\n";
}









Fortran:       MODULE SIMPLELINKEDLIST	
       CONTAINS			
        SUBROUTINE LLREMOVE(LINK,X)	
         INTEGER LINK(0:)	
         INTEGER X		
         INTEGER IT		
          IT = 0		
          DO WHILE(LINK(IT).GT.0)	
            IF (LINK(IT).EQ.X) THEN		
              LINK(IT) = LINK(LINK(IT))		
              RETURN				
            END IF			
            IT = LINK(IT)		
          END DO		
        END SUBROUTINE LLREMOVE	

        SUBROUTINE LLFOLLOW(LINK)	
         INTEGER LINK(0:)	
          IT = 0			
          WRITE (6,1) "Head",IT,LINK(IT)	
    1     FORMAT (A6,I3," -->",I3)		
    2     IT = LINK(IT)		
          IF (IT.LE.0) RETURN		
          WRITE (6,1) "at",IT,LINK(IT)	
          GO TO 2			
        END SUBROUTINE LLFOLLOW	
      END MODULE SIMPLELINKEDLIST	

      PROGRAM POKE
      USE SIMPLELINKEDLIST	
      INTEGER LINK(0:5)		
      DATA LINK/3, 2,4,1,5,0/	

      WRITE (6,*) "A linked-list, no cargo."
      CALL LLFOLLOW(LINK)

      WRITE (6,*) "The element at one suffers disfavour."
      CALL LLREMOVE(LINK,1)
      CALL LLFOLLOW(LINK)

      WRITE (6,*) "Off with the head
      CALL LLREMOVE(LINK,LINK(0))	
      CALL LLFOLLOW(LINK)

      WRITE (6,*) "And off with the tail."
      CALL LLREMOVE(LINK,5)		
      CALL LLFOLLOW(LINK)		

      END
Task: Executable library




Go: 
package main

import "fmt"




func hailstone(n int, recycle []int) []int {
    s := append(recycle[:0], n)
    for n > 1 {
        if n&1 == 0 {
            n = n / 2
        } else {
            n = 3*n + 1
        }
        s = append(s, n)
    }
    return s
}

func libMain() {
    seq := hailstone(27, nil)
    fmt.Println("\nHailstone sequence for the number 27:")
    fmt.Println("  has", len(seq), "elements")
    fmt.Println("  starts with", seq[0:4])
    fmt.Println("  ends with", seq[len(seq)-4:])

    var longest, length int
    for i := 1; i < 100000; i++ {
        if le := len(hailstone(i, nil)); le > length {
            longest = i
            length = le
        }
    }
    fmt.Printf("\n%d has the longest Hailstone sequence, its length being %d.\n", longest, length)
}
Task: Draw a pixel




Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
)

func main() {
    rect := image.Rect(0, 0, 320, 240)
    img := image.NewRGBA(rect)

    
    green := color.RGBA{0, 255, 0, 255}
    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)

    
    red := color.RGBA{255, 0, 0, 255}
    img.Set(100, 100, red)

    
    cmap := map[color.Color]string{green: "green", red: "red"}
    c1 := img.At(0, 0)
    c2 := img.At(100, 100)
    fmt.Println("The color of the pixel at (  0,   0) is", cmap[c1], "\b.")
    fmt.Println("The color of the pixel at (100, 100) is", cmap[c2], "\b.")
}
Task: Dining philosophers




Go: package main

import (
    "hash/fnv"
    "log"
    "math/rand"
    "os"
    "time"
)



var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}

const hunger = 3                
const think = time.Second / 100 
const eat = time.Second / 100   

var fmt = log.New(os.Stdout, "", 0) 

var done = make(chan bool)



type fork byte








func philosopher(phName string,
    dominantHand, otherHand chan fork, done chan bool) {
    fmt.Println(phName, "seated")
    
    
    h := fnv.New64a()
    h.Write([]byte(phName))
    rg := rand.New(rand.NewSource(int64(h.Sum64())))
    
    rSleep := func(t time.Duration) {
        time.Sleep(t/2 + time.Duration(rg.Int63n(int64(t))))
    }
    for h := hunger; h > 0; h-- {
        fmt.Println(phName, "hungry")
        <-dominantHand 
        <-otherHand
        fmt.Println(phName, "eating")
        rSleep(eat)
        dominantHand <- 'f' 
        otherHand <- 'f'
        fmt.Println(phName, "thinking")
        rSleep(think)
    }
    fmt.Println(phName, "satisfied")
    done <- true
    fmt.Println(phName, "left the table")
}

func main() {
    fmt.Println("table empty")
    
    
    place0 := make(chan fork, 1)
    place0 <- 'f' 
    placeLeft := place0
    for i := 1; i < len(ph); i++ {
        placeRight := make(chan fork, 1)
        placeRight <- 'f'
        go philosopher(ph[i], placeLeft, placeRight, done)
        placeLeft = placeRight
    }
    
    
    
    go philosopher(ph[0], place0, placeLeft, done)
    
    for range ph {
        <-done 
    }
    fmt.Println("table empty")
}
Task: Keyboard input_Flush the keyboard buffer




Go: package main

import (
    "log"

    gc "code.google.com/p/goncurses"
)

func main() {
    _, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    gc.FlushInput()
}
Task: Pinstripe_Printer




Go: package main
 
import (
    "github.com/fogleman/gg"
    "log"
    "os/exec"
    "runtime"
)

var palette = [2]string{
    "FFFFFF", 
    "000000", 
}
 
func pinstripe(dc *gg.Context) {
    w := dc.Width()
    h := dc.Height() / 7
    for b := 1; b <= 11; b++ {
        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
            dc.SetHexColor(palette[ci%2])
            y := h * (b - 1)
            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
            dc.Fill()
        }
    }
}
 
func main() {
    dc := gg.NewContext(842, 595)
    pinstripe(dc)
    fileName := "w_pinstripe.png"
    dc.SavePNG(fileName)
    var cmd *exec.Cmd
    if runtime.GOOS == "windows" {
        cmd = exec.Command("mspaint", "/pt", fileName)
    } else {
        cmd = exec.Command("lp", fileName)
    }
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}
Task: Pseudo-random numbers_Middle-square method







Python: seed = 675248
def random():
    global seed
    seed = int(str(seed ** 2).zfill(12)[3:9])
    return seed
for _ in range(5):
    print(random())



COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. MIDDLE-SQUARE.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 STATE.
          03 SEED         PIC 9(6) VALUE 675248.
          03 SQUARE       PIC 9(12).
          03 FILLER       REDEFINES SQUARE.
             05 FILLER    PIC 9(3).
             05 NEXT-SEED PIC 9(6).
             05 FILLER    PIC 9(3).
       
       PROCEDURE DIVISION.
       BEGIN.
           PERFORM SHOW-NUM 5 TIMES.
           STOP RUN.
       
       SHOW-NUM.
           PERFORM MAKE-RANDOM.
           DISPLAY SEED.
       
       MAKE-RANDOM.
           MULTIPLY SEED BY SEED GIVING SQUARE.
           MOVE NEXT-SEED TO SEED.
Task: Use another language to call a function







Python: 

def query(buffer_length):
    message = b'Here am I'
    L = len(message)
    return message[0:L*(L <= buffer_length)]



COBOL:        identification division.
       program-id. Query.

       environment division.
       configuration section.
       special-names.
           call-convention 0 is extern.

       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 query-result.
          05 filler value "Here I am".

       linkage section.
       01 data-reference.
          05 data-buffer   pic x occurs 0 to 8192 times
                                 depending on length-reference.
       01 length-reference usage binary-long.

       procedure division extern using data-reference length-reference.

       if length(query-result) less than or equal to length-reference
                           and length-reference less than 8193 then
           move query-result to data-reference
           move length(query-result) to length-reference
           move 1 to return-code
       end-if

       goback.
       end program Query.