code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use Gtk3 '-init'; my $window = Gtk3::Window->new(); $window->set_default_size(320, 240); $window->set_border_width(10); $window->set_title("Draw a Pixel"); $window->set_app_paintable(TRUE); my $da = Gtk3::DrawingArea->new(); $da->signal_connect('draw' => \&draw_in_drawingarea); $window->add($da); $window->show_all();...
918Draw a pixel
2perl
z2xtb
def egyptian_divmod(dividend, divisor) table = [[1, divisor]] table << table.last.map{|e| e*2} while table.last.first * 2 <= dividend answer, accumulator = 0, 0 table.reverse_each do |pow, double| if accumulator + double <= dividend accumulator += double answer += pow end end [answer, di...
914Egyptian division
14ruby
jwv7x
fn egyptian_divide(dividend: u32, divisor: u32) -> (u32, u32) { let dividend = dividend as u64; let divisor = divisor as u64; let pows = (0..32).map(|p| 1 << p); let doublings = (0..32).map(|p| divisor << p); let (answer, sum) = doublings .zip(pows) .rev() .skip_while(|(i, ...
914Egyptian division
15rust
hxuj2
def ef(fr) ans = [] if fr >= 1 return [[fr.to_i], Rational(0, 1)] if fr.denominator == 1 intfr = fr.to_i ans, fr = [intfr], fr - intfr end x, y = fr.numerator, fr.denominator while x!= 1 ans << Rational(1, (1/fr).ceil) fr = Rational(-y % x, y * (1/fr).ceil) x, y = fr.numerator, fr.den...
913Egyptian fractions
14ruby
ukmvz
require 'socket' server = TCPServer.new(12321) while (connection = server.accept) Thread.new(connection) do |conn| port, host = conn.peeraddr[1,2] client = puts begin loop do line = conn.readline puts conn.puts(line) end rescue EOFError conn.close ...
907Echo server
14ruby
aie1s
local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt local bitmap = { init = function(self, w, h, value) self.w, self.h, self.pixels = w, h, {} for y=1,h do self.pixels[y]={} end self:clear(value) end, clear = function(self, value) for y=1,self.h...
919Draw a rotating cube
1lua
6uq39
mat <- matrix(1:4, 2, 2) mat + 2 mat * 2 mat ^ 2 mat + mat mat * mat mat ^ mat
912Element-wise operations
13r
qf1xs
DoublyLinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) { if (this._value == searchValue) { var after = this.next(); this.next(nodeToInsert); nodeToInsert.prev(this); nodeToInsert.next(after); after.prev(nodeToInsert); } else if (this.next() == nu...
920Doubly-linked list/Element insertion
10javascript
hxmjh
package main import "fmt" type dlNode struct { string next, prev *dlNode } type dlList struct { head, tail *dlNode } func (list *dlList) String() string { if list.head == nil { return fmt.Sprint(list.head) } r := "[" + list.head.string for p := list.head.next; p != nil; p = p.nex...
921Doubly-linked list/Traversal
0go
g1t4n
(use 'quil.core) (def w 500) (def h 400) (defn setup [] (background 0)) (defn draw [] (push-matrix) (translate (/ w 2) (/ h 2) 0) (rotate-x 0.7) (rotate-z 0.5) (box 100 150 200) (pop-matrix)) (defsketch main :title "cuboid" :setup setup :size [w h] :draw draw :renderer:opengl)
924Draw a cuboid
6clojure
vh02f
object EgyptianDivision extends App { private def divide(dividend: Int, divisor: Int): Unit = { val powersOf2, doublings = new collection.mutable.ListBuffer[Integer]
914Egyptian division
16scala
p0gbj
use num_bigint::BigInt; use num_integer::Integer; use num_traits::{One, Zero}; use std::fmt; #[derive(Debug, Clone, PartialEq, PartialOrd)] struct Rational { nominator: BigInt, denominator: BigInt, } impl Rational { fn new(n: &BigInt, d: &BigInt) -> Rational { assert!(!d.is_zero(), "denominator ca...
913Egyptian fractions
15rust
5b9uq
use std::net::{TcpListener, TcpStream}; use std::io::{BufReader, BufRead, Write}; use std::thread; fn main() { let listener = TcpListener::bind("127.0.0.1:12321").unwrap(); println!("server is running on 127.0.0.1:12321 ..."); for stream in listener.incoming() { let stream = stream.unwrap(); ...
907Echo server
15rust
enwaj
const char *shades = ; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; ...
925Draw a sphere
5c
4po5t
null
920Doubly-linked list/Element insertion
11kotlin
l7ocp
ds = CreateDataStructure["DoublyLinkedList"]; ds["Append", "A"]; ds["Append", "B"]; ds["Append", "C"]; ds["SwapPart", 2, 3]; ds["Elements"]
920Doubly-linked list/Element insertion
1lua
2jil3
class DoubleLinkedListTraversing { static void main(args) { def linkedList = (1..9).collect() as LinkedList linkedList.each { print it } println() linkedList.reverseEach { print it } } }
921Doubly-linked list/Traversal
7groovy
2jolv
main = print . traverse True $ create [10,20,30,40] data DList a = Leaf | Node { prev::(DList a), elt::a, next::(DList a) } create = go Leaf where go _ [] = Leaf go prev (x:xs) = current where current = Node prev x next next = go current xs isLeaf Leaf = T...
921Doubly-linked list/Traversal
8haskell
stgqk
type dlNode struct { string next, prev *dlNode }
923Doubly-linked list/Element definition
0go
eila6
data DList a = Leaf | Node (DList a) a (DList a) updateLeft _ Leaf = Leaf updateLeft Leaf (Node _ v r) = Node Leaf v r updateLeft new@(Node nl _ _) (Node _ v r) = current where current = Node prev v r prev = updateLeft nl new updateRight _ Leaf = Leaf updateRight Leaf (Node l v _) = Node l v Leaf upda...
923Doubly-linked list/Element definition
8haskell
3v1zj
from PIL import Image img = Image.new('RGB', (320, 240)) pixels = img.load() pixels[100,100] = (255,0,0) img.show()
918Draw a pixel
3python
3vqzc
extension BinaryInteger { @inlinable public func egyptianDivide(by divisor: Self) -> (quo: Self, rem: Self) { let table = (0...).lazy .map({i -> (Self, Self) in let power = Self(2).power(Self(i)) return (power, power * divisor) }) .prefix(while: { $0.1 <= self ...
914Egyptian division
17swift
7e2rq
import scala.annotation.tailrec import scala.collection.mutable import scala.collection.mutable.{ArrayBuffer, ListBuffer} abstract class Frac extends Comparable[Frac] { val num: BigInt val denom: BigInt def toEgyptian: List[Frac] = { if (num == 0) { return List(this) } val fracs = new ArrayBu...
913Egyptian fractions
16scala
ra2gn
import java.io.PrintWriter import java.net.{ServerSocket, Socket} import scala.io.Source object EchoServer extends App { private val serverSocket = new ServerSocket(23) private var numConnections = 0 class ClientHandler(clientSocket: Socket) extends Runnable { private val (connectionId, closeCmd) = ({numCo...
907Echo server
16scala
qtsxw
public class Node<T> { private T element; private Node<T> next, prev; public Node<T>(){ next = prev = element = null; } public Node<T>(Node<T> n, Node<T> p, T elem){ next = n; prev = p; element = elem; } public void setNext(Node<T> n){ next = n; } public Node...
923Doubly-linked list/Element definition
9java
iy7os
p x = + gets.chomp! instance_variable_set x, 42 p
917Dynamic variable names
14ruby
7e9ri
use strict; use warnings; use Tk; use Time::HiRes qw( time ); my $size = 600; my $wait = int 1000 / 30; my ($height, $width) = ($size, $size * sqrt 8/9); my $mid = $width / 2; my $rot = atan2(0, -1) / 3; my $mw = MainWindow->new; my $c = $mw->Canvas(-width => $width, -height => $heigh...
919Draw a rotating cube
2perl
p02b0
require 'matrix' class Matrix def element_wise( operator, other ) Matrix.build(row_size, column_size) do |row, col| self[row, col].send(operator, other[row, col]) end end end m1, m2 = Matrix[[3,1,4],[1,5,9]], Matrix[[2,7,1],[8,2,2]] puts [:+,:-,:*,:/, :fdiv,:**,:%].each do |op| puts % [op, m1.e...
912Element-wise operations
14ruby
nmsit
package com.rosettacode; import java.util.LinkedList; import java.util.stream.Collectors; import java.util.stream.IntStream; public class DoubleLinkedListTraversing { public static void main(String[] args) { final LinkedList<String> doubleLinkedList = IntStream.range(1, 10) .mapToObj(Strin...
921Doubly-linked list/Traversal
9java
18lp2
DoublyLinkedList.prototype.getTail = function() { var tail; this.traverse(function(node){tail = node;}); return tail; } DoublyLinkedList.prototype.traverseBackward = function(func) { func(this); if (this.prev() != null) this.prev().traverseBackward(func); } DoublyLinkedList.prototype.printB...
921Doubly-linked list/Traversal
10javascript
qf4x8
function DoublyLinkedList(value, next, prev) { this._value = value; this._next = next; this._prev = prev; }
923Doubly-linked list/Element definition
10javascript
z2pt2
struct Matrix { elements: Vec<f32>, pub height: u32, pub width: u32, } impl Matrix { fn new(elements: Vec<f32>, height: u32, width: u32) -> Matrix {
912Element-wise operations
15rust
d90ny
(use 'quil.core) (def w 500) (def h 400) (defn setup [] (background 0)) (defn draw [] (push-matrix) (translate 250 200 0) (sphere 100) (pop-matrix)) (defsketch main :title "sphere" :setup setup :size [w h] :draw draw :renderer:opengl)
925Draw a sphere
6clojure
hxtjr
null
921Doubly-linked list/Traversal
11kotlin
jw67r
null
923Doubly-linked list/Element definition
11kotlin
qfux1
local node = { data=data, prev=nil, next=nil }
923Doubly-linked list/Element definition
1lua
st5q8
package main import ( "fmt" "math/rand" "time" )
922Dutch national flag problem
0go
st4qa
my %node_model = ( data => 'something', prev => undef, next => undef, ); sub insert { my ($anchor, $newlink) = @_; $newlink->{next} = $anchor->{next}; $newlink->{prev} = $anchor; $newlink->{next}->{prev} = $newlink; $anchor->{next} = $newlink; } my $nod...
920Doubly-linked list/Element insertion
2perl
qfgx6
const char * shades = ; double dist(double x, double y, double x0, double y0) { double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0); if (l > 1) { x -= x0; y -= y0; } else if (l >= 0) { x -= l * x0; y -= l * y0; } return sqrt(x * x + y * y); } enum { sec = 0, min, hur }; void draw(int size) { doubl...
926Draw a clock
5c
5b0uk
null
921Doubly-linked list/Traversal
1lua
hxyj8
import Data.List (sort) import System.Random (randomRIO) import System.IO.Unsafe (unsafePerformIO) data Color = Red | White | Blue deriving (Show, Eq, Ord, Enum) dutch :: [Color] -> [Color] dutch = sort isDutch :: [Color] -> Bool isDutch x = x == dutch x randomBalls :: Int -> [Color] randomBalls 0 = [] randomBalls ...
922Dutch national flag problem
8haskell
9gqmo
from visual import * scene.title = scene.range = 2 scene.autocenter = True print print deg45 = math.radians(45.0) cube = box() cube.rotate( angle=deg45, axis=(1,0,0) ) cube.rotate( angle=deg45, axis=(0,0,1) ) while True: rate(50) cube.rotate( angle=0.005, axis=(0,1,0) )
919Draw a rotating cube
3python
18vpc
require 'gtk3' Width, Height = 320, 240 PosX, PosY = 100, 100 window = Gtk::Window.new window.set_default_size(Width, Height) window.title = 'Draw a pixel' window.signal_connect(:draw) do |widget, context| context.set_antialias(Cairo::Antialias::NONE) context.set_source_rgb(1.0, 0.0, 0.0) context.f...
918Draw a pixel
14ruby
y506n
extern crate piston_window; extern crate image; use piston_window::*; fn main() { let (width, height) = (320, 240); let mut window: PistonWindow = WindowSettings::new("Red Pixel", [width, height]) .exit_on_esc(true).build().unwrap();
918Draw a pixel
15rust
m48ya
def insert(anchor, new): new.next = anchor.next new.prev = anchor anchor.next.prev = new anchor.next = new
920Doubly-linked list/Element insertion
3python
strq9
my %node = ( data => 'say what', next => \%foo_node, prev => \%bar_node, ); $node{next} = \%quux_node;
923Doubly-linked list/Element definition
2perl
vh820
import java.util.Arrays; import java.util.Random; public class DutchNationalFlag { enum DutchColors { RED, WHITE, BLUE } public static void main(String[] args){ DutchColors[] balls = new DutchColors[12]; DutchColors[] values = DutchColors.values(); Random rand = new Random(...
922Dutch national flag problem
9java
tlpf9
package main import "fmt" func cuboid(dx, dy, dz int) { fmt.Printf("cuboid%d%d%d:\n", dx, dy, dz) cubLine(dy+1, dx, 0, "+-") for i := 1; i <= dy; i++ { cubLine(dy-i+1, dx, i-1, "/ |") } cubLine(0, dx, dy, "+-|") for i := 4*dz - dy - 2; i > 0; i-- { cubLine(0, dx, dy, "| |") ...
924Draw a cuboid
0go
ao91f
import java.awt.image.BufferedImage import java.awt.Color import scala.language.reflectiveCalls object RgbBitmap extends App { class RgbBitmap(val dim: (Int, Int)) { def width = dim._1 def height = dim._2 private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) def apply(...
918Draw a pixel
16scala
l7ncq
import java.awt.event.ActionEvent import java.awt._ import javax.swing.{JFrame, JPanel, Timer} import scala.math.{Pi, atan, cos, sin, sqrt} object RotatingCube extends App { class RotatingCube extends JPanel { private val vertices: Vector[Array[Double]] = Vector(Array(-1, -1, -1), Array(-1, -1, 1), Arra...
919Draw a rotating cube
16scala
st7qo
const dutchNationalFlag = () => { const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red'; const isSorted = arr => arr.every((e,i) => e >= arr[Math.max(i-1, 0)]); function* randomGen (max, n) { let i = 0; while (i < n) { i += 1; yield Math.floor(Math.random() * max); } } ...
922Dutch national flag problem
10javascript
m4xyv
import Graphics.Rendering.OpenGL import Graphics.UI.GLUT type Fl = GLfloat cuboid :: IO () cuboid = do color red ; render front color green; render side color blue ; render top red,green,blue :: Color4 GLfloat red = Color4 1 0 0 1 green = Color4 0 1 0 1 blue = Color4 0 0 1 1 render :: [(Fl, Fl, Fl)...
924Draw a cuboid
8haskell
z2bt0
class Node(object): def __init__(self, data = None, prev = None, next = None): self.prev = prev self.next = next self.data = data def __str__(self): return str(self.data) def __repr__(self): return repr(self.data) def iter_forward(self): c = self...
923Doubly-linked list/Element definition
3python
ukovd
null
922Dutch national flag problem
11kotlin
o678z
class DListNode def insert_after(search_value, new_value) if search_value == value new_node = self.class.new(new_value, nil, nil) next_node = self.succ self.succ = new_node new_node.prev = self new_node.succ = next_node next_node.prev = new_node elsif self.succ.nil? r...
920Doubly-linked list/Element insertion
14ruby
83j01
use std::collections::LinkedList; fn main() { let mut list = LinkedList::new(); list.push_front(8); }
920Doubly-linked list/Element insertion
15rust
o6h83
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>> class Node<T> { var value: T fileprivate var prev: NodePtr<T>? fileprivate var next: NodePtr<T>? init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) { self.value = value self.prev = prev self.next = next } } @discardableResult fu...
920Doubly-linked list/Element insertion
17swift
0z7s6
import java.awt.*; import java.awt.event.*; import static java.lang.Math.*; import javax.swing.*; public class Cuboid extends JPanel { double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}}; int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {...
924Draw a cuboid
9java
o6g8d
class List: def __init__(self, data, next=None, prev=None): self.data = data self.next = next self.prev = prev def append(self, data): if self.next == None: self.next = List(data, None, self) return self.next else: return self.next.app...
921Doubly-linked list/Traversal
3python
z2att
class DListNode < ListNode attr_accessor :prev def initialize(value, prev=nil, succ=nil) @value = value @prev = prev @prev.succ = self if prev @succ = succ @succ.prev = self if succ end def self.from_values(*ary) ary << (f = ary.pop) ary.map! {|i| new i } ary.inject(f) {|p, ...
923Doubly-linked list/Element definition
14ruby
4pn5p
use std::collections::LinkedList; fn main() {
923Doubly-linked list/Element definition
15rust
g1d4o
null
922Dutch national flag problem
1lua
iyjot
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> canvas { background-color: black; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; canvas.h...
924Draw a cuboid
10javascript
tlkfm
long long x, y, dx, dy, scale, clen; typedef struct { double r, g, b; } rgb; rgb ** pix; void sc_up() { long long tmp = dx - dy; dy = dx + dy; dx = tmp; scale *= 2; x *= 2; y *= 2; } void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; double h = 6.0 * clen / scale; double VAL = 1 - (cos(3.14159265357...
927Dragon curve
5c
qfcxc
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>> class Node<T> { var value: T fileprivate var prev: NodePtr<T>? fileprivate var next: NodePtr<T>? init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) { self.value = value self.prev = prev self.next = next } }
923Doubly-linked list/Element definition
17swift
5biu8
class DListNode def get_tail self.find {|node| node.succ.nil?} end def each_previous(&b) yield self self.prev.each_previous(&b) if self.prev end end head = DListNode.from_array([:a, :b, :c]) head.each {|node| p node.value} head.get_tail.each_previous {|node| p node.value}
921Doubly-linked list/Traversal
14ruby
6uw3t
null
924Draw a cuboid
11kotlin
xd2ws
import java.util object DoublyLinkedListTraversal extends App { private val ll = new util.LinkedList[String] private def traverse(iter: util.Iterator[String]) = while (iter.hasNext) iter.next traverse(ll.iterator) traverse(ll.descendingIterator) }
921Doubly-linked list/Traversal
16scala
cr093
use warnings; use strict; use 5.010; use List::Util qw( shuffle ); my @colours = qw( blue white red ); sub are_ordered { my $balls = shift; my $last = 0; for my $ball (@$balls) { return if $ball < $last; $last = $ball; } return 1; } sub show { my $balls = shift; print j...
922Dutch national flag problem
2perl
g1f4e
package main import ( "fmt" "image" "image/color" "image/png" "math" "os" ) type vector [3]float64 func normalize(v *vector) { invLen := 1 / math.Sqrt(dot(v, v)) v[0] *= invLen v[1] *= invLen v[2] *= invLen } func dot(x, y *vector) float64 { return x[0]*y[0] + x[1]*y[1] +...
925Draw a sphere
0go
o648q
package main import ( "golang.org/x/net/websocket" "flag" "fmt" "html/template" "io" "math" "net/http" "time" ) var ( Portnum string Hostsite string ) type PageSettings struct { Host string Port string } const ( Canvaswidth = 512 Canvasheight = 512
926Draw a clock
0go
83u0g
null
924Draw a cuboid
1lua
qfvx0
import Graphics.Rendering.OpenGL.GL import Graphics.UI.GLUT.Objects import Graphics.UI.GLUT setProjection :: IO () setProjection = do matrixMode $= Projection ortho (-1) 1 (-1) 1 0 (-1) grey1,grey9,red,white :: Color4 GLfloat grey1 = Color4 0.1 0.1 0.1 1 grey9 = Color4 0.9 0.9 0.9 1 red = Color4 1 0 0 1 w...
925Draw a sphere
8haskell
2jqll
import Control.Concurrent import Data.List import System.Time import System.Console.ANSI number :: (Integral a) => a -> [String] number 0 = ["" ," " ," " ," " ,""] number 1 = [" " ," " ," " ," " ," "] number 2 = ["" ," " ,"" ," " ,""] number 3 = ["" ," " ...
926Draw a clock
8haskell
l7wch
import random colours_in_order = 'Red White Blue'.split() def dutch_flag_sort(items, order=colours_in_order): 'return sort of items using the given order' reverse_index = dict((x,i) for i,x in enumerate(order)) return sorted(items, key=lambda x: reverse_index[x]) def dutch_flag_check(items, order=colours...
922Dutch national flag problem
3python
ratgq
public class Sphere{ static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}; static double[] light = { 30, 30, -50 }; private static void normalize(double[] v){ double len = Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } pr...
925Draw a sphere
9java
6up3z
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Draw a sphere</title> <script> var light=[30,30,-50],gR,gk,gambient; function normalize(v){ var len=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); v[0]/=len; v[1]/=len; v[2]/=len; return v; } function dot(x,y){ var d=x[0]*y[0]+x[1]*y[1]+x[2]*y[2]; return d...
925Draw a sphere
10javascript
l7xcf
import java.awt.*; import java.awt.event.*; import static java.lang.Math.*; import java.time.LocalTime; import javax.swing.*; class Clock extends JPanel { final float degrees06 = (float) (PI / 30); final float degrees30 = degrees06 * 5; final float degrees90 = degrees30 * 3; final int size = 590; ...
926Draw a clock
9java
3vkzg
class Ball FLAG = {red: 1, white: 2, blue: 3} def initialize @color = FLAG.keys.sample end def color @color end def <=>(other) FLAG[self.color] <=> FLAG[other.color] end def inspect @color end end balls = [] balls = Array.new(8){Ball.new} while balls == balls.sort puts puts
922Dutch national flag problem
14ruby
jw37x
var sec_old = 0; function update_clock() { var t = new Date(); var arms = [t.getHours(), t.getMinutes(), t.getSeconds()]; if (arms[2] == sec_old) return; sec_old = arms[2]; var c = document.getElementById('clock'); var ctx = c.getContext('2d'); ctx.fillStyle = "rgb(0,200,200)"; ctx.fillRect(0, 0, c.width, c.he...
926Draw a clock
10javascript
cre9j
extern crate rand; use rand::Rng;
922Dutch national flag problem
15rust
hx6j2
object FlagColor extends Enumeration { type FlagColor = Value val Red, White, Blue = Value } val genBalls = (1 to 10).map(i => FlagColor(scala.util.Random.nextInt(FlagColor.maxId))) val sortedBalls = genBalls.sorted val sorted = if (genBalls == sortedBalls) "sorted" else "not sorted" println(s"Generated balls...
922Dutch national flag problem
16scala
p09bj
-- Create and populate tables CREATE TABLE colours (id INTEGER PRIMARY KEY, name VARCHAR(5)); INSERT INTO colours (id, name) VALUES ( 1, 'red' ); INSERT INTO colours (id, name) VALUES ( 2, 'white'); INSERT INTO colours (id, name) VALUES ( 3, 'blue' ); CREATE TABLE balls ( colour INTEGER REFERENCES colours ); INSERT I...
922Dutch national flag problem
19sql
ei2au
null
925Draw a sphere
11kotlin
d97nz
null
926Draw a clock
11kotlin
nmgij
sub cubLine ($$$$) { my ($n, $dx, $dy, $cde) = @_; printf '%*s', $n + 1, substr($cde, 0, 1); for (my $d = 9 * $dx - 1 ; $d > 0 ; --$d) { print substr($cde, 1, 1); } print substr($cde, 0, 1); printf "%*s\n", $dy + 1, substr($cde, 2, 1); } sub cuboid ($$$) { my ($dx, $dy, $dz) = @_...
924Draw a cuboid
2perl
2jslf
require ("math") shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'} function normalize (vec) len = math.sqrt(vec[1]^2 + vec[2]^2 + vec[3]^2) return {vec[1]/len, vec[2]/len, vec[3]/len} end light = normalize{30, 30, -50} function dot (vec1, vec2) d = vec1[1]*vec2[1] + vec1[2]*vec2[2] + vec1[3]*v...
925Draw a sphere
1lua
fcjdp
Dynamic[ClockGauge[], UpdateInterval -> 1]
926Draw a clock
1lua
d9rnq
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "os" )
927Dragon curve
0go
2jwl7
def _pr(t, x, y, z): txt = '\n'.join(''.join(t[(n,m)] for n in range(3+x+z)).rstrip() for m in reversed(range(3+y+z))) return txt def cuboid(x,y,z): t = {(n,m):' ' for n in range(3+x+z) for m in range(3+y+z)} xrow = ['+'] + ['%i'% (i% 10) for i in range(x)] + ['+'] for i,ch in e...
924Draw a cuboid
3python
vh029
import Data.List import Graphics.Gnuplot.Simple pl = [[0,0],[0,1]] r_90 = [[0,1],[-1,0]] ip :: [Int] -> [Int] -> Int ip xs = sum . zipWith (*) xs matmul xss yss = map (\xs -> map (ip xs ). transpose $ yss) xss vmoot xs = (xs++).map (zipWith (+) lxs). flip matmul r_90. map (flip (zipWith (-)) lxs) .rever...
927Dragon curve
8haskell
ao61g
import java.awt.Color; import java.awt.Graphics; import java.util.*; import javax.swing.JFrame; public class DragonCurve extends JFrame { private List<Integer> turns; private double startingAngle, side; public DragonCurve(int iter) { super("Dragon Curve"); setBounds(100, 100, 800, 600); ...
927Dragon curve
9java
jwn7c
use utf8; binmode STDOUT, ':utf8'; $|++; my ($rows, $cols) = split /\s+/, `stty size`; my $x = int($rows / 2 - 1); my $y = int($cols / 2 - 16); my @chars = map {[ /(...)/g ]} (" ", " : ", " "); while (1) { my @indices = m...
926Draw a clock
2perl
7enrh
var DRAGON = (function () {
927Dragon curve
10javascript
183p7
X, Y, Z = 6, 2, 3 DIR = { => [1,0], => [0,1], => [1,1]} def cuboid(nx, ny, nz) puts % [nx, ny, nz] x, y, z = X*nx, Y*ny, Z*nz area = Array.new(y+z+1){ * (x+y+1)} draw_line = lambda do |n, sx, sy, c| dx, dy = DIR[c] (n+1).times do |i| xi, yi = sx+i*dx, sy+i*dy area[yi][xi] = (area[yi][xi]...
924Draw a cuboid
14ruby
5bouj
use strict; use warnings; my $x = my $y = 255; $x |= 1; my $depth = 255; my $light = Vector->new(rand, rand, rand)->normalized; print "P2\n$x $y\n$depth\n"; my ($r, $ambient) = (($x - 1)/2, 0); my ($r2) = $r ** 2; { for my $x (-$r .. $r) { my $x2 = $x**2; for my $y (-$r .. $r) { my $y2 = $y**2; my ...
925Draw a sphere
2perl
jwf7f
import java.awt._ import java.awt.event.{MouseAdapter, MouseEvent} import javax.swing._ import scala.math.{Pi, cos, sin} object Cuboid extends App { SwingUtilities.invokeLater(() => { class Cuboid extends JPanel { private val nodes: Array[Array[Double]] = Array(Array(-1, -1, -1), Array(-1, -1, 1...
924Draw a cuboid
16scala
7efr9
null
927Dragon curve
11kotlin
5bsua
import time def chunks(l, n=5): return [l[i:i+n] for i in range(0, len(l), n)] def binary(n, digits=8): n=int(n) return '{0:0{1}b}'.format(n, digits) def secs(n): n=int(n) h='x' * n return .join(chunks(h)) def bin_bit(h): h=h.replace(,) h=h.replace(,) return .join(list(h)) x=st...
926Draw a clock
3python
jwd7p
function dragon() local l = "l" local r = "r" local inverse = {l = r, r = l} local field = {r} local num = 1 local loop_limit = 6
927Dragon curve
1lua
4p05c