code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import math
shades = ('.',':','!','*','o','e','&','
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light) | 925Draw a sphere
| 3python
| hxtjw |
int main(int argC, char* argV[])
{
int i,zeroCount= 0,firstNonZero = -1;
double* vector;
if(argC == 1){
printf(,argV[0]);
}
else{
printf();
for(i=1;i<argC;i++){
printf(,argV[i]);
}
printf();
vector = (double*)malloc((argC-1)*sizeof(double));
for(i=1;i<=argC;i++){
vector[i-1] = atof(argV[i]);
if(vector[i-1]==0.0)
zeroCount++;
if(vector[i-1]!=0.0 && firstNonZero==-1)
firstNonZero = i-1;
}
if(zeroCount == argC){
printf();
}
else{
for(i=0;i<argC;i++){
if(i==firstNonZero && vector[i]==1)
printf(,i+1);
else if(i==firstNonZero && vector[i]==-1)
printf(,i+1);
else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])>0.0)
printf(,fabs(vector[i]),i+1);
else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])==0.0)
printf(,labs(vector[i]),i+1);
else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])>0.0)
printf(,vector[i],i+1);
else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])==0.0)
printf(,vector[i],i+1);
else if(fabs(vector[i])==1.0 && i!=0)
printf(,(vector[i]==-1)?'-':'+',i+1);
else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])>0.0)
printf(,(vector[i]<0)?'-':'+',fabs(vector[i]),i+1);
else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])==0.0)
printf(,(vector[i]<0)?'-':'+',labs(vector[i]),i+1);
}
}
}
free(vector);
return 0;
} | 928Display a linear combination
| 5c
| 3vjza |
int add(int a, int b) {
return a + b;
} | 929Documentation
| 5c
| ra0g7 |
float mean(float* arr,int size){
int i = 0;
float sum = 0;
while(i != size)
sum += arr[i++];
return sum/size;
}
float variance(float reference,float* arr, int size){
int i=0;
float* newArr = (float*)malloc(size*sizeof(float));
for(;i<size;i++)
newArr[i] = (reference - arr[i])*(reference - arr[i]);
return mean(newArr,size);
}
float* extractData(char* str, int *len){
float* arr;
int i=0,count = 1;
char* token;
while(str[i]!=00){
if(str[i++]==',')
count++;
}
arr = (float*)malloc(count*sizeof(float));
*len = count;
token = strtok(str,);
i = 0;
while(token!=NULL){
arr[i++] = atof(token);
token = strtok(NULL,);
}
return arr;
}
int main(int argC,char* argV[])
{
float* arr,reference,meanVal;
int len;
if(argC!=3)
printf();
else{
arr = extractData(argV[2],&len);
reference = atof(argV[1]);
meanVal = mean(arr,len);
printf(,variance(reference,arr,len));
printf(,(reference - meanVal)*(reference - meanVal));
printf(,variance(meanVal,arr,len));
}
return 0;
} | 930Diversity prediction theorem
| 5c
| 83c04 |
Shoes.app(:width=>205, :height => 228, :title => ) do
def draw_ray(width, start, stop, ratio)
angle = Math::PI * 2 * ratio - Math::PI/2
strokewidth width
cos = Math::cos(angle)
sin = Math::sin(angle)
line 101+cos*start, 101+sin*start, 101+cos*stop, 101+sin*stop
end
def update
t = Time.now
@time.text = t.strftime()
h, m, s = (t.hour % 12).to_f, t.min.to_f, t.sec.to_f
s += t.to_f - t.to_i
@hands.clear do
draw_ray(3, 0, 70, (h + m/60)/12)
draw_ray(2, 0, 90, (m + s/60)/60)
draw_ray(1, 0, 95, s/60)
end
end
@time = para(:align=>, :family => )
stack(:width=>203, :height=>203) do
strokewidth 1
fill gradient(deepskyblue, aqua)
oval 1, 1, 200
fill black
oval 98, 98, 6
0.upto(59) {|m| draw_ray(1, (m % 5 == 0? 96: 98), 100, m.to_f/60)}
end.move(0,23)
@hands = stack(:width=>203, :height=>203) {}.move(0,23)
animate(5) {update}
end | 926Draw a clock
| 14ruby
| kqthg |
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn(, 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf();
return 1;
}
printf();
pvm_recv(-1, 2);
pvm_unpackf(, &i_data, &i2);
printf(, i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf(, &i_data, &f_data);
printf(, i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf(, i_data, f_data);
pvm_send(parent, 1);
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf(, i_data, i2);
pvm_send(parent, 2);
}
pvm_exit();
return 0;
} | 931Distributed programming
| 5c
| styq5 |
(def
#^{:doc "Metadata can contain documentation and can be added to vars like this."}
test1)
(defn test2
"defn and some other macros allow you add documentation like this. Works the same way"
[]) | 929Documentation
| 6clojure
| bsdkz |
int
main()
{
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo(, NULL, &hints, &res0);
if (error) {
fprintf(stderr, , gai_strerror(error));
exit(1);
}
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (error) {
fprintf(stderr, , gai_strerror(error));
} else {
printf(, host);
}
}
freeaddrinfo(res0);
return 0;
} | 932DNS query
| 5c
| o6980 |
(defn diversity-theorem [truth predictions]
(let [square (fn[x] (* x x))
mean (/ (reduce + predictions) (count predictions))
avg-sq-diff (fn[a] (/ (reduce + (for [x predictions] (square (- x a)))) (count predictions)))]
{:average-error (avg-sq-diff truth)
:crowd-error (square (- truth mean))
:diversity (avg-sq-diff mean)}))
(println (diversity-theorem 49 '(48 47 51)))
(println (diversity-theorem 49 '(48 47 51 42))) | 930Diversity prediction theorem
| 6clojure
| fc5dm |
Shoes.app :width => 500, :height => 500, :resizable => false do
image 400, 470, :top => 30, :left => 50 do
nostroke
fill
image :top => 230, :left => 0 do
oval 70, 130, 260, 40
blur 30
end
oval 10, 10, 380, 380
image :top => 0, :left => 0 do
fill
oval 30, 30, 338, 338
blur 10
end
fill gradient(rgb(1.0, 1.0, 1.0, 0.7), rgb(1.0, 1.0, 1.0, 0.0))
oval 80, 14, 240, 176
image :top => 0, :left => 0 do
fill
oval 134, 134, 130, 130
blur 40
end
image :top => 150, :left => 40, :width => 320, :height => 260 do
fill gradient(rgb(0.7, 0.9, 1.0, 0.0), rgb(0.7, 0.9, 1.0, 0.6))
oval 60, 60, 200, 136
blur 20
end
end
end | 925Draw a sphere
| 14ruby
| bs3kq |
null | 926Draw a clock
| 15rust
| bszkx |
null | 925Draw a sphere
| 15rust
| p06bu |
package main
import (
"fmt"
"strings"
)
type nNode struct {
name string
children []nNode
}
type iNode struct {
level int
name string
}
func toNest(iNodes []iNode, start, level int, n *nNode) {
if level == 0 {
n.name = iNodes[0].name
}
for i := start + 1; i < len(iNodes); i++ {
if iNodes[i].level == level+1 {
c := nNode{iNodes[i].name, nil}
toNest(iNodes, i, level+1, &c)
n.children = append(n.children, c)
} else if iNodes[i].level <= level {
return
}
}
}
func makeIndent(outline string, tab int) []iNode {
lines := strings.Split(outline, "\n")
iNodes := make([]iNode, len(lines))
for i, line := range lines {
line2 := strings.TrimLeft(line, " ")
le, le2 := len(line), len(line2)
level := (le - le2) / tab
iNodes[i] = iNode{level, line2}
}
return iNodes
}
func toMarkup(n nNode, cols []string, depth int) string {
var span int
var colSpan func(nn nNode)
colSpan = func(nn nNode) {
for i, c := range nn.children {
if i > 0 {
span++
}
colSpan(c)
}
}
for _, c := range n.children {
span = 1
colSpan(c)
}
var lines []string
lines = append(lines, `{| class="wikitable" style="text-align: center;"`)
const l1, l2 = "|-", "| |"
lines = append(lines, l1)
span = 1
colSpan(n)
s := fmt.Sprintf(`| style="background:%s " colSpan=%d |%s`, cols[0], span, n.name)
lines = append(lines, s, l1)
var nestedFor func(nn nNode, level, maxLevel, col int)
nestedFor = func(nn nNode, level, maxLevel, col int) {
if level == 1 && maxLevel > level {
for i, c := range nn.children {
nestedFor(c, 2, maxLevel, i)
}
} else if level < maxLevel {
for _, c := range nn.children {
nestedFor(c, level+1, maxLevel, col)
}
} else {
if len(nn.children) > 0 {
for i, c := range nn.children {
span = 1
colSpan(c)
cn := col + 1
if maxLevel == 1 {
cn = i + 1
}
s := fmt.Sprintf(`| style="background:%s " colspan=%d |%s`, cols[cn], span, c.name)
lines = append(lines, s)
}
} else {
lines = append(lines, l2)
}
}
}
for maxLevel := 1; maxLevel < depth; maxLevel++ {
nestedFor(n, 1, maxLevel, 0)
if maxLevel < depth-1 {
lines = append(lines, l1)
}
}
lines = append(lines, "|}")
return strings.Join(lines, "\n")
}
func main() {
const outline = `Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.`
const (
yellow = "#ffffe6;"
orange = "#ffebd2;"
green = "#f0fff0;"
blue = "#e6ffff;"
pink = "#ffeeff;"
)
cols := []string{yellow, orange, green, blue, pink}
iNodes := makeIndent(outline, 4)
var n nNode
toNest(iNodes, 0, 0, &n)
fmt.Println(toMarkup(n, cols, 4))
fmt.Println("\n")
const outline2 = `Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
Propagating the sums upward as necessary.
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.
Optionally add color to the nodes.`
cols2 := []string{blue, yellow, orange, green, pink}
var n2 nNode
iNodes2 := makeIndent(outline2, 4)
toNest(iNodes2, 0, 0, &n2)
fmt.Println(toMarkup(n2, cols2, 4))
} | 933Display an outline as a nested table
| 0go
| y5g64 |
import java.util.{ Timer, TimerTask }
import java.time.LocalTime
import scala.math._
object Clock extends App {
private val (width, height) = (80, 35)
def getGrid(localTime: LocalTime): Array[Array[Char]] = {
val (minute, second) = (localTime.getMinute, localTime.getSecond())
val grid = Array.fill[Char](height, width)(' ')
def toGridCoord(x: Double, y: Double): (Int, Int) =
(floor((y + 1.0) / 2.0 * height).toInt, floor((x + 1.0) / 2.0 * width).toInt)
def makeText(grid: Array[Array[Char]], r: Double, theta: Double, str: String) {
val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
(0 until str.length).foreach(i =>
if (row >= 0 && row < height && col + i >= 0 && col + i < width) grid(row)(col + i) = str(i))
}
def makeCircle(grid: Array[Array[Char]], r: Double, c: Char) {
var theta = 0.0
while (theta < 2 * Pi) {
val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c
theta = theta + 0.01
}
}
def makeHand(grid: Array[Array[Char]], maxR: Double, theta: Double, c: Char) {
var r = 0.0
while (r < maxR) {
val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c
r = r + 0.01
}
}
makeCircle(grid, 0.98, '@')
makeHand(grid, 0.6, (localTime.getHour() + minute / 60.0 + second / 3600.0) * Pi / 6 - Pi / 2, 'O')
makeHand(grid, 0.85, (minute + second / 60.0) * Pi / 30 - Pi / 2, '*')
makeHand(grid, 0.90, second * Pi / 30 - Pi / 2, '.')
(1 to 12).foreach(n => makeText(grid, 0.87, n * Pi / 6 - Pi / 2, n.toString))
grid
} | 926Draw a clock
| 16scala
| aoy1n |
(import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address)
(doseq [addr (InetAddress/getAllByName "www.kame.net")]
(cond
(instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr))
(instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr)))) | 932DNS query
| 6clojure
| tlufv |
object Sphere extends App {
private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))
private def drawSphere(r: Double, k: Double, ambient: Double): Unit = {
def dot(x: Array[Double], y: Array[Double]) = {
val d = x.head * y.head + x(1) * y(1) + x.last * y.last
if (d < 0) -d else 0D
}
for (i <- math.floor(-r).toInt to math.ceil(r).toInt; x = i + .5)
println(
(for (j <- math.floor(-2 * r).toInt to math.ceil(2 * r).toInt; y = j / 2.0 + .5)
yield if (x * x + y * y <= r * r) {
def intensity(vec: Array[Double]) = {
val b = math.pow(dot(light, vec), k) + ambient
if (b <= 0) shades.length - 2
else math.max((1 - b) * (shades.length - 1), 0).toInt
}
shades(intensity(normalize(Array(x, y, scala.math.sqrt(r * r - x * x - y * y)))))
} else ' ').mkString)
}
private def normalize(v: Array[Double]): Array[Double] = {
val len = math.sqrt(v.head * v.head + v(1) * v(1) + v.last * v.last)
v.map(_ / len)
}
normalize(light).copyToArray(light)
drawSphere(20, 4, .1)
drawSphere(10, 2, .4)
} | 925Draw a sphere
| 16scala
| ei9ab |
module OutlineTree where
import Data.Bifunctor (first)
import Data.Bool (bool)
import Data.Char (isSpace)
import Data.List (find, intercalate)
import Data.Tree (Tree (..), foldTree, levels)
wikiTablesFromOutline :: [String] -> String -> String
wikiTablesFromOutline colorSwatch outline =
intercalate "\n\n" $
wikiTableFromTree colorSwatch
<$> ( forestFromLineIndents
. indentLevelsFromLines
. lines
)
outline
wikiTableFromTree :: [String] -> Tree String -> String
wikiTableFromTree colorSwatch =
wikiTableFromRows
. levels
. paintedTree colorSwatch
. widthLabelledTree
. (paddedTree "" <*> treeDepth)
main :: IO ()
main =
( putStrLn
. wikiTablesFromOutline
[ "#ffffe6",
"#ffebd2",
"#f0fff0",
"#e6ffff",
"#ffeeff"
]
)
"Display an outline as a nested table.\n\
\ Parse the outline to a tree,\n\
\ measuring the indent of each line,\n\
\ translating the indentation to a nested structure,\n\
\ and padding the tree to even depth.\n\
\ count the leaves descending from each node,\n\
\ defining the width of a leaf as 1,\n\
\ and the width of a parent node as a sum.\n\
\ (The sum of the widths of its children)\n\
\ and write out a table with 'colspan' values\n\
\ either as a wiki table,\n\
\ or as HTML."
forestFromLineIndents :: [(Int, String)] -> [Tree String]
forestFromLineIndents = go
where
go [] = []
go ((n, s): xs) =
let (subOutline, rest) = span ((n <) . fst) xs
in Node s (go subOutline): go rest
indentLevelsFromLines :: [String] -> [(Int, String)]
indentLevelsFromLines xs =
let pairs = first length . span isSpace <$> xs
indentUnit = maybe 1 fst (find ((0 <) . fst) pairs)
in first (`div` indentUnit) <$> pairs
paddedTree :: a -> Tree a -> Int -> Tree a
paddedTree padValue = go
where
go tree n
| 1 >= n = tree
| otherwise =
Node
(rootLabel tree)
( (`go` pred n)
<$> bool nest [Node padValue []] (null nest)
)
where
nest = subForest tree
treeDepth :: Tree a -> Int
treeDepth = foldTree go
where
go _ [] = 1
go _ xs = (succ . maximum) xs
widthLabelledTree :: Tree a -> Tree (a, Int)
widthLabelledTree = foldTree go
where
go x [] = Node (x, 1) []
go x xs =
Node
(x, foldr ((+) . snd . rootLabel) 0 xs)
xs
paintedTree :: [String] -> Tree a -> Tree (String, a)
paintedTree [] tree = fmap ("",) tree
paintedTree (color: colors) tree =
Node
(color, rootLabel tree)
( zipWith
(fmap . (,))
(cycle colors)
(subForest tree)
)
wikiTableFromRows :: [[(String, (String, Int))]] -> String
wikiTableFromRows rows =
let wikiRow = unlines . fmap cellText
cellText (color, (txt, width))
| null txt = "| |"
| otherwise =
"| "
<> cw color width
<> "| "
<> txt
cw color width =
let go w
| 1 < w = " colspan=" <> show w
| otherwise = ""
in "style=\"background:"
<> color
<> "; \""
<> go width
<> " "
in "{| class=\"wikitable\" "
<> "style=\"text-align: center;\"\n|-\n"
<> intercalate "|-\n" (wikiRow <$> rows)
<> "|}" | 933Display an outline as a nested table
| 8haskell
| hxsju |
package main
import "fmt"
func averageSquareDiff(f float64, preds []float64) (av float64) {
for _, pred := range preds {
av += (pred - f) * (pred - f)
}
av /= float64(len(preds))
return
}
func diversityTheorem(truth float64, preds []float64) (float64, float64, float64) {
av := 0.0
for _, pred := range preds {
av += pred
}
av /= float64(len(preds))
avErr := averageSquareDiff(truth, preds)
crowdErr := (truth - av) * (truth - av)
div := averageSquareDiff(av, preds)
return avErr, crowdErr, div
}
func main() {
predsArray := [2][]float64{{48, 47, 51}, {48, 47, 51, 42}}
truth := 49.0
for _, preds := range predsArray {
avErr, crowdErr, div := diversityTheorem(truth, preds)
fmt.Printf("Average-error:%6.3f\n", avErr)
fmt.Printf("Crowd-error :%6.3f\n", crowdErr)
fmt.Printf("Diversity :%6.3f\n\n", div)
}
} | 930Diversity prediction theorem
| 0go
| 5bwul |
package main
import (
"errors"
"log"
"net"
"net/http"
"net/rpc"
)
type TaxComputer float64
func (taxRate TaxComputer) Tax(x float64, r *float64) error {
if x < 0 {
return errors.New("Negative values not allowed")
}
*r = x * float64(taxRate)
return nil
}
func main() {
c := TaxComputer(.05)
rpc.Register(c)
rpc.HandleHTTP()
listener, err := net.Listen("tcp", ":1234")
if err != nil {
log.Fatal(err)
}
http.Serve(listener, nil)
} | 931Distributed programming
| 0go
| vh12m |
null | 929Documentation
| 0go
| nmui1 |
class DiversityPredictionTheorem {
private static double square(double d) {
return d * d
}
private static double averageSquareDiff(double d, double[] predictions) {
return Arrays.stream(predictions)
.map({ it -> square(it - d) })
.average()
.orElseThrow()
}
private static String diversityTheorem(double truth, double[] predictions) {
double average = Arrays.stream(predictions)
.average()
.orElseThrow()
return String.format("average-error:%6.3f%n", averageSquareDiff(truth, predictions)) + String.format("crowd-error :%6.3f%n", square(truth - average)) + String.format("diversity :%6.3f%n", averageSquareDiff(average, predictions))
}
static void main(String[] args) {
println(diversityTheorem(49.0, [48.0, 47.0, 51.0] as double[]))
println(diversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0] as double[]))
}
} | 930Diversity prediction theorem
| 7groovy
| crb9i |
(() => {
"use strict"; | 933Display an outline as a nested table
| 10javascript
| jwq7n |
var net = require('net')
var server = net.createServer(function (c){
c.write('hello\r\n')
c.pipe(c) // echo messages back
})
server.listen(3000, 'localhost') | 931Distributed programming
| 8haskell
| eitai |
var net = require('net')
var server = net.createServer(function (c){
c.write('hello\r\n')
c.pipe(c) | 931Distributed programming
| 10javascript
| aof10 |
package main
import (
"fmt"
"strings"
)
func linearCombo(c []int) string {
var sb strings.Builder
for i, n := range c {
if n == 0 {
continue
}
var op string
switch {
case n < 0 && sb.Len() == 0:
op = "-"
case n < 0:
op = " - "
case n > 0 && sb.Len() == 0:
op = ""
default:
op = " + "
}
av := n
if av < 0 {
av = -av
}
coeff := fmt.Sprintf("%d*", av)
if av == 1 {
coeff = ""
}
sb.WriteString(fmt.Sprintf("%s%se(%d)", op, coeff, i+1))
}
if sb.Len() == 0 {
return "0"
} else {
return sb.String()
}
}
func main() {
combos := [][]int{
{1, 2, 3},
{0, 1, 2, 3},
{1, 0, 3, 4},
{1, 2, 0},
{0, 0, 0},
{0},
{1, 1, 1},
{-1, -1, -1},
{-1, -2, 0, -3},
{-1},
}
for _, c := range combos {
t := strings.Replace(fmt.Sprint(c), " ", ", ", -1)
fmt.Printf("%-15s -> %s\n", t, linearCombo(c))
}
} | 928Display a linear combination
| 0go
| bsfkh |
square1 :: Int -> Int
square1 x = x * x
square2 :: Int -> Int
square2 x = x * x
square3 :: Int -> Int
square3 x = x * x
square4 :: Int -> Int
square4 x = x * x
data Tree a = Leaf a | Node [Tree a]
class Foo a where
bar :: a | 929Documentation
| 8haskell
| ukwv2 |
mean :: (Fractional a, Foldable t) => t a -> a
mean lst = sum lst / fromIntegral (length lst)
meanSq :: Fractional c => c -> [c] -> c
meanSq x = mean . map (\y -> (x-y)^^2)
diversityPrediction x estimates = do
putStrLn $ "TrueValue:\t" ++ show x
putStrLn $ "CrowdEstimates:\t" ++ show estimates
let avg = mean estimates
let avgerr = meanSq x estimates
putStrLn $ "AverageError:\t" ++ show avgerr
let crowderr = (x - avg)^^2
putStrLn $ "CrowdError:\t" ++ show crowderr
let diversity = meanSq avg estimates
putStrLn $ "Diversity:\t" ++ show diversity | 930Diversity prediction theorem
| 8haskell
| xd6w4 |
package main
import (
"fmt"
"net"
)
func main() {
if addrs, err := net.LookupHost("www.kame.net"); err == nil {
fmt.Println(addrs)
} else {
fmt.Println(err)
}
} | 932DNS query
| 0go
| 4pe52 |
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
my %rules = (
X => 'X+YF+',
Y => '-FX-Y'
);
my $dragon = 'FX';
$dragon =~ s/([XY])/$rules{$1}/eg for 1..10;
($x, $y) = (0, 0);
$theta = 0;
$r = 6;
for (split //, $dragon) {
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; }
}
$xrng = max(@X) - min(@X);
$yrng = max(@Y) - min(@Y);
$xt = -min(@X)+10;
$yt = -min(@Y)+10;
$svg = SVG->new(width=>$xrng+20, height=>$yrng+20);
$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 $fh, '>', 'dragon_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh; | 927Dragon curve
| 2perl
| o6u8x |
class LinearCombination {
private static String linearCombo(int[] c) {
StringBuilder sb = new StringBuilder()
for (int i = 0; i < c.length; ++i) {
if (c[i] == 0) continue
String op
if (c[i] < 0 && sb.length() == 0) {
op = "-"
} else if (c[i] < 0) {
op = " - "
} else if (c[i] > 0 && sb.length() == 0) {
op = ""
} else {
op = " + "
}
int av = Math.abs(c[i])
String coeff = av == 1 ? "": "" + av + "*"
sb.append(op).append(coeff).append("e(").append(i + 1).append(')')
}
if (sb.length() == 0) {
return "0"
}
return sb.toString()
}
static void main(String[] args) {
int[][] combos = [
[1, 2, 3],
[0, 1, 2, 3],
[1, 0, 3, 4],
[1, 2, 0],
[0, 0, 0],
[0],
[1, 1, 1],
[-1, -1, -1],
[-1, -2, 0, -3],
[-1]
]
for (int[] c: combos) {
printf("%-15s -> %s\n", Arrays.toString(c), linearCombo(c))
}
}
} | 928Display a linear combination
| 7groovy
| ra8gh |
public class Doc{
private String field;
public int method(long num) throws BadException{ | 929Documentation
| 9java
| m4kym |
import java.util.Arrays;
public class DiversityPredictionTheorem {
private static double square(double d) {
return d * d;
}
private static double averageSquareDiff(double d, double[] predictions) {
return Arrays.stream(predictions)
.map(it -> square(it - d))
.average()
.orElseThrow();
}
private static String diversityTheorem(double truth, double[] predictions) {
double average = Arrays.stream(predictions)
.average()
.orElseThrow();
return String.format("average-error:%6.3f%n", averageSquareDiff(truth, predictions))
+ String.format("crowd-error :%6.3f%n", square(truth - average))
+ String.format("diversity :%6.3f%n", averageSquareDiff(average, predictions));
}
public static void main(String[] args) {
System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0}));
System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0, 42.0}));
}
} | 930Diversity prediction theorem
| 9java
| bsnk3 |
class Sphere: UIView{
override func drawRect(rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()
let locations: [CGFloat] = [0.0, 1.0]
let colors = [UIColor.whiteColor().CGColor,
UIColor.blueColor().CGColor]
let colorspace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColors(colorspace,
colors, locations)
var startPoint = CGPoint()
var endPoint = CGPoint()
startPoint.x = self.center.x - (self.frame.width * 0.1)
startPoint.y = self.center.y - (self.frame.width * 0.15)
endPoint.x = self.center.x
endPoint.y = self.center.y
let startRadius: CGFloat = 0
let endRadius: CGFloat = self.frame.width * 0.38
CGContextDrawRadialGradient (context, gradient, startPoint,
startRadius, endPoint, endRadius,
0)
}
}
var s = Sphere(frame: CGRectMake(0, 0, 200, 200)) | 925Draw a sphere
| 17swift
| kqzhx |
use strict;
use warnings;
my @rows;
my $row = -1;
my $width = 0;
my $color = 0;
our $bg = 'e0ffe0';
parseoutline( do { local $/; <DATA> =~ s/\t/ /gr } );
print "<table border=1 cellspacing=0>\n";
for ( @rows )
{
my $start = 0;
print " <tr>\n";
for ( @$_ )
{
my ($data, $col, $span, $bg) = @$_;
print " <td></td>\n" x ( $col - $start ),
" <td colspan=$span align=center bgcolor=
$start = $col + $span;
}
print " <td></td>\n" x ( $width - $start ), " </tr>\n";
}
print "</table>\n";
sub parseoutline
{
++$row;
while( $_[0] =~ /^( *)(.*)\n((?:\1 .*\n)*)/gm )
{
my ($head, $body, $col) = ($2, $3, $width);
$row == 1 and local $bg = qw( ffffe0 ffe0e0 )[ $color ^= 1];
if( length $body ) { parseoutline( $body ) } else { ++$width }
push @{ $rows[$row] }, [ $head, $col, $width - $col, $bg ];
}
--$row;
}
__DATA__
Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML. | 933Display an outline as a nested table
| 2perl
| xdtw8 |
def addresses = InetAddress.getAllByName('www.kame.net')
println "IPv4: ${addresses.find { it instanceof Inet4Address }?.hostAddress}"
println "IPv6: ${addresses.find { it instanceof Inet6Address }?.hostAddress}" | 932DNS query
| 7groovy
| l7kc1 |
module Main where
import Network.Socket
getWebAddresses :: HostName -> IO [SockAddr]
getWebAddresses host = do
results <- getAddrInfo (Just defaultHints) (Just host) (Just "http")
return [ addrAddress a | a <- results, addrSocketType a == Stream ]
showIPs :: HostName -> IO ()
showIPs host = do
putStrLn $ "IP addresses for " ++ host ++ ":"
addresses <- getWebAddresses host
mapM_ (putStrLn . (" "++) . show) addresses
main = showIPs "www.kame.net" | 932DNS query
| 8haskell
| qf3x9 |
import Text.Printf (printf)
linearForm :: [Int] -> String
linearForm = strip . concat . zipWith term [1..]
where
term :: Int -> Int -> String
term i c = case c of
0 -> mempty
1 -> printf "+e(%d)" i
-1 -> printf "-e(%d)" i
c -> printf "%+d*e(%d)" c i
strip str = case str of
'+':s -> s
"" -> "0"
s -> s | 928Display a linear combination
| 8haskell
| d94n4 |
class Group<T>(val name: String) {
fun add(member: T): Int { ... }
} | 929Documentation
| 11kotlin
| tlgf0 |
'use strict';
function sum(array) {
return array.reduce(function (a, b) {
return a + b;
});
}
function square(x) {
return x * x;
}
function mean(array) {
return sum(array) / array.length;
}
function averageSquareDiff(a, predictions) {
return mean(predictions.map(function (x) {
return square(x - a);
}));
}
function diversityTheorem(truth, predictions) {
var average = mean(predictions);
return {
'average-error': averageSquareDiff(truth, predictions),
'crowd-error': square(truth - average),
'diversity': averageSquareDiff(average, predictions)
};
}
console.log(diversityTheorem(49, [48,47,51]))
console.log(diversityTheorem(49, [48,47,51,42])) | 930Diversity prediction theorem
| 10javascript
| wn3e2 |
null | 929Documentation
| 1lua
| z2rty |
import itertools
import re
import sys
from collections import deque
from typing import NamedTuple
RE_OUTLINE = re.compile(r, re.M)
COLORS = itertools.cycle(
[
,
,
,
,
,
]
)
class Node:
def __init__(self, indent, value, parent, children=None):
self.indent = indent
self.value = value
self.parent = parent
self.children = children or []
self.color = None
def depth(self):
if self.parent:
return self.parent.depth() + 1
return -1
def height(self):
if not self.children:
return 0
return max(child.height() for child in self.children) + 1
def colspan(self):
if self.leaf:
return 1
return sum(child.colspan() for child in self.children)
@property
def leaf(self):
return not bool(self.children)
def __iter__(self):
q = deque()
q.append(self)
while q:
node = q.popleft()
yield node
q.extend(node.children)
class Token(NamedTuple):
indent: int
value: str
def tokenize(outline):
for match in RE_OUTLINE.finditer(outline):
indent, value = match.groups()
yield Token(len(indent), value)
def parse(outline):
tokens = list(tokenize(outline))
temp_root = Node(-1, , None)
_parse(tokens, 0, temp_root)
root = temp_root.children[0]
pad_tree(root, root.height())
return root
def _parse(tokens, index, node):
if index >= len(tokens):
return
token = tokens[index]
if token.indent == node.indent:
current = Node(token.indent, token.value, node.parent)
node.parent.children.append(current)
_parse(tokens, index + 1, current)
elif token.indent > node.indent:
current = Node(token.indent, token.value, node)
node.children.append(current)
_parse(tokens, index + 1, current)
elif token.indent < node.indent:
_parse(tokens, index, node.parent)
def pad_tree(node, height):
if node.leaf and node.depth() < height:
pad_node = Node(node.indent + 1, , node)
node.children.append(pad_node)
for child in node.children:
pad_tree(child, height)
def color_tree(node):
if not node.value:
node.color =
elif node.depth() <= 1:
node.color = next(COLORS)
else:
node.color = node.parent.color
for child in node.children:
color_tree(child)
def table_data(node):
indent =
if node.colspan() > 1:
colspan = f'colspan='
else:
colspan =
if node.color:
style = f'style='
else:
style =
attrs = .join([colspan, style])
return f
def html_table(tree):
table_cols = tree.colspan()
row_cols = 0
buf = []
for node in tree:
if row_cols == 0:
buf.append()
buf.append(table_data(node))
row_cols += node.colspan()
if row_cols == table_cols:
buf.append()
row_cols = 0
buf.append()
return .join(buf)
def wiki_table_data(node):
if not node.value:
return
if node.colspan() > 1:
colspan = f
else:
colspan =
if node.color:
style = f'style='
else:
style =
attrs = .join([colspan, style])
return f
def wiki_table(tree):
table_cols = tree.colspan()
row_cols = 0
buf = ['{| class= style=']
for node in tree:
if row_cols == 0:
buf.append()
buf.append(wiki_table_data(node))
row_cols += node.colspan()
if row_cols == table_cols:
row_cols = 0
buf.append()
return .join(buf)
def example(table_format=):
outline = (
)
tree = parse(outline)
color_tree(tree)
if table_format == :
print(wiki_table(tree))
else:
print(html_table(tree))
if __name__ == :
args = sys.argv[1:]
if len(args) == 1:
table_format = args[0]
else:
table_format =
example(table_format) | 933Display an outline as a nested table
| 3python
| qfzxi |
use Data::Dumper;
use IO::Socket::INET;
use Safe;
sub get_data {
my $sock = new IO::Socket::INET
LocalHost => "localhost",
LocalPort => "10000",
Proto => "tcp",
Listen => 1,
Reuse => 1;
unless ($sock) { die "Socket creation failure" }
my $cli = $sock->accept();
my $safe = new Safe;
my $x = $safe->reval(join("", <$cli>));
close $cli;
close $sock;
return $x;
}
sub send_data {
my $host = shift;
my $data = shift;
my $sock = new IO::Socket::INET
PeerAddr => "$host:10000",
Proto => "tcp",
Reuse => 1;
unless ($sock) { die "Socket creation failure" }
print $sock Data::Dumper->Dump([$data]);
close $sock;
}
if (@ARGV) {
my $x = get_data();
print "Got data\n", Data::Dumper->Dump([$x]);
} else {
send_data('some_host', { a=>100, b=>[1 .. 10] });
} | 931Distributed programming
| 2perl
| iylo3 |
import java.net.InetAddress;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
class DnsQuery {
public static void main(String[] args) {
try {
InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net");
for(int i=0; i < ipAddr.length ; i++) {
if (ipAddr[i] instanceof Inet4Address) {
System.out.println("IPv4: " + ipAddr[i].getHostAddress());
} else if (ipAddr[i] instanceof Inet6Address) {
System.out.println("IPv6: " + ipAddr[i].getHostAddress());
}
}
} catch (UnknownHostException uhe) {
System.err.println("unknown host");
}
}
} | 932DNS query
| 9java
| p0ib3 |
const dns = require("dns");
dns.lookup("www.kame.net", {
all: true
}, (err, addresses) => {
if(err) return console.error(err);
console.log(addresses);
}) | 932DNS query
| 10javascript
| xdzw9 |
import java.util.Arrays;
public class LinearCombination {
private static String linearCombo(int[] c) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c.length; ++i) {
if (c[i] == 0) continue;
String op;
if (c[i] < 0 && sb.length() == 0) {
op = "-";
} else if (c[i] < 0) {
op = " - ";
} else if (c[i] > 0 && sb.length() == 0) {
op = "";
} else {
op = " + ";
}
int av = Math.abs(c[i]);
String coeff = av == 1 ? "" : "" + av + "*";
sb.append(op).append(coeff).append("e(").append(i + 1).append(')');
}
if (sb.length() == 0) {
return "0";
}
return sb.toString();
}
public static void main(String[] args) {
int[][] combos = new int[][]{
new int[]{1, 2, 3},
new int[]{0, 1, 2, 3},
new int[]{1, 0, 3, 4},
new int[]{1, 2, 0},
new int[]{0, 0, 0},
new int[]{0},
new int[]{1, 1, 1},
new int[]{-1, -1, -1},
new int[]{-1, -2, 0, -3},
new int[]{-1},
};
for (int[] c : combos) {
System.out.printf("%-15s -> %s\n", Arrays.toString(c), linearCombo(c));
}
}
} | 928Display a linear combination
| 9java
| stcq0 |
null | 932DNS query
| 11kotlin
| 7eqr4 |
null | 930Diversity prediction theorem
| 11kotlin
| rasgo |
function square(x)
return x * x
end
function mean(a)
local s = 0
local c = 0
for i,v in pairs(a) do
s = s + v
c = c + 1
end
return s / c
end
function averageSquareDiff(a, predictions)
local results = {}
for i,x in pairs(predictions) do
table.insert(results, square(x - a))
end
return mean(results)
end
function diversityTheorem(truth, predictions)
local average = mean(predictions)
print("average-error: " .. averageSquareDiff(truth, predictions))
print("crowd-error: " .. square(truth - average))
print("diversity: " .. averageSquareDiff(average, predictions))
end
function main()
diversityTheorem(49, {48, 47, 51})
diversityTheorem(49, {48, 47, 51, 42})
end
main() | 930Diversity prediction theorem
| 1lua
| 7e0ru |
struct List {
struct MNode *head;
struct MNode *tail;
struct MNode *tail_pred;
};
struct MNode {
struct MNode *succ;
struct MNode *pred;
};
typedef struct MNode *NODE;
typedef struct List *LIST;
LIST newList(void);
int isEmpty(LIST);
NODE getTail(LIST);
NODE getHead(LIST);
NODE addTail(LIST, NODE);
NODE addHead(LIST, NODE);
NODE remHead(LIST);
NODE remTail(LIST);
NODE insertAfter(LIST, NODE, NODE);
NODE removeNode(LIST, NODE);
LIST newList(void)
{
LIST tl = malloc(sizeof(struct List));
if ( tl != NULL )
{
tl->tail_pred = (NODE)&tl->head;
tl->tail = NULL;
tl->head = (NODE)&tl->tail;
return tl;
}
return NULL;
}
int isEmpty(LIST l)
{
return (l->head->succ == 0);
}
NODE getHead(LIST l)
{
return l->head;
}
NODE getTail(LIST l)
{
return l->tail_pred;
}
NODE addTail(LIST l, NODE n)
{
n->succ = (NODE)&l->tail;
n->pred = l->tail_pred;
l->tail_pred->succ = n;
l->tail_pred = n;
return n;
}
NODE addHead(LIST l, NODE n)
{
n->succ = l->head;
n->pred = (NODE)&l->head;
l->head->pred = n;
l->head = n;
return n;
}
NODE remHead(LIST l)
{
NODE h;
h = l->head;
l->head = l->head->succ;
l->head->pred = (NODE)&l->head;
return h;
}
NODE remTail(LIST l)
{
NODE t;
t = l->tail_pred;
l->tail_pred = l->tail_pred->pred;
l->tail_pred->succ = (NODE)&l->tail;
return t;
}
NODE insertAfter(LIST l, NODE r, NODE n)
{
n->pred = r; n->succ = r->succ;
n->succ->pred = n; r->succ = n;
return n;
}
NODE removeNode(LIST l, NODE n)
{
n->pred->succ = n->succ;
n->succ->pred = n->pred;
return n;
} | 934Doubly-linked list/Definition
| 5c
| tl2f4 |
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
'''Method for returning data got from client'''
return 'Server responded:%s'% data
def div(self, num1, num2):
'''Method for divide 2 numbers'''
return num1/num2
def foo_function():
'''A function (not an instance method)'''
return True
HOST =
PORT = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))
server.register_introspection_functions()
server.register_instance(MyHandlerInstance())
server.register_function(foo_function)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting...'
server.server_close() | 931Distributed programming
| 3python
| nm2iz |
local socket = require('socket')
local ip_tbl = socket.dns.getaddrinfo('www.kame.net')
for _, v in ipairs(ip_tbl) do
io.write(string.format('%s:%s\n', v.family, v.addr))
end | 932DNS query
| 1lua
| jws71 |
null | 928Display a linear combination
| 11kotlin
| ao313 |
procedure StoreVar(integer N, integer NTyp)
--
-- Store a variable, applying any final operator as needed.
-- If N is zero, PopFactor (ie store in a new temporary variable of
-- the specified type). Otherwise N should be an index to symtab.
-- If storeConst is 1, NTyp is ignored/overridden, otherwise it
-- should usually be the declared or local type of N.
--
...
end procedure | 929Documentation
| 2perl
| kqnhc |
: (doc 'car)
: (doc '+Entity)
: (doc '+ 'firefox) | 929Documentation
| 12php
| 3v7zq |
sub diversity {
my($truth, @pred) = @_;
my($ae,$ce,$cp,$pd,$stats);
$cp += $_/@pred for @pred;
$ae = avg_error($truth, @pred);
$ce = ($cp - $truth)**2;
$pd = avg_error($cp, @pred);
my $fmt = "%13s:%6.3f\n";
$stats = sprintf $fmt, 'average-error', $ae;
$stats .= sprintf $fmt, 'crowd-error', $ce;
$stats .= sprintf $fmt, 'diversity', $pd;
}
sub avg_error {
my($m, @v) = @_;
my($avg_err);
$avg_err += ($_ - $m)**2 for @v;
$avg_err/@v;
}
print diversity(49, qw<48 47 51>) . "\n";
print diversity(49, qw<48 47 51 42>); | 930Diversity prediction theorem
| 2perl
| d9unw |
require 'drb/drb'
URI=
class TimeServer
def get_current_time
return Time.now
end
end
FRONT_OBJECT = TimeServer.new
$SAFE = 1
DRb.start_service(URI, FRONT_OBJECT)
DRb.thread.join | 931Distributed programming
| 14ruby
| fcudr |
function t2s(t)
local s = "["
for i,v in pairs(t) do
if i > 1 then
s = s .. ", " .. v
else
s = s .. v
end
end
return s .. "]"
end
function linearCombo(c)
local sb = ""
for i,n in pairs(c) do
local skip = false
if n < 0 then
if sb:len() == 0 then
sb = sb .. "-"
else
sb = sb .. " - "
end
elseif n > 0 then
if sb:len() ~= 0 then
sb = sb .. " + "
end
else
skip = true
end
if not skip then
local av = math.abs(n)
if av ~= 1 then
sb = sb .. av .. "*"
end
sb = sb .. "e(" .. i .. ")"
end
end
if sb:len() == 0 then
sb = "0"
end
return sb
end
function main()
local combos = {
{ 1, 2, 3},
{ 0, 1, 2, 3 },
{ 1, 0, 3, 4 },
{ 1, 2, 0 },
{ 0, 0, 0 },
{ 0 },
{ 1, 1, 1 },
{ -1, -1, -1 },
{ -1, -2, 0, -3 },
{ -1 }
}
for i,c in pairs(combos) do
local arr = t2s(c)
print(string.format("%15s ->%s", arr, linearCombo(c)))
end
end
main() | 928Display a linear combination
| 1lua
| ei6ac |
(ns double-list)
(defprotocol PDoubleList
(get-head [this])
(add-head [this x])
(get-tail [this])
(add-tail [this x])
(remove-node [this node])
(add-before [this node x])
(add-after [this node x])
(get-nth [this n]))
(defrecord Node [prev next data])
(defn make-node
"Create an internal or finalized node"
([prev next data] (Node. prev next data))
([m key] (when-let [node (get m key)]
(assoc node:m m:key key))))
(defn get-next [node] (make-node (:m node) (:next node)))
(defn get-prev [node] (make-node (:m node) (:prev node)))
(defn- seq* [m start next]
(seq
(for [x (iterate #(get m (next %)) (get m start))
:while x]
(:data x))))
(defmacro when->
([x pred form] `(let [x# ~x] (if ~pred (-> x# ~form) x#)))
([x pred form & more] `(when-> (when-> ~x ~pred ~form) ~@more)))
(declare get-nth-key)
(deftype DoubleList [m head tail]
Object
(equals [this x]
(and (instance? DoubleList x)
(= m (.m ^DoubleList x))))
(hashCode [this] (hash (or this ())))
clojure.lang.Sequential
clojure.lang.Counted
(count [_] (count m))
clojure.lang.Seqable
(seq [_] (seq* m head:next))
clojure.lang.Reversible
(rseq [_] (seq* m tail:prev))
clojure.lang.IPersistentCollection
(empty [_] (DoubleList. (empty m) nil nil))
(equiv [this x]
(and (sequential? x)
(= (seq x) (seq this))))
(cons [this x] (.add-tail this x))
PDoubleList
(get-head [_] (make-node m head))
(add-head [this x]
(let [new-key (Object.)
m (when-> (assoc m new-key (make-node nil head x))
head (assoc-in [head:prev] new-key))
tail (if tail tail new-key)]
(DoubleList. m new-key tail)))
(get-tail [_] (make-node m tail))
(add-tail [this x]
(if-let [tail (.get-tail this)]
(.add-after this tail x)
(.add-head this x)))
(remove-node [this node]
(if (get m (:key node))
(let [{:keys [prev next key]} node
head (if prev head next)
tail (if next tail prev)
m (when-> (dissoc m key)
prev (assoc-in [prev:next] next)
next (assoc-in [next:prev] prev))]
(DoubleList. m head tail))
this))
(add-after [this node x]
(if (get m (:key node))
(let [{:keys [prev next key]} node
new-key (Object.)
m (when-> (-> (assoc m new-key (make-node key next x))
(assoc-in , [key:next] new-key))
next (assoc-in [next:prev] new-key))
tail (if next tail new-key)]
(DoubleList. m head tail))
this))
(add-before [this node x]
(if (:prev node)
(.add-after this (get-prev node) x)
(.add-head this x)))
(get-nth [this n] (make-node m (get-nth-key this n))))
(defn get-nth-key [^DoubleList this n]
(if (< -1 n (.count this))
(let [[start next n] (if (< n (/ (.count this) 2))
[(.head this):next n]
[(.tail this):prev (- (.count this) n 1)])]
(nth (iterate #(get-in (.m this) [% next]) start) n))
(throw (IndexOutOfBoundsException.))))
(defn double-list
([] (DoubleList. nil nil nil))
([coll] (into (double-list) coll)))
(defmethod print-method DoubleList [dl w]
(print-method (interpose '<-> (seq dl)) w))
(defmethod print-method Node [n w]
(print-method (symbol "#:double_list.Node") w)
(print-method (into {} (dissoc n:m)) w)) | 934Doubly-linked list/Definition
| 6clojure
| m4gyq |
use feature 'say';
use Socket qw(getaddrinfo getnameinfo);
my ($err, @res) = getaddrinfo('orange.kame.net', 0, { protocol=>Socket::IPPROTO_TCP } );
die "getaddrinfo error: $err" if $err;
say ((getnameinfo($_->{addr}, Socket::NI_NUMERICHOST))[1]) for @res | 932DNS query
| 2perl
| fcvd7 |
class Doc(object):
def method(self, num):
pass | 929Documentation
| 3python
| bsdkr |
example(package.skeleton) | 929Documentation
| 13r
| 7e8ry |
package main
import (
"fmt"
"strconv"
)
const DMAX = 20 | 935Disarium numbers
| 0go
| qffxz |
use strict;
use warnings;
use feature 'say';
sub linear_combination {
my(@coef) = @$_;
my $e = '';
for my $c (1..+@coef) { $e .= "$coef[$c-1]*e($c) + " if $coef[$c-1] }
$e =~ s/ \+ $//;
$e =~ s/1\*//g;
$e =~ s/\+ -/- /g;
$e or 0;
}
say linear_combination($_) for
[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, -3], [-1 ] | 928Display a linear combination
| 2perl
| 9gpmn |
'''Diversity prediction theorem'''
from itertools import chain
from functools import reduce
def diversityValues(x):
'''The mean error, crowd error and
diversity, for a given observation x
and a non-empty list of predictions ps.
'''
def go(ps):
mp = mean(ps)
return {
'mean-error': meanErrorSquared(x)(ps),
'crowd-error': pow(x - mp, 2),
'diversity': meanErrorSquared(mp)(ps)
}
return go
def meanErrorSquared(x):
'''The mean of the squared differences
between the observed value x and
a non-empty list of predictions ps.
'''
def go(ps):
return mean([
pow(p - x, 2) for p in ps
])
return go
def main():
'''Observed value: 49,
prediction lists: various.
'''
print(unlines(map(
showDiversityValues(49),
[
[48, 47, 51],
[48, 47, 51, 42],
[50, '?', 50, {}, 50],
[]
]
)))
print(unlines(map(
showDiversityValues('49'),
[
[50, 50, 50],
[40, 35, 40],
]
)))
def showDiversityValues(x):
'''Formatted string representation
of diversity values for a given
observation x and a non-empty
list of predictions p.
'''
def go(ps):
def showDict(dct):
w = 4 + max(map(len, dct.keys()))
def showKV(a, kv):
k, v = kv
return a + k.rjust(w, ' ') + (
': ' + showPrecision(3)(v) + '\n'
)
return 'Predictions: ' + showList(ps) + ' ->\n' + (
reduce(showKV, dct.items(), '')
)
def showProblem(e):
return (
unlines(map(indented(1), e)) if (
isinstance(e, list)
) else indented(1)(repr(e))
) + '\n'
return 'Observation: ' + repr(x) + '\n' + (
either(showProblem)(showDict)(
bindLR(numLR(x))(
lambda n: bindLR(numsLR(ps))(
compose(Right, diversityValues(n))
)
)
)
)
return go
def Left(x):
'''Constructor for an empty Either (option type) value
with an associated string.
'''
return {'type': 'Either', 'Right': None, 'Left': x}
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
def bindLR(m):
'''Either monad injection operator.
Two computations sequentially composed,
with any value produced by the first
passed as an argument to the second.
'''
def go(mf):
return (
mf(m.get('Right')) if None is m.get('Left') else m
)
return go
def compose(*fs):
'''Composition, from right to left,
of a series of functions.
'''
def go(f, g):
def fg(x):
return f(g(x))
return fg
return reduce(go, fs, identity)
def concatMap(f):
'''A concatenated list over which a function has been mapped.
The list monad can be derived by using a function f which
wraps its output in a list,
(using an empty list to represent computational failure).
'''
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def either(fl):
'''The application of fl to e if e is a Left value,
or the application of fr to e if e is a Right value.
'''
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
) else fr(e['Right'])
def identity(x):
'''The identity function.'''
return x
def indented(n):
'''String indented by n multiples
of four spaces.
'''
return lambda s: (4 * ' ' * n) + s
def mean(xs):
'''Arithmetic mean of a list
of numeric values.
'''
return sum(xs) / float(len(xs))
def numLR(x):
'''Either Right x if x is a float or int,
or a Left explanatory message.'''
return Right(x) if (
isinstance(x, (float, int))
) else Left(
'Expected number, saw: ' + (
str(type(x)) + ' ' + repr(x)
)
)
def numsLR(xs):
'''Either Right xs if all xs are float or int,
or a Left explanatory message.'''
def go(ns):
ls, rs = partitionEithers(map(numLR, ns))
return Left(ls) if ls else Right(rs)
return bindLR(
Right(xs) if (
bool(xs) and isinstance(xs, list)
) else Left(
'Expected a non-empty list, saw: ' + (
str(type(xs)) + ' ' + repr(xs)
)
)
)(go)
def partitionEithers(lrs):
'''A list of Either values partitioned into a tuple
of two lists, with all Left elements extracted
into the first list, and Right elements
extracted into the second list.
'''
def go(a, x):
ls, rs = a
r = x.get('Right')
return (ls + [x.get('Left')], rs) if None is r else (
ls, rs + [r]
)
return reduce(go, lrs, ([], []))
def showList(xs):
'''Compact string representation of a list'''
return '[' + ','.join(str(x) for x in xs) + ']'
def showPrecision(n):
'''A string showing a floating point number
at a given degree of precision.'''
def go(x):
return str(round(x, n))
return go
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
if __name__ == '__main__':
main() | 930Diversity prediction theorem
| 3python
| fc5de |
module Disarium
where
import Data.Char ( digitToInt)
isDisarium :: Int -> Bool
isDisarium n = (sum $ map (\(c , i ) -> (digitToInt c ) ^ i )
$ zip ( show n ) [1 , 2 ..]) == n
solution :: [Int]
solution = take 18 $ filter isDisarium [0, 1 ..] | 935Disarium numbers
| 8haskell
| m44yf |
<?php
$ipv4_record = dns_get_record(,DNS_A);
$ipv6_record = dns_get_record(,DNS_AAAA);
print . $ipv4_record[0][] . ;
print . $ipv6_record[0][] . ;
?> | 932DNS query
| 12php
| hx0jf |
from turtle import *
def dragon(step, length):
dcr(step, length)
def dcr(step, length):
step -= 1
length /= 1.41421
if step > 0:
right(45)
dcr(step, length)
left(90)
dcl(step, length)
right(45)
else:
right(45)
forward(length)
left(90)
forward(length)
right(45)
def dcl(step, length):
step -= 1
length /= 1.41421
if step > 0:
left(45)
dcr(step, length)
right(90)
dcl(step, length)
left(45)
else:
left(45)
forward(length)
right(90)
forward(length)
left(45) | 927Dragon curve
| 3python
| iy5of |
diversityStats <- function(trueValue, estimates)
{
collectivePrediction <- mean(estimates)
data.frame("True Value" = trueValue,
as.list(setNames(estimates, paste("Guess", seq_along(estimates)))),
"Average Error" = mean((trueValue - estimates)^2),
"Crowd Error" = (trueValue - collectivePrediction)^2,
"Prediction Diversity" = mean((estimates - collectivePrediction)^2))
}
diversityStats(49, c(48, 47, 51))
diversityStats(49, c(48, 47, 51, 42)) | 930Diversity prediction theorem
| 13r
| o6l84 |
use strict;
use warnings;
my ($n,@D) = (0, 0);
while (++$n) {
my($m,$sum);
map { $sum += $_ ** ++$m } split '', $n;
push @D, $n if $n == $sum;
last if 19 == @D;
}
print "@D\n"; | 935Disarium numbers
| 2perl
| 4pp5d |
>>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194 | 932DNS query
| 3python
| tlufw |
using namespace Rcpp ;
// [[Rcpp::export]]
CharacterVector getNameInfo(std::string fqdn) {
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);
if (error) { return(NA_STRING); }
int i = 0 ;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { i++ ; }
}
CharacterVector results(i) ;
i = 0;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { results[i++] = host ; }
}
freeaddrinfo(res0);
return(results) ;
} | 932DNS query
| 13r
| iyco5 |
=begin rdoc
RDoc is documented here[http:
This is a class documentation comment. This text shows at the top of the page
for the class.
Comments can be written inside / blocks or
in normal '
There are no '@parameters' like javadoc, but 'name-value' lists can be written:
Author:: Joe Schmoe
Date:: today
=end
class Doc
Constant = nil
def a_method(arg1, arg2='default value')
do_stuff
end
def self.class_method
Constant
end
end | 929Documentation
| 14ruby
| 18tpw |
null | 929Documentation
| 15rust
| aoz14 |
class Doc {
private val field = 0
def method(num: Long): Int = { | 929Documentation
| 16scala
| xdywg |
Dragon<-function(Iters){
Rotation<-matrix(c(0,-1,1,0),ncol=2,byrow=T)
Iteration<-list()
Iteration[[1]] <- matrix(rep(0,16), ncol = 4)
Iteration[[1]][1,]<-c(0,0,1,0)
Iteration[[1]][2,]<-c(1,0,1,-1)
Moveposition<-rep(0,Iters)
Moveposition[1]<-4
if(Iters > 1){
for(l in 2:Iters){
Moveposition[l]<-(Moveposition[l-1]*2)-2
}}
Move<-list()
for (i in 1:Iters){
half<-dim(Iteration[[i]])[1]/2
half<-1:half
for(j in half){
Iteration[[i]][j+length(half),]<-c(Iteration[[i]][j,1:2]%*%Rotation,Iteration[[i]][j,3:4]%*%Rotation)
}
Move[[i]]<-matrix(rep(0,4),ncol=4)
Move[[i]][1,1:2]<-Move[[i]][1,3:4]<-(Iteration[[i]][Moveposition[i],c(3,4)]*-1)
Iteration[[i+1]]<-matrix(rep(0,2*dim(Iteration[[i]])[1]*4),ncol=4)
for(k in 1:dim(Iteration[[i]])[1]){
Iteration[[i+1]][k,]<-Iteration[[i]][k,]+Move[[i]]
}
xlimits<-c(min(Iteration[[i]][,3])-2,max(Iteration[[i]][,3]+2))
ylimits<-c(min(Iteration[[i]][,4])-2,max(Iteration[[i]][,4]+2))
plot(0,0,type='n',axes=FALSE,xlab="",ylab="",xlim=xlimits,ylim=ylimits)
s<-dim(Iteration[[i]])[1]
s<-1:s
segments(Iteration[[i]][s,1], Iteration[[i]][s,2], Iteration[[i]][s,3], Iteration[[i]][s,4], col= 'red')
}} | 927Dragon curve
| 13r
| stlqy |
def linear(x):
return ' + '.join(['{}e({})'.format('-' if v == -1 else '' if v == 1 else str(v) + '*', i + 1)
for i, v in enumerate(x) if v] or ['0']).replace(' + -', ' - ')
list(map(lambda x: print(linear(x)), [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0],
[0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, 3], [-1]])) | 928Display a linear combination
| 3python
| cr19q |
def mean(a) = a.sum(0.0) / a.size
def mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 })
def diversity_theorem(truth, predictions)
average = mean(predictions)
puts ,
,
,
,
end
diversity_theorem(49.0, [48.0, 47.0, 51.0])
diversity_theorem(49.0, [48.0, 47.0, 51.0, 42.0]) | 930Diversity prediction theorem
| 14ruby
| z2gtw |
def isDisarium(n):
digitos = len(str(n))
suma = 0
x = n
while x != 0:
suma += (x% 10) ** digitos
digitos -= 1
x
if suma == n:
return True
else:
return False
if __name__ == '__main__':
limite = 19
cont = 0
n = 0
print(,limite,)
while cont < limite:
if isDisarium(n):
print(n, end = )
cont += 1
n += 1 | 935Disarium numbers
| 3python
| g114h |
irb(main):001:0> require 'socket'
=> true
irb(main):002:0> Addrinfo.getaddrinfo(, nil, nil, :DGRAM) \
irb(main):003:0* .map! { |ai| ai.ip_address }
=> [, ] | 932DNS query
| 14ruby
| 3v4z7 |
func add(a: Int, b: Int) -> Int {
return a + b
} | 929Documentation
| 17swift
| p0fbl |
object DiversityPredictionTheorem {
def square(d: Double): Double
= d * d
def average(a: Array[Double]): Double
= a.sum / a.length
def averageSquareDiff(d: Double, predictions: Array[Double]): Double
= average(predictions.map(it => square(it - d)))
def diversityTheorem(truth: Double, predictions: Array[Double]): String = {
val avg = average(predictions)
f"average-error: ${averageSquareDiff(truth, predictions)}%6.3f\n" +
f"crowd-error : ${square(truth - avg)}%6.3f\n"+
f"diversity : ${averageSquareDiff(avg, predictions)}%6.3f\n"
}
def main(args: Array[String]): Unit = {
println(diversityTheorem(49.0, Array(48.0, 47.0, 51.0)))
println(diversityTheorem(49.0, Array(48.0, 47.0, 51.0, 42.0)))
}
} | 930Diversity prediction theorem
| 16scala
| m4hyc |
use std::net::ToSocketAddrs;
fn main() {
let host = "www.kame.net"; | 932DNS query
| 15rust
| 6ug3l |
import java.net._
InetAddress.getAllByName("www.kame.net").foreach(x => println(x.getHostAddress)) | 932DNS query
| 16scala
| 9gjm5 |
function sum(array: Array<number>): number {
return array.reduce((a, b) => a + b)
}
function square(x: number):number {
return x * x
}
function mean(array: Array<number>): number {
return sum(array) / array.length
}
function averageSquareDiff(a: number, predictions: Array<number>): number {
return mean(predictions.map(x => square(x - a)))
}
function diversityTheorem(truth: number, predictions: Array<number>): Object {
const average: number = mean(predictions)
return {
"average-error": averageSquareDiff(truth, predictions),
"crowd-error": square(truth - average),
"diversity": averageSquareDiff(average, predictions)
}
}
console.log(diversityTheorem(49, [48,47,51]))
console.log(diversityTheorem(49, [48,47,51,42])) | 930Diversity prediction theorem
| 20typescript
| g1q4g |
def linearCombo(c)
sb =
c.each_with_index { |n, i|
if n == 0 then
next
end
if n < 0 then
if sb.length == 0 then
op =
else
op =
end
elsif n > 0 then
if sb.length > 0 then
op =
else
op =
end
else
op =
end
av = n.abs()
if av!= 1 then
coeff = % [av]
else
coeff =
end
sb = sb + % [op, coeff, i + 1]
}
if sb.length == 0 then
return
end
return sb
end
def main
combos = [
[1, 2, 3],
[0, 1, 2, 3],
[1, 0, 3, 4],
[1, 2, 0],
[0, 0, 0],
[0],
[1, 1, 1],
[-1, -1, -1],
[-1, -2, 0, -3],
[-1],
]
for c in combos do
print % [c, linearCombo(c)]
end
end
main() | 928Display a linear combination
| 14ruby
| 2jelw |
type dlNode struct {
int
next, prev *dlNode
} | 934Doubly-linked list/Definition
| 0go
| hxqjq |
use std::fmt::{Display, Formatter, Result};
use std::process::exit;
struct Coefficient(usize, f64);
impl Display for Coefficient {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let i = self.0;
let c = self.1;
if c == 0. {
return Ok(());
}
write!(
f,
" {} {}e({})",
if c < 0. {
"-"
} else if f.alternate() {
" "
} else {
"+"
},
if (c.abs() - 1.).abs() < f64::EPSILON {
"".to_string()
} else {
c.abs().to_string() + "*"
},
i + 1
)
}
}
fn usage() {
println!("Usage: display-linear-combination a1 [a2 a3 ...]");
}
fn linear_combination(coefficients: &[f64]) -> String {
let mut string = String::new();
let mut iter = coefficients.iter().enumerate(); | 928Display a linear combination
| 15rust
| vhw2t |
object LinearCombination extends App {
val combos = Seq(Seq(1, 2, 3), Seq(0, 1, 2, 3),
Seq(1, 0, 3, 4), Seq(1, 2, 0), Seq(0, 0, 0), Seq(0),
Seq(1, 1, 1), Seq(-1, -1, -1), Seq(-1, -2, 0, -3), Seq(-1))
private def linearCombo(c: Seq[Int]): String = {
val sb = new StringBuilder
for {i <- c.indices
term = c(i)
if term != 0} {
val av = math.abs(term)
def op = if (term < 0 && sb.isEmpty) "-"
else if (term < 0) " - "
else if (term > 0 && sb.isEmpty) "" else " + "
sb.append(op).append(if (av == 1) "" else s"$av*").append("e(").append(i + 1).append(')')
}
if (sb.isEmpty) "0" else sb.toString
}
for (c <- combos) {
println(f"${c.mkString("[", ", ", "]")}%-15s -> ${linearCombo(c)}%s")
}
} | 928Display a linear combination
| 16scala
| 4ps50 |
import qualified Data.Map as M
type NodeID = Maybe Rational
data Node a = Node
{vNode :: a,
pNode, nNode :: NodeID}
type DLList a = M.Map Rational (Node a)
empty = M.empty
singleton a = M.singleton 0 $ Node a Nothing Nothing
fcons :: a -> DLList a -> DLList a
fcons a list | M.null list = singleton a
| otherwise = M.insert newid new $
M.insert firstid changed list
where (firstid, Node firstval _ secondid) = M.findMin list
newid = firstid - 1
new = Node a Nothing (Just firstid)
changed = Node firstval (Just newid) secondid
rcons :: a -> DLList a -> DLList a
rcons a list | M.null list = singleton a
| otherwise = M.insert lastid changed $
M.insert newid new list
where (lastid, Node lastval penultimateid _) = M.findMax list
newid = lastid + 1
changed = Node lastval penultimateid (Just newid)
new = Node a (Just lastid) Nothing
mcons :: a -> Node a -> Node a -> DLList a -> DLList a
mcons a n1 n2 = M.insert n1id left .
M.insert midid mid . M.insert n2id right
where Node n1val farleftid (Just n2id) = n1
Node n2val (Just n1id) farrightid = n2
midid = (n1id + n2id) / 2
mid = Node a (Just n1id) (Just n2id)
left = Node n1val farleftid (Just midid)
right = Node n2val (Just midid) farrightid
firstNode :: DLList a -> Node a
firstNode = snd . M.findMin
lastNode :: DLList a -> Node a
lastNode = snd . M.findMax
nextNode :: DLList a -> Node a -> Maybe (Node a)
nextNode l n = nNode n >>= flip M.lookup l
prevNode :: DLList a -> Node a -> Maybe (Node a)
prevNode l n = pNode n >>= flip M.lookup l
fromList = foldr fcons empty
toList = map vNode . M.elems | 934Doubly-linked list/Definition
| 8haskell
| iymor |
Point = Struct.new(:x, :y)
Line = Struct.new(:start, :stop)
Shoes.app(:width => 800, :height => 600, :resizable => false) do
def split_segments(n)
dir = 1
@segments = @segments.inject([]) do |new, l|
a, b, c, d = l.start.x, l.start.y, l.stop.x, l.stop.y
mid_x = a + (c-a)/2.0 - (d-b)/2.0*dir
mid_y = b + (d-b)/2.0 + (c-a)/2.0*dir
mid_p = Point.new(mid_x, mid_y)
dir *= -1
new << Line.new(l.start, mid_p)
new << Line.new(mid_p, l.stop)
end
end
@segments = [Line.new(Point.new(200,200), Point.new(600,200))]
15.times do |n|
info
split_segments(n)
end
stack do
@segments.each do |l|
line l.start.x, l.start.y, l.stop.x, l.stop.y
end
end
end | 927Dragon curve
| 14ruby
| d9gns |
use ggez::{
conf::{WindowMode, WindowSetup},
error::GameResult,
event,
graphics::{clear, draw, present, Color, MeshBuilder},
nalgebra::Point2,
Context,
};
use std::time::Duration; | 927Dragon curve
| 15rust
| fcrd6 |
import java.util.LinkedList;
public class DoublyLinkedList {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.addFirst("Add First");
list.addLast("Add Last 1");
list.addLast("Add Last 2");
list.addLast("Add Last 1");
traverseList(list);
list.removeFirstOccurrence("Add Last 1");
traverseList(list);
}
private static void traverseList(LinkedList<String> list) {
System.out.println("Traverse List:");
for ( int i = 0 ; i < list.size() ; i++ ) {
System.out.printf("Element number%d - Element value = '%s'%n", i, list.get(i));
}
System.out.println();
}
} | 934Doubly-linked list/Definition
| 9java
| xdfwy |
import javax.swing.JFrame
import java.awt.Graphics
class DragonCurve(depth: Int) extends JFrame(s"Dragon Curve (depth $depth)") {
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
val len = 400 / Math.pow(2, depth / 2.0);
val startingAngle = -depth * (Math.PI / 4);
val steps = getSteps(depth).filterNot(c => c == 'X' || c == 'Y')
def getSteps(depth: Int): Stream[Char] = {
if (depth == 0) {
"FX".toStream
} else {
getSteps(depth - 1).flatMap{
case 'X' => "XRYFR"
case 'Y' => "LFXLY"
case c => c.toString
}
}
}
override def paint(g: Graphics): Unit = {
var (x, y) = (230, 350)
var (dx, dy) = ((Math.cos(startingAngle) * len).toInt, (Math.sin(startingAngle) * len).toInt)
for (c <- steps) c match {
case 'F' => {
g.drawLine(x, y, x + dx, y + dy)
x = x + dx
y = y + dy
}
case 'L' => {
val temp = dx
dx = dy
dy = -temp
}
case 'R' => {
val temp = dx
dx = -dy
dy = temp
}
}
}
}
object DragonCurve extends App {
new DragonCurve(14).setVisible(true);
} | 927Dragon curve
| 16scala
| 3vhzy |
show(DLNode) | 934Doubly-linked list/Definition
| 10javascript
| o6y86 |
do { *rmp = 0; _mdr(rmdr, rmp, n); } while (0)
void _mdr(int *rmdr, int *rmp, long long n)
{
int r = n ? 1 : 0;
while (n) {
r *= (n % 10);
n /= 10;
}
(*rmp)++;
if (r >= 10)
_mdr(rmdr, rmp, r);
else
*rmdr = r;
}
int main(void)
{
int i, j, vmdr, vmp;
const int values[] = { 123321, 7739, 893, 899998 };
const int vsize = sizeof(values) / sizeof(values[0]);
printf();
for (i = 0; i < vsize; ++i) {
mdr(&vmdr, &vmp, values[i]);
printf(, values[i], vmdr, vmp);
}
int table[10][twidth] = { 0 };
int tfill[10] = { 0 };
int total = 0;
for (i = 0; total < 10 * twidth; ++i) {
mdr(&vmdr, &vmp, i);
if (tfill[vmdr] < twidth) {
table[vmdr][tfill[vmdr]++] = i;
total++;
}
}
printf();
for (i = 0; i < 10; ++i) {
printf(, i);
for (j = 0; j < twidth; ++j)
printf(, table[i][j], j != twidth - 1 ? : );
printf();
}
return 0;
} | 936Digital root/Multiplicative digital root
| 5c
| p0sby |
null | 934Doubly-linked list/Definition
| 11kotlin
| p08b6 |
package main
import (
"fmt"
"strings"
)
func sentenceType(s string) string {
if len(s) == 0 {
return ""
}
var types []string
for _, c := range s {
if c == '?' {
types = append(types, "Q")
} else if c == '!' {
types = append(types, "E")
} else if c == '.' {
types = append(types, "S")
}
}
if strings.IndexByte("?!.", s[len(s)-1]) == -1 {
types = append(types, "N")
}
return strings.Join(types, "|")
}
func main() {
s := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
fmt.Println(sentenceType(s))
} | 937Determine sentence type
| 0go
| cr49g |
null | 934Doubly-linked list/Definition
| 1lua
| 18opo |
text = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"
p2t = { [""]="N", ["."]="S", ["!"]="E", ["?"]="Q" }
for s, p in text:gmatch("%s*([^%!%?%.]+)([%!%?%.]?)") do
print(s..p..": "..p2t[p])
end | 937Determine sentence type
| 1lua
| ukjvl |
use strict;
use warnings;
use feature 'say';
use Lingua::Sentence;
my $para1 = <<'EOP';
hi there, how are you today? I'd like to present to you the washing machine
9001. You have been nominated to win one of these! Just make sure you don't
break it
EOP
my $para2 = <<'EOP';
Just because there are punctuation characters like "?", "!" or especially "."
present, it doesn't necessarily mean you have reached the end of a sentence,
does it Mr. Magoo? The syntax highlighting here for Perl isn't bad at all.
EOP
my $splitter = Lingua::Sentence->new("en");
for my $text ($para1, $para2) {
for my $s (split /\n/, $splitter->split( $text =~ s/\n//gr ) {
print "$s| ";
if ($s =~ /!$/) { say 'E' }
elsif ($s =~ /\?$/) { say 'Q' }
elsif ($s =~ /\.$/) { say 'S' }
else { say 'N' }
}
} | 937Determine sentence type
| 2perl
| 0zfs4 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.