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

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

//--------------------------------------------------------------------------------------------------
const int BMP_SIZE = 512, CELL_SIZE = 8;

//--------------------------------------------------------------------------------------------------
enum directions { NONE, NOR = 1, EAS = 2, SOU = 4, WES = 8 };

//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ) {}
    ~myBitmap()
    {
	DeleteObject( pen );
	DeleteDC( hdc );
	DeleteObject( bmp );
    }

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

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

	hdc = CreateCompatibleDC( dc );
	SelectObject( hdc, bmp );
	ReleaseDC( GetConsoleWindow(), dc );
	width = w; height = h;

	return true;
    }

    void clear()
    {
	ZeroMemory( pBits, width * height * sizeof( DWORD ) );
    }

    void setPenColor( DWORD clr )
    {
	if( pen ) DeleteObject( pen );
	pen = CreatePen( PS_SOLID, 1, clr );
	SelectObject( hdc, pen );
    }

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

	GetObject( bmp, sizeof( bitmap ), &bitmap );

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

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

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

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

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

	delete [] dwpBits;
    }

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

private:
    HBITMAP bmp;
    HDC	    hdc;
    HPEN    pen;
    void    *pBits;
    int	    width, height;
};
//--------------------------------------------------------------------------------------------------
class mazeGenerator
{
public:
    mazeGenerator()
    {
	_world = 0;
	_bmp.create( BMP_SIZE, BMP_SIZE );
	_bmp.setPenColor( RGB( 0, 255, 0 ) );
    }

    ~mazeGenerator() { killArray(); }

    void create( int side )
    {
	_s = side;
	generate();
	display();
    }

private:
    void generate()
    {
	killArray();
	_world = new BYTE[_s * _s];
	ZeroMemory( _world, _s * _s );
	_ptX = rand() % _s; _ptY = rand() % _s;
	carve();
    }

    void carve()
    {
	while( true )
	{
	    int d = getDirection();
	    if( d < NOR ) return;

	    switch( d )
	    {
	        case NOR:
	            _world[_ptX + _s * _ptY] |= NOR; _ptY--;
		    _world[_ptX + _s * _ptY] = SOU | SOU << 4;
		break;
	        case EAS:
		    _world[_ptX + _s * _ptY] |= EAS; _ptX++;
		    _world[_ptX + _s * _ptY] = WES | WES << 4;
		break;
		case SOU:
		    _world[_ptX + _s * _ptY] |= SOU; _ptY++;
		    _world[_ptX + _s * _ptY] = NOR | NOR << 4;
		break;
		case WES:
		    _world[_ptX + _s * _ptY] |= WES; _ptX--;
		    _world[_ptX + _s * _ptY] = EAS | EAS << 4;
	    }
	}
    }

    void display()
    {
	_bmp.clear();
	HDC dc = _bmp.getDC();
	for( int y = 0; y < _s; y++ )
	{
	    int yy = y * _s;
	    for( int x = 0; x < _s; x++ )
	    {
		BYTE b = _world[x + yy];
		int nx = x * CELL_SIZE,
		    ny = y * CELL_SIZE;

		if( !( b & NOR ) )
		{
		    MoveToEx( dc, nx, ny, NULL );
		    LineTo( dc, nx + CELL_SIZE + 1, ny );
		}
		if( !( b & EAS ) )
		{
		    MoveToEx( dc, nx + CELL_SIZE, ny, NULL );
		    LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 );
		}
		if( !( b & SOU ) )
		{
		    MoveToEx( dc, nx, ny + CELL_SIZE, NULL );
		    LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE );
		}
		if( !( b & WES ) )
		{
		    MoveToEx( dc, nx, ny, NULL );
		    LineTo( dc, nx, ny + CELL_SIZE + 1 );
		}
	    }
	}

	//_bmp.saveBitmap( "f:\\rc\\maze.bmp" );
	BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY );
    }

    int getDirection()
    {
	int d = 1 << rand() % 4;
	while( true )
	{
	    for( int x = 0; x < 4; x++ )
	    {
		if( testDir( d ) ) return d;
		d <<= 1;
		if( d > 8 ) d = 1;
	    }
	    d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4;
	    if( !d ) return -1;
	    switch( d )
	    {
		case NOR: _ptY--; break;
		case EAS: _ptX++; break;
		case SOU: _ptY++; break;
		case WES: _ptX--; break;
	    }
            d = 1 << rand() % 4;
	}
    }

    bool testDir( int d )
    {
	switch( d )
	{
	    case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] );
	    case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] );
	    case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] );
	    case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] );
	}
	return false;
    }

    void killArray() { if( _world ) delete [] _world; }

    BYTE*    _world;
    int      _s, _ptX, _ptY;
    myBitmap _bmp;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
    srand( GetTickCount() );

    mazeGenerator mg;
    int s;
    while( true )
    {
	cout << "Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): "; cin >> s;
	if( !s ) return 0;
	if( !( s & 1 ) ) s++;
	if( s >= 3 ) mg.create( s );
	cout << endl;
	system( "pause" );
	system( "cls" );
    }
    return 0;
}
//--------------------------------------------------------------------------------------------------


(ns maze.core
  (:require [clojure.set :refer [intersection
                                 select]]
            [clojure.string :as str]))

;; Misc functions
(defn neighborhood
  ([] (neighborhood [0 0]))
  ([coord] (neighborhood coord 1))
  ([[y x] r]
   (let [y-- (- y r) y++ (+ y r)
         x-- (- x r) x++ (+ x r)]
     #{[y++ x] [y-- x] [y x--] [y x++]})))

(defn cell-empty? [maze coords]
  (= :empty (get-in maze coords)))

(defn wall? [maze coords]
  (= :wall (get-in maze coords)))

(defn filter-maze
  ([pred maze coords]
   (select (partial pred maze) (set coords)))
  ([pred maze]
   (filter-maze
     pred
     maze
     (for [y (range (count maze))
           x (range (count (nth maze y)))]
       [y x]))))

(defn create-empty-maze [width height]
  (let [width (inc (* 2 width))
        height (inc (* 2 height))]
    (vec (take height
               (interleave
                 (repeat (vec (take width (repeat :wall))))
                 (repeat (vec (take width (cycle [:wall :empty])))))))))

(defn next-step [possible-steps]
  (rand-nth (vec possible-steps)))

;;Algo
(defn create-random-maze [width height]
  (loop [maze (create-empty-maze width height)
         stack []
         nonvisited (filter-maze cell-empty? maze)
         visited #{}
         coords (next-step nonvisited)]
    (if (empty? nonvisited)
      maze
      (let [nonvisited-neighbors (intersection (neighborhood coords 2) nonvisited)]
        (cond
          (seq nonvisited-neighbors)
          (let [next-coords (next-step nonvisited-neighbors)
                wall-coords (map #(+ %1 (/ (- %2 %1) 2)) coords next-coords)]
            (recur (assoc-in maze wall-coords :empty)
                   (conj stack coords)
                   (disj nonvisited next-coords)
                   (conj visited next-coords)
                   next-coords))

          (seq stack)
          (recur maze (pop stack) nonvisited visited (last stack)))))))

;;Conversion to string
(def cell-code->str
  ["  " "  " "  " "  " "· " "╵ " "╴ " "┘ "
   "  " "  " "  " "  " "╶─" "└─" "──" "┴─"
   "  " "  " "  " "  " "╷ " "│ " "┐ " "┤ "
   "  " "  " "  " "  " "┌─" "├─" "┬─" "┼─"])

(defn cell-code [maze coord]
  (transduce
    (comp
      (map (partial wall? maze))
      (keep-indexed (fn [idx el] (when el idx)))
      (map (partial bit-shift-left 1)))
    (completing bit-or)
    0
    (sort (cons coord (neighborhood coord)))))

(defn cell->str [maze coord]
  (get cell-code->str (cell-code maze coord)))

(defn maze->str [maze]
  (->> (for [y (range (count maze))]
         (for [x (range (count (nth maze y)))]
           (cell->str maze [y x])))
       (map str/join)
       (str/join \newline)))

;;Task
(println (maze->str (create-random-maze 10 10)))


100 MS=10:REM MAZE SIZE
110 DIM S(MS+1,MS+1):REM SOUTH WALLS
120 DIM W(MS+1,MS+1):REM WEST WALLS
130 DIM V(MS+1,MS+1):REM VISITED CELLS
140 PRINT "INITIALIZING..."
150 GOSUB 260:REM INITIALIZE MAZE
160 PRINT "BUILDING..."
170 DIM PC(MS*MS+1):DIM PR(MS*MS+1):REM STACK
180 REM PICK RANDOM STARTING CELL
190 X = RND(-TI)
200 C=(INT(RND(1)*MS)+1)
210 R=(INT(RND(1)*MS)+1)
220 GOSUB 400:REM BUILD MAZE
230 GOSUB 540:REM DRAW MAZE
240 END
250 REM -----INITIALIZE MAZE-----
260 REM SET WALLS ON AND VISITED CELLS OFF
270 T=MS+1
280 FOR C=0 TO T:FOR R=0 TO T:
290 S(C,R)=1:W(C,R)=1:V(C,R)=0
300 NEXT R:NEXT C
310 REM SET BORDER CELLS TO VISITED
320 FOR C=0 TO T
330 V(C,0)=1:V(C,T)=1
340 NEXT C
350 FOR R=0 TO T
360 V(0,R)=1:V(T,R)=1
370 NEXT R
380 RETURN
390 REM -----BUILD MAZE-----
400 U=U+1:PC(U)=C:PR(U)=R:REM PUSH
410 V(C,R)=1
420 IF V(C,R+1)=1 AND V(C+1,R)=1 AND V(C,R-1)=1 AND V(C-1,R)=1 THEN GOTO 500
430 Z=INT(RND(1)*4)
440 IF Z=0 AND V(C,R+1)=0 THEN S(C,R)=0:R=R+1:GOTO 400
450 IF Z=1 AND V(C+1,R)=0 THEN W(C+1,R)=0:C=C+1:GOTO 400
460 IF Z=2 AND V(C,R-1)=0 THEN S(C,R-1)=0:R=R-1:GOTO 400
470 IF Z=3 AND V(C-1,R)=0 THEN W(C,R)=0:C=C-1:GOTO 400
480 GOTO 430
500 C=PC(U):R=PR(U):U=U-1:REM POP
510 IF U > 0 THEN GOTO 420
520 RETURN
530 REM -----DRAW MAZE-----
540 REM OPEN 4,4:CMD 4:REM SEND OUTPUT TO PRINTER
550 PRINT "+--+--+--+--+--+--+--+--+--+--+"
560 FOR R = 1 TO MS
570 FOR C = 1 TO MS+1
580 IF W(C,R)=0 THEN PRINT "   ";
590 IF W(C,R)=1 THEN PRINT ":  ";
600 NEXT C
610 PRINT
620 FOR C = 1 TO MS
630 IF S(C,R)=0 THEN PRINT "+  ";
640 IF S(C,R)=1 THEN PRINT "+--";
650 NEXT C
660 PRINT "+"
670 NEXT R
680 REM PRINT#4:CLOSE 4:REM CLOSE PRINTER DEVICE
690 RETURN


with Ada.Command_Line;
with Ada.Directories;
with Ada.Text_IO;

procedure Make_Directory_Path is
begin
   if Ada.Command_Line.Argument_Count /= 1 then
      Ada.Text_IO.Put_Line ("Usage: make_directory_path <path/to/dir>");
      return;
   end if;

   declare
      Path : String renames Ada.Command_Line.Argument (1);
   begin
      Ada.Directories.Create_Path (Path);
   end;
end Make_Directory_Path;


void
mkdirp(text path)
{
    list l;
    text p, s;

    file().b_affix(path).news(l, 0, 0, "/");

    for (, s in l) {
        p = p + s + "/";
        trap_q(mkdir, p, 00755);
    }
}

integer
main(void)
{
    mkdirp("./path/to/dir");

    0;
}


use framework "Foundation"
use scripting additions

-- createOrFindDirectoryMay :: Bool -> FilePath -> Maybe IO ()
on createOrFindDirectoryMay(fp)
    createDirectoryIfMissingMay(true, fp)
end createOrFindDirectoryMay

-- createDirectoryIfMissingMay :: Bool -> FilePath -> Maybe IO ()
on createDirectoryIfMissingMay(blnParents, fp)
    if doesPathExist(fp) then
        nothing("Directory already exists: " & fp)
    else
        set e to reference
        set ca to current application
        set oPath to (ca's NSString's stringWithString:(fp))'s ¬
            stringByStandardizingPath
        set {bool, nse} to ca's NSFileManager's ¬
            defaultManager's createDirectoryAtPath:(oPath) ¬
            withIntermediateDirectories:(blnParents) ¬
            attributes:(missing value) |error|:(e)
        if bool then
            just(fp)
        else
            nothing((localizedDescription of nse) as string)
        end if
    end if
end createDirectoryIfMissingMay

-- TEST ----------------------------------------------------------------------
on run

    createOrFindDirectoryMay("~/Desktop/Notes/today")

end run

-- GENERIC FUNCTIONS ---------------------------------------------------------

-- doesPathExist :: FilePath -> IO Bool
on doesPathExist(strPath)
    set ca to current application
    ca's NSFileManager's defaultManager's ¬
        fileExistsAtPath:((ca's NSString's ¬
            stringWithString:strPath)'s ¬
            stringByStandardizingPath)
end doesPathExist

-- just :: a -> Just a
on just(x)
    {nothing:false, just:x}
end just

-- nothing :: () -> Nothing
on nothing(msg)
    {nothing:true, msg:msg}
end nothing


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

PROC Map(REAL POINTER a1,a2,b1,b2,s,res)
  REAL tmp1,tmp2,tmp3

  RealSub(s,a1,tmp1) ;tmp1=s-a1
  RealSub(b2,b1,tmp2) ;tmp2=b2-b1
  RealMult(tmp1,tmp2,tmp3) ;tmp3=(s-a1)*(b2-b1)
  RealSub(a2,a1,tmp1) ;tmp1=a2-a1
  RealDiv(tmp3,tmp1,tmp2) ;tmp2=(s-a1)*(b2-b1)/(a2-a1)
  RealAdd(b1,tmp2,res) ;res=b1+(s-a1)*(b2-b1)/(a2-a1)
RETURN

PROC Main()
  BYTE i
  REAL a1,a2,b1,b2,s,res

  Put(125) PutE() ;clear screen

  ValR("0",a1) ValR("10",a2)
  ValR("-1",b1) ValR("0",b2)

  FOR i=0 TO 10
  DO
    IntToReal(i,s)
    Map(a1,a2,b1,b2,s,res)
    PrintR(s) Print(" maps to ")
    PrintRE(res)
  OD
RETURN


(defun shuffle (list)                        ;; Z not uniform
  (sort list '> :key (lambda(x) (random 1.0))))

(defun neighbors (x y maze)
  (remove-if-not
   (lambda (x-y) (and (< -1 (first x-y) (array-dimension maze 0))
                 (< -1 (second x-y) (array-dimension maze 1))))
   `((,x ,(+ y 2)) (,(- x 2) ,y) (,x ,(- y 2)) (,(+ x 2) ,y))))

(defun remove-wall (maze x y &optional visited)
  (labels ((walk (maze x y)
             (push (list x y) visited)
             (loop for (u v) in (shuffle (neighbors x y maze))
                unless (member (list u v) visited :test 'equal)
                do (setf (aref maze u v) #\space
                         (aref maze (/ (+ x u) 2) (/ (+ y v) 2)) #\space)
                   (walk maze u v))))
    (setf (aref maze x y) #\space)
    (walk maze x y)))

(defun draw-maze (width height &key (block #\BOX_DRAWINGS_LIGHT_DIAGONAL_CROSS))
  (let ((maze (make-array (list (1+ (* 2 height)) (1+ (* 2 width)))
                          :element-type 'character :initial-element block)))
    (remove-wall maze (1+ (* 2 (random height))) (1+ (* 2 (random width))))
    (loop for i below (array-dimension maze 0)
          do (fresh-line)
             (loop for j below (array-dimension maze 1)
                   do (princ (aref maze i j))))))

(draw-maze 20 6)


with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Strings.Fixed;

procedure Digital_Rain is
   type Column_Type     is range 0 .. 150;
   type Row_Type        is range 0 .. 25;
   type Character_Range is new Character range 'A' .. 'Z';
   subtype Delay_Range  is Integer range 2 .. 6;

   package Column_Random    is new Ada.Numerics.Discrete_Random (Column_Type);
   package Row_Random       is new Ada.Numerics.Discrete_Random (Row_Type);
   package Character_Random is new Ada.Numerics.Discrete_Random (Character_Range);
   package Delay_Random     is new Ada.Numerics.Discrete_Random (Delay_Range);

   Column_Generator    : Column_Random.Generator;
   Row_Generator       : Row_Random.Generator;
   Character_Generator : Character_Random.Generator;
   Delay_Generator     : Delay_Random.Generator;

   Esc     : constant Character := Character'Val (8#33#);
   Running : Boolean   := True;
   Char    : Character;
   use Ada.Text_IO;

   protected Text_Out is
      procedure Put_At (Row : Row_Type; Col : Column_Type;
                        Color : Integer; Item : Character);
   end Text_Out;

   protected body Text_Out is
      procedure Put_At (Row : Row_Type; Col : Column_Type;
                        Color : Integer; Item : Character)
      is
         use Ada.Strings;
      begin
         Put (Esc & "[" &
                Fixed.Trim (Row'Image, Left) & ";" &
                Fixed.Trim (Col'Image, Left) & "H");             -- Place Cursor
         Put (Esc & "[" & Fixed.Trim (Color'Image, Left) & "m"); -- Foreground color
         Put (Item);
      end Put_At;
   end Text_Out;

   task type Rainer;

   task body Rainer is
      Row : Row_Type;
      Col : Column_Type;
      Del : Delay_Range;
   begin
      Outer_Loop:
      loop
         Col := Column_Random.Random (Column_Generator);
         Row := Row_Random.Random (Row_Generator);
         for Rain in reverse Boolean loop
            Del := Delay_Random.Random (Delay_Generator);
            for R in 0 .. Row loop
               if Rain then
                  if R in 1 .. Row then
                     Text_Out.Put_At (R - 1, Col, Color => 32, Item => Char);
                  end if;
                  Char := Character (Character_Random.Random (Character_Generator));
                  if R in 0 .. Row - 1 then
                     Text_Out.Put_At (R, Col, Color => 97, Item => Char);
                  end if;
               else
                  Text_Out.Put_At (R, Col, Color => 30, Item => ' ');
               end if;
               delay 0.020 * Del;
               exit Outer_Loop when not Running;
            end loop;
         end loop;
      end loop Outer_Loop;
   end Rainer;

   Dummy   : Character;
   Rainers : array (1 .. 50) of Rainer;
begin
   Put (ESC & "[?25l");        -- Hide the cursor
   Put (ESC & "[40m");         -- Black background
   Put (ESC & "[2J");          -- Clear Terminal

   Get_Immediate (Dummy);
   Running := False;
   delay 0.200;

   Put (ESC & "[?25h");        -- Restore the cursor
   Put (ESC & "[0;0H");        -- Place cursor
   Put (ESC & "[39m");         -- Default foreground
   Put (ESC & "[49m");         -- Default backgound
   Put (ESC & "[2J");          -- Clear Terminal
end Digital_Rain;


# syntax: GAWK -f MAKE_DIRECTORY_PATH.AWK path ...
BEGIN {
    for (i=1; i<=ARGC-1; i++) {
      path = ARGV[i]
      msg = (make_dir_path(path) == 0) ? "created" : "exists"
      printf("'%s' %s\n",path,msg)
    }
    exit(0)
}
function make_dir_path(path,  cmd) {
#   cmd = sprintf("mkdir -p '%s'",path) # Unix
    cmd = sprintf("MKDIR \"%s\" 2>NUL",path) # MS-Windows
    return system(cmd)
}


#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

int main (int argc, char **argv) {
    char *str, *s;
    struct stat statBuf;

    if (argc != 2) {
        fprintf (stderr, "usage: %s <path>\n", basename (argv[0]));
        exit (1);
    }
    s = argv[1];
    while ((str = strtok (s, "/")) != NULL) {
        if (str != s) {
            str[-1] = '/';
        }
        if (stat (argv[1], &statBuf) == -1) {
            mkdir (argv[1], 0);
        } else {
            if (! S_ISDIR (statBuf.st_mode)) {
                fprintf (stderr, "couldn't create directory %s\n", argv[1]);
                exit (1);
            }
        }
        s = NULL;
    }
    return 0;
}


with Ada.Text_IO;
procedure Map is
   type First_Range  is new Float range 0.0 .. 10.0;
   type Second_Range is new Float range -1.0 .. 0.0;
   function Translate (Value : First_Range) return Second_Range is
      B1 : Float := Float (Second_Range'First);
      B2 : Float := Float (Second_Range'Last);
      A1 : Float := Float (First_Range'First);
      A2 : Float := Float (First_Range'Last);
      Result : Float;
   begin
      Result := B1 + (Float (Value) - A1) * (B2 - B1) / (A2 - A1);
      return Second_Range (Result);
   end;
   function Translate (Value : Second_Range) return First_Range is
      B1 : Float := Float (First_Range'First);
      B2 : Float := Float (First_Range'Last);
      A1 : Float := Float (Second_Range'First);
      A2 : Float := Float (Second_Range'Last);
      Result : Float;
   begin
      Result := B1 + (Float (Value) - A1) * (B2 - B1) / (A2 - A1);
      return First_Range (Result);
   end;
   Test_Value : First_Range := First_Range'First;
begin
   loop
      Ada.Text_IO.Put_Line (First_Range'Image (Test_Value) & " maps to: "
                          & Second_Range'Image (Translate (Test_Value)));
      exit when Test_Value = First_Range'Last;
      Test_Value := Test_Value + 1.0;
   end loop;
end Map;


# maps a real s in the range [ a1, a2 ] to the range [ b1, b2 ]           #
# there are no checks that s is in the range or that the ranges are valid #
PROC map range = ( REAL s, a1, a2, b1, b2 )REAL:
    b1 + ( ( s - a1 ) * ( b2 - b1 ) ) / ( a2 - a1 );

# test the mapping #
FOR i FROM 0 TO 10 DO
    print( ( whole( i, -2 ), " maps to ", fixed( map range( i, 0, 10, -1, 0 ), -8, 2 ), newline ) )
OD


void main() @safe {
    import std.stdio, std.algorithm, std.range, std.random;

    enum uint w = 14, h = 10;
    auto vis = new bool[][](h, w),
         hor = iota(h + 1).map!(_ => ["+---"].replicate(w)).array,
         ver = h.iota.map!(_ => ["|   "].replicate(w) ~ "|").array;

    void walk(in uint x, in uint y) /*nothrow*/ @safe /*@nogc*/ {
        vis[y][x] = true;
        //foreach (immutable p; [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover) {
        foreach (const p; [[x-1, y], [x, y+1], [x+1, y], [x, y-1]].randomCover) {
            if (p[0] >= w || p[1] >= h || vis[p[1]][p[0]]) continue;
            if (p[0] == x) hor[max(y, p[1])][x] = "+   ";
            if (p[1] == y) ver[y][max(x, p[0])] = "    ";
            walk(p[0], p[1]);
        }
    }
    walk(uniform(0, w), uniform(0, h));
    foreach (const a, const b; hor.zip(ver ~ []))
        join(a ~ "+\n" ~ b).writeln;
}


:: Matrix Digital Rain Task from RosettaCode
:: Batch File Implementation

@echo off
setlocal enabledelayedexpansion

rem escape character (for Windows 10 VT100 escape sequences)
rem info: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
for /f %%e in ('echo prompt $e^| cmd') do @set "esc=%%e"

rem set window size
set "col=120"   %== please don't make this too large ==%
set "row=30"   %== please don't make this too large ==%
mode con cols=%col% lines=%row%

rem set up the variables for display
set "rain_length=12"
for /l %%y in (1,1,%col%) do set "disp_col[%%y]= "   %== what to display ==%
for /l %%y in (1,1,%col%) do set "ctr_col[%%y]=0"   %== counter for rain length ==%

rem hide the cursor, and clear the screen
<nul set /p "=%esc%[?25l"
cls

:matrix_loop
for /l %%y in (1,1,%col%) do (
    if !ctr_col[%%y]! equ 0 (
        set "disp_col[%%y]= "
    ) else (
        set /a "rnd_digit=!random! %% 10"
        if !ctr_col[%%y]! equ 1 (
            set "disp_col[%%y]=%esc%[97m!rnd_digit!%esc%[32m"
        ) else if !ctr_col[%%y]! equ 2 (
            set "disp_col[%%y]=%esc%[92m!rnd_digit!%esc%[32m"
        ) else (
            set "disp_col[%%y]=!rnd_digit!"
        )
        set /a "ctr_col[%%y]=(!ctr_col[%%y]! + 1) %% (%rain_length% + 1)"
    )
    rem drop rain randomly
    set /a "rnd_drop=!random! %% 20"
    if !rnd_drop! equ 0 set "ctr_col[%%y]=1"
)
set "disp_line=%esc%[32m"
for /l %%y in (1,1,%col%) do set "disp_line=!disp_line!!disp_col[%%y]!"
<nul set /p "=%esc%[1T%esc%[1;1H"   %== scroll down and set cursor position to home ==%
echo(%disp_line%
goto matrix_loop


#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
	if(argc != 2)
	{
		std::cout << "usage: mkdir <path>\n";
		return -1;
	}

	fs::path pathToCreate(argv[1]);

	if (fs::exists(pathToCreate))
		return 0;

	if (fs::create_directories(pathToCreate))
		return 0;
	else
	{
		std::cout << "couldn't create directory: " << pathToCreate.string() << std::endl;
		return -1;
	}
}


(defn mkdirp [path]
  (let [dir (java.io.File. path)]
    (if (.exists dir)
      true
      (.mkdirs dir))))


import std.stdio;

void main() {
    makeDir("parent/test");
}

/// Manual implementation of what mkdirRecurse in std.file does.
void makeDir(string path) out {
    import std.exception : enforce;
    import std.file : exists;
    enforce(path.exists, "Failed to create the requested directory.");
} body {
    import std.array : array;
    import std.file;
    import std.path : pathSplitter, chainPath;

    auto workdir = "";
    foreach (dir; path.pathSplitter) {
        workdir = chainPath(workdir, dir).array;
        if (workdir.exists) {
            if (!workdir.isDir) {
                import std.conv : text;
                throw new FileException(text("The file ", workdir, " in the path ", path, " is not a directory."));
            }
        } else {
            workdir.mkdir();
        }
    }
}


double inc = (nHasta - nDesde) / ( nTotal - 1);
lista[0] = nDesde;
lista[nTotal] = nHasta;
for( n=1; n<nTotal; n++){
    lista[n] = lista[n-1] + inc;
}


------------------------ MAP RANGE -----------------------

-- rangeMap :: (Num, Num) -> (Num, Num) -> Num -> Num
on rangeMap(a, b)
    script
        on |λ|(s)
            set {a1, a2} to a
            set {b1, b2} to b
            b1 + ((s - a1) * (b2 - b1)) / (a2 - a1)
        end |λ|
    end script
end rangeMap

--------------------------- TEST -------------------------
on run
    set mapping to rangeMap({0, 10}, {-1, 0})

    set xs to enumFromTo(0, 10)
    set ys to map(mapping, xs)
    set zs to map(approxRatio(0), ys)

    unlines(zipWith3(formatted, xs, ys, zs))
end run

------------------------- DISPLAY ------------------------

-- formatted :: Int -> Float -> Ratio -> String
on formatted(x, m, r)
    set fract to showRatio(r)
    set {n, d} to splitOn("/", fract)

    (justifyRight(2, space, x as string) & "   ->   " & ¬
        justifyRight(4, space, m as string)) & "   =   " & ¬
        justifyRight(2, space, n) & "/" & d
end formatted

-------------------- GENERIC FUNCTIONS -------------------

-- Absolute value.
-- abs :: Num -> Num
on abs(x)
    if 0 > x then
        -x
    else
        x
    end if
end abs

-- approxRatio :: Real -> Real -> Ratio
on approxRatio(epsilon)
    script
        on |λ|(n)
            if {real, integer} contains (class of epsilon) and 0 < epsilon then
                set e to epsilon
            else
                set e to 1 / 10000
            end if

            script gcde
                on |λ|(e, x, y)
                    script _gcd
                        on |λ|(a, b)
                            if b < e then
                                a
                            else
                                |λ|(b, a mod b)
                            end if
                        end |λ|
                    end script
                    |λ|(abs(x), abs(y)) of _gcd
                end |λ|
            end script

            set c to |λ|(e, 1, n) of gcde
            ratio((n div c), (1 div c))
        end |λ|
    end script
end approxRatio

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m ≤ n then
        set lst to {}
        repeat with i from m to n
            set end of lst to i
        end repeat
        return lst
    else
        return {}
    end if
end enumFromTo

-- gcd :: Int -> Int -> Int
on gcd(a, b)
    set x to abs(a)
    set y to abs(b)
    repeat until y = 0
        if x > y then
            set x to x - y
        else
            set y to y - x
        end if
    end repeat
    return x
end gcd

-- justifyLeft :: Int -> Char -> String -> String
on justifyLeft(n, cFiller, strText)
    if n > length of strText then
        text 1 thru n of (strText & replicate(n, cFiller))
    else
        strText
    end if
end justifyLeft

-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller, strText)
    if n > length of strText then
        text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
    else
        strText
    end if
end justifyRight

-- length :: [a] -> Int
on |length|(xs)
    set c to class of xs
    if list is c or string is c then
        length of xs
    else
        (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
    end if
end |length|

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- minimum :: Ord a => [a] -> a
on minimum(xs)
    set lng to length of xs
    if lng < 1 then return missing value
    set m to item 1 of xs
    repeat with x in xs
        set v to contents of x
        if v < m then set m to v
    end repeat
    return m
end minimum

-- ratio :: Int -> Int -> Ratio Int
on ratio(x, y)
    script go
        on |λ|(x, y)
            if 0 ≠ y then
                if 0 ≠ x then
                    set d to gcd(x, y)
                    {type:"Ratio", n:(x div d), d:(y div d)}
                else
                    {type:"Ratio", n:0, d:1}
                end if
            else
                missing value
            end if
        end |λ|
    end script
    go's |λ|(x * (signum(y)), abs(y))
end ratio

-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
    set out to {}
    if n < 1 then return out
    set dbl to {a}

    repeat while (n > 1)
        if (n mod 2) > 0 then set out to out & dbl
        set n to (n div 2)
        set dbl to (dbl & dbl)
    end repeat
    return out & dbl
end replicate

-- showRatio :: Ratio -> String
on showRatio(r)
    (n of r as string) & "/" & (d of r as string)
end showRatio

-- signum :: Num -> Num
on signum(x)
    if x < 0 then
        -1
    else if x = 0 then
        0
    else
        1
    end if
end signum

-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, pat}
    set xs to text items of src
    set my text item delimiters to dlm
    return xs
end splitOn

-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
    set c to class of xs
    if list is c then
        if 0 < n then
            items 1 thru min(n, length of xs) of xs
        else
            {}
        end if
    else if string is c then
        if 0 < n then
            text 1 thru min(n, length of xs) of xs
        else
            ""
        end if
    else if script is c then
        set ys to {}
        repeat with i from 1 to n
            set v to xs's |λ|()
            if missing value is v then
                return ys
            else
                set end of ys to v
            end if
        end repeat
        return ys
    else
        missing value
    end if
end take

-- unlines :: [String] -> String
on unlines(xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set str to xs as text
    set my text item delimiters to dlm
    str
end unlines

-- zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
on zipWith3(f, xs, ys, zs)
    set lng to minimum({length of xs, length of ys, length of zs})
    if 1 > lng then return {}
    set lst to {}
    tell mReturn(f)
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, item i of ys, item i of zs)
        end repeat
        return lst
    end tell
end zipWith3


program MazeGen_Rosetta;

{$APPTYPE CONSOLE}

uses System.SysUtils, System.Types, System.Generics.Collections, System.IOUtils;

type
  TMCell = record
    Visited  : Boolean;
    PassTop  : Boolean;
    PassLeft : Boolean;
  end;
  TMaze  = array of array of TMCell;
  TRoute = TStack<TPoint>;

const
  mwidth  = 24;
  mheight = 14;

procedure ClearVisited(var AMaze: TMaze);
var
  x, y: Integer;
begin
  for y := 0 to mheight - 1 do
    for x := 0 to mwidth - 1 do
      AMaze[x, y].Visited := False;
end;

procedure PrepareMaze(var AMaze: TMaze);
var
  Route    : TRoute;
  Position : TPoint;
  d        : Integer;
  Pool     : array of TPoint; // Pool of directions to pick randomly from
begin
  SetLength(AMaze, mwidth, mheight);
  ClearVisited(AMaze);
  Position := Point(Random(mwidth), Random(mheight));
  Route := TStack<TPoint>.Create;
  try
    with Position do
    while True do
    begin
      repeat
        SetLength(Pool, 0);
        if (y > 0)         and not AMaze[x, y-1].Visited then Pool := Pool + [Point(0, -1)];
        if (x < mwidth-1)  and not AMaze[x+1, y].Visited then Pool := Pool + [Point(1,  0)];
        if (y < mheight-1) and not AMaze[x, y+1].Visited then Pool := Pool + [Point(0,  1)];
        if (x > 0)         and not AMaze[x-1, y].Visited then Pool := Pool + [Point(-1, 0)];

        if Length(Pool) = 0 then // no direction to draw from
        begin
          if Route.Count = 0 then Exit; // and we are back at start so this is the end
          Position := Route.Pop;
        end;
      until Length(Pool) > 0;

      d := Random(Length(Pool));
      Offset(Pool[d]);

      AMaze[x, y].Visited := True;
      if Pool[d].y = -1 then AMaze[x, y+1].PassTop  := True; // comes from down to up ( ^ )
      if Pool[d].x =  1 then AMaze[x, y].PassLeft   := True; // comes from left to right ( --> )
      if Pool[d].y =  1 then AMaze[x, y].PassTop    := True; // comes from left to right ( v )
      if Pool[d].x = -1 then AMaze[x+1, y].PassLeft := True; // comes from right to left ( <-- )
      Route.Push(Position);
    end;
  finally
    Route.Free;
  end;
end;

function MazeToString(const AMaze: TMaze; const S, E: TPoint): String; overload;
var
  x, y: Integer;
  v   : Char;
begin
  Result := '';
  for y := 0 to mheight - 1 do
  begin
    for x := 0 to mwidth - 1 do
      if AMaze[x, y].PassTop then Result := Result + '+'#32#32#32 else Result := Result + '+---';
    Result := Result + '+' + sLineBreak;
    for x := 0 to mwidth - 1 do
    begin
      if S = Point(x, y) then v := 'S' else
        if E = Point(x, y) then v := 'E' else
          v := #32'*'[Ord(AMaze[x, y].Visited) + 1];

      Result := Result + '|'#32[Ord(AMaze[x, y].PassLeft) + 1] + #32 + v + #32;
    end;
    Result := Result + '|' + sLineBreak;
  end;
  for x := 0 to mwidth - 1 do Result := Result + '+---';
  Result := Result + '+' + sLineBreak;
end;

procedure Main;
var
  Maze: TMaze;
begin
  Randomize;
  PrepareMaze(Maze);
  ClearVisited(Maze);     // show no route
  Write(MazeToString(Maze, Point(-1, -1), Point(-1, -1)));
  ReadLn;
end;

begin
  Main;

end.


(defun matrix-digital-rain ()
  (with-screen (scr :input-echoing nil :input-blocking nil :cursor-visible nil)
    (let* ((width (width scr))
           (height (height scr))
           ;; start at a random height in each column.
           (positions (loop repeat width collect (random height)))
           ;; run each column at a random speed.
           (speeds (loop repeat width collect (random 4))))
      ;; generate a random ascii char
      (flet ((randch () (+ 64 (random 58))))
        ;; hit the q key to exit the main loop.
        (bind scr #\q 'exit-event-loop)
        (bind scr nil
          (lambda (win event)
            (loop for col from 0 to (1- width) do
              (loop repeat (nth col speeds) do
                ;; position of the first point in the current column
                (let ((pos (nth col positions)))
                  (setf (attributes win) '(:bold))
                  (setf (fgcolor win) :green)
                  (add win (randch) :y (mod pos height) :x col :fgcolor :white)
                  (add win (randch) :y (mod (- pos 1) height) :x col)
                  (add win (randch) :y (mod (- pos 2) height) :x col)
                  (setf (attributes win) '())
                  (add win (randch) :y (mod (- pos 3) height) :x col)
                  ;; overwrite the last char half the height from the first char.
                  (add win #\space  :y (mod (- pos (floor height 2)) height) :x col)
                  (refresh win)
                  ;; advance the current column
                  (setf (nth col positions) (mod (+ pos 1) height))))))))
      (setf (frame-rate scr) 20)
      (run-event-loop scr))))


program Make_directory_path;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IOUtils;

const
  Path1 = '.\folder1\folder2\folder3'; // windows relative path (others OS formats are acepted)
  Path2 = 'folder4\folder5\folder6';

begin
  // "ForceDirectories" work with relative path if start with "./"
  if ForceDirectories(Path1) then
    Writeln('Created "', path1, '" sucessfull.');

  // "TDirectory.CreateDirectory" work with any path format
  //  but don't return sucess, requere "TDirectory.Exists" to check
  TDirectory.CreateDirectory(Path2);
  if TDirectory.Exists(Path2) then
    Writeln('Created "', path2, '" sucessfull.');
  Readln;
end.


> System.IO.Directory.CreateDirectory (System.IO.Directory.GetCurrentDirectory())
;;
val it : System.IO.DirectoryInfo =
  Temp {Attributes = Directory;
        CreationTime = 2016-06-01 04:12:25;
        CreationTimeUtc = 2016-06-01 02:12:25;
        Exists = true;
        Extension = "";
        FullName = "C:\Users\Kai\AppData\Local\Temp";
        LastAccessTime = 2016-08-18 20:42:21;
        LastAccessTimeUtc = 2016-08-18 18:42:21;
        LastWriteTime = 2016-08-18 20:42:21;
        LastWriteTimeUtc = 2016-08-18 18:42:21;
        Name = "Temp";
        Parent = Local;
        Root = C:\;}
>


USE: io.directories
"path/to/dir" make-directories


#ifdef __FB_WIN32__
    Dim pathname As String = "Ring\docs"
#else
    Dim pathname As String = "Ring/docs"
#endif

Dim As String mkpathname = "mkdir " & pathname
Dim result As Long = Shell (mkpathname)

If result = 0 Then
    Print "Created the directory..."
    Chdir(pathname)
    Print Curdir
Else
    Print "error: unable to create folder " & pathname & " in the current path."
End If
Sleep


getMapped: function [a,b,i][
    round .to:1 b\0 + ((i - a\0) * (b\1 - b\0))/(a\1 - a\0)
]

rangeA: @[0.0 10.0]
rangeB: @[0-1.0 0.0]

loop 0..10 'x [
    mapped: getMapped rangeA rangeB to :floating x
    print [x "maps to" mapped]
]


mapRange(a1, a2, b1, b2, s)
{
	return b1 + (s-a1)*(b2-b1)/(a2-a1)
}

out := "Mapping [0,10] to [-1,0] at intervals of 1:`n"

Loop 11
	out .= "f(" A_Index-1 ") = " mapRange(0,10,-1,0,A_Index-1) "`n"
MsgBox % out


size = 20
n = 2 * size + 1
endpos = n * n - 2
startpos = n + 1
#
f = 100 / (n - 0.5)
len m[] n * n
#
background 000
func show_maze . .
  clear
  for i range len m[]
    if m[i] = 0
      x = i mod n
      y = i div n
      color 777
      move x * f - f / 2 y * f - f / 2
      rect f * 1.5 f * 1.5
    .
  .
  sleep 0.001
.
offs[] = [ 1 n -1 (-n) ]
brdc[] = [ n - 2 -1 1 -1 ]
brdr[] = [ -1 n - 2 -1 1 ]
#
func m_maze pos . .
  m[pos] = 0
  call show_maze
  d[] = [ 0 1 2 3 ]
  for i = 3 downto 0
    d = random (i + 1)
    dir = d[d]
    d[d] = d[i]
    r = pos div n
    c = pos mod n
    posn = pos + 2 * offs[dir]
    if c <> brdc[dir] and r <> brdr[dir] and m[posn] <> 0
      posn = pos + 2 * offs[dir]
      m[(pos + posn) div 2] = 0
      call m_maze posn
    .
  .
.
func make_maze . .
  for i range len m[]
    m[i] = 1
  .
  call m_maze startpos
  m[endpos] = 0
.
call make_maze
call show_maze


program MazeGen

    // First and last columns/rows are "dead" cells. Makes generating
    // a maze with border walls much easier. Therefore, a visible
    // 20x20 maze has a maze size of 22.
    mazeSize int = 22;

    south boolean[][];
    west boolean[][];
    visited boolean[][];

    function main()
        initMaze();
        generateMaze();
        drawMaze();
    end

    private function initMaze()

        visited = createBooleanArray(mazeSize, mazeSize, false);

        // Initialize border cells as already visited
        for(col int from 1 to mazeSize)
            visited[col][1] = true;
            visited[col][mazeSize] = true;
        end
        for(row int from 1 to mazeSize)
            visited[1][row] = true;
            visited[mazeSize][row] = true;
        end

        // Initialize all walls as present
        south = createBooleanArray(mazeSize, mazeSize, true);
        west = createBooleanArray(mazeSize, mazeSize, true);

    end

    private function createBooleanArray(col int in, row int in, initialState boolean in) returns(boolean[][])

        newArray boolean[][] = new boolean[0][0];

        for(i int from 1 to col)
            innerArray boolean[] = new boolean[0];
            for(j int from 1 to row)
                innerArray.appendElement(initialState);
            end
            newArray.appendElement(innerArray);
        end

        return(newArray);

    end

    private function createIntegerArray(col int in, row int in, initialValue int in) returns(int[][])

        newArray int[][] = new int[0][0];

        for(i int from 1 to col)
            innerArray int[] = new int[0];
            for(j int from 1 to row)
                innerArray.appendElement(initialValue);
            end
            newArray.appendElement(innerArray);
        end

        return(newArray);

    end

    private function generate(col int in, row int in)

        // Mark cell as visited
        visited[col][row] = true;

        // Keep going as long as there is an unvisited neighbor
        while(!visited[col][row + 1] || !visited[col + 1][row] ||
                !visited[col][row - 1] || !visited[col - 1][row])

            while(true)
                r float = MathLib.random(); // Choose a random direction

                case
                    when(r < 0.25 && !visited[col][row + 1]) // Go south
                        south[col][row] = false; // South wall down
                        generate(col, row + 1);
                        exit while;
                    when(r >= 0.25 && r < 0.50 && !visited[col + 1][row]) // Go east
                        west[col + 1][row] = false; // West wall of neighbor to the east down
                        generate(col + 1, row);
                        exit while;
                    when(r >= 0.5 && r < 0.75 && !visited[col][row - 1]) // Go north
                        south[col][row - 1] = false; // South wall of neighbor to the north down
                        generate(col, row - 1);
                        exit while;
                    when(r >= 0.75 && r < 1.00 && !visited[col - 1][row]) // Go west
                        west[col][row] = false; // West wall down
                        generate(col - 1, row);
                        exit while;
                end
            end
        end

    end

    private function generateMaze()

        // Pick random start position (within the visible maze space)
        randomStartCol int = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2);
        randomStartRow int = MathLib.floor((MathLib.random() *(mazeSize - 2)) + 2);

        generate(randomStartCol, randomStartRow);

    end

    private function drawMaze()

        line string;

        // Iterate over wall arrays (skipping dead border cells as required).
        // Construct a line at a time and output to console.
        for(row int from 1 to mazeSize - 1)

            if(row > 1)
                line = "";
                for(col int from 2 to mazeSize)
                    if(west[col][row])
                        line ::= "|   ";
                    else
                        line ::= "    ";
                    end
                end
                Syslib.writeStdout(line);
            end

            line = "";
            for(col int from 2 to mazeSize - 1)
                if(south[col][row])
                    line ::= "+---";
                else
                    line ::= "+   ";
                end
            end
            line ::= "+";
            SysLib.writeStdout(line);

        end

    end

end


package main

import (
    gc "github.com/rthornton128/goncurses"
    "log"
    "math/rand"
    "time"
)

// Time between row updates in microseconds.
// Controls the speed of the digital rain effect.
const rowDelay = 40000

func main() {
    start := time.Now()
    rand.Seed(time.Now().UnixNano())

    // Characters to randomly appear in the rain sequence.
    chars := []byte("0123456789")
    totalChars := len(chars)

    // Set up ncurses screen and colors.
    stdscr, err := gc.Init()
    if err != nil {
        log.Fatal("init", err)
    }
    defer gc.End()

    gc.Echo(false)
    gc.Cursor(0)

    if !gc.HasColors() {
        log.Fatal("Program requires a colour capable terminal")
    }

    if err := gc.StartColor(); err != nil {
        log.Fatal(err)
    }

    if err := gc.InitPair(1, gc.C_GREEN, gc.C_BLACK); err != nil {
        log.Fatal("InitPair failed: ", err)
    }
    stdscr.ColorOn(1)
    maxY, maxX := stdscr.MaxYX()

    /* Create slices of columns based on screen width. */

    // Slice containing the current row of each column.
    columnsRow := make([]int, maxX)

    // Slice containing the active status of each column.
    // A column draws characters on a row when active.
    columnsActive := make([]int, maxX)

    // Set top row as current row for all columns.
    for i := 0; i < maxX; i++ {
        columnsRow[i] = -1
        columnsActive[i] = 0
    }

    for {
        for i := 0; i < maxX; i++ {
            if columnsRow[i] == -1 {
                // If a column is at the top row, pick a
                // random starting row and active status.
                columnsRow[i] = rand.Intn(maxY + 1)
                columnsActive[i] = rand.Intn(2)
            }
        }

        // Loop through columns and draw characters on rows.
        for i := 0; i < maxX; i++ {
            if columnsActive[i] == 1 {
                // Draw a random character at this column's current row.
                charIndex := rand.Intn(totalChars)
                stdscr.MovePrintf(columnsRow[i], i, "%c", chars[charIndex])
            } else {
                // Draw an empty character if the column is inactive.
                stdscr.MovePrintf(columnsRow[i], i, "%c", ' ')
            }

            columnsRow[i]++

            // When a column reaches the bottom row, reset to top.
            if columnsRow[i] >= maxY {
                columnsRow[i] = -1
            }

            // Randomly alternate the column's active status.
            if rand.Intn(1001) == 0 {
                if columnsActive[i] == 0 {
                    columnsActive[i] = 1
                } else {
                    columnsActive[i] = 0
                }
            }
        }
        time.Sleep(rowDelay * time.Microsecond)
        stdscr.Refresh()
        elapsed := time.Since(start)
        // Stop after 1 minute.
        if elapsed.Minutes() >= 1 {
            break
        }
    }
}


Public Sub Form_Open()

If Not Exist(User.home &/ "TestFolder") Then Mkdir User.Home &/ "TestFolder"

End


import System.Directory (createDirectory, setCurrentDirectory)
import Data.List.Split  (splitOn)

main :: IO ()
main = do
  let path = splitOn "/" "path/to/dir"
  mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path


require 'general/dirutils'
pathcreate '/tmp/some/path/to/dir'


import java.io.File;

public interface Test {

    public static void main(String[] args) {
        try {
            File f = new File("C:/parent/test");
            if (f.mkdirs())
                System.out.println("path successfully created");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


var path = require('path');
var fs = require('fs');

function mkdirp (p, cb) {
    cb = cb || function () {};
    p = path.resolve(p);

    fs.mkdir(p, function (er) {
        if (!er) {
            return cb(null);
        }
        switch (er.code) {
            case 'ENOENT':
                // The directory doesn't exist. Make its parent and try again.
                mkdirp(path.dirname(p), function (er) {
                    if (er) cb(er);
                    else mkdirp(p, cb);
                });
                break;

                // In the case of any other error, something is borked.
            default:
                cb(er);
                break;
        }
    });
}


# syntax: GAWK -f MAP_RANGE.AWK
BEGIN {
    a1 = 0
    a2 = 10
    b1 = -1
    b2 = 0
    for (i=a1; i<=a2; i++) {
      printf("%g maps to %g\n",i,map_range(a1,a2,b1,b2,i))
    }
    exit(0)
}
function map_range(a1,a2,b1,b2,num) {
    return b1 + ((num-a1) * (b2-b1) / (a2-a1))
}


)abbrev package TESTP TestPackage
TestPackage(R:Field) : with
    mapRange: (Segment(R), Segment(R)) -> (R->R)
  == add
    mapRange(fromRange, toRange) ==
      (a1,a2,b1,b2) := (lo fromRange,hi fromRange,lo toRange,hi toRange)
      (x:R):R +-> b1+(x-a1)*(b2-b1)/(a2-a1)


function MapRange(s, a1, a2, b1, b2)
	return b1+(s-a1)*(b2-b1)/(a2-a1)
end function

for i = 0 to 10
	print i; " maps to "; MapRange(i,0,10,-1,0)
next i
end


defmodule Maze do
  def generate(w, h) do
    maze = (for i <- 1..w, j <- 1..h, into: Map.new, do: {{:vis, i, j}, true})
           |> walk(:rand.uniform(w), :rand.uniform(h))
    print(maze, w, h)
    maze
  end

  defp walk(map, x, y) do
    Enum.shuffle( [[x-1,y], [x,y+1], [x+1,y], [x,y-1]] )
    |> Enum.reduce(Map.put(map, {:vis, x, y}, false), fn [i,j],acc ->
      if acc[{:vis, i, j}] do
        {k, v} = if i == x, do: {{:hor, x, max(y, j)}, "+   "},
                          else: {{:ver, max(x, i), y}, "    "}
        walk(Map.put(acc, k, v), i, j)
      else
        acc
      end
    end)
  end

  defp print(map, w, h) do
    Enum.each(1..h, fn j ->
      IO.puts Enum.map_join(1..w, fn i -> Map.get(map, {:hor, i, j}, "+---") end) <> "+"
      IO.puts Enum.map_join(1..w, fn i -> Map.get(map, {:ver, i, j}, "|   ") end) <> "|"
    end)
    IO.puts String.duplicate("+---", w) <> "+"
  end
end

Maze.generate(20, 10)


require'ide/qt/gl2'
coinsert'jgl2'

junk=: 7 u:;48 65 16b30a1(+i.)&.>10 26 90
sz=:40 25
len=: <.1.4*{:sz
heat=: (224 255 255),~(<.0.5+255*(%>./)(-<./)^>:(% >./)i.len)*/0 1 0

cols=: i.0
rows=: i.0
scale=: 24
live=: (#heat)#<i.3 0

update=: {{
  try. glfill 0 0 0 255 catch. wd'timer 0' return. end.
  glfont font=.'courier ',":0.8*scale
  upd=. 0>._3++/?2 2 2 2 4
  cols=: cols,upd{.(?~{.sz)-.(-<.0.3*{:sz){.cols
  rows=: (#cols){.rows
  live=: }.live,<(scale*cols,.rows),.?(#cols)##junk
  for_p. live do.
    gltextcolor glrgb p_index{heat
    if.p_index=<:#live do.
      glfont font,' bold'
    end.
    for_xyj.;p do.
      gltextxy 2{.xyj
      gltext 8 u:junk{~{:xyj
    end.
  end. glpaint''
  keep=: rows<{:sz-1
  cols=: keep#cols
  rows=: keep#rows+1
  EMPTY
}}
sys_timer_z_=: update_base_

wd rplc&('DIMS';":scale*sz) {{)n
  pc rain closeok;
  setp wh DIMS;
  cc green isidraw flush;
  pshow;
  timer 100
}}


var tileSize = 20;
// a higher fade factor will make the characters fade quicker
var fadeFactor = 0.05;

var canvas;
var ctx;

var columns = [];
var maxStackHeight;

function init() {
	canvas = document.getElementById('canvas');
	ctx = canvas.getContext('2d');

    // https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
    const resizeObserver = new ResizeObserver(entries =>
    {
        for (let entry of entries)
        {
            if (entry.contentBoxSize)
            {
                // Firefox implements `contentBoxSize` as a single content rect, rather than an array
                const contentBoxSize = Array.isArray(entry.contentBoxSize) ? entry.contentBoxSize[0] : entry.contentBoxSize;

                canvas.width = contentBoxSize.inlineSize;
                canvas.height = window.innerHeight;

                initMatrix();
            }
        }
    });

    // observe the size of the document
    resizeObserver.observe(document.documentElement);

	// start the main loop
	tick();
}

function initMatrix() {
    columns = [];

    maxStackHeight = Math.ceil(canvas.height/tileSize);

    // divide the canvas into columns
    for (let i = 0 ; i < canvas.width/tileSize ; ++i) {
        var column = {};
        // save the x position of the column
        column.x = i*tileSize;
        // create a random stack height for the column
        column.stackHeight = 10+Math.random()*maxStackHeight;
        // add a counter to count the stack height
        column.stackCounter = 0;
        // add the column to the list
        columns.push(column);
    }
}

function draw() {
    // draw a semi transparent black rectangle on top of the scene to slowly fade older characters
    ctx.fillStyle = "rgba(0 , 0 , 0 , "+fadeFactor+")";
    ctx.fillRect(0 , 0 , canvas.width , canvas.height);

    ctx.font = (tileSize-2)+"px monospace";
    ctx.fillStyle = "rgb(0 , 255 , 0)";
    for (let i = 0 ; i < columns.length ; ++i) {
        // pick a random ascii character (change the 94 to a higher number to include more characters)
        var randomCharacter = String.fromCharCode(33+Math.floor(Math.random()*94));
        ctx.fillText(randomCharacter , columns[i].x , columns[i].stackCounter*tileSize+tileSize);

        // if the stack is at its height limit, pick a new random height and reset the counter
        if (++columns[i].stackCounter >= columns[i].stackHeight)
        {
            columns[i].stackHeight = 10+Math.random()*maxStackHeight;
            columns[i].stackCounter = 0;
        }
    }
}

// MAIN LOOP
function tick() {
    draw();
    setTimeout(tick , 50);
}

var b_isFullscreen = false;

function fullscreen() {
    var elem = document.documentElement;
    if (elem.requestFullscreen) {
        elem.requestFullscreen();
    }
    else if (elem.webkitRequestFullscreen) {
        elem.webkitRequestFullscreen(); // Safari
    }
    else if (elem.msRequestFullscreen) {
        elem.msRequestFullscreen(); // IE11
    }
}

function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    }
    else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen(); // Safari
    }
    else if (document.msExitFullscreen) {
        document.msExitFullscreen(); // IE11
    }
}

function toggleFullscreen() {
    if (!b_isFullscreen) {
        fullscreen();
        b_isFullscreen = true;
    }
    else {
        exitFullscreen();
        b_isFullscreen = false;
    }
}

function updateTileSize() {
    tileSize = Math.min(Math.max(document.getElementById("tileSize").value , 10) , 100);
    initMatrix();
}

function updateFadeFactor() {
    fadeFactor = Math.min(Math.max(document.getElementById("fadeFactor").value , 0.0) , 1.0);
    initMatrix();
}


// version 1.0.6

import java.io.File

fun main(args: Array<String>) {
    // using built-in mkdirs() method
    val success = File("./path/to/dir").mkdirs()
    if (success) println("Directory path was created successfully")
    else         println("Failed to create directory path")
}


require("lfs")

function mkdir (path)
  local sep, pStr = package.config:sub(1, 1), ""
  for dir in path:gmatch("[^" .. sep .. "]+") do
    pStr = pStr .. dir .. sep
    lfs.mkdir(pStr)
  end
end

mkdir("C:\\path\\to\\dir") -- Quoting backslashes requires escape sequence


(define (mkdir-p mypath)
    (if (= "/" (mypath 0)) ;; Abs or relative path?
        (setf /? "/")
        (setf /? "")
    )
    (setf path-components (clean empty? (parse mypath "/"))) ;; Split path and remove empty elements
    (for (x 0 (length path-components))
        (setf walking-path (string /? (join (slice path-components 0 (+ 1 x)) "/")))
        (make-dir walking-path)
    )
)

;; Using user-made function...
(mkdir-p "/tmp/rosetta/test1")

;; ... or calling OS command directly.
(! "mkdir -p /tmp/rosetta/test2")
(exit)


/* map s from [a, b] to [c, d] */
define m(a, b, c, d, s) {
	return (c + (s - a) * (d - c) / (b - a))
}

scale = 6  /* division to 6 decimal places */
"[0, 10] => [-1, 0]
"
for (i = 0; i <= 10; i += 2) {
	/*
         * If your bc(1) has a print statement, you can try
	 * print i, " => ", m(0, 10, -1, 0, i), "\n"
	 */
	i; "   => "; m(0, 10, -1, 0, i)
}
quit


_map_ ← {
 a1‿a2 _𝕣_ b1‿b2 s:
 b1 + ((s - a1) × b2 - b1) ÷ a2 - a1
}

ZeroTen ← 0‿10 _map_ ¯1‿0

•Show ZeroTen 0.1
•Show ZeroTen 8


import Maybe as M
import Result as R
import Matrix
import Mouse
import Random exposing (Seed)
import Matrix.Random
import Time exposing (Time, every, second)
import Set exposing (Set, fromList)
import List exposing (..)
import String exposing (join)
import Html exposing (Html, br, input, h1, h2, text, div, button)
import Html.Events as HE
import Html.Attributes as HA
import Html.App exposing (program)
import Json.Decode  as JD
import Svg
import Svg.Attributes exposing (version, viewBox, cx, cy, r, x, y, x1, y1, x2, y2, fill,points, style, width, height, preserveAspectRatio)

minSide = 10
maxSide = 40
w = 700
h = 700
dt = 0.001

type alias Direction = Int
down = 0
right = 1

type alias Door = (Matrix.Location, Direction)

type State = Initial | Generating | Generated | Solved

type alias Model =
  { rows : Int
  , cols : Int
  , animate : Bool
  , boxes : Matrix.Matrix Bool
  , doors : Set Door
  , current : List Matrix.Location
  , state : State
  , seedStarter : Int
  , seed : Seed
  }

initdoors : Int -> Int -> Set Door
initdoors rows cols =
  let
    pairs la lb = List.concatMap (\at -> List.map ((,) at) lb) la
    downs = pairs (pairs [0..rows-2] [0..cols-1]) [down]
    rights = pairs (pairs [0..rows-1] [0..cols-2]) [right]
  in downs ++ rights |> fromList

initModel : Int -> Int -> Bool -> State -> Int -> Model
initModel rows cols animate state starter =
  let rowGenerator = Random.int 0 (rows-1)
      colGenerator = Random.int 0 (cols-1)
      locationGenerator = Random.pair rowGenerator colGenerator
      (c, s)= Random.step locationGenerator (Random.initialSeed starter)
  in { rows = rows
     , cols = cols
     , animate = animate
     , boxes = Matrix.matrix rows cols (\location -> state == Generating && location == c)
     , doors = initdoors rows cols
     , current = if state == Generating then [c] else []
     , state = state
     , seedStarter = starter -- updated every Tick until maze generated.
     , seed = s
     }

view model =
  let
    borderLineStyle = style "stroke:green;stroke-width:0.3"
    wallLineStyle = style "stroke:green;stroke-width:0.1"

    x1Min = x1 <| toString 0
    y1Min = y1 <| toString 0
    x1Max = x1 <| toString model.cols
    y1Max = y1 <| toString model.rows
    x2Min = x2 <| toString 0
    y2Min = y2 <| toString 0
    x2Max = x2 <| toString model.cols
    y2Max = y2 <| toString model.rows

    borders = [ Svg.line [ x1Min, y1Min, x2Max, y2Min, borderLineStyle ] []
              , Svg.line [ x1Max, y1Min, x2Max, y2Max, borderLineStyle ] []
              , Svg.line [ x1Max, y1Max, x2Min, y2Max, borderLineStyle ] []
              , Svg.line [ x1Min, y1Max, x2Min, y2Min, borderLineStyle ] []
              ]

    doorToLine door =
      let (deltaX1, deltaY1) = if (snd door == right) then (1,0) else (0,1)
          (row, column) = fst door
      in Svg.line [ x1 <| toString (column + deltaX1)
                  , y1 <| toString (row    + deltaY1)
                  , x2 <| toString (column + 1)
                  , y2 <| toString (row    + 1)
                  , wallLineStyle ] []

    doors = (List.map doorToLine <| Set.toList model.doors )

    circleInBox (row,col) color =
      Svg.circle [ r "0.25"
      , fill (color)
      , cx (toString (toFloat col + 0.5))
      , cy (toString (toFloat row + 0.5))
      ] []

    showUnvisited location box =
       if box then [] else [ circleInBox location "yellow" ]

    unvisited = model.boxes
                  |> Matrix.mapWithLocation showUnvisited
                  |> Matrix.flatten
                  |> concat

    current =
      case head model.current of
          Nothing -> []
          Just c -> [circleInBox c "black"]

    maze =
      if model.animate || model.state /= Generating
      then [ Svg.g [] <| doors ++ borders ++ unvisited ++ current ]
      else [ Svg.g [] <| borders ]
  in
    div
      []
      [ h2 [centerTitle] [text "Maze Generator"]
      , div
          [floatLeft]
          (  slider "rows" minSide maxSide model.rows SetRows
          ++ [ br [] [] ]

          ++ slider "cols" minSide maxSide model.cols SetCols
          ++ [ br [] [] ]

          ++ checkbox "Animate" model.animate SetAnimate
          ++ [ br [] [] ]

          ++ [ button
                 [ HE.onClick Generate ]
                 [ text "Generate"]
             ] )
      , div
          [floatLeft]
          [ Svg.svg
              [ version "1.1"
              , width (toString w)
              , height (toString h)
              , viewBox (join " "
                           [ 0          |> toString
                           , 0          |> toString
                           , model.cols |> toString
                           , model.rows |> toString ])
              ]
              maze
          ]
      ]

checkbox label checked msg =
  [ input
      [ HA.type' "checkbox"
      , HA.checked checked
      , HE.on "change" (JD.map msg HE.targetChecked)
      ]
      []
    , text label
  ]

slider name min max current msg =
  [ input
    [ HA.value (if current >= min then current |> toString else "")
    , HE.on "input" (JD.map msg HE.targetValue )
    , HA.type' "range"
    , HA.min <| toString min
    , HA.max <| toString max
    ]
    []
  , text <| name ++ "=" ++ (current |> toString)
  ]

floatLeft = HA.style [ ("float", "left") ]
centerTitle = HA.style [ ( "text-align", "center") ]

unvisitedNeighbors : Model -> Matrix.Location -> List Matrix.Location
unvisitedNeighbors model (row,col) =
  [(row, col-1), (row-1, col), (row, col+1), (row+1, col)]
    |> List.filter (\l -> fst l >= 0 && snd l >= 0 && fst l < model.rows && snd l < model.cols)
    |> List.filter (\l -> (Matrix.get l model.boxes) |> M.withDefault False |> not)

updateModel' : Model -> Int -> Model
updateModel' model t =
  case head model.current of
    Nothing -> {model | state = Generated, seedStarter = t }
    Just prev ->
      let neighbors = unvisitedNeighbors model prev
      in if (length neighbors) > 0 then
           let (neighborIndex, seed) = Random.step (Random.int 0 (length neighbors-1)) model.seed
               next = head (drop neighborIndex neighbors) |> M.withDefault (0,0)
               boxes = Matrix.set next True model.boxes
               dir = if fst prev == fst next then right else down
               doorCell = if (  (dir == down)   && (fst prev < fst next))
                             || (dir == right ) && (snd prev < snd next) then prev else next
               doors = Set.remove (doorCell, dir) model.doors
           in {model | boxes=boxes, doors=doors, current=next :: model.current, seed=seed, seedStarter = t}
         else
           let tailCurrent = tail model.current |> M.withDefault []
           in updateModel' {model | current = tailCurrent} t

updateModel : Msg -> Model -> Model
updateModel msg model =
  let stringToCellCount s =
    let v' = String.toInt s |> R.withDefault minSide
    in if v' < minSide then minSide else v'
  in case msg of
       Tick tf ->
         let t = truncate tf
         in
           if (model.state == Generating) then updateModel' model t
           else { model | seedStarter = t }

       Generate ->
         initModel model.rows model.cols model.animate Generating model.seedStarter

       SetRows countString ->
         initModel (stringToCellCount countString) model.cols model.animate Initial model.seedStarter

       SetCols countString ->
         initModel model.rows (stringToCellCount countString) model.animate Initial model.seedStarter

       SetAnimate b ->
         { model | animate = b }

       NoOp -> model

type Msg = NoOp | Tick Time | Generate | SetRows String | SetCols String | SetAnimate Bool

subscriptions model = every (dt * second) Tick

main =
  let
    update msg model = (updateModel msg model, Cmd.none)
    init = (initModel 21 36 False Initial 0, Cmd.none)
  in program
       { init = init
       , view = view
       , update = update
       , subscriptions = subscriptions
       }


using Gtk, Colors, Cairo
import Base.iterate, Base.IteratorSize, Base.IteratorEltype

const caps = [c for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
startfall() = rand() < 0.2
endfall() = rand() < 0.2
startblank() = rand() < 0.1
endblank() = rand() < 0.05
bechangingchar() = rand() < 0.03

struct RainChars chars::Vector{Char} end
Base.IteratorSize(s::RainChars) = Base.IsInfinite()
Base.IteratorEltype(s::RainChars) = Char
function Base.iterate(rain::RainChars, state = (true, false, 0))
    c = '\0'
    isfalling, isblank, blankcount = state
    if isfalling # falling, so feed the column
        if isblank
            c = ' '
            ((blankcount += 1) > 12) && (isblank = endblank())
        else
            c = bechangingchar() ? '~' : rand(rain.chars)
            isblank, blankcount = startblank(), 0
        end
        endfall() && (isfalling = false)
    else
        isfalling = startfall()
    end
    return c, (isfalling, isblank, blankcount)
end

function digitalrain()
    mapwidth, mapheight, fontpointsize = 800, 450, 14
    windowmaxx = div(mapwidth, Int(round(fontpointsize * 0.9)))
    windowmaxy = div(mapheight, fontpointsize)
    basebuffer = fill(' ', windowmaxy, windowmaxx)
    bkcolor, rcolor, xcolor = colorant"black", colorant"green", colorant"limegreen"

    columngenerators = [Iterators.Stateful(RainChars(caps)) for _ in 1:windowmaxx]

    win = GtkWindow("Digital Rain Effect", mapwidth, mapheight) |>
        (GtkFrame() |> (can = GtkCanvas()))
    set_gtk_property!(can, :expand, true)

    draw(can) do widget
        ctx = Gtk.getgc(can)
        select_font_face(ctx, "Leonardo\'s mirrorwriting", Cairo.FONT_SLANT_NORMAL,
            Cairo.FONT_WEIGHT_BOLD)
        set_font_size(ctx, fontpointsize)
        set_source(ctx, bkcolor)
        rectangle(ctx, 0, 0, mapwidth, mapheight)
        fill(ctx)
        set_source(ctx, rcolor)
        for i in 1:size(basebuffer)[1], j in 1:size(basebuffer)[2]
            move_to(ctx, j * fontpointsize * 0.9, i * fontpointsize)
            c = basebuffer[i, j]
            if c == '~'
				set_source(ctx, xcolor)
                show_text(ctx, String([rand(caps)]))
				set_source(ctx, rcolor)
            else
                show_text(ctx, String([c]))
            end
        end
    end

    while true
        for col in 1:windowmaxx
            c = popfirst!(columngenerators[col])
            if c != '\0'
                basebuffer[2:end, col] .= basebuffer[1:end-1, col]
                basebuffer[1, col] = c
            end
        end
        draw(can)
        Gtk.showall(win)
        sleep(0.05)
    end
end

digitalrain()


10 mode 0:defint a-z:randomize time:ink 0,0:ink 1,26:ink 2,19:border 0
20 dim p(20):mm=5:dim act(mm):for i=1 to mm:act(i)=rnd*19+1:next
30 md=mm-2:dim del(md):for i=1 to md:del(i)=rnd*19+1:next
40 for i=1 to mm:x=act(i):locate x,p(x)+1:pen 1:print chr$(rnd*55+145);
50 if p(x)>0 then locate x,p(x):pen 2:print chr$(rnd*55+145);
60 p(x)=p(x)+1:if p(x)=25 then locate x,25:pen 2:print chr$(rnd*55+145);:p(x)=0:act(i)=rnd*19+1
70 next
80 for i=1 to md:x=del(i):locate x,p(x)+1:print " ";
90 p(x)=p(x)+1:if p(x)=25 then p(x)=0:del(i)=rnd*19+1
100 next
110 goto 40


import os

try:
  createDir("./path/to/dir")
  echo "Directory now exists."
except OSError:
  echo "Failed to create the directory."


class Program {
  function : Main(args : String[]) ~ Nil {
    System.IO.File.Directory->CreatePath("your/path/name")->PrintLine();
  }
}


#load "unix.cma"

let mkdir_p ~path ~perms =
  let ps = String.split_on_char '/' path in
  let rec aux acc = function [] -> ()
  | p::ps ->
      let this = String.concat Filename.dir_sep (List.rev (p::acc)) in
      Unix.mkdir this perms;
      aux (p::acc) ps
  in
  aux [] ps

let () =
  mkdir_p "path/to/dir" 0o700


use File::Path qw(make_path);

make_path('path/to/dir')


without js -- (file i/o)
if not create_directory("myapp/interface/letters") then
    crash("Filesystem problem - could not create the new folder")
end if


#include <stdio.h>

#define mapRange(a1,a2,b1,b2,s) (b1 + (s-a1)*(b2-b1)/(a2-a1))

int main()
{
	int i;
	puts("Mapping [0,10] to [-1,0] at intervals of 1:");

	for(i=0;i<=10;i++)
	{
		printf("f(%d) = %g\n",i,mapRange(0,10,-1,0,i));
	}

	return 0;
}


using System;
using System.Linq;

public class MapRange
{
    public static void Main() {
        foreach (int i in Enumerable.Range(0, 11))
            Console.WriteLine($"{i} maps to {Map(0, 10, -1, 0, i)}");
    }

    static double Map(double a1, double a2, double b1, double b2, double s) => b1 + (s - a1) * (b2 - b1) / (a2 - a1);
}


(require 'cl-lib)

(cl-defstruct maze rows cols data)

(defmacro maze-pt (w r c)
  `(+ (* (mod ,r (maze-rows ,w)) (maze-cols ,w))
      (mod ,c (maze-cols ,w))))

(defmacro maze-ref (w r c)
  `(aref (maze-data ,w) (maze-pt ,w ,r ,c)))

(defun new-maze (rows cols)
  (setq rows (1+ rows)
        cols (1+ cols))
  (let ((m (make-maze :rows rows :cols cols :data (make-vector (* rows cols) nil))))

    (dotimes (r rows)
      (dotimes (c cols)
        (setf (maze-ref m r c) (copy-sequence '(wall ceiling)))))

    (dotimes (r rows)
      (maze-set m r (1- cols) 'visited))

    (dotimes (c cols)
      (maze-set m (1- rows) c 'visited))

    (maze-unset m 0 0 'ceiling) ;; Maze Entrance
    (maze-unset m (1- rows) (- cols 2) 'ceiling) ;; Maze Exit

    m))

(defun maze-is-set (maze r c v)
  (member v (maze-ref maze r c)))

(defun maze-set (maze r c v)
  (let ((cell (maze-ref maze r c)))
    (when (not (member v cell))
      (setf (maze-ref maze r c) (cons v cell)))))

(defun maze-unset (maze r c v)
  (setf (maze-ref maze r c) (delete v (maze-ref maze r c))))

(defun print-maze (maze &optional marks)
  (dotimes (r (1- (maze-rows maze)))

    (dotimes (c (1- (maze-cols maze)))
      (princ (if (maze-is-set maze r c 'ceiling) "+---" "+   ")))
    (princ "+")
    (terpri)

    (dotimes (c (1- (maze-cols maze)))
      (princ (if (maze-is-set maze r c 'wall) "|" " "))
      (princ (if (member (cons r c) marks) " * " "   ")))
    (princ "|")
    (terpri))

  (dotimes (c (1- (maze-cols maze)))
    (princ (if (maze-is-set maze (1- (maze-rows maze)) c 'ceiling) "+---" "+   ")))
  (princ "+")
  (terpri))

(defun shuffle (lst)
  (sort lst (lambda (a b) (= 1 (random 2)))))

(defun to-visit (maze row col)
  (let (unvisited)
    (dolist (p '((0 . +1) (0 . -1) (+1 . 0) (-1 . 0)))
      (let ((r (+ row (car p)))
            (c (+ col (cdr p))))
      (unless (maze-is-set maze r c 'visited)
        (push (cons r c) unvisited))))
    unvisited))

(defun make-passage (maze r1 c1 r2 c2)
  (if (= r1 r2)
      (if (< c1 c2)
          (maze-unset maze r2 c2 'wall) ; right
        (maze-unset maze r1 c1 'wall))  ; left
    (if (< r1 r2)
        (maze-unset maze r2 c2 'ceiling)   ; up
      (maze-unset maze r1 c1 'ceiling))))  ; down

(defun dig-maze (maze row col)
  (let (backup
        (run 0))
    (maze-set maze row col 'visited)
    (push (cons row col) backup)
    (while backup
      (setq run (1+ run))
      (when (> run (/ (+ row col) 3))
        (setq run 0)
        (setq backup (shuffle backup)))
      (setq row (caar backup)
            col (cdar backup))
      (let ((p (shuffle (to-visit maze row col))))
        (if p
            (let ((r (caar p))
                  (c (cdar p)))
              (make-passage maze row col r c)
              (maze-set maze r c 'visited)
              (push (cons r c) backup))
          (pop backup)
          (setq backup (shuffle backup))
          (setq run 0))))))

(defun generate (rows cols)
  (let* ((m (new-maze rows cols)))
    (dig-maze m (random rows) (random cols))
    (print-maze m)))

(defun parse-ceilings (line)
  (let (rtn
        (i 1))
    (while (< i (length line))
      (push (eq ?- (elt line i)) rtn)
      (setq i (+ i 4)))
    (nreverse rtn)))

(defun parse-walls (line)
  (let (rtn
        (i 0))
    (while (< i (length line))
      (push (eq ?| (elt line i)) rtn)
      (setq i (+ i 4)))
    (nreverse rtn)))

(defun parse-maze (file-name)
  (let ((rtn)
        (lines (with-temp-buffer
                 (insert-file-contents-literally file-name)
                 (split-string (buffer-string) "\n" t))))
    (while lines
      (push (parse-ceilings (pop lines)) rtn)
      (push (parse-walls (pop lines)) rtn))
    (nreverse rtn)))

(defun read-maze (file-name)
  (let* ((raw (parse-maze file-name))
         (rows (1- (/ (length raw) 2)))
         (cols (length (car raw)))
         (maze (new-maze rows cols)))
    (dotimes (r rows)
      (let ((ceilings (pop raw)))
        (dotimes (c cols)
          (unless (pop ceilings)
            (maze-unset maze r c 'ceiling))))
      (let ((walls (pop raw)))
        (dotimes (c cols)
          (unless (pop walls)
            (maze-unset maze r c 'wall)))))
    maze))

(defun find-exits (maze row col)
  (let (exits)
    (dolist (p '((0 . +1) (0 . -1) (-1 . 0) (+1 . 0)))
      (let ((r (+ row (car p)))
            (c (+ col (cdr p))))
        (unless
            (cond
             ((equal p '(0 . +1)) (maze-is-set maze r   c   'wall))
             ((equal p '(0 . -1)) (maze-is-set maze row col 'wall))
             ((equal p '(+1 . 0)) (maze-is-set maze r   c   'ceiling))
             ((equal p '(-1 . 0)) (maze-is-set maze row col 'ceiling)))
          (push (cons r c) exits))))
    exits))

(defun drop-visited (maze points)
  (let (not-visited)
    (while points
      (unless (maze-is-set maze (caar points) (cdar points) 'visited)
        (push (car points) not-visited))
      (pop points))
    not-visited))

(defun solve-maze (maze)
  (let (solution
        (exit (cons (- (maze-rows maze) 2) (- (maze-cols maze) 2)))
        (pt (cons 0 0)))
    (while (not (equal pt exit))
      (maze-set maze (car pt) (cdr pt) 'visited)
      (let ((exits (drop-visited maze (find-exits maze (car pt) (cdr pt)))))
        (if (null exits)
            (setq pt (pop solution))
          (push pt solution)
          (setq pt (pop exits)))))
    (push pt solution)))

(defun solve (file-name)
  (let* ((maze (read-maze file-name))
         (solution (solve-maze maze)))
    (print-maze maze solution)))

(generate 20 20)


SeedRandom[1234];
ClearAll[ColorFunc]
chars = RandomSample[Flatten[CharacterRange @@@ Partition[Characters["\[CapitalAlpha]\[CapitalPi]ЀѵҊԯ\:03e2\:03efｦﾝⲀ⳩\[ForAll]∗℀℺⨀⫿"], 2]]];
charlen = Length[chars];
fadelength = 6;
ColorFunc[fade_] := ColorFunc[fade] = Blend[{Black, Green}, fade/fadelength]
rows = 30;
cols = 50;
n = 10;
trailpos = {RandomInteger[{1, cols}, n], RandomInteger[{1, rows}, n]} // Transpose;
trailchars = RandomInteger[{1, Length[chars]}, n];
charmap = ConstantArray[".", {rows, cols}];
fade = ConstantArray[5, {rows, cols}];
indices = MapIndexed[#2 &, fade, {2}];
Dynamic[Graphics[{txts}, PlotRange -> {{1, cols}, {1, rows}}, PlotRangePadding -> 1, Background -> Black]]
Do[
 trailpos[[All, 2]] += 1;
 fade = Ramp[fade - 1];
 trailchars = Mod[trailchars + 1, charlen, 1];
 Do[
  If[trailpos[[i, 2]] >= rows,
   trailpos[[i, 2]] = 1;
   trailpos[[i, 1]] = RandomInteger[{1, cols}];
   ];
  charmap[[trailpos[[i, 2]], trailpos[[i, 1]]]] =
   chars[[trailchars[[i]]]];
  fade[[trailpos[[i, 2]], trailpos[[i, 1]]]] = fadelength
  ,
  {i, n}
  ];
 txts = MapThread[If[#2 > 0, Text[Style[#1, ColorFunc[#2]], {#1, rows - #2 + 1} & @@ Reverse[#3]], {}] &, {charmap, fade, indices}, 2];
 Pause[0.1]
 ,
 {1000}
]


import os, random, sequtils
import ncurses

const RowDelay = 40   # In milliseconds.

proc exit() {.noconv.} =
  endwin()
  quit QuitSuccess

proc run() =

  const
    Chars = "0123456789"    # Characters to randomly appear in the rain sequence.

  let stdscr = initscr()
  noEcho()
  cursSet(0)
  startColor()
  initPair(1, COLOR_GREEN, COLOR_BLACK)
  attron(COLOR_PAIR(1).cint)

  var width, height: cint
  stdscr.getmaxyx(height, width)
  let maxX = width - 1
  let maxY = height - 1

  # Create arrays of columns based on screen width.

  # Array containing the current row of each column.
  # Set top row as current row for all columns.
  var columnsRow = repeat(cint -1, width)

  # Array containing the active status of each column.
  # A column draws characters on a row when active.
  var columnsActive = newSeq[bool](width)

  setControlCHook(exit)
  while true:

    for i in 0..maxX:
      if columnsRow[i] == -1:
        # If a column is at the top row, pick a random starting row and active status.
        columnsRow[i] = cint(rand(maxY))
        columnsActive[i] = bool(rand(1))

    # Loop through columns and draw characters on rows.
    for i in 0..maxX:
      if columnsActive[i]:
        # Draw a random character at this column's current row.
        let charIndex = rand(Chars.high)
        mvprintw(columnsRow[i], i, "%c", Chars[charIndex])
      else:
        # Draw an empty character if the column is inactive.
        mvprintw(columnsRow[i], i, " ")

      inc columnsRow[i]
      # When a column reaches the bottom row, reset to top.
      if columnsRow[i] > maxY: columnsRow[i] = -1

      # Randomly alternate the column's active status.
      if rand(999) == 0: columnsActive[i] = not columnsActive[i]

    sleep(RowDelay)
    refresh()

run()


New-Item -Path ".\path\to\dir" -ItemType Directory -ErrorAction SilentlyContinue


from errno import EEXIST
from os import mkdir, curdir
from os.path import split, exists

def mkdirp(path, mode=0777):
    head, tail = split(path)
    if not tail:
        head, tail = split(head)
    if head and tail and not exists(head):
        try:
            mkdirp(head, mode)
        except OSError as e:
            # be happy if someone already created the path
            if e.errno != EEXIST:
                raise
        if tail == curdir:  # xxx/newdir/. exists if xxx/newdir exists
            return
    try:
        mkdir(path, mode)
    except OSError as e:
        # be happy if someone already created the path
        if e.errno != EEXIST:
            raise


#lang racket
(define path-str "/tmp/woo/yay")
(define path/..-str "/tmp/woo")

;; clean up from a previous run
(when (directory-exists? path-str)
  (delete-directory path-str)
  (delete-directory path/..-str))
;; delete-directory/files could also be used -- but that requires goggles and rubber
;; gloves to handle safely!

(define (report-path-exists)
  (printf "~s exists (as a directory?):~a~%~s exists (as a directory?):~a~%~%"
          path/..-str (directory-exists? path/..-str)
          path-str (directory-exists? path-str)))

(report-path-exists)

;; Really ... this is the only bit that matters!
(make-directory* path-str)

(report-path-exists)


#include <iostream>
#include <utility>

template<typename tVal>
tVal map_value(std::pair<tVal,tVal> a, std::pair<tVal, tVal> b, tVal inVal)
{
  tVal inValNorm = inVal - a.first;
  tVal aUpperNorm = a.second - a.first;
  tVal normPosition = inValNorm / aUpperNorm;

  tVal bUpperNorm = b.second - b.first;
  tVal bValNorm = normPosition * bUpperNorm;
  tVal outVal = b.first + bValNorm;

  return outVal;
}

int main()
{
  std::pair<float,float> a(0,10), b(-1,0);

  for(float value = 0.0; 10.0 >= value; ++value)
    std::cout << "map_value(" << value << ") = " << map_value(a, b, value) << std::endl;

  return 0;
}


(defn maprange [[a1 a2] [b1 b2] s]
	(+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1))))

> (doseq [s (range 11)]
       (printf "%2s maps to %s\n" s (maprange [0 10] [-1 0] s)))

 0 maps to -1
 1 maps to -9/10
 2 maps to -4/5
 3 maps to -7/10
 4 maps to -3/5
 5 maps to -1/2
 6 maps to -2/5
 7 maps to -3/10
 8 maps to -1/5
 9 maps to -1/10
10 maps to 0


-module( maze ).

-export( [cell_accessible_neighbours/1, cell_content/1, cell_content_set/2, cell_pid/3, cell_position/1, display/1, generation/2, stop/1, task/0] ).

-record( maze, {dict, max_x, max_y, start} ).
-record( state, {content=" ", controller, is_dug=false, max_x, max_y, neighbours=[], position, walls=[north, south, east, west], walk_done} ).

cell_accessible_neighbours( Pid ) -> read( Pid, accessible_neighbours ).

cell_content( Pid ) -> read( Pid, content ).

cell_content_set( Pid, Content ) -> Pid ! {content, Content, erlang:self()}.

cell_pid( X, Y, Maze ) -> dict:fetch( {X, Y}, Maze#maze.dict ).

cell_position( Pid ) -> read( Pid, position ).

display( #maze{dict=Dict, max_x=Max_x, max_y=Max_y} ) ->
	Position_pids = dict:to_list( Dict ),
	display( Max_x, Max_y, reads(Position_pids, content), reads(Position_pids, walls) ).

generation( Max_x, Max_y ) ->
       Controller = erlang:self(),
       Position_pids = cells_create( Controller, Max_x, Max_y ),
       Pids = [Y || {_X, Y} <- Position_pids],
       [X ! {position_pids, Position_pids} || X <- Pids],
       {Position, Pid} = lists:nth( random:uniform(Max_x * Max_y), Position_pids ),
       Pid ! {dig, Controller},
       receive
       {dig_done} -> ok
       end,
       #maze{dict=dict:from_list(Position_pids), max_x=Max_x, max_y=Max_y, start=Position}.

stop( #maze{dict=Dict} ) ->
      Controller = erlang:self(),
      Pids = [Y || {_X, Y} <- dict:to_list(Dict)],
      [X ! {stop, Controller} || X <- Pids],
      ok.

task() ->
       Maze = generation( 16, 8 ),
       io:fwrite( "Starting at ~p~n", [Maze#maze.start] ),
       display( Maze ),
       stop( Maze ).

cells_create( Controller, Max_x, Max_y ) -> [{{X, Y}, cell_create(Controller, Max_x, Max_y, {X, Y})} || X <- lists:seq(1, Max_x), Y<- lists:seq(1, Max_y)].

cell_create( Controller, Max_x, Max_y, {X, Y} ) -> erlang:spawn_link( fun() -> random:seed( X*1000, Y*1000, (X+Y)*1000 ), loop( #state{controller=Controller, max_x=Max_x, max_y=Max_y, position={X, Y}} ) end ).

display( Max_x, Max_y, Position_contents, Position_walls ) ->
        All_rows = [display_row( Max_x, Y, Position_contents, Position_walls ) || Y <- lists:seq(Max_y, 1, -1)],
        [io:fwrite("~s+~n~s|~n", [North, West]) || {North, West} <- All_rows],
	io:fwrite("~s+~n", [lists:flatten(lists:duplicate(Max_x, display_row_north(true)))] ).

display_row( Max_x, Y, Position_contents, Position_walls ) ->
	North_wests = [display_row_walls(proplists:get_value({X,Y}, Position_contents), proplists:get_value({X,Y}, Position_walls)) || X <- lists:seq(1, Max_x)],
	North = lists:append( [North || {North, _West} <- North_wests] ),
	West = lists:append( [West || {_X, West} <- North_wests] ),
	{North, West}.

display_row_walls( Content, Walls ) -> {display_row_north( lists:member(north, Walls) ), display_row_west( lists:member(west, Walls), Content )}.

display_row_north( true ) -> "+---";
display_row_north( false ) -> "+   ".

display_row_west( true, Content ) -> "| " ++ Content ++ " ";
display_row_west( false, Content ) -> "  " ++ Content ++ " ".

loop( State ) ->
    receive
    {accessible_neighbours, Pid} ->
    	Pid ! {accessible_neighbours, loop_accessible_neighbours( State#state.neighbours, State#state.walls ), erlang:self()},
        loop( State );
    {content, Pid} ->
    	Pid ! {content, State#state.content, erlang:self()},
        loop( State );
    {content, Content, _Pid} ->
        loop( State#state{content=Content} );
    {dig, Pid} ->
	    Not_dug_neighbours = loop_not_dug( State#state.neighbours ),
	    New_walls = loop_dig( Not_dug_neighbours, lists:delete( loop_wall_from_pid(Pid, State#state.neighbours), State#state.walls), Pid ),
	    loop( State#state{is_dug=true, walls=New_walls, walk_done=Pid} );
    {dig_done} ->
	    Not_dug_neighbours = loop_not_dug( State#state.neighbours ),
	    New_walls = loop_dig( Not_dug_neighbours, State#state.walls, State#state.walk_done ),
	    loop( State#state{walls=New_walls} );
    {is_dug, Pid} ->
    	    Pid ! {is_dug, State#state.is_dug, erlang:self()},
	    loop( State );
    {position, Pid} ->
    	Pid ! {position, State#state.position, erlang:self()},
        loop( State );
    {position_pids, Position_pids} ->
        {_My_position, Neighbours} = lists:foldl( fun loop_neighbours/2, {State#state.position, []}, Position_pids ),
        erlang:garbage_collect(), % Shrink process after using large Pid_positions. For memory starved systems.
        loop( State#state{neighbours=Neighbours} );
    {stop, Controller} when Controller =:= State#state.controller ->
    	   ok;
    {walls, Pid} ->
    	    Pid ! {walls, State#state.walls, erlang:self()},
	    loop( State )
    end.

loop_accessible_neighbours( Neighbours, Walls ) -> [Pid || {Direction, Pid} <- Neighbours, not lists:member(Direction, Walls)].

loop_dig( [], Walls, Pid ) ->
	Pid ! {dig_done},
	Walls;
loop_dig( Not_dug_neighbours, Walls, _Pid ) ->
        {Dig_pid, Dig_direction} = lists:nth( random:uniform(erlang:length(Not_dug_neighbours)), Not_dug_neighbours ),
        Dig_pid ! {dig, erlang:self()},
	lists:delete( Dig_direction, Walls ).

loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y + 1 -> {{X, My_y}, [{north, Pid} | Acc]};
loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y - 1 -> {{X, My_y}, [{south, Pid} | Acc]};
loop_neighbours( {{X, Y}, Pid}, {{My_x, Y}, Acc} ) when X =:= My_x + 1 -> {{My_x, Y}, [{east, Pid} | Acc]};
loop_neighbours( {{X, Y}, Pid}, {{My_x, Y}, Acc} ) when X =:= My_x - 1 -> {{My_x, Y}, [{west, Pid} | Acc]};
loop_neighbours( _Position_pid, Acc ) -> Acc.

loop_not_dug( Neighbours ) ->
	My_pid = erlang:self(),
	[Pid ! {is_dug, My_pid} || {_Direction, Pid} <- Neighbours],
	[{Pid, Direction} || {Direction, Pid} <- Neighbours, not read_receive(Pid, is_dug)].

loop_wall_from_pid( Pid, Neighbours ) -> loop_wall_from_pid_result( lists:keyfind(Pid, 2, Neighbours) ).
loop_wall_from_pid_result( {Direction, _Pid} ) -> Direction;
loop_wall_from_pid_result( false ) -> controller.

read( Pid, Key ) ->
	Pid ! {Key, erlang:self()},
	read_receive( Pid, Key ).

read_receive( Pid, Key ) ->
        receive
        {Key, Value, Pid} -> Value
        end.

reads( Position_pids, Key ) ->
    My_pid = erlang:self(),
    [Pid ! {Key, My_pid} || {_Position, Pid} <- Position_pids],
    [{Position, read_receive(Pid, Key)} || {Position, Pid} <- Position_pids].