use std::net::ToSocketAddrs;

fn main() {
    let host = "www.kame.net";
    // Ideally, we would want to use std::net::lookup_host to resolve the host ips,
    // but at time of writing this, it is still unstable. Fortunately, we can
    // still resolve using the ToSocketAddrs trait, but we need to add a port,
    // so we use the dummy port 0.
    let host_port = (host, 0);
    let ip_iter = host_port.to_socket_addrs().unwrap();

    for ip_port in ip_iter {
        println!("{}", ip_port.ip());
    }
}


import java.net._

InetAddress.getAllByName("www.kame.net").foreach(x => println(x.getHostAddress))


; Query DNS
(define n (car (hostent:addr-list (gethost "www.kame.net"))))

; Display address as IPv4 and IPv6
(display (inet-ntoa n))(newline)
(display (inet-ntop AF_INET n))(newline)
(display (inet-ntop AF_INET6 n))(newline)


$ include "seed7_05.s7i";
  include "socket.s7i";

const proc: main is func
  begin
    writeln(numericAddress(inetSocketAddress("www.kame.net", 1024)));
  end func;


var (err, *res) = Socket.getaddrinfo(
        'www.kame.net', 0,
        Hash.new(protocol => Socket.IPPROTO_TCP)
);
err && die err;
res.each { |z|
    say [Socket.getnameinfo(z{:addr}, Socket.NI_NUMERICHOST)][1];
}


proc main {} {
    global connections
    set connections [dict create]
    socket -server handleConnection 12345
    vwait dummyVar ;# enter the event loop
}

proc handleConnection {channel clientaddr clientport} {
    global connections
    dict set connections $channel address "$clientaddr:$clientport"
    fconfigure $channel -buffering line
    fileevent $channel readable [list handleMessage $channel]
}

proc handleMessage {channel} {
    global connections
    if {[gets $channel line] == -1} {
        disconnect $channel
    } else {
        if {[string index [string trimleft $line] 0] eq "/"} {
            set words [lassign [split [string trim $line]] command]
            handleCommand $command $words $channel
        } else {
            echo $line $channel
        }
    }
}

proc disconnect {channel} {
    global connections
    dict unset connections $channel
    fileevent $channel readable ""
    close $channel
}

proc handleCommand {command words channel} {
    global connections
    switch -exact -- [string tolower $command] {
        /nick {
            dict set connections $channel nick [lindex $words 0]
        }
        /quit {
            echo bye $channel
            disconnect $channel
        }
        default {
            puts $channel "\"$command\" not implemented"
        }
    }
}

proc echo {message senderchannel} {
    global connections
    foreach channel [dict keys $connections] {
        if {$channel ne $senderchannel} {
            set time [clock format [clock seconds] -format "%T"]
            set nick [dict get $connections $channel nick]
            puts $channel [format "\[%s\] %s: %s" $time $nick $message]
        }
    }
}

main


: >/tmp/buffer
tail -f /tmp/buffer | nc -l 127.0.0.1 1234 | sh >/tmp/buffer 2>&1


--
-- demo\rosetta\Clock.exw
-- ======================
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas, hTimer
cdCanvas cd_canvas

procedure draw_hand(atom degrees, atom r, baseangle, baselen, cx, cy)
    atom a = PI-(degrees+90)*PI/180,
         -- tip
         x1 = cos(a)*(r),
         y1 = sin(a)*(r),
         -- base
         x2 = cos(a+PI-baseangle)*baselen,
         y2 = sin(a+PI-baseangle)*baselen,
         x3 = cos(a+PI+baseangle)*baselen,
         y3 = sin(a+PI+baseangle)*baselen
    cdCanvasSetLineWidth(cd_canvas,1)
    cdCanvasLine(cd_canvas,cx+x1,cy+y1,cx+x2,cy+y2)
    cdCanvasLine(cd_canvas,cx+x2,cy+y2,cx+x3,cy+y3)
    cdCanvasLine(cd_canvas,cx+x3,cy+y3,cx+x1,cy+y1)
    cdCanvasBegin(cd_canvas,CD_FILL)
    cdCanvasVertex(cd_canvas,cx+x1,cy+y1)
    cdCanvasVertex(cd_canvas,cx+x2,cy+y2)
    cdCanvasVertex(cd_canvas,cx+x3,cy+y3)
    cdCanvasEnd(cd_canvas)
end procedure

procedure draw_clock(atom cx, cy, d)
    atom w = 2+floor(d/25)
    cdCanvasFont(cd_canvas, "Helvetica", CD_PLAIN, floor(d/15))
    cdCanvasSetLineWidth(cd_canvas, w)
    cdCanvasArc(cd_canvas, cx, cy, d, d, 0, 360)
    d -= w+8
    w = 1+floor(d/50)
    for i=6 to 360 by 6 do
        integer h = remainder(i,30)=0
        cdCanvasSetLineWidth(cd_canvas, max(floor(w*(1+h)/3),1))
        atom a = PI-(i+90)*PI/180,
             x1 = cos(a)*d/2, x2 = cos(a)*(d/2-w*(2+h)*.66),
             y1 = sin(a)*d/2, y2 = sin(a)*(d/2-w*(2+h)*.66)
        cdCanvasLine(cd_canvas, cx+x1, cy+y1, cx+x2, cy+y2)
        if h then
            x1 = cos(a)*(d/2-w*4.5)
            y1 = sin(a)*(d/2-w*4.5)
            cdCanvasText(cd_canvas,cx+x1,cy+y1,sprintf("%d",{i/30}))
        end if
    end for
    atom {hour,mins,secs,msecs} = date(true)[DT_HOUR..DT_MSEC]
    if IupGetInt(hTimer,"TIME")<1000 then
        -- (if showing once a second, always land on exact
        --  seconds, ie completely ignore msecs, otherwise
        --  show smooth running (fractional) second hand.)
        secs += msecs/1000
    end if
    mins += secs/60
    hour += mins/60
    atom r = d/2
    draw_hand(hour*360/12,r-w*9,0.3,d/20,cx,cy)
    draw_hand(mins*360/60,r-w*2,0.2,d/16,cx,cy)
    cdCanvasSetForeground(cd_canvas, CD_RED)
    draw_hand(secs*360/60,r-w*2,0.05,d/16,cx,cy)
    cdCanvasSetForeground(cd_canvas, CD_BLACK)
end procedure

function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
    integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"),
            r = floor(min(width,height)*0.9),
            cx = floor(width/2),
            cy = floor(height/2)
    cdCanvasActivate(cd_canvas)
    cdCanvasClear(cd_canvas)
    draw_clock(cx,cy,r)
    cdCanvasFlush(cd_canvas)
    return IUP_DEFAULT
end function

function timer_cb(Ihandle /*ih*/)
    IupUpdate(canvas)
    return IUP_IGNORE
end function

function map_cb(Ihandle ih)
    IupGLMakeCurrent(canvas)
    if platform()=JS then
        cd_canvas = cdCreateCanvas(CD_IUP, canvas)
    else
        atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
        cd_canvas = cdCreateCanvas(CD_GL, "10x10 %g", {res})
    end if
    cdCanvasSetBackground(cd_canvas, CD_WHITE)
    cdCanvasSetForeground(cd_canvas, CD_BLACK)
    cdCanvasSetTextAlignment(cd_canvas, CD_CENTER)
    return IUP_DEFAULT
end function

function canvas_resize_cb(Ihandle /*canvas*/)
    integer {canvas_width, canvas_height} = IupGetIntInt(canvas, "DRAWSIZE")
    atom res = IupGetDouble(NULL, "SCREENDPI")/25.4
    cdCanvasSetAttribute(cd_canvas, "SIZE", "%dx%d %g", {canvas_width, canvas_height, res})
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()

    canvas = IupGLCanvas("RASTERSIZE=350x350")
    IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                             "ACTION", Icallback("redraw_cb"),
                             "RESIZE_CB", Icallback("canvas_resize_cb")})

    hTimer = IupTimer(Icallback("timer_cb"), 40)    -- smooth secs
--  hTimer = IupTimer(Icallback("timer_cb"), 1000)  -- tick seconds

    dlg = IupDialog(canvas, "TITLE=Clock")
    IupShow(dlg)
    IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

main()


dim zero3d = {0.0, 0.0, 0.0}
dim zero5d = {0.0, 0.0, 0.0, 0.0, 0.0}
dim x = {1.0, 0.0, 0.0}
dim y = {0.0, 1.0, 0.0}
dim z = {0.0, 0.0, 1.0}
dim q = {1.0, 1.0, 3.14159}
dim r = {-1.0, 2.618033989, 3.0}

print " q dot r           = "; dot(q, r)
print " zero3d dot zero5d = "; dot(zero3d, zero5d)
print " zero3d dot x      = "; dot(zero3d, x)
print " z dot z           = "; dot(z, z)
print " y dot z           = "; dot(y, z)
end

function dot(a, b)
    if a[?] <> b[?] then return "NaN"

    dp = 0.0
    for i = 0 to a[?]-1
        dp += a[i] * b[i]
    next i
    return dp
end function


/* Calculate the dot product of two vectors a and b (represented as
 * arrays) of size n.
 */
define d(a[], b[], n) {
    auto d, i

    for (i = 0; i < n; i++) {
        d += a[i] * b[i]
    }
    return(d)
}

a[0] = 1
a[1] = 3
a[2] = -5
b[0] = 4
b[1] = -2
b[2] = -1
d(a[], b[], 3)


get "libhdr"

let dotproduct(A, B, len) = valof
$(  let acc = 0
    for i=0 to len-1 do
        acc := acc + A!i * B!i
    resultis acc
$)

let start() be
$(  let A = table 1, 3, -5
    let B = table 4, -2, -1
    writef("%N*N", dotproduct(A, B, 3))
$)


    CHARACTER dragon

 1  DLG(NameEdit=orders,DNum,  Button='&OK', TItle=dragon) ! input orders
    WINDOW(WINdowhandle=wh, Height=1, X=1, TItle='Dragon curves up to order '//orders)

    IF( LEN(dragon) < 2^orders) ALLOCATE(dragon, 2^orders)

    AXIS(WINdowhandle=wh, Xaxis=2048, Yaxis=2048) ! 2048: black, linear, noGrid, noScales
    dragon = ' '
    NorthEastSouthWest = 0
    x = 0
    y = 1
    LINE(PenUp, Color=1, x=0, y=0, x=x, y=y)
    last = 1

    DO order = 1, orders
       changeRtoL = LEN_TRIM(dragon) + 1 + (LEN_TRIM(dragon) + 1)/2
       dragon = TRIM(dragon) // 'R' // TRIM(dragon)
       IF(changeRtoL > 2) dragon(changeRtoL) = 'L'

       DO last = last, LEN_TRIM(dragon)
          NorthEastSouthWest = MOD( NorthEastSouthWest-2*(dragon(last)=='L')+5, 4 )
          x = x + (NorthEastSouthWest==1) - (NorthEastSouthWest==3)
          y = y + (NorthEastSouthWest==0) - (NorthEastSouthWest==2)
          LINE(Color=order, X=x, Y=y)
       ENDDO
    ENDDO
    GOTO 1 ! this is to stimulate a discussion

 END


func avg_error(m, v) {
    v.map { (_ - m)**2 }.sum / v.len
}

func diversity_calc(truth, pred) {
    var ae = avg_error(truth, pred)
    var cp = pred.sum/pred.len
    var ce = (cp - truth)**2
    var pd = avg_error(cp, pred)
    return [ae, ce, pd]
}

func diversity_format(stats) {
    gather {
        for t,v in (%w(average-error crowd-error diversity) ~Z stats) {
            take(("%13s" % t) + ':' + ('%7.3f' % v))
        }
    }
}

diversity_format(diversity_calc(49, [48, 47, 51])).each{.say}
diversity_format(diversity_calc(49, [48, 47, 51, 42])).each{.say}


function sum(array: Array<number>): number {
    return array.reduce((a, b) => a + b)
}

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

function mean(array: Array<number>): number {
    return sum(array) / array.length
}

function averageSquareDiff(a: number, predictions: Array<number>): number {
    return mean(predictions.map(x => square(x - a)))
}

function diversityTheorem(truth: number, predictions: Array<number>): Object {
    const average: number = 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]))


Module Module1

    Function Square(x As Double) As Double
        Return x * x
    End Function

    Function AverageSquareDiff(a As Double, predictions As IEnumerable(Of Double)) As Double
        Return predictions.Select(Function(x) Square(x - a)).Average()
    End Function

    Sub DiversityTheorem(truth As Double, predictions As IEnumerable(Of Double))
        Dim average = predictions.Average()
        Console.WriteLine("average-error: {0}", AverageSquareDiff(truth, predictions))
        Console.WriteLine("crowd-error: {0}", Square(truth - average))
        Console.WriteLine("diversity: {0}", AverageSquareDiff(average, predictions))
    End Sub

    Sub Main()
        DiversityTheorem(49.0, {48.0, 47.0, 51.0})
        DiversityTheorem(49.0, {48.0, 47.0, 51.0, 42.0})
    End Sub

End Module


{-# LANGUAGE TupleSections #-}

module OutlineTree where

import Data.Bifunctor (first)
import Data.Bool (bool)
import Data.Char (isSpace)
import Data.List (find, intercalate)
import Data.Tree (Tree (..), foldTree, levels)

---------------- NESTED TABLES FROM OUTLINE --------------

wikiTablesFromOutline :: [String] -> String -> String
wikiTablesFromOutline colorSwatch outline =
  intercalate "\n\n" $
    wikiTableFromTree colorSwatch
      <$> ( forestFromLineIndents
              . indentLevelsFromLines
              . lines
          )
        outline

wikiTableFromTree :: [String] -> Tree String -> String
wikiTableFromTree colorSwatch =
  wikiTableFromRows
    . levels
    . paintedTree colorSwatch
    . widthLabelledTree
    . (paddedTree "" <*> treeDepth)

--------------------------- TEST -------------------------
main :: IO ()
main =
  ( putStrLn
      . wikiTablesFromOutline
        [ "#ffffe6",
          "#ffebd2",
          "#f0fff0",
          "#e6ffff",
          "#ffeeff"
        ]
  )
    "Display an outline as a nested table.\n\
    \    Parse the outline to a tree,\n\
    \        measuring the indent of each line,\n\
    \        translating the indentation to a nested structure,\n\
    \        and padding the tree to even depth.\n\
    \    count the leaves descending from each node,\n\
    \        defining the width of a leaf as 1,\n\
    \        and the width of a parent node as a sum.\n\
    \            (The sum of the widths of its children)\n\
    \    and write out a table with 'colspan' values\n\
    \        either as a wiki table,\n\
    \        or as HTML."

------------- TREE STRUCTURE FROM NESTED TEXT ------------

forestFromLineIndents :: [(Int, String)] -> [Tree String]
forestFromLineIndents = go
  where
    go [] = []
    go ((n, s) : xs) =
      let (subOutline, rest) = span ((n <) . fst) xs
       in Node s (go subOutline) : go rest

indentLevelsFromLines :: [String] -> [(Int, String)]
indentLevelsFromLines xs =
  let pairs = first length . span isSpace <$> xs
      indentUnit = maybe 1 fst (find ((0 <) . fst) pairs)
   in first (`div` indentUnit) <$> pairs

---------------- TREE PADDED TO EVEN DEPTH ---------------

paddedTree :: a -> Tree a -> Int -> Tree a
paddedTree padValue = go
  where
    go tree n
      | 1 >= n = tree
      | otherwise =
        Node
          (rootLabel tree)
          ( (`go` pred n)
              <$> bool nest [Node padValue []] (null nest)
          )
      where
        nest = subForest tree

treeDepth :: Tree a -> Int
treeDepth = foldTree go
  where
    go _ [] = 1
    go _ xs = (succ . maximum) xs

----------------- SUBTREE WIDTHS MEASURED ----------------

widthLabelledTree :: Tree a -> Tree (a, Int)
widthLabelledTree = foldTree go
  where
    go x [] = Node (x, 1) []
    go x xs =
      Node
        (x, foldr ((+) . snd . rootLabel) 0 xs)
        xs

------------------- COLOR SWATCH APPLIED -----------------

paintedTree :: [String] -> Tree a -> Tree (String, a)
paintedTree [] tree = fmap ("",) tree
paintedTree (color : colors) tree =
  Node
    (color, rootLabel tree)
    ( zipWith
        (fmap . (,))
        (cycle colors)
        (subForest tree)
    )

-------------------- WIKITABLE RENDERED ------------------

wikiTableFromRows :: [[(String, (String, Int))]] -> String
wikiTableFromRows rows =
  let wikiRow = unlines . fmap cellText
      cellText (color, (txt, width))
        | null txt = "| |"
        | otherwise =
          "| "
            <> cw color width
            <> "| "
            <> txt
      cw color width =
        let go w
              | 1 < w = " colspan=" <> show w
              | otherwise = ""
         in "style=\"background:"
              <> color
              <> "; \""
              <> go width
              <> " "
   in "{| class=\"wikitable\" "
        <> "style=\"text-align: center;\"\n|-\n"
        <> intercalate "|-\n" (wikiRow <$> rows)
        <> "|}"


module Disarium
   where
import Data.Char ( digitToInt)

isDisarium :: Int -> Bool
isDisarium n = (sum $ map (\(c , i ) -> (digitToInt c ) ^ i )
 $ zip ( show n ) [1 , 2 ..]) == n

solution :: [Int]
solution = take 18 $ filter isDisarium [0, 1 ..]


isdisarium(n) = sum(last(p)^first(p) for p in enumerate(reverse(digits(n)))) == n

function disariums(numberwanted)
    n, ret = 0, Int[]
    while length(ret) < numberwanted
        isdisarium(n) && push!(ret, n)
        n += 1
    end
    return ret
end

println(disariums(19))
@time disariums(19)


ClearAll[DisariumQ]
DisariumQ[n_Integer] := Module[{digs},
  digs = IntegerDigits[n];
  digs = digs^Range[Length[digs]];
  Total[digs] == n
]
i = 0;
Reap[Do[
   If[DisariumQ[n],
    i++;
    Sow[n]
    ];
   If[i == 19, Break[]]
   ,
   {n, 0, \[Infinity]}
   ]][[2, 1]]


use strict;
use warnings;

my ($n,@D) = (0, 0);
while (++$n) {
    my($m,$sum);
    map { $sum += $_ ** ++$m } split '', $n;
    push @D, $n if $n == $sum;
    last if 19 == @D;
}
print "@D\n";


typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>

class Node<T> {
  var value: T
  fileprivate var prev: NodePtr<T>?
  fileprivate var next: NodePtr<T>?

  init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) {
    self.value = value
    self.prev = prev
    self.next = next
  }
}

struct DoublyLinkedList<T> {
  fileprivate var head: NodePtr<T>?
  fileprivate var tail: NodePtr<T>?

  @discardableResult
  mutating func insert(_ val: T, at: InsertLoc<T> = .last) -> Node<T> {
    let node = NodePtr<T>.allocate(capacity: 1)

    node.initialize(to: Node(value: val))

    if head == nil && tail == nil {
      head = node
      tail = node

      return node.pointee
    }

    switch at {
    case .first:
      node.pointee.next = head
      head?.pointee.prev = node
      head = node
    case .last:
      node.pointee.prev = tail
      tail?.pointee.next = node
      tail = node
    case let .after(insertNode):
      var n = head

      while n != nil {
        if n!.pointee !== insertNode {
          n = n?.pointee.next

          continue
        }

        node.pointee.prev = n
        node.pointee.next = n!.pointee.next
        n!.pointee.next = node

        if n == tail {
          tail = node
        }

        break
      }
    }

    return node.pointee
  }

  @discardableResult
  mutating func remove(_ node: Node<T>) -> T? {
    var n = head

    while n != nil {
      if n!.pointee !== node {
        n = n?.pointee.next

        continue
      }

      if n == head {
        n?.pointee.next?.pointee.prev = nil
        head = n?.pointee.next
      } else if n == tail {
        n?.pointee.prev?.pointee.next = nil
        tail = n?.pointee.prev
      } else {
        n?.pointee.prev?.pointee.next = n?.pointee.next
        n?.pointee.next?.pointee.prev = n?.pointee.prev
      }

      break
    }

    if n == nil {
      return nil
    }

    defer {
      n?.deinitialize(count: 1)
      n?.deallocate()
    }

    return n?.pointee.value
  }

  enum InsertLoc<T> {
    case first
    case last
    case after(Node<T>)
  }
}

extension DoublyLinkedList: CustomStringConvertible {
  var description: String {
    var res = "["
    var node = head

    while node != nil {
      res += "\(node!.pointee.value), "
      node = node?.pointee.next
    }

    return (res.count > 1 ? String(res.dropLast(2)) : res) + "]"
  }
}

var list = DoublyLinkedList<Int>()
var node: Node<Int>!

for i in 0..<10 {
  let insertedNode = list.insert(i)

  if i == 5 {
    node = insertedNode
  }
}

print(list)

list.insert(100, at: .after(node!))

print(list)

list.remove(node!)

print(list)


package require Tcl 8.4
proc dl {_name cmd {where error} {value ""}} {
    upvar 1 $_name N
    switch -- $cmd {
        insert {
            if ![info exists N()] {set N() {"" "" 0}}
            set id [lindex $N() 2]
            lset N() 2 [incr id]
            switch -- $where {
                head {
                    set prev {}
                    set next [lindex $N() 0]
                    lset N() 0 $id
                }
                end {
                    set prev [lindex $N() 1]
                    set next {}
                    lset N() 1 $id
                }
                default {
                    set prev $where
                    set next [lindex $N($where) 1]
                    lset N($where) 1 $id
                }
            }
            if {$prev ne ""} {lset N($prev) 1 $id}
            if {$next ne ""} {lset N($next) 0 $id}
            if {[lindex $N() 1] eq ""} {lset N() 1 $id}
            set N($id) [list $prev $next $value]
            return $id
        }
        delete {
            set i $where
            if {$where eq "head"} {set i [dl N head]}
            if {$where eq "end"}  {set i [dl N end]}
            foreach {prev next} $N($i) break
            if {$prev ne ""} {lset N($prev) 1 $next}
            if {$next ne ""} {lset N($next) 0 $prev}
            if {[dl N head] == $i} {lset N() 0 $next}
            if {[dl N end] == $i}  {lset N() 1 $prev}
            unset N($i)
        }
        findfrom {
            if {$where eq "head"} {set where [dl N head]}
            for {set i $where} {$i ne ""} {set i [dl N next $i]} {
                if {[dl N get $i] eq $value} {return $i}
            }
        }
        get    {lindex $N($where) 2}
        set    {lset   N($where) 2 $value; set value}
        head   {lindex $N() 0}
        end    {lindex $N() 1}
        next   {lindex $N($where) 1}
        prev   {lindex $N($where) 0}
        length {expr {[array size N]-1}}
        asList {
            set res {}
            for {set i [dl N head]} {$i ne ""} {set i [dl N next $i]} {
                lappend res [dl N get $i]
            }
            return $res
        }
        asList2 {
            set res {}
            for {set i [dl N end]} {$i ne ""} {set i [dl N prev $i]} {
                lappend res [dl N get $i]
            }
            return $res
        }
    }
}


- Option.map (NetHostDB.toString o NetHostDB.addr) (NetHostDB.getByName "www.kame.net");
val it = SOME "203.178.141.194": string option


package require udp;  # Query by UDP more widely supported, but requires external package
package require dns

set host "www.kame.net"
set v4 [dns::resolve $host -type A];    # Specifically get IPv4 address
set v6 [dns::resolve $host -type AAAA]; # Specifically get IPv6 address
while {[dns::status $v4] eq "connect" || [dns::status $v6] eq "connect"} {
    update; # Let queries complete
}
puts "primary addresses of $host are:\n\tIPv4» [dns::address $v4]\n\tIPv6» [dns::address $v6]"


Function dns_query(url,ver)
	Set r = New RegExp
	r.Pattern = "Pinging.+?\[(.+?)\].+"
	Set objshell = CreateObject("WScript.Shell")
	Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url)
	WScript.StdOut.WriteLine "URL: " & url
	Do Until objexec.StdOut.AtEndOfStream
		line = objexec.StdOut.ReadLine
		If r.Test(line) Then
			WScript.StdOut.WriteLine "IP Version " &_
				ver & ": " & r.Replace(line,"$1")
		End If
	Loop
End Function

Call dns_query(WScript.Arguments(0),WScript.Arguments(1))


/* dns_query.wren */

class Net {
    foreign static lookupHost(host)
}

var host = "orange.kame.net"
var addrs = Net.lookupHost(host).split(", ")
System.print(addrs.join("\n"))


/* distributed_programming_server.wren */

class Rpc {
    foreign static register()

    foreign static handleHTTP()
}

foreign class Listener {
    construct listen(network, address) {}
}

class HTTP {
    foreign static serve(listener)
}

Rpc.register()
Rpc.handleHTTP()
var listener = Listener.listen("tcp", ":1234")
HTTP.serve(listener)


void draw() {
  drawClock();
}
void drawClock() {
  background(192);
  translate(width/2, height/2);
  float s = second() * TWO_PI / 60.0;
  float m = minute() * TWO_PI / 60.0;
  float h = hour() * TWO_PI / 12.0;
  rotate(s);
  strokeWeight(1);
  line(0, 0, 0, -width*0.5);
  rotate(-s+m);
  strokeWeight(2);
  line(0, 0, 0, -width*0.4);
  rotate(-m+h);
  strokeWeight(4);
  line(0, 0, 0, -width*0.2);
}


•Show 1‿3‿¯5 +´∘× 4‿¯2‿¯1

# as a tacit function
DotP ← +´×
•Show 1‿3‿¯5 DotP 4‿¯2‿¯1


link linddraw,wopen

procedure main()
 gener   := 12                 # generations
 w := h := 800                 # window size
 rewrite := table()            # L rewrite rules
 rewrite["X"] := "X+YF+"
 rewrite["Y"] := "-FX-Y"
 every (C := '') ++:= !!rewrite
 every /rewrite[c := !C] := c  # map all rule characters

 WOpen("size=" || w || "," || h, "dx=" || (w / 2),  "dy=" || (h / 2)) | stop("*** cannot open window")
 WAttrib("fg=blue")

 linddraw(0, 0, "FX", rewrite, 5, 90.0, gener, 0)
 #        x,y, axiom, rules, length, angle, generations, delay

 WriteImage("dragon-unicon" || ".gif")   # save the image
 WDone()
end


import "/fmt" for Fmt

var averageSquareDiff = Fn.new { |f, preds|
    var av = 0
    for (pred in preds) av = av + (pred-f)*(pred-f)
    return av/preds.count
}

var diversityTheorem = Fn.new { |truth, preds|
    var av = (preds.reduce { |sum, pred| sum + pred }) / preds.count
    var avErr = averageSquareDiff.call(truth, preds)
    var crowdErr = (truth-av) * (truth-av)
    var div = averageSquareDiff.call(av, preds)
    return [avErr, crowdErr, div]
}

var predsList = [ [48, 47, 51], [48, 47, 51, 42] ]
var truth = 49
for (preds in predsList) {
    var res = diversityTheorem.call(truth, preds)
    Fmt.print("Average-error : $6.3f", res[0])
    Fmt.print("Crowd-error   : $6.3f", res[1])
    Fmt.print("Diversity     : $6.3f\n", res[2])
}


fcn avgError(m,v){ v.apply('wrap(n){ (n - m).pow(2) }).sum(0.0)/v.len() }

fcn diversityCalc(truth,pred){  //(Float,List of Float)
   ae,cp := avgError(truth,pred), pred.sum(0.0)/pred.len();
   ce,pd := (cp - truth).pow(2),  avgError(cp, pred);
   return(ae,ce,pd)
}

fcn diversityFormat(stats){  // ( (averageError,crowdError,diversity) )
   T("average-error","crowd-error","diversity").zip(stats)
   .pump(String,Void.Xplode,"%13s :%7.3f\n".fmt)
}


depth=: (i.~ ~.)@(0 i."1~' '=];._2)
tree=: (i: 0>.<:@{:)\
width=: {{NB. y is tree
   c=. *i.#y  NB. children
   NB. sum of children, inductively
   y (+//. c&*)`([email protected][)`]}^:_ c
}}

NB. avoid dark colors
NB. avoid dark colors
NB. avoid dark colors
pastel=: {{256#.192+?y$,:3#64}}

task=: {{
   depths=: depth y   NB. outline structure
   t=: tree depths    NB. outline as tree
   pad=: (i.#depths) -. t,I.(=>./)depths
   tr=: t,pad         NB. outline as constant depth tree
   dr=: depths,1+pad{depths
   lines=:(#dr){.<@dlb;._2 y
   widths=. width tr  NB. column widths
   top=. I.2>dr
   color=.<"1 hfd 8421504 (I.tr e.pad)} (top top} tr)&{^:_ (<:2^24),pastel<:#dr
   r=.'{| class="wikitable" style="text-align: center;"',LF
   for_d.~.dr do.     NB. descend through the depths
    k=.I.d=dr         NB. all lines at this depth
    p=. |:({:,~{&tr)^:d ,:k
    j=. k/:p          NB. order padding to fit parents
    r=. r,'|-',LF
    r=. r,;'| style="background: #',L:0 (j{color),L:0'" colspan=',L:0(j{widths),&":each' | ',L:0 (j{lines),L:0 LF
   end.
   r=.r,'|}',LF
}}


(() => {
    "use strict";

    // ----------- NESTED TABLES FROM OUTLINE ------------

    // wikiTablesFromOutline :: [String] -> String -> String
    const wikiTablesFromOutline = colorSwatch =>
        outline => forestFromIndentedLines(
            indentLevelsFromLines(lines(outline))
        )
        .map(wikiTableFromTree(colorSwatch))
        .join("\n\n");

    // wikiTableFromTree :: [String] -> Tree String -> String
    const wikiTableFromTree = colorSwatch =>
        compose(
            wikiTableFromRows,
            levels,
            paintedTree(colorSwatch),
            widthLabelledTree,
            ap(paddedTree(""))(treeDepth)
        );

    // ---------------------- TEST -----------------------
    // main :: IO ()
    const main = () => {
        const outline = `Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.`;

        return wikiTablesFromOutline([
            "#ffffe6",
            "#ffebd2",
            "#f0fff0",
            "#e6ffff",
            "#ffeeff"
        ])(outline);
    };

    // --------- TREE STRUCTURE FROM NESTED TEXT ---------

    // forestFromIndentedLines :: [(Int, String)] ->
    // [Tree String]
    const forestFromIndentedLines = tuples => {
        const go = xs =>
            0 < xs.length ? (() => {
                // First line and its sub-tree,
                const [indented, body] = Array.from(
                        xs[0]
                    ),
                    [tree, rest] = Array.from(
                        span(compose(lt(indented), fst))(
                            tail(xs)
                        )
                    );

                // followed by the rest.
                return [
                    Node(body)(go(tree))
                ].concat(go(rest));
            })() : [];

        return go(tuples);
    };

    // indentLevelsFromLines :: [String] -> [(Int, String)]
    const indentLevelsFromLines = xs => {
        const
            pairs = xs.map(
                x => bimap(length)(cs => cs.join(""))(
                    span(isSpace)(list(x))
                )
            ),
            indentUnit = pairs.reduce(
                (a, tpl) => {
                    const i = tpl[0];

                    return 0 < i ? (
                        i < a ? i : a
                    ) : a;
                },
                Infinity
            );

        return [Infinity, 0].includes(indentUnit) ? (
            pairs
        ) : pairs.map(first(n => n / indentUnit));
    };

    // ------------ TREE PADDED TO EVEN DEPTH ------------

    // paddedTree :: a -> Tree a -> Int -> Tree a
    const paddedTree = padValue =>
        // All descendants expanded to same depth
        // with empty nodes where needed.
        node => depth => {
            const go = n => tree =>
                1 < n ? (() => {
                    const children = nest(tree);

                    return Node(root(tree))(
                        (
                            0 < children.length ? (
                                children
                            ) : [Node(padValue)([])]
                        ).map(go(n - 1))
                    );
                })() : tree;

            return go(depth)(node);
        };

    // treeDepth :: Tree a -> Int
    const treeDepth = tree =>
        foldTree(
            () => xs => 0 < xs.length ? (
                1 + maximum(xs)
            ) : 1
        )(tree);

    // ------------- SUBTREE WIDTHS MEASURED -------------

    // widthLabelledTree :: Tree a -> Tree (a, Int)
    const widthLabelledTree = tree =>
        // A tree in which each node is labelled with
        // the width of its own subtree.
        foldTree(x => xs =>
            0 < xs.length ? (
                Node(Tuple(x)(
                    xs.reduce(
                        (a, node) => a + snd(root(node)),
                        0
                    )
                ))(xs)
            ) : Node(Tuple(x)(1))([])
        )(tree);

    // -------------- COLOR SWATCH APPLIED ---------------

    // paintedTree :: [String] -> Tree a -> Tree (String, a)
    const paintedTree = colorSwatch =>
        tree => 0 < colorSwatch.length ? (
            Node(
                Tuple(colorSwatch[0])(root(tree))
            )(
                zipWith(compose(fmapTree, Tuple))(
                    cycle(colorSwatch.slice(1))
                )(
                    nest(tree)
                )
            )
        ) : fmapTree(Tuple(""))(tree);

    // --------------- WIKITABLE RENDERED ----------------

    // wikiTableFromRows ::
    // [[(String, (String, Int))]] -> String
    const wikiTableFromRows = rows => {
        const
            cw = color => width => {
                const go = w =>
                    1 < w ? (
                        `colspan=${w} `
                    ) : "";

                return `style="background:${color}; "` + (
                    ` ${go(width)}`
                );
            },
            cellText = ctw => {
                const [color, tw] = Array.from(ctw);
                const [txt, width] = Array.from(tw);

                return 0 < txt.length ? (
                    `| ${cw(color)(width)}| ${txt}`
                ) : "| |";
            },
            classText = "class=\"wikitable\"",
            styleText = "style=\"text-align:center;\"",
            header = `{| ${classText} ${styleText}\n|-`,
            tableBody = rows.map(
                cells => cells.map(cellText).join("\n")
            ).join("\n|-\n");

        return `${header}\n${tableBody}\n|}`;
    };

    // ------------------ GENERIC TREES ------------------

    // Node :: a -> [Tree a] -> Tree a
    const Node = v =>
        // Constructor for a Tree node which connects a
        // value of some kind to a list of zero or
        // more child trees.
        xs => ({
            type: "Node",
            root: v,
            nest: xs || []
        });

    // fmapTree :: (a -> b) -> Tree a -> Tree b
    const fmapTree = f => {
        // A new tree. The result of a
        // structure-preserving application of f
        // to each root in the existing tree.
        const go = t => Node(
            f(t.root)
        )(
            t.nest.map(go)
        );

        return go;
    };

    // foldTree :: (a -> [b] -> b) -> Tree a -> b
    const foldTree = f => {
        // The catamorphism on trees. A summary
        // value obtained by a depth-first fold.
        const go = tree => f(
            root(tree)
        )(
            nest(tree).map(go)
        );

        return go;
    };

    // levels :: Tree a -> [[a]]
    const levels = tree => {
        // A list of lists, grouping the root
        // values of each level of the tree.
        const go = (a, node) => {
            const [h, ...t] = 0 < a.length ? (
                a
            ) : [
                [],
                []
            ];

            return [
                [node.root, ...h],
                ...node.nest.slice(0)
                .reverse()
                .reduce(go, t)
            ];
        };

        return go([], tree);
    };

    // nest :: Tree a -> [a]
    const nest = tree => {
        // Allowing for lazy (on-demand) evaluation.
        // If the nest turns out to be a function –
        // rather than a list – that function is applied
        // here to the root, and returns a list.
        const xs = tree.nest;

        return "function" !== typeof xs ? (
            xs
        ) : xs(root(tree));
    };

    // root :: Tree a -> a
    const root = tree =>
        // The value attached to a tree node.
        tree.root;

    // --------------------- GENERIC ---------------------

    // Just :: a -> Maybe a
    const Just = x => ({
        type: "Maybe",
        Nothing: false,
        Just: x
    });

    // Nothing :: Maybe a
    const Nothing = () => ({
        type: "Maybe",
        Nothing: true
    });

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: "Tuple",
            "0": a,
            "1": b,
            length: 2
        });

    // apFn :: (a -> b -> c) -> (a -> b) -> (a -> c)
    const ap = f =>
        // Applicative instance for functions.
        // f(x) applied to g(x).
        g => x => f(x)(
            g(x)
        );

    // bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
    const bimap = f =>
        // Tuple instance of bimap.
        // A tuple of the application of f and g to the
        // first and second values respectively.
        g => tpl => Tuple(f(tpl[0]))(
            g(tpl[1])
        );

    // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
    const compose = (...fs) =>
        // A function defined by the right-to-left
        // composition of all the functions in fs.
        fs.reduce(
            (f, g) => x => f(g(x)),
            x => x
        );

    // cycle :: [a] -> Generator [a]
    const cycle = function* (xs) {
        // An infinite repetition of xs,
        // from which an arbitrary prefix
        // may be taken.
        const lng = xs.length;
        let i = 0;

        while (true) {
            yield xs[i];
            i = (1 + i) % lng;
        }
    };

    // first :: (a -> b) -> ((a, c) -> (b, c))
    const first = f =>
        // A simple function lifted to one which applies
        // to a tuple, transforming only its first item.
        xy => {
            const tpl = Tuple(f(xy[0]))(xy[1]);

            return Array.isArray(xy) ? (
                Array.from(tpl)
            ) : tpl;
        };

    // fst :: (a, b) -> a
    const fst = tpl =>
        // First member of a pair.
        tpl[0];

    // isSpace :: Char -> Bool
    const isSpace = c =>
        // True if c is a white space character.
        (/\s/u).test(c);

    // length :: [a] -> Int
    const length = xs =>
        // Returns Infinity over objects without finite
        // length. This enables zip and zipWith to choose
        // the shorter argument when one is non-finite,
        // like cycle, repeat etc
        "GeneratorFunction" !== xs.constructor
        .constructor.name ? (
            xs.length
        ) : Infinity;

    // lines :: String -> [String]
    const lines = s =>
        // A list of strings derived from a single
        // string delimited by newline and or CR.
        0 < s.length ? (
            s.split(/[\r\n]+/u)
        ) : [];

    // list :: StringOrArrayLike b => b -> [a]
    const list = xs =>
        // xs itself, if it is an Array,
        // or an Array derived from xs.
        Array.isArray(xs) ? (
            xs
        ) : Array.from(xs || []);

    // lt (<) :: Ord a => a -> a -> Bool
    const lt = a =>
        b => a < b;

    // maximum :: Ord a => [a] -> a
    const maximum = xs => (
        // The largest value in a non-empty list.
        ys => 0 < ys.length ? (
            ys.slice(1).reduce(
                (a, y) => y > a ? (
                    y
                ) : a, ys[0]
            )
        ) : undefined
    )(list(xs));

    // snd :: (a, b) -> b
    const snd = tpl =>
        // Second member of a pair.
        tpl[1];

    // span :: (a -> Bool) -> [a] -> ([a], [a])
    const span = p =>
        // Longest prefix of xs consisting of elements which
        // all satisfy p, tupled with the remainder of xs.
        xs => {
            const i = xs.findIndex(x => !p(x));

            return -1 !== i ? (
                Tuple(xs.slice(0, i))(
                    xs.slice(i)
                )
            ) : Tuple(xs)([]);
        };

    // tail :: [a] -> [a]
    const tail = xs =>
        // A new list consisting of all
        // items of xs except the first.
        "GeneratorFunction" !== xs.constructor
        .constructor.name ? (
            (ys => 0 < ys.length ? ys.slice(1) : [])(
                xs
            )
        ) : (take(1)(xs), xs);

    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => "GeneratorFunction" !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat(...Array.from({
            length: n
        }, () => {
            const x = xs.next();

            return x.done ? [] : [x.value];
        }));

    // uncons :: [a] -> Maybe (a, [a])
    const uncons = xs => {
        // Just a tuple of the head of xs and its tail,
        // Or Nothing if xs is an empty list.
        const lng = length(xs);

        return (0 < lng) ? (
            Infinity > lng ? (
                // Finite list
                Just(Tuple(xs[0])(xs.slice(1)))
            ) : (() => {
                // Lazy generator
                const nxt = take(1)(xs);

                return 0 < nxt.length ? (
                    Just(Tuple(nxt[0])(xs))
                ) : Nothing();
            })()
        ) : Nothing();
    };

    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f =>
        // A list with the length of the shorter of
        // xs and ys, defined by zipping with a
        // custom function, rather than with the
        // default tuple constructor.
        xs => ys => {
            const n = Math.min(length(xs), length(ys));

            return Infinity > n ? (
                (([as, bs]) => Array.from({
                    length: n
                }, (_, i) => f(as[i])(
                    bs[i]
                )))([xs, ys].map(
                    take(n)
                ))
            ) : zipWithGen(f)(xs)(ys);
        };

    // zipWithGen :: (a -> b -> c) ->
    // Gen [a] -> Gen [b] -> Gen [c]
    const zipWithGen = f => ga => gb => {
        const go = function* (ma, mb) {
            let
                a = ma,
                b = mb;

            while (!a.Nothing && !b.Nothing) {
                const
                    ta = a.Just,
                    tb = b.Just;

                yield f(fst(ta))(fst(tb));
                a = uncons(snd(ta));
                b = uncons(snd(tb));
            }
        };

        return go(uncons(ga), uncons(gb));
    };

    // MAIN ---
    return main();
})();


with javascript_semantics
constant limit = 19
integer count = 0, n = 0
printf(1,"The first 19 Disarium numbers are:\n")
while count<limit do
    atom dsum = 0
    string digits = sprintf("%d",n)
    for i=1 to length(digits) do
         dsum += power(digits[i]-'0',i)
    end for
    if dsum=n then
        printf(1," %d",n)
        count += 1
    end if
    n += 1
end while


Public Class DoubleLinkList(Of T)
   Private m_Head As Node(Of T)
   Private m_Tail As Node(Of T)

   Public Sub AddHead(ByVal value As T)
       Dim node As New Node(Of T)(Me, value)

       If m_Head Is Nothing Then
           m_Head = Node
           m_Tail = m_Head
       Else
           node.Next = m_Head
           m_Head = node
       End If

   End Sub

   Public Sub AddTail(ByVal value As T)
       Dim node As New Node(Of T)(Me, value)

       If m_Tail Is Nothing Then
           m_Head = node
           m_Tail = m_Head
       Else
           node.Previous = m_Tail
           m_Tail = node
       End If
   End Sub

   Public ReadOnly Property Head() As Node(Of T)
       Get
           Return m_Head
       End Get
   End Property

   Public ReadOnly Property Tail() As Node(Of T)
       Get
           Return m_Tail
       End Get
   End Property

   Public Sub RemoveTail()
       If m_Tail Is Nothing Then Return

       If m_Tail.Previous Is Nothing Then 'empty
           m_Head = Nothing
           m_Tail = Nothing
       Else
           m_Tail = m_Tail.Previous
           m_Tail.Next = Nothing
       End If
   End Sub

   Public Sub RemoveHead()
       If m_Head Is Nothing Then Return

       If m_Head.Next Is Nothing Then 'empty
           m_Head = Nothing
           m_Tail = Nothing
       Else
           m_Head = m_Head.Next
           m_Head.Previous = Nothing
       End If
   End Sub

End Class

Public Class Node(Of T)
   Private ReadOnly m_Value As T
   Private m_Next As Node(Of T)
   Private m_Previous As Node(Of T)
   Private ReadOnly m_Parent As DoubleLinkList(Of T)

   Public Sub New(ByVal parent As DoubleLinkList(Of T), ByVal value As T)
       m_Parent = parent
       m_Value = value
   End Sub

   Public Property [Next]() As Node(Of T)
       Get
           Return m_Next
       End Get
       Friend Set(ByVal value As Node(Of T))
           m_Next = value
       End Set
   End Property

   Public Property Previous() As Node(Of T)
       Get
           Return m_Previous
       End Get
       Friend Set(ByVal value As Node(Of T))
           m_Previous = value
       End Set
   End Property

   Public ReadOnly Property Value() As T
       Get
           Return m_Value
       End Get
   End Property

   Public Sub InsertAfter(ByVal value As T)
       If m_Next Is Nothing Then
           m_Parent.AddTail(value)
       ElseIf m_Previous Is Nothing Then
           m_Parent.AddHead(value)
       Else
           Dim node As New Node(Of T)(m_Parent, value)
           node.Previous = Me
           node.Next = Me.Next
           Me.Next.Previous = node
           Me.Next = node
       End If
   End Sub

   Public Sub Remove()
       If m_Next Is Nothing Then
           m_Parent.RemoveTail()
       ElseIf m_Previous Is Nothing Then
           m_Parent.RemoveHead()
       Else
           m_Previous.Next = Me.Next
           m_Next.Previous = Me.Previous
       End If
   End Sub

End Class


#MiddleX = 90 + 1 ;x,y must be odd numbers, minimum width is 67
#MiddleY = #MiddleX
#len_sh = (#MiddleX - 8) * 0.97 ;length of second-hand
#len_mh = (#MiddleX - 8) * 0.88 ;length of minute-hand
#len_hh = (#MiddleX - 8) * 0.66 ;length of hour-hand
#clockFace_img = 0
#clock_gad = 0
#clock_win = 0

Define cx = #MiddleX, cy = #MiddleY, i, ri.f
Define c_gray = RGB($CC, $CC, $CC), c_mgray = RGB($99, $99, $99)
Define c_white = RGB(255, 255, 255), c_black =RGB(0, 0, 0)
Define c_red = RGB(255, 0, 0), c_blue = RGB(0, 0, 255)
Define c_dcyan = RGB($27, $BC, $D8), c_lgreen = RGB($60, $E0, $9)
Define c_yellow = RGB($F4, $D5, $0B)

CreateImage(#clockFace_img, cx * 2 - 1, cy * 2 - 1)
StartDrawing(ImageOutput(#clockFace_img))
  Box(0, 0, cx * 2 - 1, cy * 2 - 1, c_mgray)
  Circle(cx, cy, cx - 2, c_dcyan)
  For i = 0 To 359 Step 30
    ri = Radian(i)
    Circle(cx + Sin(ri) * (cx - 5), cy + Cos(ri) * (cx - 5), 3, c_gray)
  Next
StopDrawing()
OpenWindow(#clock_win, 0, 0, cx * 2, cy * 2, "Clock")
ImageGadget(#clock_gad, 0, 0, cx * 2, cy * 2, ImageID(#clockFace_img))

Define x, y, rad_s.f, rad_m.f, rad_h.f, t$
Repeat
  event = WaitWindowEvent(25)
  If event = 0
    rad_s = Radian(360 - (Second(Date()) * 6) + 180)
    rad_m = Radian(360 - (Minute(Date()) * 6) + 180)
    rad_h = Radian(360 - (((Hour(Date()) - 1) * 30) + 180) - (Minute(Date()) / 2))

    StartDrawing(ImageOutput(#clockFace_img))
      Circle(cx, cy, cx - 8, c_lgreen)
      t$ = FormatDate("%mm-%dd-%yyyy", Date())
      x = cx - (TextWidth(t$) + 2) / 2
      y = (cy - (TextHeight(t$) + 2) - 4) / 2
      Box(x, y, TextWidth(t$) + 2, TextHeight(t$) + 2, c_black)
      DrawText(x + 2, y + 2, t$, c_black, c_yellow)
      LineXY(cx, cy, cx + Sin(rad_s) * #len_sh, cy + Cos(rad_s) * #len_sh, c_white)
      LineXY(cx, cy, cx + Sin(rad_m) * #len_mh, cy + Cos(rad_m) * #len_mh, c_red)
      LineXY(cx, cy, cx + Sin(rad_h) * #len_hh, cy + Cos(rad_h) * #len_hh, c_black)
      Circle(cx, cy, 4, c_blue)
    StopDrawing()
    SetGadgetState(#clock_gad, ImageID(#clockFace_img))
  EndIf
Until event = #PB_Event_CloseWindow


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

int dot_product(int *, int *, size_t);

int
main(void)
{
        int a[3] = {1, 3, -5};
        int b[3] = {4, -2, -1};

        printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0])));

        return EXIT_SUCCESS;
}

int
dot_product(int *a, int *b, size_t n)
{
        int sum = 0;
        size_t i;

        for (i = 0; i < n; i++) {
                sum += a[i] * b[i];
        }

        return sum;
}


import java.awt.Color;
import java.awt.Graphics;
import java.util.*;
import javax.swing.JFrame;

public class DragonCurve extends JFrame {

    private List<Integer> turns;
    private double startingAngle, side;

    public DragonCurve(int iter) {
        super("Dragon Curve");
        setBounds(100, 100, 800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        turns = getSequence(iter);
        startingAngle = -iter * (Math.PI / 4);
        side = 400 / Math.pow(2, iter / 2.);
    }

    public List<Integer> getSequence(int iterations) {
        List<Integer> turnSequence = new ArrayList<Integer>();
        for (int i = 0; i < iterations; i++) {
            List<Integer> copy = new ArrayList<Integer>(turnSequence);
            Collections.reverse(copy);
            turnSequence.add(1);
            for (Integer turn : copy) {
                turnSequence.add(-turn);
            }
        }
        return turnSequence;
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        double angle = startingAngle;
        int x1 = 230, y1 = 350;
        int x2 = x1 + (int) (Math.cos(angle) * side);
        int y2 = y1 + (int) (Math.sin(angle) * side);
        g.drawLine(x1, y1, x2, y2);
        x1 = x2;
        y1 = y2;
        for (Integer turn : turns) {
            angle += turn * (Math.PI / 2);
            x2 = x1 + (int) (Math.cos(angle) * side);
            y2 = y1 + (int) (Math.sin(angle) * side);
            g.drawLine(x1, y1, x2, y2);
            x1 = x2;
            y1 = y2;
        }
    }

    public static void main(String[] args) {
        new DragonCurve(14).setVisible(true);
    }
}


using DataFrames

text = """
Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.
"""

const bcolor = ["background: #ffffaa;", "background: #ffdddd;",
    "background: #ddffdd;", "background: #ddddff;"]
colorstring(n) = bcolor[n == 1 ? 1  : mod1(n - 1, length(bcolor) - 1) + 1]

function processtable(txt)
    df = DataFrame()
    indents = Int[]
    linetext = String[]
    for line in split(txt, "\n")
        if length(line) > 0
            n = findfirst(!isspace, line)
            push!(linetext, String(line[n:end]))
            push!(indents, n - 1)
        end
    end
    len = length(indents)
    divisor = gcd(indents)
    indents .= div.(indents, divisor)
    parent(i) = (n = findlast(x -> indents[x] < indents[i], 1:i-1)) == nothing ? 0 : n
    children(i) = findall(x -> parent(x) == i, 1:len)
    treesize(i) = (s = children(i); isempty(s) ? 1 : sum(treesize, s))
    prioronlevel(i) = (j = indents[i]; filter(x -> indents[x] == j, 1:i-1))
    treesizeprior(i) = (s = prioronlevel(i); isempty(s) ? 0 : sum(treesize, s))
    startpos(i) = (n = parent(i)) == 0 ? 0 : treesizeprior(n) - treesizeprior(i)
    function leveloneparent(i)
        p = parent(i)
        return p < 1 ? 1 : p ==1 ? sum(x -> indents[x] <= 1, 1:i) : leveloneparent(p)
    end
    df.TEXT = linetext
    df.INDENT = indents
    df.COLSPAN = [treesize(i) for i in 1:len]
    df.PRESPAN = [max(0, startpos(i)) for i in 1:len]
    df.LEVELONEPARENT = [leveloneparent(i) for i in 1:len]
    return df
end

function htmlfromdataframe(df)
    println("
A Rosetta Code Nested Table

")
    for ind in minimum(df.INDENT):maximum(df.INDENT)
        println("
")
        for row in eachrow(df)
            if row[:INDENT] == ind
                if row[:PRESPAN] > 0
                    println(" 	")
                end
                print(" 0
                    println("colspan=\"$(row[:COLSPAN])\"")
                end
                println(" style = \"$(colorstring(row[:LEVELONEPARENT]))\" >$(row[:TEXT])	")
            end
        end
        println("
")
    end
    println("
")
end

htmlfromdataframe(processtable(text))
textplus = text * "    Optionally add color to the nodes."
htmlfromdataframe(processtable(textplus))


s = "Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.";
s = StringSplit[s, "\n"];
indentation = LengthWhile[Characters[#], EqualTo[" "]] & /@ s;
s = MapThread[StringDrop, {s, indentation}];
indentation =
  indentation /.
   Thread[Union[indentation] -> Range[Length[Union[indentation]]]];
ii = Transpose[{Range[Length[indentation]], indentation}];
(*ii//Grid*)

sel = Table[
   {i, [email protected][ii, #[[2]] < i[[2]] \[And] #[[1]]  "Name"];

vl = VertexList[g];
head = FirstPosition[vl, 1][[1]];
dm = GraphDistanceMatrix[g];
depth = ReverseSortBy[Transpose[{vl, dm[[All, head]]}], Last];
colspandb = <||>;
data = Table[
   vert = d[[1]];
   vd = VertexInDegree[g, vert];
   vics = VertexInComponent[g, vert, {1}];
   vocs = [email protected][g, vert];
   cspan = 0;
   Do[
    If[KeyExistsQ[colspandb, vic],
     cspan += colspandb[vic]
     ]
    ,
    {vic, vics}
    ];
   If[cspan == 0, cspan = 1];
   AssociateTo[colspandb, d[[1]] -> cspan];
   {Sequence @@ d, vd, vics, vocs, cspan}
   ,
   {d, depth}
   ];

emptybefore = Table[
   {d[[1]],
    [email protected]
     Select[
       data, #[[1]] < d[[1]] \[And]
         Length[#[[4]]] == 0 \[And] #[[2]] < d[[2]] &][[All, {1, 2,
        3}]]}
   ,
   {d, data}
   ];
emptybefore = Association[Rule @@@ emptybefore];

depthcopy = depth;
depthcopy[[All, 2]] += 1;
graphelements =
  SortBy[Sort /@ GatherBy[depthcopy, Last], First /* Last][[All, All,
    1]];

str = {"
"};
colorsdb = <|1 -> "#ffffe6", 2 -> "#ffebd2", 6 -> "#f0fff0",
   10 -> "#e6ffff"|>;
Do[
 AppendTo[str, "
"];
 totalspan = 0;
 Do[
  If[KeyExistsQ[colorsdb, g],
   color = colorsdb[g]
   ,
   (*Print["sel",SelectFirst[data,First/*EqualTo[g]][[5]]];*)

   color =
    colorsdb[
     Max[
      Intersection[SelectFirst[data, First /* EqualTo[g]][[5]],
       Keys[colorsdb]]]]
   ];
  span = SelectFirst[data, First /* EqualTo[g]][[6]];
  totalspan += span;

  empty = emptybefore[g];
  str = str~Join~
    ConstantArray["	",
     empty];
  If[span == 1,
   AppendTo[str,
     "<td style=\"background-color: " <> color <> ";\">" <> s[[g]] <>
      "	"];
   ,
   AppendTo[str,
     "<tdcolspan=\"" <> ToString[span] <>
      "\" style=\"background-color: " <> color <> ";\">" <> s[[g]] <>
      "	"];
   ];
  ,
  {g, ge}
  ];
 extra =
  SelectFirst[data, First /* EqualTo[1]][[6]] - totalspan - empty;
 str = str~Join~
   ConstantArray["	",
    extra];
 AppendTo[str, "
"];
 ,
 {ge, graphelements}
 ]
AppendTo[str, "
"];
StringRiffle[str, "\n"]


import strutils

const Outline = """Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML."""

type Color {.pure.} = enum
  NoColor
  Yellow = "#ffffe6;"
  Orange = "#ffebd2;"
  Green = "#f0fff0;"
  Blue = "#e6ffff;"

const Line1Color = Yellow
const Line2Colors = [Orange, Green, Blue]

type Node = ref object
  value: string
  level: Natural
  width: Natural
  color: Color
  parent: Node
  children: seq[Node]

#---------------------------------------------------------------------------------------------------

proc leadingSpaces(line: string): int =
  ## return the number of leading spaces.
  while line[result] == ' ':
    inc result

#---------------------------------------------------------------------------------------------------

proc buildTree(outline: string): tuple[root: Node, depth: Natural] =
  ## Build the tree for the given outline.

  result.root = Node()
  var level: int
  var startPos = @[-1]
  var nodes: seq[Node] = @[result.root]
  var linecount = 0

  for line in Outline.splitLines:
    inc linecount
    if line.len == 0: continue
    let start = line.leadingSpaces()
    level = startPos.find(start)

    if level < 0:
      # Level not yet encountered.
      if start < startPos[^1]:
        raise newException(ValueError, "wrong indentation at line " & $linecount)
      startPos.add(start)
      nodes.add(nil)
      level = startPos.high

    # Create the node.
    let node = Node(value: line.strip(), level: level)
    let parent = nodes[level - 1]
    parent.children.add(node)
    node.parent = parent
    nodes[level] = node   # Set the node as current node for this level.

  result.depth = nodes.high

#---------------------------------------------------------------------------------------------------

proc padTree(node: Node; depth: Natural) =
  ## pad the tree with empty nodes to get an even depth.
  if node.level == depth:
    return
  if node.children.len == 0:
    # Add an empty node.
    node.children.add(Node(level: node.level + 1, parent: node))
  for child in node.children:
    child.padTree(depth)

#---------------------------------------------------------------------------------------------------

proc computeWidths(node: Node) =
  ## Compute the widths.
  var width = 0
  if node.children.len == 0:
    width = 1
  else:
    for child in node.children:
      child.computeWidths()
      inc width, child.width
  node.width = width

#---------------------------------------------------------------------------------------------------

proc build(nodelists: var seq[seq[Node]]; node: Node) =
  ## Build the list of nodes per level.
  nodelists[node.level].add(node)
  for child in node.children:
    nodelists.build(child)

#---------------------------------------------------------------------------------------------------

proc setColors(nodelists: seq[seq[Node]]) =
  ## Set the colors of the nodes.
  for node in nodelists[1]:
    node.color = Line1Color
  for i, node in nodelists[2]:
    node.color = Line2Colors[i mod Line2Colors.len]
  for level in 3..nodelists.high:
    for node in nodelists[level]:
      node.color = if node.value.len != 0: node.parent.color else: NoColor

#---------------------------------------------------------------------------------------------------

proc writeWikiTable(nodelists: seq[seq[Node]]) =
  ## Output the wikitable.
  echo "{| class='wikitable' style='text-align: center;'"
  for level in 1..nodelists.high:
    echo "|-"
    for node in nodelists[level]:
      if node.width > 1:
        # Node with children.
        echo "| style='background: $1 ' colspan=$2 | $3".format(node.color, node.width, node.value)
      elif node.value.len > 0:
        # Leaf with contents.
        echo "| style='background: $1 ' | $2".format(node.color, node.value)
      else:
        # Empty cell.
        echo "|  | "
  echo "|}"

#---------------------------------------------------------------------------------------------------

proc writeHtml(nodelists: seq[seq[Node]]) =
  ## Output the HTML.
  echo "
"
  for level in 1..nodelists.high:
    echo "
"
    for node in nodelists[level]:
      if node.width > 1:
        # Node with children.
        echo "    $3	".format(node.width, node.color, node.value)
      elif node.value.len > 0:
        # Leaf with contents.
        echo "    $2	".format(node.color, node.value)
      else:
        # Empty cell.
        echo "    	"
    echo "
"
  echo "
"

#———————————————————————————————————————————————————————————————————————————————————————————————————

let (root, depth) = Outline.buildTree()
root.padTree(depth)
root.computeWidths()
var nodelists = newSeq[seq[Node]](depth + 1)
nodelists.build(root)
nodelists.setColors()
echo "WikiTable:"
nodelists.writeWikiTable()
echo "HTML:"
nodelists.writeHtml()


main =>
  Limit = 19,
  D = [],
  N = 0,
  printf("The first %d Disarium numbers are:\n",Limit),
  while (D.len < Limit)
     if disarium_number(N) then
       D := D ++ [N]
     end,
     N := N + 1,
     if N mod 10_000_000 == 0 then
       println(test=N)
     end
  end,
  println(D).

disarium_number(N) =>
  Sum = 0,
  Digits = N.to_string.len,
  X = N,
  while (X != 0, Sum <= N)
    Sum := Sum + (X mod 10) ** Digits,
    Digits := Digits - 1,
    X := X div 10
  end,
  Sum == N.


#!/usr/bin/python

def isDisarium(n):
    digitos = len(str(n))
    suma = 0
    x = n
    while x != 0:
        suma += (x % 10) ** digitos
        digitos -= 1
        x //= 10
    if suma == n:
        return True
    else:
        return False

if __name__ == '__main__':
    limite = 19
    cont = 0
    n = 0
    print("The first",limite,"Disarium numbers are:")
    while cont < limite:
        if isDisarium(n):
            print(n, end = " ")
            cont += 1
        n += 1


100H: /* FIND SOME DISARIUM NUMBERS - NUMBERS WHOSE DIGIT POSITION-POWER     */
      /* SUMS ARE EQUAL TO THE NUMBER, E.G. 135 = 1^1 + 3^2 + 5^3            */

   /* CP/M BDOS SYSTEM CALL, IGNORE THE RETURN VALUE                         */
   BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
   PR$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS( 2, C );  END;
   PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S );  END;
   PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH  */
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
      V = N;
      W = LAST( N$STR );
      N$STR( W ) = '$';
      N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL PR$STRING( .N$STR( W ) );
   END PR$NUMBER;

   /* TABLE OF POWERS UP TO THE FOURTH POWER - AS WE ARE ONLY FINDING THE   */
   /* DISARIUM NUMBERS UP TO 9999                                           */
   DECLARE POWER( 40 /* ( 1 : 4, 0 : 9 ) */ ) ADDRESS;
   DECLARE MAX$DISARIUM LITERALLY '9999';

   DECLARE ( N, D, POWER$OF$TEN, COUNT, LENGTH, V, P, DPS, NSUB, NPREV )
                                              ADDRESS;

   /* COMPUTE THE NTH POWERS OF 0-9                                         */
   DO D = 0 TO 9; POWER( D ) = D; END;
   NSUB  = 10;
   NPREV =  0;
   DO N = 2 TO 4;
      POWER( NSUB ) = 0;
      DO D = 1 TO 9;
         POWER( NSUB + D ) = POWER( NPREV + D ) * D;
      END;
      NPREV = NSUB;
      NSUB  = NSUB + 10;
   END;

   /* PRINT THE DISARIUM NUMBERS UPTO 9999 OR THE 18TH, WHICHEVER IS SOONER */
   POWER$OF$TEN = 10;
   LENGTH       =  1;
   COUNT, N     =  0;
   DO WHILE( N < MAX$DISARIUM AND COUNT < 18 );
      IF N = POWER$OF$TEN THEN DO;
         /* THE NUMBER OF DIGITS JUST INCREASED                             */
         POWER$OF$TEN = POWER$OF$TEN * 10;
         LENGTH       = LENGTH       +  1;
      END;
      /* FORM THE DIGIT POWER SUM                                           */
      V   = N;
      P   = LENGTH * 10;
      DPS = 0;
      DO D = 1 TO LENGTH;
         P = P - 10;
         DPS = DPS + POWER( P + ( V MOD 10 ) );
         V = V / 10;
      END;
      IF DPS = N THEN DO;
         /* N IS DISARIUM                                                   */
         COUNT = COUNT + 1;
         CALL PR$CHAR( ' ' );
         CALL PR$NUMBER( N );
      END;
      N = N + 1;
   END;

EOF


import "/llist" for DLinkedList

var dll = DLinkedList.new()
for (i in 1..3) dll.add(i)
System.print(dll)
for (i in 1..3) dll.remove(i)
System.print(dll)


class Node{
   fcn init(_value,_prev=Void,_next=Void)
      { var value=_value, prev=_prev, next=_next; }
   fcn toString{ value.toString() }
   fcn append(value){  // loops not allowed: create a new Node
      b,c := Node(value,self,next),next;
      next=b;
      if(c) c.prev=b;
      b
   }
   fcn delete{
      if(prev) prev.next=next;
      if(next) next.prev=prev;
      self
   }
   fcn last  { n,p := self,self; while(n){ p,n = n,n.next } p }
   fcn first { n,p := self,self; while(n){ p,n = n,n.prev } p }
   fcn walker(forward=True){
      dir:=forward and "next" or "prev";
      Walker(fcn(rn,dir){
         if(not (n:=rn.value)) return(Void.Stop);
	 rn.set(n.setVar(dir));
         n.value;
      }.fp(Ref(self),dir))
   }
}


import time

def chunks(l, n=5):
    return [l[i:i+n] for i in range(0, len(l), n)]

def binary(n, digits=8):
    n=int(n)
    return '{0:0{1}b}'.format(n, digits)

def secs(n):
    n=int(n)
    h='x' * n
    return "|".join(chunks(h))

def bin_bit(h):
    h=h.replace("1","x")
    h=h.replace("0"," ")
    return "|".join(list(h))

x=str(time.ctime()).split()
y=x[3].split(":")

s=y[-1]
y=map(binary,y[:-1])

print bin_bit(y[0])
print
print bin_bit(y[1])
print
print secs(s)


static void Main(string[] args)
{
	Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 }));
	Console.Read();
}

private static decimal DotProduct(decimal[] vec1, decimal[] vec2)
{
	if (vec1 == null)
		return 0;

	if (vec2 == null)
		return 0;

	if (vec1.Length != vec2.Length)
		return 0;

	decimal tVal = 0;
	for (int x = 0; x < vec1.Length; x++)
	{
		tVal += vec1[x] * vec2[x];
	}

	return tVal;
}


#include <iostream>
#include <numeric>

int main()
{
    int a[] = { 1, 3, -5 };
    int b[] = { 4, -2, -1 };

    std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl;

    return 0;
}


var DRAGON = (function () {
   // MATRIX MATH
   // -----------

   var matrix = {
      mult: function ( m, v ) {
         return [ m[0][0] * v[0] + m[0][1] * v[1],
                  m[1][0] * v[0] + m[1][1] * v[1] ];
      },

      minus: function ( a, b ) {
         return [ a[0]-b[0], a[1]-b[1] ];
      },

      plus: function ( a, b ) {
         return [ a[0]+b[0], a[1]+b[1] ];
      }
   };

   // SVG STUFF
   // ---------

   // Turn a pair of points into an SVG path like "M1 1L2 2".
   var toSVGpath = function (a, b) {  // type system fail
      return "M" + a[0] + " " + a[1] + "L" + b[0] + " " + b[1];
   };

   // DRAGON MAKING
   // -------------

   // Make a dragon with a better fractal algorithm
   var fractalMakeDragon = function (svgid, ptA, ptC, state, lr, interval) {

      // make a new <path>
      var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
      path.setAttribute( "class",  "dragon");
      path.setAttribute( "d", toSVGpath(ptA, ptC) );

      // append the new path to the existing <svg>
      var svg = document.getElementById(svgid); // call could be eliminated
      svg.appendChild(path);

      // if we have more iterations to go...
      if (state > 1) {

         // make a new point, either to the left or right
         var growNewPoint = function (ptA, ptC, lr) {
            var left  = [[ 1/2,-1/2 ],
                         [ 1/2, 1/2 ]];

            var right = [[ 1/2, 1/2 ],
                         [-1/2, 1/2 ]];

            return matrix.plus(ptA, matrix.mult( lr ? left : right,
                                                 matrix.minus(ptC, ptA) ));
         };

         var ptB = growNewPoint(ptA, ptC, lr, state);

         // then recurse using each new line, one left, one right
         var recurse = function () {
            // when recursing deeper, delete this svg path
            svg.removeChild(path);

            // then invoke again for new pair, decrementing the state
            fractalMakeDragon(svgid, ptB, ptA, state-1, lr, interval);
            fractalMakeDragon(svgid, ptB, ptC, state-1, lr, interval);
         };

         window.setTimeout(recurse, interval);
      }
   };

   // Export these functions
   // ----------------------
   return {
      fractal: fractalMakeDragon

      // ARGUMENTS
      // ---------
      //    svgid    id of <svg> element
      //    ptA      first point [x,y] (from top left)
      //    ptC      second point [x,y]
      //    state    number indicating how many steps to recurse
      //    lr       true/false to make new point on left or right

      // CONFIG
      // ------
      // CSS rules should be made for the following
      //    svg#fractal
      //    svg path.dragon
   };

}());


#!/usr/bin/perl

use strict;
use warnings;

my @rows;
my $row = -1;
my $width = 0;
my $color = 0;
our $bg = 'e0ffe0';

parseoutline( do { local $/; <DATA> =~ s/\t/  /gr } );

print "
\n";
for ( @rows )
  {
  my $start = 0;
  print "
\n";
  for ( @$_ ) # columns
    {
    my ($data, $col, $span, $bg) = @$_;
    print "    	\n" x ( $col - $start ),
      "     $data 	\n";
    $start = $col + $span;
    }
  print "    	\n" x ( $width - $start ), "
\n";
  }
print "
\n";

sub parseoutline
  {
  ++$row;
  while( $_[0] =~ /^( *)(.*)\n((?:\1 .*\n)*)/gm )
    {
    my ($head, $body, $col) = ($2, $3, $width);
    $row == 1 and local $bg = qw( ffffe0 ffe0e0 )[ $color ^= 1];
    if( length $body ) { parseoutline( $body ) } else { ++$width }
    push @{ $rows[$row] }, [ $head, $col, $width - $col, $bg ];
    }
  --$row;
  }

__DATA__
Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.


my $disarium = (^∞).hyper.map: { $_ if $_ == sum .polymod(10 xx *).reverse Z** 1..* };

put $disarium[^18];
put $disarium[18];


func is_disarium(n) {
    n.digits.flip.sum_kv{|k,d| d**(k+1) } == n
}

say 18.by(is_disarium)


import strconv

const dmax = 20  // maximum digits
const limit = 20 // maximum number of disariums to find

fn main() {
    // Pre-calculated exponential and power serials
    mut exp1 := [][]u64{len: 1+dmax, init: []u64{len: 11}}
    mut pow1 := [][]u64{len: 1+dmax, init: []u64{len: 11}}

    for i := u64(1); i <= 10; i++ {
        exp1[1][i] = i
    }
    for i := u64(1); i <= 9; i++ {
        pow1[1][i] = i
    }
    pow1[1][10] = 9

    for i := 1; i < dmax; i++ {
        for j := 0; j <= 9; j++ {
            exp1[i+1][j] = exp1[i][j] * 10
            pow1[i+1][j] = pow1[i][j] * u64(j)
        }
        exp1[i+1][10] = exp1[i][10] * 10
        pow1[i+1][10] = pow1[i][10] + pow1[i+1][9]
    }

    // Digits of candidate and values of known low bits
    mut digits := []int{len: 1+dmax} // Digits form
    mut exp2 := []u64{len: 1+dmax} // Number form
    mut pow2 := []u64{len: 1+dmax} // pow2ers form

    mut exp, mut pow, mut min, mut max := u64(0),u64(0),u64(0),u64(0)
    start := 1
    final := dmax
    mut count := 0
    for digit := start; digit <= final; digit++ {
        println("# of digits: $digit")
        mut level := 1
        digits[0] = 0
        for {
            // Check limits derived from already known low bit values
            // to find the most possible candidates
            for 0 < level && level < digit {
                // Reset path to try next if checking in level is done
                if digits[level] > 9 {
                    digits[level] = 0
                    level--
                    digits[level]++
                    continue
                }

                // Update known low bit values
                exp2[level] = exp2[level-1] + exp1[level][digits[level]]
                pow2[level] = pow2[level-1] + pow1[digit+1-level][digits[level]]

                // Max possible value
                pow = pow2[level] + pow1[digit-level][10]

                if pow < exp1[digit][1] { // Try next since upper limit is invalidly low
                    digits[level]++
                    continue
                }

                max = pow % exp1[level][10]
                pow -= max
                if max < exp2[level] {
                    pow -= exp1[level][10]
                }
                max = pow + exp2[level]

                if max < exp1[digit][1] { // Try next since upper limit is invalidly low
                    digits[level]++
                    continue
                }

                // Min possible value
                exp = exp2[level] + exp1[digit][1]
                pow = pow2[level] + 1

                if exp > max || max < pow { // Try next since upper limit is invalidly low
                    digits[level]++
                    continue
                }

                if pow > exp {
                    min = pow % exp1[level][10]
                    pow -= min
                    if min > exp2[level] {
                        pow += exp1[level][10]
                    }
                    min = pow + exp2[level]
                } else {
                    min = exp
                }

                // Check limits existence
                if max < min {
                    digits[level]++ // Try next number since current limits invalid
                } else {
                    level++ // Go for further level checking since limits available
                }
            }

            // All checking is done, escape from the main check loop
            if level < 1 {
                break
            }

            // Finally check last bit of the most possible candidates
            // Update known low bit values
            exp2[level] = exp2[level-1] + exp1[level][digits[level]]
            pow2[level] = pow2[level-1] + pow1[digit+1-level][digits[level]]

            // Loop to check all last bits of candidates
            for digits[level] < 10 {
                // Print out new Disarium number
                if exp2[level] == pow2[level] {
                    mut s := ""
                    for i := dmax; i > 0; i-- {
                        s += "${digits[i]}"
                    }
                    n, _ := strconv.common_parse_uint2(s, 10, 64)
                    println(n)
                    count++
                    if count == limit {
                        println("\nFound the first $limit Disarium numbers.")
                        return
                    }
                }

                // Go to followed last bit candidate
                digits[level]++
                exp2[level] += exp1[level][1]
                pow2[level]++
            }

            // Reset to try next path
            digits[level] = 0
            level--
            digits[level]++
        }
        println('')
    }
}


import "./math" for Int

var limit = 19
var count = 0
var disarium = []
var n = 0
while (count < limit) {
    var sum = 0
    var digits = Int.digits(n)
    for (i in 0...digits.count) sum = sum + digits[i].pow(i+1)
    if (sum == n) {
        disarium.add(n)
        count = count + 1
    }
    n = n + 1
}
System.print("The first 19 Disarium numbers are:")
System.print(disarium)


#lang racket/gui

(require racket/date slideshow/pict)

(define (clock h m s [r 100])
  (define (draw-hand length angle
                     #:width [width 1]
                     #:color [color "black"])
    (dc (λ (dc dx dy)
          (define old-pen (send dc get-pen))
          (send dc set-pen (new pen% [width width] [color color]))
          (send dc draw-line
                (+ dx r) (+ dy r)
                (+ dx r (* length (sin angle)))
                (+ dy r (* length (cos angle))))
          (send dc set-pen old-pen))
      (* 2 r) (* 2 r)))
  (cc-superimpose
   (for/fold ([pict (circle (* 2 r))])
             ([angle (in-range 0 (* 2 pi) (/ pi 6))]
              [hour (cons 12 (range 1 12))])
     (define angle* angle)
     (define r* (* r 0.8))
     (define txt (text (number->string hour) '(bold . "Helvetica")))
     (define x (- (* r* (sin angle*)) (/ (pict-width txt) 2)))
     (define y (+ (* r* (cos angle*)) (/ (pict-height txt) 2)))
     (pin-over pict (+ r x) (- r y) txt))
   (draw-hand (* r 0.7) (+ pi (* (modulo h 12) (- (/ pi 6))))
              #:width 3)
   (draw-hand (* r 0.5) (+ pi (* m (- (/ pi 30))))
              #:width 2)
   (draw-hand (* r 0.7) (+ pi (* s (- (/ pi 30))))
              #:color "red")
   (disk (* r 0.1))))

(define f (new frame% [label "Clock"] [width 300] [height 300]))

(define c
  (new canvas%
       [parent f]
       [paint-callback
        (λ (c dc)
          (define date (current-date))
          (draw-pict (clock (date-hour date)
                            (date-minute date)
                            (date-second date)
                            (/ (send c get-width) 2))
                     dc 0 0))]))

(define t
  (new timer%
       [notify-callback (λ () (send c refresh-now))]
       [interval 1000]))

(send f show #t)


my ($rows,$cols) = qx/stty size/.words;
my $v = floor $rows / 2;
my $h = floor $cols / 2 - 16;

my @t = < ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀>;
my @b = < ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀>;

loop {
    my @x = DateTime.now.Str.substr(11,8).ords X- ord('0');
    print "\e[H\e[J";
    print "\e[$v;{$h}H";
    print ~@t[@x];
    print "\e[{$v+1};{$h}H";
    print ~@b[@x];
    print "\e[H";
    sleep 1;
}


(defn dot-product [& matrix]
  {:pre [(apply == (map count matrix))]}
  (apply + (apply map * matrix)))

(defn dot-product2 [x y]
 (->> (interleave x y)
      (partition 2 2)
      (map #(apply * %))
      (reduce +)))

(defn dot-product3
  "Dot product of vectors. Tested on version 1.8.0."
  [v1 v2]
  {:pre [(= (count v1) (count v2))]}
  (reduce + (map * v1 v2)))

;Example Usage
(println (dot-product [1 3 -5] [4 -2 -1]))
(println (dot-product2 [1 3 -5] [4 -2 -1]))
(println (dot-product3 [1 3 -5] [4 -2 -1]))


% Compute the dot product of two sequences
% If the sequences are not the same length, it signals length_mismatch
% Any type may be used as long as it supports addition and multiplication
dot_product = proc [T: type] (a, b: sequence[T])
              returns (T) signals (length_mismatch, empty, overflow)
              where T has add: proctype (T,T) returns (T) signals (overflow),
                          mul: proctype (T,T) returns (T) signals (overflow)
    sT = sequence[T]
    % throw errors if necessary
    if sT$size(a) ~= sT$size(b) then signal length_mismatch end
    if sT$empty(a) then signal empty end

    % because we don't know what type T is yet, we can't instantiate it
    % with a default value, so we use the first pair from the sequences
    s: T := sT$bottom(a) * sT$bottom(b) resignal overflow
    for i: int in int$from_to(2, sT$size(a)) do
        s := s + a[i] * b[i] resignal overflow
    end
    return(s)
end dot_product

% calculate the dot product of the given example
start_up = proc ()
    po: stream := stream$primary_output()

    a: sequence[int] := sequence[int]$[1, 3, -5]
    b: sequence[int] := sequence[int]$[4, -2, -1]

    stream$putl(po, int$unparse(dot_product[int](a,b)))
end start_up


include "simple-turtle" {search: "."};

def rules:
   { F: "F+S",
     S: "F-S" };

def dragon($count):
  rules as $rules
  | def p($count):
      if $count <= 0 then .
      else gsub("S"; "s") | gsub("F"; $rules["F"]) | gsub("s"; $rules["S"])
      | p($count-1)
      end;
  "F" | p($count) ;

def interpret($x):
  if   $x == "+" then turtleRotate(90)
  elif $x == "-" then turtleRotate(-90)
  elif $x == "F" then turtleForward(4)
  elif $x == "S" then turtleForward(4)
  else .
  end;

def dragon_curve($n):
  dragon($n)
  | split("")
  | reduce .[] as $action (turtle([200,300]) | turtleDown;
      interpret($action) ) ;

dragon_curve(15)
| path("none"; "red"; "0.1") | svg(1700)


using Luxor
function dragon(turtle::Turtle, level=4, size=200, direction=45)
    if level != 0
        Turn(turtle, -direction)
        dragon(turtle, level-1, size/sqrt(2), 45)
        Turn(turtle, direction*2)
        dragon(turtle, level-1, size/sqrt(2), -45)
        Turn(turtle, -direction)
    else
        Forward(turtle, size)
    end
end

Drawing(900, 500, "./Dragon.png")
t = Turtle(300, 300, true, 0, (0., 0.0, 0.0));
dragon(t, 10,400)
finish()
preview()


with javascript_semantics
constant html = false,
         outlines = {"""
Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.""",			"""
Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
            Propagating the sums upward as necessary.
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.
    Optionally add color to the nodes."""}

constant yellow = "#ffffe6;",
         orange = "#ffebd2;",
         green  = "#f0fff0;",
         blue   = "#e6ffff;",
         pink   = "#ffeeff;",
         colours = {{yellow, orange, green, blue, pink},
                    {blue, yellow, orange, green, pink}}

function calc_spans(sequence lines, integer ldx)
    sequence children = lines[ldx][$]
    if length(children)!=0 then
        integer span = 0
        for i=1 to length(children) do
            integer child = children[i]
            lines = calc_spans(lines,child)
            span += lines[child][4]
        end for
        lines[ldx][4] = span
--  else -- (span already 1)
    end if
    return lines
end function

procedure markup(string outline, sequence colours)
    sequence lines = split(outline,"\n",no_empty:=true),
             pi = {},   -- indents (to locate parents)
             pdx = {},  -- indexes for ""
             children = {}
    string text
    integer maxdepth = 0,
            parent, depth, span
    for i=1 to length(lines) do
        string line = trim_tail(lines[i])
        text = trim_head(line)
        integer indent = length(line)-length(text)
        -- remove any completed parents
        while length(pi) and indent<=pi[$] do
            pi = pi[1..$-1]
            pdx = pdx[1..$-1]
        end while
        parent = 0
        if length(pi) then
            parent = pdx[$]
            lines[parent][$] = deep_copy(lines[parent][$]) & i -- (update children)
        end if
        pi &= indent
        pdx &= i
        depth = length(pi)
        span = 1 -- (default/assume no children[=={}])
        lines[i] = {i,depth,indent,span,parent,text,children}
        maxdepth = max(maxdepth,depth)
    end for
    lines = calc_spans(lines,1)

    string res = iff(html?"
\n"
                         :"{| class=\"wikitable\" style=\"text-align: center;\"\n")
    for d=1 to maxdepth do
        res &= iff(html?"
\n"
                       :"|-\n")
        integer cdx = 1, lii, lident
        for i=1 to length(lines) do
            {lii,depth,lident,span,parent,text,children} = lines[i]
            if depth=2 then cdx += 1 end if
            string style = sprintf(`style="background: %s"`,{colours[cdx]})
            if depth=d then
                if span!=1 then style &= sprintf(` colspan="%d"`,span) end if
                res &= sprintf(iff(html?"%s	\n"
                                       :"| %s | %s\n"),{style,text})
            elsif depth<d and children={} then
--              res &= iff(html?"	\n"
--                             :"|	|\n")
                res &= sprintf(iff(html?"	\n"
                                       :"| %s |\n"),{style})
            end if
        end for
        if html then
            res &= "
\n"
        end if
    end for
    res &= iff(html?"
\n"
                   :"|}\n")
    puts(1,res)
end procedure
for i=1 to length(outlines) do
    markup(outlines[i],colours[i])
end for


with Ada.Text_Io;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;

procedure Display_Linear is

   subtype Position is Positive;
   type Coefficient is new Integer;
   type Combination is array (Position range <>) of Coefficient;

   function Linear_Combination (Comb : Combination) return String is
      use Ada.Strings.Unbounded;
      use Ada.Strings;
      Accu : Unbounded_String;
   begin
      for Pos in Comb'Range loop
         case Comb (Pos) is
            when Coefficient'First .. -1 =>
               Append (Accu, (if Accu = "" then "-" else " - "));
            when 0 => null;
            when 1 .. Coefficient'Last =>
               Append (Accu, (if Accu /= "" then " + " else ""));
         end case;

         if Comb (Pos) /= 0 then
            declare
               Abs_Coeff   : constant Coefficient := abs Comb (Pos);
               Coeff_Image : constant String := Fixed.Trim (Coefficient'Image (Abs_Coeff), Left);
               Exp_Image   : constant String := Fixed.Trim (Position'Image (Pos), Left);
            begin
               if Abs_Coeff /= 1 then
                  Append (Accu, Coeff_Image & "*");
               end if;
               Append (Accu, "e(" & Exp_Image & ")");
            end;
         end if;
      end loop;

      return (if Accu = "" then "0" else To_String (Accu));
   end Linear_Combination;

   use Ada.Text_Io;
begin
   Put_Line (Linear_Combination ((1, 2, 3)));
   Put_Line (Linear_Combination ((0, 1, 2, 3)));
   Put_Line (Linear_Combination ((1, 0, 3, 4)));
   Put_Line (Linear_Combination ((1, 2, 0)));
   Put_Line (Linear_Combination ((0, 0, 0)));
   Put_Line (Linear_Combination ((1 => 0)));
   Put_Line (Linear_Combination ((1, 1, 1)));
   Put_Line (Linear_Combination ((-1, -1, -1)));
   Put_Line (Linear_Combination ((-1, -2, 0, -3)));
   Put_Line (Linear_Combination ((1 => -1)));
end Display_Linear;


func Disarium(N);       \Return 'true' if N is a Disarium number
int  N, N0, D(10), A(10), I, J, Sum;
[N0:= N;
for J:= 0 to 10-1 do A(J):= 1;
I:= 0;
repeat  N:= N/10;
        D(I):= rem(0);
        I:= I+1;
        for J:= 0 to I-1 do
            A(J):= A(J) * D(J);
until   N = 0;
Sum:= 0;
for J:= 0 to I-1 do
    Sum:= Sum + A(J);
return Sum = N0;
];

int Cnt, N;
[Cnt:= 0;  N:= 0;
loop    [if Disarium(N) then
            [IntOut(0, N);  ChOut(0, ^ );
            Cnt:= Cnt+1;
            if Cnt >= 19 then quit;
            ];
        N:= N+1;
        ];
]


Red [Needs: 'View]
view [t: h4 rate 1 on-time [t/data: now/time]]


/*REXX program displays the  current (local) time  as a  digital clock  on the terminal.*/
trace off                                        /*turn off tracing/possible host errors*/
parse arg !                                      /*obtain optional arguments from the CL*/
if !all(arg())  then exit                        /*was there a request for some help?   */
if !cms         then address ''                  /*If CMS,  then initialize ADDRESS name*/

signal on halt                                   /*initialize target label when HALTed. */
signal on noValue                                /*     "        "     "     "  noValue.*/
signal on syntax                                 /*     "        "     "     "  syntax. */

parse var ! ops                                  /*obtain optional arguments from the CL*/
ops = space(ops)                                 /*elide superfluous blanks from options*/
blinkSecs = 1                                    /*amount of time between displays.     */
creep     = 1                                    /*moves the output "around" the screen.*/
tops      = '.C=blue .BC=░ .BS=1 .BLOCK=12'      /*options to be specified for  $T.REXX */

  do while ops\==''                              /*process all the specified options.   */
  parse var ops _1 2 1 _ . 1 y ops               /*extract various information from opt.*/
  upper _                                        /*uppercase the    _    REXX variavle. */
           select
           when _==','                    then nop              /*ignore any comma used.*/
           when _1==.  &  pos("=",_)\==0  then tops= tops y     /*add this value to TOPS*/
           when abbn('BLINKSECs')         then blinksecs= no()  /*use/not use BLINKSECs.*/
           when abbn('CREEPs')            then creep= no()      /* "   "   "  CREEPs.   */
           otherwise                      call er 55,y          /*whoops! Invalid option*/
           end   /*select*/
  end            /*while ops¬==''*/

if \!pcrexx  then  blinkSecs= 0                  /*Not PC/REXX?  Then turn off BLINKSECS*/
tops= space(tops)                                /*elide superfluous blanks in  TOPS.   */
parse value  scrsize()  with  sd sw .            /*obtain the terminal screen dimensions*/
oldTime=                                         /*blank out the OLDTIME for comparison.*/
           do until queued()\==0                 /*if user entered some text, then QUIT.*/
           ct= time()                            /*obtain the current  (system)  time.  */
           mn= substr(ct, 4, 2)                  /*extract the minutes part of the time.*/
           ss= right(ct, 2)                      /*   "     "  seconds   "  "   "    "  */
           i_= 0                                 /*REXX variable used for display creep.*/
           p_= 0                                 /*  "      "      "   "     "      "   */
           call blinksec
           if ct==oldTime  then  if !cms  then 'CP SLEEP'       /*sleep for one second. */
                                          else call delay 1     /*  "    "   "     "    */

           if creep  then do;            p_ = 3  + right(mn, 1) /*perform display creep.*/
                          if sd>26  then p_ = p_ +  left(mn, 1)
                          if sd>33  then p_ = p_ +  left(mn, 1)
                          if sd>44  then p_ = p_ +  left(mn, 1) + right(mn, 1)
                          end
           _p= - p_                              /*change the sign of the  P_  number.  */
           i_= 2 + left(ct, 1)                   /*obtain indentation size base on  HH. */
           if sw>108  then ctt= ct               /*maybe use wider  format for the clock*/
                      else ctt= left(ct, 5)      /*maybe use narrow    "    "   "    "  */
           r= $t('.P='_p  ".I="i_  tops  ctt)    /*where the rubber meets the road.     */
           if r\==0   then leave                 /*Had an error in  $T ?   Then quit.   */
           oldTime= time()                       /*save the new time, it may be the same*/
           end   /*forever*/
exit 0                                           /*stick a fork in it,  we're all done. */

/*═════════════════════════════general 1-line subs══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/
!all:  !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
!cal:     if symbol('!CALL')\=="VAR"  then !call=;      return !call
!env:     !env= 'ENVIRONMENT';    if !sys=="MSDOS"  |  !brexx  |  !r4  |  !roo  then !env= 'SYSTEM';    if !os2  then !env= "OS2"!env;    !ebcdic= 3=='f3'x;    if !crx  then !env= "DOS";      return
!fid:     parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .;   call !sys;   if !dos  then do;   _= lastpos('\', !fn);   !fm= left(!fn, _);   !fn= substr(!fn, _+1);   parse var !fn !fn '.' !ft;   end;   return word(0 !fn !ft !fm, 1 +('0'arg(1)))
!rex:     parse upper version !ver !vernum !verdate .; !brexx= 'BY'==!vernum; !kexx= "KEXX"==!ver; !pcrexx= 'REXX/PERSONAL'==!ver | "REXX/PC"==!ver; !r4= 'REXX-R4'==!ver; !regina="REXX-REGINA"==left(!ver, 11); !roo='REXX-ROO'==!ver; call !env; return
!sys:     !cms= !sys=='CMS';    !os2= !sys=="OS2";    !tso= !sys=='TSO'  |  !sys=="MVS";    !vse= !sys=='VSE';    !dos= pos("DOS", !sys)\==0  |  pos('WIN', !sys)\==0  |  !sys=="CMD";    !crx= left(!sys, 6)=='DOSCRX';    call !rex;              return
!var:     call !fid;   if !kexx  then return space( dosenv( arg(1) ) );                      return space( value( arg(1), , !env))
$t:       !call= ']$T';  call "$T"  arg(1);   !call=;                                        return result
abb:      parse upper arg abbu;     parse arg abb;      return abbrev(abbu, _, abbl(abb) )
abbl:     @abc = 'abcdefghijklmnopqrstuvwxyz';          return verify(arg(1)'a', @abc, 'M') - 1
abbn:     parse arg abbn;                               return abb(abbn) | abb('NO'abbn)
blinksec: if \blinksecs  then return;      bsec= ' ';      ss2= right(ss, 2);      if sw<=80  then bsec= copies(" ", 2 + ss2)  ss2;      call scrwrite 1 + right(mn, 1), 1, bsec, , , 1;      call cursor sd - right(mn, 1), sw - length(bsec);     return
er:       parse arg _1,_2;  call '$ERR'  "14"p(_1)  p(word(_1, 2)  !fid(1))  _2;  if _1<0  then return _1;    exit result
err:      call er '-'arg(1),arg(2);                     return ''
erx:      call er '-'arg(1),arg(2);                     exit 0
halt:     call er .1
no:       if arg(1)\==''  then call er 01,arg(2);        return left(_, 2) \== 'NO'
noValue:  !sigl= sigl;         call er 17,!fid(2)  !fid(3)  !sigl          condition('D')  sourceline(!sigl)
p:        return word( arg(1), 1)
syntax:   !sigl= sigl;         call er 13,!fid(2)  !fid(3)  !sigl  !cal()  condition('D')  sourceline(!sigl)


dot_product = (ary1, ary2) ->
  if ary1.length != ary2.length
    throw "can't find dot product: arrays have different lengths"
  dotprod = 0
  for v, i in ary1
    dotprod += v * ary2[i]
  dotprod

console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1 ]) # 3
try
  console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 0 ]) # exception
catch e
  console.log e


(defun dot-product (a b)
  (apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list))))


// version 1.0.6

import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame

class DragonCurve(iter: Int) : JFrame("Dragon Curve") {
    private val turns: MutableList<Int>
    private val startingAngle: Double
    private val side: Double

    init {
        setBounds(100, 100, 800, 600)
        defaultCloseOperation = EXIT_ON_CLOSE
        turns = getSequence(iter)
        startingAngle = -iter * Math.PI / 4
        side = 400.0 / Math.pow(2.0, iter / 2.0)
    }

    fun getSequence(iterations: Int): MutableList<Int> {
        val turnSequence = mutableListOf<Int>()
        for (i in 0 until iterations) {
            val copy = mutableListOf<Int>()
            copy.addAll(turnSequence)
            copy.reverse()
            turnSequence.add(1)
            copy.mapTo(turnSequence) { -it }
        }
        return turnSequence
    }

    override fun paint(g: Graphics) {
        g.color = Color.BLUE
        var angle = startingAngle
        var x1 = 230
        var y1 = 350
        var x2 = x1 + (Math.cos(angle) * side).toInt()
        var y2 = y1 + (Math.sin(angle) * side).toInt()
        g.drawLine(x1, y1, x2, y2)
        x1 = x2
        y1 = y2
        for (turn in turns) {
            angle += turn * Math.PI / 2.0
            x2 = x1 + (Math.cos(angle) * side).toInt()
            y2 = y1 + (Math.sin(angle) * side).toInt()
            g.drawLine(x1, y1, x2, y2)
            x1 = x2
            y1 = y2
        }
    }
}

fun main(args: Array<String>) {
    DragonCurve(14).isVisible = true
}