task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. Print "Awake!" End. Related task   Nautical bell
#Zoomscript
Zoomscript
print "Sleeping..." wait 1 println print "Awake!"
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Standard_ML
Standard ML
open XWindows ; open Motif ;   val countWindow = fn () =>   let val ctr = ref 0; val shell = XtAppInitialise "" "demo" "top" [] [XmNwidth 300, XmNheight 150 ] ; val main = XmCreateMainWindow shell "main" [XmNmappedWhenManaged true ] ; val frame = XmCreateForm main "frame" [XmNwidth 390, XmNheight 290 ] ; val text = XmCreateLabel frame "show" [XmNlabelString "No clicks yet" ] ; val buttn = XmCreateDrawnButton frame "press" [XmNwidth 75 , XmNheight 30 , XmNlabelString "Click me" , XmNbottomAttachment XmATTACH_POSITION,XmNbottomPosition 98 ] ; val report = fn (w,c,t) => (XtSetValues text [XmNlabelString (Int.toString (ctr:= !ctr +1; !ctr)) ] ; t ) in   ( XtSetCallbacks buttn [ (XmNactivateCallback , report) ] XmNarmCallback ; XtManageChildren [ text,buttn ] ; XtManageChildren [ frame ] ; XtManageChild main ; XtRealizeWidget shell )   end;  
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Tcl
Tcl
package require Tk pack [label .l -text "There have been no clicks yet"] set count 0 pack [button .b -text "click me" -command upd] proc upd {} { .l configure -text "Number of clicks: [incr ::count]" }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#C.23
C#
using System;   class Program { static void Main() { Console.WriteLine(new DateTime()); } }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#C.2B.2B
C++
#include <iostream> #include <chrono> #include <ctime> int main() { std::chrono::system_clock::time_point epoch; std::time_t t = std::chrono::system_clock::to_time_t(epoch); std::cout << std::asctime(std::gmtime(&t)) << '\n'; return 0; }
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Nim
Nim
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)
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Perl
Perl
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;
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#C.23
C#
using System; using System.Collections;   namespace RosettaCode { class SierpinskiTriangle { int len; BitArray b;   public SierpinskiTriangle(int n) { if (n < 1) { throw new ArgumentOutOfRangeException("Order must be greater than zero"); } len = 1 << (n+1); b = new BitArray(len+1, false); b[len>>1] = true; }   public void Display() { for (int j = 0; j < len / 2; j++) { for (int i = 0; i < b.Count; i++) { Console.Write("{0}", b[i] ? "*" : " "); } Console.WriteLine(); NextGen(); } }   private void NextGen() { BitArray next = new BitArray(b.Count, false); for (int i = 0; i < b.Count; i++) { if (b[i]) { next[i - 1] = next[i - 1] ^ true; next[i + 1] = next[i + 1] ^ true; } } b = next; } } }
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Sierpinski[n_] := Nest[Join @@ Table[With[{a = #[[i, 1]], b = #[[i, 2]], c = #[[i, 3]]}, {{a, (a + b)/2, (c + a)/2}, {(a + b)/2, b, (b + c)/2}, {(c + a)/2, (b + c)/2, c}}], {i, Length[#]}] &, {{{0, 0}, {1/2, 1}, {1, 0}}}, n] Graphics[{Black, Polygon /@ Sierpinski[8]}]
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#MATLAB
MATLAB
[x, x0] = deal(cat(3, [1 0]', [-1 0]', [0 sqrt(3)]')); for k = 1 : 6 x = x(:,:) + x0 * 2 ^ k / 2; end patch('Faces', reshape(1 : 3 * 3 ^ k, 3, '')', 'Vertices', x(:,:)')
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#TI-89_BASIC
TI-89 BASIC
Prgm Local clicks 0 → clicks 1 → ok © System variable also set by Dialog statement While ok = 1 Dialog Title "Rosetta Code" Text "There have been " & string(clicks) & " OKs" EndDlog clicks + 1 → clicks EndWhile EndPrgm
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Unicon
Unicon
  import gui $include "guih.icn"   class SimpleApp : Dialog (label)   # -- automatically called when the dialog is created method component_setup() # create and add the label label := Label("label=There have been no clicks yet","pos=50%,33%", "align=c,c") add (label)   # create and add the button button := TextButton("label=Click me", "pos=50%,66%", "align=c,c") button.connect(self, "clicked", ACTION_EVENT) add (button)   # some cosmetic settings for the window attrib("size=180,70", "bg=light gray") end   method clicked () static count := 0 count +:= 1 label.set_label ("Clicked " || count || " times") end end   procedure main() local d := SimpleApp () d.show_modal() end  
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Clojure
Clojure
(println (java.util.Date. 0))
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. epoch.   DATA DIVISION. WORKING-STORAGE SECTION. 01 epoch-date. 03 year PIC 9(4). 03 month PIC 99. 03 dday PIC 99.   PROCEDURE DIVISION. MOVE FUNCTION DATE-OF-INTEGER(1) TO epoch-date   DISPLAY year "-" month "-" dday   GOBACK .
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Phix
Phix
-- -- demo\rosetta\SierpinskyPentagon.exw -- =================================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer constant title = "Sierpinski Pentagon", scale_factor = 1/(2+cos(2*PI/5)*2), side_factor = 1+cos(2*PI/5)*2, angles = sq_mul(2*PI/5,tagset(7,3)), cosangles = apply(angles,cos), sinangles = apply(angles,sin) integer level = 3 procedure drawPentagon(atom x, y, side, w, h, integer depth) if depth=0 then cdCanvasBegin(cddbuffer,CD_FILL) for i=1 to 5 do x += cosangles[i] * side y -= sinangles[i] * side cdCanvasVertex(cddbuffer, w+x, h-y) end for cdCanvasEnd(cddbuffer) else side *= scale_factor atom distance = side*side_factor for i=1 to 5 do x += cosangles[i] * distance y -= sinangles[i] * distance drawPentagon(x, y, side, w, h, depth-1) end for end if end procedure function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") atom hw = min(w/2,h/2), margin = 20, radius = hw - 2*margin, side = radius * sin(PI/5) * 2 cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) drawPentagon(hw, 3*margin, side, w/2-radius-2*margin, h, level) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdCanvas cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_PARCHMENT) cdCanvasSetForeground(cddbuffer, CD_BLUE) return IUP_DEFAULT end function procedure set_dlg_title() IupSetStrAttribute(dlg, "TITLE", "%s (level %d)",{title,level}) end procedure function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if if find(c,"+-") then if c='+' then level = min(5,level+1) elsif c='-' then level = max(0,level-1) end if set_dlg_title() IupRedraw(canvas) end if return IUP_CONTINUE end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=640x640") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) set_dlg_title() IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#C.2B.2B
C++
#include <iostream> #include <string> #include <list> #include <algorithm> #include <iterator>   using namespace std;   template<typename OutIt> void sierpinski(int n, OutIt result) { if( n == 0 ) { *result++ = "*"; } else { list<string> prev; sierpinski(n-1, back_inserter(prev));   string sp(1 << (n-1), ' '); result = transform(prev.begin(), prev.end(), result, [sp](const string& x) { return sp + x + sp; }); transform(prev.begin(), prev.end(), result, [sp](const string& x) { return x + " " + x; }); } }   int main() { sierpinski(4, ostream_iterator<string>(cout, "\n")); return 0; }
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Nim
Nim
import imageman   const Black = ColorRGBU [byte 0, 0, 0] # For background. Red = ColorRGBU [byte 255, 0, 0] # For triangle.   proc drawSierpinski(img: var Image; txy: array[1..6, float]; levelsYet: Natural) = var nxy: array[1..6, float] if levelsYet > 0: for i in 1..6: let pos = if i < 5: i + 2 else: i - 4 nxy[i] = (txy[i] + txy[pos]) / 2 img.drawSierpinski([txy[1], txy[2], nxy[1], nxy[2], nxy[5], nxy[6]], levelsYet - 1) img.drawSierpinski([nxy[1], nxy[2], txy[3], txy[4], nxy[3], nxy[4]], levelsyet - 1) img.drawSierpinski([nxy[5], nxy[6], nxy[3], nxy[4], txy[5], txy[6]], levelsyet - 1) else: img.drawPolyline(closed = true, Red, (txy[1].toInt, txy[2].toInt), (txy[3].toInt, txy[4].toInt),(txy[5].toInt, txy[6].toInt))   var image = initImage[ColorRGBU](800, 800) image.fill(Black) image.drawSierpinski([400.0, 100.0, 700.0, 500.0, 100.0, 500.0], 7) image.savePNG("sierpinski_triangle.png", compression = 9)
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Objeck
Objeck
use Game.SDL2; use Game.Framework;   class Test { @framework : GameFramework; @colors : Color[]; @step : Int;   function : Main(args : String[]) ~ Nil { Test->New()->Run(); }   New() { @framework := GameFramework->New(GameConsts->SCREEN_WIDTH, GameConsts->SCREEN_HEIGHT, "Sierpinski Triangle"); @framework->SetClearColor(Color->New(0,0,0)); @colors := Color->New[1]; @colors[0] := Color->New(178,34,34); }   method : Run() ~ Nil { if(@framework->IsOk()) { e := @framework->GetEvent();   quit := false; while(<>quit) { # process input while(e->Poll() <> 0) { if(e->GetType() = EventType->SDL_QUIT) { quit := true; }; };   @framework->FrameStart(); @framework->Clear(); Render(8, 20, 20, 450); @framework->Show(); @framework->FrameEnd(); }; } else { "--- Error Initializing Environment ---"->ErrorLine(); return; };   leaving { @framework->Quit(); }; }   method : Render(level : Int, x : Int, y : Int, size : Int) ~ Nil { if(level > -1) { renderer := @framework->GetRenderer();   renderer->LineColor(x, y, x+size, y, @colors[0]); renderer->LineColor(x, y, x, y+size, @colors[0]); renderer->LineColor(x+size, y, x, y+size, @colors[0]);   Render(level-1, x, y, size/2); Render(level-1, x+size/2, y, size/2); Render(level-1, x, y+size/2, size/2); }; } }   consts GameConsts { SCREEN_WIDTH := 640, SCREEN_HEIGHT := 480 }  
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Vedit_macro_language
Vedit macro language
Reg_Set(10, "There have been no clicks yet") #1 = 0 repeat (ALL) { #2 = Dialog_Input_1(3, "`Simple Windowed Application`, `|@(10)`, `[&Click me]`,`[&Exit]`", APP+CENTER, 0, 0) if (#2 != 1) { break } // ESC or Exit #1++ Num_Str(#1, 10) Reg_Set(10, "Clicked", INSERT) Reg_Set(10, " times", APPEND) }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#CoffeeScript
CoffeeScript
console.log new Date(0).toISOString()
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Common_Lisp
Common Lisp
(multiple-value-bind (second minute hour day month year) (decode-universal-time 0 0) (format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second))
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#D
D
main() { print(new Date.fromEpoch(0,new TimeZone.utc())); }
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Processing
Processing
  float s_angle, scale, margin = 25, total = 4; float p_size = 700; float radius = p_size/2-2*margin; float side = radius * sin(PI/5)*2;   void setup() { float temp = width/2; size(590, 590); background(0, 0, 200); stroke(255); s_angle = 72*PI/180; scale = 1/(2+cos(s_angle)*2); for (int i = 0; i < total; i++) { background(0, 0, 200); drawPentagon(width/2, (height-p_size)/2 + 3*margin, side, total); } }   void drawPentagon(float x, float y, float side, float depth) { float angle = 3*s_angle; if (depth == 0) { for (int i = 0; i < 5; i++) { float px = x; float py = y; x = x+cos(angle)*side; y = y-sin(angle)*side; line(x, y, px, py); angle += s_angle; } } else { side *= scale; float distance = side+side*cos(s_angle)*2; for (int j = 0; j < 5; j++) { x = x+cos(angle)*distance; y = y-sin(angle)*distance; drawPentagon(x, y, side, depth-1); angle += s_angle; } } }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Clojure
Clojure
(ns example (:require [clojure.contrib.math :as math]))   ; Length of integer in binary ; (copied from a private multimethod in clojure.contrib.math) (defmulti #^{:private true} integer-length class)   (defmethod integer-length java.lang.Integer [n] (count (Integer/toBinaryString n))) (defmethod integer-length java.lang.Long [n] (count (Long/toBinaryString n))) (defmethod integer-length java.math.BigInteger [n] (count (.toString n 2)))   (defn sierpinski-triangle [order] (loop [size (math/expt 2 order) v (math/expt 2 (- size 1))] (when (pos? size) (println (apply str (map #(if (bit-test v %) "*" " ") (range (integer-length v))))) (recur (dec size) (bit-xor (bit-shift-left v 1) (bit-shift-right v 1))))))   (sierpinski-triangle 4)
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#OCaml
OCaml
open Graphics   let round v = int_of_float (floor (v +. 0.5))   let middle (x1, y1) (x2, y2) = ((x1 +. x2) /. 2.0, (y1 +. y2) /. 2.0)   let draw_line (x1, y1) (x2, y2) = moveto (round x1) (round y1); lineto (round x2) (round y2); ;;   let draw_triangle (p1, p2, p3) = draw_line p1 p2; draw_line p2 p3; draw_line p3 p1; ;;   let () = open_graph ""; let width = float (size_x ()) in let height = float (size_y ()) in let pad = 20.0 in let initial_triangle = ( (pad, pad), (width -. pad, pad), (width /. 2.0, height -. pad) ) in let rec loop step tris = if step <= 0 then tris else loop (pred step) ( List.fold_left (fun acc (p1, p2, p3) -> let m1 = middle p1 p2 and m2 = middle p2 p3 and m3 = middle p3 p1 in let tri1 = (p1, m1, m3) and tri2 = (p2, m2, m1) and tri3 = (p3, m3, m2) in tri1 :: tri2 :: tri3 :: acc ) [] tris ) in let res = loop 6 [ initial_triangle ] in List.iter draw_triangle res; ignore (read_key ())
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#11l
11l
T Item String name, date, category   F (name, date, category) .name = name .date = date .category = category   F String() R .name‘, ’(.date)‘, ’(.category)   V db_filename = ‘simdb.csv’   F load() [Item] db L(line) File(:db_filename).read().rtrim("\n").split("\n") V item = line.split(‘, ’) db.append(Item(item[0], item[1], item[2])) R db   F store(item) File(:db_filename, ‘a’).write(String(item)"\n")   F printUsage() print(|‘ Usage: simdb cmd [categoryName] add add item, followed by optional category latest print last added item(s), followed by optional category all print all For instance: add "some item name" "some category name’)   F addItem(args) I args.len < 2 printUsage() R   V date = Time().strftime(‘%Y-%m-%d %H:%M:%S’) V cat = I args.len == 3 {args[2]} E ‘none’ store(Item(args[1], date, cat))   F printLatest(a) V db = load() I db.empty print(‘No entries in database.’) R   I a.len == 2 L(item) reversed(db) I item.category == a[1] print(item) L.break L.was_no_break print(‘There are no items for category '’a[1]‘'’) E print(db.last)   F printAll() V db = load() I db.empty print(‘No entries in database.’) R   L(item) db print(item)   :start: I :argv.len C 2..4 S :argv[1].lowercase() ‘add’ addItem(:argv[1..]) ‘latest’ printLatest(:argv[1..]) ‘all’ printAll() E printUsage() E printUsage()
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#11l
11l
F scs(String x, y) I x.empty R y I y.empty R x I x[0] == y[0] R x[0]‘’scs(x[1..], y[1..]) I scs(x, y[1..]).len <= scs(x[1..], y).len R y[0]‘’scs(x, y[1..]) E R x[0]‘’scs(x[1..], y)   print(scs(‘abcbdab’, ‘bdcaba’))
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Visual_Basic
Visual Basic
VERSION 5.00 Begin VB.Form Form2 Caption = "There have been no clicks yet" ClientHeight = 2940 ClientLeft = 60 ClientTop = 600 ClientWidth = 8340 LinkTopic = "Form1" ScaleHeight = 2940 ScaleWidth = 8340 StartUpPosition = 3 'Windows Default Begin VB.CommandButton Command1 Caption = "Click me!" Height = 495 Left = 3600 TabIndex = 0 Top = 1200 Width = 1215 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False '-----user-written code begins here; everything above this line is hidden in the GUI----- Private clicked As Long   Private Sub Command1_Click() clicked = clicked + 1 Me.Caption = clicked & " clicks." End Sub  
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Web_68
Web 68
@1Introduction. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Licence as published by the Free Software Foundation, either version 3 of the Licence, or (at your option) any later version.   Copyright (c) 2012 Sian Mountbatten.   @m cvs simpleapp = "$Id: $"   @a@<Prelude@> BEGIN @<Included declarations@> @<Plain values in the outer reach@> @<Names in the outer reach@> @<Procedures in the outer reach@> @<Logic in the outer reach@> END @<Postlude@>   @ The local compiler requires a special prelude.@^system dependencies@>   @<Prel...@>= PROGRAM simpleapp CONTEXT VOID USE @<Library preludes@>   @ And a special postlude.@^system dependencies@>   @<Post...@>= FINISH   @ The program requires the predefined forms and the standard prelude.   @<Library...@>= simpleapp fd,standard   @ This Web 68 file provides the Xforms prelude.   @iforms.w@>   @1Initialisation. The initial processing consists of initialising the Xforms library.   @<Logic...@>= open(argf,"",arg channel); fl initialize(argc,argv,"simpleapp",NIL,0);   @ Declare the !REF FILE!.   @<Names...@>= FILE @!argf;   @1Main processing. The form is created in !simpleapp fd! the source code of which is 108 lines long. Firstly, define the callback for the button.   @<Proc...@>= button cb:=(REF FLOBJECT obj,INT data)VOID: ( clicks +:= 1; fl set object label(text box OF click form,whole(clicks,0)+" click"+ (clicks=1|""|"s")+" on the button") );   @ Declare !clicks!.   @<Plain...@>= INT clicks:=0;   @ Create the form, show it and hand control to the Xforms library.   @<Logic...@>= click form:=create form click; fl show form(click OF click form,fl place center,fl full border,"SimpleApp"); fl do forms   @ Declare the form.   @<Names...@>= REF FDCLICK click form;   @1Macro declarations. All the macros used in the program are declared here.   @<Include...@>= macro fl do forms; macro fl initialize; macro fl set object label; macro fl show form;   @ To compile the program, use this command: <pre> ca -l mod -l forms simpleapp.w68 </pre> The predefined form will have been compiled with this command: <pre> ca -m mod simpleappfd.w68 </pre> The predefined form was created by the <b>fdesign</b> program for the Xforms library, and the resulting form definition file was converted to Web 68 by the program <b>fdtow68</b>.
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Dart
Dart
main() { print(new Date.fromEpoch(0,new TimeZone.utc())); }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Delphi
Delphi
program ShowEpoch;   {$APPTYPE CONSOLE}   uses SysUtils;   begin Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', 0)); end.
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Erlang
Erlang
2> calendar:universal_time(). {{2013,9,13},{8,3,16}} 3> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). 63546278932 4> calendar:gregorian_seconds_to_datetime(63546278932). {{2013,9,13},{8,8,52}} 11> calendar:gregorian_seconds_to_datetime(0). {{0,1,1},{0,0,0}}
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Prolog
Prolog
main:- write_sierpinski_pentagon('sierpinski_pentagon.svg', 600, 5).   write_sierpinski_pentagon(File, Size, Order):- open(File, write, Stream), format(Stream, "<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n", [Size, Size]), write(Stream, "<rect width='100%' height='100%' fill='white'/>\n"), Margin = 5, Radius is Size/2 - 2 * Margin, Side is Radius * sin(pi/5) * 2, Height is Side * (sin(pi/5) + sin(2 * pi/5)), X is Size/2, Y is (Size - Height)/2, Scale_factor is 1/(2 + cos(2 * pi/5) * 2), sierpinski_pentagon(Stream, X, Y, Scale_factor, Side, Order), write(Stream, "</svg>\n"), close(Stream).   sierpinski_pentagon(Stream, X, Y, _, Side, 1):- !, write(Stream, "<polygon stroke-width='1' stroke='black' fill='blue' points='"), format(Stream, '~g,~g', [X, Y]), Angle is 6 * pi/5, write_pentagon_points(Stream, Side, Angle, X, Y, 5), write(Stream, "'/>\n"). sierpinski_pentagon(Stream, X, Y, Scale_factor, Side, N):- Side1 is Side * Scale_factor, N1 is N - 1, Angle is 6 * pi/5, sierpinski_pentagons(Stream, X, Y, Scale_factor, Side1, Angle, N1, 5).   write_pentagon_points(_, _, _, _, _, 0):-!. write_pentagon_points(Stream, Side, Angle, X, Y, N):- N1 is N - 1, X1 is X + cos(Angle) * Side, Y1 is Y - sin(Angle) * Side, Angle1 is Angle + 2 * pi/5, format(Stream, ' ~g,~g', [X1, Y1]), write_pentagon_points(Stream, Side, Angle1, X1, Y1, N1).   sierpinski_pentagons(_, _, _, _, _, _, _, 0):-!. sierpinski_pentagons(Stream, X, Y, Scale_factor, Side, Angle, N, I):- I1 is I - 1, Distance is Side + Side * cos(2 * pi/5) * 2, X1 is X + cos(Angle) * Distance, Y1 is Y - sin(Angle) * Distance, Angle1 is Angle + 2 * pi/5, sierpinski_pentagon(Stream, X1, Y1, Scale_factor, Side, N), sierpinski_pentagons(Stream, X1, Y1, Scale_factor, Side, Angle1, N, I1).
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#CLU
CLU
sierpinski = proc (size: int) returns (string) ss: stream := stream$create_output()   for i: int in int$from_to(0, size*4-1) do c: int := 1 for j: int in int$from_to(1, size*4-1-i) do stream$putc(ss, ' ') end for k: int in int$from_to(0, i) do if c//2=0 then stream$puts(ss, " ") else stream$puts(ss, " *") end c := c*(i-k)/(k+1) end stream$putc(ss, '\n') end return(stream$get_contents(ss)) end sierpinski   start_up = proc () stream$puts( stream$primary_output(), sierpinski(4) ) end start_up
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#PARI.2FGP
PARI/GP
  \\ Sierpinski triangle fractal \\ Note: plotmat() can be found here on \\ http://rosettacode.org/wiki/Brownian_tree#PARI.2FGP page. \\ 6/3/16 aev pSierpinskiT(n)={ my(sz=2^n,M=matrix(sz,sz),x,y); for(y=1,sz, for(x=1,sz, if(!bitand(x,y),M[x,y]=1);));\\fends plotmat(M); } {\\ Test: pSierpinskiT(9); \\ SierpT9.png }  
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#Bracmat
Bracmat
whl ' ( arg$:?command & ( get'db | (db=1)&lst$(db,db,NEW) ) &  !command  : ( add & :?name:?tag:?date & whl ' ( arg$:?argmnt & arg$:?value & (!argmnt.!value)  : ( (title|name.?name) | (category|tag.?tag) | (date.?date) ) ) & (  !name:~ & !tag:~ & !date:~ & (  !db:?*!tag^(?+(!date.!name)+?)*? & out$"This record already exists" |  !tag^(!date.!name)*!db:?db & lst$(db,db,NEW) ) | out$"invalid data" ) | latest & :?date & nothing found:?latest & (  !db  :  ? *  ?tag ^ ( ? + ( (>!date:?date.?name) & (!name,!tag,!date):?latest & ~ ) + ? ) * ? | out$!latest ) | latest/category & :?date:?latests:?latest & (  !db  :  ? * ( ?tag & !latests !latest:?latests & :?latest:?date ) ^ ( ? + ( (>!date:?date.?name) & (!name,!tag,!date):?latest & ~ ) + ? ) * ? | !latests !latest:?latests&out$!latests ) | sorted & 0:?sorted & (  !db  :  ? *  ?tag ^ ( ? + ( (?date.?name) & (!date.!name,!tag,!date)+!sorted:?sorted & ~ ) + ? ) * ? | whl ' (!sorted:(?.?row)+?sorted&out$!row) ) ) );  
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#Ada
Ada
with Ada.Text_IO;   procedure Shortest is   function Scs (Left, Right : in String) return String is Left_Tail  : String renames Left (Left'First + 1 .. Left'Last); Right_Tail : String renames Right (Right'First + 1 .. Right'Last); begin if Left = "" then return Right; end if; if Right = "" then return Left; end if;   if Left (Left'First) = Right (Right'First) then return Left (Left'First) & Scs (Left_Tail, Right_Tail); end if;   declare S1 : constant String := Scs (Left, Right_Tail); S2 : constant String := Scs (Left_Tail, Right); begin return (if S1'Length <= S2'Length then Right (Right'First) & S1 else Left (Left'First) & S2); end; end Scs;   procedure Exercise (Left, Right : String) is use Ada.Text_Io; begin Put ("scs ( "); Put (Left); Put (" , "); Put (Right); Put ( " ) -> "); Put (Scs (Left, Right)); New_Line; end Exercise;   begin Exercise ("abcbdab", "bdcaba"); Exercise ("WEASELS", "WARDANCE"); end Shortest;
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#ALGOL_68
ALGOL 68
BEGIN PRIO SCS = 1; # returns the shortest common supersequence of x and y # OP SCS = ( STRING x, y )STRING: IF x = "" THEN y ELIF y = "" THEN x ELIF x[ LWB x ] = y[ LWB y ] THEN x[ LWB x ] + ( x[ LWB x + 1 : ] SCS y[ LWB y + 1 : ] ) ELIF STRING x y sub = x SCS y[ LWB y + 1 : ]; STRING x sub y = x[ LWB x + 1 : ] SCS y; INT x y sub size = ( UPB x y sub - LWB x y sub ) + 1; INT x sub y size = ( UPB x sub y - LWB x sub y ) + 1; x y sub size <= x sub y size THEN y[ LWB y ] + x y sub ELSE x[ LWB x ] + x sub y FI # SCS # ;   print( ( "abcbdab" SCS "bdcaba", newline ) ) END
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Wren
Wren
import "graphics" for Canvas, Color import "input" for Mouse import "dome" for Window   class SimpleWindowedApplication { construct new(width, height) { Window.title = "Simple windowed application" _fore = Color.white _clicks = 0 }   init() { drawControls() }   update() { if (Mouse["left"].justPressed && insideButton) _clicks = _clicks + 1 }   draw(alpha) { drawControls() }   insideButton { var p = Mouse.position return p.x >= 120 && p.x <= 200 && p.y >= 90 && p.y <= 170 }   drawControls() { Canvas.cls() if (_clicks == 0) { Canvas.print("There have been no clicks yet", 40, 40, _fore) } else if (_clicks == 1) { Canvas.print("The button has been clicked once", 30, 40, _fore) } else { Canvas.print("The button has been clicked %(_clicks) times", 10, 40, _fore) } Canvas.rectfill(120, 90, 80, 80, Color.red) Canvas.rect(120, 90, 80, 80, Color.blue) Canvas.print("click me", 130, 125, _fore) } }   var Game = SimpleWindowedApplication.new(600, 600)
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#F.23
F#
printfn "%s" ((new System.DateTime()).ToString("u"))
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Factor
Factor
USING: calendar calendar.format io ;   0 micros>timestamp timestamp>ymdhms print
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Forth
Forth
include lib/longjday.4th 0 posix>jday .longjday cr
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Python
Python
from turtle import * import math speed(0) # 0 is the fastest speed. Otherwise, 1 (slow) to 10 (fast) hideturtle() # hide the default turtle   part_ratio = 2 * math.cos(math.radians(72)) side_ratio = 1 / (part_ratio + 2)   hide_turtles = True # show/hide turtles as they draw path_color = "black" # path color fill_color = "black" # fill color   # turtle, size def pentagon(t, s): t.color(path_color, fill_color) t.pendown() t.right(36) t.begin_fill() for i in range(5): t.forward(s) t.right(72) t.end_fill()   # iteration, turtle, size def sierpinski(i, t, s): t.setheading(0) new_size = s * side_ratio   if i > 1: i -= 1   # create four more turtles for j in range(4): t.right(36) short = s * side_ratio / part_ratio dist = [short, s, s, short][j]   # spawn a turtle spawn = Turtle() if hide_turtles:spawn.hideturtle() spawn.penup() spawn.setposition(t.position()) spawn.setheading(t.heading()) spawn.forward(dist)   # recurse for spawned turtles sierpinski(i, spawn, new_size)   # recurse for parent turtle sierpinski(i, t, new_size)   else: # draw a pentagon pentagon(t, s) # delete turtle del t   def main(): t = Turtle() t.hideturtle() t.penup() screen = t.getscreen() y = screen.window_height() t.goto(0, y/2-20)   i = 5 # depth. i >= 1 size = 300 # side length   # so the spawned turtles move only the distance to an inner pentagon size *= part_ratio   # begin recursion sierpinski(i, t, size)   main()
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#COBOL
COBOL
identification division. program-id. sierpinski-triangle-program. data division. working-storage section. 01 sierpinski. 05 n pic 99. 05 i pic 999. 05 k pic 999. 05 m pic 999. 05 c pic 9(18). 05 i-limit pic 999. 05 q pic 9(18). 05 r pic 9. procedure division. control-paragraph. move 4 to n. multiply n by 4 giving i-limit. subtract 1 from i-limit. perform sierpinski-paragraph varying i from 0 by 1 until i is greater than i-limit. stop run. sierpinski-paragraph. subtract i from i-limit giving m. multiply m by 2 giving m. perform m times, display space with no advancing, end-perform. move 1 to c. perform inner-loop-paragraph varying k from 0 by 1 until k is greater than i. display ''. inner-loop-paragraph. divide c by 2 giving q remainder r. if r is equal to zero then display ' * ' with no advancing. if r is not equal to zero then display ' ' with no advancing. compute c = c * (i - k) / (k + 1).
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Perl
Perl
my $levels = 6; my $side = 512; my $height = get_height($side);   sub get_height { my($side) = @_; $side * sqrt(3) / 2 }   sub triangle { my($x1, $y1, $x2, $y2, $x3, $y3, $fill, $animate) = @_; my $svg; $svg .= qq{<polygon points="$x1,$y1 $x2,$y2 $x3,$y3"}; $svg .= qq{ style="fill: $fill; stroke-width: 0;"} if $fill; $svg .= $animate ? qq{>\n <animate attributeType="CSS" attributeName="opacity"\n values="1;0;1" keyTimes="0;.5;1" dur="20s" repeatCount="indefinite" />\n</polygon>\n} : ' />'; return $svg; }   sub fractal { my( $x1, $y1, $x2, $y2, $x3, $y3, $r ) = @_; my $svg; $svg .= triangle( $x1, $y1, $x2, $y2, $x3, $y3 ); return $svg unless --$r; my $side = abs($x3 - $x2) / 2; my $height = get_height($side); $svg .= fractal( $x1, $y1-$height*2, $x1-$side/2, $y1-3*$height, $x1+$side/2, $y1-3*$height, $r); $svg .= fractal( $x2, $y1, $x2-$side/2, $y1-$height, $x2+$side/2, $y1-$height, $r); $svg .= fractal( $x3, $y1, $x3-$side/2, $y1-$height, $x3+$side/2, $y1-$height, $r); }   open my $fh, '>', 'run/sierpinski_triangle.svg'; print $fh <<'EOD', <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <radialGradient id="basegradient" cx="50%" cy="65%" r="50%" fx="50%" fy="65%"> <stop offset="10%" stop-color="#ff0" /> <stop offset="60%" stop-color="#f00" /> <stop offset="99%" stop-color="#00f" /> </radialGradient> </defs> EOD   triangle( $side/2, 0, 0, $height, $side, $height, 'url(#basegradient)' ), triangle( $side/2, 0, 0, $height, $side, $height, '#000', 'animate' ), '<g style="fill: #fff; stroke-width: 0;">', fractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ), '</g></svg>';
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#C
C
"Soon Rising","Dee","Lesace","10-12-2000","New Hat Press" "Brave Chicken","Tang","Owe","04-01-2008","Nowhere Press" "Aardvark Point","Dee","Lesace","5-24-2001","New Hat Press" "Bat Whisperer, The","Tang","Owe","01-03-2004","Nowhere Press" "Treasure Beach","Argus","Jemky","09-22-1999","Lancast"
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#C
C
#include <stdio.h> #include <string.h>   typedef struct link link_t; struct link { int len; char letter; link_t *next; };   // Stores a copy of a SCS of x and y in out. Caller needs to make sure out is long enough. int scs(char *x, char *y, char *out) { int lx = strlen(x), ly = strlen(y); link_t lnk[ly + 1][lx + 1];   for (int i = 0; i < ly; i++) lnk[i][lx] = (link_t) {ly - i, y[i], &lnk[i + 1][lx]};   for (int j = 0; j < lx; j++) lnk[ly][j] = (link_t) {lx - j, x[j], &lnk[ly][j + 1]};   lnk[ly][lx] = (link_t) {0};   for (int i = ly; i--; ) { for (int j = lx; j--; ) { link_t *lp = &lnk[i][j]; if (y[i] == x[j]) { lp->next = &lnk[i+1][j+1]; lp->letter = x[j]; } else if (lnk[i][j+1].len < lnk[i+1][j].len) { lp->next = &lnk[i][j+1]; lp->letter = x[j]; } else { lp->next = &lnk[i+1][j]; lp->letter = y[i]; } lp->len = lp->next->len + 1; } }   for (link_t *lp = &lnk[0][0]; lp; lp = lp->next) *out++ = lp->letter;   return 0; }   int main(void) { char x[] = "abcbdab", y[] = "bdcaba", res[128]; scs(x, y, res); printf("SCS(%s, %s) -> %s\n", x, y, res); return 0; }
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#XPL0
XPL0
include c:\cxpl\stdlib; \standard library provides mouse routines, etc. def Ww=40, Wh=12, Wx=(80-Ww)/2, Wy=(25-Wh)/2; \window width, etc. def Bw=11, Bh=4, Bx=Wx+(Ww-Bw)/2, By=Wy+3*(Wh-Bh)/4; \button size & position int Clicks, Mx, My; \number of clicks and mouse coordinates   [ShowCursor(false); \turn off flashing cursor Attrib($1F); \bright white characters on blue SetWind(Wx, Wy, Wx+Ww, Wy+Wh, 2, true); \blue window with no scroll DrawBox(Wx, Wy, Wx+Ww, Wy+Wh, 3); \draw borders Cursor(Wx+5, Wy+3); Text(6, "There have been no clicks yet."); DrawBox(Bx, By, Bx+Bw, By+Bh, 0); \draw button Cursor(Bx+2, By+2); Text(6, "Click me");   OpenMouse; ShowMouse(true); Clicks:= 0; repeat if GetMouseButton(0) then \left button down [while GetMouseButton(0) do []; \wait for release Mx:= GetMousePosition(0) / 8; \character coordinates My:= GetMousePosition(1) / 8; if Mx>=Bx & Mx<=Bx+Bw & My>=By & My<=By+Bh then [Clicks:= Clicks+1; \mouse pointer is on the button Cursor(Wx+4, Wy+3); Text(6, "Times button has been clicked: "); IntOut(6, Clicks); ]; ]; until ChkKey; \keystroke terminates program SetVid(3); \turn off mouse and turn on flashing cursor ]
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Yorick
Yorick
#include "button.i"   window, 0; btn_click = Button(text="click me", x=.395, y=.65, dx=0.04368, dy=0.0091); btn_quit = Button(text="quit", x=.395, y=.6, dx=0.02184, dy=0.0091); count = 0; msg = "There have been no clicks yet"; finished = 0; do { fma; plt, msg, .395, .7, justify="CH"; button_plot, btn_click; button_plot, btn_quit; xy = mouse(0, 0, ""); if(button_test(btn_click, xy(1), xy(2))) { count++; msg = swrite(format="Number of clicks: %d", count); } else if(button_test(btn_quit, xy(1), xy(2))) { finished = 1; winkill, 0; } } while(!finished);
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Fortran
Fortran
' FB 1.05.0 Win64   #Include "vbcompat.bi"   ' The first argument to the Format function is a date serial ' and so the first statement below displays the epoch.   Dim f As String = "mmmm d, yyyy hh:mm:ss" Print Format( 0 , f) '' epoch Print Format( 0.5, f) '' noon on the same day Print Format(-0.5, f) '' noon on the previous day Print Format(1000000, f) '' one million days after the epoch Print Format(-80000, f) '' eighty thousand days before the epoch Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Include "vbcompat.bi"   ' The first argument to the Format function is a date serial ' and so the first statement below displays the epoch.   Dim f As String = "mmmm d, yyyy hh:mm:ss" Print Format( 0 , f) '' epoch Print Format( 0.5, f) '' noon on the same day Print Format(-0.5, f) '' noon on the previous day Print Format(1000000, f) '' one million days after the epoch Print Format(-80000, f) '' eighty thousand days before the epoch Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ [ 1 1 30 times [ tuck + ] swap join ] constant do ] is phi ( --> n/d )   [ 5 times [ 2dup walk 1 5 turn ] 2drop ] is pentagon ( n/d n --> )   forward is pentaflake   [ dup 0 = iff [ drop ' [ 79 126 229 ] fill pentagon ] done 1 - temp put 5 times [ 2dup 2 1 phi v- v* temp share pentaflake 2dup fly 1 5 turn ] temp release 2drop ] resolves pentaflake ( n/d n --> )   turtle 3 10 turn 300 1 fly 2 5 turn ' [ 79 126 229 ] colour 400 1 5 pentaflake
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Racket
Racket
#lang racket/base (require racket/draw pict racket/math racket/class)   ;; exterior angle (define 72-degrees (degrees->radians 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. (define scale-factor (/ (+ 2 (* (cos 72-degrees) 2)))) ;; 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. (define dist-factor (+ 1 (* (cos 72-degrees) 2)))   ;; don't use scale, since it scales brushes too (making lines all tiny) (define (draw-pentagon x y side depth dc) (let recur ((x x) (y y) (side side) (depth depth)) (cond [(zero? depth) (define p (new dc-path%)) (send p move-to x y) (for/fold ((x x) (y y) (α (* 3 72-degrees))) ((i 5)) (send p line-to x y) (values (+ x (* side (cos α))) (- y (* side (sin α))) (+ α 72-degrees))) (send p close) (send dc draw-path p)] [else (define side/ (* side scale-factor)) (define dist (* side/ dist-factor))  ;; The top positions form a virtual pentagon of their own,  ;; so simply move from one to the other by changing direction. (for/fold ((x x) (y y) (α (* 3 72-degrees))) ((i 5)) (recur x y side/ (sub1 depth)) (values (+ x (* dist (cos α))) (- y (* dist (sin α))) (+ α 72-degrees)))])))   (define (dc-draw-pentagon depth w h #:margin (margin 4)) (dc (lambda (dc dx dy) (define old-brush (send dc get-brush)) (send dc set-brush (make-brush #:style 'transparent)) (draw-pentagon (/ w 2) (* 3 margin) (* (- (/ w 2) (* 2 margin)) (sin (/ pi 5)) 2) depth dc) (send dc set-brush old-brush)) w h))   (dc-draw-pentagon 1 120 120) (dc-draw-pentagon 2 120 120) (dc-draw-pentagon 3 120 120) (dc-draw-pentagon 4 120 120) (dc-draw-pentagon 5 640 640)
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Comal
Comal
0010 DIM part$(FALSE:TRUE) OF 2 0020 part$(FALSE):=" ";part$(TRUE):="* " 0030 INPUT "Order? ":order# 0040 size#:=2^order# 0050 FOR y#:=size#-1 TO 0 STEP -1 DO 0060 PRINT " "*y#, 0070 FOR x#:=0 TO size#-y#-1 DO PRINT part$(x# BITAND y#=0), 0080 PRINT 0090 ENDFOR y# 0100 END
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Phix
Phix
-- demo\rosetta\SierpinskyTriangle.exw include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas procedure SierpinskyTriangle(integer level, atom x, atom y, atom w, atom h) atom w2 = w/2, w4 = w/4, h2 = h/2 if level=1 then cdCanvasBegin(cddbuffer,CD_CLOSED_LINES) cdCanvasVertex(cddbuffer, x, y) cdCanvasVertex(cddbuffer, x+w2, y+h) cdCanvasVertex(cddbuffer, x+w, y) cdCanvasEnd(cddbuffer) else SierpinskyTriangle(level-1, x, y, w2, h2) SierpinskyTriangle(level-1, x+w4, y+h2, w2, h2) SierpinskyTriangle(level-1, x+w2, y, w2, h2) end if end procedure integer level = 7 function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) SierpinskyTriangle(level, w*0.05, h*0.05, w*0.9, h*0.9) cdCanvasFlush(cddbuffer) IupSetStrAttribute(dlg, "TITLE", "Sierpinsky Triangle (level %d)",{level}) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_GRAY) return IUP_DEFAULT end function function esc_close(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if if find(c,"+-") then level = max(1,min(12,level+','-c)) IupRedraw(canvas) end if return IUP_CONTINUE end function procedure main() IupOpen() canvas = IupCanvas(NULL) IupSetAttribute(canvas, "RASTERSIZE", "640x640") IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) dlg = IupDialog(canvas) IupSetAttribute(dlg, "TITLE", "Sierpinsky Triangle") IupSetCallback(dlg, "K_ANY", Icallback("esc_close")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#C.23
C#
  using System; using System.IO;   namespace Simple_database { class Program { public static void Main(string[] args) { // // For appropriate use of this program // use standard Windows Command Processor or cmd.exe // // Create cmd.bat file at the same folder with executive version // of program Simple_database.exe, so when started, the correct // file path will be automatically set to cmd console. // // Start notepad, write only cmd.exe and save file as cmd.bat // // To start cmd just double click at cmd.bat file. // // // // Console application command line start command // // application name.exe [argument] [argument parameters] // // // Command line argument followed by parameters // // [a] - Add new entry // // ["data1"]["data2"]["data3"]...["data n"] // // ["data1"] - Data category ! // ["data2"] - Data // ["data3"] - Data // // // NOTICE ! // // First parameter is taken for data category. // // // // Command line argument with no parameters // // [p1] - Print the latest entry // // [p2] - Print the latest entry for each category // // [p3] - Print all entries sorted by a date // // //   // // Command line example // // Small_database.exe [a] ["home"] ["+398125465458"] ["My tel number"] // // Small_database.exe [a] ["office"] ["+398222789000"] ["Boss"] // // Small_database.exe [a] [cd] ["Action movie"] ["Movie title"] // Small_database.exe [a] [cd] ["SF movie"] ["Movie title"] // Small_database.exe [a] [dvd] ["Action movie"] ["Movie title"] // // // NOTICE ! // // Brackets and space between arguments and parameters are necessary. // Quotes must be used when parameters have more than one word. // // If not used as shown in examples, program will show error message. // //     // // Check command line for arguments // // if(args.Length==0) { Console.WriteLine(); Console.WriteLine(" Missing Argument Error. "); Console.WriteLine(); } else { switch (args[0]) { case "[a]" : Add_New_Entry(args); break;   case "[p1]": Print_Document("Print the latest entry.txt"); break;   case "[p2]": Print_Document("Print the latest entry for each category.txt"); break;   case "[p3]": Print_Document("Print all entries sorted by a date.txt"); break;   default : { Console.WriteLine(); Console.WriteLine(" Incorrect Argument Error. "); Console.WriteLine(); } break; } } }   static void Add_New_Entry(string [] args) {   // // Check parameters // // // Minimum one parameter, category // if(args.Length==1) { Console.WriteLine(); Console.WriteLine(" Missing Parameters Error..... "); Console.WriteLine(); } else { bool parameters_ok = true; foreach (string a in args) { if(!a.StartsWith("[") || !a.EndsWith("]")) { parameters_ok = !parameters_ok; break; } } // // Add new entry to Data base document // if(parameters_ok) { // // // Console.WriteLine(); Console.WriteLine(" Parameters are ok..... "); Console.WriteLine(); Console.WriteLine(" Writing new entry to database..... "); // // Create new Data base entry // args[0] = string.Empty; string line = string.Empty; foreach (string a in args) { line+=a; } line+="[" + DateTime.Now.ToString() + "]"; args[0] = "[" + DateTime.Now.ToString() + "]"; // // Write entry to Data base // StreamWriter w = new StreamWriter("Data base.txt",true); w.WriteLine(line); // // Close and dispose stream writer // w.Close(); w.Dispose(); // // // Console.WriteLine(); Console.WriteLine(" New entry is written to database. ");   Create_Print_Documents(args);   // // // Console.WriteLine(); Console.WriteLine(" Add new entry command executed. "); // // // } else { Console.WriteLine(); Console.WriteLine(" ! Parameters are not ok ! "); Console.WriteLine(); Console.WriteLine(" Add new entry command is not executed. "); Console.WriteLine(); } } }   static void Create_Print_Documents(string [] args) { // // // Console.WriteLine(); Console.WriteLine(" Creating new print documents. "); // // Create "Print all entries sorted by a date.txt" // File.Copy("Data base.txt","Print all entries sorted by a date.txt",true); // // // Console.WriteLine(); Console.WriteLine(" Print all entries sorted by a date.txt created. "); // // Create "Print the latest entry.txt" // // // Create new entry // string line = string.Empty; foreach (string a in args) { line+=a; } // StreamWriter w = new StreamWriter("Print the latest entry.txt"); // w.WriteLine(line); // w.Close(); w.Dispose(); // // // Console.WriteLine(); Console.WriteLine(" Print the latest entry.txt created. "); // // Create "Print the latest entry for each category.txt" // string latest_entry = string.Empty; foreach (string a in args) { latest_entry+=a; }   if(!File.Exists("Print the latest entry for each category.txt")) { File.WriteAllText("Print the latest entry for each category.txt",latest_entry); } else { StreamReader r = new StreamReader("Print the latest entry for each category.txt"); // w = new StreamWriter("Print the latest entry for each category 1.txt",true); // line = string.Empty; // while(!r.EndOfStream) { line = r.ReadLine(); if(line.Contains(args[1].ToString())) { w.WriteLine(latest_entry); latest_entry = "ok"; } else { w.WriteLine(line); } } // add new category if(latest_entry != "ok") w.WriteLine(latest_entry); // w.Close(); w.Dispose(); // r.Close(); r.Dispose(); // File.Copy("Print the latest entry for each category 1.txt", "Print the latest entry for each category.txt",true); // File.Delete("Print the latest entry for each category 1.txt"); // // // Console.WriteLine(); Console.WriteLine(" Print the latest entry for each category.txt created. "); Console.WriteLine(); } }   static void Print_Document(string file_name) { // // Print document // Console.WriteLine(); Console.WriteLine(file_name.Replace(".txt","")+ " : "); Console.WriteLine(); // StreamReader r = new StreamReader(file_name); // string line = string.Empty; // line = r.ReadToEnd(); // Console.WriteLine(line); // r.Close(); r.Dispose(); // // // } } }  
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#C.23
C#
public class ShortestCommonSupersequence { Dictionary<(string, string), string> cache = new();   public string scs(string x, string y) { if (x.Length == 0) return y; if (y.Length == 0) return x;   if (cache.TryGetValue((x, y), out var result)) return result;   if (x[0] == y[0]) { return cache[(x, y)] = x[0] + scs(x.Substring(1), y.Substring(1)); }   var xr = scs(x.Substring(1), y); var yr = scs(x, y.Substring(1)); if (yr.Length <= xr.Length) { return cache[(x, y)] = y[0] + yr; } else { return cache[(x, y)] = x[0] + xr; } }   public static void Main(string[] args) { var scs = new ShortestCommonSupersequence(); Console.WriteLine(scs.scs("abcbdab", "bdcaba")); } }  
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#FutureBasic
FutureBasic
window 1   print date$ print date$("d MMM yyyy") print date$("EEE, MMM d, yyyy") print date$("MMMM d, yyyy ") print date$("MMMM d, yyyy G") print "This is day ";date$("D");" of the year" print print time$ print time$("hh:mm:ss") print time$("h:mm a") print time$("h:mm a zzz") print print time$("h:mm a ZZZZ "); date$("MMMM d, yyyy G")   HandleEvents
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Go
Go
package main import ("fmt"; "time")   func main() { fmt.Println(time.Time{}) }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Groovy
Groovy
def date = new Date(0) def format = new java.text.SimpleDateFormat('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ') format.timeZone = TimeZone.getTimeZone('UTC') println (format.format(date))
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Raku
Raku
constant $sides = 5; constant order = 5; constant $dim = 250; constant scaling-factor = ( 3 - 5**.5 ) / 2; my @orders = ((1 - scaling-factor) * $dim) «*» scaling-factor «**» (^order);   my $fh = open('sierpinski_pentagon.svg', :w);   $fh.say: qq|<svg height="{$dim*2}" width="{$dim*2}" style="fill:blue" version="1.1" xmlns="http://www.w3.org/2000/svg">|;   my @vertices = map { cis( $_ * τ / $sides ) }, ^$sides;   for 0 ..^ $sides ** order -> $i { my $vector = [+] @vertices[$i.base($sides).fmt("%{order}d").comb] «*» @orders; $fh.say: pgon ((@orders[*-1] * (1 - scaling-factor)) «*» @vertices «+» $vector)».reals».fmt("%0.3f"); };   sub pgon (@q) { qq|<polygon points="{@q}" transform="translate({$dim},{$dim}) rotate(-18)"/>| }   $fh.say: '</svg>'; $fh.close;
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Common_Lisp
Common Lisp
(defun print-sierpinski (order) (loop with size = (expt 2 order) repeat size for v = (expt 2 (1- size)) then (logxor (ash v -1) (ash v 1)) do (fresh-line) (loop for i below (integer-length v) do (princ (if (logbitp i v) "*" " ")))))
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#PicoLisp
PicoLisp
(de sierpinski (N) (let (D '("1") S "0") (do N (setq D (conc (mapcar '((X) (pack S X S)) D) (mapcar '((X) (pack X "0" X)) D) ) S (pack S S) ) ) D ) )   (out '(display -) (let Img (sierpinski 7) (prinl "P1") (prinl (length (car Img)) " " (length Img)) (mapc prinl Img) ) )  
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#PostScript
PostScript
%!PS   /sierp { % level ax ay bx by cx cy 6 cpy triangle sierpr } bind def   /sierpr { 12 cpy 10 -4 2 { 5 1 roll exch 4 -1 roll add 0.5 mul 3 1 roll add 0.5 mul 3 -1 roll 2 roll } for  % l a b c bc ac ab 13 -1 roll dup 0 gt { 1 sub dup 4 cpy 18 -2 roll sierpr dup 7 index 7 index 2 cpy 16 -2 roll sierpr 9 3 roll 1 index 1 index 2 cpy 13 4 roll sierpr } { 13 -6 roll 7 { pop } repeat } ifelse triangle } bind def   /cpy { { 5 index } repeat } bind def   /triangle { newpath moveto lineto lineto closepath stroke } bind def   6 50 100 550 100 300 533 sierp showpage
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#11l
11l
F sierpinski_carpet(n) V carpet = [String(‘#’)] L 1..n carpet = carpet.map(x -> x‘’x‘’x) [+] carpet.map(x -> x‘’x.replace(‘#’, ‘ ’)‘’x) [+] carpet.map(x -> x‘’x‘’x) R carpet.join("\n")   print(sierpinski_carpet(3))
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. simple-database.   ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT OPTIONAL database-file ASSIGN Database-Path ORGANIZATION INDEXED ACCESS SEQUENTIAL RECORD KEY data-title ALTERNATE RECORD KEY data-tag WITH DUPLICATES ALTERNATE RECORD KEY date-added WITH DUPLICATES FILE STATUS file-status . DATA DIVISION. FILE SECTION. FD database-file. 01 database-record. *> Date is in YYYYMMDD format. 03 date-added PIC 9(8). 03 data-tag PIC X(20). 03 data-title PIC X(50). 03 data-contents PIC X(200). *> Adding extra space is considered good style so the record *> can be expanded in the future. 03 FILLER PIC X(50).   WORKING-STORAGE SECTION. 78 Database-Path VALUE "database.dat".   01 file-status PIC XX. 88 file-ok VALUE "00". 88 duplicate-key VALUE "22". 88 key-not-found VALUE "23".   01 num-args PIC 99.   01 action PIC XX. 88 create-entry VALUE "-c". 88 remove-entry VALUE "-r". 88 find-entry VALUE "-f". 88 print-latest VALUE "-l". 88 print-database VALUES "-a", "-d", "-t". *> Printed by title. 88 print-by-title VALUE "-a". 88 print-by-date VALUE "-d". 88 print-by-tag VALUE "-t". 88 print-help VALUES "-h", SPACES.   01 read-direction-flag PIC X VALUE SPACE. 88 read-backwards VALUE "B".   01 edited-date PIC 9(4)/99/99. PROCEDURE DIVISION. DECLARATIVES. database-file-error SECTION. USE AFTER ERROR ON database-file   DISPLAY "An error has occurred while using " Database-Path ". Error no. " file-status DISPLAY "The program will terminate."   CLOSE database-file   GOBACK . END DECLARATIVES.   main-line. DISPLAY 1 UPON ARGUMENT-NUMBER ACCEPT action FROM ARGUMENT-VALUE   ACCEPT num-args FROM ARGUMENT-NUMBER   EVALUATE TRUE WHEN create-entry IF num-args >= 4 PERFORM write-entry ELSE DISPLAY "-a requires arguments to enter in the " "database. See help (-h) for details." END-IF   WHEN remove-entry IF num-args >= 2 PERFORM delete-entry ELSE DISPLAY "-r requires the title of the entry to " "delete." END-IF   WHEN find-entry IF num-args >= 2 PERFORM display-specified-entry ELSE DISPLAY "-f requires the title of the entry to " "find." END-IF   WHEN print-latest PERFORM show-latest   WHEN print-database PERFORM show-database   WHEN print-help PERFORM show-general-help   WHEN OTHER DISPLAY action " is not a valid option." END-EVALUATE   GOBACK . write-entry. OPEN EXTEND database-file   DISPLAY 2 UPON ARGUMENT-NUMBER ACCEPT data-tag FROM ARGUMENT-VALUE DISPLAY 3 UPON ARGUMENT-NUMBER ACCEPT data-title FROM ARGUMENT-VALUE IF data-title = SPACES DISPLAY "The title cannot be blank." PERFORM close-and-terminate END-IF   DISPLAY 4 UPON ARGUMENT-NUMBER ACCEPT data-contents FROM ARGUMENT-VALUE   ACCEPT date-added FROM DATE YYYYMMDD   WRITE database-record INVALID KEY IF duplicate-key DISPLAY "An entry in the database already has " "that title. Please choose a different " "title or remove the entry." ELSE PERFORM database-file-error END-IF END-WRITE   PERFORM close-database . delete-entry. PERFORM get-title-arg OPEN I-O database-file PERFORM read-title   DELETE database-file   PERFORM close-database . display-specified-entry. PERFORM get-title-arg OPEN INPUT database-file PERFORM read-title   PERFORM show-record   PERFORM close-database . get-title-arg. DISPLAY 2 UPON ARGUMENT-NUMBER ACCEPT data-title FROM ARGUMENT-VALUE . read-title. START database-file KEY IS = data-title INVALID KEY IF key-not-found DISPLAY "An entry with that title was not found." PERFORM close-and-terminate ELSE PERFORM database-file-error END-IF END-START   READ database-file . close-and-terminate. PERFORM close-database GOBACK . show-latest. OPEN INPUT database-file   PERFORM start-at-last-date READ database-file PERFORM show-record   PERFORM close-database . show-database. OPEN INPUT database-file   EVALUATE TRUE WHEN print-by-title *> Primary key is the title. CONTINUE WHEN print-by-tag MOVE LOW-VALUES TO data-tag START database-file KEY IS > data-tag WHEN print-by-date PERFORM start-at-last-date SET read-backwards TO TRUE END-EVALUATE   PERFORM FOREVER *> The problem with statements instead of functions... IF NOT read-backwards READ database-file NEXT AT END EXIT PERFORM END-READ ELSE READ database-file PREVIOUS AT END EXIT PERFORM END-READ END-IF   PERFORM show-record DISPLAY SPACE END-PERFORM   PERFORM close-database . start-at-last-date. MOVE HIGH-VALUES TO date-added START database-file KEY IS < date-added . close-database. CLOSE database-file . show-record. MOVE date-added TO edited-date DISPLAY "Date added: " edited-date " Tag: " data-tag DISPLAY "Title: " data-title DISPLAY "Contents:" DISPLAY " " FUNCTION TRIM(data-contents) . show-general-help. DISPLAY "Help: Possible options are:" DISPLAY " -a - Show all the entries (sorted by title)." DISPLAY " -c - Create a new entry in the database. -c needs" " further arguments in this format:" DISPLAY ' "tag" "title" "content"' DISPLAY " Max argument sizes (in characters): tag - 20, " "title - 50, content - 200" DISPLAY " The title must be unique and not be blank." DISPLAY " -d - Show all the entries sorted by date added." DISPLAY " -f - Finds and displays entry with the title " "provided. The title should be specified as shown for " "-c." DISPLAY " -h - Show this help menu." DISPLAY " -l - Show the latest entry." DISPLAY " -r - Remove the entry with the title provided. " "The title should be specified as shown for -c." DISPLAY " -t - Show all the entries sorted by tag." .
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#C.2B.2B
C++
#include <iostream>   std::string scs(std::string x, std::string y) { if (x.empty()) { return y; } if (y.empty()) { return x; } if (x[0] == y[0]) { return x[0] + scs(x.substr(1), y.substr(1)); } if (scs(x, y.substr(1)).size() <= scs(x.substr(1), y).size()) { return y[0] + scs(x, y.substr(1)); } else { return x[0] + scs(x.substr(1), y); } }   int main() { auto res = scs("abcbdab", "bdcaba"); std::cout << res << '\n'; return 0; }
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#D
D
import std.stdio, std.functional, std.array, std.range;   dstring scs(in dstring x, in dstring y) nothrow @safe { alias mScs = memoize!scs; if (x.empty) return y; if (y.empty) return x; if (x.front == y.front) return x.front ~ mScs(x.dropOne, y.dropOne); if (mScs(x, y.dropOne).length <= mScs(x.dropOne, y).length) return y.front ~ mScs(x, y.dropOne); else return x.front ~ mScs(x.dropOne, y); }   void main() @safe { scs("abcbdab", "bdcaba").writeln; }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Haskell
Haskell
import System.Time   main = putStrLn $ calendarTimeToString $ toUTCTime $ TOD 0 0
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Icon_and_Unicon
Icon and Unicon
link printf,datetime   procedure main() # Unicon now := gettimeofday().sec if now = &now then printf("&now and gettimeofday().sec are equal\n") printf("Now (UTC) %s, (local) %s\n",gtime(now),ctime(now)) printf("Epoch %s\n",gtime(0)) # Icon and Unicon now := DateToSec(&date) + ClockToSec(&clock) printf("Now is also %s and %s\n",SecToDate(now),SecToDateLine(now)) end
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Ruby
Ruby
  THETA = Math::PI * 2 / 5 SCALE_FACTOR = (3 - Math.sqrt(5)) / 2 MARGIN = 20   attr_reader :pentagons, :renderer def settings size(400, 400) end   def setup sketch_title 'Pentaflake' radius = width / 2 - 2 * MARGIN center = Vec2D.new(radius - 2 * MARGIN, 3 * MARGIN) pentaflake = Pentaflake.new(center, radius, 5) @pentagons = pentaflake.pentagons end   def draw background(255) stroke(0) pentagons.each do |penta| draw_pentagon(penta) end no_loop end   def draw_pentagon(pent) points = pent.vertices begin_shape points.each do |pnt| pnt.to_vertex(renderer) end end_shape(CLOSE) end   def renderer @renderer ||= GfxRender.new(self.g) end     class Pentaflake attr_reader :pentagons   def initialize(center, radius, depth) @pentagons = [] create_pentagons(center, radius, depth) end   def create_pentagons(center, radius, depth) if depth.zero? pentagons << Pentagon.new(center, radius) else radius *= SCALE_FACTOR distance = radius * Math.sin(THETA) * 2 (0..4).each do |idx| x = center.x + Math.cos(idx * THETA) * distance y = center.y + Math.sin(idx * THETA) * distance center = Vec2D.new(x, y) create_pentagons(center, radius, depth - 1) end end end end   class Pentagon attr_reader :center, :radius   def initialize(center, radius) @center = center @radius = radius end   def vertices (0..4).map do |idx| center + Vec2D.new(radius * Math.sin(THETA * idx), radius * Math.cos(THETA * idx)) end end end    
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   var order: uint8 := 4; # default order   # Read order from command line if there is an argument ArgvInit(); var argmt := ArgvNext(); if argmt != 0 as [uint8] then var a: int32; (a, argmt) := AToI(argmt); if a<3 or 7<a then print("Order must be between 3 and 7."); print_nl(); ExitWithError(); end if; order := a as uint8; end if;   var one: uint8 := 1; # shift argument can't be constant... var size: uint8 := one << order;   var y: uint8 := size; while y > 0 loop var x: uint8 := 0; while x < y-1 loop print_char(' '); x := x + 1; end loop; x := 0; while x + y <= size loop if x & (y-1) != 0 then print(" "); else print("* "); end if; x := x + 1; end loop; print_nl(); y := y - 1; end loop;
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Processing
Processing
  PVector [] coord = {new PVector(0, 0), new PVector(150, 300), new PVector(300, 0)};   void setup() { size(400,400); background(32); sierpinski(new PVector(150,150), 8); noLoop(); }   void sierpinski(PVector cPoint, int cDepth) { if (cDepth == 0) { set(50+int(cPoint.x), (height-50)-int(cPoint.y), color(192)); return; } for (int v=0; v<3; v++) { sierpinski(new PVector((cPoint.x+coord[v].x)/2, (cPoint.y+coord[v].y)/2), cDepth-1); } }  
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Prolog
Prolog
sierpinski(N) :- sformat(A, 'Sierpinski order ~w', [N]), new(D, picture(A)), draw_Sierpinski(D, N, point(350,50), 600), send(D, size, size(690,690)), send(D, open).   draw_Sierpinski(Window, 1, point(X, Y), Len) :- X1 is X - round(Len/2), X2 is X + round(Len/2), Y1 is Y + Len * sqrt(3) / 2, send(Window, display, new(Pa, path)), ( send(Pa, append, point(X, Y)), send(Pa, append, point(X1, Y1)), send(Pa, append, point(X2, Y1)), send(Pa, closed, @on), send(Pa, fill_pattern, colour(@default, 0, 0, 0)) ).     draw_Sierpinski(Window, N, point(X, Y), Len) :- Len1 is round(Len/2), X1 is X - round(Len/4), X2 is X + round(Len/4), Y1 is Y + Len * sqrt(3) / 4, N1 is N - 1, draw_Sierpinski(Window, N1, point(X, Y), Len1), draw_Sierpinski(Window, N1, point(X1, Y1), Len1), draw_Sierpinski(Window, N1, point(X2, Y1), Len1).
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Action.21
Action!
BYTE FUNC InCarpet(BYTE x,y) DO IF x MOD 3=1 AND y MOD 3=1 THEN RETURN (0) FI x==/3 y==/3 UNTIL x=0 AND y=0 OD RETURN (1)   PROC DrawCarpet(INT x0 BYTE y0,depth) BYTE i,x,y,size   size=1 FOR i=1 TO depth DO size==*3 OD   FOR y=0 TO size-1 DO FOR x=0 TO size-1 DO IF InCarpet(x,y) THEN Plot(x0+2*x,y0+2*y) Plot(x0+2*x+1,y0+2*y) Plot(x0+2*x+1,y0+2*y+1) Plot(x0+2*x,y0+2*y+1) FI OD OD RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   DrawCarpet(79,15,4)   DO UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#Common_Lisp
Common Lisp
(defvar *db* nil)   (defvar *db-cat* (make-hash-table :test 'equal))   (defvar *db-file* "db.txt")   (defstruct item "this is the unit of data stored/displayed in *db*" (title " ") (category "default") (date (progn (get-universal-time))))   (defun set-category(new-item) (setf (gethash (item-category new-item) *db-cat*) 't))   (defun find-item-in-db (&optional category) (if (null category) (car *db*) (find category *db* :key #'item-category :test #'string=)))   (defun scan-category () "scan categories from an existing database -- after reading it from disk" (dolist (itm *db*) (set-category itm)))   (defun pr-univ-time (utime) (multiple-value-bind (second minute hour date month year day-of-week dst-p tz) (decode-universal-time utime) (declare (ignore day-of-week dst-p tz)) (format nil "~4,'0d-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d" year month date hour minute second)))   (defun pr (&optional (item (find-item-in-db)) (stream t)) "print an item" (when item (format stream "~a: (~a) (~a)~%" (item-title item) (item-category item) (pr-univ-time (item-date item)))))   (defun pr-per-category () "print the latest item from each category" (loop for k being the hash-keys in *db-cat* do (pr (find-item-in-db k))))   (defun pr-all () "print all the items, *db* is sorted by time." (dolist (itm *db*) (pr itm)))   (defun pr-all-categories (&optional (stream t)) (loop for k being the hash-keys in *db-cat* do (format stream "(~a) " k)))   (defun insert-item (item) "insert item into database in a time sorted list. okay for a small list, as per spec." (let ((first-item (car *db*)) (new-itm item)) (set-category new-itm) (push new-itm *db*) (when (and first-item (>= (item-date new-itm) (item-date first-item))) (setf *db* (sort *db* #'> :key #'item-date))) *db*))   (defun read-db-from-file (&optional (file *db-file*)) (with-open-file (in file :if-does-not-exist nil) (when in (with-standard-io-syntax (setf *db* (read in))) (scan-category))))   (defun save-db-to-file (&optional (file *db-file*)) (with-open-file (out file :direction :output :if-exists :supersede) (with-standard-io-syntax (print *db* out))))   (defun del-db () (setf *db* nil) (save-db-to-file))   (defun del-item (itm) (read-db-from-file) (setf *db* (remove itm *db* :key #'item-title :test #'string=)) (save-db-to-file))   (defun add-item-to-db (args) (read-db-from-file) (insert-item (make-item :title (first args) :category (second args))) (save-db-to-file))   (defun help-menu () (format t "clisp db.lisp ~{~15T~a~^~% ~}" '("delete <item-name> ------------------- delete an item" "delete-all --------------------------- delete the database" "insert <item-name> <item-category> --- insert an item with its category" "show --------------------------------- shows the latest inserted item" "show-categories ---------------------- show all categories" "show-all ----------------------------- show all items" "show-per-category -------------------- show the latest item per category")))   (defun db-cmd-run (args) (cond ((and (> (length args) 1) (equal (first args) "delete")) (del-item (second args))) ((equal (first args) "delete-all") (del-db)) ((and (> (length args) 2) (equal (first args) "insert")) (add-item-to-db (rest args))) ((equal (first args) "show") (read-db-from-file) (pr)) ((equal (first args) "show-categories") (read-db-from-file) (pr-all-categories)) ((equal (first args) "show-all") (read-db-from-file) (pr-all)) ((equal (first args) "show-per-category") (read-db-from-file) (pr-per-category)) (t (help-menu))))   ;; modified https://rosettacode.org/wiki/Command-line_arguments#Common_Lisp (defun db-argv () (or #+clisp ext:*args* #+sbcl (cdr sb-ext:*posix-argv*) #+allegro (cdr (sys:command-line-arguments)) #+lispworks (cdr sys:*line-arguments-list*) nil))   (db-cmd-run (db-argv))
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#Elixir
Elixir
defmodule SCS do def scs(u, v) do lcs = LCS.lcs(u, v) |> to_charlist scs(to_charlist(u), to_charlist(v), lcs, []) |> to_string end   defp scs(u, v, [], res), do: Enum.reverse(res) ++ u ++ v defp scs([h|ut], [h|vt], [h|lt], res), do: scs(ut, vt, lt, [h|res]) defp scs([h|_]=u, [vh|vt], [h|_]=lcs, res), do: scs(u, vt, lcs, [vh|res]) defp scs([uh|ut], v, lcs, res), do: scs(ut, v, lcs, [uh|res]) end   u = "abcbdab" v = "bdcaba" IO.puts "SCS(#{u}, #{v}) = #{SCS.scs(u, v)}"
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#Factor
Factor
USING: combinators io kernel locals math memoize sequences ;   MEMO:: scs ( x y -- seq ) { { [ x empty? ] [ y ] } { [ y empty? ] [ x ] } { [ x first y first = ] [ x rest y rest scs x first prefix ] } { [ x y rest scs length x rest y scs length <= ] [ x y rest scs y first prefix ] } [ x rest y scs x first prefix ] } cond ;   "abcbdab" "bdcaba" scs print
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#Go
Go
package main   import ( "fmt" "strings" )   func lcs(x, y string) string { xl, yl := len(x), len(y) if xl == 0 || yl == 0 { return "" } x1, y1 := x[:xl-1], y[:yl-1] if x[xl-1] == y[yl-1] { return fmt.Sprintf("%s%c", lcs(x1, y1), x[xl-1]) } x2, y2 := lcs(x, y1), lcs(x1, y) if len(x2) > len(y2) { return x2 } else { return y2 } }   func scs(u, v string) string { ul, vl := len(u), len(v) lcs := lcs(u, v) ui, vi := 0, 0 var sb strings.Builder for i := 0; i < len(lcs); i++ { for ui < ul && u[ui] != lcs[i] { sb.WriteByte(u[ui]) ui++ } for vi < vl && v[vi] != lcs[i] { sb.WriteByte(v[vi]) vi++ } sb.WriteByte(lcs[i]) ui++ vi++ } if ui < ul { sb.WriteString(u[ui:]) } if vi < vl { sb.WriteString(v[vi:]) } return sb.String() }   func main() { u := "abcbdab" v := "bdcaba" fmt.Println(scs(u, v)) }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#J
J
6!:0'' 2011 8 8 20 25 44.725
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Java
Java
import java.text.DateFormat; import java.util.Date; import java.util.TimeZone;   public class DateTest{ public static void main(String[] args) { Date date = new Date(0); DateFormat format = DateFormat.getDateTimeInstance(); format.setTimeZone(TimeZone.getTimeZone("UTC")); System.out.println(format.format(date)); } }
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Rust
Rust
// [dependencies] // svg = "0.8.0"   fn sierpinski_pentagon( mut document: svg::Document, mut x: f64, mut y: f64, mut side: f64, order: usize, ) -> svg::Document { use std::f64::consts::PI; use svg::node::element::Polygon;   let degrees72 = 0.4 * PI; let mut angle = 3.0 * degrees72; let scale_factor = 1.0 / (2.0 + degrees72.cos() * 2.0);   if order == 1 { let mut points = Vec::new(); points.push((x, y)); for _ in 0..5 { x += angle.cos() * side; y -= angle.sin() * side; angle += degrees72; points.push((x, y)); } let polygon = Polygon::new() .set("fill", "blue") .set("stroke", "black") .set("stroke-width", "1") .set("points", points); document = document.add(polygon); } else { side *= scale_factor; let distance = side + side * degrees72.cos() * 2.0; for _ in 0..5 { x += angle.cos() * distance; y -= angle.sin() * distance; angle += degrees72; document = sierpinski_pentagon(document, x, y, side, order - 1); } } document }   fn write_sierpinski_pentagon(file: &str, size: usize, order: usize) -> std::io::Result<()> { use std::f64::consts::PI; use svg::node::element::Rectangle;   let margin = 5.0; let radius = (size as f64) / 2.0 - 2.0 * margin; let side = radius * (0.2 * PI).sin() * 2.0; let height = side * ((0.2 * PI).sin() + (0.4 * PI).sin()); let x = (size as f64) / 2.0; let y = (size as f64 - height) / 2.0;   let rect = Rectangle::new() .set("width", "100%") .set("height", "100%") .set("fill", "white");   let mut document = svg::Document::new() .set("width", size) .set("height", size) .add(rect);   document = sierpinski_pentagon(document, x, y, side, order); svg::save(file, &document) }   fn main() { write_sierpinski_pentagon("sierpinski_pentagon.svg", 600, 5).unwrap(); }
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Scala
Scala
import java.awt._ import java.awt.event.ActionEvent import java.awt.geom.Path2D   import javax.swing._   import scala.annotation.tailrec import scala.math.{Pi, cos, sin, sqrt}   object SierpinskiPentagon extends App { SwingUtilities.invokeLater(() => {   class SierpinskiPentagon extends JPanel {   /* Try to avoid random color values clumping together */   private var hue = math.random   // exterior angle private val deg072 = 2 * Pi / 5d //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. */ //private val scaleFactor = 1 / (2 + cos(deg072) * 2) private var limit = 0   private def drawPentagon(g: Graphics2D, x: Double, y: Double, side: Double, depth: Int): Unit = { val scaleFactor = 1 / (2 + cos(deg072) * 2)   if (depth == 0) { // draw from the top @tailrec def iter0(i: Int, x: Double, y: Double, angle: Double, p: Path2D.Double): Path2D.Double = { if (i < 0) p else { p.lineTo(x, y) iter0(i - 1, x + cos(angle) * side, y - sin(angle) * side, angle + deg072, p) } }   def p1: Path2D.Double = iter0(4, x, y, 3 * deg072, { val p = new Path2D.Double p.moveTo(x, y) p })   def p: Path2D.Double = iter0(4, x, y, 3 * deg072, p1)   def next: Color = { hue = (hue + (sqrt(5) - 1) / 2) % 1 Color.getHSBColor(hue.toFloat, 1, 1) }   g.setColor(next) g.fill(p) } else { val _side = 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 * cos(deg072) * 2 /* The top positions form a virtual pentagon of their own, so simply move from one to the other by changing direction. */   def iter1(i: Int, x: Double, y: Double, angle: Double): Unit = { if (i < 0) () else { drawPentagon(g, x, y, _side, depth - 1) iter1(i - 1, x + cos(angle) * distance, y - sin(angle) * distance, angle + deg072) } }   iter1(4, x + cos(3 * deg072) * distance, y - sin(3 * deg072) * distance, 4 * deg072) } }   override def paintComponent(gg: Graphics): Unit = { val (g, margin) = (gg.asInstanceOf[Graphics2D], 20) val side = (getWidth / 2 - 2 * margin) * sin(Pi / 5) * 2   super.paintComponent(gg) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawPentagon(g, getWidth / 2, 3 * margin, side, limit) }   new Timer(3000, (_: ActionEvent) => { limit += 1 if (limit >= 5) limit = 0 repaint() }).start()   setPreferredSize(new Dimension(640, 640)) setBackground(Color.white) }   val f = new JFrame("Sierpinski Pentagon") { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) setResizable(true) add(new SierpinskiPentagon, BorderLayout.CENTER) pack() setLocationRelativeTo(null) setVisible(true) } })   }
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#D
D
void main() /*@safe*/ { import std.stdio, std.algorithm, std.string, std.array;   enum level = 4; auto d = ["*"]; foreach (immutable n; 0 .. level) { immutable sp = " ".replicate(2 ^^ n); d = d.map!(a => sp ~ a ~ sp).array ~ d.map!(a => a ~ " " ~ a).array; } d.join('\n').writeln; }
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Python
Python
  # a very simple version import turtle as t def sier(n,length): if n == 0: return for i in range(3): sier(n - 1, length / 2) t.fd(length) t.rt(120)  
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Sierpinski_Carpet is subtype Index_Type is Integer range 1..81; type Pattern_Array is array(Index_Type range <>, Index_Type range <>) of Boolean; Pattern : Pattern_Array(1..81,1..81) := (Others =>(others => true)); procedure Clear_Center(P : in out Pattern_Array; X1 : Index_Type; X2 : Index_Type; Y1 : Index_Type; Y2 : Index_Type) is Xfirst : Index_Type; Xlast  : Index_Type; Yfirst : Index_Type; Ylast  : Index_Type; Diff  : Integer; begin Xfirst :=(X2 - X1 + 1) / 3 + X1; Diff := Xfirst - X1; Xlast  := Xfirst + Diff; Yfirst := (Y2 - Y1) / 3 + Y1; YLast  := YFirst + Diff;   for I in XFirst..XLast loop for J in YFirst..YLast loop P(I, J) := False; end loop; end loop; end Clear_Center;   procedure Print(P : Pattern_Array) is begin for I in P'range(1) loop for J in P'range(2) loop if P(I,J) then Put('*'); else Put(' '); end if; end loop; New_Line; end loop; end Print;   procedure Divide_Square(P : in out Pattern_Array; Order : Positive) is Factor : Natural := 0; X1, X2 : Index_Type; Y1, Y2  : Index_Type; Division : Index_Type; Num_Sections : Index_Type; begin while Factor < Order loop Num_Sections := 3**Factor; Factor := Factor + 1; X1  := P'First; Division  := P'Last / Num_Sections; X2 := Division; Y1 := X1; Y2 := X2; loop loop Clear_Center(P, X1, X2, Y1, Y2); exit when X2 = P'Last; X1 := X2; X2 := X2 + Division; end loop; exit when Y2 = P'Last; Y1 := Y2; Y2 := Y2 + Division; X1 := P'First; X2 := Division; end loop; end loop; end Divide_Square;   begin Divide_Square(Pattern, 3); Print(Pattern); end Sierpinski_Carpet;
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#D
D
import std.stdio, std.algorithm, std.string, std.conv, std.array, std.file, std.csv, std.datetime;   private { immutable filename = "simdb.csv";   struct Item { string name, date, category; }   void addItem(in string[] item) { if (item.length < 3) return printUsage(); auto db = load(); const date = (cast(DateTime)Clock.currTime).toISOExtString; const cat = (item.length == 4) ? item[3] : "none"; db ~= Item(item[2], date, cat); store(db); }   void printLatest(in string[] a) { auto db = load(); if (db.empty) return writeln("No entries in database."); db.sort!q{ a.date > b.date }; if (a.length == 3) { foreach (item; db) if (item.category == a[2]) writefln("%s, %s, %s", item.tupleof); } else { writefln("%s, %s, %s", db[0].tupleof); } }   void printAll() { auto db = load(); if (db.empty) return writeln("No entries in database."); db.sort!q{ a.date < b.date }; foreach (item; db) writefln("%s, %s, %s", item.tupleof); }   Item[] load() { Item[] db; if (filename.exists && filename.isFile) { try { const text = filename.readText; if (!text.empty) db = csvReader!Item(text).array; } catch (CSVException e) { writeln(e.msg); } } return db; }   void store(in Item[] db) { auto f = File(filename, "w+"); foreach (item; db) f.writefln("%s,%s,%s", item.tupleof); }   void printUsage() { writeln( `Usage: simdb cmd [categoryName]   add add item, followed by optional category latest print last added item(s), followed by optional category all print all   For instance: add "some item name" "some category name"`); } }   void main(in string[] args) { if (args.length < 2 || args.length > 4) return printUsage();   switch (args[1].toLower) { case "add": addItem(args); break; case "latest": printLatest(args); break; case "all": printAll(); break; default: printUsage(); break; } }
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#Haskell
Haskell
scs :: Eq a => [a] -> [a] -> [a] scs [] ys = ys scs xs [] = xs scs xss@(x:xs) yss@(y:ys) | x == y = x : scs xs ys | otherwise = ws where us = scs xs yss vs = scs xss ys ws | length us < length vs = x : us | otherwise = y : vs   main = putStrLn $ scs "abcbdab" "bdcaba"
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#Java
Java
public class ShortestCommonSuperSequence { private static boolean isEmpty(String s) { return null == s || s.isEmpty(); }   private static String scs(String x, String y) { if (isEmpty(x)) { return y; } if (isEmpty(y)) { return x; }   if (x.charAt(0) == y.charAt(0)) { return x.charAt(0) + scs(x.substring(1), y.substring(1)); }   if (scs(x, y.substring(1)).length() <= scs(x.substring(1), y).length()) { return y.charAt(0) + scs(x, y.substring(1)); } else { return x.charAt(0) + scs(x.substring(1), y); } }   public static void main(String[] args) { System.out.println(scs("abcbdab", "bdcaba")); } }
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#JavaScript
JavaScript
document.write(new Date(0).toUTCString());
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#jq
jq
0 | todate
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible. Related task   Date format
#Julia
Julia
using Base.Dates # just using Dates in versions > 0.6 println("Time zero (the epoch) is $(unix2datetime(0)).")
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Sidef
Sidef
define order = 5 define sides = 5 define dim = 500 define scaling_factor = ((3 - 5**0.5) / 2) var orders = order.of {|i| ((1-scaling_factor) * dim) * scaling_factor**i }   say <<"STOP"; <?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg height="#{dim*2}" width="#{dim*2}" style="fill:blue" transform="translate(#{dim},#{dim}) rotate(-18)" version="1.1" xmlns="http://www.w3.org/2000/svg"> STOP   var vertices = sides.of {|i| Complex(0, i * Number.tau / sides).exp }   for i in ^(sides**order) { var vector = ([vertices["%#{order}d" % i.base(sides) -> chars]] »*« orders «+») var points = (vertices »*» orders[-1]*(1-scaling_factor) »+» vector »reals()» «%« '%0.3f') say ('<polygon points="' + points.join(' ') + '"/>') }   say '</svg>'
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Related tasks Sierpinski triangle/Graphical for graphics images of this pattern. Sierpinski carpet
#Delphi
Delphi
program SierpinskiTriangle;   {$APPTYPE CONSOLE}   procedure PrintSierpinski(order: Integer); var x, y, size: Integer; begin size := (1 shl order) - 1; for y := size downto 0 do begin Write(StringOfChar(' ', y)); for x := 0 to size - y do begin if (x and y) = 0 then Write('* ') else Write(' '); end; Writeln; end; end;   begin PrintSierpinski(4); end.
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ 1 & ] is odd ( n --> b )   [ 4 times [ 2dup walk 1 4 turn ] 2drop ] is square ( n/d --> )   [ dup witheach [ odd if [ ' [ 0 0 0 ] fill [ 2 1 square ] ] 2 1 fly ] size -2 * 1 fly 1 4 turn 2 1 fly -1 4 turn ] is showline ( [ --> )   [ [] 0 rot 0 join witheach [ tuck + rot join swap ] drop ] is nextline ( [ --> [ )   [ ' [ 1 ] swap bit 1 - times [ dup showline nextline ] showline ] is sierpinski ( n --> )   turtle 5 8 turn 400 1 fly 3 8 turn 8 sierpinski
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#R
R
  ## Plotting Sierpinski triangle. aev 4/1/17 ## ord - order, fn - file name, ttl - plot title, clr - color pSierpinskiT <- function(ord, fn="", ttl="", clr="navy") { m=640; abbr="STR"; dftt="Sierpinski triangle"; n=2^ord; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE); cat(" *** START", abbr, date(), "\n"); if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")}; if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord); cat(" *** Plot file:", pf,".png", "title:", ttl, "\n"); for(y in 1:n) { for(x in 1:n) { if(bitwAnd(x, y)==0) {M[x,y]=1} ##if(bitwAnd(x, y)>0) {M[x,y]=1} ## Try this for "reversed" ST }} plotmat(M, pf, clr, ttl); cat(" *** END", abbr, date(), "\n"); } ## Executing: pSierpinskiT(6,,,"red"); pSierpinskiT(8);  
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### ######### ######### # ## ## # # ## ## # ######### ######### ### ### ### ### # # # # # # # # ### ### ### ### ######### ######### # ## ## # # ## ## # ######### ######### ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ###### ### ########################### # ## ## ## ## ## ## ## ## # ########################### The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters. Related task   Sierpinski triangle
#ALGOL_68
ALGOL 68
PROC in carpet = (INT in x, in y)BOOL: ( INT x := in x, y := in y; BOOL out; DO IF x = 0 OR y = 0 THEN out := TRUE; GO TO stop iteration ELIF x MOD 3 = 1 AND y MOD 3 = 1 THEN out := FALSE; GO TO stop iteration FI;   x %:= 3; y %:= 3 OD; stop iteration: out );   PROC carpet = (INT n)VOID: FOR i TO 3 ** n DO FOR j TO 3 ** n DO IF in carpet(i-1, j-1) THEN print("* ") ELSE print(" ") FI OD; print(new line) OD;   carpet(3)
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points: (3,4), (5,11), (12,8), (9,5), and (5,6) Show the answer here, on this page.
#11l
11l
F area_by_shoelace(x, y) R abs(sum(zip(x, y[1..] [+] y[0.<1]).map((i, j) -> i * j)) -sum(zip(x[1..] [+] x[0.<1], y).map((i, j) -> i * j))) / 2   V points = [(3, 4), (5, 11), (12, 8), (9, 5), (5, 6)] V x = points.map(p -> p[0]) V y = points.map(p -> p[1])   print(area_by_shoelace(x, y))
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc. You should track the following details: A description of the item. (e.g., title, name) A category or tag (genre, topic, relationship such as “friend” or “family”) A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually Other optional fields The command should support the following Command-line arguments to run: Add a new entry Print the latest entry Print the latest entry for each category Print all entries sorted by a date The category may be realized as a tag or as structure (by making all entries in that category subitems) The file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:   JSON   S-Expressions   YAML   others Related task   Take notes on the command line
#Erlang
Erlang
  #! /usr/bin/env escript   -compile({no_auto_import,[date/0]}).   main( ["add", Tag | Descriptions] ) -> add( date(), Tag, Descriptions ); main( ["add_date", Date, Tag | Descriptions] ) -> add( date_internal(string:tokens(Date, "-")), Tag, Descriptions ); main( ["print_latest"] ) -> print_latest( contents() ); main( ["print_latest_for_each"] ) -> print_latest_for_each( contents() ); main( ["print_all_date", Date] ) -> print_all_date( date_internal(string:tokens(Date, "-")), contents() ); main( _Error ) -> usage().       add( Date, Tag, Descriptions ) -> Contents = contents(), file:write_file( file(), io_lib:format("simple_database_v1.~n~p.~n", [[{Date, Tag, Descriptions} | Contents]]) ).   date() -> {{Date, _Time}} = calendar:local_time(), Date.   date_external( {Year, Month, Day} ) -> string:join( [erlang:integer_to_list(Year), erlang:integer_to_list(Month), erlang:integer_to_list(Day)], "-" ); date_external( _Error ) -> usage().   date_internal( [Year, Month, Day] ) -> {erlang:list_to_integer(Year), erlang:list_to_integer(Month), erlang:list_to_integer(Day)}; date_internal( _Error ) -> usage().   file() -> "simple_database_contents".   contents() -> contents( file:consult(file()) ).   contents( {ok, [simple_database_v1, Contents]} ) -> Contents; contents( {error, Error} ) when is_atom(Error) -> []; contents( {error, _Error} ) -> io:fwrite( "Error: ~p corrupt. Starting from scratch~n", [file()] ), [].   print_all_date( _Date, [] ) -> ok; print_all_date( Date, Contents ) -> [print_latest([{D, Tag, Descriptions}]) || {D, Tag, Descriptions} <- Contents, D =:= Date].   print_latest( [] ) -> ok; print_latest( [{Date, Tag, Descriptions} | _T] ) -> io:fwrite( "~s~n", [string:join( [date_external(Date), Tag | Descriptions], " ")] ).   print_latest_for_each( [] ) -> ok; print_latest_for_each( Contents ) -> Tags = lists:usort( [Tag || {_Date, Tag, _Descriptions} <- Contents] ), [print_latest([lists:keyfind(X, 2, Contents)]) || X <- Tags].   usage() -> io:fwrite( "Usage: ~p [add | add_date <date>] tag description ...~n", [escript:script_name()] ), io:fwrite( "Or: ~p [print_latest | print_latest_for_each | print_all_date <date>]~n", [escript:script_name()] ), io:fwrite( "Date format is YYYY-MM-DD~n" ), io:fwrite( "Data stored in ~p~n", [file()] ), init:stop().  
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , which is the shortest common super-sequence of u {\displaystyle u} and v {\displaystyle v} where both u {\displaystyle u} and v {\displaystyle v} are a subsequence of s {\displaystyle s} . Defined as such, s {\displaystyle s} is not necessarily unique. Demonstrate this by printing s {\displaystyle s} where u = {\displaystyle u=} “abcbdab” and v = {\displaystyle v=} “bdcaba”. Also see Wikipedia: shortest common supersequence
#jq
jq
# largest common substring # Uses recursion, taking advantage of jq's TCO def lcs: . as [$x, $y] | if ($x|length == 0) or ($y|length == 0) then "" else $x[:-1] as $x1 | $y[:-1] as $y1 | if $x[-1:] == $y[-1:] then ([$x1, $y1] | lcs) + $x[-1:] else ([$x, $y1] | lcs) as $x2 | ([$x1, $y] | lcs) as $y2 | if ($x2|length) > ($y2|length) then $x2 else $y2 end end end;   def scs: def eq($s;$i; $t;$j): $s[$i:$i+1] == $t[$j:$j+1];   . as [$u, $v] | lcs as $lcs | reduce range(0; $lcs|length) as $i ( { ui: 0, vi: 0, sb: "" }; until( .ui == ($u|length) or eq($u;.ui; $lcs;$i); .ui as $ui | .sb += $u[$ui:$ui+1] | .ui += 1 ) | until(.vi == ($v|length) or eq($v;.vi; $lcs;$i); .vi as $vi | .sb += $v[$vi:$vi+1] | .vi += 1 ) | .sb += $lcs[$i:$i+1] | .ui += 1 | .vi += 1 ) | if .ui < ($u|length) then .sb = .sb + $u[.ui:] else . end | if .vi < ($v|length) then .sb = .sb + $v[.vi:] else . end | .sb ;   [ "abcbdab", "bdcaba" ] | scs