module singleton ;
import std.stdio ;
import std.thread ;
import std.random ;
import std.c.time ;

class Dealer {
  private static Dealer me ;
  static Dealer Instance() {
    writefln("   Calling Dealer... ") ;
    if(me is null) // Double Checked Lock
      synchronized  // this part of code can only be executed by one thread a time
        if(me is null)
          me = new Dealer ;
    return me ;
  }
  private static string[] str = ["(1)Enjoy", "(2)Rosetta", "(3)Code"] ;
  private int state ;
  private this() {
    for(int i = 0 ; i < 3 ; i++) {
      writefln("...calling Dealer... ") ;
      msleep(rand() & 2047) ;
    }
    writefln(">>Dealer is called to come in!") ;
    state = str.length - 1 ;
  }
  Dealer nextState() {
    synchronized(this) // accessed to Object _this_ is locked ... is it necessary ???
      state = (state + 1) % str.length ;
    return this ;
  }
  string toString() { return str[state] ; }
}

class Coder : Thread {
  private string name_ ;
  Coder hasName(string name) {  name_ = name ; return this ; }
  override int run() {
    msleep(rand() & 1023) ;
    writefln(">>%s come in.", name_) ;
    Dealer single = Dealer.Instance ;
    msleep(rand() & 1023) ;
    for(int i = 0 ; i < 3 ; i++) {
      writefln("%9s got %-s", name_, single.nextState) ;
      msleep(rand() & 1023) ;
    }
    return 0 ;
  }
}

void main() {
  Coder x = new Coder ;
  Coder y = new Coder ;
  Coder z = new Coder ;

  x.hasName("Peter").start() ;
  y.hasName("Paul").start() ;
  z.hasName("Mary").start() ;

  x.wait ;  y.wait ;  z.wait ;
}


unit Singleton;

interface

type
  TSingleton = class
  private
    //Private fields and methods here...

     class var _instance: TSingleton;
  protected
    //Other protected methods here...
  public
    //Global point of access to the unique instance
    class function Create: TSingleton;

    destructor Destroy; override;

    //Other public methods and properties here...
  end;

implementation

{ TSingleton }

class function TSingleton.Create: TSingleton;
begin
  if (_instance = nil) then
    _instance:= inherited Create as Self;

  result:= _instance;
end;

destructor TSingleton.Destroy;
begin
  _instance:= nil;
  inherited;
end;

end.


: list-append ( previous new -- )
    [ swap next>> >>next drop ] [ >>next drop ] 2bi ;

SYMBOLS: A B C ;

A <linked-list>
[ C <linked-list> list-append ] keep
[ B <linked-list> list-append ] keep
.


class Node
{
  const Int value
  Node? successor // can be null, for end of series

  new make (Int value, Node? successor := null)
  {
    this.value = value
    this.successor = successor
  }

  // insert method for this problem
  public Void insert (Node newNode)
  {
    newNode.successor = this.successor
    this.successor = newNode
  }
}

// simple class to test putting 'c' between 'a' and 'b'
class Main
{
  public static Void main ()
  {
    c := Node (2)
    b := Node (3)
    a := Node (1, b)
    a.insert (c)

    echo (a.value)
    echo (a.successor.value)
    echo (a.successor.successor.value)
  }
}


\ Create the list and some list elements
create A   0 , char A ,
create B   0 , char B ,
create C   0 , char C ,


elemental subroutine addAfter(nodeBefore,value)
   type (node), intent(inout) :: nodeBefore
   real, intent(in)           :: value
   type (node), pointer       :: newNode

   allocate(newNode)
   newNode%data = value
   newNode%next => nodeBefore%next
   nodeBefore%next => newNode
end subroutine addAfter


sub insert_ll_int( anchor as ll_int ptr, ins as ll_int ptr)
    ins->nxt = anchor->nxt
    anchor->nxt = ins
end sub


package main

import "fmt"

type Ele struct {
    Data interface{}
    Next *Ele
}

func (e *Ele) insert(data interface{}) {
    if e == nil {
        panic("attept to modify nil")
    }
    e.Next = &Ele{data, e.Next}
}

func (e *Ele) printList() {
    if e == nil {
        fmt.Println(nil)
        return
    }
    fmt.Printf("(%v", e.Data)
    for {
        e = e.Next
        if e == nil {
            fmt.Println(")")
            return
        }
        fmt.Print(" ", e.Data)
    }
}

func main() {
    h := &Ele{"A", &Ele{"B", nil}}
    h.printList()
    h.insert("C")
    h.printList()
}


def sleep(milliseconds :int, nextThing) {
    stdout.println("Sleeping...")
    timer.whenPast(timer.now() + milliseconds, fn {
        stdout.println("Awake!")
        nextThing()
    })
}


program Sleep type BasicProgram{}

    // Syntax: 	sysLib.wait(time BIN(9,2) in)

    function main()
    	SysLib.writeStdout("Sleeping!");
        sysLib.wait(15); // waits for 15 seconds
        SysLib.writeStdout("Awake!");
    end

end


class
    APPLICATION
inherit
    EXECUTION_ENVIRONMENT
create
    make
feature -- Initialization
    make
            -- Sleep for a given number of nanoseconds.
        do
            print ("Enter a number of nanoseconds: ")
            io.read_integer_64
            print ("Sleeping...%N")
            sleep (io.last_integer_64)
            print ("Awake!%N")
        end
end


import extensions;

public program()
{
    int sleep := console.readLine().toInt();
    console.printLine("Sleeping...");
    system'threading'threadControl.sleep(sleep);
    console.printLine("Awake!")
}


sleep = fn seconds ->
          IO.puts "Sleeping..."
          :timer.sleep(1000 * seconds)    #  in milliseconds
          IO.puts "Awake!"
        end

sec = if System.argv==[], do: 1, else: hd(System.argv) |> String.to_integer
sleep.(sec)


def is_prime:
  . as $n
  | if ($n < 2)         then false
    elif ($n % 2 == 0)  then $n == 2
    elif ($n % 3 == 0)  then $n == 3
    elif ($n % 5 == 0)  then $n == 5
    elif ($n % 7 == 0)  then $n == 7
    elif ($n % 11 == 0) then $n == 11
    elif ($n % 13 == 0) then $n == 13
    elif ($n % 17 == 0) then $n == 17
    elif ($n % 19 == 0) then $n == 19
    else {i:23}
         | until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
	 | .i * .i > $n
    end;

def sum(s): reduce s as $x (null; . + $x);

# emit a stream of the prime factors as per prime factorization
def prime_factors:
  . as $num
  | def m($p):  # emit $p with appropriate multiplicity
      $num | while( . % $p == 0; . / $p )
      | $p ;
  if (. % 2) == 0 then m(2) else empty end,
  (range(3; 1 + (./2); 2)
    | select(($num % .) == 0 and is_prime)
    | m(.));


# v0.6

function sumdigits(n::Integer)
    sum = 0
    while n > 0
        sum += n % 10
        n = div(n, 10)
    end
    return sum
end

using Primes
issmith(n::Integer) = !isprime(n) && sumdigits(n) == sum(sumdigits(f) for f in factor(Vector, n))

smithnumbers = collect(n for n in 2:10000 if issmith(n))
println("Smith numbers up to 10000:\n$smithnumbers")


// version 1.0.6

fun getPrimeFactors(n: Int): MutableList<Int> {
    val factors = mutableListOf<Int>()
    if (n < 2) return factors
    var factor = 2
    var nn = n
    while (true) {
        if (nn % factor == 0) {
            factors.add(factor)
            nn /= factor
            if (nn == 1) return factors
        }
        else if (factor >= 3) factor += 2
        else factor = 3
    }
}

fun sumDigits(n: Int): Int = when {
        n < 10 -> n
        else   -> {
            var sum = 0
            var nn = n
            while (nn > 0) {
                sum += (nn % 10)
                nn /= 10
            }
            sum
        }
    }

fun isSmith(n: Int): Boolean {
    if (n < 2) return false
    val factors = getPrimeFactors(n)
    if (factors.size == 1) return false
    val primeSum = factors.sumBy { sumDigits(it) }
    return sumDigits(n) == primeSum
}

fun main(args: Array<String>) {
    println("The Smith numbers below 10000 are:\n")
    var count = 0
    for (i in 2 until 10000) {
        if (isSmith(i)) {
            print("%5d".format(i))
            count++
        }
    }
    println("\n\n$count numbers found")
}


class
	SINGLETON
create {SINGLETON_ACCESS}
	default_create
feature
	-- singleton features go here
end


fn Singleton()
	if this.self then return this.self cls
	var new: {}
	iter k,v as this._props do
		new[k]:v
	cls
	this.self:new
	return new
cls
Singleton._props: {
	name: "Singleton",
	fn setName(self,new)
		self.name:new
	cls,
}

var MySingleton: Singleton()
log(MySingleton == Singleton()) --true
log(MySingleton.name) --Singleton

var NewSingleton: Singleton()
NewSingleton>>setName("Test")

log(MySingleton.name) --Test


-module(singleton).

-export([get/0, set/1, start/0]).

-export([loop/1]).

% spec singleton:get() -> {ok, Value::any()} | not_set
get() ->
     ?MODULE ! {get, self()},
     receive
	{ok, not_set} -> not_set;
        Answer -> Answer
     end.

% spec singleton:set(Value::any()) -> ok
set(Value) ->
    ?MODULE ! {set, self(), Value},
    receive
        ok -> ok
    end.

start() ->
    register(?MODULE, spawn(?MODULE, loop, [not_set])).

loop(Value) ->
    receive
        {get, From} ->
             From ! {ok, Value},
             loop(Value);
        {set, From, NewValue} ->
             From ! ok,
             loop(NewValue)
        end.


class NodeList {
    private enum Flag { FRONT }
    private ListNode head
    void insert(value, insertionPoint=Flag.FRONT) {
        if (insertionPoint == Flag.FRONT) {
            head = new ListNode(payload: value, next: head)
        } else {
            def node = head
            while (node.payload != insertionPoint) {
                node = node.next
                if (node == null) {
                    throw new IllegalArgumentException(
                        "Insertion point ${afterValue} not already contained in list")
                }
            }
            node.next = new ListNode(payload:value, next:node.next)
        }
    }
    String toString() { "${head}" }
}


insertAfter a b (c:cs) | a==c = a : b : cs
                       | otherwise = c : insertAfter a b cs
insertAfter _ _ [] = error "Can't insert"


record Node (value, successor)

procedure insert_node (node, newNode)
  newNode.successor := node.successor
  node.successor := newNode
end


list=: 1 65,:_ 66
A=:0  NB. reference into list
B=:1  NB. reference into list
insertAfter=: monad define
   'localListName localListNode localNewValue'=. y
   localListValue=: ".localListName
   localOldLinkRef=: <localListNode,0
   localNewLinkRef=: #localListValue
   localNewNode=: (localOldLinkRef { localListValue), localNewValue
   (localListName)=: (localNewLinkRef localOldLinkRef} localListValue), localNewNode
)


(let ((seconds (read-number "Time in seconds: ")))
  (message "Sleeping ...")
  (sleep-for seconds)
  (message "Awake!"))


main() ->
    io:format("Sleeping...~n"),
    timer:sleep(1000), %% in milliseconds
    io:format("Awake!~n").


      ..............
      INPUT("Enter the time to sleep in seconds: ";sleep)
      PRINT("Sleeping...")
      PAUSE(sleep)
      PRINT("Awake!")
      ..............


open System
open System.Threading

[<EntryPoint>]
let main args =
    let sleep = Convert.ToInt32(Console.ReadLine())
    Console.WriteLine("Sleeping...")
    Thread.Sleep(sleep); //milliseconds
    Console.WriteLine("Awake!")
    0


USING: calendar io math.parser threads ;

: read-sleep ( -- )
    readln string>number seconds
    "Sleeping..." print
    sleep
    "Awake!" print ;


-- Returns a boolean indicating whether n is prime
function isPrime (n)
    if n < 2 then return false end
    if n < 4 then return true end
    if n % 2 == 0 then return false end
    for d = 3, math.sqrt(n), 2 do
        if n % d == 0 then return false end
    end
    return true
end

-- Returns a table of the prime factors of n
function primeFactors (n)
    local pfacs, divisor = {}, 1
    if n < 1 then return pfacs end
    while not isPrime(n) do
        while not isPrime(divisor) do divisor = divisor + 1 end
        while n % divisor == 0 do
            n = n / divisor
            table.insert(pfacs, divisor)
        end
        divisor = divisor + 1
        if n == 1 then return pfacs end
    end
    table.insert(pfacs, n)
    return pfacs
end

-- Returns the sum of the digits of n
function sumDigits (n)
    local sum, nStr = 0, tostring(n)
    for digit = 1, nStr:len() do
        sum = sum + tonumber(nStr:sub(digit, digit))
    end
    return sum
end

-- Returns a boolean indicating whether n is a Smith number
function isSmith (n)
    if isPrime(n) then return false end
    local sumFacs = 0
    for _, v in ipairs(primeFactors(n)) do
        sumFacs = sumFacs + sumDigits(v)
    end
    return sumFacs == sumDigits(n)
end

-- Main procedure
for n = 1, 10000 do
    if isSmith(n) then io.write(n .. "\t") end
end


USING: classes.singleton kernel io prettyprint ;
IN: singleton-demo

SINGLETON: bar
GENERIC: foo ( obj -- )
M: bar foo drop "Hello!" print ;


include FMS-SI.f

\ A singleton is created by using normal Forth data
\ allocation words such as value or variable as instance variables.
\ Any number of instances of a singleton class may be
\ instantiated but messages will all operate on the same shared data
\ so it is the same as if only one object has been created.
\ The data name space will remain private to the class.

:class singleton
  0 value a
  0 value b
  :m printa a . ;m
  :m printb b . ;m
  :m add-a ( n -- ) a + to a ;m
  :m add-b ( n -- ) b + to b ;m
;class

singleton s1
singleton s2
singleton s3

4 s1 add-a
9 s2 add-b
s3 printa \ => 4
s3 printb \ => 9
s1 printb \ => 9
s2 printa \ => 4


REM Sacado del forum de FreeBASIC (https://www.freebasic.net/forum/viewtopic.php?t=20432)

Type singleton
    Public :
    Declare Static Function crearInstancia() As singleton Ptr
    Declare Destructor ()
    Dim i As Integer
    Private :
    Declare Constructor()
    Declare Constructor(Byref rhs As singleton)
    Declare Static Function instancia(Byval crear As Integer) As singleton Ptr
End Type

Static Function singleton.crearInstancia() As singleton Ptr
    Return singleton.instancia(1)
End Function

Static Function singleton.instancia(Byval crear As Integer) As singleton Ptr
    Static ref As singleton Ptr = 0
    Function = 0
    If crear = 0 Then
        ref = 0
    Elseif ref = 0 Then
        ref = New singleton
        Function = ref
    End If
End Function

Constructor singleton ()
End Constructor

Destructor singleton()
singleton.instancia(0)
End Destructor

'-----------------------------------------------------------------------------
Dim As singleton Ptr ps1 = singleton.crearinstancia()
ps1->i = 1234
Print ps1, ps1->i

Dim As singleton Ptr ps2 = singleton.crearinstancia()
Print ps2

Delete ps1

Dim As singleton Ptr ps3 = singleton.crearinstancia()
Print ps3, ps3->i
Delete ps3
Sleep


package main

import (
    "log"
    "math/rand"
    "sync"
    "time"
)

var (
    instance string
    once     sync.Once // initialize instance with once.Do
)

func claim(color string, w *sync.WaitGroup) {
    time.Sleep(time.Duration(rand.Intn(1e8))) // hesitate up to .1 sec
    log.Println("trying to claim", color)
    once.Do(func() { instance = color })
    log.Printf("tried %s. instance: %s", color, instance)
    w.Done()
}

func main() {
    rand.Seed(time.Now().Unix())
    var w sync.WaitGroup
    w.Add(2)
    go claim("red", &w) // these two attempts run concurrently
    go claim("blue", &w)
    w.Wait()
    log.Println("after trying both, instance =", instance)
}


void insertNode(Node<T> anchor_node, Node<T> new_node)
{
    new_node.next = anchor_node.next;
    anchor_node.next = new_node;
}


LinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
    if (this._value == searchValue) {
        nodeToInsert.next(this.next());
        this.next(nodeToInsert);
    }
    else if (this.next() == null)
        throw new Error(0, "value '" + searchValue + "' not found in linked list.")
    else
        this.next().insertAfter(searchValue, nodeToInsert);
}
var list = createLinkedListFromArray(['A','B']);
list.insertAfter('A', new LinkedList('C', null));


 def new($item; $next):
  if $next | (.==null or is_singly_linked_list)
  then {$item, $next}
  else "new(_;_) called with invalid SLL: \($next)" | error
  end;

# A constructor:
def new($x): new($x; null);

def insert($x):
  .next |= new($x; .);


function Base.insert!(ll::LinkedList{T}, index::Integer, item::T) where T
    if index == 1
        if isempty(ll)
            return push!(ll, item)
        else
            ll.head = Node{T}(item, ll.head)
        end
    else
        nd = ll.head
        while index > 2
            if nd.next isa EmptyNode
                throw(BoundsError())
            else
                nd = nd.next
                index -= 1
            end
        end
        nd.next = Node{T}(item, nd.next)
    end
    return ll
end


// version 1.1.2

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

fun <T: Number> insertAfter(prev: Node<T>, new: Node<T>) {
    new.next = prev.next
    prev.next = new
}

fun main(args: Array<String>) {
    val b = Node(3)
    val a = Node(1, b)
    println("Before insertion : $a")
    val c = Node(2)
    insertAfter(a, c)
    println("After  insertion : $a")
}


using concurrent

class Main
{
  public static Void main ()
  {
    echo ("Enter a time to sleep: ")
    input := Env.cur.in.readLine
    try
    {
      time := Duration.fromStr (input)
      echo ("sleeping ...")
      Actor.sleep (time)
      echo ("awake!")
    }
    catch
    {
      echo ("Invalid time entered")
    }
  }
}


#APPTYPE CONSOLE
DIM %msec
PRINT "Milliseconds to sleep: ";
%msec = FILEGETS(stdin, 10)
PRINT "Sleeping..."
SLEEP(%msec)
PRINT "Awake!"
PAUSE


: sleep ( ms -- )
  ." Sleeping..."
  ms
  ." awake." cr ;


program test_sleep

  implicit none
  integer :: iostat
  integer :: seconds
  character (32) :: argument

  if (iargc () == 1) then
    call getarg (1, argument)
    read (argument, *, iostat = iostat) seconds
    if (iostat == 0) then
      write (*, '(a)') 'Sleeping...'
      call sleep (seconds)
      write (*, '(a)') 'Awake!'
    end if
  end if

end program test_sleep


' FB 1.05.0 Win64

Dim ms As UInteger
Input "Enter number of milliseconds to sleep" ; ms
Print "Sleeping..."
Sleep ms, 1  '' the "1" means Sleep can't be interrupted with a keystroke
Print "Awake!"
End


Module Checkit {
      Set Fast !
      Form 80, 40
      Refresh
      Function Smith(max=10000) {
            Function SumDigit(a$) {
                  def long sum
                  For i=1 to len(a$) {sum+=val(mid$(a$,i, 1)) }
                  =sum
            }
                  x=max
                  \\ Euler's Sieve
                        Dim r(x+1)=1
                        k=2
                        k2=k**2
                        While k2<x {
                              For m=k2 to x step k {r(m)=0}
                              Repeat {
                              k++ :  k2=k**2
                              } Until r(k)=1 or k2>x
                        }
            r(0)=0
            smith=0
            smith2=0
            lastI=0
            inventory smithnumbers
            Top=max div 100
            c=4
            For i=4 to max {
                if c> top then  print over $(0,6), ceil(i/max*100);"%" : Refresh : c=1
                c++
                  if r(i)=0 then {
                        smith=sumdigit(str$(i)) : lastI=i
                        smith2=0
                        do {
                              ii=int(sqrt(i))+1
                              do {  ii-- :   while r(ii)<>1 {ii--} } until i mod ii=0
                               if ii<2 then smith2+=sumdigit(str$(i)):exit
                               smith3=sumdigit(str$(ii))
                              do {
                                   smith2+=smith3
                                    i=i div ii : if ii<2  or i<2 then exit
                              } until  i mod ii<>0  or smith2>smith
                        } until i<2 or smith2>smith
                       If  smith=smith2 then Append smithnumbers, lastI
                  }
            }
            =smithnumbers
      }
      const MaxNumbers=10000
      numbers= Smith(MaxNumbers)
      Print
      Print $(,5), numbers
      Print
      Print format$(" {0} smith numbers found <= {1}", Len(numbers), MaxNumbers)
}
Checkit


            NORMAL MODE IS INTEGER
            PRINT COMMENT$ SMITH NUMBERS$

          R GENERATE PRIMES UP TO 10,000 USING SIEVE METHOD
            BOOLEAN SIEVE
            DIMENSION SIEVE(10000)
            DIMENSION PRIMES(1500)

            THROUGH SET, FOR I=2, 1, I.G.10000
SET         SIEVE(I) = 1B

            THROUGH NXPRIM, FOR P=2, 1, P.G.100
            WHENEVER SIEVE(P)
                THROUGH MARK, FOR I=P*P, P, I.G.10000
MARK            SIEVE(I) = 0B
NXPRIM      END OF CONDITIONAL

            NPRIMS = 0
            THROUGH CNTPRM, FOR P=2, 1, P.G.10000
            WHENEVER SIEVE(P)
                PRIMES(NPRIMS) = P
                NPRIMS = NPRIMS + 1
CNTPRM      END OF CONDITIONAL

          R CHECK SMITH NUMBERS
            THROUGH SMITH, FOR I=4, 1, I.GE.10000
            WHENEVER .NOT. SIEVE(I)
                K = I
                PFSUM = 0
                THROUGH FACSUM, FOR P=0, 1, P.GE.NPRIMS .OR. K.E.0
                L = PRIMES(P)
FACDIV          WHENEVER K/L*L.E.K .AND. K.NE.0
                    PFSUM = PFSUM + DGTSUM.(L)
                    K = K/L
                    TRANSFER TO FACDIV
FACSUM          END OF CONDITIONAL
                WHENEVER PFSUM.E.DGTSUM.(I), PRINT FORMAT NUMFMT,I
SMITH       END OF CONDITIONAL

            VECTOR VALUES NUMFMT = $I5*$

          R GET SUM OF DIGITS OF N
            INTERNAL FUNCTION(N)
            ENTRY TO DGTSUM.
            DSUM = 0
            DNUM = N
LOOP        WHENEVER DNUM.E.0, FUNCTION RETURN DSUM
            DSUM = DSUM + DNUM-DNUM/10*10
            DNUM = DNUM/10
            TRANSFER TO LOOP
            END OF FUNCTION
            END OF PROGRAM


isSmith := proc(n::posint)
local factors, sumofDigits, sumofFactorDigits, x;
if isprime(n) then
  return false;
else
  sumofDigits := add(x, x = convert(n, base, 10));
  sumofFactorDigits := add(map(x -> op(convert(x, base, 10)), [op(NumberTheory:-PrimeFactors(n))]));
  return evalb(sumofDigits = sumofFactorDigits);
end if;
end proc:

findSmith := proc(n::posint)
return select(isSmith, [seq(1 .. n - 1)]);
end proc:

findSmith(10000);


@Singleton
class SingletonClass {

    def invokeMe() {
        println 'invoking method of a singleton class'
    }

    static void main(def args) {
        SingletonClass.instance.invokeMe()
    }
}


class Singleton
   method print()
       write("Hi there.")
   end
   initially
       write("In constructor!")
       Singleton := create |self
end

procedure main()
   Singleton().print()
   Singleton().print()
end


Singleton := Object clone
Singleton clone = Singleton


class Singleton
{
    private static Singleton myInstance;
    public static Singleton getInstance()
    {
        if (myInstance == null)
        {
            synchronized(Singleton.class)
            {
                if (myInstance == null)
                {
                    myInstance = new Singleton();
                }
            }
        }

        return myInstance;
    }

    protected Singleton()
    {
        // Constructor code goes here.
    }

    // Any other methods
}


to insert :after :list :value
  localmake "tail member :after :list
  if not empty? :tail [.setbf :tail fput :value bf :tail]
  output :list
end

show insert 5 [3 5 1 8] 2


MODULE SinglyLinkedList EXPORTS Main;

TYPE
  Link = REF LinkRcd;
  LinkRcd = RECORD
    Next: Link;
    Data: INTEGER
  END;

  PROCEDURE InsertAppend(anchor, next: Link) =
  BEGIN
    IF anchor # NIL AND next # NIL THEN
      next.Next := anchor.Next;
      anchor.Next := next
    END
  END InsertAppend;

VAR
  a: Link := NEW(Link, Next := NIL, Data := 1);
  b: Link := NEW(Link, Next := NIL, Data := 2);
  c: Link := NEW(Link, Next := NIL, Data := 3);

BEGIN
  InsertAppend(a, b);
  InsertAppend(a, c)
END SinglyLinkedList.


type Node[T] = ref object
  next: Node[T]
  data: T

proc newNode[T](data: T): Node[T] =
  Node[T](data: data)

var a = newNode 12
var b = newNode 13
var c = newNode 14

proc insertAppend(a, n: var Node) =
  n.next = a.next
  a.next = n

a.insertAppend(b)
b.insertAppend(c)


let rec insert_after a b = function
   c :: cs when a = c -> a :: b :: cs
 | c :: cs            -> c :: insert_after a b cs
 | []                 -> raise Not_found


do
  t = eval[input["Enter amount of time to sleep: ", "1 second"]]
while ! (t conforms time)

println["Sleeping..."]
sleep[t]
println["Awake!"]


package main

import "time"
import "fmt"

func main() {
    fmt.Print("Enter number of seconds to sleep: ")
    var sec float64
    fmt.Scanf("%f", &sec)
    fmt.Print("Sleeping…")
    time.Sleep(time.Duration(sec * float64(time.Second)))
    fmt.Println("\nAwake!")
}


def sleepTest = {
    println("Sleeping...")
    sleep(it)
    println("Awake!")
}


import Control.Concurrent

main = do seconds <- readLn
          putStrLn "Sleeping..."
          threadDelay $ round $ seconds * 1000000
          putStrLn "Awake!"


DLG(NameEdit = milliseconds, Button = "Go to sleep")
WRITE(StatusBar) "Sleeping ... "
SYSTEM(WAIT = milliseconds)
WRITE(Messagebox) "Awake!"


smithQ[n_] := Not[PrimeQ[n]] &&
            Total[IntegerDigits[n]] == Total[IntegerDigits /@ Flatten[ConstantArray @@@ FactorInteger[n]],2];
Select[Range[2, 10000], smithQ]


MODULE SmithNumbers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE SumDigits(n : INTEGER) : INTEGER;
VAR sum : INTEGER;
BEGIN
    sum := 0;
    WHILE n > 0 DO
        sum := sum + (n MOD 10);
        n := n DIV 10;
    END;
    RETURN sum;
END SumDigits;

VAR
    n,i,j,fc,sum,rc : INTEGER;
    buf : ARRAY[0..63] OF CHAR;
BEGIN
    rc := 0;
    FOR i:=1 TO 10000 DO
        n := i;
        fc := 0;
        sum := SumDigits(n);

        j := 2;
        WHILE n MOD j = 0 DO
            INC(fc);
            sum := sum - SumDigits(j);
            n := n DIV j;
        END;

        j := 3;
        WHILE j*j<=n DO
            WHILE n MOD j = 0 DO
                INC(fc);
                sum := sum - SumDigits(j);
                n := n DIV j;
            END;
            INC(j,2);
        END;

        IF n#1 THEN
            INC(fc);
            sum := sum - SumDigits(n);
        END;

        IF (fc>1) AND (sum=0) THEN
            FormatString("%4i  ", buf, i);
            WriteString(buf);
            INC(rc);
            IF rc=10 THEN
                rc := 0;
                WriteLn;
            END;
        END;
    END;

    ReadChar;
END SmithNumbers.


function Singleton() {
	if(Singleton._instance) return Singleton._instance;
	this.set("");
	Singleton._instance = this;
}

Singleton.prototype.set = function(msg) { this.msg = msg; }
Singleton.prototype.append = function(msg) { this.msg += msg; }
Singleton.prototype.get = function() { return this.msg; }

var a = new Singleton();
var b = new Singleton();
var c = new Singleton();

a.set("Hello");
b.append(" World");
c.append("!!!");

document.write( (new Singleton()).get() );


struct IAmaSingleton end

x = IAmaSingleton()
y = IAmaSingleton()

println("x == y is $(x == y) and x === y is $(x === y).")


// version 1.1.2

object Singleton {
    fun speak() = println("I am a singleton")
}

fun main(args: Array<String>) {
    Singleton.speak()
}


// Define the thread if it doesn't exist
// New definition supersede any current threads.

not ::serverwide_singleton->istype
? define serverwide_singleton => thread {
    data public switch = 'x'
}

local(
    a = serverwide_singleton,
    b = serverwide_singleton,
)

#a->switch = 'a'
#b->switch = 'b'

#a->switch // b


Singleton ::= Object clone tap {
  self id := 0.
  self newID := {
    self id := self id + 1.
  }.
  self clone := {
    err ArgError clone tap { self message := "Singleton object!". } throw.
  }.
}.

println: Singleton newID. ; 1
println: Singleton newID. ; 2
println: Singleton newID. ; 3


Collection Class new: LinkedList(data, mutable next)

LinkedList method: initialize   := next := data ;
LinkedList method: data   @data ;
LinkedList method: next   @next ;
LinkedList method: add(e) e @next LinkedList new := next ;

LinkedList method: forEachNext
   dup ifNull: [ drop self ]
   dup 1 ifEq: [ drop false return ]
   dup next dup ifNull: [ drop 1 ]
   swap data true ;

: testLink  LinkedList new($A, null) dup add($B) dup add($C) ;

testLink println


list = .linkedlist~new
index = list~insert("abc")   -- insert a first item, keeping the index
list~insert("def")           -- adds to the end
list~insert("123", .nil)     -- adds to the begining
list~insert("456", index)    -- inserts between "abc" and "def"
list~remove(index)           -- removes "abc"


type
  pCharNode = ^CharNode;
  CharNode = record
               data: char;
               next: pCharNode;
             end;

(* This procedure inserts a node (newnode) directly after another node which is assumed to already be in a list.
  It does not allocate a new node, but takes an already allocated node, thus allowing to use it (together with
  a procedure to remove a node from a list) for splicing a node from one list to another. *)
procedure InsertAfter(listnode, newnode: pCharNode);
begin
  newnode^.next := listnode^.next;
  listnode^.next := newnode;
end;


my @l  = ($A, $B);
push @l, $C, splice @l, 1;


with javascript_semantics
enum NEXT,DATA
constant empty_sll = {{1}}
sequence sll = deep_copy(empty_sll)

procedure insert_after(object data, integer pos=length(sll))
    sll = append(sll,{sll[pos][NEXT],data})
    sll[pos][NEXT] = length(sll)
end procedure

insert_after("ONE")
insert_after("TWO")
insert_after("THREE")

?sll


procedure main()

repeat {
   writes("Enter number of seconds to sleep :")
   s := reads()
   if s = ( 0 < integer(s)) then break
   }

write("\nSleeping for ",s," seconds.")
delay(1000 * s)
write("Awake!")
end


read,i,prompt='Input sleep time in seconds: '
print,'Sleeping...'
wait,i ; in seconds, but accepts floats(/fractional) as input
print,'Awake!'


sleep =: 6!:3

sleeping=: monad define
  smoutput 'Sleeping...'
  sleep y
  smoutput 'Awake!'
)


import java.util.InputMismatchException;
import java.util.Scanner;

public class Sleep {
    public static void main(final String[] args) throws InterruptedException {
        try {
            int ms = new Scanner(System.in).nextInt(); //Java's sleep method accepts milliseconds
            System.out.println("Sleeping...");
            Thread.sleep(ms);
            System.out.println("Awake!");
        } catch (InputMismatchException inputMismatchException) {
            System.err.println("Exception: " + inputMismatchException);
        }
    }
}


WinActivate, ahk_class MozillaUIWindowClass
Click 200, 200 right  ; relative to external window (firefox)
sleep, 2000
WinMinimize
CoordMode, Mouse, Screen
Click 400, 400 right  ; relative to top left corner of the screen.


import strformat

func primeFactors(n: int): seq[int] =
  result = newSeq[int]()
  var n = n
  var i = 2
  while n mod i == 0:
    result.add(i)
    n = n div i
  i = 3
  while i * i <= n:
    while n mod i == 0:
      result.add(i)
      n = n div i
    inc i, 2
  if n != 1:
    result.add(n)

func sumDigits(n: int): int =
  var n = n
  var sum = 0
  while n > 0:
    inc sum, n mod 10
    n = n div 10
  sum

var cnt = 0
for n in 1..10_000:
  var factors = primeFactors(n)
  if factors.len > 1:
    var sum = sumDigits(n)
    for f in factors:
      dec sum, sumDigits(f)
    if sum == 0:
      stdout.write(&"{n:4}  ")
      inc cnt
    if cnt == 10:
      cnt = 0
      stdout.write("\n")
echo()


use Collection;

class Test {
  function : Main(args : String[]) ~ Nil {
    for(n := 1; n < 10000; n+=1;) {
      factors := PrimeFactors(n);
      if(factors->Size() > 1) {
        sum := SumDigits(n);
        each(i : factors) {
          sum -= SumDigits(factors->Get(i));
        };

        if(sum = 0) {
          n->PrintLine();
        };
      };
    };
  }

  function : PrimeFactors(n : Int) ~ IntVector {
    result := IntVector->New();

    for(i := 2; n % i = 0; n /= i;) {
      result->AddBack(i);
    };

    for(i := 3; i * i <= n; i += 2;) {
      while(n % i = 0) {
        result->AddBack(i);
        n /= i;
      };
    };

    if(n <> 1) {
      result->AddBack(n);
    };

    return result;
  }

  function : SumDigits(n : Int) ~ Int {
    sum := 0;
    while(n > 0) {
      sum += (n % 10);
      n /= 10;
    };

    return sum;
  }
}


-- parent script "SingletonDemo"

property _instance
property _someProperty

----------------------------------------
-- @constructor
----------------------------------------
on new (me)
  if not voidP(me.script._instance) then return me.script._instance
  me.script._instance = me
  me._someProperty = 0
  return me
end

----------------------------------------
-- sample method
----------------------------------------
on someMethod (me, x)
  me._someProperty = me._someProperty + x
  return me._someProperty
end


:- object(singleton).

    :- public(value/1).
    value(Value) :-
        state(Value).

    :- public(set_value/1).
    set_value(Value) :-
        retract(state(_)),
        assertz(state(Value)).

    :- private(state/1).
    :- dynamic(state/1).
    state(0).

:- end_object.


/* NetRexx */
options replace format comments java crossref symbols binary

import java.util.random

class RCSingleton public

  method main(args = String[]) public static
    RCSingleton.Testcase.main(args)
    return

  -- ---------------------------------------------------------------------------
  class RCSingleton.Instance public

    properties private static
      _instance = Instance()

    properties private
      _refCount = int
      _random   = Random

    method Instance() private
      this._refCount = 0
      this._random = Random()
      return

    method getInstance public static returns RCSingleton.Instance
      return _instance

  method getRandom public returns Random
    return _random

    method addRef public protect
      _refCount = _refCount + 1
      return

    method release public protect
      if _refCount > 0 then
        _refCount = _refCount - 1
      return

    method getRefCount public protect returns int
      return _refCount

  -- ---------------------------------------------------------------------------
  class RCSingleton.Testcase public implements Runnable

  properties private
    _instance = RCSingleton.Instance

  method run public
    say threadInfo'|-'
    thud = Thread.currentThread
    _instance = RCSingleton.Instance.getInstance
    thud.yield
    _instance.addRef
    say threadInfo'|'_instance.getRefCount
    thud.yield
    do
      thud.sleep(_instance.getRandom.nextInt(1000))
    catch ex = InterruptedException
      ex.printStackTrace
      end
    _instance.release
    say threadInfo'|'_instance.getRefCount
    return

  method main(args = String[]) public static
    threads = [ Thread -
      Thread(Testcase()), Thread(Testcase()), Thread(Testcase()), -
      Thread(Testcase()), Thread(Testcase()), Thread(Testcase()) ]
    say threadInfo'|-'
    mn = Testcase()
    mn._instance = RCSingleton.Instance.getInstance
    say mn.threadInfo'|'mn._instance.getRefCount
    mn._instance.addRef
    say mn.threadInfo'|'mn._instance.getRefCount
    do
      loop tr over threads
        (Thread tr).start
        end tr
      Thread.sleep(400)
    catch ex = InterruptedException
      ex.printStackTrace
      end
    mn._instance.release
    say mn.threadInfo'|'mn._instance.getRefCount
    return

  method threadInfo public static returns String
    trd = Thread.currentThread
    tid = trd.getId
    hc  = trd.hashCode
    info = Rexx(trd.getName).left(16, '_')':' -
        || Rexx(Long.toString(tid)).right(10, 0)':' -
        || '@'Rexx(Integer.toHexString(hc)).right(8, 0)
    return info


(de insertAfter (Item Lst New)
   (when (member Item Lst)
      (con @ (cons New (cdr @))) )
   Lst )


/* Let H be a pointer to a node in a one-way-linked list. */
/* Insert an element, whose value is given by variable V, following that node. */

allocate node set (Q);
node.p = H; /* The new node now points at the list where we want to insert it. */
node.value = V;
H->p = Q;   /* Break the list at H, and point it at the new node. */


define insert_into_list(anchor, x);
   cons(x, back(anchor)) -> back(anchor);
enddefine;
;;; Build inital list
lvars l1 = cons("a", []);
insert_into_list(l1, "b");
;;; insert c
insert_into_list(l1,  "c");


Procedure insertAfter(Value, *node.MyData = #Null)
  Protected *newNode.MyData = AllocateMemory(SizeOf(MyData))
  If *newNode
    If *node
      *newNode\next = *node\next
      *node\next = *newNode
    EndIf
    *newNode\Value = Value
  EndIf
  ProcedureReturn *newNode ;return pointer to newnode
EndProcedure

Define *SL_List.MyData, a = 1, b = 2, c = 3

*SL_List = insertAfter(a) ;start the list
insertAfter(b, *SL_List) ;insert after head of list
insertAfter(c, *SL_List) ;insert after head of list and before tail


def chain_insert(lst, at, item):
    while lst is not None:
        if lst[0] == at:
            lst[1] = [item, lst[1]]
            return
        else:
            lst = lst[1]
    raise ValueError(str(at) + " not found")

chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
print chain


<script>

  setTimeout(function () {
    document.write('Awake!')
  }, prompt("Number of milliseconds to sleep"));

  document.write('Sleeping... ');

</script>


/*
   Sleep, in Jsish
*/

printf('Sleep time (in milliseconds)? ');
var ms = parseInt(console.input());

puts('Sleeping...');
sleep(ms);
puts('Awake!');


print("Please enter sleep duration in seconds: ")
input = int(readline(STDIN))
println("Sleeping...")
sleep(input)
println("Awake!")


// version 1.0.6

fun main(args: Array<String>) {
    print("Enter number of milliseconds to sleep: ")
    val ms = readLine()!!.toLong()
    println("Sleeping...")
    Thread.sleep(ms)
    println("Awake!")
}


stdoutnl('Sleeping...')
sleep(5000) // Sleep 5 seconds
stdoutnl('Awake!')


#define WINVER 0x500
#include<windows.h>

int main()
{
	int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
	int x = maxX/2, y = maxY/2;
	double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;

	INPUT ip;

	ZeroMemory(&ip,sizeof(ip));

	ip.type = INPUT_MOUSE;

	while(x > 5 || y < maxY-5){

	ip.mi.mouseData = 0;
	ip.mi.dx = x * factorX;
	ip.mi.dy = y * factorY;
	ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;

	SendInput(1,&ip,sizeof(ip));
	Sleep(1);
	if(x>3)
		x-=1;
	if(y<maxY-3)
		y+=1;
	}

	ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;

	SendInput(1,&ip,sizeof(ip));

	return 0;
}


(defun sh (cmd)
#+clisp (shell cmd)
#+ecl (si:system cmd)
#+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)
#+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*))
(sh "xdotool mousemove 0 0 click 1")
(sleep 2)
(sh "xdotool mousemove 300 300 click 1")


using fwt
using gfx

class Main
{
  public static Void main ()
  {
    button1 := Button
    {
      text = "don't click!"
      onAction.add |Event e|
      {
        echo ("clicked by code")
      }
    }
    button2 := Button
    {
      text = "click"
      onAction.add |Event e|
      {
        // fire all the event listeners on button1
        button1.onAction.fire(e)
      }
    }
    Window
    {
      title = "simulate mouse event"
      size = Size (300, 200)
      button1,
      button2,
    }.open
  }
}


isSmith(n)=my(f=factor(n)); if(#f~==1 && f[1,2]==1, return(0)); sum(i=1, #f~, sumdigits(f[i, 1])*f[i, 2]) == sumdigits(n);
select(isSmith, [1..9999])


program SmithNum;
{$IFDEF FPC}
  {$MODE objFPC} //result and  useful for x64
  {$CODEALIGN PROC=64}
{$ENDIF}
uses
  sysutils;
type
  tdigit  = byte;
  tSum    = LongInt;
const
  base = 10;
  //maxDigitCnt *(base-1) <= High(tSum)
  //maxDigitCnt <= High(tSum) DIV (base-1);
  maxDigitCnt = 16;

  StartPrimNo = 6;
  csegsieveSIze = 2*3*5*7*11*13;//prime 0..5
type
  tDgtSum = record
              dgtNum : LongInt;
              dgtSum : tSum;
              dgts   : array[0..maxDigitCnt-1] of tdigit;
            end;
  tNumFactype = word;
  tnumFactor = record
                 numfacCnt: tNumFactype;
                 numfacts : array[1..15] of tNumFactype;
               end;
  tpnumFactor= ^tnumFactor;

  tsieveprim = record
                 spPrim   : Word;
                 spDgtsum : Word;
                 spOffset : LongWord;
               end;
  tpsieveprim = ^tsieveprim;

  tsievePrimarr  = array[0..6542-1] of tsieveprim;
  tsegmSieve     = array[1..csegsieveSIze] of tnumFactor;

var
  Primarr:tsievePrimarr;
  copySieve,
  actSieve : tsegmSieve;
  PrimDgtSum :tDgtSum;
  PrimCnt : NativeInt;

function IncDgtSum(var ds:tDgtSum):boolean;
//add 1 to dgts and corrects sum of Digits
//return if overflow happens
var
  i : NativeInt;
Begin
  i := High(ds.dgts);
  inc(ds.dgtNum);
  repeat
    IF ds.dgts[i] < Base-1 then
    //add one and done
    Begin
      inc(ds.dgts[i]);
      inc(ds.dgtSum);
      BREAK;
    end
    else
    Begin
      ds.dgts[i] := 0;
      dec(ds.dgtSum,Base-1);
    end;
    dec(i);
 until i < Low(ds.dgts);
 result := i < Low(ds.dgts)
end;

procedure OutDgtSum(const ds:tDgtSum);
var
  i : NativeInt;
Begin
  i := Low(ds.dgts);
  repeat
    write(ds.dgts[i]:3);
    inc(i);
  until i > High(ds.dgts);
  writeln(' sum of digits :  ',ds.dgtSum:3);
end;

procedure OutSieve(var s:tsegmSieve);
var
  i,j : NativeInt;
Begin
  For i := Low(s) to High(s) do
    with s[i] do
    Begin
      write(i:6,numfacCnt:4);
      For j := 1 to numfacCnt do
        write(numFacts[j]:5);
      writeln;
    end;
end;

procedure SieveForPrimes;
// sieve for all primes < High(Word)
var
  sieve : array of byte;
  pS : pByte;
  p,i   : NativeInt;
Begin
  setlength(sieve,High(Word));
  Fillchar(sieve[Low(sieve)],length(sieve),#0);
  pS:= @sieve[0]; //zero based
  dec(pS);// make it one based
  //sieve
  p := 2;
  repeat
    i := p*p;
    IF i> High(Word) then
      BREAK;
    repeat pS[i] := 1; inc(i,p); until i > High(Word);
    repeat inc(p) until pS[p] = 0;
  until false;
  //now fill array of primes
  fillchar(PrimDgtSum,SizeOf(PrimDgtSum),#0);
  IncDgtSum(PrimDgtSum);//1
  i := 0;
  For p := 2 to High(Word) do
  Begin
    IncDgtSum(PrimDgtSum);
    if pS[p] = 0 then
    Begin
      with PrimArr[i] do
      Begin
        spOffset := 2*p;//start at 2*prime
        spPrim   := p;
        spDgtsum := PrimDgtSum.dgtSum;
      end;
      inc(i);
    end;
  end;
  PrimCnt := i-1;
end;

procedure MarkWithPrime(SpIdx:NativeInt;var sf:tsegmSieve);
var
  i : NativeInt;
  pSf :^tnumFactor;
  MarkPrime : NativeInt;
Begin
  with Primarr[SpIdx] do
  Begin
    MarkPrime := spPrim;
    i :=  spOffSet;
    IF i <= csegsieveSize then
    Begin
      pSf := @sf[i];
      repeat
        pSf^.numFacts[pSf^.numfacCnt+1] := SpIdx;
        inc(pSf^.numfacCnt);
        inc(pSf,MarkPrime);
        inc(i,MarkPrime);
      until i > csegsieveSize;
    end;
    spOffset := i-csegsieveSize;
  end;
end;

procedure InitcopySieve(var cs:tsegmSieve);
var
  pr: NativeInt;
Begin
  fillchar(cs[Low(cs)],sizeOf(cs),#0);
  For Pr := 0 to 5 do
  Begin
    with Primarr[pr] do
     spOffset := spPrim;//mark the prime too
    MarkWithPrime(pr,cs);
  end;
end;

procedure MarkNextSieve(var s:tsegmSieve);
var
  idx: NativeInt;
Begin
  s:= copySieve;
  For idx := StartPrimNo to PrimCnt do
    MarkWithPrime(idx,s);
end;

function DgtSumInt(n: NativeUInt):NativeUInt;
var
  r : NativeUInt;
Begin
  result := 0;
  repeat
    r := n div base;
    inc(result,n-base*r);
    n := r
  until r = 0;
end;

{function DgtSumOfFac(pN: tpnumFactor;dgtNo:tDgtSum):boolean;}
function TestSmithNum(pN: tpnumFactor;dgtNo:tDgtSum):boolean;
var
  i,k,r,dgtSumI,dgtSumTarget : NativeUInt;
  pSp:tpsieveprim;
  pNumFact : ^tNumFactype;
Begin
  i := dgtNo.dgtNum;
  dgtSumTarget :=dgtNo.dgtSum;

  dgtSumI := 0;
  with pN^ do
  Begin
    k := numfacCnt;
    pNumFact := @numfacts[k];
  end;

  For k := k-1 downto 0 do
  Begin
    pSp := @PrimArr[pNumFact^];
    r := i DIV pSp^.spPrim;
    repeat
      i := r;
      r := r DIV pSp^.spPrim;
      inc(dgtSumI,pSp^.spDgtsum);
    until (i - r* pSp^.spPrim) <> 0;
    IF dgtSumI > dgtSumTarget then
    Begin
      result := false;
      EXIT;
    end;
    dec(pNumFact);
  end;
  If i <> 1 then
    inc(dgtSumI,DgtSumInt(i));
  result := dgtSumI = dgtSumTarget
end;

function CheckSmithNo(var s:tsegmSieve;var dgtNo:tDgtSum;Lmt:NativeInt=csegsieveSIze):NativeUInt;
var
  pNumFac : tpNumFactor;
  i : NativeInt;
Begin
  result := 0;
  i := low(s);
  pNumFac := @s[i];
  For i := i to lmt do
  Begin
    incDgtSum(dgtNo);
    IF pNumFac^.numfacCnt<> 0 then
      IF TestSmithNum(pNumFac,dgtNo) then
      Begin
        inc(result);
        //Mark as smith number
        inc(pNumFac^.numfacCnt,1 shl 15);
      end;
    inc(pNumFac);
  end;
end;

const
  limit = 100*1000*1000;
var
  actualNo :tDgtSum;
  i,s : NativeInt;
Begin
  SieveForPrimes;
  InitcopySieve(copySieve);
  i := 1;
  s:= -6;//- 2,3,5,7,11,13

  fillchar(actualNo,SizeOf(actualNo),#0);
  while i < Limit-csegsieveSize do
  Begin
    MarkNextSieve(actSieve);
    inc(s,CheckSmithNo(actSieve,actualNo));
    inc(i, csegsieveSize);
  end;
  //check the rest
  MarkNextSieve(actSieve);
  inc(s,CheckSmithNo(actSieve,actualNo,Limit-i+1));
  write(s:8,' smith-numbers up to ',actualNo.dgtnum:10);
end.


type Singleton = object # Singleton* would export
  foo*: int

var single* = Singleton(foo: 0)


class Singleton {
  @singleton : static : Singleton;

  New : private () {
  }

  function : GetInstance() ~ Singleton {
    if(@singleton <> Nil) {
      @singleton := Singleton->New();
    };

    return @singleton;
  }

  method : public : DoStuff() ~ Nil {
    ...
  }
}


// SomeSingleton.h
@interface SomeSingleton : NSObject
{
  // any instance variables
}

+ (SomeSingleton *)sharedInstance;

@end


Object Class new: Sequence(channel)
Sequence method: initialize(initialValue)
   Channel newSize(1) := channel
   @channel send(initialValue) drop ;

Sequence method: nextValue  @channel receive dup 1 + @channel send drop ;


a = .singleton~new
b = .singleton~new

a~foo = "Rick"
if a~foo \== b~foo then say "A and B are not the same object"

::class singleton
-- initialization method for the class
::method init class
  expose singleton
  -- mark this as unallocated.  We could also just allocate
  -- the singleton now, but better practice is probably wait
  -- until it is requested
  singleton = .nil

-- override the new method.  Since this is a guarded
-- method by default, this is thread safe
::method new class
  expose singleton
  -- first request?  Do the real creation now
  if singleton == .nil then do
     -- forward to the super class.  We use this form of
     -- FORWARD rather than explicit call ~new:super because
     -- this takes care of any arguments passed to NEW as well.
     forward class(super) continue
     singleton = result
  end
  return singleton

-- an attribute that can be used to demonstrate this really is
a singleton.
::attribute foo


#lang racket

;; insert b after a in a mutable list (assumes that a is in the input list)
(define (insert-after! list a b)
  (if (equal? (mcar list) a)
    (set-mcdr! list (mcons b (mcdr list)))
    (insert-after! (mcdr list) a b)))

(define l (mcons 1 (mcons 2 (mcons 3 '()))))
(insert-after! l 2 2.5)
l ; -> (mcons 1 (mcons 2 (mcons 2.5 (mcons 3))))


    method insert ($value) {
        $.next = Cell.new(:$value, :$.next)
    }


/*REXX program demonstrates how to create and show a single-linked list.*/
@.=0                                   /*define a null linked list.     */
call [email protected] 3                            /*linked list:  12 Proth primes. */
call [email protected] 5
call [email protected] 13
call [email protected] 17
call [email protected] 41
call [email protected] 97
call [email protected] 113
call [email protected] 193
call [email protected] 241
call [email protected] 257
call [email protected] 353
call [email protected] 449
call [email protected]
     after = 97                        /* ◄──── REXX code to do insert. */
     newVal=100                        /* ◄────   "    "   "  "    "    */
     #[email protected]..after                        /* ◄────   "    "   "  "    "    */
     call [email protected] #,newVal                /* ◄────   "    "   "  "    "    */
say
say 'a new value of' newval "has been inserted after element value:" after
call [email protected]
exit                                   /*stick a fork in it, we're done.*/
/*──────────────────────────────────[email protected] subroutine─────────────────────*/
[email protected]:  procedure expose @.;  parse arg #,y
@.[email protected]._last+1                      /*bump number of list elements.  */
[email protected]._last
@._._value=y                           /*define new value list element. */
@._.[email protected].#._next
@.#._next=_
@..y=_                                 /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return                                 /*return to invoker of this sub. */
/*──────────────────────────────────[email protected] subroutine────────────────────*/
[email protected]: say;  w=max(7, @.max_width )    /*use the max width of nums or 7.*/
say center('item',6)        center('value',w)        center('next',6)
say center(''    ,6,'─')    center(''     ,w,'─')    center(''    ,6,'─')
p=1
        do j=1  until p==0      /*show all entries of linked list*/
        say  right(j,6)   right(@.p._value,w)   right(@.p._next,6)
        [email protected].p._next
        end   /*j*/
return
/*──────────────────────────────────[email protected] subroutine─────────────────────*/
[email protected]: procedure expose @.; parse arg y /*get element to be added to list*/
[email protected]._last                              /*set the previous last element. */
n=_+1                                  /*bump last ptr in linked list.  */
@._._next=n                            /*set the  next  pointer value.  */
@._last=n                              /*define next item in linked list*/
@.n._value=y                           /*set item to the value specified*/
@.n._next=0                            /*set the  next  pointer value.  */
@..y=n                                 /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return                                 /*return to invoker of this sub. */


make "Void "V0
make "Long "U4
make "kernel32_handle libload "kernel32.dll
to Sleep :dwMilliseconds
end
external "Sleep [ Void Sleep Long] :kernel32_handle

to millisleep :n
	print [Sleeping...]
	Sleep :n                  ; units: 1/1000th of a second
	print [Awake.]
end


Input "Please input the number of milliseconds you would like to sleep. "; sleeptime
Print "Sleeping..."
CallDLL #kernel32, "Sleep", sleeptime As long, ret As void
Print "Awake!"


on doSleep (ms)
  put "Sleeping..."
  sleep(ms)
  put "Awake!"
end


to sleep :n
print [Sleeping...]
wait :n                  ; units: 1/60th of a second
print [Awake.]
end


:- object(sleep).

    :- public(how_long/1).

    how_long(Seconds) :-
        write('Sleeping ...'), nl,
        thread_sleep(Seconds),
        write('... awake!'), nl.

:- end_object.


#include "fbgfx.bi"
#define rect 4

Windowtitle "Mouse events"
Screen 19,32
Dim Shared As Integer xres, yres
Screeninfo xres, yres

Type box
    As Single x, y, z
    As String caption
    As Uinteger textcol, boxcol
End Type

Dim Shared As box label(rect,1)
Dim Shared As box button(rect,1)
Dim Shared As Boolean flag
Dim Shared As fb.event e
Dim As Uinteger background = Rgb(100,100,100)

Sub thickline(x1 As Double, y1 As Double, x2 As Double, y2 As Double,_
    thickness As Double, colour As Uinteger, im As Any Pointer = 0)
    Dim p As Uinteger = Rgb(255, 255, 254)
    If thickness < 2 Then
        Line(x1,y1)-(x2,y2), colour
    Else
        Dim As Double h = Sqr((x2-x1)^2+(y2-y1)^2), s = (y1-y2)/h, c = (x2-x1)/h
        For x As Integer = 1 To 2
            Line im,(x1+s*thickness/2,y1+c*thickness/2)-(x2+s*thickness/2,y2+c*thickness/2),p
            Line im,(x1-s*thickness/2,y1-c*thickness/2)-(x2-s*thickness/2,y2-c*thickness/2),p
            Line im,(x1+s*thickness/2,y1+c*thickness/2)-(x1-s*thickness/2,y1-c*thickness/2),p
            Line im,(x2+s*thickness/2,y2+c*thickness/2)-(x2-s*thickness/2,y2-c*thickness/2),p
            Paint im,((x1+x2)/2, (y1+y2)/2), p, p
            p = colour
        Next x
    End If
End Sub

Function inbox(p1() As box, p2 As box) As Integer
    Type pt2d : As Single x, y : End Type
    Type ln2d : As pt2d v1, v2 : End Type
    #macro isleft(L,p)
        -Sgn((L.v1.x-L.v2.x)*(p.y-L.v2.y) - (p.x-L.v2.x)*(L.v1.y-L.v2.y))
    #endmacro
    Dim As Single n1 = p1(rect,0).z
    Dim As Integer index, nextindex
    Dim send As ln2d
    Dim As Integer n, wn = 0
    For n = 1 To 4
        index = n Mod 5 : nextindex = (n+1) Mod 5
        If nextindex = 0 Then nextindex = 1
        send.v1.x = p1(index,n1).x : send.v2.x = p1(nextindex,n1).x
        send.v1.y = p1(index,n1).y : send.v2.y = p1(nextindex,n1).y
        If p1(index,n1).y <= p2.y Then
            If p1(nextindex,n1).y > p2.y Then
                If isleft(send,p2) > 0 Then wn += 1
            End If
        Else
            If p1(nextindex,n1).y <= p2.y Then
                If isleft(send,p2) < 0 Then wn -= 1
            End If
        End If
    Next n
    Return wn
End Function

Sub draw_box(p() As box, col As Uinteger, pnt As String = "paint", im As Any Pointer = 0)
    Dim As Integer index, nextindex
    Dim As Single n1 = p(rect,0).z
    Dim As Double xc, yc
    For n As Integer = 1 To 4
        xc += p(n,n1).x : yc += p(n,n1).y
        index = n Mod 5 : nextindex = (n+1) Mod 5
        If nextindex = 0 Then nextindex = 1
        thickline(p(index,n1).x,p(index,n1).y, p(nextindex,n1).x,p(nextindex,n1).y,4,col,im)
    Next n
    xc /= Ubound(p) : yc /= Ubound(p)
    If pnt = "paint" Then Paint(xc,yc), col, col
End Sub

Sub highlightbox(box() As box, mp As box, col As Uinteger)
    box(rect,0).z = 1
    If inbox(box(),mp) Then draw_box(box(),col,"dont_paint")
End Sub

Sub checkbox(box() As box,mp As box)
    flag = True
    label(rect,1).caption = box(rect,1).caption
    label(rect,1).textcol = box(rect,1).textcol
    label(rect,1).boxcol  = box(rect,1).boxcol
End Sub

Sub drawbox(x As Integer, y As Integer, box()As box, boxlength As Integer, _
    boxheight As Integer, col As Uinteger, highlight As Uinteger, caption As String)
    Dim As box startpoint
    startpoint.x = x : startpoint.y = y
    Dim As Integer mmx, mmy
    Getmouse mmx, mmy
    Dim As box mouse
    mouse.x = mmx : mouse.y = mmy
    box(rect,1).boxcol = col
    box(rect,1).caption = caption
    Dim As Uinteger outline, count = 1
    outline = Rgb(255,255,255)
    For x As Integer = 1 To 4
        Select Case x
        Case 1
            box(1,count).x = startpoint.x
            box(1,count).y = startpoint.y
        Case 2
            box(2,count).x = box(1,count).x + boxlength
            box(2,count).y = box(1,count).y
        Case 3
            box(3,count).x = box(2,count).x
            box(3,count).y = box(2,count).y + boxheight
        Case 4
            box(4,count).x = box(3,count).x - boxlength
            box(4,count).y = box(3,count).y
        End Select
    Next x
    box(rect,0).z = 1
    draw_box(box(),col)
    draw_box(box(),outline,"nopaint")
    If inbox(box(),mouse) Then
        highlightbox(box(),mouse,highlight)
        If (Screenevent(@e)) Then
            If e.type = fb.EVENT_MOUSE_BUTTON_PRESS Then checkbox(box(),mouse)
        End If
    End If
    Draw String(box(1,1).x+5,box(1,1).y+5), box(rect,1).caption,box(rect,1).textcol
End Sub

' ---------- Main Program ----------
Do
    Screenlock
    Cls
    Paint(0,0), background
    Draw String(300,50), "BUTTON CLICK TEST", Rgb(0,0,200)

    drawbox(100,100,button(),100,50,Rgb(200,200,0),Rgb(00,0,200),"Box 1")
    drawbox(100,200,button(),100,50,Rgb(200,0,190),Rgb(00,0,200),"Box 2")
    drawbox(100,300,button(),100,50,Rgb(0,200,190),Rgb(00,0,200),"Box 3")

    If flag Then drawbox(400,100,label(),250,250,label(rect,1).boxcol,Rgb(255,255,255),label(rect,1).caption)
    If (Screenevent(@e)) Then
        If e.type=13 Then End
    End If
    Screenunlock
    Sleep 1, 1
Loop Until Inkey = Chr(27)


use ntheory qw/:all/;
my @smith;
forcomposites {
  push @smith, $_  if sumdigits($_) == sumdigits(join("",factor($_)));
} 10000-1;
say scalar(@smith), " Smith numbers below 10000.";
say "@smith";


with javascript_semantics
function sum_digits(integer n, base=10)
    integer res = 0
    while n do
        res += remainder(n,base)
        n = floor(n/base)
    end while
    return res
end function

function smith(integer n)
    sequence p = prime_factors(n,true,-1)
    if length(p)=1 then return false end if
    integer sp = sum(apply(p,sum_digits)),
            sn = sum_digits(n)
    return sn=sp
end function

sequence s = apply(filter(tagset(10000),smith),sprint)
printf(1,"%d smith numbers found: %s\n",{length(s),join(shorten(s,"",8),", ")})


Class Singleton
  static sys inst 'private
  int instantiated() { return inst }
  void constructor(){ if not inst then [email protected] }

  'all other methods start with @this=inst
end class

'if not singleton.instantiated
  new Singleton MySingleton
'endif


declare
   local
      class Singleton
	 meth init
	    skip
	 end
      end
      L = {NewLock}
      Instance
   in
      fun {GetInstance}
	 lock L then
	    if {IsFree Instance} then
	       Instance = {New Singleton init}
	    end
	    Instance
	 end
      end
   end


package Singleton;
use strict;
use warnings;

my $Instance;

sub new {
    my $class = shift;
    $Instance ||= bless {}, $class; # initialised once only
}

sub name {
    my $self = shift;
    $self->{name};
}

sub set_name {
    my ($self, $name) = @_;
    $self->{name} = $name;
}

package main;

my $s1 = Singleton->new;
$s1->set_name('Bob');
printf "name: %s, ref: %s\n", $s1->name, $s1;

my $s2 = Singleton->new;
printf "name: %s, ref: %s\n", $s2->name, $s2;


-- <separate include file>
object chk = NULL
class singleton
    public procedure check()
        if chk==NULL then
            chk = this
        elsif this!=chk then
            ?9/0
        end if
        ?"ok"
    end procedure
end class

global singleton s = new()
--global singleton s2 = new()
-- </separate include file>

s.check()
--s2.check()    -- dies


class Singleton {
  protected static $instance = null;
  public $test_var;
  private function __construct(){
    //Any constructor code
  }
  public static function getInstance(){
    if (is_null(self::$instance)){
      self::$instance = new self();
    }
    return self::$instance;
  }
}

$foo = Singleton::getInstance();
$foo->test_var = 'One';

$bar = Singleton::getInstance();
echo $bar->test_var; //Prints 'One'

$fail = new Singleton(); //Fatal error


class ListNode
  def insert_after(search_value, new_value)
    if search_value == value
      self.succ = self.class.new(new_value, succ)
    elsif self.succ.nil?
      raise StandardError, "value #{search_value} not found in list"
    else
      self.succ.insert_after(search_value, new_value)
    end
  end
end

list = ListNode.new(:a, ListNode.new(:b))
list.insert_after(:a, :c)


impl<T> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push(&mut self, elem: T) {
    let new_node = Box::new(Node {
        elem: elem,
        next: self.head.take(),
    });
    self.head = Some(new_node);
}


/*
Here is a basic list definition

sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
*/

object List {
  def add[A](as: List[A], a: A): List[A] = Cons(a, as)
}


(define (insert-after a b lst)
  (if (null? lst)
      lst       ; This should be an error, but we will just return the list untouched
      (let ((c (car lst))
            (cs (cdr lst)))
        (if (equal? a c)
            (cons a (cons b cs))
            (cons c (insert-after a b cs))))))


func insert_after(a,b) {
    b{:next} = a{:next};
    a{:next} = b;
}

var B = Hash.new(
    data => 3,
    next => nil,    # not a circular list
);
var A = Hash.new(
    data => 1,
    next => B,
);
var C = Hash.new(
    data => 2,
);

insert_after(A, C);


local socket = require("socket")
io.write("Input a number of seconds to sleep: ")
local input = io.read("*number")
print("Sleeping")
socket.sleep(input)
print("Awake!")


Module CheckIt {
      Input "Input a number of milliseconds to sleep:", N
      Print "Sleeping..."
      Wait N
      Print "Awake"
}
CheckIt


sleep := proc(secs)
           print("Sleeping...");
           Threads:-Sleep(secs);
           print("Awake!");
         end proc:


Sleep[seconds_] := (Print["Sleeping..."]; Pause[seconds]; Print["Awake!"];)


function sleep()

    time = input('How many seconds would you like me to sleep for? ');
    assert(time > .01);
    disp('Sleeping...');
    pause(time);
    disp('Awake!');

end


package main

import "github.com/go-vgo/robotgo"

func main() {
    robotgo.MouseClick("left", false) // single clicks left mouse button
    robotgo.MouseClick("right", true) // double clicks right mouse button
}


Point p = component.getLocation();
Robot robot = new Robot();
robot.mouseMove(p.getX(), p.getY()); //you may want to move a few pixels closer to the center by adding to these values
robot.mousePress(InputEvent.BUTTON1_MASK); //BUTTON1_MASK is the left button,
                                       //BUTTON2_MASK is the middle button, BUTTON3_MASK is the right button
robot.mouseRelease(InputEvent.BUTTON1_MASK);


# Wrap win32 API function mouse_event() from the User32 dll.
function mouse_event_wrapper(dwFlags,dx,dy,dwData,dwExtraInfo)
    ccall((:mouse_event, "User32"),stdcall,Nothing,(UInt32,UInt32,UInt32,UInt32,UInt),dwFlags,dx,dy,dwData,dwExtraInfo)
end

function click()
    mouse_event_wrapper(0x2,0,0,0,0)
    mouse_event_wrapper(0x4,0,0,0,0)
end


// version 1.1.2

import java.awt.Robot
import java.awt.event.InputEvent

fun sendClick(buttons: Int) {
    val r = Robot()
    r.mousePress(buttons)
    r.mouseRelease(buttons)
}

fun main(args: Array<String>) {
    sendClick(InputEvent.BUTTON3_DOWN_MASK) // simulate a click of the mouse's right button
}


(de factor (N)
   (make
      (let (D 2  L (1 2 2 . (4 2 4 2 4 6 2 6 .))  M (sqrt N))
         (while (>= M D)
            (if (=0 (% N D))
               (setq M (sqrt (setq N (/ N (link D)))))
               (inc 'D (pop 'L)) ) )
         (link N) ) ) )
(de sumdigits (N)
   (sum format (chop N)) )
(de smith (X)
   (make
      (for N X
         (let R (factor N)
            (and
               (cdr R)
               (= (sum sumdigits R) (sumdigits N))
               (link N) ) ) ) ) )
(let L (smith 10000)
   (println 'first-10 (head 10 L))
   (println 'last-10 (tail 10 L))
   (println 'all (length L)) )


smith: procedure options(main);
    /* find the digit sum of N */
    digitSum: procedure(nn) returns(fixed);
        declare (n, nn, s) fixed;
        s = 0;
        do n=nn repeat(n/10) while(n>0);
            s = s + mod(n,10);
        end;
        return(s);
    end digitSum;

    /* find and count factors of N */
    factors: procedure(nn, facs) returns(fixed);
        declare (n, nn, cnt, fac, facs(16)) fixed;
        cnt = 0;
        if nn<=1 then return(0);

        /* factors of two */
        do n=nn repeat(n/2) while(mod(n,2)=0);
            cnt = cnt + 1;
            facs(cnt) = 2;
        end;

        /* take out odd factors */
        do fac=3 repeat(fac+2) while(fac <= n);
            do n=n repeat(n/fac) while(mod(n,fac) = 0);
                cnt = cnt + 1;
                facs(cnt) = fac;
            end;
        end;

        return(cnt);
    end factors;

    /* see if a number is a Smith number */
    smith: procedure(n) returns(bit);
        declare (n, nfacs, facsum, i, facs(16)) fixed;
        nfacs = factors(n, facs);
        if nfacs <= 1 then
            return('0'b); /* primes are not Smith numbers */

        facsum = 0;
        do i=1 to nfacs;
            facsum = facsum + digitSum(facs(i));
        end;
        return(facsum = digitSum(n));
    end smith;

    /* print all Smith numbers up to 10000 */
    declare (i, cnt) fixed;
    cnt = 0;
    do i=2 to 9999;
        if smith(i) then do;
            put edit(i) (F(5));
            cnt = cnt + 1;
            if mod(cnt,16) = 0 then put skip;
        end;
    end;
    put skip list('Found', cnt, 'Smith numbers.');
end smith;


(class +Singleton)

(dm message1> ()
   (prinl "This is method 1 on " This) )

(dm message2> ()
   (prinl "This is method 2 on " This) )


Global SingletonSemaphore=CreateSemaphore(1)

Interface OO_Interface    ; Interface for any value of this type
  Get.i()
  Set(Value.i)
  Destroy()
EndInterface

Structure OO_Structure ; The *VTable structure
  Get.i
  Set.i
  Destroy.i
EndStructure

Structure OO_Var
  *VirtualTable.OO_Structure
  Value.i
EndStructure

Procedure OO_Get(*Self.OO_Var)
  ProcedureReturn *Self\Value
EndProcedure

Procedure OO_Set(*Self.OO_Var, n)
  *Self\Value = n
EndProcedure

Procedure CreateSingleton()
  If TrySemaphore(SingletonSemaphore)
    *p.OO_Var = AllocateMemory(SizeOf(OO_Var))
    If *p
      *p\VirtualTable = ?VTable
    EndIf
  EndIf
  ProcedureReturn *p
EndProcedure

Procedure OO_Destroy(*Self.OO_Var)
  FreeMemory(*Self)
  SignalSemaphore(SingletonSemaphore)
EndProcedure

DataSection
  VTable:
  Data.i @OO_Get()
  Data.i @OO_Set()
  Data.i @OO_Destroy()
EndDataSection


>>> class Borg(object):
	__state = {}
	def __init__(self):
		self.__dict__ = self.__state
	# Any other class names/methods

>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>> # For any datum!


#lang racket
(provide instance)
(define singleton%
  (class object%
    (super-new)))
(define instance (new singleton%))


proc insertIntoList {existingList predecessor newElement} {
  upvar $existingList exList
  set exList [linsert $exList [expr [lsearch -exact $exList $predecessor] + 1] $newElement]
}

set list {A B}
insertIntoList list A C
puts $list


import "/llist" for LinkedList

var ll = LinkedList.new(["A", "B"])
ll.insertAfter("A", "C")
System.print(ll)


; x86_64 Linux NASM
; Linked_List_Insert.asm

%ifndef INSERT
%define INSERT

%include "Linked_List_Definition.asm" ; see LL def task
%include "Heap_Alloc.asm" ; see memory allocation task

section .text

; rdi - link to insert after
; rsi - value that the new link will hold
Insert_After:
  push rdi
  push rsi
  mov rdi, linkSize
  call alloc
  cmp rax, 0
  je Memory_Allocation_Failure_Exception
  pop rdi
  mov dword [rax + value], edi
  pop rdi
  mov rsi, qword [rdi + next]
  mov qword [rax + next], rsi
  mov qword [rdi + next], rax
  ret

%endif


def \Node\ Link, Data;          \linked list element definition
def IntSize = 4;                \number of bytes in an integer

proc Insert(List, Node);        \Insert Node into List
int  List, Node;
[Node(Link):= List(Link);
 List(Link):= Node;
];

int MyNode, MyList;
int A, B, C;
[A:= Reserve(2*IntSize);
 B:= Reserve(2*IntSize);
 C:= Reserve(2*IntSize);
A(Data):= 1;
B(Data):= 2;
C(Data):= 3;
MyList:= A;                     \make initial list
A(Link):= 0;
Insert(A, B);                   \insert node B after A
Insert(A, C);                   \insert node C after A
MyNode:= MyList;                \traverse the linked list
while MyNode # 0 do             \display the example data
    [IntOut(0, MyNode(Data));
    ChOut(0, ^ );
    MyNode:= MyNode(Link);      \move to next node
    ];
]


// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
// by Galileo, 02/2022

FIL = 1 : DATO = 2 : LINK = 3
countNodes = 0 : Nodes = 10

dim list(Nodes, 3)

sub searchNode(node)
    local i, prevNode

    for i = 1 to countNodes
        if i = node break
        prevNode = list(prevNode, LINK)
    next

    return prevNode
end sub

sub insertNode(node, newNode, after)
    local prevNode, i

    prevNode = searchNode(node)

    if after prevNode = list(prevNode, LINK)

    for i = 1 to Nodes
        if not list(i, FIL) break
    next

    list(i, FIL) = true
    list(i, DATO) = newNode
    list(i, LINK) = list(prevNode, LINK)
    list(prevNode, LINK) = i

    countNodes = countNodes + 1
    if countNodes = Nodes then Nodes = Nodes + 10 : redim list(Nodes, 3) : end if
end sub

sub printNode(node)
    local prevNode

    prevNode = searchNode(node)
    node = list(prevNode, LINK)

    // print list(node, FIL);
    print list(node, DATO);
    // print list(node, LINK);
    print
end sub

insertNode(1, 1000, true)
insertNode(1, 2000, true)
insertNode(1, 3000, true)

printNode(1)
printNode(2)
printNode(3)


"Enter number of milliseconds to sleep" ask int
"Sleeping..." puts!
sleep
"Awake!" puts!


time = int(input("time to sleep (ms): "))

println "Sleeping..."
sleep(time)
println "Awake!"


using System;
using System.Console;
using System.Threading.Thread; // this is where the Sleep() method comes from

module Zzzz
{
    Main() : void
    {
        def nap_time = Int32.Parse(ReadLine());
        WriteLine("Sleeping...");
        Sleep(nap_time); // parameter is time in milliseconds
        WriteLine("Awake!");
    }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sleep(secs) public static binary
  ms = (secs * 1000).format(null, 0) -- milliseconds, rounded to nearest integer
  say 'Sleeping...'
  do
    Thread.sleep(ms)
  catch ix = InterruptedException
    say 'Sleep interrupted!'
    ix.printStackTrace()
  end
  say 'Awake!'
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
  secs = -1
  loop until \secs.datatype('N')
    if secs > 0 then do
      say 'Napping for' secs's'
      say
      sleep(secs)
    end
    say
    say 'How many seconds do you want me to sleep? (enter something non-numeric to terminate)\-'
    parse ask secs .
    say
    end
  say
  say 'Goodbye...'
  say
  return


(println "Sleeping..." )
(sleep 2000) ; Wait for 2 seconds
(println "Awake!")


declare
  [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
  Button
  Window = {QTk.build td(button(text:"Click me" handle:Button))}
in
  {Window show}
  {Delay 500}
  {Tk.send event(generate Button "<ButtonPress-1>")}
  {Delay 500}
  {Tk.send event(generate Button "<ButtonRelease-1>")}


--
-- demo\rosetta\Simulate_mouse_input.exw
--
-- Note that CURSORPOS, SCREENPOSITION, and MOUSEBUTTON are known to be a little flaky and/or system-dependent, ymmv.
--
without js -- you'd better hope this sort of thing ain't possible in a browser!
requires("1.0.1") -- (IupGetGlobalIntInt)
include pGUI.e
include timedate.e

integer delay = 16  -- (4s @ 250ms)
Ihandle dlg, btn

function action_cb(Ihandle /*btn*/)
    string t = format_timedate(date(),"hh:mm:sspm")
    IupSetStrAttribute(btn,"TITLE","Clicked at %s",{t})
    return IUP_DEFAULT
end function

integer cx, cy

function timer_cb(Ihandle timer)
    if delay then
        IupSetStrAttribute(btn,"TITLE","%3.2f",{delay/4})
        delay -= 1
        {cx,cy} = IupGetGlobalIntInt("CURSORPOS")
    else
        integer {xb,yb} = IupGetIntInt(btn,"SCREENPOSITION"),
                {wb,hb} = IupGetIntInt(btn,"RASTERSIZE"),
                {dx,dy} = {xb+floor(wb/2),yb+floor(hb/2)}
        if {dx,dy}!={cx,cy} then
            if IupGetInt(timer,"TIME")=250 then
                IupSetInt(timer,"TIME",40)
                IupSetInt(timer,"RUN",false)
                IupSetInt(timer,"RUN",true)
            end if
            for i=1 to 15 do
                if cx<dx then cx += 1 end if
                if cx>dx then cx -= 1 end if
                if cy<dy then cy += 1 end if
                if cy>dy then cy -= 1 end if
            end for
            string cxcy = sprintf("%dx%d ",{cx,cy})
            IupSetGlobal("CURSORPOS",cxcy)
        else
            string s = sprintf("%dx%d 1 2",{dx,dy})
            IupSetStrGlobal("MOUSEBUTTON", s)
            IupSetAttribute(timer,"RUN","NO")
        end if
    end if
    return IUP_CONTINUE
end function

IupOpen()
btn = IupButton("button",Icallback("action_cb"),"SIZE=100x12")
dlg = IupDialog(btn,`TITLE="Simulate mouse input", CHILDOFFSET=10x40, SIZE=200x80`)
IupShow(dlg)
Ihandle timer = IupTimer(Icallback("timer_cb"), 250)
if platform()!=JS then -- (just for consistency)
    IupMainLoop()
    IupClose()
end if


100H:

/* CP/M BDOS FUNCTIONS */
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; GO TO 0; END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;

/* PRINT NUMBER */
PR$NUM: PROCEDURE (N);
    DECLARE S (6) BYTE INITIAL ('     $');
    DECLARE N ADDRESS, I BYTE;
    I = 5;
    DIGIT: S(I := I-1) = '0' + N MOD 10;
    IF (N := N / 10) > 0 THEN GO TO DIGIT;
    DO WHILE I>0;
        S(I := I-1) =' ';
    END;
    CALL PRINT(.S);
END PR$NUM;

/* SUM OF DIGITS OF N */
DIGIT$SUM: PROCEDURE (N) BYTE;
    DECLARE N ADDRESS, SUM BYTE;
    SUM = 0;
    DO WHILE N > 0;
        SUM = SUM + N MOD 10;
        N = N / 10;
    END;
    RETURN SUM;
END DIGIT$SUM;

/* FIND AND COUNT FACTORS OF N */
FACTORS: PROCEDURE (N, FACBUF) BYTE;
    DECLARE (N, FACBUF, FAC, FACS BASED FACBUF) ADDRESS;
    DECLARE COUNT BYTE;
    COUNT = 0;
    IF N <= 1 THEN RETURN 0;

    /* TAKE OUT FACTORS OF TWO */
    DO WHILE NOT N;
        FACS(COUNT) = 2;
        COUNT = COUNT + 1;
        N = SHR(N, 1);
    END;

    /* TAKE OUT ODD FACTORS */
    FAC = 3;
    DO WHILE FAC <= N;
        DO WHILE N MOD FAC = 0;
            N = N / FAC;
            FACS(COUNT) = FAC;
            COUNT = COUNT + 1;
        END;
        FAC = FAC + 2;
    END;

    RETURN COUNT;
END FACTORS;

/* SEE IF A NUMBER IS A SMITH NUMBER */
SMITH: PROCEDURE (N) BYTE;
    DECLARE FACS (16) ADDRESS;
    DECLARE N ADDRESS, (F, NFACS, FACSUM) BYTE;
    IF (NFACS := FACTORS(N, .FACS)) <= 1 THEN
        RETURN 0; /* PRIMES ARE NOT SMITH NUMBERS */

    FACSUM = 0;
    DO F = 0 TO NFACS-1;
        FACSUM = FACSUM + DIGIT$SUM(FACS(F));
    END;

    RETURN FACSUM = DIGIT$SUM(N);
END SMITH;

/* PRINT ALL SMITH NUMBERS UP TO 10.000 */
DECLARE (I, COUNT) ADDRESS;
COUNT = 0;
DO I = 2 TO 9$999;
    IF SMITH(I) THEN DO;
        CALL PR$NUM(I);
        COUNT = COUNT + 1;
        IF (COUNT AND 0FH) = 0 THEN
            CALL PRINT(.(13,10,'$'));
    END;
END;
CALL PRINT(.(13,10,'FOUND $'));
CALL PR$NUM(COUNT);
CALL PRINT(.' SMITH NUMBERS.$');
CALL EXIT;
EOF


class Singleton {
    # We create a lexical variable in the class block that holds our single instance.
    my Singleton $instance = Singleton.bless; # You can add initialization arguments here.
    method new {!!!} # Singleton.new dies.
    method instance { $instance; }
}


require 'singleton'
class MySingleton
   include Singleton
   # constructor and/or methods go here
end

a = MySingleton.instance # instance is only created the first time it is requested
b = MySingleton.instance
puts a.equal?(b) # outputs "true"


object Singleton {
  // any code here gets executed as if in a constructor
}


class Singleton(name) {
    static instance;

    method new(name) {
        instance := Singleton.bless(Hash(:name => name));
    }
    method new {
        Singleton.new(nil);
    }
}

var s1 = Singleton('foo');
say s1.name;                #=> 'foo'
say s1.object_id;           #=> '30424504'

var s2 = Singleton();
say s2.name;                #=> 'foo'
say s2.object_id;           #=> '30424504'

s2.name = 'bar';            # change name in s2
say s1.name;                #=> 'bar'


define: #Singleton &builder: [Oddball clone]


SomeClass class>>sharedInstance

       SharedInstance ifNil: [SharedInstance := self basicNew initialize].
       ^ SharedInstance


const std = @import("std");

var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);

const allocator = arena.allocator();

pub fn LinkedList(comptime Value: type) type {
    return struct {
        const This = @This();

        const Node = struct {
            value: Value,
            next: ?*Node,
        };

        head: ?*Node,
        tail: ?*Node,

        pub fn init() This {
            return LinkedList(Value) {
                .head = null,
                .tail = null,
            };
        }

        pub fn add(this: *This, value: Value) !void {
            var newNode = try allocator.create(Node);

            newNode.* = .{ .value = value, .next = null };

            if (this.tail) |tail| {
                tail.next = newNode;
                this.tail = newNode;
            } else if (this.head) |head| {
                head.next = newNode;
                this.tail = newNode;
            } else {
                this.head = newNode;
            }
        }
    };
}


import os, strutils

echo "Enter how long I should sleep (in milliseconds):"
var timed = stdin.readLine.parseInt()
echo "Sleeping..."
sleep timed
echo "Awake!"


10 PRINT "I'LL TELL YOU WHEN I BECOME AWAKE AGAIN..."
20 PAUSE 100
30 PRINT "NOW I'M AWAKE AGAIN."


bundle Default {
  class Test {
    function : Main(args : System.String[]) ~ Nil {
      if(args->Size() = 1) {
        "Sleeping..."->PrintLine();
        Thread->Sleep(args[0]->ToInt());
        "Awake!"->PrintLine();
      };
    }
  }
}


#import <Foundation/Foundation.h>

int main()
{
  @autoreleasepool {

    NSTimeInterval sleeptime;
    printf("wait time in seconds: ");
    scanf("%f", &sleeptime);

    NSLog(@"sleeping...");
    [NSThread sleepForTimeInterval: sleeptime];
    NSLog(@"awakening...");

  }
  return 0;
}


#load "unix.cma";;
let seconds = read_int ();;
print_endline "Sleeping...";;
Unix.sleep seconds;; (* number is integer in seconds *)
print_endline "Awake!";;


(load "@lib/http.l" "@lib/scrape.l")

# Connect to the demo app at https://7fach.de/app/
(scrape "7fach.de" 80 "app")

# Log in
(expect "'admin' logged in"
   (enter 3 "admin")       # Enter user name into 3rd field
   (enter 4 "admin")       # Enter password into 4th field
   (press "login") )       # Press the "login" button

(click "Items")         # Open "Items" dialog
(click "Spare Part")    # Click on "Spare Part" article
(prinl (value 8))       # Print the price (12.50)
(click "logout")        # Log out


Macro Click()
  mouse_event_(#MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  mouse_event_(#MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
EndMacro

; Click at the current location
Click()

Delay(1000) ; Wait a second

; Move to a new location and click it
SetCursorPos_(50, 50)
Click()


import ctypes

def click():
    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    # Mouse LClick Down, relative coords, dx=0, dy=0
    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    # Mouse LClick Up, relative coords, dx=0, dy=0

click()


#lang at-exp racket

(require ffi/unsafe)

(define mouse-event
  (get-ffi-obj "mouse_event" (ffi-lib "user32")
               (_fun _int32 _int32 _int32 _int32 _pointer -> _void)))

(mouse-event #x2 0 0 0 #f)
(mouse-event #x4 0 0 0 #f)


use X11::libxdo;
my $xdo = Xdo.new;

my ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );

sleep .25;

for ^$dw -> $mx {
    my $my = (($mx / $dh * τ).sin * 500).abs.Int + 200;
    $xdo.move-mouse( $mx, $my, 0 );
    my ($x, $y, $window-id, $screen) = $xdo.get-mouse-info;
    my $name = (try $xdo.get-window-name($window-id) if $window-id)
       // 'No name set';

    my $line = "Mouse location: x=$x : y=$y\nWindow under mouse:\nWindow ID: " ~
       $window-id ~ "\nWindow name: " ~ $name ~ "\nScreen #: $screen";

    print "\e[H\e[J", $line;
    sleep .001;
}

say '';

#`[ There are several available routines controlling mouse position and button events.

.move-mouse( $x, $y, $screen ) # Move the mouse to a specific location.

.move-mouse-relative( $delta-x, $delta-y ) # Move the mouse relative to it's current position.

.move-mouse-relative-to-window( $x, $y, $window ) # Move the mouse to a specific location relative to the top-left corner of a window.

.get-mouse-location() # Get the current mouse location (coordinates and screen ID number).

.get-mouse-info() # Get all mouse location-related data.

.wait-for-mouse-to-move-from( $origin-x, $origin-y ) # Wait for the mouse to move from a location.

.wait-for-mouse-to-move-to( $dest-x, $dest-y ) # Wait for the mouse to move to a location.

.mouse-button-down( $window, $button ) # Send a mouse press (aka mouse down) for a given button at the current mouse location.

.mouse-button-up( $window, $button ) # Send a mouse release (aka mouse up) for a given button at the current mouse location.

.mouse-button-click( $window, $button ) # Send a click for a specific mouse button at the current mouse location.

.mouse-button-multiple( $window, $button, $repeat = 2, $delay? ) # Send a one or more clicks of a specific mouse button at the current mouse location.
]


DisableDebugger
#ECHO=#True ; #True: Print all results
Global NewList f.i()

Procedure.i ePotenz(Wert.i)
  Define.i var=Wert, i
  While var
    i+1
    var/10
  Wend
  ProcedureReturn i
EndProcedure

Procedure.i n_Element(Wert.i,Stelle.i=1)
  If Stelle>0
    ProcedureReturn (Wert%Int(Pow(10,Stelle))-Wert%Int(Pow(10,Stelle-1)))/Int(Pow(10,Stelle-1))
  Else
    ProcedureReturn 0
  EndIf
EndProcedure

Procedure.i qSumma(Wert.i)
  Define.i sum, pos
  For pos=1 To ePotenz(Wert)
    sum+ n_Element(Wert,pos)
  Next pos
  ProcedureReturn sum
EndProcedure

Procedure.b IsPrime(n.i)
  Define.i i=5
  If n<2 : ProcedureReturn #False : EndIf
  If n%2=0 : ProcedureReturn Bool(n=2) : EndIf
  If n%3=0 : ProcedureReturn Bool(n=3) : EndIf
  While i*i<=n
    If n%i=0 : ProcedureReturn #False : EndIf
    i+2
    If n%i=0 : ProcedureReturn #False : EndIf
    i+4
  Wend
  ProcedureReturn #True
EndProcedure

Procedure PFZ(n.i,pf.i=2)
  If n>1 And n<>pf
    If n%pf=0
      AddElement(f()) : f()=pf
      PFZ(n/pf,pf)
    Else
      While Not IsPrime(pf+1) : pf+1 : Wend
      PFZ(n,pf+1)
    EndIf
  ElseIf n=pf
    AddElement(f()) : f()=pf
  EndIf
EndProcedure

OpenConsole("Smith numbers")
;upto=100 : sn=0 : Gosub Smith_loop
;upto=1000 : sn=0 : Gosub Smith_loop
upto=10000 : sn=0 : Gosub Smith_loop
Input()
End

Smith_loop:
  For i=2 To upto
    ClearList(f()) : qs=0
    PFZ(i)
    CompilerIf #ECHO : Print(Str(i)+~": \t") : CompilerEndIf
    ForEach f()
      CompilerIf #ECHO : Print(Str(F())+~"\t") : CompilerEndIf
      qs+qSumma(f())
    Next
    If ListSize(f())>1 And qSumma(i)=qs
      CompilerIf #ECHO : Print("SMITH-NUMBER") : CompilerEndIf
      sn+1
    EndIf
    CompilerIf #ECHO : PrintN("") : CompilerEndIf
  Next
  Print(~"\n"+Str(sn)+" Smith number up to "+Str(upto))
Return


class SingletonClass {

static let sharedInstance = SingletonClass()

    ///Override the init method and make it private
    private override init(){
    // User can do additional manipulations here.
    }
}
// Usage
let sharedObject = SingletonClass.sharedInstance


package require TclOO

# This is a metaclass, a class that defines the behavior of other classes
oo::class create singleton {
   superclass oo::class
   variable object
   unexport create ;# Doesn't make sense to have named singletons
   method new args {
      if {![info exists object]} {
         set object [next {*}$args]
      }
      return $object
   }
}

singleton create example {
   method counter {} {
      my variable count
      return [incr count]
   }
}


module Singleton {
   speak() {
      println("I am a singleton");
   }
}

Singleton.speak();


public class Singleton : Object {
    static Singleton? instance;

    // Private constructor
    Singleton() {

    }

    // Public constructor
    public static Singleton get_instance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

void main() {
    Singleton a = Singleton.get_instance();
    Singleton b = Singleton.get_instance();
    if (a == b) {
        print("Equal.\n");
    }
}


class Singleton {
    // Returns the singleton. If it hasn't been created, creates it first.
    static instance { __instance == null ? __instance = Singleton.new_() : __instance }

    // Private constructor.
    construct new_() {}

    // instance method
    speak() { System.print("I'm a singleton.") }

}

var s1 = Singleton.instance
var s2 = Singleton.instance
System.print("s1 and s2 are same object = %(Object.same(s1, s2))")
s1.speak() // call instance method


: sleepMilli(n)  "Sleeping..." . n sleep "Awake!" println ;


Say time()
Call sysSleep 10 -- wait 10 seconds
Say time()


declare
  class TextFile from Open.file Open.text end
  StdIn = {New TextFile init(name:stdin)}
  WaitTime = {String.toInt {StdIn getS($)}}
in
  {System.showInfo "Sleeping..."}
  {Delay WaitTime} %% in milliseconds
  {System.showInfo "Awake!"}


sleep(ms)={
  print("Sleeping...");
  while((ms-=gettime()) > 0,);
  print("Awake!")
};

sleep(input())


<@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<@ SAYLIT>Sleeping</@>
<@ ACTPAUVAR>secs</@>
<@ SAYLIT>Awake</@>


# Project : Simulate input/Mouse

load "guilib.ring"
load "stdlib.ring"

paint = null

new qapp
        {
        win1 = new qwidget() {
                  setwindowtitle("")
                  setgeometry(100,100,800,600)
                  setwindowtitle("Mouse events")

                  line1 = new qlineedit(win1) {
                              setgeometry(150,450,300,30)
                              settext("")}

                  line2 = new qlineedit(win1) {
                              setgeometry(150,400,300,30)
                              settext("")}

                  new qpushbutton(win1) {
                          setgeometry(150,500,300,30)
                          settext("draw")
                          myfilter = new qallevents(win1)
                          myfilter.setMouseButtonPressevent("drawpress()")
                          myfilter.setMouseButtonReleaseevent("drawrelease()")
                          installeventfilter(myfilter)
                  }
                  show()
        }
        exec()
        }

func drawpress()
        line2.settext("")
        line1.settext("Mouse was pressed")

func drawrelease()
        line1.settext("")
        line2.settext("Mouse was released")


extern crate autopilot;
extern crate rand;
use rand::Rng;

// Moves the mouse in a sine wave across the screen.
const TWO_PI: f64 = std::f64::consts::PI * 2.0;
fn sine_mouse_wave() -> Result<(), autopilot::mouse::MouseError> {
    let screen_size = autopilot::screen::size();
    let scoped_height = screen_size.height / 2.0 - 10.0; // Stay in screen bounds.
    for x in 0..screen_size.width as u64 {
        let y = (scoped_height * ((TWO_PI * x as f64) / screen_size.width).sin() + scoped_height)
            .round();
        let duration: u64 = rand::thread_rng().gen_range(1, 3);
        try!(autopilot::mouse::move_to(autopilot::geometry::Point::new(
            x as f64,
            y as f64
        )));
        std::thread::sleep(std::time::Duration::from_millis(duration));
    }
    Ok(())
}

fn main() {
    sine_mouse_wave().expect("Unable to move mouse");
}


  val (p , robot)= (component.location, new Robot())
  robot.mouseMove(p.getX().toInt, p.getY().toInt) //you may want to move a few pixels closer to the center by adding to these values
  robot.mousePress(InputEvent.BUTTON1_MASK) //BUTTON1_MASK is the left button
  robot.mouseRelease(InputEvent.BUTTON1_MASK)


# Simulate a full click cycle: button down and up
event generate .okBtn <ButtonPress-1> -x 5 -y 5
event generate .okBtn <ButtonRelease-1> -x 5 -y 5


/* simulate_input_mouse.wren */

var KeyPressMask    = 1 << 0
var ButtonPressMask = 1 << 2
var Button1Mask     = 1 << 8
var ExposureMask    = 1 << 15
var Button1         = 1
var KeyPress        = 2
var ButtonPress     = 4
var Expose          = 12
var ClientMessage   = 33

var XK_a            = 0x0061
var XK_q            = 0x0071
var XK_Escape       = 0xff1b

foreign class XGC {
    construct default(display, screenNumber) {}
}

foreign class XColormap {
    construct default(display, screenNumber) {}
}

foreign class XColor {
    construct new() {}

    foreign pixel
}

// XEvent is a C union, not a struct, so we amalgamate the properties
foreign class XEvent {
    construct new() {}        // creates the union and returns a pointer to it

    foreign eventType         // gets type field, common to all union members

    foreign eventType=(et)    // sets type field

    foreign button            // gets xbutton.button

    foreign button=(b)        // sets xbutton.button

    foreign state=(st)        // sets xbutton.state

    foreign sameScreen=(ss)   // sets xbutton.same_screen

    foreign dataL             // gets xclient.data.l (data is a union)
}

foreign class XDisplay {
    construct openDisplay(displayName) {}

    foreign defaultScreen()

    foreign rootWindow(screenNumber)

    foreign blackPixel(screenNumber)

    foreign whitePixel(screenNumber)

    foreign selectInput(w, eventMask)

    foreign mapWindow(w)

    foreign closeDisplay()

    foreign nextEvent(eventReturn)

    foreign createSimpleWindow(parent, x, y, width, height, borderWidth, border, background)

    foreign drawString(d, gc, x, y, string, length)

    foreign storeName(w, windowName)

    foreign flush()

    foreign internAtom(atomName, onlyIfExists)

    foreign setWMProtocols(w, protocols, count)

    foreign sendEvent(w, propogate, eventMask, eventSend)

    foreign destroyWindow(w)

    foreign parseColor(colormap, spec, exactDefReturn)

    foreign allocColor(colormap, screenInOut)

    foreign setWindowBackground(w, backgroundPixel)

    foreign clearArea(w, x, y, width, height, exposures)
}

class X {
   foreign static lookupKeysym(keyEvent, index)
}

/* open connection with the server */
var xd = XDisplay.openDisplay("")
if (xd == 0) {
    System.print("Cannot open display.")
    return
}
var s = xd.defaultScreen()

/* create window */
var w = xd.createSimpleWindow(xd.rootWindow(s), 10, 10, 350, 250, 1, xd.blackPixel(s), xd.whitePixel(s))
xd.storeName(w, "Simulate mouse press")
var white = true // current background color

/* select kind of events we are interested in */
xd.selectInput(w, ExposureMask | KeyPressMask | ButtonPressMask)

/* map (show) the window */
xd.mapWindow(w)
xd.flush()

/* default graphics context */
var gc = XGC.default(xd, s)

/* connect the close button in the window handle */
var wmDeleteWindow = xd.internAtom("WM_DELETE_WINDOW", true)
xd.setWMProtocols(w, [wmDeleteWindow], 1)

/* create color green */
var green = XColor.new()
var colormap = XColormap.default(xd, s)
xd.parseColor(colormap, "#00FF00", green)
xd.allocColor(colormap, green)

/* event loop */
var e = XEvent.new()
while (true) {
    xd.nextEvent(e)
    var et = e.eventType
    if (et == Expose) {
        /* draw or redraw the window */
        var msg1 = "Press the 'a' key to switch the background color"
        var msg2 = "between white and green."
        xd.drawString(w, gc, 10, 20, msg1, msg1.count)
        xd.drawString(w, gc, 10, 35, msg2, msg2.count)
    } else if (et == ButtonPress) {
        System.write("\nButtonPress event received, ")
        if (white) {
            System.print("switching from white to green")
            xd.setWindowBackground(w, green.pixel)
        } else {
            System.print("switching from green to white")
            xd.setWindowBackground(w, xd.whitePixel(s))
        }
        xd.clearArea(w, 0, 0, 0, 0, true)
        white = !white
    } else if (et == ClientMessage) {
        /* delete window event */
         if (e.dataL[0] == wmDeleteWindow) break
    } else if (et == KeyPress) {
        System.print("\nKeyPress event received")
        /* exit if q or escape are pressed */
        var keysym = X.lookupKeysym(e, 0)
        if (keysym == XK_q || keysym == XK_Escape) {
            break
        } else if (keysym == XK_a) {
            /* if a is pressed, manufacture a ButtonPress event and send it to the window */
            System.print("> Key 'a' pressed, sending ButtonPress event")
            var e2 = XEvent.new()
            e2.eventType = ButtonPress
            e2.state = Button1Mask
            e2.button = Button1
            e2.sameScreen = true
            xd.sendEvent(w, true, ButtonPressMask, e2)
        } else {
            System.print("> Key other than 'a' pressed, not processed")
        }
    }
}

xd.destroyWindow(w)

/* close connection to server */
xd.closeDisplay()


run, cmd /k
WinWait, ahk_class ConsoleWindowClass
controlsend, ,hello console, ahk_class ConsoleWindowClass


from sys import stdout

def factors(n):
    rt = []
    f = 2
    if n == 1:
        rt.append(1);
    else:
        while 1:
            if 0 == ( n % f ):
                rt.append(f);
                n //= f
                if n == 1:
                    return rt
            else:
                f += 1
    return rt

def sum_digits(n):
    sum = 0
    while n > 0:
        m = n % 10
        sum += m
        n -= m
        n //= 10

    return sum

def add_all_digits(lst):
    sum = 0
    for i in range (len(lst)):
        sum += sum_digits(lst[i])

    return sum

def list_smith_numbers(cnt):
    for i in range(4, cnt):
        fac = factors(i)
        if len(fac) > 1:
            if sum_digits(i) == add_all_digits(fac):
                stdout.write("{0} ".format(i) )

# entry point
list_smith_numbers(10_000)


#lang racket
(require math/number-theory)

(define (sum-of-digits n)
  (let inr ((n n) (s 0))
    (if (zero? n) s (let-values (([q r] (quotient/remainder n 10))) (inr q (+ s r))))))

(define (smith-number? n)
  (and (not (prime? n))
       (= (sum-of-digits n)
          (for/sum ((pe (in-list (factorize n))))
            (* (cadr pe) (sum-of-digits (car pe)))))))

(module+ test
  (require rackunit)
  (check-equal? (sum-of-digits 0) 0)
  (check-equal? (sum-of-digits 33) 6)
  (check-equal? (sum-of-digits 30) 3)

  (check-true (smith-number? 166)))

(module+ main
  (let loop ((ns (filter smith-number? (range 1 (add1 10000)))))
    (unless (null? ns)
      (let-values (([l r] (split-at ns (min (length ns) 15))))
        (displayln l)
        (loop r)))))


class [static] Borg{ var v }
b1 := Borg; b2 := Borg();
b1 == b2 //--> True
b1.v=123; b2.v.println(); //--> 123


$seconds = <>;
print "Sleeping...\n";
sleep $seconds; # number is in seconds
print "Awake!\n";


without js -- (prompt_number, sleep)
atom a = prompt_number("wait for duration (in seconds, 0..20):", {0,20})
puts(1,"Sleeping...\n")
sleep(a)
puts(1,"Awake!\n")


$seconds = 42;
echo "Sleeping...\n";
sleep($seconds); # number is integer in seconds
echo "Awake!\n";


(prinl "Sleeping..." )
(wait 2000)                # Wait for 2 seconds
(prinl "Awake!")


Run("notepad")
WinWaitActive("Untitled - Notepad")
Send("The answer is 42")


 100  REM SIMULATE KEYBORD INPUT
 110  GOSUB 170"OPEN&WRITE KB
 120  PRINT "HOME:RUN140"M$"MARK
 130  PRINT D$C$A$"EXEC"F$: END
 140  INPUT "NAME? ";N$
 150  PRINT "HELLO, "N$"!"
 160  END
 170 D$ =  CHR$ (4):C$ = "CLOSE"
 180 M$ =  CHR$ (13):O$ = "OPEN"
 190 F$ = "KB":A$ = F$ + M$ + D$
 200  PRINT D$"MON I"M$D$O$;
 210  PRINT A$C$A$"DELETE"A$O$;
 220  PRINT A$"WRITE"F$: RETURN


gcc -o simkeypress -L/usr/X11R6/lib -lX11 simkeypress.c


(import java.awt.Robot)
(import java.awt.event.KeyEvent)
(defn keytype [str]
  (let [robot (new Robot)]
       (doseq [ch str]
	      (if (Character/isUpperCase ch)
		  (doto robot
			(.keyPress (. KeyEvent VK_SHIFT))
			(.keyPress (int ch))
			(.keyRelease (int ch))
			(.keyRelease (. KeyEvent VK_SHIFT)))
		  (let [upCh (Character/toUpperCase ch)]
		       (doto robot
			     (.keyPress (int upCh))
			     (.keyRelease (int upCh))))))))


package main

import (
    "github.com/micmonay/keybd_event"
    "log"
    "runtime"
    "time"
)

func main() {
    kb, err := keybd_event.NewKeyBonding()
    if err != nil {
        log.Fatal(err)
    }

    // For linux, need to wait 2 seconds
    if runtime.GOOS == "linux" {
        time.Sleep(2 * time.Second)
    }

    //set keys
    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)

    //launch
    err = kb.Launching()
    if err != nil {
        log.Fatal(err)
    }
}


constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;

multi factors ( 1 ) { 1 }
multi factors ( Int $remainder is copy ) {
  gather for @primes -> $factor {

    # if remainder < factor², we're done
    if $factor * $factor > $remainder {
      take $remainder if $remainder > 1;
      last;
    }

    # How many times can we divide by this prime?
    while $remainder %% $factor {
        take $factor;
        last if ($remainder div= $factor) === 1;
    }
  }
}
# Code above here is verbatim from RC:Count_in_factors#Raku

sub is_smith_number ( Int $n ) {
  (!$n.is-prime) and ( [+] $n.comb ) == ( [+] factors($n).join.comb );
}

my @s = grep &is_smith_number, 2 ..^ 10_000;
say "{@s.elems} Smith numbers below 10_000";
say 'First 10: ', @s[  ^10      ];
say 'Last  10: ', @s[ *-10 .. * ];