func normalize (vec)  { vec »/» (vec »*« vec -> sum.sqrt) }
func dot       (x, y) { -(x »*« y -> sum) `max` 0 }

var x = var y = 255
x += 1 if x.is_even    # must be odd

var light = normalize([ 3, 2, -5 ])
var depth = 255

func draw_sphere(rad, k, ambient) {
    var pixels = []
    var r2 = (rad * rad)
    var range = (-rad .. rad)
    for x,y in (range ~X range) {
        if ((var x2 = x*x) + (var y2 = y*y) < r2) {
            var vector = normalize([x, y, (r2 - x2 - y2).sqrt])
            var intensity = (dot(light, vector)**k + ambient)
            var pixel = (0 `max` (intensity*depth -> int) `min` depth)
            pixels << pixel
        }
        else {
            pixels << 0
        }
    }
    return pixels
}

var outfile = %f'sphere-sidef.pgm'
var out = outfile.open('>:raw')

out.say("P5\n#{x} #{y}\n#{depth}")    # .pgm header
out.print(draw_sphere((x-1)/2, .9, .2).map{.chr}.join)
out.close


-module( doubly_linked_list ).

-export( [append/2, foreach_next/2, foreach_previous/2, free/1, insert/3, new/1, task/0] ).

append( New, Start ) -> Start ! {append, New}.

foreach_next( Fun, Start ) -> Start ! {foreach_next, Fun}.

foreach_previous( Fun, Start ) -> Start ! {foreach_previous, Fun}.

free( Element ) -> Element ! {free}.

insert( New, After, Start ) -> Start ! {insert, New, After}.

new( Data ) -> erlang:spawn( fun() -> loop( Data, noprevious, nonext ) end ).

task() ->
    A = new( a ),
    B = new( b ),
    append( B, A ),
    C = new( c ),
    insert( C, A, A ),
    foreach_next( fun(Data) -> io:fwrite("foreach_next ~p~n", [Data]) end, A ),
    timer:sleep( 100 ),
    foreach_previous( fun(Data) -> io:fwrite("foreach_previous ~p~n", [Data]) end, B ).

loop( Data, Previous, Next ) ->
      My_pid = erlang:self(),
      receive
      {append, New} ->
             New_next = loop_append( New, Next, My_pid ),
             loop( Data, Previous, New_next );
      {foreach_next, Fun} ->
                catch Fun( Data ),
                loop_foreach_next( Fun, Next ),
                loop( Data, Previous, Next );
      {foreach_previous, Fun} ->
                catch Fun( Data ),
                loop_foreach_previous( Fun, Previous ),
                loop( Data, Previous, Next );
      {free} ->
             ok;
      {insert, New, My_pid} ->
	     New ! {previous, My_pid},
             loop_append( Next, New, My_pid ),
             loop( Data, Previous, New );
      {insert, New, After} ->
             Next ! {insert, New, After},
             loop( Data, Previous, Next );
      {previous, New_previous} ->
             loop( Data, New_previous, Next )
        end.

loop_append( New, nonext, My_pid ) ->
        New ! {previous, My_pid},
        New;
loop_append( New, Next, _My_pid ) ->
        Next ! {append, New},
        Next.

loop_foreach_next( _Fun, nonext ) -> ok;
loop_foreach_next( Fun, Next ) -> Next ! {foreach_next, Fun}.

loop_foreach_previous( _Fun, noprevious ) -> ok;
loop_foreach_previous( Fun, Next ) -> Next ! {foreach_previous, Fun}.


Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log"
Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide
FileRead, Contents, %LogFile%
FileDelete, %LogFile%
RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match)
MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])")


:: DNS Query Task from Rosetta Code Wiki
:: Batch File Implementation

@echo off

set "domain=www.kame.net"
echo DOMAIN: "%domain%"
echo(
call :DNS_Lookup "%domain%"
pause
exit /b

::Main Procedure
::Uses NSLOOKUP Command. Also uses a dirty "parsing" to detect IP addresses.
:DNS_Lookup [domain]

::Define Variables and the TAB Character
set "dom=%~1"
set "record="
set "reccnt=0"
for /f "delims=" %%T in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do set "TAB=%%T"

setlocal enabledelayedexpansion
for /f "tokens=1* delims=:" %%x in ('nslookup "!dom!" 2^>nul') do (
    set "line=%%x"
    if /i "!line:~0,4!"=="Name" set "record=yes"
    if /i "!line:~0,5!"=="Alias" set "record="
    if "!record!"=="yes" (
        set /a reccnt+=1
        if "%%y"=="" (set "catch_!reccnt!=%%x") else (set "catch_!reccnt!=%%x:%%y")
    )
)
for /l %%c in (1,1,%reccnt%) do (
    if /i "!catch_%%c:~0,7!"=="Address" echo(!catch_%%c:*s:  =!
    if /i "!catch_%%c:~0,1!"=="%TAB%" echo(!catch_%%c:%TAB%  =!
)
endlocal
goto :EOF


var sec_old = 0;
function update_clock() {
	var t = new Date();
	var arms = [t.getHours(), t.getMinutes(), t.getSeconds()];
	if (arms[2] == sec_old) return;
	sec_old = arms[2];

	var c = document.getElementById('clock');
	var ctx = c.getContext('2d');
	ctx.fillStyle = "rgb(0,200,200)";
	ctx.fillRect(0, 0, c.width, c.height);
	ctx.fillStyle = "white";
	ctx.fillRect(3, 3, c.width - 6, c.height - 6);
	ctx.lineCap = 'round';

	var orig = { x: c.width / 2, y: c.height / 2 };
	arms[1] += arms[2] / 60;
	arms[0] += arms[1] / 60;
	draw_arm(ctx, orig, arms[0] * 30, c.width/2.5 - 15, c.width / 20,  "green");
	draw_arm(ctx, orig, arms[1] * 6,  c.width/2.2 - 10, c.width / 30,  "navy");
	draw_arm(ctx, orig, arms[2] * 6,  c.width/2.0 - 6,  c.width / 100, "maroon");
}

function draw_arm(ctx, orig, deg, len, w, style)
{
	ctx.save();
	ctx.lineWidth = w;
	ctx.lineCap = 'round';
	ctx.translate(orig.x, orig.y);
	ctx.rotate((deg - 90) * Math.PI / 180);
	ctx.strokeStyle = style;
	ctx.beginPath();
	ctx.moveTo(-len / 10, 0);
	ctx.lineTo(len, 0);
	ctx.stroke();
	ctx.restore();
}

function init_clock() {
	var clock = document.createElement('canvas');
	clock.width = 100;
	clock.height = 100;
	clock.id = "clock";
	document.body.appendChild(clock);

	window.setInterval(update_clock, 200);
}


10 REM DRAGON CURVE
20 REM SIN, COS IN ARRAYS FOR PI/4 MULTIPL.
30 DIM S(7),C(7)
40 QPI=ATN(1)
50 FOR I=0 TO 7
60 S(I)=SIN(I*QPI)
70 C(I)=COS(I*QPI)
80 NEXT I
90 LEVEL=15
100 INSIZE=128:REM 2^WHOLE_NUM (LOOKS BETTER)
110 X=112
120 Y=70
130 SQ=SQR(2)
140 ROTQPI=0:ITER=0:RQ=1
150 DIM R(LEVEL)
160 GRAPHIC 2,1
170 GOSUB 190
180 END
190 REM DRAGON
200 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 220
210 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8
220 IF LEVEL>1 THEN GO TO 290
230 YN=S(ROTQPI)*INSIZE+Y
240 XN=C(ROTQPI)*INSIZE+X
250 DRAW ,X,Y TO XN,YN
260 ITER=ITER+1
270 X=XN:Y=YN
280 RETURN
290 INSIZE=INSIZE*SQ/2
300 ROTQPI=ROTQPI+RQ
310 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 330
320 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8
330 LEVEL=LEVEL-1
340 R(LEVEL)=RQ:RQ=1
350 GOSUB 190
360 ROTQPI=ROTQPI-R(LEVEL)*2
370 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 390
380 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8
390 RQ=-1
400 GOSUB 190
410 RQ=R(LEVEL)
420 ROTQPI=ROTQPI+RQ
430 IF ROTQPI<0 THEN ROTQPI=ROTQPI+8:GOTO 450
440 IF ROTQPI>7 THEN ROTQPI=ROTQPI-8
450 LEVEL=LEVEL+1
460 INSIZE=INSIZE*SQ
470 RETURN


(defpackage #:dragon
  (:use #:clim-lisp #:clim)
  (:export #:dragon #:dragon-part))
(in-package #:dragon)

(defun dragon-part (depth bend-direction)
  (if (zerop depth)
      (draw-line* *standard-output* 0 0 1 0)
      (with-scaling (t (/ (sqrt 2)))
        (with-rotation (t (* pi -1/4 bend-direction))
          (dragon-part (1- depth) 1)
          (with-translation (t 1 0)
            (with-rotation (t (* pi 1/2 bend-direction))
              (dragon-part (1- depth) -1)))))))

(defun dragon (&optional (depth 7) (size 100))
  (with-room-for-graphics ()
    (with-scaling (t size)
      (dragon-part depth 1))))


//! Documentation for the module
//!
//! **Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Aenean a
//! sagittis sapien, eu pellentesque ex. Nulla facilisi. Praesent eget sapien
//! sollicitudin, laoreet ipsum at, fringilla augue. In hac habitasse platea
//! dictumst. Nunc in neque sed magna suscipit mattis sed quis mi. Curabitur
//! quis mi a ante mollis commodo. Sed tincidunt ut metus vel accumsan.
#![doc(html_favicon_url = "https://example.com/favicon.ico")]
#![doc(html_logo_url = "https://example.com/logo.png")]

/// Documentation for a constant
pub const THINGY: u32 = 42;

/// Documentation for a Rust `enum` (tagged union)
pub enum Whatsit {
    /// Documentation for the `Yo` variant
    Yo(Whatchamabob),
    /// Documentation for the `HoHo` variant
    HoHo,
}

/// Documentation for a data structure
pub struct Whatchamabob {
    /// Doodads do dad
    pub doodad: f64,
    /// Whether or not this is a thingamabob
    pub thingamabob: bool
}

/// Documentation for a trait (interface)
pub trait Frobnify {
    /// `Frobnify` something
    fn frob(&self);
}

/// Documentation specific to this struct's implementation of `Frobnify`
impl Frobnify for Whatchamabob {
    /// `Frobnify` the `Whatchamabob`
    fn frob(&self) {
        println!("Frobbed: {}", self.doodad);
    }
}

/// Documentation for a function
///
/// Pellentesque sodales lacus nisi, in malesuada lectus vestibulum eget.
/// Integer rhoncus imperdiet justo. Pellentesque egestas sem ac
/// consectetur suscipit. Maecenas tempus dignissim purus, eu tincidunt mi
/// tincidunt id. Morbi ac laoreet erat, eu ultricies neque. Fusce molestie
/// urna quis nisl condimentum, sit amet fringilla nunc ornare. Pellentesque
/// vestibulum ac nibh eu accumsan. In ornare orci at rhoncus finibus. Donec
/// sed ipsum ex. Pellentesque ante nisl, pharetra id purus auctor, euismod
/// semper erat. Nunc sit amet eros elit.
pub fn main() {
    let foo = Whatchamabob{ doodad: 1.2, thingamabob: false };
    foo.frob();
}


/**
  * This is a class documentation comment. This text shows at the top of the page for this class
  *
  * @author Joe Schmoe
  */
class Doc {
  /**
    * This is a field comment for a variable
    */
  private val field = 0

  /**
    * This is a method comment. It has parameter tags (param) and a return value tag (return).
    *
    * @param num a number with the variable name "num"
    * @return another number
    */
  def method(num: Long): Int = {
    //...code here
    ???
  }
}


FooClass comment: 'This is a comment ....'.


CREATE TABLESPACE myTs;

COMMENT ON TABLESPACE myTs IS 'Description of the tablespace.';

CREATE SCHEMA mySch;

COMMENT ON SCHEMA mySch IS 'Description of the schema.';

CREATE TYPE myType AS (col1 INT) MODE DB2SQL;

COMMENT ON TYPE mytype IS 'Description of the type.';

CREATE TABLE myTab (
  myCol1 INT NOT NULL,
  myCol2 INT
);

COMMENT ON TABLE myTab IS 'Description of the table.';
COMMENT ON myTab (
  myCol1 IS 'Description of the column.',
  myCol2 IS 'Description of the column.'
);

ALTER TABLE myTab ADD CONSTRAINT myConst PRIMARY KEY (myCol1);

COMMENT ON CONSTRAINT myTab.myConst IS 'Description of the constraint.';

CREATE INDEX myInd ON
  myTab (myCol2);

COMMENT ON INDEX myInd IS 'Description of the index.';

-- V11.1
CREATE USAGE LIST myUsList FOR TABLE myTab;

COMMENT ON USAGE LISTmyUsList IS 'Description of the usage list.';

/**
 * Detailed description of the trigger.
 */
CREATE TRIGGER myTrig
  AFTER INSERT ON myTab
  REFERENCING NEW AS N
  FOR EACH ROW
 BEGIN
 END;

COMMENT ON TRIGGER myTrig IS 'General description of the trigger.';

CREATE VARIABLE myVar INT;

COMMENT ON VARIABLE myVar IS 'General description of the variable.';

/**
 * General description of the function (reads until the first dot).
 * Detailed description of the function, until the first empty line.
 *
 * IN VAR1
 *   Description of IN parameter in variable VAR1.
 * OUT VAR2
 *   Description of OUT parameter in variable VAR2.
 * INOUT VAR3
 *   Description of INOUT parameter in variable VAR3.
 * RETURNS Description of what it returns.
 */
CREATE FUNCTION myfun (
  IN VAR1 INT,
  OUT VAR2 INT,
  INOUT VAR3 INT)
  RETURNS INT
 BEGIN
 END;

/**
 * General description of the procedure (reads until the first dot).
 * Detailed description of the procedure, until the first empty line.
 *
 * IN VAR1
 *   Description of IN parameter in variable VAR1.
 * OUT VAR2
 *   Description of OUT parameter in variable VAR2.
 * INOUT VAR3
 *   Description of INOUT parameter in variable VAR3.
 */
CREATE PROCEDURE myProc (
  IN VAR1 INT,
  OUT VAR2 INT,
  INOUT VAR3 INT)
 BEGIN
 END;

CREATE MODULE myMod;

COMMENT ON MODULE myMod IS 'General description of the module.';

/**
 * General description of the procedure (reads until the first dot).
 * Detailed description of the procedure, until the first empty line.
 *
 * IN VAR1
 *   Description of IN parameter in variable VAR1.
 * OUT VAR2
 *   Description of OUT parameter in variable VAR2.
 * INOUT VAR3
 *   Description of INOUT parameter in variable VAR3.
 */
ALTER MODULE myMod
  ADD PROCEDURE myProc (
  IN VAR1 INT,
  OUT VAR2 INT,
  INOUT VAR3 INT)
 BEGIN
 END;

CREATE ROLE myRole;

COMMENT ON ROLE myRole IS 'Description of the role.';

CREATE SEQUENCE mySeq;

COMMENT ON ROLE mySeq IS 'Description of the sequence.';


using System;
using System.Linq;
using System.Collections.Generic;

public class MainClass {
    static double Square(double x) => x * x;

    static double AverageSquareDiff(double a, IEnumerable<double> predictions)
        => predictions.Select(x => Square(x - a)).Average();

    static void DiversityTheorem(double truth, IEnumerable<double> predictions)
    {
        var average = predictions.Average();
        Console.WriteLine($@"average-error: {AverageSquareDiff(truth, predictions)}
crowd-error: {Square(truth - average)}
diversity: {AverageSquareDiff(average, predictions)}");
    }

    public static void Main() {
	DiversityTheorem(49, new []{48d,47,51});
    	DiversityTheorem(49, new []{48d,47,51,42});
    }
}


#include <iostream>
#include <vector>
#include <numeric>

float sum(const std::vector<float> &array)
{
    return std::accumulate(array.begin(), array.end(), 0.0);
}

float square(float x)
{
    return x * x;
}

float mean(const std::vector<float> &array)
{
    return sum(array) / array.size();
}

float averageSquareDiff(float a, const std::vector<float> &predictions)
{
    std::vector<float> results;
    for (float x : predictions)
        results.push_back(square(x - a));
    return mean(results);
}

void diversityTheorem(float truth, const std::vector<float> &predictions)
{
    float average = mean(predictions);
    std::cout
        << "average-error: " << averageSquareDiff(truth, predictions) << "\n"
        << "crowd-error: " << square(truth - average) << "\n"
        << "diversity: " << averageSquareDiff(average, predictions) << std::endl;
}

int main() {
    diversityTheorem(49, {48,47,51});
    diversityTheorem(49, {48,47,51,42});
    return 0;
}


Point3D :=
   Point subclass:#Point3D
        instanceVariableNames:'z'
        classVariableNames:''
        poolDictionaries:''
        category:''
        inEnvironment:nil.

Point3D compile:'z ^ z'.
Point3D compile:'z:v z := v'.

normalize := [:v | |invLen|
    invLen := 1 / (dot value:v value:v) sqrt.
    v x: v x * invLen.
    v y: v y * invLen.
    v z: v z * invLen.
].

dot := [:a :b |
    (a x * b x) + (a y * b y) + (a z * b z)
].

drawSphere := [:r :k :amb :dir |
    |w h imh vec img|

    w := r*4. h := r*3.
    img := Image width:w height:h depth:8.
    img photometric:#blackIs0; createPixelStore.
    vec := Point3D new.
    0-r to:r do:[:x |
        0-r to:r do:[:y |
            |z s lum|
            (z := (r*r) - (x*x) - (y*y)) >= 0 ifTrue:[
                vec x: x.
                vec y: y.
                vec z: z sqrt.
                normalize value:vec.
                s := dot value:dir value:vec.
                s < 0 ifTrue:[ s := 0 ].
                lum := 255 * ((s raisedTo: k) + amb) / (1 + amb).
                lum < 0 ifTrue:[
                    lum := 0
                ] ifFalse:[ lum > 255 ifTrue:[
                    lum := 255
                ]].
                img atX:(x+(w//2)) y:(y+(h//2)) put:(Color greyByte:lum).
            ]
        ]
    ].
    img
].

main := [
    |dir img|

    dir := Point3D new x:-30; y:-30; z:50; yourself.
    normalize value:dir.
    img := drawSphere value: 100 value: 1.5 value: 0.2 value: dir.
    img displayOn:(View new extent:400@400; openAndWait).
    img saveOn:'sphere.png'.
].

main value.


type DListAux<'T> = {mutable prev: DListAux<'T> option; data: 'T; mutable next: DListAux<'T> option}
type DList<'T> = {mutable front: DListAux<'T> option; mutable back: DListAux<'T> option} //'

let empty() = {front=None; back=None}

let addFront dlist elt =
  match dlist.front with
  | None ->
      let e = Some {prev=None; data=elt; next=None}
      dlist.front <- e
      dlist.back <- e
  | Some e2 ->
      let e1 = Some {prev=None; data=elt; next=Some e2}
      e2.prev <- e1
      dlist.front <- e1

let addBack dlist elt =
  match dlist.back with
  | None -> addFront dlist elt
  | Some e2 ->
      let e1 = Some {prev=Some e2; data=elt; next=None}
      e2.next <- e1
      dlist.back <- e1

let addAfter dlist link elt =
  if link.next = dlist.back then addBack dlist elt else
    let e = Some {prev=Some link; data=elt; next=link.next}
    link.next <- e


module dlist
  implicit none
  type node
     type(node), pointer :: next => null()
     type(node), pointer :: prev => null()
     integer :: data
  end type node

  type dll
     type(node), pointer :: head => null()
     type(node), pointer :: tail => null()
     integer :: num_nodes = 0
  end type dll

  public  :: node, dll, append, prepend, insert, dump, reverse_dump, tidy
  private :: init

contains
  ! Create a new doubly-linked list
  elemental type(dll) function new_dll()
    new_dll = dll(null(),null(),0)
    return
  end function new_dll

  ! Append an element to the end of the list
  elemental subroutine append(dl2, value)
    type(dll), intent(inout) :: dl2
    integer, intent(in)      :: value

    type(node), pointer :: np

    ! If the list is empty
    if (dl2%num_nodes == 0) then
       call init(dl2, value)
       return
    end if

    ! Add new element to the end
    dl2%num_nodes = dl2%num_nodes + 1
    np => dl2%tail
    allocate(dl2%tail)
    dl2%tail%data = value
    dl2%tail%prev => np
    dl2%tail%prev%next => dl2%tail
  end subroutine append

  ! Prepend an element to the beginning of the list
  elemental subroutine prepend(dl2, value)
    type(dll), intent(inout) :: dl2
    integer, intent(in)      :: value

    type(node), pointer :: np

    if (dl2%num_nodes == 0) then
       call init(dl2, value)
       return
    end if

    dl2%num_nodes = dl2%num_nodes + 1
    np => dl2%head
    allocate(dl2%head)
    dl2%head%data = value
    dl2%head%next => np
    dl2%head%next%prev => dl2%head
  end subroutine prepend

  ! Insert immediately before the given index
  elemental subroutine insert(dl2, index, value)
    type(dll), intent(inout) :: dl2
    integer, intent(in)      :: index
    integer, intent(in)      :: value

    type(node), pointer :: element
    type(node), pointer :: np1, np2
    integer             :: i

    if (dl2%num_nodes == 0) then
       call init(dl2, value)
       return
    end if

    ! If index is beyond the end then append
    if (index > dl2%num_nodes) then
       call append(dl2, value)
       return
    end if

    ! If index is less than 1 then prepend
    if (index <= 1) then
       call prepend(dl2, value)
       return
    end if

    ! Find the node at position 'index' counting from 1
    np1 => dl2%head
    do i=1, index-2
       np1 => np1%next
    end do
    np2 => np1%next

    ! Create the new node
    allocate(element)
    element%data = value

    ! Connect it up
    element%prev => np1
    element%next => np2
    np1%next => element
    np2%prev => element
    dl2%num_nodes = dl2%num_nodes + 1
  end subroutine insert

  subroutine dump(dl2)
    type(dll), intent(in) :: dl2
    type(node), pointer :: current
    integer :: i

    write(*,fmt='(a,i0,a)',advance='no') 'Doubly-linked list has ',dl2%num_nodes,' element - fwd = '
    current => dl2%head
    i = 1
    write(*,fmt='(i0,a)',advance='no') current%data,', '
    do
       current => current%next
       if (.not. associated(current)) then
          exit
       end if
       i = i + 1
       if (i == dl2%num_nodes) then
          write(*,'(i0)') current%data
       else
          write(*,fmt='(i0,a)',advance='no') current%data,', '
       end if
    end do
  end subroutine dump

  subroutine reverse_dump(dl2)
    type(dll), intent(in) :: dl2
    type(node), pointer :: current
    integer :: i

    write(*,fmt='(a,i0,a)',advance='no') 'Doubly-linked list has ',dl2%num_nodes,' element - bwd = '
    current => dl2%tail
    write(*,fmt='(i0,a)',advance='no') current%data,', '
    i = 1
    do
       current => current%prev
       if (.not. associated(current)) then
          exit
       end if
       i = i + 1
       if (i == dl2%num_nodes) then
          write(*,'(i0)') current%data
       else
          write(*,fmt='(i0,a)',advance='no') current%data,', '
       end if
    end do
  end subroutine reverse_dump

  ! Deallocate all allocated memory
  elemental subroutine tidy(dl2)
    type(dll), intent(inout) :: dl2
    type(node), pointer :: current, last

    current => dl2%head
    do
       last => current
       current => current%next
       if (associated(last)) then
          deallocate(last)
       end if
       if (associated(current, dl2%tail)) then
          deallocate(current)
          exit
       end if
    end do
  end subroutine tidy

  elemental subroutine init(dl2, value)
    type(dll), intent(inout) :: dl2
    integer, intent(in)      :: value
    allocate(dl2%head)
    dl2%tail => dl2%head
    dl2%tail%data = value
    dl2%num_nodes = 1
    return
  end subroutine init

end module dlist

program dl
  use dlist
  implicit none

  type(dll) :: mydll

  mydll = new_dll()
  call append(mydll, 5)
  call append(mydll, 7)
  call prepend(mydll, 3)
  call prepend(mydll, 1)
  call insert(mydll, 3, 4)
  call dump(mydll)

  call reverse_dump(mydll)

  call tidy(mydll)
end program dl


      name$ = "www.kame.net"

      AF_INET = 2
      AF_INET6 = 23
      WSASYS_STATUS_LEN = 128
      WSADESCRIPTION_LEN = 256

      SYS "LoadLibrary", "WS2_32.DLL" TO ws2%
      SYS "GetProcAddress", ws2%, "WSAStartup"  TO `WSAStartup`
      SYS "GetProcAddress", ws2%, "WSACleanup"  TO `WSACleanup`
      SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo`

      DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \
      \ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \
      \ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%}

      DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \
      \      ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%}
      DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{}

      DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)}
      DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \
      \                sin6_addr&(15), sin6_scope_id%}

      SYS `WSAStartup`, &202, WSAdata{} TO res%
      IF res% ERROR 102, "WSAStartup failed"

      addrinfo.ai_family% = AF_INET
      SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res%
      IF res% ERROR 103, "getaddrinfo failed"

      !(^sockaddr_in{}+4) = ipv4info.lp_ai_addr%
      PRINT "IPv4 address = " ;
      PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ;
      PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3)

      addrinfo.ai_family% = AF_INET6
      SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res%
      IF res% ERROR 104, "getaddrinfo failed"

      !(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr%
      PRINT "IPv6 address = " ;
      PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ;
      PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ;
      PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ;
      PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ;
      PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ;
      PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ;
      PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ;
      PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15)

      SYS `WSACleanup`


#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>		/* getaddrinfo, getnameinfo */
#include <stdio.h>		/* fprintf, printf */
#include <stdlib.h>		/* exit */
#include <string.h>		/* memset */

int
main()
{
	struct addrinfo hints, *res, *res0;
	int error;
	char host[NI_MAXHOST];

	/*
	 * Request only one socket type from getaddrinfo(). Else we
	 * would get both SOCK_DGRAM and SOCK_STREAM, and print two
	 * copies of each numeric address.
	 */
	memset(&hints, 0, sizeof hints);
	hints.ai_family = PF_UNSPEC;     /* IPv4, IPv6, or anything */
	hints.ai_socktype = SOCK_DGRAM;  /* Dummy socket type */

	/*
	 * Use getaddrinfo() to resolve "www.kame.net" and allocate
	 * a linked list of addresses.
	 */
	error = getaddrinfo("www.kame.net", NULL, &hints, &res0);
	if (error) {
		fprintf(stderr, "%s\n", gai_strerror(error));
		exit(1);
	}

	/* Iterate the linked list. */
	for (res = res0; res; res = res->ai_next) {
		/*
		 * Use getnameinfo() to convert res->ai_addr to a
		 * printable string.
		 *
		 * NI_NUMERICHOST means to present the numeric address
		 * without doing reverse DNS to get a domain name.
		 */
		error = getnameinfo(res->ai_addr, res->ai_addrlen,
		    host, sizeof host, NULL, 0, NI_NUMERICHOST);

		if (error) {
			fprintf(stderr, "%s\n", gai_strerror(error));
		} else {
			/* Print the numeric address. */
			printf("%s\n", host);
		}
	}

	/* Free the linked list. */
	freeaddrinfo(res0);

	return 0;
}


        private string LookupDns(string s)
        {
            try
            {
                System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);

                string result = ip.AddressList[0].ToString();

                for (int i = 1; i < ip.AddressList.Length; ++i)
                    result += ", " + ip.AddressList[i].ToString();

                return result;
            }
            catch (System.Net.Sockets.SocketException se)
            {
                return se.Message;
            }
        }


package Server is
   pragma Remote_Call_Interface;
   procedure Foo;
   function Bar return Natural;
end Server;


using Gtk, Colors, Graphics, Dates

const radius = 300
const win = GtkWindow("Clock", radius, radius)
const can = GtkCanvas()
push!(win, can)

global drawcontext = []

function drawline(ctx, l, color)
    isempty(l) && return
    p = first(l)
    move_to(ctx, p.x, p.y)
    set_source(ctx, color)
    for i = 2:length(l)
        p = l[i]
        line_to(ctx, p.x, p.y)
    end
    stroke(ctx)
end

function clockbody(ctx)
    set_coordinates(ctx, BoundingBox(0, 100, 0, 100))
    rectangle(ctx, 0, 0, 100, 100)
    set_source(ctx, colorant"yellow")
    fill(ctx)
    set_source(ctx, colorant"blue")
    arc(ctx, 50, 50, 45, 45, 360)
    stroke(ctx)
    for hr in 1:12
        radians = hr * pi / 6.0
        drawline(ctx, [Point(50 + 0.95 * 45 * sin(radians),
            50 - 0.95 * 45 * cos(radians)),
            Point(50 + 1.0 * 45 * sin(radians),
            50 - 1.0 * 45 * cos(radians))], colorant"blue")
    end
end

Gtk.draw(can) do widget
    ctx = getgc(can)
    if length(drawcontext) < 1
        push!(drawcontext, ctx)
    else
        drawcontext[1] = ctx
    end
    clockbody(ctx)
end

function update(can)
    dtim = now()
    hr = hour(dtim)
    mi = minute(dtim)
    sec = second(dtim)
    if length(drawcontext) < 1
        return
    end
    ctx = drawcontext[1]
    clockbody(ctx)
    rad = (hr % 12) * pi / 6.0 + mi * pi / 360.0
    drawline(ctx, [Point(50, 50),
        Point(50 + 45 * 0.5 * sin(rad), 50 - 45 * 0.5 * cos(rad))], colorant"black")
    stroke(ctx)
    rad = mi * pi / 30.0  + sec * pi / 1800.0
    drawline(ctx, [Point(50, 50),
        Point(50 + 0.7 * 45 * sin(rad), 50 - 0.7 * 45 * cos(rad))], colorant"darkgreen")
    stroke(ctx)
    rad = sec * pi / 30.0
    drawline(ctx, [Point(50, 50),
        Point(50 + 0.9 * 45 * sin(rad), 50 - 0.9 * 45 * cos(rad))], colorant"red")
    stroke(ctx)
    reveal(can)
end

Gtk.showall(win)
sloc = Base.Threads.SpinLock()
lock(sloc)
signal_connect(win, :destroy) do widget
    unlock(sloc)
end
while !trylock(sloc)
    update(win)
    sleep(1.0)
end


// version 1.1

import java.awt.*
import java.time.LocalTime
import javax.swing.*

class Clock : JPanel() {
    private val degrees06: Float = (Math.PI / 30.0).toFloat()
    private val degrees30: Float = degrees06 * 5.0f
    private val degrees90: Float =  degrees30 * 3.0f
    private val size = 590
    private val spacing = 40
    private val diameter = size - 2 * spacing
    private val cx = diameter / 2 + spacing
    private val cy = cx

    init {
        preferredSize = Dimension(size, size)
        background =  Color.white
        Timer(1000) {
            repaint()
        }.start()
    }

    override public fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        drawFace(g)
        val time  = LocalTime.now()
        val hour = time.hour
        val minute = time.minute
        val second = time.second
        var angle: Float = degrees90 - degrees06 * second
        drawHand(g, angle, diameter / 2 - 30, Color.red)
        val minsecs: Float = minute + second / 60.0f
        angle = degrees90 - degrees06 * minsecs
        drawHand(g, angle, diameter / 3 + 10, Color.black)
        val hourmins: Float = hour + minsecs / 60.0f
        angle = degrees90 - degrees30 * hourmins
        drawHand(g, angle, diameter / 4 + 10, Color.black)
    }

    private fun drawFace(g: Graphics2D) {
        g.stroke = BasicStroke(2.0f)
        g.color = Color.yellow
        g.fillOval(spacing, spacing, diameter, diameter)
        g.color = Color.black
        g.drawOval(spacing, spacing, diameter, diameter)
    }

    private fun drawHand(g: Graphics2D, angle: Float, radius: Int, color: Color) {
        val x: Int  = cx + (radius.toDouble() * Math.cos(angle.toDouble())).toInt()
        val y: Int =  cy - (radius.toDouble() * Math.sin(angle.toDouble())).toInt()
        g.color = color
        g.drawLine(cx, cy, x, y)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        f.title = "Clock"
        f.isResizable = false
        f.add(Clock(), BorderLayout.CENTER)
        f.pack()
        f.setLocationRelativeTo(null)
        f.isVisible = true
    }
}


import std.stdio, std.string;

struct Board {
    enum char spc = ' ';
    char[][] b = [[' ']]; // Set at least 1x1 board.
    int shiftx, shifty;

    void clear() pure nothrow {
        shiftx = shifty = 0;
        b = [['\0']];
    }

    void check(in int x, in int y) pure nothrow {
        while (y + shifty < 0) {
            auto newr = new char[b[0].length];
            newr[] = spc;
            b = newr ~ b;
            shifty++;
        }

        while (y + shifty >= b.length) {
            auto newr = new char[b[0].length];
            newr[] = spc;
            b ~= newr;
        }

        while (x + shiftx < 0) {
            foreach (ref c; b)
                c = [spc] ~ c;
            shiftx++;
        }

        while (x + shiftx >= b[0].length)
            foreach (ref c; b)
                c ~= [spc];
    }

    char opIndexAssign(in char value, in int x, in int y)
    pure nothrow {
        check(x, y);
        b[y + shifty][x + shiftx] = value;
        return value;
    }

    string toString() const pure {
        return format("%-(%s\n%)", b);
    }
}

struct Turtle {
    static struct TState {
        int[2] xy;
        int heading;
    }

    enum int[2][] dirs = [[1, 0],  [1,   1], [0,  1], [-1,  1],
                          [-1, 0], [-1, -1], [0, -1],  [1, -1]];
    enum string trace = r"-\|/-\|/";
    TState t;

    void reset() pure nothrow {
        t = typeof(t).init;
    }

    void turn(in int dir) pure nothrow {
        t.heading = (t.heading + 8 + dir) % 8;
    }

    void forward(ref Board b) pure nothrow {
        with (t) {
            xy[] += dirs[heading][];
            b[xy[0], xy[1]] = trace[heading];
            xy[] += dirs[heading][];
            b[xy[0], xy[1]] = b.spc;
        }
    }
}

void dragonX(in int n, ref Turtle t, ref Board b) pure nothrow {
    if (n >= 0) { // X -> X+YF+
        dragonX(n - 1, t, b);
        t.turn(2);
        dragonY(n - 1, t, b);
        t.forward(b);
        t.turn(2);
    }
}

void dragonY(in int n, ref Turtle t, ref Board b) pure nothrow {
    if (n >= 0) { // Y -> -FX-Y
        t.turn(-2);
        t.forward(b);
        dragonX(n - 1, t, b);
        t.turn(-2);
        dragonY(n - 1, t, b);
    }
}

void main() {
    Turtle t;
    Board b;
                      // Seed : FX
    t.forward(b);     // <- F
    dragonX(7, t, b); // <- X
    writeln(b);
}


/**
 Adds two numbers
 :param: a an integer.
 :param: b another integer.
 :returns: the sum of a and b
 */
func add(a: Int, b: Int) -> Int {
    return a + b
}


#****f* RosettaCode/TclDocDemo
# FUNCTION
#    TclDocDemo is a simple illustration of how to do documentation
#    of Tcl code using Robodoc.
# SYNOPSYS
#    TclDocDemo foo bar
# INPUTS
#    foo -- the first part of the message to print
#    bar -- the last part of the message to print
# RESULT
#    No result
# NOTES
#    Prints a message based on a template by filling in with the
#    supplied strings.
#*****
proc TclDocDemo {foo bar} {
    puts [format "%s -- %s" $foo $bar]
}


// The meaning of life!
var mol = 42

// A function to add two numbers
var add = Fn.new { |x, y| x + y }

/* A class with some string utilites */
class StrUtil {
    // reverses an ASCII string
    static reverse(s) { s[-1..0] }

    // capitalizes the first letter of an ASCII string
    static capitalize(s) {
        var firstByte = s[0].bytes[0]
        if (firstByte >= 97 && firstByte <= 122) {
            firstByte = firstByte - 32
            return String.fromByte(firstByte) + s[1..-1]
        }
        return s
    }
}

// test code
var smol = "meaning of life"
System.print("'%(smol)' + 123       = %(add.call(mol, 123))")
System.print("'%(smol)' reversed    = %(StrUtil.reverse(smol))")
System.print("'%(smol)' capitalized = %(StrUtil.capitalize(smol))")


 10 LET a=10: REM a is the number of apples
1000 DEF FN s(q)=q*q: REM s is a function that takes a single numeric parameter and returns its square


(defn diversity-theorem [truth predictions]
  (let [square (fn[x] (* x x))
        mean (/ (reduce + predictions) (count predictions))
        avg-sq-diff (fn[a] (/ (reduce + (for [x predictions] (square (- x a)))) (count predictions)))]
    {:average-error (avg-sq-diff truth)
     :crowd-error (square (- truth mean))
     :diversity (avg-sq-diff mean)}))

(println (diversity-theorem 49 '(48 47 51)))
(println (diversity-theorem 49 '(48 47 51 42)))


import std.algorithm;
import std.stdio;

auto square = (real x) => x * x;

auto meanSquareDiff(R)(real a, R predictions) {
    return predictions.map!(x => square(x - a)).mean;
}

void diversityTheorem(R)(real truth, R predictions) {
    auto average = predictions.mean;
    writeln("average-error: ", meanSquareDiff(truth, predictions));
    writeln("crowd-error: ", square(truth - average));
    writeln("diversity: ", meanSquareDiff(average, predictions));
    writeln;
}

void main() {
    diversityTheorem(49.0, [48.0, 47.0, 51.0]);
    diversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0]);
}


class Sphere: UIView{

  override func drawRect(rect: CGRect)
  {
    let context = UIGraphicsGetCurrentContext()
    let locations: [CGFloat] = [0.0, 1.0]

    let colors = [UIColor.whiteColor().CGColor,
      UIColor.blueColor().CGColor]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    let gradient = CGGradientCreateWithColors(colorspace,
      colors, locations)

    var startPoint = CGPoint()
    var endPoint = CGPoint()
    startPoint.x = self.center.x - (self.frame.width * 0.1)
    startPoint.y = self.center.y - (self.frame.width * 0.15)
    endPoint.x = self.center.x
    endPoint.y = self.center.y
    let startRadius: CGFloat = 0
    let endRadius: CGFloat = self.frame.width * 0.38

    CGContextDrawRadialGradient (context, gradient, startPoint,
      startRadius, endPoint, endRadius,
      0)
  }
}

var s = Sphere(frame: CGRectMake(0, 0, 200, 200))


type dlNode struct {
    int
    next, prev *dlNode
}

// Field 'members' allows loops to be prevented.  All nodes
// inserted should be added to members.  Code that operates
// on the list can check any pointer against members to
// find out if the pointer is already in the list.
type dlList struct {
    members map[*dlNode]int
    head, tail **dlNode
}


import qualified Data.Map as M

type NodeID = Maybe Rational
data Node a = Node
   {vNode :: a,
    pNode, nNode :: NodeID}
type DLList a = M.Map Rational (Node a)

empty = M.empty

singleton a = M.singleton 0 $ Node a Nothing Nothing

fcons :: a -> DLList a -> DLList a
fcons a list | M.null list = singleton a
             | otherwise   = M.insert newid new $
                             M.insert firstid changed list
  where (firstid, Node firstval _ secondid) = M.findMin list
        newid = firstid - 1
        new     = Node a        Nothing      (Just firstid)
        changed = Node firstval (Just newid) secondid

rcons :: a -> DLList a -> DLList a
rcons a list | M.null list = singleton a
             | otherwise   = M.insert lastid changed $
                             M.insert newid new list
  where (lastid, Node lastval penultimateid _) = M.findMax list
        newid = lastid + 1
        changed = Node lastval penultimateid (Just newid)
        new     = Node a       (Just lastid) Nothing

mcons :: a -> Node a -> Node a -> DLList a -> DLList a
mcons a n1 n2 = M.insert n1id left .
    M.insert midid mid . M.insert n2id right
  where Node n1val farleftid   (Just n2id) = n1
        Node n2val (Just n1id) farrightid  = n2
        midid = (n1id + n2id) / 2   -- Hence the use of Rationals.
        mid = Node a (Just n1id) (Just n2id)
        left  = Node n1val farleftid    (Just midid)
        right = Node n2val (Just midid) farrightid

firstNode :: DLList a -> Node a
firstNode = snd . M.findMin

lastNode :: DLList a -> Node a
lastNode = snd . M.findMax

nextNode :: DLList a -> Node a -> Maybe (Node a)
nextNode l n = nNode n >>= flip M.lookup l

prevNode :: DLList a -> Node a -> Maybe (Node a)
prevNode l n = pNode n >>= flip M.lookup l

fromList = foldr fcons empty

toList = map vNode . M.elems


#include <boost/asio.hpp>
#include <iostream>

int main() {
  int rc {EXIT_SUCCESS};
  try {
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::resolver resolver {io_service};
    auto entries = resolver.resolve({"www.kame.net", ""});
    boost::asio::ip::tcp::resolver::iterator entries_end;
    for (; entries != entries_end; ++entries) {
      std::cout << entries->endpoint().address() << std::endl;
    }
  }
  catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    rc = EXIT_FAILURE;
  }
  return rc;
}


Class Utils.Net Extends %RegisteredObject
{

ClassMethod QueryDNS(pHost As %String, Output ip As %List) As %Status
{
	// some initialisation
	K ip S ip=""

	// check host operating system and input parameters
	S OS=$SYSTEM.Version.GetOS()
	I '$LF($LB("Windows","UNIX"), OS) Q $$$ERROR($$$GeneralError, "Not implemented.")
	I OS="Windows" S cmd="nslookup "_pHost
	I OS="UNIX" S cmd="host "_pHost
	I $MATCH(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 {
		Q $$$ERROR($$$GeneralError, "Invalid host name.")
	}

	// invoke command
	S list=##class(Utils.OS).Call(cmd, 0)

	// iterate through list
	S ptr=0, skip=1
    WHILE $LISTNEXT(list,ptr,value) {
	    I value="" CONTINUE
	    I skip, OS="Windows" S skip=$S(value["Name:": 0, 1: 1) CONTINUE
	    S ipv4=..GetIPAddr("ipv4", value) I $L(ipv4) S $LI(ip, 4)=ipv4
	    S ipv6=..GetIPAddr("ipv6", value) I $L(ipv6) S $LI(ip, 6)=ipv6
    }

	// finished
	I $LD(ip, 4)=0, $LD(ip, 6)=0 Q $$$ERROR($$$GeneralError, "Lookup failed.")
	QUIT $$$OK
}

ClassMethod GetIPAddr(pType As %String = "", pValue As %String = "") As %String
{
	I pType="ipv4" {
		S pos=$LOCATE(pValue, "((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.|$)){4}")
		I pos Q $P($E(pValue, pos, *), " ")
	}
	I pType="ipv6" {
		S pos=$LOCATE(pValue, "([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{1,4}$|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4})")
		I pos Q $P($E(pValue, pos, *), " ")
	}
	QUIT ""
}

}


(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address)

(doseq [addr (InetAddress/getAllByName "www.kame.net")]
  (cond
    (instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr))
    (instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr))))


# runs under node.js
dns = require 'dns'

dns.resolve4 'www.kame.net', (err, addresses) ->
  console.log 'IP4'
  console.log addresses

dns.resolve6 'www.kame.net', (err, addresses) ->
  console.log 'IP6'
  console.log addresses


(sb-bsd-sockets:host-ent-addresses
      (sb-bsd-sockets:get-host-by-name "www.rosettacode.org"))
(#(71 19 147 227))


require "socket"

Socket::Addrinfo.resolve(
	"www.kame.net",
	80,
	type: Socket::Type::STREAM
).each { |a|
	puts a.ip_address.address
}


#include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>

int main(int c, char **v)
{
	int tids[10];
	int parent, spawn;
	int i_data, i2;
	double f_data;

	if (c > 1) {
		spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
		if (spawn <= 0) {
			printf("Can't spawn task\n");
			return 1;
		}

		printf("Spawning successful\n");

		/* pvm_recv(task_id, msgtag).  msgtag identifies what kind of data it is,
 		 * for here: 1 = (int, double), 2 = (int, int)
		 * The receiving order is intentionally swapped, just to show.
		 * task_id = -1 means "receive from any task"
		 */
		pvm_recv(-1, 2);
		pvm_unpackf("%d %d", &i_data, &i2);
		printf("got msg type 2: %d %d\n", i_data, i2);

		pvm_recv(-1, 1);
		pvm_unpackf("%d %lf", &i_data, &f_data);
		printf("got msg type 1: %d %f\n", i_data, f_data);
	} else {
		parent = pvm_parent();

		pvm_initsend(PvmDataDefault);
		i_data = rand();
		f_data = (double)rand() / RAND_MAX;
		pvm_packf("%d %lf", i_data, f_data);
		pvm_send(parent, 1);	/* send msg type 1 */

		pvm_initsend(PvmDataDefault);
		i2 = rand();
		pvm_packf("%d %d", i_data, i2);
		pvm_send(parent, 2);	/* send msg type 2 */
	}

	pvm_exit();
	return 0;
}


1) lambdatalk code
{watch}    // displays the watch

{def watch
  {watch.init}
  {div {@ id="watch"}}
}

{def watch.draw
 {lambda {:r :g :b}
  {svg {@ style="width:300px; height:300px;"}
  {let { {:r :r} {:g :g} {:b :b} {:t {date}} }
   {watch.path 150 150 100 20 :r 1 :t}
   {watch.path 150 150 120 20 :g 2 :t}
   {watch.path 150 150 140 20 :b 3 :t}
   {watch.digit :t} }}}}

{def watch.path
 {lambda {:x :y :r :e :c :i :t}
  {path {@ d="{watch.arc :x :y :r {watch.time :i :t}}"
           fill="none" stroke=":c" stroke-width=":e"}} }}

{def watch.arc
 {lambda {:x :y :r :t}
  {let { {:x :x} {:y :y} {:r :r}
         {:start {watch.pol2car :x :y :r :t}}
         {:end   {watch.pol2car :x :y :r 0}}
         {:flag  {if {<= :t 180} then 0 else 1}} }
    M {car :start} {cdr :start}
    A :r :r 0 :flag 0 {car :end} {cdr :end} }}}

{def watch.time
 {lambda {:i :t}
  {if {= :i 1}
   then {/ {* 360 {% {S.get {+ :i 2} :t} 12}} 12}
   else {/ {* 360 {S.get {+ :i 2} :t}} 60} }}}

{def watch.pol2car
 {lambda {:cx :cy :r :t}
  {let { {:cx :cx} {:cy :cy} {:r :r}
         {:T {* {- :t 90} {/ {PI} 180}}} }
    {cons {+ :cx {* :r {cos :T}}}
          {+ :cy {* :r {sin :T}}}} }}}

{def watch.digit
 {lambda {:t}
  {text {@ x="50%" y="48%"
           base-line="middle"
           text-anchor="middle"
           font-size="2.0em"
           stroke="#ccc"}
        {S.get 0 :t}/{S.get 1 :t}/{S.get 2 :t} }
  {text {@ x="50%" y="58%"
           base-line="middle"
           text-anchor="middle"
           font-size="2.0em"
           stroke="#ccc"}
        {S.get 3 :t} : {S.get 4 :t} : {S.get 5 :t} } }}

2) javascript code (for timing)

{script
  var update = function () {
    document.getElementById("watch").innerHTML =
      LAMBDATALK.eval_forms( "{watch.draw #f00 #0f0 #00f}" )
  };
  LAMBDATALK.DICT['watch.init'] = function () {
    setTimeout( update, 10);
    setInterval( update, 1000);
    return ''
  };
}


program Dragon_curve;

{$APPTYPE CONSOLE}

uses
  Winapi.Windows,
  System.SysUtils,
  System.Classes,
  Vcl.Graphics;

type
  TDragon = class
  private
    p: TColor;
    _sin: TArray<double>;
    _cos: TArray<double>;
    s: double;
    b: TBitmap;
    FAsBitmap: TBitmap;
    const
      sep = 512;
      depth = 14;
    procedure Dragon(n, a, t: Integer; d, x, y: Double; var b: TBitmap);
  public
    constructor Create;
    destructor Destroy; override;
    property AsBitmap: TBitmap read b;
  end;

{ TDragon }

procedure TDragon.Dragon(n, a, t: Integer; d, x, y: Double; var b: TBitmap);
begin
  if n <= 1 then
  begin
    with b.Canvas do
    begin
      Pen.Color := p;
      MoveTo(Trunc(x + 0.5), Trunc(y + 0.5));
      LineTo(Trunc(x + d * _cos[a] + 0.5), Trunc(y + d * _sin[a] + 0.5));
      exit;
    end;
  end;

  d := d * s;
  var a1 := (a - t) and 7;
  var a2 := (a + t) and 7;

  dragon(n - 1, a1, 1, d, x, y, b);
  dragon(n - 1, a2, -1, d, x + d * _cos[a1], y + d * _sin[a1], b);
end;

constructor TDragon.Create;
begin
  s := sqrt(2) / 2;
  _sin := [0, s, 1, s, 0, -s, -1, -s];
  _cos := [1.0, s, 0.0, -s, -1.0, -s, 0.0, s];
  p := Rgb(64, 192, 96);
  b := TBitmap.create;

  var width := Trunc(sep * 11 / 6);
  var height := Trunc(sep * 4 / 3);
  b.SetSize(width, height);
  with b.Canvas do
  begin
    Brush.Color := clWhite;
    Pen.Width := 3;
    FillRect(Rect(0, 0, width, height));
  end;
  dragon(14, 0, 1, sep, sep / 2, sep * 5 / 6, b);
end;

destructor TDragon.Destroy;
begin
  b.Free;
  inherited;
end;

var
  Dragon: TDragon;

begin
  Dragon := TDragon.Create;
  Dragon.AsBitmap.SaveToFile('dragon.bmp');
  Dragon.Free;
end.


USING: kernel math math.statistics math.vectors prettyprint ;

TUPLE: div avg-err crowd-err diversity ;

: diversity ( x seq -- obj )
    [ n-v dup v* mean ] [ mean swap - sq ]
    [ nip dup mean v-n dup v* mean ] 2tri div boa ;

49 { 48 47 51 } diversity .
49 { 48 47 51 42 } diversity .


package main

import "fmt"

func averageSquareDiff(f float64, preds []float64) (av float64) {
    for _, pred := range preds {
        av += (pred - f) * (pred - f)
    }
    av /= float64(len(preds))
    return
}

func diversityTheorem(truth float64, preds []float64) (float64, float64, float64) {
    av := 0.0
    for _, pred := range preds {
        av += pred
    }
    av /= float64(len(preds))
    avErr := averageSquareDiff(truth, preds)
    crowdErr := (truth - av) * (truth - av)
    div := averageSquareDiff(av, preds)
    return avErr, crowdErr, div
}

func main() {
    predsArray := [2][]float64{{48, 47, 51}, {48, 47, 51, 42}}
    truth := 49.0
    for _, preds := range predsArray {
        avErr, crowdErr, div := diversityTheorem(truth, preds)
        fmt.Printf("Average-error : %6.3f\n", avErr)
        fmt.Printf("Crowd-error   : %6.3f\n", crowdErr)
        fmt.Printf("Diversity     : %6.3f\n\n", div)
    }
}


proc grey {n} {format "#%2.2x%2.2x%2.2x" $n $n $n}

pack [canvas .c -height 400 -width 640 -background white]

for {set i 0} {$i < 255} {incr i} {
  set h [grey $i]
  .c create arc [expr {100+$i/5}] [expr {50+$i/5}] [expr {400-$i/1.5}] [expr {350-$i/1.5}] \
                 -start 0 -extent 359 -fill $h -outline $h
}


\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{shadings}
\begin{document}
\begin{tikzpicture}
    \shade[ball color=black] (0,0) circle (4);
\end{tikzpicture}
\end{document}


class DoubleList (item)

  method head ()
    node := item
    every (node := node.traverse_backwards ()) # move to start of list
    return node
  end

  method tail ()
    node := item
    every (node := node.traverse_forwards ()) # move to end of list
    return node
  end

  method insert_at_head (value)
    head().insert_before (DoubleLink(value))
  end

  method insert_at_tail (value)
    tail().insert_after (DoubleLink (value))
  end

  # insert a node for new_value after that for target_value,
  # i.e. in the middle of the list
  method insert_after (target_value, new_value)
    node := head ()
    every node := head().traverse_forwards () do
      if (node.value = target_value)
        then {
          node.insert_after (DoubleLink (new_value))
         break
        }
  end

  # constructor initiates a list making a node from given value
  initially (value)
    self.item := DoubleLink (value)
end


import java.util.LinkedList;

public class DoublyLinkedList {

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<String>();
        list.addFirst("Add First");
        list.addLast("Add Last 1");
        list.addLast("Add Last 2");
        list.addLast("Add Last 1");
        traverseList(list);

        list.removeFirstOccurrence("Add Last 1");
        traverseList(list);
    }

    private static void traverseList(LinkedList<String> list) {
        System.out.println("Traverse List:");
        for ( int i = 0 ; i < list.size() ; i++ ) {
            System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i));
        }
        System.out.println();
    }

}


import std.stdio, std.socket;

void main() {
    auto domain = "www.kame.net", port = "80";

    auto a = getAddressInfo(domain, port, AddressFamily.INET);
    writefln("IPv4 address for %s: %s", domain, a[0].address);

    a = getAddressInfo(domain, port, AddressFamily.INET6);
    writefln("IPv6 address for %s: %s", domain, a[0].address);
}


program DNSQuerying;

{$APPTYPE CONSOLE}

uses
  IdGlobal, IdStackWindows;

const
  DOMAIN_NAME = 'www.kame.net';
var
  lStack: TIdStackWindows;
begin
  lStack := TIdStackWindows.Create;
  try
    Writeln(DOMAIN_NAME);
    Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME));
    Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6));
  finally
    lStack.Free;
  end;
end.


33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet).
{ok,{hostent,"orange.kame.net",
             ["www.kame.net"],
             inet,4,
             [{203,178,141,194}]}}
34> [inet_parse:ntoa(Addr) || Addr <- AddrList].
["203.178.141.194"]
35> f().
ok
36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6).
{ok,{hostent,"orange.kame.net",[],inet6,16,
             [{8193,512,3583,65521,534,16127,65201,17623}]}}
37> [inet_parse:ntoa(Addr) || Addr <- AddrList].
["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]


using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;

using static System.Console;

class DistributedProgramming
{
    const int Port = 555;

    async static Task RunClient()
    {
        WriteLine("Connecting");
        var client = new TcpClient();
        await client.ConnectAsync("localhost", Port);

        using (var stream = client.GetStream())
        {
            WriteLine("Sending loot");
            var data = Serialize(new SampleData());
            await stream.WriteAsync(data, 0, data.Length);

            WriteLine("Receiving thanks");
            var buffer = new byte[80000];
            var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
            var thanks = (string)Deserialize(buffer, bytesRead);
            WriteLine(thanks);
        }

        client.Close();
    }

    async static Task RunServer()
    {
        WriteLine("Listening");
        var listener = new TcpListener(IPAddress.Any, Port);
        listener.Start();
        var client = await listener.AcceptTcpClientAsync();

        using (var stream = client.GetStream())
        {
            WriteLine("Receiving loot");
            var buffer = new byte[80000];
            var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
            var data = (SampleData)Deserialize(buffer, bytesRead);
            WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");

            WriteLine("Sending thanks");
            var thanks = Serialize("Thanks!");
            await stream.WriteAsync(thanks, 0, thanks.Length);
        }

        client.Close();
        listener.Stop();
        Write("Press a key");
        ReadKey();
    }

    static byte[] Serialize(object data)
    {
        using (var mem = new MemoryStream())
        {
            new BinaryFormatter().Serialize(mem, data);
            return mem.ToArray();
        }
    }

    static object Deserialize(byte[] data, int length)
    {
        using (var mem = new MemoryStream(data, 0, length))
        {
            return new BinaryFormatter().Deserialize(mem);
        }
    }

    static void Main(string[] args)
    {
        if (args.Length == 0) return;

        switch (args[0])
        {
            case "client": RunClient().Wait(); break;
            case "server": RunServer().Wait(); break;
        }
    }
}

[Serializable]
class SampleData
{
    public decimal Latitude = 44.33190m;
    public decimal Longitude = 114.84129m;
    public string Loot = "140 tonnes of jade";
}


    WindowWidth  =120
    WindowHeight =144
    nomainwin

    open "Clock" for graphics_nsb_nf as #clock
    #clock "trapclose [exit]"
    #clock "fill white"
    for angle =0 to 330 step 30
        #clock "up ; home ; north ; turn "; angle
        #clock "go 40 ; down ; go 5"
    next angle

    #clock "flush"

    timer 1000, [display]
    wait

[display]  ' called only when seconds have changed
    time$   =time$()
    seconds =val( right$( time$, 2))
    ' delete the last drawn segment, if there is one
    if segId >2 then #clock "delsegment "; segId -1
    ' center the turtle
    #clock "up ; home ; down ; north"
    ' erase each hand if its position has changed
    if oldSeconds <>seconds then #clock, "size 1 ; color white ; turn "; oldSeconds *6 ; " ; go 38 ; home ; color black ; north" : oldSeconds =seconds
    ' redraw all three hands, second hand first
    #clock "size 1 ; turn "; seconds * 6 ; " ; go 38"
    ' flush to end segment, then get the next segment id #
    #clock "flush"
    #clock "segment"
    input #clock, segId

    wait

[exit]
    close #clock

    end


color 050
linewidth 0.5
x = 25
y = 60
move x y
angle = 0
#
func dragon size lev d . .
  if lev = 0
    x -= cos angle * size
    y += sin angle * size
    line x y
  else
    call dragon size / sqrt 2 lev - 1 1
    angle -= d * 90
    call dragon size / sqrt 2 lev - 1 -1
  .
.
call dragon 60 12 1


import Color exposing (..)
import Collage exposing (..)
import Element exposing (..)
import Time exposing (..)
import Html exposing (..)
import Html.App exposing (program)

type alias Point = (Float, Float)

type alias Model =
  { points : List Point
  , level : Int
  , frame : Int
  }

maxLevel = 12
frameCount = 100

type Msg = Tick Time

init : (Model,Cmd Msg)
init = ( { points = [(-200.0, -70.0), (200.0, -70.0)]
         , level = 0
         , frame = 0
         }
       , Cmd.none )

-- New point between two existing points.  Offset to left or right
newPoint : Point -> Point -> Float -> Point
newPoint  (x0,y0) (x1,y1) offset =
  let (vx, vy) = ((x1 - x0) / 2.0, (y1 - y0) / 2.0)
      (dx, dy) = (-vy * offset , vx * offset )
  in  (x0 + vx + dx, y0 + vy + dy) --offset from midpoint

-- Insert between existing points. Offset to left or right side.
newPoints : Float -> List Point -> List Point
newPoints offset points =
  case points of
    [] -> []
    [p0] -> [p0]
    p0::p1::rest -> p0 :: newPoint p0 p1 offset :: newPoints -offset (p1::rest)

update : Msg -> Model -> (Model, Cmd Msg)
update _ model =
  let mo = if (model.level == maxLevel)
           then model
           else let nextFrame = model.frame + 1
                in if (nextFrame == frameCount)
                   then { points = newPoints 1.0 model.points
                        , level = model.level+1
                        , frame = 0
                        }
                   else { model | frame = nextFrame
                        }
  in (mo, Cmd.none)

-- break a list up into n equal sized lists.
breakupInto : Int -> List a -> List (List a)
breakupInto n ls =
    let segmentCount = (List.length ls) - 1
        breakup n ls = case ls of
          [] -> []
          _ -> List.take (n+1) ls :: breakup n (List.drop n ls)
    in if n > segmentCount
       then [ls]
       else breakup (segmentCount // n) ls

view : Model -> Html Msg
view model =
  let offset = toFloat (model.frame) / toFloat frameCount
      colors = [red, orange, green, blue]
  in toHtml
       <| layers
            [ collage 700 500
              (model.points
                |> newPoints offset
                |> breakupInto (List.length colors) -- for coloring
                |> List.map path
                |> List.map2 (\color path -> traced (solid color) path ) colors )
              , show model.level
            ]

subscriptions : Model -> Sub Msg
subscriptions _ =
    Time.every (5*millisecond) Tick

main =
  program
      { init = init
      , view = view
      , update = update
      , subscriptions = subscriptions
      }


class DiversityPredictionTheorem {
    private static double square(double d) {
        return d * d
    }

    private static double averageSquareDiff(double d, double[] predictions) {
        return Arrays.stream(predictions)
                .map({ it -> square(it - d) })
                .average()
                .orElseThrow()
    }

    private static String diversityTheorem(double truth, double[] predictions) {
        double average = Arrays.stream(predictions)
                .average()
                .orElseThrow()
        return String.format("average-error : %6.3f%n", averageSquareDiff(truth, predictions)) + String.format("crowd-error   : %6.3f%n", square(truth - average)) + String.format("diversity     : %6.3f%n", averageSquareDiff(average, predictions))
    }

    static void main(String[] args) {
        println(diversityTheorem(49.0, [48.0, 47.0, 51.0] as double[]))
        println(diversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0] as double[]))
    }
}


mean :: (Fractional a, Foldable t) => t a -> a
mean lst = sum lst / fromIntegral (length lst)

meanSq :: Fractional c => c -> [c] -> c
meanSq x = mean . map (\y -> (x-y)^^2)

diversityPrediction x estimates = do
   putStrLn $ "TrueValue:\t" ++ show x
   putStrLn $ "CrowdEstimates:\t" ++ show estimates
   let avg = mean estimates
   let avgerr = meanSq x estimates
   putStrLn $ "AverageError:\t" ++ show avgerr
   let crowderr = (x - avg)^^2
   putStrLn $ "CrowdError:\t" ++ show crowderr
   let diversity = meanSq avg estimates
   putStrLn $ "Diversity:\t" ++ show diversity


% Draw a sphere in ASCII art in Turing

% Light intensity to character map
const shades := '.:!*oe&#%@'
const maxShades := length (shades)

% Absolute dot product of x and y
function dot (x, y : array 1 .. 3 of real) : real
     result abs (x(1) * y(1) + x(2) * y(2) + x(3) * y(3))
end dot

% Vector normalization
procedure normalize (var v : array 1 .. 3 of real)
    const norm := sqrt (v(1)**2 + v(2)**2 + v(3)**2)
    for i : 1 .. 3
        v(i) := v(i) / norm
    end for
end normalize

% Draws a sphere using ASCII art
procedure drawSphere (radius : real, k : int, lightsource : array 1 .. 3 of real, brightness : real)
    const diameter := 2.0 * radius
    for i : floor (-radius) .. ceil (radius)
        var x := i + 0.5
        for j : floor (-diameter) .. ceil (diameter)
            var y  := j / 2 + 0.5

            if x**2 + y**2 <= radius**2 then
                var vec : array 1 .. 3 of real
                vec(1) := x; vec(2) := y; vec(3) := sqrt (radius**2 - x**2 - y**2)
                normalize (vec)

                const b := dot (lightsource, vec) ** k + brightness
                var intensity := round ((1 - b) * maxShades)

                if intensity < 1 then
                    intensity := 1
                elsif intensity > maxShades then
                    intensity := maxShades
                end if

                put shades (intensity) ..
            else
                put ' ' ..
            end if
        end for
        put ""
    end for
end drawSphere

% Light source
var lightsource : array 1 .. 3 of real := init (30, 30, -59)
normalize (lightsource)
const brightness := 0.1

% Draw some spheres
drawSphere (20, 4, lightsource, brightness)
drawSphere (15, 10, lightsource, brightness)


shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)

Sub Normalize(v)
   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
   v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub

Function Dot(x, y)
   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
   If d < 0 Then Dot = -d Else Dot = 0 End If
End Function

'floor function is the Int function
'ceil function implementation
Function Ceil(x)
    Ceil = Int(x)
    If Ceil <> x Then Ceil = Ceil + 1 End if
End Function

Sub DrawSphere(R, k, ambient)
   Dim i, j, intensity, inten, b, x, y
   Dim vec(3)
   For i = Int(-R) to Ceil(R)
      x = i + 0.5
      line = ""
      For j = Int(-2*R) to Ceil(2*R)
         y = j / 2 + 0.5
         If x * x + y * y <= R*R Then
            vec(0) = x
            vec(1) = y
            vec(2) = Sqr(R * R - x * x - y * y)
            Normalize vec
            b = dot(light, vec)^k + ambient
            intensity = Int((1 - b) * UBound(shades))
            If intensity < 0 Then intensity = 0 End If
            If intensity >= UBound(shades) Then
               intensity = UBound(shades)
            End If
            line = line & shades(intensity)
         Else
            line = line & " "
         End If
      Next
      WScript.StdOut.WriteLine line
   Next
End Sub

Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4


// version 1.1.2

class LinkedList<E> {
    class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) {
        override fun toString(): String {
            val sb = StringBuilder(this.data.toString())
            var node = this.next
            while (node != null) {
                sb.append(" -> ", node.data.toString())
                node = node.next
            }
            return sb.toString()
        }
    }

    var first: Node<E>? = null
    var last:  Node<E>? = null

    fun addFirst(value: E) {
        if (first == null) {
            first = Node(value)
            last =  first
        }
        else {
            val node = first!!
            first = Node(value, null, node)
            node.prev = first
        }
    }

    fun addLast(value: E) {
        if (last == null) {
            last = Node(value)
            first = last
        }
        else {
            val node = last!!
            last = Node(value, node, null)
            node.next = last
        }
    }

    fun insert(after: Node<E>?, value: E) {
        if (after == null)
            addFirst(value)
        else if (after == last)
            addLast(value)
        else {
            val next = after.next
            val new = Node(value, after, next)
            after.next = new
            if (next != null) next.prev = new
        }
    }

    override fun toString() = first.toString()
}

fun main(args: Array<String>) {
    val ll = LinkedList<Int>()
    ll.addFirst(1)
    ll.addLast(4)
    ll.insert(ll.first, 2)
    ll.insert(ll.last!!.prev, 3)
    println(ll)
}


USING: dns io kernel sequences ;

"www.kame.net" [ dns-A-query ] [ dns-AAAA-query ] bi
[ message>names second print ] [email protected]


for a = callJava["java.net.InetAddress", "getAllByName", "www.kame.net"]
   println[a.getHostAddress[]]


package main

import (
    "fmt"
    "net"
)

func main() {
    if addrs, err := net.LookupHost("www.kame.net"); err == nil {
        fmt.Println(addrs)
    } else {
        fmt.Println(err)
    }
}


def addresses = InetAddress.getAllByName('www.kame.net')
println "IPv4: ${addresses.find { it instanceof Inet4Address }?.hostAddress}"
println "IPv6: ${addresses.find { it instanceof Inet6Address }?.hostAddress}"


module Main where

import Network.Socket

getWebAddresses :: HostName -> IO [SockAddr]
getWebAddresses host = do
  results <- getAddrInfo (Just defaultHints) (Just host) (Just "http")
  return [ addrAddress a | a <- results, addrSocketType a == Stream ]

showIPs :: HostName -> IO ()
showIPs host = do
  putStrLn $ "IP addresses for " ++ host ++ ":"
  addresses <- getWebAddresses host
  mapM_ (putStrLn . ("  "++) . show) addresses

main = showIPs "www.kame.net"


import arsd.rpc;

struct S1 {
    int number;
    string name;
}

struct S2 {
    string name;
    int number;
}

interface ExampleNetworkFunctions {
    string sayHello(string name);
    int add(in int a, in int b) const pure nothrow;
    S2 structTest(S1);
    void die();
}

// The server must implement the interface.
class ExampleServer : ExampleNetworkFunctions {
    override string sayHello(string name) {
        return "Hello, " ~ name;
    }

    override int add(in int a, in int b) const pure nothrow {
        return a + b;
    }

    override S2 structTest(S1 a) {
        return S2(a.name, a.number);
    }

    override void die() {
        throw new Exception("death requested");
    }

    mixin NetworkServer!ExampleNetworkFunctions;
}

class Client {
    mixin NetworkClient!ExampleNetworkFunctions;
}

void main(in string[] args) {
    import std.stdio;

    if (args.length > 1) {
        auto client = new Client("localhost", 5005);
        // These work like the interface above, but instead of
        // returning the value, they take callbacks for success (where
        // the arg is the retval) and failure (the arg is the
        // exception).
        client.sayHello("whoa", (a) { writeln(a); }, null);
        client.add(1,2, (a){ writeln(a); }, null);
        client.add(10,20, (a){ writeln(a); }, null);
        client.structTest(S1(20, "cool!"),
                          (a){ writeln(a.name, " -- ", a.number); },
                          null);
        client.die(delegate(){ writeln("shouldn't happen"); },
                   delegate(a){ writeln(a); });
        client.eventLoop;
    } else {
        auto server = new ExampleServer(5005);
        server.eventLoop;
    }
}


10 mode 1:defint a-y:deg
20 input "Current time (HH:MM)";t$
30 h=val(mid$(t$,1,2))
40 m=val(mid$(t$,4,2))
50 cls
60 r=150:s=-1
70 ph=0:pm=0
80 origin 320,200
90 for a=0 to 360 step 6
100 if a mod 30>0 then z=.9 else z=.8
110 move z*r*sin(a),z*r*cos(a)
120 draw r*sin(a),r*cos(a)
130 next
140 move 0,r
150 for a=0 to 360 step 6
160 draw r*sin(a),r*cos(a)
170 next
180 every 50 gosub 220
190 ' ENDLESS_LOOP
200 goto 200
210 ' NEW_SEC
220 s=s+1
230 if s=60 then s=0:m=m+1
240 if m=60 then m=0:h=h+1
250 if h=24 then h=0
260 if s=0 then gosub 300
270 if s>0 then gosub 420
280 return
290 ' DRAW_ALL
300 locate 1,1
310 print using "##";h;
320 print ":";
330 print using "##";m;
340 frame:move 0,0:draw .5*r*sin(ph),.5*r*cos(ph),0,0
350 frame:move 0,0:draw .7*r*sin(pm),.7*r*cos(pm),0,0
360 frame:move 0,0:draw .8*r*sin(6*59),.8*r*cos(6*59),0,0
370 pm=6*m
380 frame:move 0,0:draw .7*r*sin(pm),.7*r*cos(pm),1,0
390 ph=30*h+.5*m
400 frame:move 0,0:draw .5*r*sin(ph),.5*r*cos(ph),1,0
410 ' DRAW_SEC
420 a=6*s
430 ' uses "frame" and XOR ink mode for drawing -- requires BASIC 1.1
440 if a>0 then frame:move 0,0:draw .8*r*sin(a-6),.8*r*cos(a-6),3,1
450 frame:move 0,0:draw .8*r*sin(a),.8*r*cos(a),3,1
460 return


*        Dot product               03/05/2016
DOTPROD  CSECT
         USING  DOTPROD,R15
         SR     R7,R7              p=0
         LA     R6,1               i=1
LOOPI    CH     R6,=AL2((B-A)/4)   do i=1 to hbound(a)
         BH     ELOOPI
         LR     R1,R6              i
         SLA    R1,2               *4
         L      R3,A-4(R1)         a(i)
         L      R4,B-4(R1)         b(i)
         MR     R2,R4              a(i)*b(i)
         AR     R7,R3              p=p+a(i)*b(i)
         LA     R6,1(R6)           i=i+1
         B      LOOPI
ELOOPI   XDECO  R7,PG              edit p
         XPRNT  PG,80              print buffer
         XR     R15,R15            rc=0
         BR     R14                return
A        DC     F'1',F'3',F'-5'
B        DC     F'4',F'-2',F'-1'
PG       DC     CL80' '            buffer
         YREGS
         END    DOTPROD


report zdot_product
data: lv_n type i,
      lv_sum type i,
      lt_a type standard table of i,
      lt_b type standard table of i.

append: '1' to lt_a, '3' to lt_a, '-5' to lt_a.
append: '4' to lt_b, '-2' to lt_b, '-1' to lt_b.
describe table lt_a lines lv_n.

perform dot_product using lt_a lt_b lv_n changing lv_sum.

write lv_sum left-justified.

form dot_product using it_a like lt_a
                       it_b like lt_b
                       iv_n type i
                 changing
                       ev_sum type i.
  field-symbols: <wa_a> type i, <wa_b> type i.

  do iv_n times.
    read table: it_a assigning <wa_a> index sy-index, it_b assigning <wa_b> index sy-index.
    lv_sum = lv_sum + ( <wa_a> * <wa_b> ).
  enddo.
endform.


(defun dragon-ensure-line-above ()
  "If point is in the first line of the buffer then insert a new line above."
  (when (= (line-beginning-position) (point-min))
    (save-excursion
      (goto-char (point-min))
      (insert "\n"))))

(defun dragon-ensure-column-left ()
  "If point is in the first column then insert a new column to the left.
This is designed for use in `picture-mode'."
  (when (zerop (current-column))
    (save-excursion
      (goto-char (point-min))
      (insert " ")
      (while (= 0 (forward-line 1))
        (insert " ")))
    (picture-forward-column 1)))

(defun dragon-insert-char (char len)
  "Insert CHAR repeated LEN many times.
After each CHAR point move in the current `picture-mode'
direction (per `picture-set-motion' etc).

This is the same as `picture-insert' except in column 0 or row 0
a new row or column is inserted to make room, with existing
buffer contents shifted down or right."

  (dotimes (i len)
    (dragon-ensure-line-above)
    (dragon-ensure-column-left)
    (picture-insert char 1)))

(defun dragon-bit-above-lowest-0bit (n)
  "Return the bit above the lowest 0-bit in N.
For example N=43 binary \"101011\" has lowest 0-bit at \"...0..\"
and the bit above that is \"..1...\" so return 8 which is that
bit."
  (logand n (1+ (logxor n (1+ n)))))

(defun dragon-next-turn-right-p (n)
  "Return non-nil if the dragon curve should turn right after segment N.
Segments are numbered from N=0 for the first, so calling with N=0
is whether to turn right after drawing that N=0 segment."
  (zerop (dragon-bit-above-lowest-0bit n)))

(defun dragon-picture (len step)
  "Draw the dragon curve in a *dragon* buffer.
LEN is the number of segments of the curve to draw.
STEP is the length of each segment, in characters.

Any LEN can be given but a power-of-2 such as 256 shows the
self-similar nature of the curve.

If STEP >= 2 then the segments are lines using \"-\" or \"|\"
characters (`picture-rectangle-h' and `picture-rectangle-v').
If STEP=1 then only \"+\" corners.

There's a `sit-for' delay in the drawing loop to draw the curve
progressively on screen."

  (interactive (list (read-number "Length of curve " 256)
                     (read-number "Each step size " 3)))
  (unless (>= step 1)
    (error "Step length must be >= 1"))

  (switch-to-buffer "*dragon*")
  (erase-buffer)
  (ignore-errors ;; if already in picture-mode
    (picture-mode))

  (dotimes (n len)  ;; n=0 to len-1, inclusive
    (dragon-insert-char ?+ 1)  ;; corner char
    (dragon-insert-char (if (zerop picture-vertical-step)
                                    picture-rectangle-h picture-rectangle-v)
                                (1- step))  ;; line chars

    (if (dragon-next-turn-right-p n)
        ;; turn right
        (picture-set-motion (- picture-horizontal-step) picture-vertical-step)
      ;; turn left
      (picture-set-motion picture-horizontal-step (- picture-vertical-step)))

    ;; delay to display the drawing progressively
    (sit-for .01))

  (picture-insert ?+ 1) ;; endpoint
  (picture-mode-exit)
  (goto-char (point-min)))

(dragon-picture 128 2)


echo 'Use: ' , (;:inv 2 {. ARGV) , ' <reference value>  <observations>'

data=: ([: ". [: ;:inv 2&}.) ::([: exit 1:) ARGV

([: exit (1: [email protected]('insufficient data'"_)))^:(2 > #) data

mean=: +/ % #
variance=: [: mean [: *: -

averageError=: ({. variance }.)@:]
crowdError=:  variance {.
diversity=:  variance }.

echo (<;._2'average error;crowd error;diversity;') ,: ;/ (averageError`crowdError`diversity`:0~ [email protected]:}.) data

exit 0


import java.util.Arrays;

public class DiversityPredictionTheorem {
    private static double square(double d) {
        return d * d;
    }

    private static double averageSquareDiff(double d, double[] predictions) {
        return Arrays.stream(predictions)
            .map(it -> square(it - d))
            .average()
            .orElseThrow();
    }

    private static String diversityTheorem(double truth, double[] predictions) {
        double average = Arrays.stream(predictions)
            .average()
            .orElseThrow();
        return String.format("average-error : %6.3f%n", averageSquareDiff(truth, predictions))
            + String.format("crowd-error   : %6.3f%n", square(truth - average))
            + String.format("diversity     : %6.3f%n", averageSquareDiff(average, predictions));
    }

    public static void main(String[] args) {
        System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0}));
        System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0, 42.0}));
    }
}


var shades = ".:!*oe&#\%@"
var light = [30, 30, -50]

var normalize = Fn.new { |v|
    var len = (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]).sqrt
    for (i in 0..2) v[i] =  v[i] / len
}

var dot = Fn.new { |x, y|
    var d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
    return (d < 0) ? -d : 0
}

var drawSphere = Fn.new { |r, k, ambient|
    var vec = [0] * 3
    for (i in (-r).floor..r.ceil) {
        var x = i + 0.5
        for (j in (-2*r).floor..(2*r).ceil) {
            var y = j/2 + 0.5
            if (x*x + y*y <= r*r) {
                var vec = [x, y, (r*r - x*x - y*y).sqrt]
                normalize.call(vec)
                var b = dot.call(light, vec).pow(k) + ambient
                var intensity = ((1 - b) * (shades.count - 1)).truncate
                if (intensity < 0) intensity = 0
                if (intensity >= shades.count - 1) intensity = shades.count - 2
                System.write(shades[intensity])
            } else {
                System.write(" ")
            }
        }
        System.print()
    }
}

normalize.call(light)
drawSphere.call(20, 4, 0.1)
drawSphere.call(10, 2, 0.4)


-- Doubly Linked List in Lua 6/15/2020 db
-------------------
-- IMPLEMENTATION:
-------------------

local function Node(data)
  return { data=data } --implied: return { data=data, prev=nil, next=nil }
end

local List = {
  head = nil,
  tail = nil,
  insertHead = function(self, data)
    local node = Node(data)
    if (self.head) then
      self.head.prev = node
      node.next = self.head
      self.head = node
    else
      self.head = node
      self.tail = node
    end
    return node
  end,
  insertTail = function(self, data)
    local node = Node(data)
    if self.tail then
      self.tail.next = node
      node.prev = self.tail
      self.tail = node
    else
      self.head = node
      self.tail = node
    end
    return node
  end,
  insertBefore = function(self,mark,data)
    if (mark) then
      local node = Node(data)
      if (mark == self.head) then
        self.head.next = node
        node.next = self.head
        self.head = node
      else
        mark.prev.next = node
        node.prev = mark.prev
        mark.prev = node
        node.next = mark
      end
      return node
    else
      -- if no mark given, then insertBefore()==insertHead()
      return self:insertHead(data)
    end
  end,
  insertAfter = function(self,mark,data)
    if (mark) then
      local node = Node(data)
      if (mark == self.tail) then
        self.tail.next = node
        node.prev = self.tail
        self.tail = node
      else
        mark.next.prev = node
        node.next = mark.next
        mark.next = node
        node.prev = mark
      end
      return node
    else
      -- if no mark given, then insertAfter()==insertTail()
      return self:insertTail(data)
    end
  end,
  values = function(self)
    local result, node = {}, self.head
    while (node) do result[#result+1], node = node.data, node.next end
    return result
  end,
}
List.__index = List
setmetatable(List, {__call=function(self) return setmetatable({},self) end })

---------
-- TEST:
---------
local function validate(list, expected)
  local values = list:values()
  local actual = table.concat(values, ",")
  print(actual==expected, actual)
end
local list = List()                      validate(list, "")
local n1   = list:insertTail(1)          validate(list, "1")
local n2   = list:insertTail(2)          validate(list, "1,2")
local n3   = list:insertTail(3)          validate(list, "1,2,3")
local n4   = list:insertTail(4)          validate(list, "1,2,3,4")
local n33  = list:insertAfter(n3, 33)    validate(list, "1,2,3,33,4")
local n22  = list:insertAfter(n2, 22)    validate(list, "1,2,22,3,33,4")
local n11  = list:insertAfter(n1, 11)    validate(list, "1,11,2,22,3,33,4")
local n44  = list:insertAfter(n4, 44)    validate(list, "1,11,2,22,3,33,4,44")
local n5   = list:insertTail(5)          validate(list, "1,11,2,22,3,33,4,44,5")
local n444 = list:insertBefore(n5, 444)  validate(list, "1,11,2,22,3,33,4,44,444,5")
local n55  = list:insertAfter(nil, 55)   validate(list, "1,11,2,22,3,33,4,44,444,5,55")
local n0   = list:insertHead(0)          validate(list, "0,1,11,2,22,3,33,4,44,444,5,55")
local nm1  = list:insertBefore(nil, -1)  validate(list, "-1,0,1,11,2,22,3,33,4,44,444,5,55")
local n111 = list:insertBefore(n2, 111)  validate(list, "-1,0,1,11,111,2,22,3,33,4,44,444,5,55")
local n222 = list:insertAfter(n22, 222)  validate(list, "-1,0,1,11,111,2,22,222,3,33,4,44,444,5,55")
local n333 = list:insertBefore(n4, 333)  validate(list, "-1,0,1,11,111,2,22,222,3,33,333,4,44,444,5,55")
local n555 = list:insertAfter(n55, 555)  validate(list, "-1,0,1,11,111,2,22,222,3,33,333,4,44,444,5,55,555")


procedure main(A)
   host := gethost( A[1] | "www.kame.net") | stop("can't translate")
   write(host.name, ": ", host.addresses)
end


   2!:0'dig -4 +short www.kame.net'
orange.kame.net.
203.178.141.194

   2!:0'dig -6 +short www.kame.net'
|interface error
|       2!:0'dig -6 +short www.kame.net'


import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;

class DnsQuery {
    public static void main(String[] args) {
        try {
            InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net");
            for(int i=0; i < ipAddr.length ; i++) {
                if (ipAddr[i] instanceof Inet4Address) {
                    System.out.println("IPv4 : " + ipAddr[i].getHostAddress());
                } else if (ipAddr[i] instanceof Inet6Address) {
                    System.out.println("IPv6 : " + ipAddr[i].getHostAddress());
                }
            }
        } catch (UnknownHostException uhe) {
            System.err.println("unknown host");
        }
    }
}


const dns = require("dns");

dns.lookup("www.kame.net", {
             all: true
          }, (err, addresses) => {
              if(err) return console.error(err);
              console.log(addresses);
          })


def storage := [].diverge()

def logService {
  to log(line :String) {
    storage.push([timer.now(), line])
  }
  to search(substring :String) {
    var matches := []
    for [time, line] ? (line.startOf(substring) != -1) in storage {
      matches with= [time, line]
    }
    return matches
  }
}

introducer.onTheAir()
def sturdyRef := makeSturdyRef.temp(logService)
println(<captp>.sturdyToURI(sturdyRef))
interp.blockAtTop()


-module(srv).
-export([start/0, wait/0]).

start() ->
   net_kernel:start([srv,shortnames]),
   erlang:set_cookie(node(), rosetta),
   Pid = spawn(srv,wait,[]),
   register(srv,Pid),
   io:fwrite("~p ready~n",[node(Pid)]),
   ok.

wait() ->
   receive
       {echo, Pid, Any} ->
           io:fwrite("-> ~p from ~p~n", [Any, node(Pid)]),
           Pid ! {hello, Any},
           wait();
       Any -> io:fwrite("Error ~p~n", [Any])
   end.


Dynamic[ClockGauge[], UpdateInterval -> 1]


(defun dotp (v u)
   (if (or (endp v) (endp u))
       0
       (+ (* (first v) (first u))
          (dotp (rest v) (rest u)))))


INT FUNC DotProduct(INT ARRAY v1,v2 BYTE len)
  BYTE i,res

  res=0
  FOR i=0 TO len-1
  DO
    res==+v1(i)*v2(i)
  OD
RETURN (res)

PROC PrintVector(INT ARRAY a BYTE size)
  BYTE i

  Put('[)
  FOR i=0 TO size-1
  DO
    PrintI(a(i))
    IF i<size-1 THEN
      Put(',)
    FI
  OD
  Put('])
RETURN

PROC Test(INT ARRAY v1,v2 BYTE len)
  INT res

  res=DotProduct(v1,v2,len)
  PrintVector(v1,len)
  Put('.)
  PrintVector(v2,len)
  Put('=)
  PrintIE(res)
RETURN

PROC Main()
  INT ARRAY
    v1=[1 3 65531],
    v2=[4 65534 65535]

  Test(v1,v2,3)
RETURN


PROGRAM DRAGON

!
! for rosettacode.org
!

!$DYNAMIC
DIM RQS[0]

!$INCLUDE="PC.LIB"

PROCEDURE DRAGON
        IF LEVEL<=0 THEN
                YN=SIN(ROTATION)*INSIZE+Y
                XN=COS(ROTATION)*INSIZE+X
                LINE(X,Y,XN,YN,12,FALSE)
                ITER=ITER+1
                X=XN Y=YN
                EXIT PROCEDURE
        END IF
        INSIZE=INSIZE/SQ
        ROTATION=ROTATION+RQ*QPI
        LEVEL=LEVEL-1
        RQS[LEVEL]=RQ
        RQ=1 DRAGON
        ROTATION=ROTATION-RQS[LEVEL]*QPI*2
        RQ=-1 DRAGON
        RQ=RQS[LEVEL]
        ROTATION=ROTATION+RQ*QPI
        LEVEL=LEVEL+1
        INSIZE=INSIZE*SQ
END PROCEDURE

BEGIN
        SCREEN(9)

        LEVEL=12 INSIZE=287        ! initial values
        X=200 Y=120                !

        SQ=SQR(2)  QPI=ATN(1)      ! constants
        ROTATION=0 ITER=0 RQ=1     ! state variables
        !$DIM RQS[LEVEL]
                                   ! stack for RQ (ROTATION coefficient)
        LINE(0,0,639,349,14,TRUE)
        DRAGON
        GET(A$)
END PROGRAM


open System.Windows
open System.Windows.Media

let m = Matrix(0.0, 0.5, -0.5, 0.0, 0.0, 0.0)

let step segs =
  seq { for a: Point, b: Point in segs do
          let x = a + 0.5 * (b - a) + (b - a) * m
          yield! [a, x; b, x] }

let rec nest n f x =
  if n=0 then x else nest (n-1) f (f x)

[<System.STAThread>]
do
  let path = Shapes.Path(Stroke=Brushes.Black, StrokeThickness=0.001)
  path.Data <-
    PathGeometry
      [ for a, b in nest 13 step (seq [Point(0.0, 0.0), Point(1.0, 0.0)]) ->
          PathFigure(a, [(LineSegment(b, true) :> PathSegment)], false) ]
  (Application()).Run(Window(Content=Controls.Viewbox(Child=path))) |> ignore


'use strict';

function sum(array) {
    return array.reduce(function (a, b) {
        return a + b;
    });
}

function square(x) {
    return x * x;
}

function mean(array) {
    return sum(array) / array.length;
}

function averageSquareDiff(a, predictions) {
    return mean(predictions.map(function (x) {
        return square(x - a);
    }));
}

function diversityTheorem(truth, predictions) {
    var average = mean(predictions);
    return {
        'average-error': averageSquareDiff(truth, predictions),
        'crowd-error': square(truth - average),
        'diversity': averageSquareDiff(average, predictions)
    };
}

console.log(diversityTheorem(49, [48,47,51]))
console.log(diversityTheorem(49, [48,47,51,42]))


/* Diverisity Prediction Theorem, in Jsish */
"use strict";

function sum(arr:array):number {
    return arr.reduce(function(acc, cur, idx, arr) { return acc + cur; });
}

function square(x:number):number {
    return x * x;
}

function mean(arr:array):number {
    return sum(arr) / arr.length;
}

function averageSquareDiff(a:number, predictions:array):number {
    return mean(predictions.map(function(x:number):number { return square(x - a); }));
}

function diversityTheorem(truth:number, predictions:array):object {
    var average = mean(predictions);
    return {
        "average-error": averageSquareDiff(truth, predictions),
        "crowd-error": square(truth - average),
        "diversity": averageSquareDiff(average, predictions)
    };
}

;diversityTheorem(49, [48,47,51]);
;diversityTheorem(49, [48,47,51,42]);

/*
=!EXPECTSTART!=
diversityTheorem(49, [48,47,51]) ==> { "average-error":3, "crowd-error":0.1111111111111127, diversity:2.888888888888889 }
diversityTheorem(49, [48,47,51,42]) ==> { "average-error":14.5, "crowd-error":4, diversity:10.5 }
=!EXPECTEND!=
*/


include c:\cxpl\codes;          \intrinsic 'code' declarations
def     R=100, R2=R*R;          \radius, in pixels; radius squared
def     X0=640/2, Y0=480/2;     \coordinates of center of screen
int     X, Y, Z, C, D2;         \coords, color, distance from center squared
[SetVid($112);                  \set 640x480x24 graphics mode
for Y:= -R to +R do             \for all the coordinates near the circle
    for X:= -R to +R do         \ which is under the sphere
        [D2:= X*X + Y*Y;
        C:= 0;                  \default color is black
        if D2 <= R2 then        \coordinate is inside circle under sphere
            [Z:= sqrt(R2-D2);   \height of point on surface of sphere above X,Y
            C:= Z-(X+Y)/2+130;  \color is proportional; offset X and Y, and
            ];                  \ shift color to upper limit of its range
        Point(X+X0, Y+Y0, C<<8+C); \green + blue = cyan
       ];
repeat until KeyHit;            \wait for keystroke
SetVid($03);                    \restore normal text mode
]


ancho = 640 : alto = 480
open window 640,480
backcolor 16,16,16
clear window
sphera()

sub sphera()
	local n

	for n = 1 to 100
		color 2*n, 2*n, 2*n
		fill circle ancho/2-2*n/3, alto/2-n/2, 150-n
	next n
end sub


Module Checkit {
      Form 80, 50
      Class Null {}
      Global Null->Null()
      Class Node {
            group pred, succ
            dat=0
            Remove {
                  Print "destroyed", .dat
            }
            class:
            module Node {
                  .pred->Null
                  .succ->Null
                  if match("N") Then Read .dat
            }
      }
      Class LList {
            Group Head, Tail
            Module PushTail(k as pointer) {
                  if .Tail is Null then {
                        .Head<=k
                        .Tail<=k
                  } else {
                        n=.Tail
                        .Tail<=k
                        k=>pred=n=>pred
                        n=>pred=k
                        k=>succ=n
                  }
            }
            Function RemoveTail {
                  n=.Tail
                  if n is .Head then {
                        .Head->Null
                        .Tail->Null
                  } Else {
                        .Tail<=n=>succ
                        .Tail=>pred=n=>pred
                        n=>pred->Null
                  }
                  for n {
                        .succ->Null
                        .pred->Null
                  }
                  =n
            }
            Module PushHead(k as pointer) {
                  if .head is Null then {
                        .Head<=k
                        .Tail<=k
                  } else {
                        n=.head
                        .head<=k
                        k=>succ=n=>succ
                        n=>succ=k
                        k=>pred=n
                  }
            }
            Function RemoveHead {
                  n=.Head
                  if n is .Tail then {
                        .Head->Null
                        .Tail->Null
                  } Else {
                      .Head<=n=>pred
                      .Head=>succ=n=>succ
                       n=>succ->Null
                   }
                  for n {
                        .succ->Null
                        .pred->Null
                  }
                  =n
            }
            Module RemoveNode(k as pointer) {
                  pred=k=>pred
                  succ=k=>succ
                  if pred is succ then {
                        if .head is k else Error "Can't remove this node"
                        k=.RemoveHead()
                        clear k
                  } else {
                       pred=>succ=succ
                       succ=>pred=pred
                  }
            }
            Module InsertAfter(k as pointer, n as pointer) {
                  pred=k=>pred
                  n=>pred=pred
                  n=>succ=k
                  pred=>succ=n
                  k=>pred=n
            }
            Function IsEmpty {
                  = .Head is null or .tail is null
            }
      class:
            Module LList {
                  .Head->Null
                  .Tail->Null
            }
      }
      m->Node(100)

      L=LList()
      L.PushTail m
      If not L.Head is Null then Print L.Head=>dat=100
      for i=101 to 103 {
            m->Node(i)
            L.PushTail m
            Print "ok....", i
      }
      for i=104 to 106 {
            m->Node(i)
            L.PushHead m
            Print "ok....", i
      }

      Print "Use Head to display from last to first"
      m=L.Head
      do {
            Print m=>dat
            m=m=>pred
      } Until m is null
      Print "ok, now find 3rd and remove it"
      m1=L.Head
      i=1
      Index=3
      While i<Index {
            if m1 is null then exit
            m1=m1=>pred
            i++
      }
      If i<>Index then {
            Print "List has less than "; Index;" Items"
      } Else {
            Print "First add one new node"
                  newNode->Node(1000)
                  L.InsertAfter m1, newNode
                  L.RemoveNode m1
                  clear m1  ' last time m1 used here
                  newNode=Null
            Print "ok.............."
      }
      Print "Use Tail to display from first to last"
      m=L.Tail
      do {
            Print m=>dat
            m=m=>succ
      } Until m is null

      useother=True
      While not L.IsEmpty(){
            For This {
                  \\ we have to use a temporary variable name, here A
                         A=If(useother->L.RemoveTail(),L.RemoveHead())
                         ? A=>dat
                        useother~
                        \\ now we can try to perform removing
                        clear A
             }
      }
      Print "list is empty:"; L.IsEmpty()
}
Checkit


ds = CreateDataStructure["DoublyLinkedList"];
ds["Append", #] & /@ {1, 5, 7, 0, 3, 2};
ds["Prepend", 9];
ds["Append", 4];
(* This is adding at the end and then swap to insert in to the middle: *)
ds["Append", 14]; ds["SwapPart", Round[ds["Length"]/2], ds["Length"]];
ds["Elements"]


type
  List[T] = object
    head, tail: Node[T]

  Node[T] = ref TNode[T]

  TNode[T] = object
    next, prev: Node[T]
    data: T

proc initList[T](): List[T] = discard

proc newNode[T](data: T): Node[T] =
  new(result)
  result.data = data

proc prepend[T](l: var List[T], n: Node[T]) =
  n.next = l.head
  if l.head != nil: l.head.prev = n
  l.head = n
  if l.tail == nil: l.tail = n

proc append[T](l: var List[T], n: Node[T]) =
  n.next = nil
  n.prev = l.tail
  if l.tail != nil:
    l.tail.next = n
  l.tail = n
  if l.head == nil:
    l.head = n

proc insertAfter[T](l: var List[T], r, n: Node[T]) =
  n.prev = r
  n.next = r.next
  n.next.prev = n
  r.next = n
  if r == l.tail: l.tail = n

proc remove[T](l: var List[T], n: Node[T]) =
  if n == l.tail: l.tail = n.prev
  if n == l.head: l.head = n.next
  if n.next != nil: n.next.prev = n.prev
  if n.prev != nil: n.prev.next = n.next

proc `$`[T](l: var List[T]): string =
  result = ""
  var n = l.head
  while n != nil:
    if result.len > 0: result.add(" -> ")
    result.add($n.data)
    n = n.next

var l = initList[int]()
var n = newNode(12)
var m = newNode(13)
var i = newNode(14)
var j = newNode(15)
l.append(n)
l.prepend(m)
l.insertAfter(m, i)
l.prepend(j)
l.remove(m)
echo l

var l2 = initList[string]()
l2.prepend newNode("hello")
l2.append newNode("world")
echo l2


IMPORT Basic;
TYPE
	Node* = POINTER TO NodeDesc;
	NodeDesc* = (* ABSTRACT *) RECORD
		prev-,next-: Node;
	END;

	DLList* = POINTER TO DLListDesc;
	DLListDesc* = RECORD
		first-,last-: Node;
		size-: INTEGER;
	END;


julia> using Sockets

julia> getaddrinfo("www.kame.net")
ip"203.178.141.194"

julia> getaddrinfo("www.kame.net", IPv6)
ip"2001:200:dff:fff1:216:3eff:feb1:44d7"


// version 1.1.3

import java.net.InetAddress
import java.net.Inet4Address
import java.net.Inet6Address

fun showIPAddresses(host: String) {
    try {
        val ipas = InetAddress.getAllByName(host)
        println("The IP address(es) for '$host' is/are:\n")
        for (ipa in ipas) {
            print(when (ipa) {
                is Inet4Address -> "  ipv4 : "
                is Inet6Address -> "  ipv6 : "
                else            -> "  ipv? : "
            })
            println(ipa.hostAddress)
        }
    }
    catch (ex: Exception) {
        println(ex.message)
    }
}

fun main(args: Array<String>) {
    showIPAddresses("www.kame.net")
}


local socket = require('socket')
local ip_tbl = socket.dns.getaddrinfo('www.kame.net')

for _, v in ipairs(ip_tbl) do
  io.write(string.format('%s: %s\n', v.family, v.addr))
end


/* dns in neko */
var host_resolve = $loader.loadprim("[email protected]_resolve", 1);
var host_to_string = $loader.loadprim("[email protected]_to_string", 1);
var host_reverse = $loader.loadprim("[email protected]_reverse", 1);

var ip = host_resolve("www.kame.net");

$print("www.kame.net: ", ip, ", ", host_to_string(ip), "\n");
$print(host_to_string(ip), ": ", host_reverse(ip), "\n");


USING: concurrency.distributed concurrency.messaging threads io.sockets io.servers ;
QUALIFIED: concurrency.messaging
: prettyprint-message ( -- ) concurrency.messaging:receive . flush prettyprint-message ;
[ prettyprint-message ] "logger" spawn dup name>> register-remote-thread
"127.0.0.1" 9000 <inet4> <node-server> start-server


package main

import (
    "errors"
    "log"
    "net"
    "net/http"
    "net/rpc"
)

type TaxComputer float64

func (taxRate TaxComputer) Tax(x float64, r *float64) error {
    if x < 0 {
        return errors.New("Negative values not allowed")
    }
    *r = x * float64(taxRate)
    return nil
}

func main() {
    c := TaxComputer(.05)
    rpc.Register(c)
    rpc.HandleHTTP()
    listener, err := net.Listen("tcp", ":1234")
    if err != nil {
        log.Fatal(err)
    }
    http.Serve(listener, nil)
}


var net = require('net')

var server = net.createServer(function (c){
  c.write('hello\r\n')
  c.pipe(c) // echo messages back
})

server.listen(3000, 'localhost')


// draw a clock hand, then copy it to an image
gfx.clear color.clear
gfx.fillPoly [[60,5], [64,10], [128,5], [64,0]], color.yellow
handImg = gfx.getImage(0,0, 128,10)

clear  // clear all displays

// prepare the face sprite
faceImg = file.loadImage("/sys/pics/shapes/CircleThinInv.png")
face = new Sprite
face.image = faceImg
face.scale = 2
face.x = 480; face.y = 320
display(4).sprites.push face

// prepare the hand sprite (from previously created image)
hand = new Sprite
hand.image = handImg
hand.x = face.x; hand.y = face.y
display(4).sprites.push hand

// main loop
while true
	hand.rotation = 90 - floor(time) % 60 * 6
	wait
end while


function dotProduct(v1:Vector.<Number>, v2:Vector.<Number>):Number
{
	if(v1.length != v2.length) return NaN;
	var sum:Number = 0;
	for(var i:uint = 0; i < v1.length; i++)
		sum += v1[i]*v2[i];
	return sum;
}
trace(dotProduct(Vector.<Number>([1,3,-5]),Vector.<Number>([4,-2,-1])));


with Ada.Text_IO; use Ada.Text_IO;
procedure dot_product is
	type vect is array(Positive range <>) of Integer;
	v1 : vect := (1,3,-5);
	v2 : vect := (4,-2,-1);

	function dotprod(a: vect; b: vect) return Integer is
		sum : Integer := 0;
		begin
		if not (a'Length=b'Length) then raise Constraint_Error; end if;
		for p in a'Range loop
			sum := sum + a(p)*b(p);
		end loop;
		return sum;
	end dotprod;

begin
put_line(Integer'Image(dotprod(v1,v2)));
end dot_product;


USING: accessors colors colors.hsv fry kernel locals math
math.constants math.functions opengl.gl typed ui ui.gadgets
ui.gadgets.canvas ui.render ;

IN: dragon

CONSTANT: depth 12

TUPLE: turtle
    { angle fixnum }
    { color float }
    { x float }
    { y float } ;

TYPED: nxt-color ( turtle: turtle -- turtle )
    [ [ 360 2 depth ^ /f + ] keep
      1.0 1.0 1.0 <hsva> >rgba-components glColor4d
    ] change-color ; inline

TYPED: draw-fwd ( x1: float y1: float x2: float y2: float -- )
    GL_LINES glBegin glVertex2d glVertex2d glEnd ; inline

TYPED:: fwd ( turtle: turtle l: float -- )
    turtle x>>
    turtle y>>
    turtle angle>> pi * 180 / :> ( x y angle )
    l angle [ cos * x + ] [ sin * y + ] 2bi :> ( dx dy )
    turtle x y dx dy [ draw-fwd ] 2keep [ >>x ] [ >>y ] bi* drop ; inline

TYPED: trn ( turtle: turtle d: fixnum -- turtle )
    '[ _ + ] change-angle ; inline

TYPED:: dragon' ( turtle: turtle l: float s: fixnum d: fixnum -- )
    s zero? [
        turtle nxt-color l fwd ! don't like this drop
    ] [
        turtle d  45 * trn l 2 sqrt / s 1 -  1 dragon'
        turtle d -90 * trn l 2 sqrt / s 1 - -1 dragon'
        turtle d  45 * trn drop
    ] if ;

: dragon ( -- )
    0 0 150 180 turtle boa 400 depth 1 dragon' ;

TUPLE: dragon-canvas < canvas ;

M: dragon-canvas draw-gadget* [ drop dragon ] draw-canvas ;
M: dragon-canvas pref-dim* drop { 640 480 } ;

MAIN-WINDOW: dragon-window { { title "Dragon Curve" } }
    dragon-canvas new-canvas >>gadgets ;

MAIN: dragon-window


include turtle.fs

2 value dragon-step

: dragon ( depth dir -- )
  over 0= if dragon-step fd  2drop exit then
  dup rt
  over 1-  45 recurse
  dup 2* lt
  over 1- -45 recurse
  rt drop ;

home clear
10 45 dragon


def diversitytheorem($actual; $predicted):
  def mean: add/length;

  ($predicted | mean) as $mean
  | { avgerr: ($predicted | map(. - $actual) | map(pow(.; 2)) | mean),
      crderr: pow($mean - $actual; 2),
      divers: ($predicted | map(. - $mean) | map(pow(.;2)) | mean) } ;


import Statistics: mean

function diversitytheorem(truth::T, pred::Vector{T}) where T<:Number
    μ = mean(pred)
    avgerr = mean((pred .- truth) .^ 2)
    crderr = (μ - truth) ^ 2
    divers = mean((pred .- μ) .^ 2)
    avgerr, crderr, divers
end

for (t, s) in [(49, [48, 47, 51]),
               (49, [48, 47, 51, 42])]
    avgerr, crderr, divers = diversitytheorem(t, s)
    println("""
    average-error : $avgerr
    crowd-error   : $crderr
    diversity     : $divers
    """)
end


// version 1.1.4-3

fun square(d: Double) = d * d

fun averageSquareDiff(d: Double, predictions: DoubleArray) =
    predictions.map { square(it - d) }.average()

fun diversityTheorem(truth: Double, predictions: DoubleArray): String {
    val average = predictions.average()
    val f = "%6.3f"
    return "average-error : ${f.format(averageSquareDiff(truth, predictions))}\n" +
           "crowd-error   : ${f.format(square(truth - average))}\n" +
           "diversity     : ${f.format(averageSquareDiff(average, predictions))}\n"
}

fun main(args: Array<String>) {
    println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0)))
    println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0, 42.0)))
}