code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
package main import "time" import "fmt" func main() { fmt.Print("Enter number of seconds to sleep: ") var sec float64 fmt.Scanf("%f", &sec) fmt.Print("Sleeping") time.Sleep(time.Duration(sec * float64(time.Second))) fmt.Println("\nAwake!") }
271Sleep
0go
fx9d0
def sleepTest = { println("Sleeping...") sleep(it) println("Awake!") }
271Sleep
7groovy
8pz0b
package SSL_Node; use strict; use Class::Tiny qw( val next ); sub BUILD { my $self = shift; exists($self->{val}) or die "Must supply 'val'"; if (exists $self->{next}) { ref($self->{next}) eq 'SSL_Node' or die "If supplied, 'next' must be an SSL_Node"; } return; } package main; use strict; my @vals = 1 .. 10; my $countdown = SSL_Node->new(val => shift(@vals)); while (@vals) { my $head = SSL_Node->new(val => shift(@vals), next => $countdown); $countdown = $head; } my $node = $countdown; while ($node) { print $node->val, "... "; $node = $node->next; } print "\n";
269Singly-linked list/Traversal
2perl
4y15d
def chain_insert(lst, at, item): while lst is not None: if lst[0] == at: lst[1] = [item, lst[1]] return else: lst = lst[1] raise ValueError(str(at) + ) chain = ['A', ['B', None]] chain_insert(chain, 'A', 'C') print chain
270Singly-linked list/Element insertion
3python
30vzc
import Control.Concurrent main = do seconds <- readLn putStrLn "Sleeping..." threadDelay $ round $ seconds * 1000000 putStrLn "Awake!"
271Sleep
8haskell
4yb5s
for node in lst: print node.value
269Singly-linked list/Traversal
3python
gma4h
class ListNode def insert_after(search_value, new_value) if search_value == value self.succ = self.class.new(new_value, succ) elsif self.succ.nil? raise StandardError, else self.succ.insert_after(search_value, new_value) end end end list = ListNode.new(:a, ListNode.new(:b)) list.insert_after(:a, :c)
270Singly-linked list/Element insertion
14ruby
yo56n
impl<T> List<T> { pub fn new() -> Self { List { head: None } } pub fn push(&mut self, elem: T) { let new_node = Box::new(Node { elem: elem, next: self.head.take(), }); self.head = Some(new_node); }
270Singly-linked list/Element insertion
15rust
mi4ya
import java.util.InputMismatchException; import java.util.Scanner; public class Sleep { public static void main(final String[] args) throws InterruptedException { try { int ms = new Scanner(System.in).nextInt();
271Sleep
9java
cdg9h
<script> setTimeout(function () { document.write('Awake!') }, prompt("Number of milliseconds to sleep")); document.write('Sleeping... '); </script>
271Sleep
10javascript
56kur
object List { def add[A](as: List[A], a: A): List[A] = Cons(a, as) }
270Singly-linked list/Element insertion
16scala
lf7cq
package main import ( "github.com/fogleman/gg" "github.com/trubitsyn/go-lindenmayer" "log" "math" ) const twoPi = 2 * math.Pi var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h, theta float64 func main() { dc.SetRGB(0, 0, 1)
273Sierpinski square curve
0go
gmk4n
null
271Sleep
11kotlin
302z5
import java.io.*; public class SierpinskiSquareCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("sierpinski_square.svg"))) { SierpinskiSquareCurve s = new SierpinskiSquareCurve(writer); int size = 635, length = 5; s.currentAngle = 0; s.currentX = (size - length)/2; s.currentY = length; s.lineLength = length; s.begin(size); s.execute(rewrite(5)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } } private SierpinskiSquareCurve(final Writer writer) { this.writer = writer; } private void begin(final int size) throws IOException { write("<svg xmlns='http:
273Sierpinski square curve
9java
14qp2
head = ListNode.new(, ListNode.new(, ListNode.new())) head.insertAfter(, ) head.each {|node| print node.value, } puts current = head begin print current.value, end while current = current.succ puts
269Singly-linked list/Traversal
14ruby
7cwri
package main import ( "fmt" "github.com/mattn/go-gtk/gtk" ) func main() { gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.SetTitle("Click me") label := gtk.NewLabel("There have been no clicks yet") var clicks int button := gtk.NewButtonWithLabel("click me") button.Clicked(func() { clicks++ if clicks == 1 { label.SetLabel("Button clicked 1 time") } else { label.SetLabel(fmt.Sprintf("Button clicked%d times", clicks)) } }) vbox := gtk.NewVBox(false, 1) vbox.Add(label) vbox.Add(button) window.Add(vbox) window.Connect("destroy", func() { gtk.MainQuit() }) window.ShowAll() gtk.Main() }
272Simple windowed application
0go
miuyi
null
269Singly-linked list/Traversal
15rust
jlx72
def traverse[A](as: List[A]): Unit = as match { case Nil => print("End") case Cons(h, t) => { print(h + " ") traverse(t) } }
269Singly-linked list/Traversal
16scala
bu0k6
use strict; use warnings; use SVG; use List::Util qw(max min); use constant pi => 2 * atan2(1, 0); my $rule = 'XF-F+F-XF+F+XF-F+F-X'; my $S = 'F+F+XF+F+XF'; $S =~ s/X/$rule/g for 1..5; my (@X, @Y); my ($x, $y) = (0, 0); my $theta = pi/4; my $r = 6; for (split //, $S) { if (/F/) { push @X, sprintf "%.0f", $x; push @Y, sprintf "%.0f", $y; $x += $r * cos($theta); $y += $r * sin($theta); } elsif (/\+/) { $theta += pi/2; } elsif (/\-/) { $theta -= pi/2; } } my ($xrng, $yrng) = ( max(@X) - min(@X), max(@Y) - min(@Y)); my ($xt, $yt) = (-min(@X) + 10, -min(@Y) + 10); my $svg = SVG->new(width=>$xrng+20, height=>$yrng+20); my $points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline'); $svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'}); $svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)"); open my $fh, '>', 'sierpinski-square-curve.svg'; print $fh $svg->xmlify(-namespace=>'svg'); close $fh;
273Sierpinski square curve
2perl
tqmfg
import groovy.swing.SwingBuilder count = 0 new SwingBuilder().edt { frame(title:'Click frame', pack: true, show: true) { vbox { countLabel = label("There have been no clicks yet.") button('Click Me', actionPerformed: {count++; countLabel.text = "Clicked ${count} time(s)."}) } } }
272Simple windowed application
7groovy
tq9fh
import Graphics.UI.Gtk import Data.IORef main :: IO () main = do initGUI window <- windowNew window `onDestroy` mainQuit windowSetTitle window "Simple Windowed App" set window [ containerBorderWidth:= 10 ] hbox <- hBoxNew True 5 set window [ containerChild:= hbox ] lab <- labelNew (Just "There have been no clicks yet") button <- buttonNewWithLabel "Click me" set hbox [ containerChild:= lab ] set hbox [ containerChild:= button ] m <- newIORef 0 onClicked button $ do v <- readIORef m writeIORef m (v+1) set lab [ labelText:= "There have been " ++ show (v+1) ++ " clicks" ] widgetShowAll window mainGUI
272Simple windowed application
8haskell
kvwh0
local socket = require("socket") io.write("Input a number of seconds to sleep: ") local input = io.read("*number") print("Sleeping") socket.sleep(input) print("Awake!")
271Sleep
1lua
68v39
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = for c in axiom: if c in rules: a2 += rules[c] else: a2 += c axiom = a2 return axiom def draw_lsystem(axiom, rules, angle, iterations): xp = [1] yp = [1] direction = 0 for c in expand(axiom, rules, iterations): if c == : xn, yn = nextPoint(xp[-1], yp[-1], direction) xp.append(xn) yp.append(yn) elif c == : direction = direction - angle if direction < 0: direction = 360 + direction elif c == : direction = (direction + angle)% 360 plt.plot(xp, yp) plt.show() if __name__ == '__main__': s_axiom = s_rules = {: } s_angle = 90 draw_lsystem(s_axiom, s_rules, s_angle, 3)
273Sierpinski square curve
3python
zs9tt
null
273Sierpinski square curve
15rust
yo268
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class Clicks extends JFrame{ private long clicks = 0; public Clicks(){ super("Clicks");
272Simple windowed application
9java
4yk58
<html> <head> <title>Simple Window Application</title> </head> <body> <br> &nbsp &nbsp &nbsp &nbsp <script type="text/javascript"> var box = document.createElement('input') box.style.position = 'absolute';
272Simple windowed application
10javascript
h2ejh
null
272Simple windowed application
11kotlin
lfgcp
require"iuplua" l = iup.label{title="There have been no clicks yet."} b = iup.button{title="Click me!"} clicks = 0 function b:button_cb() clicks = clicks + 1 l.title = "There have been " .. clicks/2 .. " clicks so far."
272Simple windowed application
1lua
2trl3
typedef struct cursor_tag { double x; double y; int angle; } cursor_t; void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; } void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, , cursor->x, cursor->y); } void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } } void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, , size, size); fprintf(out, ); fprintf(out, ); fprintf(out, , cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, ); } int main(int argc, char** argv) { const char* filename = ; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, ); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
274Sierpinski arrowhead curve
5c
vzg2o
$seconds = <>; print "Sleeping...\n"; sleep $seconds; print "Awake!\n";
271Sleep
2perl
p5sb0
$seconds = 42; echo ; sleep($seconds); echo ;
271Sleep
12php
you61
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) iy = 1.0 theta = 0 ) var cx, cy, h float64 func arrowhead(order int, length float64) {
274Sierpinski arrowhead curve
0go
skiqa
import time seconds = float(raw_input()) print time.sleep(seconds) print
271Sleep
3python
140pc
sleep <- function(time=1) { message("Sleeping...") flush.console() Sys.sleep(time) message("Awake!") } sleep()
271Sleep
13r
h2wjj
use strict; use warnings; use SVG; use List::Util qw(max min); use constant pi => 2 * atan2(1, 0); my %rules = ( X => 'YF+XF+Y', Y => 'XF-YF-X' ); my $S = 'Y'; $S =~ s/([XY])/$rules{$1}/eg for 1..7; my (@X, @Y); my ($x, $y) = (0, 0); my $theta = 0; my $r = 6; for (split //, $S) { if (/F/) { push @X, sprintf "%.0f", $x; push @Y, sprintf "%.0f", $y; $x += $r * cos($theta); $y += $r * sin($theta); } elsif (/\+/) { $theta += pi/3; } elsif (/\-/) { $theta -= pi/3; } } my ($xrng, $yrng) = ( max(@X) - min(@X), max(@Y) - min(@Y)); my ($xt, $yt) = (-min(@X) + 10, -min(@Y) + 10); my $svg = SVG->new(width=>$xrng+20, height=>$yrng+20); my $points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline'); $svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'}); $svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)"); open my $fh, '>', 'sierpinski-arrowhead-curve.svg'; print $fh $svg->xmlify(-namespace=>'svg'); close $fh;
274Sierpinski arrowhead curve
2perl
gmh4e
use Tk; $main = MainWindow->new; $l = $main->Label('-text' => 'There have been no clicks yet.')->pack; $count = 0; $main->Button( -text => ' Click Me ', -command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); }, )->pack; MainLoop();
272Simple windowed application
2perl
qhnx6
import matplotlib.pyplot as plt import math def nextPoint(x, y, angle): a = math.pi * angle / 180 x2 = (int)(round(x + (1 * math.cos(a)))) y2 = (int)(round(y + (1 * math.sin(a)))) return x2, y2 def expand(axiom, rules, level): for l in range(0, level): a2 = for c in axiom: if c in rules: a2 += rules[c] else: a2 += c axiom = a2 return axiom def draw_lsystem(axiom, rules, angle, iterations): xp = [1] yp = [1] direction = 0 for c in expand(axiom, rules, iterations): if c == : xn, yn = nextPoint(xp[-1], yp[-1], direction) xp.append(xn) yp.append(yn) elif c == : direction = direction - angle if direction < 0: direction = 360 + direction elif c == : direction = (direction + angle)% 360 plt.plot(xp, yp) plt.show() if __name__ == '__main__': s_axiom = s_rules = {: , : } s_angle = 60 draw_lsystem(s_axiom, s_rules, s_angle, 7)
274Sierpinski arrowhead curve
3python
r9kgq
seconds = gets.to_f puts sleep(seconds) puts
271Sleep
14ruby
eroax
use std::{io, time, thread}; fn main() { println!("How long should we sleep in milliseconds?"); let mut sleep_string = String::new(); io::stdin().read_line(&mut sleep_string) .expect("Failed to read line"); let sleep_timer: u64 = sleep_string.trim() .parse() .expect("Not an integer"); let sleep_duration = time::Duration::from_millis(sleep_timer); println!("Sleeping..."); thread::sleep(sleep_duration); println!("Awake!"); }
271Sleep
15rust
w7ie4
object Sleeper extends App { print("Enter sleep time in milli sec: ") val ms = scala.io.StdIn.readInt() println("Sleeping...") val sleepStarted = scala.compat.Platform.currentTime Thread.sleep(ms) println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1") }
271Sleep
16scala
skfqo
long long x, y, dx, dy, scale, clen, cscale; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } } void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string(, d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } } void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string(, depth); unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf(, w, h); fflush(stdout); fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, , size, depth); sierp(size, depth + 2); return 0; }
275Sierpinski triangle/Graphical
5c
9n2m1
load_libraries :grammar attr_reader :points def setup sketch_title 'Sierpinski Arrowhead' sierpinski = SierpinskiArrowhead.new(Vec2D.new(width * 0.15, height * 0.7)) production = sierpinski.generate 6 @points = sierpinski.translate_rules(production) no_loop end def draw background(0) render points end def render(points) no_fill stroke 200.0 stroke_weight 3 begin_shape points.each_slice(2) do |v0, v1| v0.to_vertex(renderer) v1.to_vertex(renderer) end end_shape end def renderer @renderer ||= GfxRender.new(g) end def settings size(800, 800) end class SierpinskiArrowhead include Processing::Proxy attr_reader :draw_length, :pos, :theta, :axiom, :grammar DELTA = PI / 3 def initialize(pos) @axiom = 'XF' rules = { 'X' => 'YF+XF+Y', 'Y' => 'XF-YF-X' } @grammar = Grammar.new(axiom, rules) @theta = 0 @draw_length = 200 @pos = pos end def generate(gen) @draw_length = draw_length * 0.6**gen grammar.generate gen end def forward(pos) pos + Vec2D.from_angle(theta) * draw_length end def translate_rules(prod) [].tap do |pts| prod.scan(/./) do |ch| case ch when 'F' new_pos = forward(pos) pts << pos << new_pos @pos = new_pos when '+' @theta += DELTA when '-' @theta -= DELTA when 'X', 'Y' else puts() end end end end end
274Sierpinski arrowhead curve
14ruby
jlp7x
null
274Sierpinski arrowhead curve
15rust
h21j2
from functools import partial import tkinter as tk def on_click(label: tk.Label, counter: tk.IntVar) -> None: counter.set(counter.get() + 1) label[] = f def main(): window = tk.Tk() window.geometry() label = tk.Label(master=window, text=) label.pack() counter = tk.IntVar() update_counter = partial(on_click, label=label, counter=counter) button = tk.Button(master=window, text=, command=update_counter) button.pack() window.mainloop() if __name__ == '__main__': main()
272Simple windowed application
3python
skdq9
int main(){ time_t t; double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0; int i,iter,choice,numSides; printf(); scanf(,&numSides); printf(); scanf(,&side); printf(); scanf(,&iter); initwindow(windowSide,windowSide,); vertices = (double**)malloc(numSides*sizeof(double*)); for(i=0;i<numSides;i++){ vertices[i] = (double*)malloc(2 * sizeof(double)); vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides); vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides); sumX+= vertices[i][0]; sumY+= vertices[i][1]; putpixel(vertices[i][0],vertices[i][1],15); } srand((unsigned)time(&t)); seedX = sumX/numSides; seedY = sumY/numSides; putpixel(seedX,seedY,15); for(i=0;i<iter;i++){ choice = rand()%numSides; seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1); seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1); putpixel(seedX,seedY,15); } free(vertices); getch(); closegraph(); return 0; }
276Sierpinski pentagon
5c
micys
import Foundation println("Enter number of seconds to sleep") let input = NSFileHandle.fileHandleWithStandardInput() var amount = NSString(data:input.availableData, encoding: NSUTF8StringEncoding)?.intValue var interval = NSTimeInterval(amount!) println("Sleeping...") NSThread.sleepForTimeInterval(interval) println("Awake!")
271Sleep
17swift
ag81i
library(gWidgets) library(gWidgetstcltk) win <- gwindow() lab <- glabel("There have been no clicks yet", container=win) btn <- gbutton("click me", container=win, handle=function(h, ...) { val <- as.numeric(svalue(lab)) svalue(lab) <- ifelse(is.na(val) ,"1", as.character(val + 1)) } )
272Simple windowed application
13r
er8ad
package main import ( "github.com/fogleman/gg" "image/color" "math" ) var ( red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = color.RGBA{0, 255, 255, 255} ) var ( w, h = 640, 640 dc = gg.NewContext(w, h) deg72 = gg.Radians(72) scaleFactor = 1 / (2 + math.Cos(deg72)*2) palette = [5]color.Color{red, green, blue, magenta, cyan} colorIndex = 0 ) func drawPentagon(x, y, side float64, depth int) { angle := 3 * deg72 if depth == 0 { dc.MoveTo(x, y) for i := 0; i < 5; i++ { x += math.Cos(angle) * side y -= math.Sin(angle) * side dc.LineTo(x, y) angle += deg72 } dc.SetColor(palette[colorIndex]) dc.Fill() colorIndex = (colorIndex + 1) % 5 } else { side *= scaleFactor dist := side * (1 + math.Cos(deg72)*2) for i := 0; i < 5; i++ { x += math.Cos(angle) * dist y -= math.Sin(angle) * dist drawPentagon(x, y, side, depth-1) angle += deg72 } } } func main() { dc.SetRGB(1, 1, 1)
276Sierpinski pentagon
0go
agw1f
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color.Gray{0} gWhite := color.Gray{255} draw.Draw(im, bounds, image.NewUniform(gWhite), image.ZP, draw.Src) for y := 0; y < width; y++ { for x := 0; x < width; x++ { if x&y == 0 { im.SetGray(x, y, gBlack) } } } f, err := os.Create("sierpinski.png") if err != nil { fmt.Println(err) return } if err = png.Encode(f, im); err != nil { fmt.Println(err) } if err = f.Close(); err != nil { fmt.Println(err) } }
275Sierpinski triangle/Graphical
0go
erqa6
import Graphics.Gloss pentaflake :: Int -> Picture pentaflake order = iterate transformation pentagon !! order where transformation = Scale s s . foldMap copy [0,72..288] copy a = Rotate a . Translate 0 x pentagon = Polygon [ (sin a, cos a) | a <- [0,2*pi/5..2*pi] ] x = 2*cos(pi/5) s = 1/(1+x) main = display dc white (Color blue $ Scale 300 300 $ pentaflake 5) where dc = InWindow "Pentaflake" (400, 400) (0, 0)
276Sierpinski pentagon
8haskell
zs6t0
import Diagrams.Prelude import Diagrams.Backend.Cairo.CmdLine triangle = eqTriangle # fc black # lw 0 reduce t = t === (t ||| t) sierpinski = iterate reduce triangle main = defaultMain $ sierpinski !! 7
275Sierpinski triangle/Graphical
8haskell
30mzj
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel {
276Sierpinski pentagon
9java
o1n8d
require 'tk' str = TkVariable.new() count = 0 root = TkRoot.new TkLabel.new(root, => str).pack TkButton.new(root) do text command {str.value = count += 1} pack end Tk.mainloop
272Simple windowed application
14ruby
8pt01
<html> <head> <script type="application/x-javascript">
276Sierpinski pentagon
10javascript
tq3fm
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3;
275Sierpinski triangle/Graphical
9java
iafos
use iced::{
272Simple windowed application
15rust
o1z83
import scala.swing.{ BorderPanel, Button, Label, MainFrame, SimpleSwingApplication } import scala.swing.event.ButtonClicked object SimpleApp extends SimpleSwingApplication { def top = new MainFrame { contents = new BorderPanel { var nClicks = 0 val (button, label) = (new Button { text = "click me" }, new Label { text = "There have been no clicks yet" }) layout(button) = BorderPanel.Position.South layout(label) = BorderPanel.Position.Center listenTo(button) reactions += { case ButtonClicked(_) => nClicks += 1 label.text = s"There have been ${nClicks} clicks" } } } }
272Simple windowed application
16scala
dwyng
null
276Sierpinski pentagon
11kotlin
xjsws
<!-- SierpinskiTriangle.html --> <html> <head><title>Sierpinski Triangle Fractal</title> <script>
275Sierpinski triangle/Graphical
10javascript
zsyt2
Bitmap.chaosgame = function(self, n, r, niters) local w, h, vertices = self.width, self.height, {} for i = 1, n do vertices[i] = { x = w/2 + w/2 * math.cos(math.pi/2+(i-1)*math.pi*2/n), y = h/2 - h/2 * math.sin(math.pi/2+(i-1)*math.pi*2/n) } end local x, y = w/2, h/2 for i = 1, niters do local v = math.random(n) x = x + r * (vertices[v].x - x) y = y + r * (vertices[v].y - y) self:set(x,y,0xFFFFFFFF) end end local bitmap = Bitmap(128, 128) bitmap:chaosgame(5, 1/((1+math.sqrt(5))/2), 1e6) bitmap:render({[0x000000]='..', [0xFFFFFFFF]=''})
276Sierpinski pentagon
1lua
qh0x0
import java.awt.* import javax.swing.JFrame import javax.swing.JPanel fun main(args: Array<String>) { var i = 8
275Sierpinski triangle/Graphical
11kotlin
qh8x1
int main() { time_t t = 0; printf(, asctime(gmtime(&t))); return 0; }
277Show the epoch
5c
4yg5t
int main() { int x, y, i; for (y = SIZE - 1; y >= 0; y--, putchar('\n')) { for (i = 0; i < y; i++) putchar(' '); for (x = 0; x + y < SIZE; x++) printf((x & y) ? : ); } return 0; }
278Sierpinski triangle
5c
565uk
null
275Sierpinski triangle/Graphical
1lua
skoq8
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-$ @v = @vertices[@i]; $vector = 0; $vector += $v[$_] * $orders[$_] for 0..$ 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;
276Sierpinski pentagon
2perl
2tulf
(println (java.util.Date. 0))
277Show the epoch
6clojure
h2kjr
(ns example (:require [clojure.contrib.math:as 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)
278Sierpinski triangle
6clojure
jlj7m
main() { print(new Date.fromEpoch(0,new TimeZone.utc())); }
277Show the epoch
18dart
cdl9e
from turtle import * import math speed(0) hideturtle() part_ratio = 2 * math.cos(math.radians(72)) side_ratio = 1 / (part_ratio + 2) hide_turtles = True path_color = fill_color = 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() def sierpinski(i, t, s): t.setheading(0) new_size = s * side_ratio if i > 1: i -= 1 for j in range(4): t.right(36) short = s * side_ratio / part_ratio dist = [short, s, s, short][j] spawn = Turtle() if hide_turtles:spawn.hideturtle() spawn.penup() spawn.setposition(t.position()) spawn.setheading(t.heading()) spawn.forward(dist) sierpinski(i, spawn, new_size) sierpinski(i, t, new_size) else: pentagon(t, s) 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 size = 300 size *= part_ratio sierpinski(i, t, size) main()
276Sierpinski pentagon
3python
vz529
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=" <stop offset="60%" stop-color=" <stop offset="99%" stop-color=" </radialGradient> </defs> EOD triangle( $side/2, 0, 0, $height, $side, $height, 'url( triangle( $side/2, 0, 0, $height, $side, $height, ' '<g style="fill: fractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ), '</g></svg>';
275Sierpinski triangle/Graphical
2perl
vz420
,,,, ,,,, ,,,, ,,,, ,,,,
279Simple database
5c
qjwxc
typedef struct link link_t; struct link { int len; char letter; link_t *next; }; 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[] = , y[] = , res[128]; scs(x, y, res); printf(, x, y, res); return 0; }
280Shortest common supersequence
5c
3sfza
package main import ("fmt"; "time") func main() { fmt.Println(time.Time{}) }
277Show the epoch
0go
o1i8q
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))
277Show the epoch
7groovy
xjqwl
import System.Time main = putStrLn $ calendarTimeToString $ toUTCTime $ TOD 0 0
277Show the epoch
8haskell
2tvll
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
276Sierpinski pentagon
14ruby
56guj
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)) }
280Shortest common supersequence
0go
bvjkh
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)); } }
277Show the epoch
9java
68y3z
null
276Sierpinski pentagon
15rust
4yr5u
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 { private var hue = math.random
276Sierpinski pentagon
16scala
7chr9
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)
275Sierpinski triangle/Graphical
3python
u3gvd
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"
280Shortest common supersequence
8haskell
deon4
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")); } }
280Shortest common supersequence
9java
shwq0
document.write(new Date(0).toUTCString());
277Show the epoch
10javascript
lf2cf
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} }} plotmat(M, pf, clr, ttl); cat(" *** END", abbr, date(), "\n"); } pSierpinskiT(6,,,"red"); pSierpinskiT(8);
275Sierpinski triangle/Graphical
13r
cdv95
null
280Shortest common supersequence
11kotlin
a4b13
null
277Show the epoch
11kotlin
dwfnz
sub lcs { my( $u, $v ) = @_; return '' unless length($u) and length($v); my $longest = ''; for my $first ( 0..length($u)-1 ) { my $char = substr $u, $first, 1; my $i = index( $v, $char ); next if -1==$i; my $next = $char; $next .= lcs( substr( $u, $first+1), substr( $v, $i+1 ) ) unless $i==length($v)-1; $longest = $next if length($next) > length($longest); } return $longest; } sub scs { my( $u, $v ) = @_; my @lcs = split //, lcs $u, $v; my $pat = "(.*)".join("(.*)",@lcs)."(.*)"; my @u = $u =~ /$pat/; my @v = $v =~ /$pat/; my $scs = shift(@u).shift(@v); $scs .= $_.shift(@u).shift(@v) for @lcs; return $scs; } my $u = "abcbdab"; my $v = "bdcaba"; printf "Strings%s%s\n", $u, $v; printf "Longest common subsequence: %s\n", lcs $u, $v; printf "Shortest common supersquence:%s\n", scs $u, $v;
280Shortest common supersequence
2perl
9i6mn
Shoes.app(:height=>540,:width=>540, :title=>) do def triangle(slot, tri, color) x, y, len = tri slot.append do fill color shape do move_to(x,y) dx = len * Math::cos(Math::PI/3) dy = len * Math::sin(Math::PI/3) line_to(x-dx, y+dy) line_to(x+dx, y+dy) line_to(x,y) end end end @s = stack(:width => 520, :height => 520) {} @s.move(10,10) length = 512 @triangles = [[length/2,0,length]] triangle(@s, @triangles[0], rgb(0,0,0)) @n = 1 animate(1) do if @n <= 7 @triangles = @triangles.inject([]) do |sum, (x, y, len)| dx = len/2 * Math::cos(Math::PI/3) dy = len/2 * Math::sin(Math::PI/3) triangle(@s, [x, y+2*dy, -len/2], rgb(255,255,255)) sum += [[x, y, len/2], [x-dx, y+dy, len/2], [x+dx, y+dy, len/2]] end end @n += 1 end keypress do |key| case key when :control_q, then exit end end end
275Sierpinski triangle/Graphical
14ruby
4y75p
package main import ( "encoding/json" "fmt" "io" "os" "sort" "strings" "time" "unicode" )
279Simple database
0go
2fcl7
print(os.date("%c", 0))
277Show the epoch
1lua
fxtdp
null
275Sierpinski triangle/Graphical
15rust
gmj4o
import Control.Monad.State import Data.List (sortBy, nub) import System.Environment (getArgs, getProgName) import System.Directory (doesFileExist) import System.IO (openFile, hGetContents, hClose, IOMode(..), Handle, hPutStrLn) data Date = Date Integer Int Int deriving (Show, Read, Eq, Ord) data Item = Item {description :: String ,category :: [String] ,date :: Date ,optional :: [String]} deriving (Show, Read) type ItemList a = StateT [Item] IO a addItem :: Item -> ItemList () addItem i = modify (++ [i]) latest :: [Item] -> [Item] latest [] = [] latest [x]= [x] latest xs = take 1 $ sortBy newer xs newer :: Item -> Item -> Ordering newer a b = compare (date b) (date a) categories :: ItemList [String] categories = liftM (nub . concatMap category) get filterByCategory :: String -> ItemList [Item] filterByCategory c = liftM (filter (\i -> c `elem` category i)) get lastOfAll :: ItemList [Item] lastOfAll = liftM latest get latestByCategory :: ItemList [Item] latestByCategory = do cats <- categories filt <- mapM filterByCategory cats return $ concatMap latest filt sortByDate :: ItemList [Item] sortByDate = liftM (sortBy newer) get toScreen :: Item -> IO () toScreen (Item desc cats (Date y m d) opt) = putStrLn $ "Description:\t" ++ desc ++ "\nCategories:\t" ++ show cats ++ "\nDate:\t\t" ++ show y ++ "-" ++ show m ++ "-" ++ show d ++ "\nOther info:\t" ++ show opt arguments :: ItemList [Item] arguments = do args <- liftIO getArgs case args of ("add":desc:cat:year:month:day:opt) -> do let newItem = parseItem args addItem newItem return [newItem] ("latest":[]) -> do item <- lastOfAll lift $ mapM_ toScreen item return [] ("category":[]) -> do items <- latestByCategory lift $ mapM_ toScreen items return [] ("all":[]) -> do sorted <- sortByDate lift $ mapM_ toScreen sorted return [] _ -> do lift usage return [] parseItem :: [String] -> Item parseItem (_:desc:cat:year:month:day:opt) = Item {description = desc, category = words cat, date = Date (read year) (read month) (read day), optional = opt} usage :: IO () usage = do progName <- getProgName putStrLn $ "Usage: " ++ progName ++ " add|all|category|latest \ \OPTIONS\n\nadd \"description\" \"category1 category2\"... \ \year month day [\"note1\" \"note2\"...]\n\tAdds a new record \ \to the database.\n\nall\n\tPrints all items in chronological \ \order.\n\ncategory\n\tPrints the latest item for each category.\ \\n\nlatest\n\tPrints the latest item." main :: IO () main = do progName <- getProgName let fileName = progName ++ ".db" e <- doesFileExist fileName if e then do hr <- openFile fileName ReadMode f <- hGetContents hr v <- evalStateT arguments (map read $ lines f) hClose hr hw <- openFile fileName AppendMode mapM_ (hPutStrLn hw . show) v hClose hw else do v <- evalStateT arguments [] hw <- openFile fileName WriteMode mapM_ (hPutStrLn hw . show) v hClose hw
279Simple database
8haskell
a4p1g
def shortest_common_supersequence(a, b): lcs = longest_common_subsequence(a, b) scs = while len(lcs) > 0: if a[0]==lcs[0] and b[0]==lcs[0]: scs += lcs[0] lcs = lcs[1:] a = a[1:] b = b[1:] elif a[0]==lcs[0]: scs += b[0] b = b[1:] else: scs += a[0] a = a[1:] return scs + a + b
280Shortest common supersequence
3python
cny9q
require 'lcs' def scs(u, v) lcs = lcs(u, v) u, v = u.dup, v.dup scs = until lcs.empty? if u[0]==lcs[0] and v[0]==lcs[0] scs << lcs.slice!(0) u.slice!(0) v.slice!(0) elsif u[0]==lcs[0] scs << v.slice!(0) else scs << u.slice!(0) end end scs + u + v end u = v = puts
280Shortest common supersequence
14ruby
2f9lw
typedef struct{ double x,y; }point; double shoelace(char* inputFile){ int i,numPoints; double leftSum = 0,rightSum = 0; point* pointSet; FILE* fp = fopen(inputFile,); fscanf(fp,,&numPoints); pointSet = (point*)malloc((numPoints + 1)*sizeof(point)); for(i=0;i<numPoints;i++){ fscanf(fp,,&pointSet[i].x,&pointSet[i].y); } fclose(fp); pointSet[numPoints] = pointSet[0]; for(i=0;i<numPoints;i++){ leftSum += pointSet[i].x*pointSet[i+1].y; rightSum += pointSet[i+1].x*pointSet[i].y; } free(pointSet); return 0.5*fabs(leftSum - rightSum); } int main(int argC,char* argV[]) { if(argC==1) printf(,argV[0]); else printf(,shoelace(argV[1])); return 0; }
281Shoelace formula for polygonal area
5c
rmug7
import java.io.*; import java.text.*; import java.util.*; public class SimpleDatabase { final static String filename = "simdb.csv"; public static void main(String[] args) { if (args.length < 1 || args.length > 3) { printUsage(); return; } switch (args[0].toLowerCase()) { case "add": addItem(args); break; case "latest": printLatest(args); break; case "all": printAll(); break; default: printUsage(); break; } } private static class Item implements Comparable<Item>{ final String name; final String date; final String category; Item(String n, String d, String c) { name = n; date = d; category = c; } @Override public int compareTo(Item item){ return date.compareTo(item.date); } @Override public String toString() { return String.format("%s,%s,%s%n", name, date, category); } } private static void addItem(String[] input) { if (input.length < 2) { printUsage(); return; } List<Item> db = load(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf.format(new Date()); String cat = (input.length == 3) ? input[2] : "none"; db.add(new Item(input[1], date, cat)); store(db); } private static void printLatest(String[] a) { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); if (a.length == 2) { for (Item item : db) if (item.category.equals(a[1])) System.out.println(item); } else { System.out.println(db.get(0)); } } private static void printAll() { List<Item> db = load(); if (db.isEmpty()) { System.out.println("No entries in database."); return; } Collections.sort(db); for (Item item : db) System.out.println(item); } private static List<Item> load() { List<Item> db = new ArrayList<>(); try (Scanner sc = new Scanner(new File(filename))) { while (sc.hasNext()) { String[] item = sc.nextLine().split(","); db.add(new Item(item[0], item[1], item[2])); } } catch (IOException e) { System.out.println(e); } return db; } private static void store(List<Item> db) { try (FileWriter fw = new FileWriter(filename)) { for (Item item : db) fw.write(item.toString()); } catch (IOException e) { System.out.println(e); } } private static void printUsage() { System.out.println("Usage:"); System.out.println(" simdb cmd [categoryName]"); System.out.println(" add add item, followed by optional category"); System.out.println(" latest print last added item(s), followed by " + "optional category"); System.out.println(" all print all"); System.out.println(" For instance: add \"some item name\" " + "\"some category name\""); } }
279Simple database
9java
jcr7c
null
279Simple database
11kotlin
53vua
print scalar gmtime 0, "\n";
277Show the epoch
2perl
jlh7f
<?php echo gmdate('r', 0), ; ?>
277Show the epoch
12php
tqzf1