/*REXX program  finds  (and maybe displays)  Smith  (or joke)  numbers up to a given  N.*/
parse arg N .                                    /*obtain optional argument from the CL.*/
if N=='' | N==","  then N=10000                  /*Not specified?  Then use the default.*/
tell= (N>0);            N=abs(N) - 1             /*use the  │N│  for computing  (below).*/
w=length(N)                                      /*W:  used for aligning Smith numbers. */
#=0                                              /*#:  Smith numbers found  (so far).   */
@=;  do j=4  to  N;                              /*process almost all numbers up to  N. */
     if sumD(j) \== sumfactr(j)  then iterate    /*Not a Smith number?   Then ignore it.*/
     #=#+1                                       /*bump the Smith number counter.       */
     if \tell  then iterate                      /*Not showing the numbers? Keep looking*/
     @[email protected] right(j, w);         if length(@)>199  then do;    say substr(@, 2);    @=;   end
     end   /*j*/                                 /* [↑]  if N>0,  then display Smith #s.*/

if @\==''  then say substr(@, 2)                 /*if any residual Smith #s, display 'em*/
say                                              /* [↓]  display the number of Smith #s.*/
say #    ' Smith numbers found  ≤ '   N"."       /*display number of Smith numbers found*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumD:     parse arg x 1 s 2;   do d=2  for length(x)-1; s=s+substr(x,d,1); end;   return s
/*──────────────────────────────────────────────────────────────────────────────────────*/
sumFactr: procedure;  parse arg z;       $=0;    f=0             /*obtain the Z number. */
             do  while z//2==0;  $=$+2;  f=f+1;  z=z% 2;  end    /*maybe add factor of 2*/
             do  while z//3==0;  $=$+3;  f=f+1;  z=z% 3;  end    /*  "    "     "    " 3*/
                                                                 /*                  ___*/
             do j=5  by 2  while j<=z  &  j*j<=n                 /*minimum of Z or  √ N */
             if j//3==0  then iterate                            /*skip factors that ÷ 3*/
                do while z//j==0; f=f+1; $=$+sumD(j); z=z%j; end /*maybe reduce  Z by J */
             end   /*j*/                                         /* [↓]  Z:  what's left*/
          if z\==1  then do;      f=f+1; $=$+sumD(z);        end /*Residual?  Then add Z*/
          if f<2    then return 0                                /*Prime?   Not a Smith#*/
                         return $                                /*else return sum digs.*/


int main() {
	int seconds = (int)Stdio.stdin->gets();
	write("Sleeping...\n");
	sleep(seconds);
	write("Awake!\n");
	return 0;
}


put ('sleeping');
delay (2000); /* wait for 2 seconds (=2000 milliseconds). */
put ('awake');


To run:
Start up.
Demonstrate waiting.
Wait for the escape key.
Shut down.

To demonstrate waiting:
Write "How many milliseconds should I wait? " to the console without advancing.
Read some milliseconds from the console.
Write "Sleeping..." to the console.
Wait for the milliseconds.
Write "Awake!" to the console.


$d = [int] (Read-Host Duration in seconds)
Write-Host Sleeping ...
Start-Sleep $d
Write-Host Awake!


rosetta_sleep(Time) :-
	writeln('Sleeping...'),
	sleep(Time),
	writeln('Awake!').


import java.awt.Robot
public static void type(String str){
   Robot robot = new Robot();
   for(char ch:str.toCharArray()){
      if(Character.isUpperCase(ch)){
         robot.keyPress(KeyEvent.VK_SHIFT);
         robot.keyPress((int)ch);
         robot.keyRelease((int)ch);
         robot.keyRelease(KeyEvent.VK_SHIFT);
      }else{
         char upCh = Character.toUpperCase(ch);
         robot.keyPress((int)upCh);
         robot.keyRelease((int)upCh);
      }
   }
}


// version 1.1.2

import java.awt.Robot
import java.awt.event.KeyEvent

fun sendChars(s: String, pressReturn: Boolean = true) {
    val r = Robot()
    for (c in s) {
        val ci = c.toUpperCase().toInt()
        r.keyPress(ci)
        r.keyRelease(ci)
    }
    if (pressReturn) {
        r.keyPress(KeyEvent.VK_ENTER)
        r.keyRelease(KeyEvent.VK_ENTER)
    }
}

fun main(args: Array<String>) {
    sendChars("dir")  // runs 'dir' command
}


when defined(windows):
  import winlean
else:
  {.error: "not supported os".}

type
  InputType = enum
    itMouse itKeyboard itHardware
  KeyEvent = enum
    keExtendedKey = 0x0001
    keKeyUp = 0x0002
    keUnicode = 0x0004
    keScanCode = 0x0008

  MouseInput {.importc: "MOUSEINPUT".} = object
    dx, dy: clong
    mouseData, dwFlags, time: culong
    dwExtraInfo: int # ULONG_PTR

  KeybdInput {.importc: "KEYBDINPUT".} = object
    wVk, wScan: cint
    dwFlags, time: culong
    dwExtraInfo: int

  HardwareInput {.importc: "HARDWAREINPUT".} = object
    uMsg: clong
    wParamL, wParamH: cint

  InputUnion {.union.} = object
    hi: HardwareInput
    mi: MouseInput
    ki: KeybdInput
  Input = object
    `type`: clong
    hwin: InputUnion

proc sendInput(total: cint, inp: ptr Input, size: cint) {.importc: "SendInput", header: "<windows.h>".}

proc initKey(keycode: int): Input =
  result = Input(`type`: itKeyboard.clong)
  var keybd = KeybdInput(wVk: keycode.cint, wScan: 0, time: 0,
    dwExtraInfo: 0, dwFlags: 0)
  result.hwin = InputUnion(ki: keybd)

proc pressKey(input: var Input) =
  input.hwin.ki.dwFlags = keExtendedKey.culong
  sendInput(cint 1, addr input, sizeof(Input).cint)

proc releaseKey(input: var Input) =
  input.hwin.ki.dwFlags = keExtendedKey.culong or keKeyUp.culong
  sendInput(cint 1, addr input, sizeof(Input).cint)

proc pressRelease(input: var Input) =
  input.pressKey
  input.releaseKey

proc pressReleaseKeycode(input: var Input, code: int) =
  input.hwin.ki.wVk = code.cint
  input.pressRelease

proc main =
  var
    shift = initKey 0xa0 # VK_LSHIFT
    key = initKey 0x48

  pressKey shift
  pressRelease key
  releaseKey shift
  key.pressReleaseKeycode 0x45 # e key
  key.pressReleaseKeycode 0x4c # l key
  key.pressReleaseKeycode 0x4c # l key
  key.pressReleaseKeycode 0x4f # o key
  key.pressReleaseKeycode 0x20 # VK_SPACE
  key.pressReleaseKeycode 0x57 # w key
  key.pressReleaseKeycode 0x4f # o key
  key.pressReleaseKeycode 0x52 # r key
  key.pressReleaseKeycode 0x4c # l key
  key.pressReleaseKeycode 0x44 # d key

main()


# Project : Smith numbers

see "All the Smith Numbers < 1000 are:" + nl

for prime = 1 to 1000
    decmp = []
    sum1 = sumDigits(prime)
    decomp(prime)
    sum2 = 0
    if len(decmp)>1
       for n=1 to len(decmp)
           cstr = string(decmp[n])
           for m= 1 to len(cstr)
               sum2 = sum2 + number(cstr[m])
           next
       next
    ok
    if sum1 = sum2
       see "" + prime + " "
    ok
next

func decomp nr
     for i = 1 to nr
         if isPrime(i) and nr % i = 0
            add(decmp, i)
            pr = i
            while true
                  pr = pr * i
                  if nr%pr = 0
                     add(decmp, i)
                  else
                     exit
                  ok
            end
         ok
     next

func isPrime num
     if (num <= 1) return 0 ok
        if (num % 2 = 0 and num != 2) return 0 ok
        for i = 3 to floor(num / 2) -1 step 2
            if (num % i = 0) return 0 ok
        next
        return 1

func sumDigits n
     sum = 0
     while n > 0.5
           m = floor(n / 10)
           digit = n - m * 10
           sum = sum + digit
           n = m
     end
     return sum


require "prime"

class Integer

  def smith?
    return false if prime?
    digits.sum == prime_division.map{|pr,n| pr.digits.sum * n}.sum
  end

end

n   = 10_000
res = 1.upto(n).select(&:smith?)

puts "#{res.size} smith numbers below #{n}:
#{res.first(5).join(", ")},... #{res.last(5).join(", ")}"


fn main () {
    //We just need the primes below 100
    let primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
    let mut solution = Vec::new();
    let mut number;
    for i in 4..10000 {
        //Factorize each number below 10.000
        let mut prime_factors = Vec::new();
        number = i;
        for j in &primes {
            while number % j == 0 {
                number = number / j;
                prime_factors.push(j);
            }
            if number == 1 { break; }
        }
        //Number is 1 (not a prime factor) if the factorization is complete or a prime bigger than 100
        if number != 1 { prime_factors.push(&number); }
        //Avoid the prime numbers
        if prime_factors.len() < 2 { continue; }
        //Check the smith number definition
        if prime_factors.iter().fold(0, |n,x| n + x.to_string().chars().map(|d| d.to_digit(10).unwrap()).fold(0, |n,x| n + x))
            == i.to_string().chars().map(|d| d.to_digit(10).unwrap()).fold(0, |n,x| n + x) {
            solution.push(i);
        }
    }
    println!("Smith numbers below 10000 ({}) : {:?}",solution.len(), solution);
}


If OpenConsole()

  Print("Enter a time(milliseconds) to sleep: ")
  x.i = Val(Input())
  PrintN("Sleeping...")
  Delay(x) ;in milliseconds
  PrintN("Awake!")
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


import time

seconds = float(raw_input())
print "Sleeping..."
time.sleep(seconds) # number is in seconds ... but accepts fractions
print "Awake!"


sleep <- function(time=1)
{
   message("Sleeping...")
   flush.console()
   Sys.sleep(time)
   message("Awake!")
}

sleep()


#lang racket
(displayln "Enter a time (in seconds): ")
(define time (read))
(when (number? time)
  (displayln "Sleeping...")
  (sleep time)
  (displayln "Awake!"))


my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
say "Sleeping...";
sleep $sec;
say "Awake!";


INCLUDE "D2:TURTLE.ACT" ;from the Action! Tool Kit

PROC Rectangle(INT w,h)
  BYTE i

  FOR i=1 TO 2
  DO
    Forward(h)
    Left(90)
    Forward(w)
    Left(90)
  OD
RETURN

PROC Square(INT w)
  Rectangle(w,w)
RETURN

PROC Triangle(INT w)
  BYTE i

  FOR i=1 TO 3
  DO
    Forward(w)
    Right(120)
  OD
RETURN

PROC House(INT w)
  Left(90)
  Square(w)
  Triangle(w)
  Right(90)
RETURN

INT FUNC GetMax(INT ARRAY a INT count)
  INT i,max

  max=0
  FOR i=0 TO count-1
  DO
    IF a(i)>max THEN
      max=a(i)
    FI
  OD
RETURN (max)

PROC BarChart(INT ARRAY a INT count,w)
  INT max,st,i

  IF count=0 THEN RETURN FI
  max=GetMax(a,count)
  st=w/count
  Right(90)
  FOR i=0 TO count-1
  DO
    Rectangle(a(i)*w/max,st)
    Forward(st)
  OD
  Left(180)
  Forward(w)
RETURN

PROC Main()
  BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
  INT ARRAY a=[50 33 200 130 50]

  Graphics(8+16)
  COLOR1=$0C
  COLOR2=$02

  Color=1
  SetTurtle(150,110,90)
  House(75)

  Color=0
  Right(90)
  Forward(5)
  Left(90)

  Color=1
  BarChart(a,5,100)
  Right(90)
  Forward(5)
  Right(90)

  DO UNTIL CH#$FF OD
  CH=$FF
RETURN


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters; use Ada.Characters;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings; use Ada.Strings;

-- procedure main - begins program execution
procedure main is
    type Sketch_Pad is array(1 .. 50, 1 .. 50) of Character;
    thePen : Boolean := True; -- pen raised by default
    sketch : Sketch_Pad;
    ycorr, xcorr : Integer := 25;

    -- specifications
    function penPosition(thePen : in out Boolean) return String;
    procedure initGrid(sketch : in out Sketch_Pad);
    procedure commandMenu(thePen : in out Boolean; xcorr : in out Integer;
                          ycorr : in out Integer);
    procedure showMenu(xcorr : in out Integer; ycorr : in out Integer;
                       thePen : in out Boolean; sketch : in Sketch_Pad);
    procedure moveCursor(thePen : in Boolean; sketch : in out Sketch_Pad;
                         xcorr : in out Integer; ycorr : in out Integer;
                         ch : in Integer);
    procedure showGrid(sketch : in Sketch_Pad);

    -- procedure initGrid - creates the sketchpad and initializes elements
    procedure initGrid(sketch : in out Sketch_Pad) is
    begin
        sketch := (others => (others => ' '));
    end initGrid;

    -- procedure showMenu - displays the menu for the application
    procedure showMenu(xcorr : in out Integer; ycorr : in out Integer;
                       thePen : in out Boolean; sketch : in Sketch_Pad) is

        choice : Integer := 0;
    begin
        while choice /= 4 loop
            Set_Col(15);
            Put("TURTLE GRAPHICS APPLICATION");
            Set_Col(15);
            Put("===========================");
            New_Line(2);

            Put_Line("Enter 1 to print the grid map");
            Put_Line("Enter 2 for command menu");
            Put_Line("Enter 3 to raise pen up / down");
            Put_Line("Enter 4 to exit the application");
            choice := integer'value(Get_Line);

            exit when choice = 4;

            case choice is
                when 1 => showGrid(sketch);
                when 2 => commandMenu(thePen, xcorr, ycorr);
                when 3 => Put_Line("Pen is "
                              & penPosition(thePen));
                when others => Put_Line("Invalid input");
            end case;
        end loop;
    end showMenu;

    -- function penPosition - checks changes the state of whether the pen is
    -- raised up or down. If value is True, pen is rasied up
    function penPosition(thePen : in out Boolean) return String is
        str1 : constant String := "raised UP";
        str2 : constant String := "raised DOWN";
    begin
        if thePen = True then
            thePen := False;
            return str2;
        else
            thePen := True;
        end if;

        return str1;
    end penPosition;

    -- procedure command menu - provides a list of directions for the turtle
    -- to move along the grid
    procedure commandMenu(thePen : in out Boolean; xcorr : in out Integer;
                          ycorr : in  out Integer) is

        choice : Integer := 0;
    begin
        while choice <= 0 or choice > 5 loop
            Set_Col(15);
            Put("Command Menu");
            Set_Col(15);
            Put("============");
            New_Line(2);

            Put_Line("To move North enter 1");
            Put_Line("To move South enter 2");
            Put_Line("To move East enter 3");
            Put_Line("To move West enter 4");
            Put_Line("To return to previous menu enter 5");
            choice := integer'value(Get_Line);

            case choice is
                when 1 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
                when 2 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
                when 3 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
                when 4 => moveCursor(thePen, sketch, xcorr, ycorr, choice);
                when 5 => showMenu(xcorr, ycorr, thePen, sketch);
                when others => Put_Line("Invalid choice");
            end case;
        end loop;
    end commandMenu;

    -- procedure moveCursor - moves the cursor around the board by taking the
    -- x and y coordinates from the user. If the pen is down, a character is
    -- printed at that location. If the pen is up, nothing is printed but the
    -- cursor still moves to that position
    procedure moveCursor(thePen : in Boolean; sketch : in out Sketch_Pad;
                         xcorr : in out Integer; ycorr : in out Integer;
                         ch : in Integer) is

    begin
        if thePen = True then -- pen up so move cursor but do not draw
            case ch is
                when 1 => xcorr := xcorr - 1; ycorr := ycorr;
                    sketch(xcorr, ycorr) := ' ';
                when 2 => xcorr := xcorr + 1; ycorr := ycorr;
                    sketch(xcorr, ycorr) := ' ';
                when 3 => xcorr := xcorr; ycorr := ycorr + 1;
                    sketch(xcorr, ycorr) := ' ';
                when 4 => xcorr := xcorr; ycorr := ycorr - 1;
                    sketch(xcorr, ycorr) := ' ';
                when others => Put("Unreachable Code");
            end case;

        else -- pen is down so move cursor and draw
            case ch is
                when 1 => xcorr := xcorr - 1; ycorr := ycorr;
                    sketch(xcorr, ycorr) := '#';
                when 2 => xcorr := xcorr + 1; ycorr := ycorr;
                    sketch(xcorr, ycorr) := '#';
                when 3 => xcorr := xcorr; ycorr := ycorr + 1;
                    sketch(xcorr, ycorr) := '#';
                when 4 => xcorr := xcorr; ycorr := ycorr - 1;
                    sketch(xcorr, ycorr) := '#';
                when others => Put("Unreachable Code");
            end case;
        end if;
    end moveCursor;

    -- procedure showGrid - prints the sketchpad showing the plotted moves
    procedure showGrid(sketch : in Sketch_Pad) is
    begin
        New_Line;

        for I in sketch'Range(1) loop
            for J in sketch'Range(2) loop
                Put(character'image(sketch(I,J)));
            end loop;
            New_Line;
        end loop;
        New_Line;
    end showGrid;

begin
    New_Line;

    initGrid(sketch);
    showMenu(xcorr, ycorr, thePen, sketch);

   New_Line;
end main;


ocaml -I +Xlib Xlib.cma keysym.cma send_event.ml


declare
  [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
  Entry
  Window = {QTk.build td(entry(handle:Entry))}
in
  {Window show}
  {Entry getFocus(force:true)}

  for C in "Hello, world!" do
     Key = if C == 32 then "<space>" else [C] end
  in
     {Delay 100}
     {Tk.send event(generate Entry Key)}
  end


$target = "/dev/pts/51";
### How to get the correct value for $TIOCSTI is discussed here : http://www.perlmonks.org/?node_id=10920
$TIOCSTI = 0x5412 ;
open(TTY,">$target") or die "cannot open $target" ;
$b="sleep 99334 &\015";
@c=split("",$b);
sleep(2);
foreach $a ( @c ) { ioctl(TTY,$TIOCSTI,$a); select(undef,undef,undef,0.1);} ;
print "DONE\n";


object SmithNumbers extends App {

  def sumDigits(_n: Int): Int = {
    var n = _n
    var sum = 0
    while (n > 0) {
      sum += (n % 10)
      n /= 10
    }
    sum
  }

  def primeFactors(_n: Int): List[Int] = {
    var n = _n
    val result = new collection.mutable.ListBuffer[Int]
    val i = 2
    while (n % i == 0) {
      result += i
      n /= i
    }
    var j = 3
    while (j * j <= n) {
      while (n % j == 0) {
        result += i
        n /= j
      }
      j += 2
    }
    if (n != 1) result += n
    result.toList
  }

  for (n <- 1 until 10000) {
    val factors = primeFactors(n)
    if (factors.size > 1) {
      var sum = sumDigits(n)
      for (f <- factors) sum -= sumDigits(f)
      if (sum == 0) println(n)
    }
  }

}


var primes = Enumerator({ |callback|
    static primes = Hash()
    var p = 2
    loop {
        callback(p)
        p = (primes{p} := p.next_prime)
    }
})

func factors(remainder) {

    remainder == 1 && return([remainder])

    gather {
        primes.each { |factor|
            if (factor*factor > remainder) {
                take(remainder) if (remainder > 1)
                break
            }

            while (factor.divides(remainder)) {
                take(factor)
                break if ((remainder /= factor) == 1)
            }
        }
    }
}

func is_smith_number(n) {
    !n.is_prime && (n.digits.sum == factors(n).join.to_i.digits.sum)
}

var s = range(2, 10_000).grep { is_smith_number(_) }
say "#{s.len} Smith numbers below 10_000"
say "First 10: #{s.first(10)}"
say "Last  10: #{s.last(10)}"


input "Enter the number of seconds to sleep: ";s
sleep s
print "I'm awake I think..."
input "Press enter to quit";a$


rebol [
    Title: "Sleep Main Thread"
    URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread
]

naptime: to-integer ask "Please enter sleep time in seconds: "
print "Sleeping..."
wait naptime
print "Awake!"


str-time: to integer! ask "Enter wait time "    ;get user input , convert to integer
print "waiting"
wait str-time       ;Seconds
print "awake"


: sleep ( n- )
  [ time [ time over - 1 > ] until drop ] times ;
  : test
    "\nTime to sleep (in seconds): " puts getToken toNumber
    "\nSleeping..." sleep
    "\nAwake!\n" ;


/*REXX program sleeps  X  seconds  (the number of seconds is supplied via the argument).*/
parse arg secs .                                 /*obtain optional argument from the CL.*/
if secs=='' | secs==","  then secs=0             /*Not specified?  Then assume 0 (zero).*/
say 'Sleeping'    secs    "seconds."             /*inform the invoker what's happening. */
call delay secs                                  /*Snooze.  Hopefully, just a short nap.*/
say 'Awake!'                                     /*and now inform invoker we're running.*/
                                                 /*stick a fork in it,  we're all done. */


load "guilib.ring"

for n = 1 to 10
    Sleep(3)
    see "" + n + " "
next
see nl

func Sleep x
     nTime = x * 1000
     oTest = new qTest
     oTest.qsleep(nTime)


;install each cut 'gl2 gles github:zerowords/tgsjo'


using Luxor, Colors

function house(🐢, x, y, siz)
    oldorientation = 🐢.orientation
    xpos, ypos = 🐢.xpos, 🐢.ypos
    # house wall
    Reposition(🐢, x, y)
    Rectangle(🐢, siz, siz)
    # roof
    Reposition(🐢, x - siz / 2, y -  siz / 2)
    Turn(🐢, -60)
    Forward(🐢, siz)
    Turn(🐢, 120)
    Forward(🐢, siz)
    # turtle_demo
    doorheight, doorwidth = siz / 2, siz / 4
    Pencolor(🐢, 0, 0, 0)
    Reposition(🐢, x, y + doorheight / 2)
    Rectangle(🐢, doorwidth, doorheight)
    # window
    windowheight, windowwidth = siz /3, siz / 4
    Reposition(🐢, x + siz / 4, y - siz / 4)
    Rectangle(🐢, windowwidth, windowheight)
    Reposition(🐢, x - siz / 4, y - siz / 4)
    Rectangle(🐢, windowwidth, windowheight)
    Orientation(🐢, oldorientation)
    Reposition(🐢, xpos, ypos)
end

function barchart(🐢, data, x, y, siz)
    oldorientation = 🐢.orientation
    xpos, ypos = 🐢.xpos, 🐢.ypos
    maxdata = maximum(data)
    # scale to fit within a square with sides `siz` and draw bars of chart
    barwidth = siz / length(data)
    Pencolor(🐢, 1.0, 0.0, 0.5)
    Reposition(🐢, x, y)
    for n in data  # draw each bar in chart
        barheight = n * siz / maxdata
        Reposition(🐢, x, y - barheight / 2)
        Rectangle(🐢, barwidth, barheight)
        x += barwidth
    end
    Orientation(🐢, oldorientation)
    Reposition(🐢, xpos, ypos)
end

function testturtle(width = 400, height = 600)
    dra = Drawing(600, 400, "turtle_demo.png")
    origin()
    background("midnightblue")
    🐢 = Turtle()
    Pencolor(🐢, "cyan")
    Penwidth(🐢, 1.5)
    house(🐢, -width / 3, height / 7, width / 2)
    barchart(🐢, [15, 10, 50, 35, 20], width / 8, height / 8, width / 2)
    finish()
end

testturtle()


to rectangle :width :height
    repeat 2 [
        forward :height
        left 90
        forward :width
        left 90 ]
    end

to square :size
    rectangle size size
    end

to triangle :size
    repeat 3 [
        forward size
        right 120 ]
     end

to house :size
    left 90
    square size
    triangle size
    right 90
    end

to max :lst
   if equalp count lst 1 [ output first lst ]
   make "x max butfirst lst
   if x > first lst [ output x ]
   output first lst
   end

to barchart :lst :size
    right 90
    if emptyp lst [ stop ]
    make "scale size / (max lst)
    make "width size / count lst
    foreach lst [
        rectangle ? * scale width
        forward width ]
    back size
    left 90
    end

clearscreen hideturtle
house 150
penup
right 90 forward 10 left 90
pendown
barchart [ 0.5 0.33333 2 1.3 0.5 ] 200
left 90 back 10 right 90


#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Simple_turtle_graphics
use warnings;
use Tk;
use List::Util qw( max );

my $c; # the canvas

# turtle routines

my $pen = 1; # true for pendown,  false for penup
my @location = (0, 0); # upper left corner
my $direction = 0; # 0 for East, increasing clockwise
my @stack;
my $radian = 180 / atan2 0, -1;
sub dsin { sin $_[0] / $radian }
sub dcos { cos $_[0] / $radian }
sub save { push @stack, [ $direction, @location ] }
sub restore { ($direction, @location) = @{ pop @stack } }
sub turn { $direction += shift }
sub right { turn shift }
sub left { turn -shift }
sub forward
  {
  my $x = $location[0] + $_[0] * dcos $direction;
  my $y = $location[1] + $_[0] * dsin $direction;
  $pen and $c->createLine( @location, $x, $y, -width => 3 );
  @location = ($x, $y);
  }
sub back { turn 180; forward shift; turn 180 }
sub penup { $pen = 0 }
sub pendown { $pen = 1 }
sub text { $c->createText( @location, -text => shift ) }

# make window

my $mw = MainWindow->new;
$c = $mw->Canvas(
  -width => 900, -height => 900,
  )->pack;
$mw->Button(-text => 'Exit', -command => sub {$mw->destroy},
  )->pack(-fill => 'x');
$mw->after(0, \&run);
MainLoop;
-M $0 < 0 and exec $0;

sub box
  {
  my ($w, $h) = @_;
  for (1 .. 2)
    {
    forward $w;
    left 90;
    forward $h;
    left 90;
    }
  }

sub house
  {
  my $size = shift;
  box $size, $size;
  right 90;
  for ( 1 .. 3 )
    {
    right 120;
    forward $size;
    }
  penup;
  left 90;
  forward $size;
  left 90;
  save;
  forward $size * 1 / 4;
  pendown;
  box $size / 4, $size / 2;
  penup;
  forward $size * 3 / 8;
  left 90;
  forward $size / 4;
  right 90;
  pendown;
  box $size / 4, $size / 4;
  penup;
  restore;
  save;
  forward $size / 2;
  left 90;
  forward $size + 40;
  right 90;
  pendown;
  for (1 .. 8)
    {
    forward 15;
    left 45;
    forward 15;
    }
  restore;
  penup;
  }

sub graph
  {
  save;
  my $size = shift;
  my $width = $size / @_;
  my $hscale = $size / max @_;
  for ( @_ )
    {
    box $width, $hscale * $_;
    save;
    penup;
    forward $width / 2;
    left 90;
    forward 10;
    text $_;
    pendown;
    restore;
    forward $width;
    }
  restore;
  }

sub run
  {
  penup;
  forward 50;
  right 90;
  forward 400;
  pendown;
  house(300);
  penup;
  forward 400;
  pendown;
  graph( 400, 2,7,4,5,1,8,6 );
  }


--
-- demo\rosetta\Simulate_keyboard_input.exw
--
without js -- you'd better hope this sort of thing ain't possible in a browser!
include pGUI.e

string hw = "Look ma no hands! "

function timer_cb(Ihandle ih)
    if length(hw) then
        IupSetGlobalInt("KEY",hw[1])
        hw = hw[2..$]
    else
        IupSetInt(ih,"RUN",false)
    end if
    return IUP_CONTINUE
end function

IupOpen()
Ihandle txt = IupText("SIZE=170x10")
Ihandle dlg = IupDialog(txt,`TITLE="Simulate input", CHILDOFFSET=10x40, SIZE=200x80`)
IupShow(dlg)
Ihandle hTimer = IupTimer(Icallback("timer_cb"), 250)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


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

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

# 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


Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms
calc.exe
Start-Sleep -Milliseconds 300
[Microsoft.VisualBasic.Interaction]::AppActivate(“Calc”)
[System.Windows.Forms.SendKeys]::SendWait(“2{ADD}2=”)


If AW_WinActivate("Calc")
  AW_SendKeys("123+3=")
EndIf


extension BinaryInteger {
  @inlinable
  public var isSmith: Bool {
    guard self > 3 else {
      return false
    }

    let primeFactors = primeDecomposition()

    guard primeFactors.count != 1 else {
      return false
    }

    return primeFactors.map({ $0.sumDigits() }).reduce(0, +) == sumDigits()
  }

  @inlinable
  public func primeDecomposition() -> [Self] {
    guard self > 1 else { return [] }

    func step(_ x: Self) -> Self {
      return 1 + (x << 2) - ((x >> 1) << 1)
    }

    let maxQ = Self(Double(self).squareRoot())
    var d: Self = 1
    var q: Self = self & 1 == 0 ? 2 : 3

    while q <= maxQ && self % q != 0 {
      q = step(d)
      d += 1
    }

    return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self]
  }

  @inlinable
  public func sumDigits() -> Self {
    return String(self).lazy.map({ Self(Int(String($0))!) }).reduce(0, +)
  }
}

let smiths = (0..<10_000).filter({ $0.isSmith })

print("Num Smith numbers below 10,000: \(smiths.count)")
print("First 10 smith numbers: \(Array(smiths.prefix(10)))")
print("Last 10 smith numbers below 10,000: \(Array(smiths.suffix(10)))")


proc factors {x} {
    # list the prime factors of x in ascending order
    set result [list]
    while {$x % 2 == 0} {
        lappend result 2
        set x [expr {$x / 2}]
    }
    for {set i 3} {$i*$i <= $x} {incr i 2} {
        while {$x % $i == 0} {
            lappend result $i
            set x [expr {$x / $i}]
        }
    }
    if {$x != 1} {lappend result $x}
    return $result
}

proc digitsum {n} {
    ::tcl::mathop::+ {*}[split $n ""]
}

proc smith? {n} {
    set fs [factors $n]
    if {[llength $fs] == 1} {
        return false    ;# $n is prime
    }
    expr {[digitsum $n] == [digitsum [join $fs ""]]}
}
proc range {n} {
    for {set i 1} {$i < $n} {incr i} {lappend result $i}
    return $result
}

set smiths [lmap i [range 10000] {
    if {![smith? $i]} continue
    set i
}]

puts [lrange $smiths 0 12]...
puts ...[lrange $smiths end-12 end]
puts "([llength $smiths] total)"


seconds = gets.to_f
puts "Sleeping..."
sleep(seconds) # number is in seconds ... but accepts fractions
# Minimum resolution is system dependent.
puts "Awake!"


use std::{io, time, thread};

fn main() {
    println!("How long should we sleep in milliseconds?");

    let mut sleep_string = String::new();

    io::stdin().read_line(&mut sleep_string)
               .expect("Failed to read line");

    let sleep_timer: u64 = sleep_string.trim()
                                       .parse()
                                       .expect("Not an integer");
    let sleep_duration = time::Duration::from_millis(sleep_timer);

    println!("Sleeping...");
    thread::sleep(sleep_duration);
    println!("Awake!");
}


object Sleeper extends App {
  print("Enter sleep time in milli sec: ")
  val ms = scala.io.StdIn.readInt()
  println("Sleeping...")
  val sleepStarted = scala.compat.Platform.currentTime
  Thread.sleep(ms)
  println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1")
}


(use format)
(use srfi-18)

(format #t "Enter a time (in seconds): ")
(let ((time (read))) ; converts input to a number, if possible
  (if (number? time)
    (begin
      (format #t "Sleeping...~&")
      (thread-sleep! time)
      (format #t "Awake!~&"))
    (format #t "You must enter a number~&")))


$ include "seed7_05.s7i";
  include "duration.s7i";

const proc: main is func
  local
    var integer: secondsToSleep is 0;
  begin
    write("Enter number of seconds to sleep: ");
    readln(secondsToSleep);
    writeln("Sleeping...");
    wait(secondsToSleep . SECONDS);
    writeln("Awake!");
  end func;


-- demo\rosetta\turtle.e
include pGUI.e
global Ihandle canvas, dlg
global cdCanvas cdcanvas
global bool pen_down = false

global procedure pendown(atom colour=CD_BLACK)
    pen_down = true
    cdCanvasSetForeground(cdcanvas, colour)
end procedure

global procedure penup()
    pen_down = false
end procedure


from turtle import *

def rectangle(width, height):
    for _ in range(2):
        forward(height)
        left(90)
        forward(width)
        left(90)

def square(size):
    rectangle(size, size)

def triangle(size):
    for _ in range(3):
        forward(size)
        right(120)

def house(size):
    right(180)
    square(size)
    triangle(size)
    right(180)

def barchart(lst, size):
    scale = size/max(lst)
    width = size/len(lst)
    for i in lst:
        rectangle(i*scale, width)
        penup()
        forward(width)
        pendown()
    penup()
    back(size)
    pendown()

clearscreen()
hideturtle()
house(150)
penup()
forward(10)
pendown()
barchart([0.5, (1/3), 2, 1.3, 0.5], 200)
penup()
back(10)
pendown()


  [ $ "turtleduck.qky" loadfile ] now!

  [ behead do
    rot witheach
      [ do 2over 2over
        v< if 2swap
        2drop ] ]                 is largest   (       [ --> n/d )

  [ 2 times
    [ 2dup walk
      -1 4 turn
      2over walk
      -1 4 turn ]
    2drop 2drop ]                 is rectangle ( n/d n/d -->     )

  [ 2dup rectangle ]              is square    (     n/d -->     )

  [ 3 times
     [ 2dup walk
       1 3 turn ]
    2drop ]                       is triangle  (    n/d  -->     )

  [ 1 2 turn
    2dup square triangle
    1 2 turn ]                    is house     (     n/d -->     )

  [ stack ]                       is bar.width (         --> s   )

  [ stack ]                       is bar.scale (         --> s   )

  [ join temp put
    dup size n->v
    temp share do v/ 1/v
    join bar.width put
    dup largest
    temp share do v/
    join bar.scale put
    witheach
      [ do
        bar.scale share do v/
        bar.width share do
        rectangle
        bar.width share do fly ]
    temp take do -v fly
    bar.width release
    bar.scale release ]          is barchart  (   [ n/d -->     )

   turtle
   150 1 house
   10 1 fly
   ' [ [ 1 2 ] [ 1 3 ] [ 2 1 ] [ 13 10 ] [ 1 2 ] ] 200 1 barchart
   -10 1 fly


import "dome" for Window
import "graphics" for Canvas, Color
import "./turtle" for Turtle

class Main {
    construct new(width, height) {
        Window.resize(width, height)
        Canvas.resize(width, height)
        Window.title = "Simple turtle graphics"
        _w = width
        _h = height
    }

    init() {
        Canvas.cls(Color.white)
        _t = Turtle.new()
        drawHouse(_w/4)
        barChart([15, 10, 50, 35, 20], _w/3)
    }

    drawHouse(size) {
        // save initial turtle position and direction
        var saveX = _t.x
        var saveY = _t.y
        var saveD = _t.dir

        _t.pen.width = 2

        // draw house
        _t.drawRect(_w/4, _h/2, size, size)

        // draw roof
        _t.right(30)
        _t.walk(size)
        _t.right(120)
        _t.walk(size)

        // draw door
        var doorWidth  = (size/4).floor
        var doorHeight = (size/2).floor
        _t.drawRect(_w/4 + doorWidth/2, _h/2 + doorHeight, doorWidth, doorHeight)

        // draw window
        var windWidth  = (size/3).floor
        var windHeight = (size/4).floor
        _t.drawRect(_w/4 + size/2, _h/2 + size/2, windWidth, windHeight)

        // restore initial turtle position and direction
        _t.x = saveX
        _t.y = saveY
        _t.dir = saveD
    }

    // nums assumed to be all non-negative
    barChart(nums, size) {
        // save intial turtle position and direction
        var saveX = _t.x
        var saveY = _t.y
        var saveD = _t.dir

        // find maximum
        var max = 0
        for (n in nums) if (n > max) max = n

        // scale to fit within a square with sides 'size' and draw chart
        var barWidth = (size / nums.count).floor
        var startX = _w / 2 + 20
        var startY = _h / 2
        for (i in 0...nums.count) {
            var barHeight = (nums[i] * size / max).round
            _t.drawRect(startX, startY - barHeight, barWidth, barHeight)
            startX = startX + barWidth
        }

        // restore intial turtle position and direction
        _t.x = saveX
        _t.y = saveY
        _t.dir = saveD
    }

    update() {}

    draw(alpha) {}
}

var Game = Main.new(600, 600)


import autopy
autopy.key.type_string("Hello, world!") # Prints out "Hello, world!" as quickly as OS will allow.
autopy.key.type_string("Hello, world!", wpm=60) # Prints out "Hello, world!" at 60 WPM.
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)


#lang racket/gui

(define frame (new frame%
                   (label "Example")
                   (width 300)
                   (height 300)))           ; Defines an instance of a frame to put the canvas in

(define simulate-key-canvas%
  (class canvas%
    (define/public (simulate-key key)
      (send this on-char key))              ; Creates a class that inherits from the standard canvas class, that can receive simulated key presses

    (define/override (on-char key)
      (displayln (send key get-key-code)))  ; Changes the method that receives key presses to show some output

    (super-new)))

(define canvas
  (new simulate-key-canvas%
       (parent frame)))                     ; Defines an instance of the newly created class

(send frame show #t)                        ; Shows the frame with a white canvas inside
(send canvas simulate-key (new key-event% (key-code #\k)))  ; Sends the simulated key press (with a key-event% instance)
;outputs k


use X11::libxdo;

my $xdo = Xdo.new;

my $active = $xdo.get-active-window;

my $command = $*VM.config<os> eq 'darwin' ?? 'open' !! 'xdg-open';

shell "$command https://www.google.com";

sleep 1;

my $match = rx[^'Google '];

say my $w = $xdo.search(:name($match))<ID>;

sleep .25;

if $w {
    $xdo.activate-window($w);
    say "Window name: ", $xdo.get-window-name( $w );
    $xdo.type($w, 'Raku language');
    sleep .25;
    $xdo.send-sequence($w, 'Tab');
    sleep .5;
    $xdo.send-sequence($w, 'Tab');
    sleep .5;
    $xdo.send-sequence($w, 'Tab');
    sleep .5;
    $xdo.send-sequence($w, 'Return');
}


fn num_prime_factors(xx int) int {
    mut p := 2
    mut pf := 0
    mut x := xx
    if x == 1 {
        return 1
    }
    for {
        if (x % p) == 0 {
            pf++
            x /= p
            if x == 1 {
                return pf
            }
        } else {
            p++
        }
    }
    return 0
}

fn prime_factors(xx int, mut arr []int) {
    mut p := 2
    mut pf := 0
    mut x := xx
    if x == 1 {
        arr[pf] = 1
        return
    }
    for {
        if (x % p) == 0 {
            arr[pf] = p
            pf++
            x /= p
            if x == 1 {
                return
            }
        } else {
            p++
        }
    }
}

fn sum_digits(xx int) int {
    mut x := xx
    mut sum := 0
    for x != 0 {
        sum += x % 10
        x /= 10
    }
    return sum
}

fn sum_factors(arr []int, size int) int {
    mut sum := 0
    for a := 0; a < size; a++ {
        sum += sum_digits(arr[a])
    }
    return sum
}

fn list_all_smith_numbers(max_smith int) {
    mut arr := []int{}
    mut a := 0
    for a = 4; a < max_smith; a++ {
        numfactors := num_prime_factors(a)
        arr = []int{len: numfactors}
        if numfactors < 2 {
            continue
        }
        prime_factors(a, mut arr)
        if sum_digits(a) == sum_factors(arr, numfactors) {
            print("${a:4} ")
        }
    }
}

fn main() {
    max_smith := 10000
    println("All the Smith Numbers less than $max_smith are:")
    list_all_smith_numbers(max_smith)
    println('')
}


import "/math" for Int
import "/fmt" for Fmt
import "/seq" for Lst

var sumDigits = Fn.new { |n|
    var sum = 0
    while (n > 0) {
        sum = sum + n%10
        n = (n/10).floor
    }
    return sum
}

var smiths = []
System.print("The Smith numbers below 10,000 are:")
for (i in 2...10000) {
    if (!Int.isPrime(i)) {
        var thisSum = sumDigits.call(i)
        var factors = Int.primeFactors(i)
        var factSum = factors.reduce(0) { |acc, f| acc + sumDigits.call(f) }
        if (thisSum == factSum) smiths.add(i)
    }
}
for (chunk in Lst.chunks(smiths, 16)) Fmt.print("$4d", chunk)


ask "How long would you like to sleep?" message "Your answer may include any duration, such as 5 seconds, 2 hours, or even 3 centuries!"
get the value of it

if it is a duration then
	put it into sleepyTime
else
	answer "Sorry, that wasn't a valid duration!"
	exit all
end if

put "Sleeping for " & sleepyTime & "..."
wait sleepyTime
put "Awake!"


var sec = read(Number);       # any positive number (it may be fractional)
say "Sleeping...";
Sys.sleep(sec);               # in seconds
#Sys.usleep(sec);             # in microseconds
#Sys.nanosleep(sec);          # in nanoseconds
say "Awake!";


t := (FillInTheBlankMorph request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.


(TextIO.print "input a number of seconds please: ";
let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
  TextIO.print "Sleeping...\n";
  OS.Process.sleep (Time.fromReal seconds);  (* it takes a Time.time data structure as arg,
                                               but in my implementation it seems to round down to the nearest second.
                                               I dunno why; it doesn't say anything about this in the documentation *)
  TextIO.print "Awake!\n"
end)


program sleep_awake
	* pass duration in milliseconds
	display "Sleeping..."
	sleep `0'
	display "Awake!"
end

sleep_awake 2000


function (time)
    {
    Print("Sleeping...")
    Sleep(time) // time is in milliseconds
    Print("Awake!")
    }


// Rosetta Code problem: http://rosettacode.org/wiki/Simple_turtle_graphics
// Adapted from Python to Yabasic by Galileo, 01/2022

import turtle

sub rectang(width, height)
    local i

    for i = 1 to 2
        move(height)
        turn(-90)
        move(width)
        turn(-90)
    next
end sub

sub square(size)
    rectang(size, size)
end sub

sub triang(size)
    local i

    for i = 1 to 3
        move(size)
        turn(120)
    next
end sub

sub house(size)
    turn(180)
    square(size)
    triang(size)
    turn(180)
end sub

sub barchart(lst$, size)
    local t$(1), t(1), n, m, i, scale, width

    n = token(lst$, t$())
    redim t(n)

    for i = 1 to n
        t(i) = val(t$(i))
        if t(i) > m m = t(i)
    next

    scale = size/m
    width = size/n
    for i = 1 to n
        rectang(t(i)*scale, width)
        pen(false)
        move(width)
        pen(true)
    next
    pen(false)
    move(-size)
    pen(true)
end sub

startTurtle()
color 255, 255, 255
turn(90)
house(150)
pen(false)
move(10)
pen(true)
barchart("0.5 0.333 2 1.3 0.5", 200)


/*REXX pgm shows how to use the REXX/PC  PRESS cmd to simulate keyboard input.*/

call press 'This text will be put into a buffer as if it came from the keyboard'

        /* [↑]  text will be available for any program to use (including DOS).*/
                                       /*stick a fork in it,  we're all done. */


extern crate autopilot;
fn main() {
    autopilot::key::type_string("Hello, world!", None, None, &[]);
}


import java.awt.Robot
import java.awt.event.KeyEvent

/** Keystrokes when this function is executed will go to whatever application has focus at the time.
 *  Special cases may need to be made for certain symbols, but most of
 *  the VK values in KeyEvent map to the ASCII values of characters.
 */

object Keystrokes extends App {
  def keystroke(str: String) {
    val robot = new Robot()
    for (ch <- str) {
      if (Character.isUpperCase(ch)) {
        robot.keyPress(KeyEvent.VK_SHIFT)
        robot.keyPress(ch)
        robot.keyRelease(ch)
        robot.keyRelease(KeyEvent.VK_SHIFT)
      } else {
        val upCh = Character.toUpperCase(ch)
        robot.keyPress(upCh)
        robot.keyRelease(upCh)
      }
    }
  }
  keystroke(args(0))
}


set key "x"
event generate $target <Key-$key>


Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "{Down}{F2}"
WScript.Sleep 1000 ' one-second delay
WshShell.SendKeys "{Left}{Left}{BkSp}{BkSp}Some text here.~" ' ~ -> Enter


func SumDigits(N);      \Return sum of digits in N
int  N, S;
[S:= 0;
repeat  N:= N/10;
        S:= S+rem(0);
until   N=0;
return S;
];

func SumFactor(N);      \Return sum of digits of factors of N
int  N0, N, F, S;
[N:= N0;  F:= 2;  S:= 0;
repeat  if rem(N/F) = 0 then    \found a factor
                [S:= S + SumDigits(F);
                N:= N/F;
                ]
        else    F:= F+1;
until   F > N;
if F = N0 then return 0;        \is prime
return S;
];

int C, N;
[C:= 0;
Format(5, 0);
for N:= 0 to 10_000-1 do
    if SumDigits(N) = SumFactor(N) then
        [RlOut(0, float(N));
        C:= C+1;
        if rem(C/20) = 0 then CrLf(0);
        ];
]


fcn smithNumbers(N=0d10_000){ // -->(Smith numbers to N)
   [2..N].filter(fcn(n){
      (pfs:=primeFactors(n)).len()>1 and
      n.split().sum(0)==primeFactors(n).apply("split").flatten().sum(0)
   })
}


import Foundation

println("Enter number of seconds to sleep")
let input = NSFileHandle.fileHandleWithStandardInput()
var amount = NSString(data:input.availableData, encoding: NSUTF8StringEncoding)?.intValue
var interval = NSTimeInterval(amount!)
println("Sleeping...")
NSThread.sleepForTimeInterval(interval)

println("Awake!")


puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
set millis [gets stdin]
puts Sleeping...
after $millis
puts Awake!


Local dur_secs,st0,st,seconds
Define seconds() = Func
  Local hms
  getTime()→hms
  Return ((hms[1] * 60 + hms[2]) * 60) + hms[3]
EndFunc
ClockOn

Prompt dur_secs
Disp "Sleeping..."
seconds()→st
st→st0
While when(st<st0, st+86400, st) - st0 < dur_secs
  seconds()→st
EndWhile
Disp "Awake!"


1 import sleep as sleep()
[ ." Sleeping...\n" sleep() drop ." Awake!\n" bye ] is sleep

45 sleep


$$ MODE TUSCRIPT
secondsrange=2
PRINT "Sleeping ",secondsrange," seconds "
WAIT #secondsrange
PRINT "Awake after Naping ",secondsrange, " seconds"


(let ((usec (progn (put-string "enter sleep usecs: ")
                   (tointz (get-line)))))
  (put-string "Sleeping ... ")
  (flush-stream)
  (usleep usec)
  (put-line "Awake!"))


printf "Enter a time in seconds to sleep: "
read seconds
echo "Sleeping..."
sleep "$seconds"
echo "Awake!"


/* simulate_input_keyboard.wren */

import "random" for Random

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

var XK_q            = 0x0071
var XK_Escape       = 0xff1b

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

// 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 state=(st)        // sets xkey.state

    foreign keycode           // gets xkey.keycode

    foreign keycode=(kc)      // sets xkey.keycode

    foreign sameScreen=(ss)   // sets xkey.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)
}

class X {
   foreign static lookupKeysym(keyEvent, index)

   foreign static lookupString(eventStruct, bufferReturn, bytesBuffer, keysymReturn, statusInOut)
}

 /* 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 keystrokes")

/* 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)

/* event loop */
var e = XEvent.new()
var rand = Random.new()
while (true) {
    xd.nextEvent(e)
    var et = e.eventType
    if (et == Expose) {
        /* draw or redraw the window */
        var msg1 = "Click in the window to generate"
        var msg2 = "a random key press event"
        xd.drawString(w, gc, 10, 20, msg1, msg1.count)
        xd.drawString(w, gc, 10, 35, msg2, msg2.count)
    } else if (et == ButtonPress) {
        System.print("\nButtonPress event received")
        /* manufacture a KeyPress event and send it to the window */
        var e2 = XEvent.new()
        e2.eventType = KeyPress
        e2.state = ShiftMask
        e2.keycode = 24 + rand.int(33)
        e2.sameScreen = true
        xd.sendEvent(w, true, KeyPressMask, e2)
    } else if (et == ClientMessage) {
        /* delete window event */
         if (e.dataL[0] == wmDeleteWindow) break
    } else if (et == KeyPress) {
        /* handle key press */
        System.print("\nKeyPress event received")
        System.print("> Keycode: %(e.keycode)")
        /* exit if q or escape are pressed */
        var keysym = X.lookupKeysym(e, 0)
        if (keysym == XK_q || keysym == XK_Escape) {
            break
        } else {
            var buffer = List.filled(2, 0)
            var nchars = X.lookupString(e, buffer, 2, 0, 0) // don't need the last 2 parameters
            if (nchars == 1) {
                var b = buffer[0]
                if (b < 0) b = 256 + b
                System.print("> Latin-1: %(b)")
                if (b < 32 || (b >= 127 && b < 160)) {
                    System.print("> Key 'control character' pressed")
                } else {
                    System.print("> Key '%(String.fromByte(b))' pressed")
                }
            }
        }
    }
}

xd.destroyWindow(w)

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


out "Sleeping..." endl console
# sleep for 5 seconds (5000 milliseconds)
sleep 5000
out "Awake!" endl console


Function Sleep(iSecsWait As Integer)
Debug.Print Now(), "Sleeping..."
Application.Wait Now + iSecsWait / 86400 'Time is stored as fractions of 24 hour day
Debug.Print Now(), "Awake!"
End Function


iSeconds=InputBox("Enter a time in seconds to sleep: ","Sleep Example for RosettaCode.org")
WScript.Echo "Sleeping..."
WScript.Sleep iSeconds*1000		'Sleep is done in Milli-Seconds
WScript.Echo "Awake!"


#1 = Get_Num("Sleep time in 1/10 seconds: ")
Message("Sleeping...\n")
Sleep(#1)
Message("Awake!\n")


Module Program
    Sub Main()
        Dim millisecondsSleepTime = Integer.Parse(Console.ReadLine(), Globalization.CultureInfo.CurrentCulture)
        Console.WriteLine("Sleeping...")
        Threading.Thread.Sleep(millisecondsSleepTime)
        Console.WriteLine("Awake!")
    End Sub
End Module


import time
import os

fn main() {
    sec := os.input("Enter number of seconds to sleep: ").i64()
    println("Sleeping…")
    time.sleep(time.Duration(sec * time.second))
    println("Awake!")
}


import "timer" for Timer
import "io" for Stdin, Stdout

System.write("Enter time to sleep in seconds: ")
Stdout.flush()
var secs
while (true) {
    secs = Num.fromString(Stdin.readLine())
    if (secs == null) {
        System.print("Not a number try again.")
    } else break
}
System.print("Sleeping...")
Timer.sleep((secs*1000).floor)
System.print("Awake!")


; x86_64 linux nasm

section .text

Sleep:
  mov rsi, 0 ; we wont use the second sleep arg, pass null to syscall
  sub rsp, 16
  mov qword [rsp], rdi ; number of seconds the caller requested
  mov qword [rsp + 8], rsi ; we won't use the nanoseconds
  mov rdi, rsp ; pass the struct that's on the stack to
  mov rax, 35 ; sys_nanosleep
  syscall
  add rsp, 16 ; clean up stack
  ret


int Microseconds;
[Microseconds:= IntIn(0);
Text(0, "Sleeping...^m^j");
DelayUS(Microseconds);
Text(0, "Awake!^m^j");
]


const std = @import("std");
const time = std.time;
const warn = std.debug.warn;

pub fn main() void {
    warn("Sleeping...\n");

    time.sleep(1000000000); // `sleep` uses nanoseconds

    warn("Awake!\n");
}


seconds:=ask("Seconds to sleep: ").toFloat();
println("Sleeping...");
Atomic.sleep(seconds); # float, usually millisecond resolution
println("Awake!");


print "Sleeping..."
wait 1
println
print "Awake!"


F sierpinski_square(fname, size, length, order)
   V x = (size - length) / 2
   V y = Float(length)
   V angle = 0.0

   V outfile = File(fname, ‘w’)
   outfile.write(‘<svg xmlns='http://www.w3.org/2000/svg' width='’size‘' height='’size"'>\n")
   outfile.write("<rect width='100%' height='100%' fill='white'/>\n")
   outfile.write(‘<path stroke-width='1' stroke='black' fill='none' d='’)
   V s = ‘F+XF+F+XF’
   L 0 .< order
      s = s.replace(‘X’, ‘XF-F+F-XF+F+XF-F+F-X’)

   outfile.write(‘M’x‘,’y)
   L(c) s
      S c
         ‘F’
            x += length * cos(radians(angle))
            y += length * sin(radians(angle))
            outfile.write(‘ L’x‘,’y)
         ‘+’
            angle = (angle + 90) % 360
         ‘-’
            angle = (angle - 90 + 360) % 360

   outfile.write("'/>\n</svg>\n")

sierpinski_square(‘sierpinski_square.svg’, 635, 5, 5)


// See https://en.wikipedia.org/wiki/Sierpi%C5%84ski_curve#Representation_as_Lindenmayer_system
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>

class sierpinski_square {
public:
    void write(std::ostream& out, int size, int length, int order);
private:
    static std::string rewrite(const std::string& s);
    void line(std::ostream& out);
    void execute(std::ostream& out, const std::string& s);
    double x_;
    double y_;
    int angle_;
    int length_;
};

void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
    length_ = length;
    x_ = (size - length)/2;
    y_ = length;
    angle_ = 0;
    out << "<svg xmlns='http://www.w3.org/2000/svg' width='"
        << size << "' height='" << size << "'>\n";
    out << "<rect width='100%' height='100%' fill='white'/>\n";
    out << "<path stroke-width='1' stroke='black' fill='none' d='";
    std::string s = "F+XF+F+XF";
    for (int i = 0; i < order; ++i)
        s = rewrite(s);
    execute(out, s);
    out << "'/>\n</svg>\n";
}

std::string sierpinski_square::rewrite(const std::string& s) {
    std::string t;
    for (char c : s) {
        if (c == 'X')
            t += "XF-F+F-XF+F+XF-F+F-X";
        else
            t += c;
    }
    return t;
}

void sierpinski_square::line(std::ostream& out) {
    double theta = (3.14159265359 * angle_)/180.0;
    x_ += length_ * std::cos(theta);
    y_ += length_ * std::sin(theta);
    out << " L" << x_ << ',' << y_;
}

void sierpinski_square::execute(std::ostream& out, const std::string& s) {
    out << 'M' << x_ << ',' << y_;
    for (char c : s) {
        switch (c) {
        case 'F':
            line(out);
            break;
        case '+':
            angle_ = (angle_ + 90) % 360;
            break;
        case '-':
            angle_ = (angle_ - 90) % 360;
            break;
        }
    }
}

int main() {
    std::ofstream out("sierpinski_square.svg");
    if (!out) {
        std::cerr << "Cannot open output file\n";
        return 1;
    }
    sierpinski_square s;
    s.write(out, 635, 5, 5);
    return 0;
}


USING: accessors kernel L-system sequences ui ;

: square-curve ( L-system -- L-system )
    L-parser-dialect >>commands
    [ 90 >>angle ] >>turtle-values
    "F+XF+F+XF" >>axiom
    {
        { "X" "XF-F+F-XF+F+XF-F+F-X" }
    } >>rules ;

[
    <L-system> square-curve
    "Sierpinski square curve" open-window
] with-ui


package main

import (
    "github.com/fogleman/gg"
    "github.com/trubitsyn/go-lindenmayer"
    "log"
    "math"
)

const twoPi = 2 * math.Pi

var (
    width  = 770.0
    height = 770.0
    dc     = gg.NewContext(int(width), int(height))
)

var cx, cy, h, theta float64

func main() {
    dc.SetRGB(0, 0, 1) // blue background
    dc.Clear()
    cx, cy = 10, height/2+5
    h = 6
    sys := lindenmayer.Lsystem{
        Variables: []rune{'X'},
        Constants: []rune{'F', '+', '-'},
        Axiom:     "F+XF+F+XF",
        Rules: []lindenmayer.Rule{
            {"X", "XF-F+F-XF+F+XF-F+F-X"},
        },
        Angle: math.Pi / 2, // 90 degrees in radians
    }
    result := lindenmayer.Iterate(&sys, 5)
    operations := map[rune]func(){
        'F': func() {
            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
            dc.LineTo(newX, newY)
            cx, cy = newX, newY
        },
        '+': func() {
            theta = math.Mod(theta+sys.Angle, twoPi)
        },
        '-': func() {
            theta = math.Mod(theta-sys.Angle, twoPi)
        },
    }
    if err := lindenmayer.Process(result, operations); err != nil {
        log.Fatal(err)
    }
    // needed to close the square at the extreme left
    operations['+']()
    operations['F']()

    // create the image and save it
    dc.SetRGB255(255, 255, 0) // yellow curve
    dc.SetLineWidth(2)
    dc.Stroke()
    dc.SavePNG("sierpinski_square_curve.png")
}


import java.io.*;

public class SierpinskiSquareCurve {
    public static void main(final String[] args) {
        try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) {
            SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer);
            int size = 635, length = 5;
            s.currentAngle = 0;
            s.currentX = (size - length)/2;
            s.currentY = length;
            s.lineLength = length;
            s.begin(size);
            s.execute(rewrite(5));
            s.end();
        } catch (final Exception ex) {
            ex.printStackTrace();
        }
    }

    private SierpinskiSquareCurve(final Writer writer) {
        this.writer = writer;
    }

    private void begin(final int size) throws IOException {
        write("<svg xmlns='http://www.w3.org/2000/svg' width='%d' height='%d'>\n", size, size);
        write("<rect width='100%%' height='100%%' fill='white'/>\n");
        write("<path stroke-width='1' stroke='black' fill='none' d='");
    }

    private void end() throws IOException {
        write("'/>\n</svg>\n");
    }

    private void execute(final String s) throws IOException {
        write("M%g,%g\n", currentX, currentY);
        for (int i = 0, n = s.length(); i < n; ++i) {
            switch (s.charAt(i)) {
                case 'F':
                    line(lineLength);
                    break;
                case '+':
                    turn(ANGLE);
                    break;
                case '-':
                    turn(-ANGLE);
                    break;
            }
        }
    }

    private void line(final double length) throws IOException {
        final double theta = (Math.PI * currentAngle) / 180.0;
        currentX += length * Math.cos(theta);
        currentY += length * Math.sin(theta);
        write("L%g,%g\n", currentX, currentY);
    }

    private void turn(final int angle) {
        currentAngle = (currentAngle + angle) % 360;
    }

    private void write(final String format, final Object... args) throws IOException {
        writer.write(String.format(format, args));
    }

    private static String rewrite(final int order) {
        String s = AXIOM;
        for (int i = 0; i < order; ++i) {
            final StringBuilder sb = new StringBuilder();
            for (int j = 0, n = s.length(); j < n; ++j) {
                final char ch = s.charAt(j);
                if (ch == 'X')
                    sb.append(PRODUCTION);
                else
                    sb.append(ch);
            }
            s = sb.toString();
        }
        return s;
    }

    private final Writer writer;
    private double lineLength;
    private double currentX;
    private double currentY;
    private int currentAngle;

    private static final String AXIOM = "F+XF+F+XF";
    private static final String PRODUCTION = "XF-F+F-XF+F+XF-F+F-X";
    private static final int ANGLE = 90;
}


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

def rules: {"X": "XF-F+F-XF+F+XF-F+F-X"};

def sierpinski($count):
  rules as $rules
  | def p($count):
      if $count <= 0 then .
      else gsub("X"; $rules["X"]) | p($count-1)
      end;
  "F+XF+F+XF" | p($count) ;

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

def sierpinski_curve($n):
  sierpinski($n)
  | split("")
  | reduce .[] as $action (turtle([200,650]) | turtleDown;
      interpret($action) ) ;

sierpinski_curve(5)
| path("none"; "red"; 1) | svg(1000)


using Lindenmayer # https://github.com/cormullion/Lindenmayer.jl

scurve = LSystem(Dict("X" => "XF-F+F-XF+F+XF-F+F-X"), "F+XF+F+XF")

drawLSystem(scurve,
    forward = 3,
    turn = 90,
    startingy = -400,
    iterations = 6,
    filename = "sierpinski_square_curve.png",
    showpreview = true
)


import math

type

  SierpinskiCurve = object
    x, y: float
    angle: float
    length: int
    file: File

proc line(sc: var SierpinskiCurve) =
  let theta = degToRad(sc.angle)
  sc.x += sc.length.toFloat * cos(theta)
  sc.y += sc.length.toFloat * sin(theta)
  sc.file.write " L", sc.x, ',', sc.y

proc execute(sc: var SierpinskiCurve; s: string) =
  sc.file.write 'M', sc.x, ',', sc.y
  for c in s:
    case c
    of 'F': sc.line()
    of '+': sc.angle = floorMod(sc.angle + 90, 360)
    of '-': sc.angle = floorMod(sc.angle - 90, 360)
    else: discard

func rewrite(s: string): string =
  for c in s:
    if c == 'X':
      result.add "XF-F+F-XF+F+XF-F+F-X"
    else:
      result.add c

proc write(sc: var SierpinskiCurve; size, length, order: int) =
  sc.length = length
  sc.x = (size - length) / 2
  sc.y = length.toFloat
  sc.angle = 0
  sc.file.write "<svg xmlns='http://www.w3.org/2000/svg' width='", size, "' height='", size, "'>\n"
  sc.file.write "<rect width='100%' height='100%' fill='white'/>\n"
  sc.file.write "<path stroke-width='1' stroke='black' fill='none' d='"
  var s = "F+XF+F+XF"
  for _ in 1..order: s = s.rewrite()
  sc.execute(s)
  sc.file.write "'/>\n</svg>\n"

let outfile = open("sierpinski_square.svg", fmWrite)
var sc = SierpinskiCurve(file: outfile)
sc.write(635, 5, 5)
outfile.close()


use strict;
use warnings;
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);

my $rule = 'XF-F+F-XF+F+XF-F+F-X';
my $S = 'F+F+XF+F+XF';
$S =~ s/X/$rule/g for 1..5;

my (@X, @Y);
my ($x, $y) = (0, 0);
my $theta   = pi/4;
my $r       = 6;

for (split //, $S) {
    if (/F/) {
        push @X, sprintf "%.0f", $x;
        push @Y, sprintf "%.0f", $y;
        $x += $r * cos($theta);
        $y += $r * sin($theta);
    }
    elsif (/\+/) { $theta += pi/2; }
    elsif (/\-/) { $theta -= pi/2; }
}

my ($xrng, $yrng) = ( max(@X) - min(@X),  max(@Y) - min(@Y));
my ($xt,   $yt)   = (-min(@X) + 10,      -min(@Y) + 10);

my $svg = SVG->new(width=>$xrng+20, height=>$yrng+20);
my $points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline');
$svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'});
$svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");

open my $fh, '>', 'sierpinski-square-curve.svg';
print $fh  $svg->xmlify(-namespace=>'svg');
close $fh;


--
-- demo\rosetta\Sierpinski_square_curve.exw
-- ========================================
--
-- My second atempt at a Lindenmayer system. The first
--  is now saved in demo\rosetta\Penrose_tiling.exw
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas

function redraw_cb(Ihandle /*canvas*/)
    string s = "F+F+XF+F+XF"
    for n=1 to 4 do
        string next = ""
        for i=1 to length(s) do
            integer ch = s[i]
            next &= iff(ch='X'?"XF-F+F-XF+F+XF-F+F-X":ch)
        end for
        s = next
    end for

    cdCanvasActivate(cddbuffer)
    cdCanvasBegin(cddbuffer, CD_CLOSED_LINES)
    atom x=0, y=0, theta=PI/4, r = 6
    for i=1 to length(s) do
        integer ch = s[i]
        switch ch do
            case 'F':   x += r*cos(theta)
                        y += r*sin(theta)
                        cdCanvasVertex(cddbuffer, x+270, y+270)
            case '+':   theta += PI/2
            case '-':   theta -= PI/2
        end switch
    end for
    cdCanvasEnd(cddbuffer)
    cdCanvasFlush(cddbuffer)
    return IUP_DEFAULT
end function

function map_cb(Ihandle canvas)
    cdcanvas = cdCreateCanvas(CD_IUP, canvas)
    cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
    cdCanvasSetBackground(cddbuffer, CD_WHITE)
    cdCanvasSetForeground(cddbuffer, CD_BLUE)
    return IUP_DEFAULT
end function

IupOpen()
canvas = IupCanvas("RASTERSIZE=290x295")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
                         "ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,`TITLE="Sierpinski square curve"`)
IupSetAttribute(dlg,`DIALOGFRAME`,`YES`)
IupShow(dlg)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


import matplotlib.pyplot as plt
import math

def nextPoint(x, y, angle):
    a = math.pi * angle / 180
    x2 = (int)(round(x + (1 * math.cos(a))))
    y2 = (int)(round(y + (1 * math.sin(a))))
    return x2, y2

def expand(axiom, rules, level):
    for l in range(0, level):
        a2 = ""
        for c in axiom:
            if c in rules:
                a2 += rules[c]
            else:
                a2 += c
        axiom = a2
    return axiom

def draw_lsystem(axiom, rules, angle, iterations):
    xp = [1]
    yp = [1]
    direction = 0
    for c in expand(axiom, rules, iterations):
        if c == "F":
            xn, yn = nextPoint(xp[-1], yp[-1], direction)
            xp.append(xn)
            yp.append(yn)
        elif c == "-":
            direction = direction - angle
            if direction < 0:
                direction = 360 + direction
        elif c == "+":
            direction = (direction + angle) % 360

    plt.plot(xp, yp)
    plt.show()

if __name__ == '__main__':
    # Sierpinski Square L-System Definition
    s_axiom = "F+XF+F+XF"
    s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"}
    s_angle = 90

    draw_lsystem(s_axiom, s_rules, s_angle, 3)


  [ $ "turtleduck.qky" loadfile ] now!

  [ stack ]                      is switch.arg (   --> [ )

  [ switch.arg put ]             is switch     ( x -->   )

  [ switch.arg release ]         is otherwise  (   -->   )

  [ switch.arg share
    != iff ]else[ done
    otherwise ]'[ do ]done[ ]    is case       ( x -->   )

  [ $ "" swap witheach
      [ nested quackery join ] ] is expand     ( $ --> $ )

  [ $ "L" ]                      is L          ( $ --> $ )

  [ $ "R" ]                      is R          ( $ --> $ )

  [ $ "F" ]                      is F          ( $ --> $ )

  [ $ "AFRFLFRAFLFLAFRFLFRA" ]   is A          ( $ --> $ )

  $ "FLAFLFLAF"

  4 times expand

  turtle
  witheach
    [ switch
        [ char L case [ -1 4 turn ]
          char R case [  1 4 turn ]
          char F case [  5 1 walk ]
          otherwise ( ignore ) ] ]


use SVG;

role Lindenmayer {
    has %.rules;
    method succ {
        self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)
    }
}

my $sierpinski = 'X' but Lindenmayer( { X => 'XF-F+F-XF+F+XF-F+F-X' } );

$sierpinski++ xx 5;

my $dim = 600;
my $scale = 6;

my @points = (-80, 298);

for $sierpinski.comb {
    state ($x, $y) = @points[0,1];
    state $d = $scale + 0i;
    when 'F' { @points.append: ($x += $d.re).round(1), ($y += $d.im).round(1) }
    when /< + - >/ { $d *= "{$_}1i" }
    default { }
}

my @t = @points.tail(2).clone;

my $out = './sierpinski-square-curve-perl6.svg'.IO;

$out.spurt: SVG.serialize(
    svg => [
        :width($dim), :height($dim),
        :rect[:width<100%>, :height<100%>, :fill<black>],
        :polyline[
          :points((@points, map {(@t »+=» $_).clone}, ($scale,0), (0,$scale), (-$scale,0)).join: ','),
          :fill<black>, :transform("rotate(45, 300, 300)"), :style<stroke:#61D4FF>,
        ],
        :polyline[
          :points(@points.map( -> $x,$y { $x, $dim - $y + 1 }).join: ','),
          :fill<black>, :transform("rotate(45, 300, 300)"), :style<stroke:#61D4FF>,
        ],
    ],
);


// [dependencies]
// svg = "0.8.0"

use svg::node::element::path::Data;
use svg::node::element::Path;

struct SierpinskiSquareCurve {
    current_x: f64,
    current_y: f64,
    current_angle: i32,
    line_length: f64,
}

impl SierpinskiSquareCurve {
    fn new(x: f64, y: f64, length: f64, angle: i32) -> SierpinskiSquareCurve {
        SierpinskiSquareCurve {
            current_x: x,
            current_y: y,
            current_angle: angle,
            line_length: length,
        }
    }
    fn rewrite(order: usize) -> String {
        let mut str = String::from("F+XF+F+XF");
        for _ in 0..order {
            let mut tmp = String::new();
            for ch in str.chars() {
                match ch {
                    'X' => tmp.push_str("XF-F+F-XF+F+XF-F+F-X"),
                    _ => tmp.push(ch),
                }
            }
            str = tmp;
        }
        str
    }
    fn execute(&mut self, order: usize) -> Path {
        let mut data = Data::new().move_to((self.current_x, self.current_y));
        for ch in SierpinskiSquareCurve::rewrite(order).chars() {
            match ch {
                'F' => data = self.draw_line(data),
                '+' => self.turn(90),
                '-' => self.turn(-90),
                _ => {}
            }
        }
        Path::new()
            .set("fill", "none")
            .set("stroke", "black")
            .set("stroke-width", "1")
            .set("d", data)
    }
    fn draw_line(&mut self, data: Data) -> Data {
        let theta = (self.current_angle as f64).to_radians();
        self.current_x += self.line_length * theta.cos();
        self.current_y += self.line_length * theta.sin();
        data.line_to((self.current_x, self.current_y))
    }
    fn turn(&mut self, angle: i32) {
        self.current_angle = (self.current_angle + angle) % 360;
    }
    fn save(file: &str, size: usize, length: f64, order: usize) -> std::io::Result<()> {
        use svg::node::element::Rectangle;
        let x = (size as f64 - length) / 2.0;
        let y = length;
        let rect = Rectangle::new()
            .set("width", "100%")
            .set("height", "100%")
            .set("fill", "white");
        let mut s = SierpinskiSquareCurve::new(x, y, length, 0);
        let document = svg::Document::new()
            .set("width", size)
            .set("height", size)
            .add(rect)
            .add(s.execute(order));
        svg::save(file, &document)
    }
}

fn main() {
    SierpinskiSquareCurve::save("sierpinski_square_curve.svg", 635, 5.0, 5).unwrap();
}


var rules = Hash(
    x => 'xF-F+F-xF+F+xF-F+F-x',
)

var lsys = LSystem(
    width:  510,
    height: 510,

    xoff: -505,
    yoff: -254,

    len:   4,
    angle: 90,
    color: 'dark green',
)

lsys.execute('F+xF+F+xF', 5, "sierpiński_square_curve.png", rules)


import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
import "./lsystem" for LSystem, Rule

var TwoPi = Num.pi * 2

class SierpinskiSquareCurve {
    construct new(width, height, back, fore) {
        Window.title = "Sierpinski Square Curve"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _w = width
        _h = height
        _bc = back
        _fc = fore
    }

    init() {
        Canvas.cls(_bc)
        var cx = 10
        var cy = (_h/2).floor + 5
        var theta = 0
        var h = 6
        var lsys = LSystem.new(
            ["X"],                                    //  variables
            ["F", "+", "-"],                          //  constants
            "F+XF+F+XF",                              //  axiom
            [Rule.new("X", "XF-F+F-XF+F+XF-F+F-X")],  //  rules
            Num.pi / 2                                //  angle (90 degrees in radians)
        )
        var result = lsys.iterate(5)
        var operations = {
            "F": Fn.new {
                var newX = cx + h*Math.sin(theta)
                var newY = cy - h*Math.cos(theta)
                Canvas.line(cx, cy, newX, newY, _fc, 2)
                cx = newX
                cy = newY
            },
            "+": Fn.new {
                theta = (theta + lsys.angle) % TwoPi
            },
            "-": Fn.new {
                theta = (theta - lsys.angle) % TwoPi
            }
        }
        LSystem.execute(result, operations)
    }

    update() {}

    draw(alpha) {}
}

var Game = SierpinskiSquareCurve.new(770, 770, Color.blue, Color.yellow)


sierpinskiSquareCurve(4) : turtle(_);

fcn sierpinskiSquareCurve(n){	// Lindenmayer system --> Data of As
   var [const] A="AF-F+F-AF+F+AF-F+F-A", B="";  // Production rules
   var [const] Axiom="F+AF+F+AF";
   buf1,buf2 := Data(Void,Axiom).howza(3), Data().howza(3);  // characters
   do(n){
      buf1.pump(buf2.clear(),fcn(c){ if(c=="A") A else if(c=="B") B else c });
      t:=buf1; buf1=buf2; buf2=t;	// swap buffers
   }
   buf1		// n=4 --> 3,239 characters
}

fcn turtle(curve){	// a "square" turtle, directions are +-90*
   const D=10;
   ds,dir := T( T(D,0), T(0,-D), T(-D,0), T(0,D) ), 2; // turtle offsets
   dx,dy := ds[dir];
   img,color := PPM(650,650), 0x00ff00;  // green on black
   x,y := img.w/2, 10;
   curve.replace("A","").replace("B","");  // A & B are no-op during drawing
   foreach c in (curve){
      switch(c){
	 case("F"){ img.line(x,y, (x+=dx),(y+=dy), color) }  // draw forward
	 case("+"){ dir=(dir+1)%4; dx,dy = ds[dir] } // turn right 90*
	 case("-"){ dir=(dir-1)%4; dx,dy = ds[dir] } // turn left 90*
      }
   }
   img.writeJPGFile("sierpinskiSquareCurve.zkl.jpg");
}


PROC Main()
  INT ARRAY xs=[249 200 96 80 175]
  BYTE ARRAY ys=[82 176 159 55 7]
  INT x,y
  BYTE i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6

  Graphics(8+16)
  Color=1
  COLOR1=$0C
  COLOR2=$02

  x=160+Rand(30)
  y=96+Rand(30)
  DO
    i=Rand(5)
    x=x+(xs(i)-x)*62/100
	y=y+(ys(i)-y)*62/100
    Plot(x,y)
  UNTIL CH#$FF
  OD
  CH=$FF
RETURN


W := H := 640
hw := W / 2
margin := 20
radius := hw - 2 * margin
side := radius * Sin(PI := 3.141592653589793 / 5) * 2
order := 5

gdip1()
drawPentagon(hw, 3*margin, side, order, 1)
return

drawPentagon(x, y, side, depth, colorIndex){
    global G, hwnd1, hdc, Width, Height
    Red        := "0xFFFF0000"
    Green    := "0xFF00FF00"
    Blue    := "0xFF0000FF"
    Magenta    := "0xFFFF00FF"
    Cyan    := "0xFF00FFFF"
    Black    := "0xFF000000"
    Palette    := [Red, Green, Blue, Magenta, Cyan]
    PI        := 3.141592653589793
    Deg72    := 72 * PI/180
    angle    := 3 * Deg72
    ScaleFactor    := 1 / ( 2 + Cos(Deg72) * 2)

    points .= x "," y
    if (depth = 1) {
        loop 5 {
            prevx := x
            prevy := y
            x += Cos(angle) * side
            y -= Sin(angle) * side
            points .= "|" x "," y
            pPen := Gdip_CreatePen(Black, 2)
            Gdip_DrawLines(G, pPen, prevx "," prevy "|" x "," y)
            angle += Deg72
        }
        pBrush := Gdip_BrushCreateSolid(Palette[colorIndex])
        Gdip_FillPolygon(G, pBrush, Points)
        UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
    }
    else{
        side *= ScaleFactor
        dist := side * (1 + (Cos(Deg72)*2))
        loop 5{
            x += Cos(angle) * dist
            y -= Sin(angle) * dist
            colorIndex := Mod(colorIndex+1, 5) + 1
            drawPentagon(x, y, side, depth-1, colorIndex)
            angle += Deg72
        }
    }
}
; ---------------------------------------------------------------
gdip1(){
    global
    If !pToken := Gdip_Startup(){
        MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
        ExitApp
    }
    OnExit, Exit
    Width := 640, Height := 640
    Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
    Gui, 1: Show, NA
    hwnd1 := WinExist()
    hbm := CreateDIBSection(Width, Height)
    hdc := CreateCompatibleDC()
    obm := SelectObject(hdc, hbm)
    G := Gdip_GraphicsFromHDC(hdc)
    Gdip_SetSmoothingMode(G, 4)
    blackCanvas := Gdip_BrushCreateSolid(0xFFFFFFFF)
    Gdip_FillRectangle(G, blackCanvas, 0, 0, Width, Height)
    UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
}
; ---------------------------------------------------------------
gdip2(){
    global
    Gdip_DeleteBrush(pBrush)
    Gdip_DeletePen(pPen)
    SelectObject(hdc, obm)
    DeleteObject(hbm)
    DeleteDC(hdc)
    Gdip_DeleteGraphics(G)
}
; ---------------------------------------------------------------
Esc::
GuiEscape:
Exit:
gdip2()
Gdip_Shutdown(pToken)
ExitApp
Return


#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>

#define pi M_PI

int main(){

	time_t t;
	double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
	int i,iter,choice,numSides;

	printf("Enter number of sides : ");
	scanf("%d",&numSides);

	printf("Enter polygon side length : ");
	scanf("%lf",&side);

	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	initwindow(windowSide,windowSide,"Polygon Chaos");

	vertices = (double**)malloc(numSides*sizeof(double*));

	for(i=0;i<numSides;i++){
		vertices[i] = (double*)malloc(2 * sizeof(double));

		vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
		vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
		sumX+= vertices[i][0];
		sumY+= vertices[i][1];
		putpixel(vertices[i][0],vertices[i][1],15);
	}

	srand((unsigned)time(&t));

	seedX = sumX/numSides;
	seedY = sumY/numSides;

	putpixel(seedX,seedY,15);

	for(i=0;i<iter;i++){
		choice = rand()%numSides;

		seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
		seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);

		putpixel(seedX,seedY,15);
	}

	free(vertices);

	getch();

	closegraph();

	return 0;
}


#include <iomanip>
#include <iostream>

#define _USE_MATH_DEFINES
#include <math.h>

constexpr double degrees(double deg) {
    const double tau = 2.0 * M_PI;
    return deg * tau / 360.0;
}

const double part_ratio = 2.0 * cos(degrees(72));
const double side_ratio = 1.0 / (part_ratio + 2.0);

/// Define a position
struct Point {
    double x, y;

    friend std::ostream& operator<<(std::ostream& os, const Point& p);
};

std::ostream& operator<<(std::ostream& os, const Point& p) {
    auto f(std::cout.flags());
    os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' ';
    std::cout.flags(f);
    return os;
}

/// Mock turtle implementation sufficiant to handle "drawing" the pentagons
struct Turtle {
private:
    Point pos;
    double theta;
    bool tracing;

public:
    Turtle() : theta(0.0), tracing(false) {
        pos.x = 0.0;
        pos.y = 0.0;
    }

    Turtle(double x, double y) : theta(0.0), tracing(false) {
        pos.x = x;
        pos.y = y;
    }

    Point position() {
        return pos;
    }
    void position(const Point& p) {
        pos = p;
    }

    double heading() {
        return theta;
    }
    void heading(double angle) {
        theta = angle;
    }

    /// Move the turtle through space
    void forward(double dist) {
        auto dx = dist * cos(theta);
        auto dy = dist * sin(theta);

        pos.x += dx;
        pos.y += dy;

        if (tracing) {
            std::cout << pos;
        }
    }

    /// Turn the turtle
    void right(double angle) {
        theta -= angle;
    }

    /// Start/Stop exporting the points of the polygon
    void begin_fill() {
        if (!tracing) {
            std::cout << "<polygon points=\"";
            tracing = true;
        }
    }
    void end_fill() {
        if (tracing) {
            std::cout << "\"/>\n";
            tracing = false;
        }
    }
};

/// Use the provided turtle to draw a pentagon of the specified size
void pentagon(Turtle& turtle, double size) {
    turtle.right(degrees(36));
    turtle.begin_fill();
    for (size_t i = 0; i < 5; i++) {
        turtle.forward(size);
        turtle.right(degrees(72));
    }
    turtle.end_fill();
}

/// Draw a sierpinski pentagon of the desired order
void sierpinski(int order, Turtle& turtle, double size) {
    turtle.heading(0.0);
    auto new_size = size * side_ratio;

    if (order-- > 1) {
        // create four more turtles
        for (size_t j = 0; j < 4; j++) {
            turtle.right(degrees(36));

            double small = size * side_ratio / part_ratio;
            auto distList = { small, size, size, small };
            auto dist = *(distList.begin() + j);

            Turtle spawn{ turtle.position().x, turtle.position().y };
            spawn.heading(turtle.heading());
            spawn.forward(dist);

            // recurse for each spawned turtle
            sierpinski(order, spawn, new_size);
        }

        // recurse for the original turtle
        sierpinski(order, turtle, new_size);
    } else {
        // The bottom has been reached for this turtle
        pentagon(turtle, size);
    }
    if (order > 0) {
        std::cout << '\n';
    }
}

/// Run the generation of a P(5) sierpinksi pentagon
int main() {
    const int order = 5;
    double size = 500;

    Turtle turtle{ size / 2.0, size };

    std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n";
    std::cout << "<!DOCTYPE svg PUBLIC \" -//W3C//DTD SVG 1.1//EN\"\n";
    std::cout << "    \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
    std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n";
    std::cout << "    version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n";

    size *= part_ratio;
    sierpinski(order, turtle, size);

    std::cout << "</svg>";
}


import std.math;
import std.stdio;

/// Convert degrees into radians, as that is the accepted unit for sin/cos etc...
real degrees(real deg) {
    immutable tau = 2.0 * PI;
    return deg * tau / 360.0;
}

immutable part_ratio = 2.0 * cos(72.degrees);
immutable side_ratio = 1.0 / (part_ratio + 2.0);

/// Use the provided turtle to draw a pentagon of the specified size
void pentagon(Turtle turtle, real size) {
    turtle.right(36.degrees);
    turtle.begin_fill();
    foreach(i; 0..5) {
        turtle.forward(size);
        turtle.right(72.degrees);
    }
    turtle.end_fill();
}

/// Draw a sierpinski pentagon of the desired order
void sierpinski(int order, Turtle turtle, real size) {
    turtle.setheading(0.0);
    auto new_size = size * side_ratio;

    if (order-- > 1) {
        // create four more turtles
        foreach(j; 0..4) {
            turtle.right(36.degrees);
            real small = size * side_ratio / part_ratio;
            auto dist = [small, size, size, small][j];

            auto spawn = new Turtle();
            spawn.setposition(turtle.position);
            spawn.setheading(turtle.heading);
            spawn.forward(dist);

            // recurse for each spawned turtle
            sierpinski(order, spawn, new_size);
        }

        // recurse for the original turtle
        sierpinski(order, turtle, new_size);
    } else {
        // The bottom has been reached for this turtle
        pentagon(turtle, size);
    }
}

/// Run the generation of a P(5) sierpinksi pentagon
void main() {
    int order = 5;
    real size = 500;

    auto turtle = new Turtle(size/2, size);

    // Write the header to an SVG file for the image
    writeln(`<?xml version="1.0" standalone="no"?>`);
    writeln(`<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"`);
    writeln(`    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">`);
    writefln(`<svg height="%s" width="%s" style="fill:blue" transform="translate(%s,%s) rotate(-36)"`, size, size, size/2, size/2);
    writeln(`    version="1.1" xmlns="http://www.w3.org/2000/svg">`);
    // Write the close tag when the interior points have been written
    scope(success) writeln("</svg>");

    // Scale the initial turtle so that it stays in the inner pentagon
    size *= part_ratio;

    // Begin rendering
    sierpinski(order, turtle, size);
}

/// Define a position
struct Point {
    real x;
    real y;

    /// When a point is written, do it in the form "x,y " to three decimal places
    void toString(scope void delegate(const(char)[]) sink) const {
        import std.format;

        formattedWrite(sink, "%0.3f", x);
        sink(",");
        formattedWrite(sink, "%0.3f", y);
        sink(" ");
    }
}

/// Mock turtle implementation sufficiant to handle "drawing" the pentagons
class Turtle {
    /////////////////////////////////
    private:

    Point pos;
    real theta;
    bool tracing;

    /////////////////////////////////
    public:
    this() {
        // empty
    }

    this(real x, real y) {
        pos.x = x;
        pos.y = y;
    }

    // Get/Set the turtle position
    Point position() {
        return pos;
    }
    void setposition(Point pos) {
        this.pos = pos;
    }

    // Get/Set the turtle's heading
    real heading() {
        return theta;
    }
    void setheading(real angle) {
        theta = angle;
    }

    // Move the turtle through space
    void forward(real dist) {
        // Calculate both components at once for the specified angle
        auto delta = dist * expi(theta);

        pos.x += delta.re;
        pos.y += delta.im;

        if (tracing) {
            write(pos);
        }
    }

    // Turn the turle
    void right(real angle) {
        theta = theta - angle;
    }

    // Start/Stop exporting the points of the polygon
    void begin_fill() {
        write(`<polygon points="`);
        tracing = true;
    }
    void end_fill() {
        writeln(`"/>`);
        tracing = false;
    }
}


package main

import (
    "github.com/fogleman/gg"
    "image/color"
    "math"
)

var (
    red     = color.RGBA{255, 0, 0, 255}
    green   = color.RGBA{0, 255, 0, 255}
    blue    = color.RGBA{0, 0, 255, 255}
    magenta = color.RGBA{255, 0, 255, 255}
    cyan    = color.RGBA{0, 255, 255, 255}
)

var (
    w, h        = 640, 640
    dc          = gg.NewContext(w, h)
    deg72       = gg.Radians(72)
    scaleFactor = 1 / (2 + math.Cos(deg72)*2)
    palette     = [5]color.Color{red, green, blue, magenta, cyan}
    colorIndex  = 0
)

func drawPentagon(x, y, side float64, depth int) {
    angle := 3 * deg72
    if depth == 0 {
        dc.MoveTo(x, y)
        for i := 0; i < 5; i++ {
            x += math.Cos(angle) * side
            y -= math.Sin(angle) * side
            dc.LineTo(x, y)
            angle += deg72
        }
        dc.SetColor(palette[colorIndex])
        dc.Fill()
        colorIndex = (colorIndex + 1) % 5
    } else {
        side *= scaleFactor
        dist := side * (1 + math.Cos(deg72)*2)
        for i := 0; i < 5; i++ {
            x += math.Cos(angle) * dist
            y -= math.Sin(angle) * dist
            drawPentagon(x, y, side, depth-1)
            angle += deg72
        }
    }
}

func main() {
    dc.SetRGB(1, 1, 1) // White background
    dc.Clear()
    order := 5 // Can also set this to 1, 2, 3 or 4
    hw := float64(w / 2)
    margin := 20.0
    radius := hw - 2*margin
    side := radius * math.Sin(math.Pi/5) * 2
    drawPentagon(hw, 3*margin, side, order-1)
    dc.SavePNG("sierpinski_pentagon.png")
}


import Graphics.Gloss

pentaflake :: Int -> Picture
pentaflake order = iterate transformation pentagon !! order
  where
    transformation = Scale s s . foldMap copy [0,72..288]
    copy a = Rotate a . Translate 0 x
    pentagon = Polygon [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ]
    x = 2*cos(pi/5)
    s = 1/(1+x)

main = display dc white (Color blue $ Scale 300 300 $ pentaflake 5)
  where dc = InWindow "Pentaflake" (400, 400) (0, 0)


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import static java.lang.Math.*;
import java.util.Random;
import javax.swing.*;

public class SierpinskiPentagon extends JPanel {
    // exterior angle
    final double degrees072 = toRadians(72);

    /* After scaling we'll have 2 sides plus a gap occupying the length
       of a side before scaling. The gap is the base of an isosceles triangle
       with a base angle of 72 degrees. */
    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);

    final int margin = 20;
    int limit = 0;
    Random r = new Random();

    public SierpinskiPentagon() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);

        new Timer(3000, (ActionEvent e) -> {
            limit++;
            if (limit >= 5)
                limit = 0;
            repaint();
        }).start();
    }

    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {
        double angle = 3 * degrees072; // starting angle

        if (depth == 0) {

            Path2D p = new Path2D.Double();
            p.moveTo(x, y);

            // draw from the top
            for (int i = 0; i < 5; i++) {
                x = x + cos(angle) * side;
                y = y - sin(angle) * side;
                p.lineTo(x, y);
                angle += degrees072;
            }

            g.setColor(RandomHue.next());
            g.fill(p);

        } else {

            side *= scaleFactor;

            /* Starting at the top of the highest pentagon, calculate
               the top vertices of the other pentagons by taking the
               length of the scaled side plus the length of the gap. */
            double distance = side + side * cos(degrees072) * 2;

            /* The top positions form a virtual pentagon of their own,
               so simply move from one to the other by changing direction. */
            for (int i = 0; i < 5; i++) {
                x = x + cos(angle) * distance;
                y = y - sin(angle) * distance;
                drawPentagon(g, x, y, side, depth - 1);
                angle += degrees072;
            }
        }
    }

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

        int w = getWidth();
        double radius = w / 2 - 2 * margin;
        double side = radius * sin(PI / 5) * 2;

        drawPentagon(g, w / 2, 3 * margin, side, limit);
    }

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

class RandomHue {
    /* Try to avoid random color values clumping together */
    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;
    private static double hue = Math.random();

    static Color next() {
        hue = (hue + goldenRatioConjugate) % 1;
        return Color.getHSBColor((float) hue, 1, 1);
    }
}


 	Click Pentaflake to iterate.  Order: 0
 	<input type="submit" value="RESET" onclick="resetf(0);">
 	(Reset anytime: to start new Pentaflake and change color.)

    <canvas id="cvsid" width=640 height=640></canvas>


using Printf

const sides = 5
const order = 5
const dim   = 250
const scale = (3 - order ^ 0.5) / 2
const τ = 8 * atan(1, 1)
const orders = map(x -> ((1 - scale) * dim) * scale ^ x, 0:order-1)
cis(x) = Complex(cos(x), sin(x))
const vertices = map(x -> cis(x * τ  / sides), 0:sides-1)

fh = open("sierpinski_pentagon.svg", "w")
print(fh, """<svg height=\"$(dim*2)\" width=\"$(dim*2)\" style=\"fill:blue\" """ *
    """version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n""")

for i in 1:sides^order
    varr = [vertices[parse(Int, ch) + 1] for ch in split(string(i, base=sides, pad=order), "")]
    vector = sum(map(x -> varr[x] * orders[x], 1:length(orders)))
    vprod = map(x -> vector + orders[end] * (1-scale) * x, vertices)

    points = join([@sprintf("%.3f %.3f", real(v), imag(v)) for v in vprod], " ")
    print(fh, "<polygon points=\"$points\" transform=\"translate($dim,$dim) rotate(-18)\" />\n")
end

print(fh, "</svg>")
close(fh)


// version 1.1.2

import java.awt.*
import java.awt.geom.Path2D
import java.util.Random
import javax.swing.*

class SierpinskiPentagon : JPanel() {
    // exterior angle
    private val degrees072 = Math.toRadians(72.0)

    /* After scaling we'll have 2 sides plus a gap occupying the length
       of a side before scaling. The gap is the base of an isosceles triangle
       with a base angle of 72 degrees. */
    private val scaleFactor = 1.0 / (2.0 + Math.cos(degrees072) * 2.0)

    private val margin = 20
    private var limit = 0
    private val r = Random()

    init {
        preferredSize = Dimension(640, 640)
        background = Color.white
        Timer(3000) {
            limit++
            if (limit >= 5) limit = 0
            repaint()
        }.start()
    }

    private fun drawPentagon(g: Graphics2D, x: Double, y: Double, s: Double, depth: Int) {
        var angle = 3.0 * degrees072  // starting angle
        var xx = x
        var yy = y
        var side = s
        if (depth == 0) {
            val p = Path2D.Double()
            p.moveTo(xx, yy)

            // draw from the top
            for (i in 0 until 5) {
                xx += Math.cos(angle) * side
                yy -= Math.sin(angle) * side
                p.lineTo(xx, yy)
                angle += degrees072
            }

            g.color = RandomHue.next()
            g.fill(p)
        }
        else {
            side *= scaleFactor
            /* Starting at the top of the highest pentagon, calculate
               the top vertices of the other pentagons by taking the
               length of the scaled side plus the length of the gap. */
            val distance = side + side * Math.cos(degrees072) * 2.0

            /* The top positions form a virtual pentagon of their own,
               so simply move from one to the other by changing direction. */
            for (i in 0 until 5) {
                xx += Math.cos(angle) * distance
                yy -= Math.sin(angle) * distance
                drawPentagon(g, xx, yy, side, depth - 1)
                angle += degrees072
            }
        }
    }

    override fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        val hw = width / 2
        val radius = hw - 2.0 * margin
        val side = radius * Math.sin(Math.PI / 5.0) * 2.0
        drawPentagon(g, hw.toDouble(), 3.0 * margin, side, limit)
    }

    private class RandomHue {
        /* Try to avoid random color values clumping together */
        companion object {
            val goldenRatioConjugate = (Math.sqrt(5.0) - 1.0) / 2.0
            var hue = Math.random()

            fun next(): Color {
                hue = (hue + goldenRatioConjugate) % 1
                return Color.getHSBColor(hue.toFloat(), 1.0f, 1.0f)
            }
        }
    }
}

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


Bitmap.chaosgame = function(self, n, r, niters)
  local w, h, vertices = self.width, self.height, {}
  for i = 1, n do
    vertices[i] = {
      x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n),
      y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n)
    }
  end
  local x, y = w/2, h/2
  for i = 1, niters do
    local v = math.random(n)
    x = x + r * (vertices[v].x - x)
    y = y + r * (vertices[v].y - y)
    self:set(x,y,0xFFFFFFFF)
  end
end

local bitmap = Bitmap(128, 128)
bitmap:chaosgame(5, 1/((1+math.sqrt(5))/2), 1e6)
bitmap:render({[0x000000]='..', [0xFFFFFFFF]='██'})


pentaFlake[0] = RegularPolygon[5];
pentaFlake[n_] := GeometricTransformation[pentaFlake[n - 1], TranslationTransform /@ CirclePoints[{GoldenRatio^(2 n - 1), Pi/10}, 5]]
[email protected][4]


import math
import imageman

const
  Red = ColorRGBU [byte 255, 0, 0]
  Green = ColorRGBU [byte 0, 255, 0]
  Blue = ColorRGBU [byte 0, 0, 255]
  Magenta = ColorRGBU [byte 255, 0, 255]
  Cyan = ColorRGBU [byte 0, 255, 255]
  Black = ColorRGBU [byte 0, 0, 0]

  (W, H) = (640, 640)
  Deg72 = degToRad(72.0)
  ScaleFactor = 1 / ( 2 + cos(Deg72) * 2)
  Palette = [Red, Green, Blue, Magenta, Cyan]

proc drawPentagon(img: var Image; x, y, side: float; depth: int) =
  var (x, y) = (x, y)
  var colorIndex {.global.} = 0
  var angle = 3 * Deg72
  if depth == 0:
    for _ in 0..4:
      let (prevx, prevy) = (x, y)
      x += cos(angle) * side
      y -= sin(angle) * side
      img.drawLine(prevx.toInt, prevy.toInt, x.toInt, y.toInt, Palette[colorIndex])
      angle += Deg72
    colorIndex = (colorIndex + 1) mod 5
  else:
    let side = side * ScaleFactor
    let dist = side * (1 + cos(Deg72) * 2)
    for _ in 0..4:
      x += cos(angle) * dist
      y -= sin(angle) * dist
      img.drawPentagon(x, y, side, depth - 1)
      angle += Deg72

var image = initImage[ColorRGBU](W, H)
image.fill(Black)
var order = 5
let hw = W / 2
let margin = 20.0
let radius = hw - 2 * margin
let side = radius * sin(PI / 5) * 2
image.drawPentagon(hw, 3 * margin, side, order - 1)
image.savePNG("Sierpinski_pentagon.png", compression = 9)


use ntheory qw(todigits);
use Math::Complex;

$sides = 5;
$order = 5;
$dim   = 250;
$scale = ( 3 - 5**.5 ) / 2;
push @orders, ((1 - $scale) * $dim) * $scale ** $_ for 0..$order-1;

open $fh, '>', 'sierpinski_pentagon.svg';
print $fh qq|<svg height="@{[$dim*2]}" width="@{[$dim*2]}" style="fill:blue" version="1.1" xmlns="http://www.w3.org/2000/svg">\n|;

$tau = 2 * 4*atan2(1, 1);
push @vertices, cis( $_ * $tau / $sides ) for 0..$sides-1;

for $i (0 .. -1+$sides**$order)  {
    @base5 = todigits($i,5);
    @i = ( ((0)x(-1+$sides-$#base5) ), @base5);
    @v = @vertices[@i];
    $vector = 0;
    $vector += $v[$_] * $orders[$_] for 0..$#orders;

    my @points;
    for (@vertices) {
        $v = $vector + $orders[-1] * (1 - $scale) * $_;
        push @points, sprintf '%.3f %.3f', $v->Re, $v->Im;
    }
    print $fh pgon(@points);
}

sub cis  { Math::Complex->make(cos($_[0]), sin($_[0])) }
sub pgon { my(@q)=@_; qq|<polygon points="@q" transform="translate($dim,$dim) rotate(-18)"/>\n| }

print $fh '</svg>';
close $fh;