(********************************************************************)
(* The public interface                                             *)

abstype dllist_t (t : [email protected]+, is_root : bool) (* An abstract type. *)
typedef dllist_t (t : [email protected]+) = [b : bool] dllist_t (t, b)

(* Make a new dllist_t, consisting of a root node. *)
fun {t : [email protected]}
dllist_t_make () : dllist_t (t, true)

(* Is this the root node, with no element stored? *)
fun {t : [email protected]}
dllist_t_is_root
          {is_root : bool}
          (dl : dllist_t (t, is_root)) :
    [b : bool | b == is_root]
    bool b

(* Is this a non-root node, with an element stored? *)
fun {t : [email protected]}
dllist_t_isnot_root
          {is_root : bool}
          (dl : dllist_t (t, is_root)) :
    [b : bool | b == ~is_root]
    bool b

(* Return the root node of the list. *)
fun {t : [email protected]}
dllist_t_root (dl : dllist_t t) : dllist_t (t, true)

(* Return the previous node. *)
fun {t : [email protected]}
dllist_t_previous (dl : dllist_t t) : dllist_t t

(* Return the next node. *)
fun {t : [email protected]}
dllist_t_next (dl : dllist_t t) : dllist_t t

(* Insert an element before the given node. *)
fun {t : [email protected]}
dllist_t_insert_before (dl : dllist_t t, elem : t) : void

(* Insert an element after the given node. *)
fun {t : [email protected]}
dllist_t_insert_after (dl : dllist_t t, elem : t) : void

(* Remove the given node. It is an error to call this on the root
   node. *)
fun {t : [email protected]}
dllist_t_remove (dl : dllist_t t) : void

(* Return a copy of the stored element. It is an error to call this on
   the root node. *)
fun {t : [email protected]}
dllist_t_element (dl: dllist_t t) : t

fun {t : [email protected]}
dllist_t_make_generator (dl: dllist_t t, direction : int) :
    () -<cloref1> Option t

fun {t : [email protected]}
dllist_t_to_list
          (dl : dllist_t t) : [n : nat] list (t, n)

fun {t : [email protected]}
list_to_dllist_t
          {n : int}
          (dl : list (t, n)) : dllist_t t

(********************************************************************)


/* double linked list */
#include <stdio.h>
#include <stdlib.h>

struct List {
   struct MNode *head;
   struct MNode *tail;
   struct MNode *tail_pred;
};

struct MNode {
   struct MNode *succ;
   struct MNode *pred;
};

typedef struct MNode *NODE;
typedef struct List *LIST;

/*
** LIST l = newList()
** create (alloc space for) and initialize a list
*/
LIST newList(void);

/*
** int isEmpty(LIST l)
** test if a list is empty
*/
int isEmpty(LIST);

/*
** NODE n = getTail(LIST l)
** get the tail node of the list, without removing it
*/
NODE getTail(LIST);

/*
** NODE n = getHead(LIST l)
** get the head node of the list, without removing it
*/
NODE getHead(LIST);

/*
** NODE rn = addTail(LIST l, NODE n)
** add the node n to the tail of the list l, and return it (rn==n)
*/
NODE addTail(LIST, NODE);

/*
** NODE rn = addHead(LIST l, NODE n)
** add the node n to the head of the list l, and return it (rn==n)
*/
NODE addHead(LIST, NODE);

/*
** NODE n = remHead(LIST l)
** remove the head node of the list and return it
*/
NODE remHead(LIST);

/*
** NODE n = remTail(LIST l)
** remove the tail node of the list and return it
*/
NODE remTail(LIST);

/*
** NODE rn = insertAfter(LIST l, NODE r, NODE n)
** insert the node n after the node r, in the list l; return n (rn==n)
*/
NODE insertAfter(LIST, NODE, NODE);

/*
** NODE rn = removeNode(LIST l, NODE n)
** remove the node n (that must be in the list l) from the list and return it (rn==n)
*/
NODE removeNode(LIST, NODE);

LIST newList(void)
{
    LIST tl = malloc(sizeof(struct List));
    if ( tl != NULL )
    {
       tl->tail_pred = (NODE)&tl->head;
       tl->tail = NULL;
       tl->head = (NODE)&tl->tail;
       return tl;
    }
    return NULL;
}

int isEmpty(LIST l)
{
   return (l->head->succ == 0);
}

NODE getHead(LIST l)
{
  return l->head;
}

NODE getTail(LIST l)
{
  return l->tail_pred;
}

NODE addTail(LIST l, NODE n)
{
    n->succ = (NODE)&l->tail;
    n->pred = l->tail_pred;
    l->tail_pred->succ = n;
    l->tail_pred = n;
    return n;
}

NODE addHead(LIST l, NODE n)
{
    n->succ = l->head;
    n->pred = (NODE)&l->head;
    l->head->pred = n;
    l->head = n;
    return n;
}

NODE remHead(LIST l)
{
   NODE h;
   h = l->head;
   l->head = l->head->succ;
   l->head->pred = (NODE)&l->head;
   return h;
}

NODE remTail(LIST l)
{
   NODE t;
   t = l->tail_pred;
   l->tail_pred = l->tail_pred->pred;
   l->tail_pred->succ = (NODE)&l->tail;
   return t;
}

NODE insertAfter(LIST l, NODE r, NODE n)
{
   n->pred = r; n->succ = r->succ;
   n->succ->pred = n; r->succ = n;
   return n;
}

NODE removeNode(LIST l, NODE n)
{
   n->pred->succ = n->succ;
   n->succ->pred = n->pred;
   return n;
}


' version 05-04-2017
' compile with: fbc -s gui

Const As Double deg2rad = Atn(1) / 45
Const As UInteger w = 199, h = 199
Const As UInteger x0 = w \ 2, y0 = h \ 2 ' center

Dim As UInteger x, x1, x2, x3, y, y1, y2, y3
Dim As String sys_time, press
Dim As Integer hours, minutes, seconds
Dim As Double angle, a_sin, a_cos

ScreenRes w, h, 8  ' 8bit color depth (palette)
WindowTitle "Simple Clock"

' create image 8bit (palette) and set pixels to 15 (white)
Dim clockdial As Any Ptr = ImageCreate(w, h, 15, 8)

If clockdial = 0 Then
    Print "Failed to create image."
    Sleep
    End -1
End If

' draw clockdial in memory
Circle clockdial, (x0, y0), 94 ,0
Circle clockdial, (x0, y0), 90 ,0

For x = 0 To 174 Step 6
    a_sin = Sin(x * deg2rad)
    a_cos = Cos(x * deg2rad)

    x1 = 94 * a_sin : y1 = 94 * a_cos
    If x Mod 30 = 0 Then
        x2 = 85 * a_sin : y2 = 85 * a_cos
    Else
        x2 = 90 * a_sin : y2 = 90 * a_cos
    End If

    Line clockdial, (x0 + x1, y0 + y1) - (x0 + x2, y0 + y2), 0
    Line clockdial, (x0 - x1, y0 - y1) - (x0 - x2, y0 - y2), 0
Next

'draw clock
Do
    sys_time = Time
    hours   = (sys_time[0] - Asc("0")) * 10 + sys_time[1] - Asc("0")
    minutes = (sys_time[3] - Asc("0")) * 10 + sys_time[4] - Asc("0")
    seconds = (sys_time[6] - Asc("0")) * 10 + sys_time[7] - Asc("0")

    If hours > 12 Then hours -= 12

    angle = (180 - (hours * 30 + minutes / 2)) * deg2rad
    x1 = 65 * Sin(angle)
    y1 = 65 * Cos(angle)

    angle = (180 - (minutes * 6 + seconds / 10)) * deg2rad
    x2 = 80 * Sin(angle)
    y2 = 80 * Cos(angle)

    angle = (180 - seconds * 6) * deg2rad
    x3 = 90 * Sin(angle)
    y3 = 90 * Cos(angle)

    ScreenLock
    ' load image, setting pixels
    Put (0, 0), clockdial, PSet
    Line (x0, y0) - (x0 + x1, y0 + y1), 1   ' hour hand blue
    Line (x0, y0) - (x0 + x2, y0 + y2), 2   ' minute hand green
    Line (x0, y0) - (x0 + x3, y0 + y3), 12  ' second hand red
    ScreenUnLock

    Sleep 300, 1 ' wait 300 ms, don't respond to keys pressed

    ' press esc or mouse click on close window to stop program
    press = InKey
    If press = Chr(27) Or press = Chr(255) + "k" Then Exit Do

Loop

ImageDestroy(clockdial)

End


DIM SHARED angle AS DOUBLE

SUB turn (degrees AS DOUBLE)
    angle = angle + degrees*3.14159265/180
END SUB

SUB forward (length AS DOUBLE)
    LINE - STEP (COS(angle)*length, SIN(angle)*length), 7
END SUB

SUB dragon (length AS DOUBLE, split AS INTEGER, d AS DOUBLE)
    IF split=0 THEN
        forward length
    ELSE
	turn d*45
	dragon length/1.4142136, split-1, 1
	turn -d*90
	dragon length/1.4142136, split-1, -1
	turn d*45
    END IF
END SUB

' Main program

SCREEN 12
angle = 0
PSET (150,180), 0
dragon 400, 12, 1
SLEEP


def project do
  [app: :repo
   version: "0.1.0-dev",
   name: "REPO",
   source_url: "https://github.com/USER/REPO",
   homepage_url: "http://YOUR_PROJECT_HOMEPAGE"
   deps: deps]
end


(defun hello (n)
  "Say hello to the user."
  (message "hello %d" n))


def class Foo {
  """
  This is a docstring. Every object in Fancy can have it's own docstring.
  Either defined in the source code, like this one, or by using the Object#docstring: method
  """
  def a_method {
    """
    Same for methods. They can have docstrings, too.
    """
  }
}
Foo docstring println # prints docstring Foo class
Foo instance_method: 'a_method . docstring println # prints method's docstring


      SUBROUTINE SHOW(A,N)   !Prints details to I/O unit LINPR.
        REAL*8 A    !Distance to the next node.
        INTEGER N   !Number of the current node.


// Example serves as an example but does nothing useful.
//
// A package comment preceeds the package clause and explains the purpose
// of the package.
package example

// Exported variables.
var (
    // lookie
    X, Y, Z int // popular names
)

/* XP does nothing.

Here's a block comment. */
func XP() { // here we go!
    // comments inside
}

// Non-exported.
func nonXP() {}

// Doc not extracted.

var MEMEME int


import java.awt._
import java.awt.event.{MouseAdapter, MouseEvent}

import javax.swing._

import scala.math.{Pi, cos, sin}

object Cuboid extends App {
  SwingUtilities.invokeLater(() => {

    class Cuboid extends JPanel {
      private val nodes: Array[Array[Double]] =
        Array(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1), Array(-1, 1, 1),
          Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1))
      private var mouseX, prevMouseX, mouseY, prevMouseY: Int = _

      private def edges =
        Seq(Seq(0, 1), Seq(1, 3), Seq(3, 2), Seq(2, 0),
          Seq(4, 5), Seq(5, 7), Seq(7, 6), Seq(6, 4),
          Seq(0, 4), Seq(1, 5), Seq(2, 6), Seq(3, 7))

      override def paintComponent(gg: Graphics): Unit = {
        val g = gg.asInstanceOf[Graphics2D]

        def drawCube(g: Graphics2D): Unit = {
          g.translate(getWidth / 2, getHeight / 2)
          for (edge <- edges) {
            g.drawLine(nodes(edge.head)(0).round.toInt, nodes(edge.head)(1).round.toInt,
              nodes(edge(1))(0).round.toInt, nodes(edge(1))(1).round.toInt)
          }
          for (node <- nodes) g.fillOval(node(0).round.toInt - 4, node(1).round.toInt - 4, 8, 8)
        }

        super.paintComponent(gg)
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        drawCube(g)
      }

      private def scale(sx: Double, sy: Double, sz: Double): Unit = {
        for (node <- nodes) {
          node(0) *= sx
          node(1) *= sy
          node(2) *= sz
        }
      }

      private def rotateCube(angleX: Double, angleY: Double): Unit = {
        val (sinX, cosX, sinY, cosY) = (sin(angleX), cos(angleX), sin(angleY), cos(angleY))
        for (node <- nodes) {
          val (x, y, z) = (node.head, node(1), node(2))
          node(0) = x * cosX - z * sinX
          node(2) = z * cosX + x * sinX
          node(1) = y * cosY - node(2) * sinY
          node(2) = node(2) * cosY + y * sinY
        }
      }

      addMouseListener(new MouseAdapter() {
        override def mousePressed(e: MouseEvent): Unit = {
          mouseX = e.getX
          mouseY = e.getY
        }
      })

      addMouseMotionListener(new MouseAdapter() {
        override def mouseDragged(e: MouseEvent): Unit = {
          prevMouseX = mouseX
          prevMouseY = mouseY
          mouseX = e.getX
          mouseY = e.getY
          rotateCube((mouseX - prevMouseX) * 0.01, (mouseY - prevMouseY) * 0.01)
          repaint()
        }
      })

      scale(80, 120, 160)
      rotateCube(Pi / 5, Pi / 9)
      setPreferredSize(new Dimension(640, 640))
      setBackground(Color.white)
    }

    new JFrame("Cuboid") {
      add(new Cuboid, BorderLayout.CENTER)
      pack()
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
      setLocationRelativeTo(null)
      setResizable(false)
      setVisible(true)
    }
  })
}


camera { location  <0.0 , .8 ,-3.0> look_at 0}

light_source{< 3,3,-3> color rgb 1}

sky_sphere { pigment{ gradient <0,1,0> color_map {[0 color rgb <.2,.1,0>][.5 color rgb 1]} scale 2}}

plane {y,-2 pigment { hexagon color rgb .7 color rgb .5 color rgb .6 }}

sphere { 0,1
  texture {
    pigment{ color rgbft <.8,1,1,.4,.4> }
    finish { phong 1 reflection {0.40 metallic 0.5} }
  }
  interior { ior 1.5}
}


import concurrent.{scheduleAtFixedRate, scheduler}

val ROW = 10
val COL = 20
val digits = array( [
  "   __",
  " /  /",
  "/__/ ",
  "     ",
  "    /",
  "   / ",
  "   __",
  "  __/",
  "/__  ",
  "   __",
  "  __/",
  " __/ ",
  "     ",
  " /__/",
  "   / ",
  "   __",
  " /__ ",
  " __/ ",
  "   __",
  " /__ ",
  "/__/ ",
  "   __",
  "    /",
  "   / ",
  "   __",
  " /__/",
  "/__/ ",
  "   __",
  " /__/",
  " __/ "
  ] )
val colon = array( [
  "  ",
  " .",
  ". "
  ] )

def displayTime =
  def pad( n ) = if n < 10 then '0' + n else n

  t = $time
  s = (t + $timeZoneOffset)\1000%86400
  time = pad( s\3600 ) + ':' + pad( s%3600\60 ) + ':' + pad( s%60 )

  for row <- 0:3
    print( if $os.startsWith('Windows') then '\n' else '\u001B[' + (ROW + row) + ';' + COL + 'H' )

    for ch <- time
      print( if ch == ':' then colon(row) else digits(int(ch)*3 + row) )

  println()
  t

if not $os.startsWith( 'Windows' )
  print( '\u001B[2J\u001B[?25l' )

scheduleAtFixedRate( displayTime, 1000 - displayTime()%1000, 1000 )
readLine()
scheduler().shutdown()

if not $os.startsWith( 'Windows' )
  print( '\u001B[?25h' )


package main

import (
	"golang.org/x/net/websocket"
	"flag"
	"fmt"
	"html/template"
	"io"
	"math"
	"net/http"
	"time"
)

var (
	Portnum  string
	Hostsite string
)

type PageSettings struct {
	Host string
	Port string
}

const (
	Canvaswidth  = 512
	Canvasheight = 512
	//color constants
	HourColor   = "#ff7373" // pinkish
	MinuteColor = "#00b7e4" //light blue
	SecondColor = "#b58900" //gold
)

func main() {
	flag.StringVar(&Portnum, "Port", "1234", "Port to host server.")
	flag.StringVar(&Hostsite, "Site", "localhost", "Site hosting server")
	flag.Parse()
	http.HandleFunc("/", webhandler)
	http.Handle("/ws", websocket.Handler(wshandle))
	err := http.ListenAndServe(Hostsite+":"+Portnum, nil)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("server running")
}

func webhandler(w http.ResponseWriter, r *http.Request) {
	wsurl := PageSettings{Host: Hostsite, Port: Portnum}
	template, _ := template.ParseFiles("clock.html")
	template.Execute(w, wsurl)
}

//Given a websocket connection,
//serves updating time function
func wshandle(ws *websocket.Conn) {
	for {
		hour, min, sec := time.Now().Clock()
		hourx, houry := HourCords(hour, Canvasheight/2)
		minx, miny := MinSecCords(min, Canvasheight/2)
		secx, secy := MinSecCords(sec, Canvasheight/2)
		msg := "CLEAR\n"
		msg += fmt.Sprintf("HOUR %d %d %s\n", hourx, houry, HourColor)
		msg += fmt.Sprintf("MIN %d %d %s\n", minx, miny, MinuteColor)
		msg += fmt.Sprintf("SEC %d %d %s", secx, secy, SecondColor)
		io.WriteString(ws, msg)
		time.Sleep(time.Second / 60.0)
	}
}

//Given current minute or second time(i.e 30 min, 60 minutes)
//and the radius, returns pair of cords to draw line to
func MinSecCords(ctime int, radius int) (int, int) {
	//converts min/sec to angle and then to radians

	theta := ((float64(ctime)*6 - 90) * (math.Pi / 180))
	x := float64(radius) * math.Cos(theta)
	y := float64(radius) * math.Sin(theta)
	return int(x) + 256, int(y) + 256
}

//Given current hour time(i.e. 12, 8) and the radius,
//returns pair of cords to draw line to
func HourCords(ctime int, radius int) (int, int) {
	//converts hours to angle and then to radians
	theta := ((float64(ctime)*30 - 90) * (math.Pi / 180))
	x := float64(radius) * math.Cos(theta)
	y := float64(radius) * math.Sin(theta)
	return int(x) + 256, int(y) + 256
}


# Version without functions (for BASIC-256 ver. 0.9.6.66)

graphsize 390,270

level = 18 : insize = 247		# initial values
x = 92 : y = 94	        		#

iters = 2^level		        	# total number of iterations
qiter = 510/iters			# constant for computing colors
SQ = sqrt(2) : QPI = pi/4		# constants

rotation = 0 : iter = 0 : rq = 1.0	# state variables
dim rqs(level)			        # stack for rq (rotation coefficient)

color white
fastgraphics
rect 0,0,graphwidth,graphheight
refresh
gosub dragon
refresh
imgsave "Dragon_curve_BASIC-256.png", "PNG"
end

dragon:
	if level<=0 then
		yn = sin(rotation)*insize + y
		xn = cos(rotation)*insize + x
		if iter*2<iters then
			color 0,iter*qiter,255-iter*qiter
		else
			color qiter*iter-255,(iters-iter)*qiter,0
		end if
		line x,y,xn,yn
		iter = iter + 1
		x = xn : y = yn
		return
	end if
	insize = insize/SQ
	rotation = rotation + rq*QPI
	level = level - 1
	rqs[level] = rq : rq = 1
	gosub dragon
	rotation = rotation - rqs[level]*QPI*2
	rq = -1
	gosub dragon
	rq = rqs[level]
	rotation = rotation + rq*QPI
	level = level + 1
	insize = insize*SQ
	return


      MODE 8
      MOVE 800,400
      GCOL 11
      PROCdragon(512, 12, 1)
      END

      DEF PROCdragon(size, split%, d)
      PRIVATE angle
      IF split% = 0 THEN
        DRAW BY -COS(angle)*size, SIN(angle)*size
      ELSE
        angle += d*PI/4
        PROCdragon(size/SQR(2), split%-1, 1)
        angle -= d*PI/2
        PROCdragon(size/SQR(2), split%-1, -1)
        angle += d*PI/4
      ENDIF
      ENDPROC


`My Hello Message'
Print a greeting to the user.
This is only a short greeting.
{
    show "hello"
}


-- |This is a documentation comment for the following function
square1 :: Int -> Int
square1 x = x * x

-- |It can even
-- span multiple lines
square2 :: Int -> Int
square2 x = x * x

square3 :: Int -> Int
-- ^You can put the comment underneath if you like, like this
square3 x = x * x

{-|
  Haskell block comments
  are also supported
-}
square4 :: Int -> Int
square4 x = x * x

-- |This is a documentation comment for the following datatype
data Tree a = Leaf a | Node [Tree a]

-- |This is a documentation comment for the following type class
class Foo a where
    bar :: a


theory Text
imports Main
begin

chapter ‹Presenting Theories›

text ‹This text will appear in the proof document.›

section ‹Some Examples.›

― ‹A marginal comment. The expression \<^term>‹True› holds.›

lemma True_is_True: "True" ..

text ‹
The overall content of an Isabelle/Isar theory may alternate between formal
and informal text.
›

text_raw ‹Can also contain raw latex.›

text ‹This text will only compile if the fact @{thm True_is_True} holds.›

text ‹This text will only compile if the constant \<^const>‹True› is defined.›

end


NB. =========================================================
NB.*apply v apply verb x to y
apply=: 128!:2

NB. =========================================================
NB.*def c : (explicit definition)
def=: :

NB.*define a : 0 (explicit definition script form)
define=: : 0

NB.*do v name for ".
do=: ".

NB.*drop v name for }.
drop=: }.

   Note 1
Note accepts multi-line descriptions.
Definitions display the source.
)

   usleep
3 : '''libc.so.6 usleep > i i''&(15!:0) >.y'


void setup() {
  size(500, 500, P3D);
}
void draw() {
  background(192);
  translate(width/2, height/2);
  // optional color and lighting style
  stroke(200);
  fill(255);
  lights();
  // draw sphere
  sphere(200);
}


import math

shades = ('.',':','!','*','o','e','&','#','%','@')

def normalize(v):
	len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
	return (v[0]/len, v[1]/len, v[2]/len)

def dot(x,y):
	d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
	return -d if d < 0 else 0

def draw_sphere(r, k, ambient, light):
	for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
		x = i + 0.5
		line = ''

		for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
			y = j/2 + 0.5
			if x*x + y*y <= r*r:
				vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
				b = dot(light,vec)**k + ambient
				intensity = int((1-b)*(len(shades)-1))
				line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
			else:
				line += ' '

		print(line)

light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)


using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        LinkedList<string> list = new LinkedList<string>();
        list.AddFirst(".AddFirst() adds at the head.");
        list.AddLast(".AddLast() adds at the tail.");
        LinkedListNode<string> head = list.Find(".AddFirst() adds at the head.");
        list.AddAfter(head, ".AddAfter() adds after a specified node.");
        LinkedListNode<string> tail = list.Find(".AddLast() adds at the tail.");
        list.AddBefore(tail, "Betcha can't guess what .AddBefore() does.");

        System.Console.WriteLine("Forward:");
        foreach (string nodeValue in list) { System.Console.WriteLine(nodeValue); }

        System.Console.WriteLine("\nBackward:");
        LinkedListNode<string> current = tail;
        while (current != null)
        {
            System.Console.WriteLine(current.Value);
            current = current.Previous;
        }
    }
}


Rot ← ¬⊸{-⌾(𝕨⊸⊑)⌽𝕩}
Turns ← {{𝕩∾1∾¬⌾((⌊2÷˜≠)⊸⊑)𝕩}⍟𝕩 ⥊1}

•Plot´ <˘⍉>+` (<0‿1)(Rot˜)`Turns 3


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

   /**
    * This is a method comment. It has parameter tags (param), an exception tag (throws),
    * and a return value tag (return).
    *
    * @param num a number with the variable name "num"
    * @throws BadException when something bad happens
    * @return another number
    */
   public int method(long num) throws BadException{
      //...code here
   }
}


"Tell whether there are too foo items in the array."
foo(xs::Array) = ...


/**
 * A group of *members*.
 * @author A Programmer.
 * @since version 1.1.51.
 *
 * This class has no useful logic; it's just a documentation example.
 *
 * @param T the type of a member in this group.
 * @property name the name of this group.
 * @constructor Creates an empty group.
 */
class Group<T>(val name: String) {
    /**
     * Adds a [member] to this group.
     * @throws AddException if the member can't be added.
     * @return the new size of the group.
     */
    fun add(member: T): Int { ... }
}


'{def add            // define the name
 {lambda {:a :b}     // for a function with two arguments
  {+ :a :b}          // whose body calls the + primitive on them
 }                   // end function
}                    // end define
-> add

'{add 3 4}           // call the function on two values
-> 7                 // the result


:- object(set(_Type),
	extends(set)).

	% the info/1 directive is the main directive for documenting an entity
	% its value is a list of Key-Value pairs; the set of keys is user-extendable
	:- info([
		version is 1.2,
		author is 'A. Coder',
		date is 2013/10/13,
		comment is 'Set predicates with elements constrained to a single type.',
		parnames is ['Type']
	]).

	% the info/2 directive is the main directive for documenting predicates
	% its second value is a list of Key-Value pairs; the set of keys is user-extendable
	:- public(intersection/3).
	:- mode(intersection(+set, +set, ?set), zero_or_one).
	:- info(intersection/3, [
		comment is 'Returns the intersection of Set1 and Set2.',
		argnames is ['Set1', 'Set2', 'Intersection']
	]).

	...

:- end_object.


--- Converts degrees to radians (summary).
-- Given an angle measure in degrees, return an equivalent angle measure in radians (long description).
-- @param deg the angle measure in degrees
-- @return the angle measure in radians
-- @see rad2deg
function deg2rad(deg) return deg*math.pi/180 end


package require Tcl 8.5
package require Tk
package require math::linearalgebra
package require math::constants

# Helper for constructing a rectangular face in 3D
proc face {px1 py1 pz1 px2 py2 pz2 px3 py3 pz3 px4 py4 pz4 color} {
    set centroidX [expr {($px1+$px2+$px3+$px4)/4.0}]
    set centroidY [expr {($py1+$py2+$py3+$py4)/4.0}]
    set centroidZ [expr {($pz1+$pz2+$pz3+$pz4)/4.0}]
    list [list \
	      [list [expr {double($px1)}] [expr {double($py1)}] [expr {double($pz1)}]] \
	      [list [expr {double($px2)}] [expr {double($py2)}] [expr {double($pz2)}]] \
	      [list [expr {double($px3)}] [expr {double($py3)}] [expr {double($pz3)}]] \
	      [list [expr {double($px4)}] [expr {double($py4)}] [expr {double($pz4)}]]] \
	[list $centroidX $centroidY $centroidZ] \
	$color
}

# How to make a cuboid of given size at the origin
proc makeCuboid {size} {
    lassign $size x y z
    list \
	[face  0  0  0   0 $y  0  $x $y  0  $x  0  0  "#800000"] \
	[face  0  0  0   0 $y  0   0 $y $z   0  0 $z  "#ff8080"] \
	[face  0  0  0  $x  0  0  $x  0 $z   0  0 $z  "#000080"] \
	[face $x  0  0  $x $y  0  $x $y $z  $x  0 $z  "#008000"] \
	[face  0 $y  0  $x $y  0  $x $y $z   0 $y $z  "#80ff80"] \
	[face  0  0 $z  $x  0 $z  $x $y $z   0 $y $z  "#8080ff"]
}

# Project a shape onto a surface (Tk canvas); assumes that the shape's faces
# are simple and non-intersecting (i.e., it sorts by centroid z-order).
proc drawShape {surface shape} {
    global projection
    lassign $projection pmat poff
    lassign $poff px py pz
    foreach side $shape {
	lassign $side points centroid color
	set pc [::math::linearalgebra::matmul $pmat $centroid]
	lappend sorting [list [expr {[lindex $pc 2]+$pz}] $points $color]
    }
    foreach side [lsort -real -decreasing -index 0 $sorting] {
	lassign $side sortCriterion points color
	set plotpoints {}
	foreach p $points {
	    set p [::math::linearalgebra::matmul $pmat $p]
	    lappend plotpoints \
		[expr {[lindex $p 0]+$px}] [expr {[lindex $p 1]+$py}]
	}
	$surface create poly $plotpoints -outline {} -fill $color
    }
}

# How to construct the projection transform.
# This is instead of using a hokey hard-coded version
namespace eval transform {
    namespace import ::math::linearalgebra::*
    ::math::constants::constants pi
    proc make {angle scale offset} {
	variable pi
	set c [expr {cos($angle*$pi/180)}]
	set s [expr {sin($angle*$pi/180)}]
	set ms [expr {-$s}]
	set rotX [list {1.0 0.0 0.0} [list 0.0 $c $ms] [list 0.0 $s $c]]
	set rotY [list [list $c 0.0 $s] {0.0 1.0 0.0} [list $ms 0.0 $c]]
	set rotZ [list [list $c $s 0.0] [list $ms $c 0.0] {0.0 0.0 1.0}]
	set mat [scale $scale [mkIdentity 3]]
	set mat [matmul [matmul [matmul $mat $rotX] $rotY] $rotZ]
	return [list $mat $offset]
    }
}
### End of definitions

# Put the pieces together
pack [canvas .c -width 400 -height 400]
set cuboid [makeCuboid {2 3 4}]
set projection [transform::make 15 50 {100 100 100}]
drawShape .c $cuboid


#lang typed/racket

(require plot/typed)
(plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)


my $width = my $height = 255; # must be odd

my @light = normalize([ 3, 2, -5 ]);

my $depth = 255;

sub MAIN ($outfile = 'sphere-perl6.pgm') {
    spurt $outfile, "P5\n$width $height\n$depth\n"; # .pgm header
    my $out = open( $outfile, :a, :bin ) orelse .die;
    $out.write( Blob.new(draw_sphere( ($width-1)/2, .9, .2) ) );
    $out.close;
}

sub normalize (@vec) { @vec »/» ([+] @vec »*« @vec).sqrt }

sub dot (@x, @y) { -([+] @x »*« @y) max 0 }

sub draw_sphere ( $rad, $k, $ambient ) {
    my @pixels[$height];
    my $r2 = $rad * $rad;
    my @range = -$rad .. $rad;
    @range.hyper.map: -> $x {
        my @row[$width];
        @range.map: -> $y {
            if (my $x2 = $x * $x) + (my $y2 = $y * $y) < $r2 {
                my @vector = normalize([$x, $y, ($r2 - $x2 - $y2).sqrt]);
                my $intensity = dot(@light, @vector) ** $k + $ambient;
                my $pixel = (0 max ($intensity * $depth).Int) min $depth;
                @row[$y+$rad] = $pixel;
            }
            else {
                @row[$y+$rad] = 0;
            }
        }
        @pixels[$x+$rad] = @row;
    }
    flat |@pixels.map: *.list;
}


#include <iostream>
#include <list>

int main ()
{
    std::list<int> numbers {1, 5, 7, 0, 3, 2};
    numbers.insert(numbers.begin(), 9); //Insert at the beginning
    numbers.insert(numbers.end(), 4); //Insert at the end
    auto it = std::next(numbers.begin(), numbers.size() / 2); //Iterator to the middle of the list
    numbers.insert(it, 6); //Insert in the middle
    for(const auto& i: numbers)
        std::cout << i << ' ';
    std::cout << '\n';
}


(ns double-list)

(defprotocol PDoubleList
  (get-head [this])
  (add-head [this x])
  (get-tail [this])
  (add-tail [this x])
  (remove-node [this node])
  (add-before [this node x])
  (add-after [this node x])
  (get-nth [this n]))

(defrecord Node [prev next data])

(defn make-node
  "Create an internal or finalized node"
  ([prev next data] (Node. prev next data))
  ([m key] (when-let [node (get m key)]
            (assoc node :m m :key key))))

(defn get-next [node] (make-node (:m node) (:next node)))
(defn get-prev [node] (make-node (:m node) (:prev node)))

(defn- seq* [m start next]
  (seq
   (for [x (iterate #(get m (next %)) (get m start))
         :while x]
     (:data x))))

(defmacro when->
  ([x pred form] `(let [x# ~x] (if ~pred (-> x# ~form) x#)))
  ([x pred form & more] `(when-> (when-> ~x ~pred ~form) [email protected])))

(declare get-nth-key)

(deftype DoubleList [m head tail]
  Object
    (equals [this x]
      (and (instance? DoubleList x)
           (= m (.m ^DoubleList x))))
    (hashCode [this] (hash (or this ())))
  clojure.lang.Sequential
  clojure.lang.Counted
    (count [_] (count m))
  clojure.lang.Seqable
    (seq [_] (seq* m head :next))
  clojure.lang.Reversible
    (rseq [_] (seq* m tail :prev))
  clojure.lang.IPersistentCollection
    (empty [_] (DoubleList. (empty m) nil nil))
    (equiv [this x]
      (and (sequential? x)
           (= (seq x) (seq this))))
    (cons [this x] (.add-tail this x))
  PDoubleList
    (get-head [_] (make-node m head))
    (add-head [this x]
      (let [new-key (Object.)
            m (when-> (assoc m new-key (make-node nil head x))
                head (assoc-in [head :prev] new-key))
            tail (if tail tail new-key)]
        (DoubleList. m new-key tail)))
    (get-tail [_] (make-node m tail))
    (add-tail [this x]
      (if-let [tail (.get-tail this)]
        (.add-after this tail x)
        (.add-head this x)))
    (remove-node [this node]
      (if (get m (:key node))
        (let [{:keys [prev next key]} node
              head (if prev head next)
              tail (if next tail prev)
              m (when-> (dissoc m key)
                  prev (assoc-in [prev :next] next)
                  next (assoc-in [next :prev] prev))]
          (DoubleList. m head tail))
        this))
    (add-after [this node x]
      (if (get m (:key node))
        (let [{:keys [prev next key]} node
              new-key (Object.)
              m (when-> (-> (assoc m new-key  (make-node key next x))
                            (assoc-in , [key :next] new-key))
                  next (assoc-in [next :prev] new-key))
              tail (if next tail new-key)]
          (DoubleList. m head tail))
        this))
    (add-before [this node x]
      (if (:prev node)
        (.add-after this (get-prev node) x)
        (.add-head this x)))
    (get-nth [this n] (make-node m (get-nth-key this n))))

(defn get-nth-key [^DoubleList this n]
  (if (< -1 n (.count this))
    (let [[start next n] (if (< n (/ (.count this) 2))
                           [(.head this) :next n]
                           [(.tail this) :prev (- (.count this) n 1)])]
      (nth (iterate #(get-in (.m this) [% next]) start) n))
    (throw (IndexOutOfBoundsException.))))

(defn double-list
  ([] (DoubleList. nil nil nil))
  ([coll] (into (double-list) coll)))

(defmethod print-method DoubleList [dl w]
  (print-method (interpose '<-> (seq dl)) w))

(defmethod print-method Node [n w]
  (print-method (symbol "#:double_list.Node") w)
  (print-method (into {} (dissoc n :m)) w))


import Control.Concurrent
import Data.List
import System.Time

-- Library: ansi-terminal
import System.Console.ANSI

number :: (Integral a) => a -> [String]
number 0 =
  ["██████"
  ,"██  ██"
  ,"██  ██"
  ,"██  ██"
  ,"██████"]
number 1 =
  ["    ██"
  ,"    ██"
  ,"    ██"
  ,"    ██"
  ,"    ██"]
number 2 =
  ["██████"
  ,"    ██"
  ,"██████"
  ,"██    "
  ,"██████"]
number 3 =
  ["██████"
  ,"    ██"
  ,"██████"
  ,"    ██"
  ,"██████"]
number 4 =
  ["██  ██"
  ,"██  ██"
  ,"██████"
  ,"    ██"
  ,"    ██"]
number 5 =
  ["██████"
  ,"██    "
  ,"██████"
  ,"    ██"
  ,"██████"]
number 6 =
  ["██████"
  ,"██    "
  ,"██████"
  ,"██  ██"
  ,"██████"]
number 7 =
  ["██████"
  ,"    ██"
  ,"    ██"
  ,"    ██"
  ,"    ██"]
number 8 =
  ["██████"
  ,"██  ██"
  ,"██████"
  ,"██  ██"
  ,"██████"]
number 9 =
  ["██████"
  ,"██  ██"
  ,"██████"
  ,"    ██"
  ,"██████"]

colon :: [String]
colon =
  ["      "
  ,"  ██  "
  ,"      "
  ,"  ██  "
  ,"      "]

newline :: [String]
newline =
  ["\n"
  ,"\n"
  ,"\n"
  ,"\n"
  ,"\n"]

space :: [String]
space =
  [" "
  ," "
  ," "
  ," "
  ," "]

leadingZero :: (Integral a) => a -> [[String]]
leadingZero num =
  let (tens, ones) = divMod num 10
  in [number tens, space, number ones]

fancyTime :: CalendarTime -> String
fancyTime time =
  let hour   = leadingZero $ ctHour time
      minute = leadingZero $ ctMin time
      second = leadingZero $ ctSec time
      nums   = hour ++ [colon] ++ minute ++ [colon] ++ second ++ [newline]
  in concat $ concat $ transpose nums

main :: IO ()
main = do
  time <- getClockTime >>= toCalendarTime
  putStr $ fancyTime time
  threadDelay 1000000
  setCursorColumn 0
  cursorUp 5
  main


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

/* x, y: coordinates of current point; dx, dy: direction of movement.
 * Think turtle graphics.  They are divided by scale, so as to keep
 * very small coords/increments without losing precission. clen is
 * the path length travelled, which should equal to scale at the end
 * of the curve.
 */
long long x, y, dx, dy, scale, clen;
typedef struct { double r, g, b; } rgb;
rgb ** pix;

/* for every depth increase, rotate 45 degrees and scale up by sqrt(2)
 * Note how coords can still be represented by integers.
 */
void sc_up()
{
	long long tmp = dx - dy; dy = dx + dy; dx = tmp;
	scale *= 2; x *= 2; y *= 2;
}

/* Hue changes from 0 to 360 degrees over entire length of path; Value
 * oscillates along the path to give some contrast between segments
 * close to each other spatially.  RGB derived from HSV gets *added*
 * to each pixel reached; they'll be dealt with later.
 */
void h_rgb(long long x, long long y)
{
	rgb *p = &pix[y][x];

#	define SAT 1
	double h = 6.0 * clen / scale;
	double VAL = 1 - (cos(3.141592653579 * 64 * clen / scale) - 1) / 4;
	double c = SAT * VAL;
	double X = c * (1 - fabs(fmod(h, 2) - 1));

	switch((int)h) {
	case 0: p->r += c; p->g += X; return;
	case 1:	p->r += X; p->g += c; return;
	case 2: p->g += c; p->b += X; return;
	case 3: p->g += X; p->b += c; return;
	case 4: p->r += X; p->b += c; return;
	default:
		p->r += c; p->b += X;
	}
}

/* string rewriting.  No need to keep the string itself, just execute
 * its instruction recursively.
 */
void iter_string(const char * str, int d)
{
	long tmp;
#	define LEFT  tmp = -dy; dy = dx; dx = tmp
#	define RIGHT tmp = dy; dy = -dx; dx = tmp
	while (*str != '\0') {
		switch(*(str++)) {
		case 'X':	if (d) iter_string("X+YF+", d - 1); continue;
		case 'Y':	if (d) iter_string("-FX-Y", d - 1); continue;
		case '+':	RIGHT; continue;
		case '-':	LEFT;  continue;
		case 'F':
                        /* draw: increment path length; add color; move. Here
                         * is why the code does not allow user to choose arbitrary
                         * image size: if it's not a power of two, aliasing will
                         * occur and grid-like bright or dark lines will result
                         * when normalized later.  It can be gotten rid of, but that
                         * involves computing multiplicative order and would be a huge
                         * bore.
                         */
				clen ++;
				h_rgb(x/scale, y/scale);
				x += dx; y += dy;
				continue;
		}
	}
}

void dragon(long leng, int depth)
{
	long i, d = leng / 3 + 1;
	long h = leng + 3, w = leng + d * 3 / 2 + 2;

	/* allocate pixel buffer */
	rgb *buf = malloc(sizeof(rgb) * w * h);
	pix = malloc(sizeof(rgb *) * h);
	for (i = 0; i < h; i++)
		pix[i] = buf + w * i;
	memset(buf, 0, sizeof(rgb) * w * h);

        /* init coords; scale up to desired; exec string */
	x = y = d; dx = leng; dy = 0; scale = 1; clen = 0;
	for (i = 0; i < depth; i++) sc_up();
	iter_string("FX", depth);

	/* write color PNM file */
	unsigned char *fpix = malloc(w * h * 3);
	double maxv = 0, *dbuf = (double*)buf;

        /* find highest value among pixels; normalize image according
         * to it.  Highest value would be at points most travelled, so
         * this ends up giving curve edge a nice fade -- it's more apparaent
         * if we increase iteration depth by one or two.
         */
	for (i = 3 * w * h - 1; i >= 0; i--)
		if (dbuf[i] > maxv) maxv = dbuf[i];
	for (i = 3 * h * w - 1; i >= 0; i--)
		fpix[i] = 255 * dbuf[i] / maxv;

	printf("P6\n%ld %ld\n255\n", w, h);
	fflush(stdout); /* printf and fwrite may treat buffer differently */
	fwrite(fpix, h * w * 3, 1, stdout);
}

int main(int c, char ** v)
{
	int size, depth;

	depth  = (c > 1) ? atoi(v[1]) : 10;
	size = 1 << depth;

	fprintf(stderr, "size: %d depth: %d\n", size, depth);
	dragon(size, depth * 2);

	return 0;
}


f[x_,y_] := x + y (* Function comment : adds two numbers *)
f::usage = "f[x,y] gives the sum of x and y"

?f
-> f[x,y] gives the sum of x and y


function Gnash(GnashFile);	%Convert to a "function". Data is placed in the "global" area.
%   My first MatLab attempt, to swallow data as produced by Gnash's DUMP
%command in a comma-separated format. Such files start with a line


## Nim directly supports documentation using comments that start with two
## hashes (##). To create the documentation run ``nim doc file.nim``.
## ``nim doc2 file.nim`` is the same, but run after semantic checking, which
## allows it to process macros and output more information.
##
## These are the comments for the entire module.  We can have long descriptions
## here. Syntax is reStructuredText. Only exported symbols (*) get
## documentation created for them.
##
## Here comes a code block inside our documentation:
##
## .. code-block:: nim
##   var inputStrings : seq[string]
##   newSeq(inputStrings, 3)
##   inputStrings[0] = "The fourth"
##   inputStrings[1] = "assignment"
##   inputStrings[2] = "would crash"
##   #inputStrings[3] = "out of bounds"

type TPerson* = object
  ## This type contains a description of a person
  name: string
  age: int

var numValues*: int ## \
  ## `numValues` stores the number of values

proc helloWorld*(times: int) =
  ## A useful procedure
  for i in 1..times:
    echo "hello world"


#~
Sets the named row value
@param name name
@param value value
@return true of value was set, false otherwise
~#
method : public : Set(name : String, value : String) ~ Bool {
  return Set(@table->GetRowId(name), value);
}


/*!
 @function add
 @abstract Adds two numbers
 @discussion Use add to sum two numbers.
 @param a an integer.
 @param b another integer.
 @return the sum of a and b
 */
int add(int a, int b) {
    return a + b;
}


; note: use this script to generate a markdown file
; sed -n 's/\s*;!\s*//gp'

(import (owl parse))

;! # Documentation

;! ## Functions

;! ### whitespace
;! Returns a #true if argument is a space, newline, return or tab character.
   (define whitespace (byte-if (lambda (x) (has? '(#\tab #\newline #\space #\return) x))))

;! ### maybe-whitespaces
;! Returns any amount (including 0) of whitespaces. Used as whitespace characters skipper in parses.
   (define maybe-whitespaces (greedy* whitespace))


x = 6 : y = 2 : z = 3

Sub cuboid(nx, ny, nz)
   WScript.StdOut.WriteLine "Cuboid " & nx & " " & ny & " " & nz & ":"
   lx = X * nx : ly = y * ny : lz = z * nz

   'define the array
   Dim area(): ReDim area(ly+lz, lx+ly)
   For i = 0 to ly+lz
      For j = 0 to lx+ly : area(i,j) = " " : Next
   Next

   'drawing lines
   For i = 0 to nz-1 : drawLine area, lx,      0,    Z*i, "-" : Next
   For i = 0 to ny   : drawLine area, lx,    y*i, lz+y*i, "-" : Next
   For i = 0 to nx-1 : drawLine area, lz,    x*i,      0, "|" : Next
   For i = 0 to ny   : drawLine area, lz, lx+y*i,    y*i, "|" : Next
   For i = 0 to nz-1 : drawLine area, ly,     lx,    z*i, "/" : Next
   For i = 0 to nx   : drawLine area, ly,    x*i,     lz, "/" : Next

   'output the cuboid (in reverse)
   For i = UBound(area,1) to 0 Step -1
      linOut = ""
      For j = 0 to UBound(area,2) : linOut = linOut & area(i,j) : Next
      WScript.StdOut.WriteLine linOut
   Next
End Sub

Sub drawLine(arr, n, sx, sy, c)
   Select Case c
      Case "-"
         dx = 1 : dy = 0
      Case "|"
         dx = 0 : dy = 1
      Case "/"
         dx = 1 : dy = 1
   End Select
   For i = 0 to n
      xi = sx + (i * dx) : yi = sy + (i * dy)
      If arr(yi, xi) = " " Then
         arr(yi, xi) = c
      Else
         arr(yi, xi) = "+"
      End If
   Next
End Sub

cuboid 2,3,4


import "/fmt" for Fmt

var cubLine = Fn.new { |n, dx, dy, cde|
    Fmt.write("$*s", n + 1, cde[0])
    for (d in 9*dx - 1...0) System.write(cde[1])
    System.write(cde[0])
    Fmt.print("$*s", dy + 1, cde[2..-1])
}

var cuboid = Fn.new { |dx, dy, dz|
    Fmt.print("cuboid $d $d $d:", dx, dy, dz)
    cubLine.call(dy+1, dx, 0, "+-")
    for (i in 1..dy) cubLine.call(dy-i+1, dx, i-1, "/ |")
    cubLine.call(0, dx, dy, "+-|")
    for (i in 4*dz - dy - 2...0) cubLine.call(0, dx, dy, "| |")
    cubLine.call(0, dx, dy, "| +")
    for (i in 1..dy) cubLine.call(0, dx, dy-i, "| /")
    cubLine.call(0, dx, 0, "+-\n")
}

cuboid.call(2, 3, 4)
cuboid.call(1, 1, 1)
cuboid.call(6, 2, 1)


/*REXX program expresses a  lighted sphere  with  simple characters  used for shading.  */
call drawSphere  19,  4,   2/10,  '30 30 -50'    /*draw a sphere with a radius of  19.  */
call drawSphere  10,  2,   4/10,  '30 30 -50'    /*  "  "    "     "  "    "    "  ten. */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ceil:  procedure;   parse arg x;  _= trunc(x);                    return _ +(x>0) * (x\=_)
floor: procedure;   parse arg x;  _= trunc(x);                    return _ -(x<0) * (x\=_)
norm:  parse arg $a $b $c;        _= sqrt($a**2 + $b**2 + $c**2); return  $a/_  $b/_  $c/_
/*──────────────────────────────────────────────────────────────────────────────────────*/
drawSphere: procedure;  parse arg r, k, ambient, lightSource /*obtain the four arguments*/
       if 8=='f8'x  then shading= ".:!*oe&#%@"               /* EBCDIC dithering chars. */
                    else shading= "·:!°[email protected]░▒▓"               /* ASCII      "       "    */
       parse value  norm(lightSource)    with    s1  s2  s3  /*normalize light source.  */
       shadeLen= length(shading) - 1;    rr= r**2;   r2= r+r /*handy─dandy variables.   */

         do   i=floor(-r )  to ceil(r );   x= i       + .5;       xx= x**2;       $=
           do j=floor(-r2)  to ceil(r2);   y= j * .5  + .5;       yy= y**2;       z= xx+yy
           if z<=rr  then do                                 /*is point within sphere ? */
                          parse value  norm(x  y  sqrt(rr - xx - yy) )   with   v1  v2  v3
                          dot= min(0, s1*v1 + s2*v2 + s3*v3) /*the dot product of above.*/
                          b= -dot**k  +  ambient             /*calculate the brightness.*/
                          if b<=0  then brite= shadeLen
                                   else brite= max(0,  (1-b) * shadeLen)  % 1
                          $= $ || substr(shading, brite + 1,  1)
                          end                                /* [↑]  build display line.*/
                     else $= $' '                            /*append a blank to line.  */
           end   /*j*/                                       /*[↓] strip trailing blanks*/
         say strip($, 'T')                                   /*show a line of the sphere*/
         end     /*i*/                                       /* [↑]  display the sphere.*/
       return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt:  procedure; parse arg x;  if x=0  then return 0; d= digits(); numeric digits; h= d+6
       numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g= g*.5'e'_%2
         do j=0  while h>9;      m.j=h;              h=h%2+1;        end  /*j*/
         do k=j+5  to 0  by -1;  numeric digits m.k; g=(g+x/g)*.5;   end  /*k*/;  return g


(defstruct dlist head tail)
(defstruct dlink content prev next)

(defun insert-between (dlist before after data)
  "Insert a fresh link containing DATA after existing link BEFORE if not nil and before existing link AFTER if not nil"
  (let ((new-link (make-dlink :content data :prev before :next after)))
    (if (null before)
        (setf (dlist-head dlist) new-link)
        (setf (dlink-next before) new-link))
    (if (null after)
        (setf (dlist-tail dlist) new-link)
        (setf (dlink-prev after) new-link))
    new-link))

(defun insert-before (dlist dlink data)
  "Insert a fresh link containing DATA before existing link DLINK"
  (insert-between dlist (dlink-prev dlink) dlink data))

(defun insert-after (dlist dlink data)
  "Insert a fresh link containing DATA after existing link DLINK"
  (insert-between dlist dlink (dlink-next dlink) data))

(defun insert-head (dlist data)
  "Insert a fresh link containing DATA at the head of DLIST"
  (insert-between dlist nil (dlist-head dlist) data))

(defun insert-tail (dlist data)
  "Insert a fresh link containing DATA at the tail of DLIST"
  (insert-between dlist (dlist-tail dlist) nil data))

(defun remove-link (dlist dlink)
  "Remove link DLINK from DLIST and return its content"
  (let ((before (dlink-prev dlink))
        (after (dlink-next dlink)))
    (if (null before)
        (setf (dlist-head dlist) after)
        (setf (dlink-next before) after))
    (if (null after)
        (setf (dlist-tail dlist) before)
        (setf (dlink-prev after) before))))

(defun dlist-elements (dlist)
  "Returns the elements of DLIST as a list"
  (labels ((extract-values (dlink acc)
             (if (null dlink)
                 acc
                 (extract-values (dlink-next dlink) (cons (dlink-content dlink) acc)))))
    (reverse (extract-values (dlist-head dlist) nil))))


link graphics

global  xsize,
        ysize,
        fontsize

procedure main(args)
    if *args > 0 then xsize := ysize := numeric(args[1])

    /xsize := /ysize := 200
    WIN := WOpen("size=" || xsize || "," || ysize, "label=Clock", "resize=on") | stop("Fenster geht nicht auf!", image(xsize), " - ", image(ysize))
    ziffernblatt()

    repeat
    {   write(&time)

        if *Pending(WIN) > 1 then while *Pending() > 0 do
        {   e := Event()
            ziffernblatt()
        }

        Fg("#CFB53B")
        FillCircle(xsize/2, ysize/2, xsize/2 * 0.81)
        Fg("black")

        clock := &clock
        sec  := clock[7:0]
        min  := clock[4:6]
        hour := clock[1:3]

        if fontsize > 7 then
        {   #Fg("yellow")
            EraseArea(10,0, TextWidth(clock),WAttrib("fheight"))
            DrawString(10,fontsize, clock)
        }

        draw_zeiger(hour, min, sec)

        WFlush()
        delay(100)
    }
end

procedure ziffernblatt()
        xsize := WAttrib("width")
        ysize := WAttrib("height")
        if xsize < ysize then ysize := xsize
        if ysize < xsize then xsize := ysize

        EraseArea(0,0,WAttrib("width"),WAttrib("height"))

        Fg("#CFB53B")
        FillCircle(xsize/2, ysize/2, xsize/2)
        Fg("black")
        fontsize := fontsize := 30 * xsize / 800.0

        every i := 1 to 60 do
        {   winkel := 6 * i / 180.0 * &pi
            if i % 5 = 0 then
            {   laenge := 0.95
                if fontsize > 15 then
                {   Font("mono," || integer(fontsize) || ",bold")
                    WAttrib("linewidth=3")
                }
                if fontsize > 8 then
                {   Font("sans," || integer(fontsize))
                    WAttrib("linewidth=2")
                }

                if fontsize > 8 then DrawString(xsize/2 + 0.90 * xsize/2 * sin(winkel) - fontsize / 2, ysize/2 - 0.90 * ysize/2 * cos(winkel) + fontsize/2, (i/5)("I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"))
            }
            else laenge := 0.98
            if fontsize >= 5 then DrawLine(xsize/2 + laenge * xsize/2 * sin(winkel), ysize/2 - laenge * ysize/2 * cos(winkel), xsize/2 + 0.99 * xsize/2 * sin(winkel), ysize/2 - 0.99 * ysize/2 * cos(winkel))
            if fontsize < 5 then if i % 5 = 0 then
            {   WAttrib("linewidth=1")
                DrawLine(xsize/2 + laenge * xsize/2 * sin(winkel), ysize/2 - laenge * ysize/2 * cos(winkel), xsize/2 + 0.99 * xsize/2 * sin(winkel), ysize/2 - 0.99 * ysize/2 * cos(winkel))
            }
        }
        clock := &clock
        sec  := clock[7:0]
        min  := clock[4:6]
        hour := clock[1:3]

        if fontsize > 7 then
        {   EraseArea(10,0, TextWidth(clock),WAttrib("fheight"))
            DrawString(10,fontsize, clock)
        }
        draw_zeiger(hour, min, sec)

        Fg("#D4AF37")
        FillCircle(xsize/2, ysize/2, 5)
        Fg("black")
        WAttrib("linewidth=2")

        DrawCircle(xsize/2, ysize/2,5)

end

procedure draw(laenge, breite, winkel)
    WAttrib("linewidth=" || breite)
    DrawLine(xsize/2,ysize/2,xsize/2 + laenge * sin(winkel), ysize/2 - laenge * cos(winkel))
end

procedure draw_zeiger(h, m, s)
    wh := 30 * ((h % 12) + m / 60.0 + s / 3600.0) / 180 * &pi
    wm := 6 * (m + s / 60.0) / 180.0 * &pi
    ws := 6 * s / 180.0 * &pi

    draw(xsize/2 * 0.5, 5, wh) # Stundenzeiger
    draw(xsize/2 * 0.65, 3, wm) # Minutenzeiger
    draw(xsize/2 * 0.80, 1, ws) # Sekundenzeiger
end


using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public class DragonCurve : Form
{
    private List<int> turns;
    private double startingAngle, side;

    public DragonCurve(int iter)
    {
        Size = new Size(800, 600);
        StartPosition = FormStartPosition.CenterScreen;
        DoubleBuffered = true;
        BackColor = Color.White;

        startingAngle = -iter * (Math.PI / 4);
        side = 400 / Math.Pow(2, iter / 2.0);

        turns = getSequence(iter);
    }

    private List<int> getSequence(int iter)
    {
        var turnSequence = new List<int>();
        for (int i = 0; i < iter; i++)
        {
            var copy = new List<int>(turnSequence);
            copy.Reverse();
            turnSequence.Add(1);
            foreach (int turn in copy)
            {
                turnSequence.Add(-turn);
            }
        }
        return turnSequence;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

        double angle = startingAngle;
        int x1 = 230, y1 = 350;
        int x2 = x1 + (int)(Math.Cos(angle) * side);
        int y2 = y1 + (int)(Math.Sin(angle) * side);
        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
        x1 = x2;
        y1 = y2;
        foreach (int turn in turns)
        {
            angle += turn * (Math.PI / 2);
            x2 = x1 + (int)(Math.Cos(angle) * side);
            y2 = y1 + (int)(Math.Sin(angle) * side);
            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);
            x1 = x2;
            y1 = y2;
        }
    }

    [STAThread]
    static void Main()
    {
        Application.Run(new DragonCurve(14));
    }
}


addhelp(funcName, "funcName(v, n): This is a description of the function named funcName.");


procedure StoreVar(integer N, integer NTyp)
--
-- Store a variable, applying any final operator as needed.
-- If N is zero, PopFactor (ie store in a new temporary variable of
--  the specified type). Otherwise N should be an index to symtab.
-- If storeConst is 1, NTyp is ignored/overridden, otherwise it
--  should usually be the declared or local type of N.
--
    ...
end procedure


: (doc 'car)         # View documentation of a function

: (doc '+Entity)     # View documentation of a class

: (doc '+ 'firefox)  # Explicitly specify a browser


      1                                  ;Assemble with: tasm, tlink /t
      2     0000                                 .model  tiny
      3     0000                                 .code
      4                                          .386
      5                                          org     100h
      6                                  ;assume: ax=0000h, bx=0000h, cx=00ff, and
      7                                  ; direction bit is clear (so di increments)
      8                                                                  ;                  ____
      9           =0050                  X0      equ     80              ;                 /   /|
     10           =0050                  Y0      equ     80              ;                /   / |
     11           =0050                  wide    equ     2*40            ;         X0,Y0 +---+  |
     12           =0064                  tall    equ     3*40*200/240    ;               |   |  |
     13           =0035                  deep    equ     4*40/3          ;               |   | /
     14                                                                  ;               |___|/
     15
     16     0100  B0 13                  start:  mov     al, 13h         ;set 320x200x8 graphic screen
     17     0102  CD 10                          int     10h
     18     0104  68 A000                        push    0A000h          ;point es to graphic memory segment
     19     0107  07                             pop     es
     20
     21                                  ;Draw front of cuboid using horizontal lines
     22     0108  B3 64                          mov     bl, tall
     23     010A  BF E150                        mov     di, X0+(Y0+tall)*320 ;set pen at lower-left corner
     24     010D  B0 04                          mov     al, 4           ;use red ink
     25     010F  B1 50                  dc10:   mov     cl, wide        ;draw horizontal line
     26     0111  F3> AA                         rep     stosb           ;es:[di++], al; cx--
     27     0113  81 EF 0190                     sub     di, wide+320    ;move up to start of next line
     28     0117  4B                             dec     bx              ;at top of face?
     29     0118  75 F5                          jne     dc10            ;loop if not
     30
     31     011A  B3 35                          mov     bl, deep
     32                                  ;Draw top using horizontal lines
     33     011C  B0 02                  dc20:   mov     al, 2           ;use green ink
     34     011E  B1 50                          mov     cl, wide        ;draw horizontal line
     35     0120  F3> AA                         rep     stosb           ;es:[di++], al; cx--
     36
     37                                  ;Draw side using vertical lines
     38     0122  B0 01                          mov     al, 1           ;use blue ink
     39     0124  B1 64                          mov     cl, tall        ;draw vertical line
     40     0126  AA                     dc30:   stosb                   ;es:[di++], al
     41     0127  81 C7 013F                     add     di, 320-1       ;move down a pixel
     42     012B  E2 F9                          loop    dc30
     43
     44     012D  81 EF 7E8F                     sub     di, wide+(tall+1)*320-1 ;move to start of next top line
     45     0131  4B                             dec     bx              ;at deep limit?
     46     0132  75 E8                          jne     dc20            ;loop if not
     47
     48     0134  CD 16                          int     16h             ;wait for keystroke (ah=0)
     49     0136  B8 0003                        mov     ax, 0003h       ;restore normal text-mode screen
     50     0139  CD 10                          int     10h
     51     013B  C3                             ret                     ;return to DOS
     52
     53                                          end     start


import std.stdio;

class LinkedList(T)
{
 Node!(T) head, tail;

 /** Iterate in the forward direction. */
 int opApply (int delegate(uint, Node!(T)) dg)
 {
  uint i = 0;
  auto link = head;
  int result = 0;
  while (link)
  {
   result = dg (i, link);
   if (result) return result;
   i++;
   link = link.next;
  }
  return result;
 }

 static LinkedList!(T) fromArray (T[] array)
 {
  Node!(T) link = null;
  auto head = link;
  auto self = new LinkedList!(T);
  foreach (elem; array)
  {
   link = new Node!(T)(null, link, elem, self);
   if (!head)
    head = link;
  }
  return self;
 }
}

class Node(T)
{
 Node!(T) next;
 Node!(T) previous;
 LinkedList!(T) parent;
 T value;

 this (Node!(T) next, Node!(T) previous, T value, LinkedList!(T) parent)
 in
 {
  assert (parent !is null);
 }
 body
 {
  this.next = next;
  if (next)
   next.previous = this;
  if (previous)
   previous.next = this;
  this.previous = previous;
  this.value = value;
  this.parent = parent;

  if (parent.head == next)
   parent.head = this;
  if (parent.tail == previous)
   parent.tail = this;
 }

 /** Insert an element after this one. */
 void insertAfter (T value)
 {
  new Node!(T)(next, this, value, parent);
 }

 /** Insert an element before this one. */
 void insertBefore (T value)
 {
  new Node!(T)(this, previous, value, parent);
 }

 /** Remove the current node from the list. */
 void remove ()
 {
  if (next)
   next.previous = previous;
  if (previous)
   previous.next = next;
  if (parent.tail == this)
   parent.tail = previous;
  if (parent.head == this)
   parent.head = next;
 }
}

void main ()
{
 string[] sample = ["was", "it", "a", "cat", "I", "saw"];
 auto list = LinkedList!string.fromArray (sample);
 for (auto elem = list.head; elem; elem = elem.next)
 {
  writef ("%s ", elem.value);
  if (elem.value == "it") elem.insertAfter("really");
 }
 writeln;
 for (auto elem = list.tail; elem; elem = elem.previous)
 {
  writef ("%s ", elem.value);
 }
 writeln;
}


with Ada.Text_IO;  use Ada.Text_IO;
with GNAT.Sockets; use GNAT.Sockets;

procedure DNSQuerying is

   Host         : Host_Entry_Type (1, 1);
   Inet_Addr_V4 : Inet_Addr_Type (Family_Inet);
begin

   Host         := Get_Host_By_Name (Name => "www.kame.net");
   Inet_Addr_V4 := Addresses (Host);
   Put ("IPv4: " & Image (Value => Inet_Addr_V4));
end DNSQuerying;


{{
  require'gl2'
  coinsert 'jgl2'
  clock_face_paint=: {{
    try.
      'H M S'=. _3{.6!:0''
      glclear''
      center=. 2-~<.-:glqwh''
      glpen 2: glrgb 0 0 0 255
      glellipse 1+,0 2*/center
      center {{ gllines <.2+(m,m)+,0.97 1*/m*+.j.y}}"0^j.2r12p1*i.12
      center {{ gllines <.2+(m,m)+,0.92 0.99*/m*+.j.y}}"0^j.2r4p1*i.4
      hand=: center {{
        glpen 2: glbrush glrgb<.4{.255*x,4#1
        gllines<.2+m,m*1++.j.n*^j.1p1+y
        EMPTY
      }}
      1 0 0 (0.8) hand 2r60p1*S
      0 1 0 (0.7) hand 2r60p1*M+60%~S
      0 0 1 (0.4) hand 2r12p1*H+60%~M+60%~S
    catch.
      echo 13!:12''
    end.
    EMPTY
  }}
  clock_timer=: glpaint
  wd {{)n
    pc clock closeok;
    cc face isigraph;
    set face wh 200 200;
    ptimer 100;
    pshow;
}}
}}1


#include <windows.h>
#include <iostream>

//-----------------------------------------------------------------------------------------
using namespace std;

//-----------------------------------------------------------------------------------------
const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;

//-----------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap()
    {
	DeleteObject( pen ); DeleteObject( brush );
	DeleteDC( hdc ); DeleteObject( bmp );
    }

    bool create( int w, int h )
    {
	BITMAPINFO bi;
	ZeroMemory( &bi, sizeof( bi ) );
	bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );
	bi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;
	bi.bmiHeader.biCompression = BI_RGB;
	bi.bmiHeader.biPlanes      = 1;
	bi.bmiHeader.biWidth       =  w;
	bi.bmiHeader.biHeight      = -h;

	HDC dc = GetDC( GetConsoleWindow() );
	bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
	if( !bmp ) return false;

	hdc = CreateCompatibleDC( dc );
	SelectObject( hdc, bmp );
	ReleaseDC( GetConsoleWindow(), dc );

	width = w; height = h;
	return true;
    }

    void clear( BYTE clr = 0 )
    {
	memset( pBits, clr, width * height * sizeof( DWORD ) );
    }

    void setBrushColor( DWORD bClr )
    {
	if( brush ) DeleteObject( brush );
	brush = CreateSolidBrush( bClr );
	SelectObject( hdc, brush );
    }

    void setPenColor( DWORD c )
    {
	clr = c; createPen();
    }

    void setPenWidth( int w )
    {
	wid = w; createPen();
    }

    void saveBitmap( string path )
     {
	BITMAPFILEHEADER fileheader;
	BITMAPINFO       infoheader;
	BITMAP           bitmap;
	DWORD            wb;

	GetObject( bmp, sizeof( bitmap ), &bitmap );
	DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];

	ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
	ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
	ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

	infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
	infoheader.bmiHeader.biCompression = BI_RGB;
	infoheader.bmiHeader.biPlanes = 1;
	infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
	infoheader.bmiHeader.biHeight = bitmap.bmHeight;
	infoheader.bmiHeader.biWidth = bitmap.bmWidth;
	infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

	fileheader.bfType    = 0x4D42;
	fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
	fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

	GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

	HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
	WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
	WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
	CloseHandle( file );

	delete [] dwpBits;
    }

    HDC getDC() const     { return hdc; }
    int getWidth() const  { return width; }
    int getHeight() const { return height; }

private:
    void createPen()
    {
	if( pen ) DeleteObject( pen );
	pen = CreatePen( PS_SOLID, wid, clr );
	SelectObject( hdc, pen );
    }

    HBITMAP bmp;
    HDC     hdc;
    HPEN    pen;
    HBRUSH  brush;
    void    *pBits;
    int     width, height, wid;
    DWORD   clr;
};
//-----------------------------------------------------------------------------------------
class dragonC
{
public:
    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }
    void draw( int iterations ) { generate( iterations ); draw(); }

private:
    void generate( int it )
    {
	generator.push_back( 1 );
	string temp;

	for( int y = 0; y < it - 1; y++ )
	{
	    temp = generator; temp.push_back( 1 );
	    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )
		temp.push_back( !( *x ) );

	    generator = temp;
	}
    }

    void draw()
    {
	HDC dc = bmp.getDC();
	unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };
	int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;

	for( int t = 0; t < 4; t++ )
	{
	    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];
	    MoveToEx( dc, a, b, NULL );

	    bmp.setPenColor( clr[t] );
	    for( string::iterator x = generator.begin(); x < generator.end(); x++ )
	    {
		switch( dir )
		{
		    case NORTH:
			if( *x ) { a += LEN; dir = EAST; }
			else { a -= LEN; dir = WEST; }
		    break;
		    case EAST:
			if( *x ) { b += LEN; dir = SOUTH; }
			else { b -= LEN; dir = NORTH; }
		    break;
		    case SOUTH:
			if( *x ) { a -= LEN; dir = WEST; }
			else { a += LEN; dir = EAST; }
		    break;
		    case WEST:
			if( *x ) { b -= LEN; dir = NORTH; }
			else { b += LEN; dir = SOUTH; }
		}
	        LineTo( dc, a, b );
	    }
	}
	// !!! change this path !!!
	bmp.saveBitmap( "f:/rc/dragonCpp.bmp" );
    }

    int dir;
    myBitmap bmp;
    string generator;
};
//-----------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    dragonC d; d.draw( 17 );
    return system( "pause" );
}
//-----------------------------------------------------------------------------------------


; This is a small demo-code to demonstrate PureBasic’s internal
; documentation system.

;- All Includes
; By starting the line with ‘;-‘ marks that specific line as a special comment,
; and this will be included in the overview, while normal comments will not.

IncludeFile "MyLibs.pbi"
IncludeFile "Combustion_Data.pbi"

;-
;- Start of functions and Macros
;- Engeneering stuff

; A small function to calculate gas properties
Procedure.f CalcR( p.f, V.f, T.f)
  ProcedureReturn p*V/T
EndProcedure

; Example of a Macro
; These are indicated by '+' in the overview
Macro HalfPI()
  (#PI/2)
EndMacro

;-
;- - - - - - - - - - -
;- IO-Functions

Procedure Write_and_Close( File, Text$)
  If IsFile(File)
    WriteString(File,Text$)
    CloseFile(file)
  EndIf
EndProcedure


class Doc(object):
   """
   This is a class docstring. Traditionally triple-quoted strings are used because
   they can span multiple lines and you can include quotation marks without escaping.
   """
   def method(self, num):
      """This is a method docstring."""
      pass


#lang scribble/manual
(require (for-label "sandwiches.rkt"))

@defproc[(make-sandwich [ingredients (listof ingredient?)])
         sandwich?]{
  Returns a sandwich given the right ingredients.
}


#= it's yellow
sub marine { ... }
say &marine.WHY; # "it's yellow"

#= a shaggy little thing
class Sheep {
    #= not too scary
    method roar { 'roar!' }
}
say Sheep.WHY; # "a shaggy little thing"
say Sheep.^find_method('roar').WHY; # "not too scary"


include c:\cxpl\codes;                  \intrinsic 'code' declarations
real X, Y, Z, Farthest;                 \arrays: 3D coordinates of vertices
int  I, J, K, SI, Segment;
def  Size=50.0, Sz=0.008, Sx=-0.013;    \drawing size and tumbling speeds
[X:= [-2.0, +2.0, +2.0, -2.0,  -2.0, +2.0, +2.0, -2.0];
 Y:= [-1.5, -1.5, +1.5, +1.5,  -1.5, -1.5, +1.5, +1.5];
 Z:= [-1.0, -1.0, -1.0, -1.0,  +1.0, +1.0, +1.0, +1.0];
Segment:= [0,1, 1,2, 2,3, 3,0, 4,5, 5,6, 6,7, 7,4, 0,4, 1,5, 2,6, 3,7];
SetVid($101);                           \set 640x480 graphics with 256 colors
repeat  Farthest:= 0.0;                 \find the farthest vertex
        for I:= 0 to 8-1 do
            if Z(I) > Farthest then [Farthest:= Z(I);  SI:= I];
        Clear;                          \erase screen
        for I:= 0 to 2*12-1 do          \for all the vertices...
            [J:= Segment(I);  I:= I+1;  \get vertex number
            Move(fix(X(J)*Size)+640/2, fix(Y(J)*Size)+480/2);
            K:= Segment(I);
            Line(fix(X(K)*Size)+640/2, fix(Y(K)*Size)+480/2,
                if J=SI ! K=SI then $F009 \dashed blue\ else $C \red\);
            ];
        Sound(0, 1, 1);                 \delay 1/18 second to prevent flicker
        for I:= 0 to 8-1 do
            [X(I):= X(I) + Y(I)*Sz;     \rotate vertices in X-Y plane
             Y(I):= Y(I) - X(I)*Sz;
             Y(I):= Y(I) + Z(I)*Sx;     \rotate vertices in Y-Z plane
             Z(I):= Z(I) - Y(I)*Sx;
            ];
until KeyHit;                           \run until a key is struck
SetVid(3);                              \restore normal text mode (for DOS)
]


var [const] M=50.0;
fcn cuboid(w,h,z){
   w*=M; h*=M; z*=M; // relative to abs dimensions
   bitmap:=PPM(400,400);

   clr:=0xff0000;  // red facing rectangle
   bitmap.line(0,0, w,0, clr); bitmap.line(0,0, 0,h, clr);
   bitmap.line(0,h, w,h, clr); bitmap.line(w,0, w,h, clr);

   r,a:=(w+z).toFloat().toPolar(0);  // relative to the origin
   a,b:=r.toRectangular((30.0).toRad() + a).apply("toInt"); c:=a; d:=b+h;
   clr=0xff; // blue right side of cuboid
   bitmap.line(w,0, a,b, clr); bitmap.line(a,b, c,d, clr);
   bitmap.line(w,h, c,d, clr);

   e:=c-w;
   clr=0xfff00; // green top of cuboid
   bitmap.line(0,h, e,d, clr); bitmap.line(c,d, e,d, clr);

   bitmap.write(File("foo.ppm","wb"));
}(2,3,4);


10 LET width=50: LET height=width*1.5: LET depth=width*2
20 LET x=80: LET y=10
30 PLOT x,y
40 DRAW 0,height: DRAW width,0: DRAW 0,-height: DRAW -width,0: REM Front
50 PLOT x,y+height: DRAW depth/2,height: DRAW width,0: DRAW 0,-height: DRAW -width,-height
60 PLOT x+width,y+height: DRAW depth/2,height


F average_square_diff(a, predictions)
   R sum(predictions.map(x -> (x - @a) ^ 2)) / predictions.len

F diversity_theorem(truth, predictions)
   V average = sum(predictions) / predictions.len
   print(‘average-error: ’average_square_diff(truth, predictions)"\n"‘’
         ‘crowd-error:   ’((truth - average) ^ 2)"\n"‘’
         ‘diversity:     ’average_square_diff(average, predictions))

diversity_theorem(49.0, [Float(48), 47, 51])
diversity_theorem(49.0, [Float(48), 47, 51, 42])


// [dependencies]
// image = "0.23"

use image::{GrayImage, Luma};

type Vector = [f64; 3];

fn normalize(v: &mut Vector) {
    let inv_len = 1.0/dot_product(v, v).sqrt();
    v[0] *= inv_len;
    v[1] *= inv_len;
    v[2] *= inv_len;
}

fn dot_product(v1: &Vector, v2: &Vector) -> f64 {
    v1.iter().zip(v2.iter()).map(|(x, y)| *x * *y).sum()
}

fn draw_sphere(radius: u32, k: f64, ambient: f64, dir: &Vector) -> GrayImage {
    let width = radius * 4;
    let height = radius * 3;
    let mut image = GrayImage::new(width, height);
    let mut vec = [0.0; 3];
    let diameter = radius * 2;
    let r = radius as f64;
    let xoffset = (width - diameter)/2;
    let yoffset = (height - diameter)/2;
    for i in 0..diameter {
        let x = i as f64 - r;
        for j in 0..diameter {
            let y = j as f64 - r;
            let z = r * r - x * x - y * y;
            if z >= 0.0 {
                vec[0] = x;
                vec[1] = y;
                vec[2] = z.sqrt();
                normalize(&mut vec);
                let mut s = dot_product(&dir, &vec);
                if s < 0.0 {
                    s = 0.0;
                }
                let mut lum = 255.0 * (s.powf(k) + ambient)/(1.0 + ambient);
                if lum < 0.0 {
                    lum = 0.0;
                } else if lum > 255.0 {
                    lum = 255.0;
                }
                image.put_pixel(i + xoffset, j + yoffset, Luma([lum as u8]));
            }
        }
    }
    image
}

fn main() {
    let mut dir = [-30.0, -30.0, 50.0];
    normalize(&mut dir);
    match draw_sphere(200, 1.5, 0.2, &dir).save("sphere.png") {
        Ok(()) => {}
        Err(error) => eprintln!("{}", error),
    }
}


object Sphere extends App {
  private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))

  private def drawSphere(r: Double, k: Double, ambient: Double): Unit = {
    def dot(x: Array[Double], y: Array[Double]) = {
      val d = x.head * y.head + x(1) * y(1) + x.last * y.last
      if (d < 0) -d else 0D
    }

    for (i <- math.floor(-r).toInt to math.ceil(r).toInt; x = i + .5)
      println(
        (for (j <- math.floor(-2 * r).toInt to math.ceil(2 * r).toInt; y = j / 2.0 + .5)
          yield if (x * x + y * y <= r * r) {

            def intensity(vec: Array[Double]) = {
              val b = math.pow(dot(light, vec), k) + ambient
              if (b <= 0) shades.length - 2
              else math.max((1 - b) * (shades.length - 1), 0).toInt
            }

            shades(intensity(normalize(Array(x, y, scala.math.sqrt(r * r - x * x - y * y)))))
          } else ' ').mkString)
  }

  private def normalize(v: Array[Double]): Array[Double] = {
    val len = math.sqrt(v.head * v.head + v(1) * v(1) + v.last * v.last)
    v.map(_ / len)
  }

  normalize(light).copyToArray(light)
  drawSphere(20, 4, .1)
  drawSphere(10, 2, .4)

}


program Doubly_linked;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  boost.LinkedList;

var
  List: TLinkedList<string>;
  Head, Tail,Current: TLinkedListNode<string>;
  Value:string;

begin
  List := TLinkedList<string>.Create;

  List.AddFirst('.AddFirst() adds at the head.');
  List.AddLast('.AddLast() adds at the tail.');
  Head := List.Find('.AddFirst() adds at the head.');
  List.AddAfter(Head, '.AddAfter() adds after a specified node.');
  Tail := List.Find('.AddLast() adds at the tail.');
  List.AddBefore(Tail, 'Betcha can''t guess what .AddBefore() does.');

  Writeln('Forward:');
  for value in List do
    Writeln(value);

  Writeln(#10'Backward:');

  Current:= Tail;
  while Assigned(Current) do
  begin
    Writeln(Current.Value);
    Current:= Current.Prev;
  end;

  List.Free;
  Readln;
end.


def makeDLList() {
    def firstINode
    def lastINode

    def makeNode(var value, var prevI, var nextI) {
        # To meet the requirement that the client cannot create a loop, the
        # inter-node refs are protected: clients only get the external facet
        # with invariant-preserving operations.
        def iNode

        def node { # external facet

            to get() { return value }
            to put(new) { value := new }

            /** Return the value of the element of the list at the specified offset
                from this element. */
            to get(index :int) {
                if (index > 0 && node.hasNext()) {
                    return nextI.node().get(index - 1)
                } else if (index < 0 && node.hasPrev()) {
                    return prevI.node().get(index + 1)
                } else if (index <=> 0) {
                    return value
                } else {
                    throw("index out of range in dlList")
                }
            }
            to hasPrev() {
                return prevI != firstINode && prevI != null
            }
            to prev() {
                if (!node.hasPrev()) {
                    throw("there is no previous node")
                }
                return prevI.node()
            }
            to hasNext() {
                return nextI != lastINode && nextI != null
            }
            to next() {
                if (!node.hasNext()) {
                    throw("there is no next node")
                }
                return nextI.node()
            }
            to remove() {
                if (prevI == null || nextI == null) { return }
                prevI.setNextI(nextI)
                nextI.setPrevI(prevI)
                prevI := null
                nextI := null
            }
            to insertAfter(newValue) {
                def newI := makeNode(newValue, iNode, nextI)
                nextI.setPrevI(newI)
                nextI := newI
            }
            to insertBefore(newValue) {
                prevI.node().insertAfter(newValue)
            }
        }

        bind iNode { # internal facet
            to node() { return node }
            to nextI() { return nextI }
            to prevI() { return prevI }
            to setNextI(new) { nextI := new }
            to setPrevI(new) { prevI := new }
        }

        return iNode
    } # end makeNode

    bind firstINode := makeNode(null, Ref.broken("no first prev"), lastINode)
    bind lastINode := makeNode(null, firstINode, Ref.broken("no last next"))

    def dlList {
        to __printOn(out) {
            out.print("<")
            var sep := ""
            for x in dlList {
                out.print(sep)
                out.quote(x)
                sep := ", "
            }
            out.print(">")
        }
        to iterate(f) {
            var n := firstINode
            while (n.node().hasNext()) {
                n := n.nextI()
                f(n.node(), n.node()[])
            }
        }
        to atFirst() { return firstINode.nextI().node() }
        to atLast() { return lastINode.prevI().node() }
        to insertFirst(new) { return firstINode.node().insertAfter(new) }
        to push(new) { return lastINode.node().insertBefore(new) }

        /** Return the node which has the specified value */
        to nodeOf(value) {
            for node => v ? (v == value) in dlList { return node }
        }
    }
    return dlList
}


/* ARM assembly Raspberry PI  */
/*  program dnsquery.s   */

/************************************/
/* Constantes                       */
/************************************/
.equ STDIN, 0         @ Linux input console
.equ STDOUT, 1        @ Linux output console

.equ EXIT,   1         @ Linux syscall END PROGRAM
.equ FORK,   2         @ Linux syscall
.equ READ,   3         @ Linux syscall
.equ WRITE,  4         @ Linux syscall
.equ OPEN,   5         @ Linux syscall
.equ CLOSE,  6         @ Linux syscall
.equ EXECVE, 0xB      @ Linux syscall
.equ PIPE,   0x2A     @ Linux syscall
.equ DUP2,   0x3F        @ Linux syscall
.equ WAIT4,  0x72     @ Linux syscall

.equ WUNTRACED,   2   @ Wait, return status of stopped child
.equ TAILLEBUFFER,  500
/*********************************/
/* Initialized data              */
/*********************************/
.data
szCarriageReturn:    .asciz "\n"
szMessFinOK:          .asciz "Fin normale du programme. \n"
szMessError:          .asciz "Error occured !!!"
szCommand:             .asciz "/usr/bin/host"  @ command host
szNameHost:            .asciz "www.kame.net"   @ string query name
.align 4
stArg1:                 .int szCommand           @ address command
                          .int szNameHost          @ address argument
                          .int 0,0                   @ zeroes

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 4
iStatusThread:      .skip 4
pipefd:               .skip 8
sBuffer:              .skip  TAILLEBUFFER
stRusage:             .skip TAILLEBUFFER
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                           @ entry of program
    /* création pipe  */
    ldr r0,iAdrpipefd                          @ FDs address
    mov r7, #PIPE                               @ create pipe
    svc 0                                        @ call system Linux
    cmp r0,#0                                    @ error  ?
    blt 99f

    /* create child thread */
    mov r0,#0
    mov r7, #FORK                                @ call system
    svc #0
    cmp r0,#0                                     @ error ?
    blt 99f
    bne parent                                  @ if <> zero r0 contains father pid
                                                  @ else is the child
/****************************************/
/*  Child thread                       */
/****************************************/
    /* redirection sysout -> pipe */
    ldr r0,iAdrpipefd
    ldr r0,[r0,#4]
    mov r7, #DUP2                                @ call system linux
    mov r1, #STDOUT                             @
    svc #0
    cmp r0,#0                                    @ error ?
    blt 99f

    /* run command host      */
    ldr r0, iAdrszCommand                    @ r0 = address de "/usr/bin/host"
    ldr r1,iAdrstArg1                         @ address argument 1
    mov r2,#0
    mov r7, #EXECVE                            @ call system linux (execve)
    svc #0                                      @ if ok -> no return !!!
    b 100f                                      @ never exec this label
/****************************************/
/*  Father thread                       */
/****************************************/
parent:
    mov r4,r0                                     @ save child pid
1:                                                @ loop child signal
    mov r0,r4
    ldr r1,iAdriStatusThread                  @ return status thread
    mov r2,#WUNTRACED                           @ flags
    ldr r3,iAdrstRusage                        @ return structure thread
    mov r7, #WAIT4                               @ Call System
    svc #0
    cmp r0,#0                                    @ error ?
    blt 99f
    @ recup status
    ldr r0,iAdriStatusThread                 @ analyse status
    ldrb r0,[r0]                                @ firest byte
    cmp r0,#0                                    @ normal end thread ?
    bne 1b                                      @ loop

    /* close entry pipe */
    ldr r0,iAdrpipefd
    mov r7,#CLOSE                               @ call system
    svc #0

    /* read datas pipe */
    ldr r0,iAdrpipefd
    ldr r0,[r0]
    ldr r1,iAdrsBuffer                        @ buffer address
    mov r2,#TAILLEBUFFER                      @ buffer size
    mov r7, #READ                               @ call system
    svc #0
    ldr r0,iAdrsBuffer                        @ display buffer
    bl affichageMess

    ldr r0,iAdrszMessFinOK                   @ display message Ok
    bl affichageMess
    mov r0, #0                                   @ return code
    b 100f
99:
    ldr r0,iAdrszMessError                   @ erreur
    bl affichageMess
    mov r0, #1                                   @ return code
    b 100f
100:                                            @ standard end of the program
    mov r7, #EXIT                               @ request to exit program
    svc #0                                      @ perform the system call

iAdrszCarriageReturn:      .int szCarriageReturn
iAdrszMessFinOK:            .int szMessFinOK
iAdrszMessError:            .int szMessError
iAdrsBuffer:                 .int sBuffer
iAdrpipefd:                  .int pipefd
iAdrszCommand:              .int szCommand
iAdrstArg1:                  .int stArg1
iAdriStatusThread:         .int iStatusThread
iAdrstRusage:                .int stRusage

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                          @ save  registres
    mov r2,#0                                      @ counter length
1:                                                 @ loop length calculation
    ldrb r1,[r0,r2]                               @ read octet start position + index
    cmp r1,#0                                      @ if 0 its over
    addne r2,r2,#1                                @ else add 1 in the length
    bne 1b                                        @ and loop
                                                   @ so here r2 contains the length of the message
    mov r1,r0                                      @ address message in r1
    mov r0,#STDOUT                                @ code to write to the standard output Linux
    mov r7, #WRITE                                @ code call system "write"
    svc #0                                        @ call systeme
    pop {r0,r1,r2,r7,lr}                           @ restaur des  2 registres */
    bx lr                                          @ return


import java.awt.*;
import java.awt.event.*;
import static java.lang.Math.*;
import java.time.LocalTime;
import javax.swing.*;

class Clock extends JPanel {

    final float degrees06 = (float) (PI / 30);
    final float degrees30 = degrees06 * 5;
    final float degrees90 = degrees30 * 3;

    final int size = 590;
    final int spacing = 40;
    final int diameter = size - 2 * spacing;
    final int cx = diameter / 2 + spacing;
    final int cy = diameter / 2 + spacing;

    public Clock() {
        setPreferredSize(new Dimension(size, size));
        setBackground(Color.white);

        new Timer(1000, (ActionEvent e) -> {
            repaint();
        }).start();
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawFace(g);

        final LocalTime time  = LocalTime.now();
        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();

        float angle = degrees90 - (degrees06 * second);
        drawHand(g, angle, diameter / 2 - 30, Color.red);

        float minsecs = (minute + second / 60.0F);
        angle = degrees90 - (degrees06 * minsecs);
        drawHand(g, angle, diameter / 3 + 10, Color.black);

        float hourmins = (hour + minsecs / 60.0F);
        angle = degrees90 - (degrees30 * hourmins);
        drawHand(g, angle, diameter / 4 + 10, Color.black);
    }

    private void drawFace(Graphics2D g) {
        g.setStroke(new BasicStroke(2));
        g.setColor(Color.white);
        g.fillOval(spacing, spacing, diameter, diameter);
        g.setColor(Color.black);
        g.drawOval(spacing, spacing, diameter, diameter);
    }

    private void drawHand(Graphics2D g, float angle, int radius, Color color) {
        int x = cx + (int) (radius * cos(angle));
        int y = cy - (int) (radius * sin(angle));
        g.setColor(color);
        g.drawLine(cx, cy, x, y);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Clock");
            f.setResizable(false);
            f.add(new Clock(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}


         >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
identification division.
program-id. dragon.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01  segment-length pic 9 value 2.
01  mark pic x value '.'.
01  segment-count pic 9999 value 513.

01  segment pic 9999.
01  point pic 9999 value 1.
01  point-max pic 9999.
01  point-lim pic 9999 value 8192.
01  dragon-curve.
    03  filler occurs 8192.
        05  ydragon pic s9999.
        05  xdragon pic s9999.

01  x pic s9999 value 1.
01  y pic S9999 value 1.

01  xdelta pic s9 value 1. *> start pointing east
01  ydelta pic s9 value 0.

01  x-max pic s9999 value -9999.
01  x-min pic s9999 value 9999.
01  y-max pic s9999 value -9999.
01  y-min pic s9999 value 9999.

01  n pic 9999.
01  r pic 9.

01  xupper pic s9999.
01  yupper pic s9999.

01  window-line-number pic 99.
01  window-width pic 99 value 64.
01  window-height pic 99 value 22.
01  window.
    03  window-line occurs 22.
        05  window-point occurs 64 pic x.

01  direction pic x.

procedure division.
start-dragon.

    if segment-count * segment-length > point-lim
        *> too many segments for the point-table
        compute segment-count = point-lim / segment-length
    end-if

    perform varying segment from 1 by 1
    until segment > segment-count

        *>===========================================
        *> segment = n * 2 ** b
        *> if mod(n,4) = 3, turn left else turn right
        *>===========================================

        *> calculate the turn
        divide 2 into segment giving n remainder r
        perform until r <> 0
            divide 2 into n giving n remainder r
        end-perform
        divide 2 into n giving n remainder r

        *> perform the turn
        evaluate r also xdelta also ydelta
        when 0 also 1 also 0  *> turn right from east
        when 1 also -1 also 0 *> turn left from west
            *> turn to south
            move 0 to xdelta
            move 1 to ydelta
        when 1 also 1 also 0  *> turn left from east
        when 0 also -1 also 0 *> turn right from west
            *> turn to north
            move 0 to xdelta
            move -1 to ydelta
        when 0 also 0 also 1  *> turn right from south
        when 1 also 0 also -1 *> turn left from north
            *> turn to west
            move 0 to ydelta
            move -1 to xdelta
        when 1 also 0 also 1  *> turn left from south
        when 0 also 0 also -1 *> turn right from north
            *> turn to east
            move 0 to ydelta
            move 1 to xdelta
        end-evaluate

        *> plot the segment points
        perform segment-length times
            add xdelta to x
            add ydelta to y

            move x to xdragon(point)
            move y to ydragon(point)

            add 1 to point
        end-perform

        *> update the limits for the display
        compute x-max = max(x, x-max)
        compute x-min = min(x, x-min)
        compute y-max = max(y, y-max)
        compute y-min = min(y, y-min)
        move point to point-max

    end-perform

    *>==========================================
    *> display the curve
    *> hjkl corresponds to left, up, down, right
    *> anything else ends the program
    *>==========================================

    move 1 to yupper xupper

    perform with test after
    until direction <> 'h' and 'j' and 'k' and 'l'

        *>==========================================
        *> (yupper,xupper) maps to window-point(1,1)
        *>==========================================

        *> move the window
        evaluate true
        when direction = 'h' *> move window left
        and xupper > x-min + window-width
           subtract 1 from xupper
        when direction = 'j' *> move window up
        and yupper < y-max - window-height
           add 1 to yupper
        when direction = 'k' *> move window down
        and yupper > y-min + window-height
           subtract 1 from yupper
        when direction = 'l' *> move window right
        and xupper < x-max - window-width
            add 1 to xupper
        end-evaluate

        *> plot the dragon points in the window
        move spaces to window
        perform varying point from 1 by 1
        until point > point-max
            if ydragon(point) >= yupper and < yupper + window-height
            and xdragon(point) >= xupper and < xupper + window-width
                *> we're in the window
                compute y = ydragon(point) - yupper + 1
                compute x =  xdragon(point) - xupper + 1
                move mark to window-point(y, x)
            end-if
         end-perform

         *> display the window
         perform varying window-line-number from 1 by 1
         until window-line-number > window-height
             display window-line(window-line-number)
         end-perform

         *> get the next window move or terminate
         display 'hjkl?' with no advancing
         accept direction
    end-perform

    stop run
    .
end program dragon.


rebol [
    Title: "Documentation"
    URL: http://rosettacode.org/wiki/Documentation
	Purpose: {To demonstrate documentation of REBOL pograms.}
]

; Notice the fields in the program header. The header is required for
; valid REBOL programs, although the fields don't have to be filled
; in. Standard fields are defined (see 'system/script/header'), but
; I can also define other fields as I like and they'll be available
; there.

; This is a comment. The semicolon can be inserted anywhere outside of
; a string and will escape to end of line. See the inline comments
; below.

; Functions can have a documentation string as the first part of the
; argument definition block. Each argument can specify what types it
; will accept as well as a description. All typing/documentation
; entries are optional. Notice that local variables can be documented
; as well.

sum: func [
	"Add numbers in block."
	data [block! list!] "List of numbers to add together."
	/average "Calculate average instead of sum."
	/local
	i "Iteration variable."
	x "Variable to hold results."
] [
	x: 0  repeat i data [x: x + i]
	either average [x / length? data][x] ; Functions return last result.
]

print [sum [1 2 3 4 5 6] crlf  sum/average [7 8 9 10] crlf]

; The help message is constructed from the public information about
; the function. Internal variable information isn't shown.

help sum  print ""

; The source command provides the source to any user functions,
; reconstructing the documentation strings if they're provided:

source sum  print ""

; This is an object, describing a person, whose name is Bob.

bob: make object! [
	name: "Bob Sorkopath"
	age: 24
	hi: func ["Say hello."][print "Hello!"]
]

; I can use the 'help' word to get a list of the fields of the object

help bob  print ""

; If I want see the documentation or source for 'bob/hi', I have to
; get a little tricky to get it from the object's namespace:

x: get in bob 'hi  help x  print ""

probe get in bob 'hi


    # Determine The Average Word Name Length

    To determine the average length of a word name two values
    are needed. First, the total length of all names in the
    Dictionary:

    ~~~
    #0 [ d:name s:length + ] d:for-each
    ~~~

    And then the number of words in the Dictionary:

    ~~~
    #0 [ drop n:inc ] d:for-each
    ~~~

    With these, a simple division is all that's left.

    ~~~
    /
    ~~~

    Finally, display the results:

    ~~~
    'Average_name_length:_%n\n s:format s:put
    ~~~


/*REXX program illustrates how to display embedded documentation (help) within REXX code*/
parse arg doc                                    /*obtain (all) the arguments from C.L. */
if doc='?'  then call help                       /*show documentation if arg=a single ? */
/*■■■■■■■■■regular■■■■■■■■■■■■■■■■■■■■■■■■■*/
/*■■■■■■■■■■■■■■■■■mainline■■■■■■■■■■■■■■■■*/
/*■■■■■■■■■■■■■■■■■■■■■■■■■■code■■■■■■■■■■■*/
/*■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■here.■■■■■*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
help: ?=0;    do j=1  for sourceline();  _=sourceline(j)         /*get a line of source.*/
              if _='<help>'   then do;  ?=1;  iterate;  end      /*search for  <help>   */
              if _='</help>'  then leave                         /*   "    "   </help>  */
              if ?            then say _
              end   /*j*/
      exit                                       /*stick a fork in it,  we're all done. */
/*══════════════════════════════════start of the in═line documentation AFTER the  <help>
<help>
       To use the  YYYY  program, enter one of:

             YYYY  numberOfItems
             YYYY                            (no arguments uses the default)
             YYYY  ?                         (to see this documentation)

       ─── where:  numberOfItems             is the number of items to be used.

           If no  "numberOfItems"  are entered, the default of  100  is used.
</help>
════════════════════════════════════end of the in═line documentation BEFORE the </help> */


/*
Multiply two numbers
n1: an integer.
n2: an integer.
returns product of n1 and n2
 */
see mult(3, 5) + nl
func mult n1, n2
     return n1*n2


=begin rdoc
RDoc is documented here[http://www.ruby-doc.org/core/classes/RDoc.html].

This is a class documentation comment.  This text shows at the top of the page
for the class.

Comments can be written inside "=begin rdoc"/"end" blocks or
in normal '#' comment blocks.

There are no '@parameters' like javadoc, but 'name-value' lists can be written:
Author:: Joe Schmoe
Date:: today
=end

class Doc
  # This is a comment for a Constant
  Constant = nil

  # This is a method comment.  Parameters and return values can be named
  # with the "call-seq" directive.
  #
  # call-seq:
  #   a_method(first_arg, second_arg) -> return_value
  #
  def a_method(arg1, arg2='default value')
    do_stuff
  end

  # Class methods will be shown in a separate section of the generated documentation.
  def self.class_method
    Constant
  end
end

# :include:boilerplate.txt


with Ada.Text_IO;
with Ada.Command_Line;

procedure Diversity_Prediction is

   type Real is new Float;
   type Real_Array is array (Positive range <>) of Real;

   package Real_IO is new Ada.Text_Io.Float_IO (Real);
   use Ada.Text_IO, Ada.Command_Line, Real_IO;

   function Mean (Data : Real_Array) return Real is
      Sum : Real := 0.0;
   begin
      for V of Data loop
         Sum := Sum + V;
      end loop;
      return Sum / Real (Data'Length);
   end Mean;

   function Variance (Reference : Real; Data : Real_Array) return Real is
      Res : Real_Array (Data'Range);
   begin
      for A in Data'Range loop
         Res (A) := (Reference - Data (A)) ** 2;
      end loop;
      return Mean (Res);
   end Variance;

   procedure Diversity (Truth : Real; Estimates : Real_Array)
   is
      Average       : constant Real := Mean (Estimates);
      Average_Error : constant Real := Variance (Truth, Estimates);
      Crowd_Error   : constant Real := (Truth - Average) ** 2;
      Diversity     : constant Real := Variance (Average, Estimates);
   begin
      Real_IO.Default_Exp := 0;
      Real_IO.Default_Aft := 5;
      Put ("average-error : "); Put (Average_Error);  New_Line;
      Put ("crowd-error   : "); Put (Crowd_Error);    New_Line;
      Put ("diversity     : "); Put (Diversity);      New_Line;
   end Diversity;

begin
   if Argument_Count <= 1 then
      Put_Line ("Usage: diversity_prediction <truth> <data_1> <data_2> ...");
      return;
   end if;

   declare
      Truth     : constant Real := Real'Value (Argument (1));
      Estimates : Real_Array (2 .. Argument_Count);
   begin
      for A in 2 .. Argument_Count loop
         Estimates (A) := Real'Value (Argument (A));
      end loop;

      Diversity (Truth, Estimates);
   end;
end Diversity_Prediction;


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

float mean(float* arr,int size){
	int i = 0;
	float sum = 0;

	while(i != size)
		sum += arr[i++];

	return sum/size;
}

float variance(float reference,float* arr, int size){
	int i=0;
	float* newArr = (float*)malloc(size*sizeof(float));

	for(;i<size;i++)
		newArr[i] = (reference - arr[i])*(reference - arr[i]);

	return mean(newArr,size);
}

float* extractData(char* str, int *len){
	float* arr;
	int i=0,count = 1;
	char* token;

	while(str[i]!=00){
		if(str[i++]==',')
			count++;
	}

	arr = (float*)malloc(count*sizeof(float));
	*len = count;

	token = strtok(str,",");

	i = 0;

	while(token!=NULL){
		arr[i++] = atof(token);
		token = strtok(NULL,",");
	}

	return arr;
}

int main(int argC,char* argV[])
{
	float* arr,reference,meanVal;
	int len;
	if(argC!=3)
		printf("Usage : %s <reference value> <observations separated by commas>");
	else{
		arr = extractData(argV[2],&len);

		reference = atof(argV[1]);

		meanVal = mean(arr,len);

		printf("Average Error : %.9f\n",variance(reference,arr,len));
		printf("Crowd Error : %.9f\n",(reference - meanVal)*(reference - meanVal));
		printf("Diversity : %.9f",variance(meanVal,arr,len));
	}

	return 0;
}