code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
require("LuaXML")
function addNode(parent, nodeName, key, value, content)
local node = xml.new(nodeName)
table.insert(node, content)
parent:append(node)[key] = value
end
root = xml.new("CharacterRemarks")
addNode(root, "Character", "name", "April", "Bubbly: I'm > Tam and <= Emily")
addNode(root, "Character", "name", "Tam O'Shanter", 'Burns: "When chapman billies leave the street ..."')
addNode(root, "Character", "name", "Emily", "Short & shrift")
print(root) | 34XML/Output
| 1lua
| 1kbpo |
null | 35XML/Input
| 11kotlin
| 8qq0q |
isPrime :: Integer -> Bool
isPrime n
|n == 2 = True
|n == 1 = False
|otherwise = null $ filter (\i -> mod n i == 0 ) [2 .. root]
where
root :: Integer
root = toInteger $ floor $ sqrt $ fromIntegral n
isWieferichPrime :: Integer -> Bool
isWieferichPrime n = isPrime n && mod ( 2 ^ ( n - 1 ) - 1 ) ( n ^ 2 ) == 0
solution :: [Integer]
solution = filter isWieferichPrime [2 .. 5000]
main :: IO ( )
main = do
putStrLn "Wieferich primes less than 5000:"
print solution | 45Wieferich primes
| 8haskell
| w15ed |
import java.util.*;
public class WieferichPrimes {
public static void main(String[] args) {
final int limit = 5000;
System.out.printf("Wieferich primes less than%d:\n", limit);
for (Integer p : wieferichPrimes(limit))
System.out.println(p);
}
private static boolean[] primeSieve(int limit) {
boolean[] sieve = new boolean[limit];
Arrays.fill(sieve, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3; ; p += 2) {
int q = p * p;
if (q >= limit)
break;
if (sieve[p]) {
int inc = 2 * p;
for (; q < limit; q += inc)
sieve[q] = false;
}
}
return sieve;
}
private static long modpow(long base, long exp, long mod) {
if (mod == 1)
return 0;
long result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;
base = (base * base) % mod;
}
return result;
}
private static List<Integer> wieferichPrimes(int limit) {
boolean[] sieve = primeSieve(limit);
List<Integer> result = new ArrayList<>();
for (int p = 2; p < limit; ++p) {
if (sieve[p] && modpow(2, p - 1, p * p) == 1)
result.add(p);
}
return result;
}
} | 45Wieferich primes
| 9java
| k79hm |
require
module Modulo
refine Integer do
def factorial_mod(m) = (1..self).inject(1){|prod, n| (prod *= n) % m }
end
end
using Modulo
primes = Prime.each(11000).to_a
(1..11).each do |n|
res = primes.select do |pr|
prpr = pr*pr
((n-1).factorial_mod(prpr) * (pr-n).factorial_mod(prpr) - (-1)**n) % (prpr) == 0
end
puts
end | 43Wilson primes of order n
| 14ruby
| ab51s |
null | 43Wilson primes of order n
| 15rust
| ep4aj |
null | 37Write language name in 3D ASCII
| 11kotlin
| vcm21 |
io.write(" /$$\n")
io.write("| $$\n")
io.write("| $$ /$$ /$$ /$$$$$$\n")
io.write("| $$ | $$ | $$ |____ $$\n")
io.write("| $$ | $$ | $$ /$$$$$$$\n")
io.write("| $$ | $$ | $$ /$$__ $$\n")
io.write("| $$$$$$$$| $$$$$$/| $$$$$$$\n")
io.write("|________/ \______/ \_______/\n") | 37Write language name in 3D ASCII
| 1lua
| ul9vl |
from tkinter import *
import tkinter.messagebox
def maximise():
root.geometry(.format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))
def minimise():
root.iconify()
def delete():
if tkinter.messagebox.askokcancel(,):
root.quit()
root = Tk()
mx=Button(root,text=,command=maximise)
mx.grid()
mx.bind(maximise)
mn=Button(root,text=,command=minimise)
mn.grid()
mn.bind(minimise)
root.protocol(,delete)
mainloop() | 40Window management
| 3python
| 96dmf |
use feature 'say';
use ntheory qw(is_prime powmod);
say 'Wieferich primes less than 5000: ' . join ', ', grep { is_prime($_) and powmod(2, $_-1, $_*$_) == 1 } 1..5000; | 45Wieferich primes
| 2perl
| n8biw |
use strict;
use X11::Protocol;
my $X = X11::Protocol->new;
my $window = $X->new_rsrc;
$X->CreateWindow ($window,
$X->root,
'InputOutput',
0,
0,
0,0,
300,100,
0,
background_pixel => $X->black_pixel,
event_mask => $X->pack_event_mask('Exposure',
'ButtonPress'),
);
my $gc = $X->new_rsrc;
$X->CreateGC ($gc, $window,
foreground => $X->white_pixel);
$X->{'event_handler'} = sub {
my %event = @_;
my $event_name = $event{'name'};
if ($event_name eq 'Expose') {
$X->PolyRectangle ($window, $gc, [ 10,10,
30,20 ]);
$X->PolyText8 ($window, $gc,
10, 55,
[ 0,
'Hello ... click mouse button to exit.' ]);
} elsif ($event_name eq 'ButtonPress') {
exit 0;
}
};
$X->MapWindow ($window);
for (;;) {
$X->handle_input;
} | 42Window creation/X11
| 2perl
| 523u2 |
wheel =
middle, wheel_size = wheel[4], wheel.size
res = File.open().each_line.select do |word|
w = word.chomp
next unless w.size.between?(3, wheel_size)
next unless w.match?(middle)
wheel.each_char{|c| w.sub!(c, ) }
w.empty?
end
puts res | 38Word wheel
| 14ruby
| gul4q |
require 'lxp'
data = [[<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>]]
p = lxp.new({StartElement = function (parser, name, attr)
if name == 'Student' and attr.Name then
print(attr.Name)
end
end})
p:parse(data)
p:close() | 35XML/Input
| 1lua
| oss8h |
size_t lr = 0;
size_t filterit(void *ptr, size_t size, size_t nmemb, void *stream)
{
if ( (lr + size*nmemb) > BUFSIZE ) return BUFSIZE;
memcpy(stream+lr, ptr, size*nmemb);
lr += size*nmemb;
return size*nmemb;
}
int main()
{
CURL *curlHandle;
char buffer[BUFSIZE];
regmatch_t amatch;
regex_t cregex;
curlHandle = curl_easy_init();
curl_easy_setopt(curlHandle, CURLOPT_URL, );
curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, filterit);
curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, buffer);
int success = curl_easy_perform(curlHandle);
curl_easy_cleanup(curlHandle);
buffer[lr] = 0;
regcomp(&cregex, , REG_NEWLINE);
regexec(&cregex, buffer, 1, &amatch, 0);
int bi = amatch.rm_so;
while ( bi-- > 0 )
if ( memcmp(&buffer[bi], , 4) == 0 ) break;
buffer[amatch.rm_eo] = 0;
printf(, &buffer[bi+4]);
regfree(&cregex);
return 0;
} | 49Web scraping
| 5c
| yza6f |
def isPrime(n):
for i in range(2, int(n**0.5) + 1):
if n% i == 0:
return False
return True
def isWeiferich(p):
if not isPrime(p):
return False
q = 1
p2 = p ** 2
while p > 1:
q = (2 * q)% p2
p -= 1
if q == 1:
return True
else:
return False
if __name__ == '__main__':
print()
for i in range(2, 5001):
if isWeiferich(i):
print(i) | 45Wieferich primes
| 3python
| dopn1 |
from Xlib import X, display
class Window:
def __init__(self, display, msg):
self.display = display
self.msg = msg
self.screen = self.display.screen()
self.window = self.screen.root.create_window(
10, 10, 100, 100, 1,
self.screen.root_depth,
background_pixel=self.screen.white_pixel,
event_mask=X.ExposureMask | X.KeyPressMask,
)
self.gc = self.window.create_gc(
foreground = self.screen.black_pixel,
background = self.screen.white_pixel,
)
self.window.map()
def loop(self):
while True:
e = self.display.next_event()
if e.type == X.Expose:
self.window.fill_rectangle(self.gc, 20, 20, 10, 10)
self.window.draw_text(self.gc, 10, 50, self.msg)
elif e.type == X.KeyPress:
raise SystemExit
if __name__ == :
Window(display.Display(), ).loop() | 42Window creation/X11
| 3python
| 4v65k |
package main
import "fmt"
func divisors(n int) []int {
divs := []int{1}
divs2 := []int{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs = append(divs, i)
if i != j {
divs2 = append(divs2, j)
}
}
}
for i := len(divs) - 1; i >= 0; i-- {
divs2 = append(divs2, divs[i])
}
return divs2
}
func abundant(n int, divs []int) bool {
sum := 0
for _, div := range divs {
sum += div
}
return sum > n
}
func semiperfect(n int, divs []int) bool {
le := len(divs)
if le > 0 {
h := divs[0]
t := divs[1:]
if n < h {
return semiperfect(n, t)
} else {
return n == h || semiperfect(n-h, t) || semiperfect(n, t)
}
} else {
return false
}
}
func sieve(limit int) []bool { | 47Weird numbers
| 0go
| 96qmt |
typedef struct word_count_tag {
const char* word;
size_t count;
} word_count;
int compare_word_count(const void* p1, const void* p2) {
const word_count* w1 = p1;
const word_count* w2 = p2;
if (w1->count > w2->count)
return -1;
if (w1->count < w2->count)
return 1;
return 0;
}
bool get_top_words(const char* filename, size_t count) {
GError* error = NULL;
GMappedFile* mapped_file = g_mapped_file_new(filename, FALSE, &error);
if (mapped_file == NULL) {
fprintf(stderr, , error->message);
g_error_free(error);
return false;
}
const char* text = g_mapped_file_get_contents(mapped_file);
if (text == NULL) {
fprintf(stderr, , filename);
g_mapped_file_unref(mapped_file);
return false;
}
gsize file_size = g_mapped_file_get_length(mapped_file);
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, g_free);
GRegex* regex = g_regex_new(, 0, 0, NULL);
GMatchInfo* match_info;
g_regex_match_full(regex, text, file_size, 0, 0, &match_info, NULL);
while (g_match_info_matches(match_info)) {
char* word = g_match_info_fetch(match_info, 0);
char* lower = g_utf8_strdown(word, -1);
g_free(word);
size_t* count = g_hash_table_lookup(ht, lower);
if (count != NULL) {
++*count;
g_free(lower);
} else {
count = g_new(size_t, 1);
*count = 1;
g_hash_table_insert(ht, lower, count);
}
g_match_info_next(match_info, NULL);
}
g_match_info_free(match_info);
g_regex_unref(regex);
g_mapped_file_unref(mapped_file);
size_t size = g_hash_table_size(ht);
word_count* words = g_new(word_count, size);
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
for (size_t i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {
words[i].word = key;
words[i].count = *(size_t*)value;
}
qsort(words, size, sizeof(word_count), compare_word_count);
if (count > size)
count = size;
printf(, count);
printf();
for (size_t i = 0; i < count; ++i)
printf(, i + 1, words[i].count, words[i].word);
g_free(words);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, , argv[0]);
return EXIT_FAILURE;
}
if (!get_top_words(argv[1], 10))
return EXIT_FAILURE;
return EXIT_SUCCESS;
} | 50Word frequency
| 5c
| vcs2o |
weirds :: [Int]
weirds = filter abundantNotSemiperfect [1 ..]
abundantNotSemiperfect :: Int -> Bool
abundantNotSemiperfect n =
let ds = descProperDivisors n
d = sum ds - n
in 0 < d && not (hasSum d ds)
hasSum :: Int -> [Int] -> Bool
hasSum _ [] = False
hasSum n (x:xs)
| n < x = hasSum n xs
| otherwise = (n == x) || hasSum (n - x) xs || hasSum n xs
descProperDivisors
:: Integral a
=> a -> [a]
descProperDivisors n =
let root = (floor . sqrt) (fromIntegral n :: Double)
lows = filter ((0 ==) . rem n) [root,root - 1 .. 1]
factors
| n == root ^ 2 = tail lows
| otherwise = lows
in tail $ reverse (quot n <$> lows) ++ factors
main :: IO ()
main =
(putStrLn . unlines) $
zipWith (\i x -> show i ++ (" -> " ++ show x)) [1 ..] (take 25 weirds) | 47Weird numbers
| 8haskell
| bjmk2 |
require
puts Prime.each(5000).select{|p| 2.pow(p-1 ,p*p) == 1 } | 45Wieferich primes
| 14ruby
| tnaf2 |
null | 45Wieferich primes
| 15rust
| zdeto |
func primeSieve(limit: Int) -> [Bool] {
guard limit > 0 else {
return []
}
var sieve = Array(repeating: true, count: limit)
sieve[0] = false
if limit > 1 {
sieve[1] = false
}
if limit > 4 {
for i in stride(from: 4, to: limit, by: 2) {
sieve[i] = false
}
}
var p = 3
while true {
var q = p * p
if q >= limit {
break
}
if sieve[p] {
let inc = 2 * p
while q < limit {
sieve[q] = false
q += inc
}
}
p += 2
}
return sieve
}
func modpow(base: Int, exponent: Int, mod: Int) -> Int {
if mod == 1 {
return 0
}
var result = 1
var exp = exponent
var b = base
b%= mod
while exp > 0 {
if (exp & 1) == 1 {
result = (result * b)% mod
}
b = (b * b)% mod
exp >>= 1
}
return result
}
func wieferichPrimes(limit: Int) -> [Int] {
let sieve = primeSieve(limit: limit)
var result: [Int] = []
for p in 2..<limit {
if sieve[p] && modpow(base: 2, exponent: p - 1, mod: p * p) == 1 {
result.append(p)
}
}
return result
}
let limit = 5000
print("Wieferich primes less than \(limit):")
for p in wieferichPrimes(limit: limit) {
print(p)
} | 45Wieferich primes
| 17swift
| fi1dk |
import scala.swing.{ MainFrame, SimpleSwingApplication }
import scala.swing.Swing.pair2Dimension
object WindowExample extends SimpleSwingApplication {
def top = new MainFrame {
title = "Hello!"
centerOnScreen
preferredSize = ((200, 150))
}
} | 42Window creation/X11
| 16scala
| k72hk |
use strict;
use XML::Mini::Document;
my @students = ( [ "April", "Bubbly: I'm > Tam and <= Emily" ],
[ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" ],
[ "Emily", "Short & shrift" ]
);
my $doc = XML::Mini::Document->new();
my $root = $doc->getRoot();
my $studs = $root->createChild("CharacterRemarks");
foreach my $s (@students)
{
my $stud = $studs->createChild("Character");
$stud->attribute("name", $s->[0]);
$stud->text($s->[1]);
}
print $doc->toString(); | 34XML/Output
| 2perl
| yz36u |
import java.util.ArrayList;
import java.util.List;
public class WeirdNumbers {
public static void main(String[] args) {
int n = 2; | 47Weird numbers
| 9java
| guf4m |
package main
import (
"github.com/mattn/go-gtk/glib"
"github.com/mattn/go-gtk/gtk"
)
func main() {
gtk.Init(nil)
window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
window.Connect("destroy",
func(*glib.CallbackContext) { gtk.MainQuit() }, "")
window.Show()
gtk.Main()
} | 46Window creation
| 0go
| 743r2 |
import groovy.swing.SwingBuilder
new SwingBuilder().frame(title:'My Window', size:[200,100]).show() | 46Window creation
| 7groovy
| ulnv9 |
package main
import (
"fmt"
"strings"
)
func wrap(text string, lineWidth int) (wrapped string) {
words := strings.Fields(text)
if len(words) == 0 {
return
}
wrapped = words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return
}
var frog = `
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.`
func main() {
fmt.Println("wrapped at 80:")
fmt.Println(wrap(frog, 80))
fmt.Println("wrapped at 72:")
fmt.Println(wrap(frog, 72))
} | 44Word wrap
| 0go
| jgm7d |
(() => {
'use strict'; | 47Weird numbers
| 10javascript
| k7yhq |
(second (re-find #" (\d{1,2}:\d{1,2}:\d{1,2}) UTC" (slurp "http://tycho.usno.navy.mil/cgi-bin/timer.pl"))) | 49Web scraping
| 6clojure
| 29sl1 |
(defn count-words [file n]
(->> file
slurp
clojure.string/lower-case
(re-seq #"\w+")
frequencies
(sort-by val >)
(take n))) | 50Word frequency
| 6clojure
| r5ng2 |
import Graphics.HGL
aWindow = runGraphics $
withWindow_ "Rosetta Code task: Creating a window" (300, 200) $ \ w -> do
drawInWindow w $ text (100, 100) "Hello World"
getKey w | 46Window creation
| 8haskell
| 8q70z |
def wordWrap(text, length = 80) {
def sb = new StringBuilder()
def line = ''
text.split(/\s/).each { word ->
if (line.size() + word.size() > length) {
sb.append(line.trim()).append('\n')
line = ''
}
line += " $word"
}
sb.append(line.trim()).toString()
} | 44Word wrap
| 7groovy
| 52tuv |
null | 47Weird numbers
| 11kotlin
| 298li |
use strict;
use warnings;
for my $tuple ([" ", 2], ["_", 1], [" ", 1], ["\\", 1], [" ", 11], ["|", 1], ["\n", 1],
[" ", 1], ["|", 1], [" ", 3], ["|", 1], [" ", 1], ["_", 1], [" ", 1], ["\\", 1], [" ", 2], ["_", 2], ["|", 1], [" ", 1], ["|", 1], ["\n", 1],
[" ", 1], ["_", 3], ["/", 1], [" ", 2], ["_", 2], ["/", 1], [" ", 1], ["|", 1], [" ", 4], ["|", 1], ["\n", 1],
["_", 1], ["|", 1], [" ", 3], ["\\", 1], ["_", 3], ["|", 1], ["_", 1], ["|", 1], [" ", 3], ["_", 1], ["|", 1], ["\n", 1]
) {
print $tuple->[0] x $tuple->[1];
} | 37Write language name in 3D ASCII
| 2perl
| 0xes4 |
ss =
concat
[ "In olden times when wishing still helped one, there lived a king"
, "whose daughters were all beautiful, but the youngest was so beautiful"
, "that the sun itself, which has seen so much, was astonished whenever"
, "it shone in her face. Close by the king's castle lay a great dark"
, "forest, and under an old lime-tree in the forest was a well, and when"
, "the day was very warm, the king's child went out into the forest and"
, "sat down by the side of the cool fountain, and when she was bored she"
, "took a golden ball, and threw it up on high and caught it, and this"
, "ball was her favorite plaything."
]
wordwrap maxlen = wrap_ 0 . words
where
wrap_ _ [] = "\n"
wrap_ pos (w:ws)
| pos == 0 = w ++ wrap_ (pos + lw) ws
| pos + lw + 1 > maxlen = '\n': wrap_ 0 (w: ws)
| otherwise = ' ': w ++ wrap_ (pos + lw + 1) ws
where
lw = length w
main = mapM_ putStr [wordwrap 72 ss, "\n", wordwrap 32 ss] | 44Word wrap
| 8haskell
| osk8p |
>>> from xml.etree import ElementTree as ET
>>> from itertools import izip
>>> def characterstoxml(names, remarks):
root = ET.Element()
for name, remark in izip(names, remarks):
c = ET.SubElement(root, , {'name': name})
c.text = remark
return ET.tostring(root)
>>> print characterstoxml(
names = [, , ],
remarks = [ ,
'Burns: ',
'Short & shrift' ] ).replace('><','>\n<') | 34XML/Output
| 3python
| m36yh |
function make(n, d)
local a = {}
for i=1,n do
table.insert(a, d)
end
return a
end
function reverse(t)
local n = #t
local i = 1
while i < n do
t[i],t[n] = t[n],t[i]
i = i + 1
n = n - 1
end
end
function tail(list)
return { select(2, unpack(list)) }
end
function divisors(n)
local divs = {}
table.insert(divs, 1)
local divs2 = {}
local i = 2
while i * i <= n do
if n % i == 0 then
local j = n / i
table.insert(divs, i)
if i ~= j then
table.insert(divs2, j)
end
end
i = i + 1
end
reverse(divs)
for i,v in pairs(divs) do
table.insert(divs2, v)
end
return divs2
end
function abundant(n, divs)
local sum = 0
for i,v in pairs(divs) do
sum = sum + v
end
return sum > n
end
function semiPerfect(n, divs)
if #divs > 0 then
local h = divs[1]
local t = tail(divs)
if n < h then
return semiPerfect(n, t)
else
return n == h
or semiPerfect(n - h, t)
or semiPerfect(n, t)
end
else
return false
end
end
function sieve(limit) | 47Weird numbers
| 1lua
| vco2x |
package main
import (
"bytes"
"fmt"
"io/ioutil"
"strings"
)
var rows, cols int | 48Wireworld
| 0go
| lmscw |
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) throws Exception {
JFrame w = new JFrame("Title");
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(800,600);
w.setVisible(true);
}
} | 46Window creation
| 9java
| epva5 |
window.open("webpage.html", "windowname", "width=800,height=600"); | 46Window creation
| 10javascript
| 0xrsz |
library(XML)
char2xml <- function(names, remarks){
tt <- xmlHashTree()
head <- addNode(xmlNode("CharacterRemarks"), character(), tt)
node <- list()
for (i in 1:length(names)){
node[[i]] <- addNode(xmlNode("Character", attrs=c(name=names[i])), head, tt)
addNode(xmlTextNode(remarks[i]), node[[i]], tt)
}
return(tt)
}
output <- char2xml( names=c("April","Tam O'Shanter","Emily"),
remarks=c("Bubbly: I'm > Tam and <= Emily", 'Burns: "When chapman billies leave the street ..."', "Short & shrift") ) | 34XML/Output
| 13r
| zdfth |
import Data.List
import Control.Monad
import Control.Arrow
import Data.Maybe
states=" Ht."
shiftS=" t.."
borden bc xs = bs: (map (\x -> bc:(x++[bc])) xs) ++ [bs]
where r = length $ head xs
bs = replicate (r+2) bc
take3x3 = ap ((.). taken. length) (taken. length. head) `ap` borden '*'
where taken n = transpose. map (take n.map (take 3)).map tails
nwState xs | e =='.' && noH>0 && noH<3 = 'H'
| otherwise = shiftS !! (fromJust $ elemIndex e states)
where e = xs!!1!!1
noH = length $ filter (=='H') $ concat xs
runCircuit = iterate (map(map nwState).take3x3) | 48Wireworld
| 8haskell
| 1k9ps |
import javax.swing.JFrame
fun main(args: Array<String>) {
JFrame("Title").apply {
setSize(800, 600)
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
isVisible = true
}
} | 46Window creation
| 11kotlin
| k7mh3 |
use strict;
use feature 'say';
use List::Util 'sum';
use POSIX 'floor';
use Algorithm::Combinatorics 'subsets';
use ntheory <is_prime divisors>;
sub abundant {
my($x) = @_;
my $s = sum( my @l = is_prime($x) ? 1 : grep { $x != $_ } divisors($x) );
$s > $x ? ($s, sort { $b <=> $a } @l) : ();
}
my(@weird,$n);
while () {
$n++;
my ($sum, @div) = abundant($n);
next unless $sum;
next if $sum / $n > 1.1;
if ($n >= 10430 and (! int $n%70) and is_prime(int $n/70)) {
} else {
my $next;
my $l = shift @div;
my $iter = subsets(\@div);
while (my $s = $iter->next) {
++$next and last if sum(@$s) == $n - $l;
}
next if $next;
}
push @weird, $n;
last if @weird == 25;
}
say "The first 25 weird numbers:\n" . join ' ', @weird; | 47Weird numbers
| 2perl
| sw4q3 |
py = '''\
'''
lines = py.replace('
for i, l in enumerate(lines):
print( ' ' * (len(lines) - i) + l) | 37Write language name in 3D ASCII
| 3python
| 8qw0o |
package rosettacode;
import java.util.StringTokenizer;
public class WordWrap
{
int defaultLineWidth=80;
int defaultSpaceWidth=1;
void minNumLinesWrap(String text)
{
minNumLinesWrap(text,defaultLineWidth);
}
void minNumLinesWrap(String text,int LineWidth)
{
StringTokenizer st=new StringTokenizer(text);
int SpaceLeft=LineWidth;
int SpaceWidth=defaultSpaceWidth;
while(st.hasMoreTokens())
{
String word=st.nextToken();
if((word.length()+SpaceWidth)>SpaceLeft)
{
System.out.print("\n"+word+" ");
SpaceLeft=LineWidth-word.length();
}
else
{
System.out.print(word+" ");
SpaceLeft-=(word.length()+SpaceWidth);
}
}
}
public static void main(String[] args)
{
WordWrap now=new WordWrap();
String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie.";
System.out.println("DEFAULT:");
now.minNumLinesWrap(wodehouse);
System.out.println("\n\nLINEWIDTH=120");
now.minNumLinesWrap(wodehouse,120);
}
} | 44Word wrap
| 9java
| w14ej |
use utf8;
use XML::Simple;
my $ref = XMLin('<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&
</Students>');
print join( "\n", map { $_->{'Name'} } @{$ref->{'Student'}}); | 35XML/Input
| 2perl
| 4vv5d |
local iup = require "iuplua"
iup.dialog{
title = "Window";
iup.vbox{
margin = "10x10";
iup.label{title = "A window"}
}
}:show()
iup.MainLoop() | 46Window creation
| 1lua
| bj9ka |
function wrap (text, limit) {
if (text.length > limit) { | 44Word wrap
| 10javascript
| 8qh0l |
require 'rexml/document'
include REXML
remarks = {
%q(April) => %q(Bubbly: I'm > Tam and <= Emily),
%q(Tam O'Shanter) => %q(Burns: ),
%q(Emily) => %q(Short & shrift),
}
doc = Document.new
root = doc.add_element()
remarks.each do |name, remark|
root.add_element(, {'Name' => name}).add_text(remark)
end
doc.write($stdout, 2) | 34XML/Output
| 14ruby
| cym9k |
'''Weird numbers'''
from itertools import chain, count, islice, repeat
from functools import reduce
from math import sqrt
from time import time
def weirds():
'''Non-finite stream of weird numbers.
(Abundant, but not semi-perfect)
OEIS: A006037
'''
def go(n):
ds = descPropDivs(n)
d = sum(ds) - n
return [n] if 0 < d and not hasSum(d, ds) else []
return concatMap(go)(count(1))
def hasSum(n, xs):
'''Does any subset of xs sum to n?
(Assuming xs to be sorted in descending
order of magnitude)'''
def go(n, xs):
if xs:
h, t = xs[0], xs[1:]
if n < h:
return go(n, t)
else:
return n == h or go(n - h, t) or go(n, t)
else:
return False
return go(n, xs)
def descPropDivs(n):
'''Descending positive divisors of n,
excluding n itself.'''
root = sqrt(n)
intRoot = int(root)
blnSqr = root == intRoot
lows = [x for x in range(1, 1 + intRoot) if 0 == n% x]
return [
n
lows[1:-1] if blnSqr else lows[1:]
)
] + list(reversed(lows))
def main():
'''Test'''
start = time()
n = 50
xs = take(n)(weirds())
print(
(tabulated('First ' + str(n) + ' weird numbers:\n')(
lambda i: str(1 + i)
)(str)(5)(
index(xs)
)(range(0, n)))
)
print(
'\nApprox computation time: ' +
str(int(1000 * (time() - start))) + ' ms'
)
def chunksOf(n):
'''A series of lists of length n,
subdividing the contents of xs.
Where the length of xs is not evenly divible,
the final list will be shorter than n.'''
return lambda xs: reduce(
lambda a, i: a + [xs[i:n + i]],
range(0, len(xs), n), []
) if 0 < n else []
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
def concatMap(f):
'''A concatenated list or string over which a function f
has been mapped.
The list monad can be derived by using an (a -> [b])
function which wraps its output in a list (using an
empty list to represent computational failure).
'''
return lambda xs: chain.from_iterable(map(f, xs))
def index(xs):
'''Item at given (zero-based) index.'''
return lambda n: None if 0 > n else (
xs[n] if (
hasattr(xs, )
) else next(islice(xs, n, None))
)
def paddedMatrix(v):
''''A list of rows padded to equal length
(where needed) with instances of the value v.'''
def go(rows):
return paddedRows(
len(max(rows, key=len))
)(v)(rows)
return lambda rows: go(rows) if rows else []
def paddedRows(n):
'''A list of rows padded (but never truncated)
to length n with copies of value v.'''
def go(v, xs):
def pad(x):
d = n - len(x)
return (x + list(repeat(v, d))) if 0 < d else x
return list(map(pad, xs))
return lambda v: lambda xs: go(v, xs) if xs else []
def showColumns(n):
'''A column-wrapped string
derived from a list of rows.'''
def go(xs):
def fit(col):
w = len(max(col, key=len))
def pad(x):
return x.ljust(4 + w, ' ')
return ''.join(map(pad, col))
q, r = divmod(len(xs), n)
return unlines(map(
fit,
transpose(paddedMatrix('')(
chunksOf(q + int(bool(r)))(
xs
)
))
))
return lambda xs: go(xs)
def succ(x):
'''The successor of a value. For numeric types, (1 +).'''
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
def tabulated(s):
'''Heading -> x display function -> fx display function ->
number of columns -> f -> value list -> tabular string.'''
def go(xShow, fxShow, intCols, f, xs):
w = max(map(compose(len)(xShow), xs))
return s + '\n' + showColumns(intCols)([
xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
])
return lambda xShow: lambda fxShow: lambda nCols: (
lambda f: lambda xs: go(
xShow, fxShow, nCols, f, xs
)
)
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.'''
return lambda xs: (
xs[0:n]
if isinstance(xs, list)
else list(islice(xs, n))
)
def transpose(m):
'''The rows and columns of the argument transposed.
(The matrix containers and rows can be lists or tuples).'''
if m:
inner = type(m[0])
z = zip(*m)
return (type(m))(
map(inner, z) if tuple != inner else z
)
else:
return m
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.'''
def go(f, x):
v = x
while not p(v):
v = f(v)
return v
return lambda f: lambda x: go(f, x)
if __name__ == '__main__':
main() | 47Weird numbers
| 3python
| 0xgsq |
<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>Wireworld</title>
<script src="wireworld.js"></script></head><body>
<input type='file' accept='text/plain' onchange='openFile( event )' />
<br /></body></html> | 48Wireworld
| 9java
| 74trj |
extern crate xml;
use std::collections::HashMap;
use std::str;
use xml::writer::{EmitterConfig, XmlEvent};
fn characters_to_xml(characters: HashMap<String, String>) -> String {
let mut output: Vec<u8> = Vec::new();
let mut writer = EmitterConfig::new()
.perform_indent(true)
.create_writer(&mut output);
writer
.write(XmlEvent::start_element("CharacterRemarks"))
.unwrap();
for (character, line) in &characters {
let element = XmlEvent::start_element("Character").attr("name", character);
writer.write(element).unwrap();
writer.write(XmlEvent::characters(line)).unwrap();
writer.write(XmlEvent::end_element()).unwrap();
}
writer.write(XmlEvent::end_element()).unwrap();
str::from_utf8(&output).unwrap().to_string()
}
#[cfg(test)]
mod tests {
use super::characters_to_xml;
use std::collections::HashMap;
#[test]
fn test_xml_output() {
let mut input = HashMap::new();
input.insert(
"April".to_string(),
"Bubbly: I'm > Tam and <= Emily".to_string(),
);
input.insert(
"Tam O'Shanter".to_string(),
"Burns: \"When chapman billies leave the street ...\"".to_string(),
);
input.insert("Emily".to_string(), "Short & shrift".to_string());
let output = characters_to_xml(input);
println!("{}", output);
assert!(output.contains(
"<Character name=\"Tam O'Shanter\">Burns: \"When chapman \
billies leave the street ...\"</Character>"
));
assert!(output
.contains("<Character name=\"April\">Bubbly: I'm > Tam and <= Emily</Character>"));
assert!(output.contains("<Character name=\"Emily\">Short & shrift</Character>"));
}
} | 34XML/Output
| 15rust
| lm9cc |
val names = List("April", "Tam O'Shanter", "Emily")
val remarks = List("Bubbly: I'm > Tam and <= Emily", """Burns: "When chapman billies leave the street ..."""", "Short & shrift")
def characterRemarks(names: List[String], remarks: List[String]) = <CharacterRemarks>
{ names zip remarks map { case (name, remark) => <Character name={name}>{remark}</Character> } }
</CharacterRemarks>
characterRemarks(names, remarks) | 34XML/Output
| 16scala
| ul2v8 |
<?php
$data = '<Students>
<Student Name= Gender= DateOfBirth= />
<Student Name= Gender= DateOfBirth= />
<Student Name= Gender= DateOfBirth= />
<Student Name= Gender= DateOfBirth=>
<Pet Type= Name= />
</Student>
<Student DateOfBirth= Gender= Name= />
</Students>';
$xml = new XMLReader();
$xml->xml( $data );
while ( $xml->read() )
if ( XMLREADER::ELEMENT == $xml->nodeType && $xml->localName == 'Student' )
echo $xml->getAttribute('Name') . ;
?> | 35XML/Input
| 12php
| i00ov |
<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>Wireworld</title>
<script src="wireworld.js"></script></head><body>
<input type='file' accept='text/plain' onchange='openFile( event )' />
<br /></body></html> | 48Wireworld
| 10javascript
| phmb7 |
text = <<EOS
EOS
def banner3D_1(text, shift=-1)
txt = text.each_line.map{|line| line.gsub('
offset = Array.new(txt.size){|i| * shift.abs * i}
offset.reverse! if shift < 0
puts offset.zip(txt).map(&:join)
end
banner3D_1(text)
puts
def banner3D_2(text, shift=-2)
txt = text.each_line.map{|line| line.chomp + ' '}
offset = txt.each_index.map{|i| * shift.abs * i}
offset.reverse! if shift < 0
txt.each_with_index do |line,i|
line2 = offset[i] + line.gsub(' ',' ').gsub('
puts line2, line2.tr('/\\\\','\\\\/')
end
end
banner3D_2(text)
puts
def banner3D_3(text)
txt = text.each_line.map(&:rstrip)
offset = [*0...txt.size].reverse
area = Hash.new(' ')
box = [%w(/ / / \\), %w(\\ \\ \\ /)]
txt.each_with_index do |line,i|
line.each_char.with_index do |c,j|
next if c==' '
x = offset[i] + 2*j
box[0].each_with_index{|c,k| area[[x+k,i ]] = c}
box[1].each_with_index{|c,k| area[[x+k,i+1]] = c}
end
end
(xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax)
puts (ymin..ymax).map{|y| (xmin..xmax).map{|x| area[[x,y]]}.join}
end
banner3D_3 <<EOS
EOS | 37Write language name in 3D ASCII
| 14ruby
| i0qoh |
package main
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"net/http"
"regexp"
"time"
)
func main() {
resp, err := http.Get("http: | 49Web scraping
| 0go
| 1kmp5 |
package main
import (
"fmt"
"io/ioutil"
"log"
"regexp"
"sort"
"strings"
)
type keyval struct {
key string
val int
}
func main() {
reg := regexp.MustCompile(`\p{Ll}+`)
bs, err := ioutil.ReadFile("135-0.txt")
if err != nil {
log.Fatal(err)
}
text := strings.ToLower(string(bs))
matches := reg.FindAllString(text, -1)
groups := make(map[string]int)
for _, match := range matches {
groups[match]++
}
var keyvals []keyval
for k, v := range groups {
keyvals = append(keyvals, keyval{k, v})
}
sort.Slice(keyvals, func(i, j int) bool {
return keyvals[i].val > keyvals[j].val
})
fmt.Println("Rank Word Frequency")
fmt.Println("==== ==== =========")
for rank := 1; rank <= 10; rank++ {
word := keyvals[rank-1].key
freq := keyvals[rank-1].val
fmt.Printf("%2d %-4s %5d\n", rank, word, freq)
}
} | 50Word frequency
| 0go
| swvqa |
null | 44Word wrap
| 11kotlin
| bjlkb |
pub fn char_from_id(id: u8) -> char {
[' ', '#', '/', '_', 'L', '|', '\n'][id as usize]
}
const ID_BITS: u8 = 3;
pub fn decode(code: &[u8]) -> String {
let mut ret = String::new();
let mut carry = 0;
let mut carry_bits = 0;
for &b in code {
let mut bit_pos = ID_BITS - carry_bits;
let mut cur = b >> bit_pos;
let mask = (1 << bit_pos) - 1;
let id = carry | (b & mask) << carry_bits;
ret.push(char_from_id(id));
while bit_pos + ID_BITS < 8 {
ret.push(char_from_id(cur & ((1 << ID_BITS) - 1)));
cur >>= ID_BITS;
bit_pos += ID_BITS;
}
carry = cur;
carry_bits = 8 - bit_pos;
}
ret
}
fn main() {
let code = [
72, 146, 36, 0, 0, 0, 0, 0, 0, 0, 128, 196, 74, 182, 41, 1, 0, 0, 0, 0, 0, 0, 160, 196, 77, 0,
52, 1, 18, 0, 9, 144, 36, 9, 146, 36, 113, 147, 36, 9, 160, 4, 80, 130, 100, 155, 160, 41, 145,
155, 108, 74, 128, 38, 64, 19, 41, 73, 2, 160, 137, 155, 0, 84, 130, 38, 64, 19, 112, 155, 18,
160, 137, 155, 0, 160, 18, 42, 73, 18, 36, 73, 2, 128, 74, 76, 1, 0, 40, 128, 219, 38, 104, 219,
4, 0, 160, 0
];
println!("{}", decode(&code));
} | 37Write language name in 3D ASCII
| 15rust
| n8si4 |
def ASCII3D = {
val name = """
*
** ** * * *
* * * * * * *
* * * * * * *
* * *** * ***
* * * * * * *
* * * * * * *
** ** * * *** * *
*
*
""" | 37Write language name in 3D ASCII
| 16scala
| tnofb |
def time = "unknown"
def text = new URL('http: | 49Web scraping
| 7groovy
| jgt7o |
import Data.List
import Network.HTTP (simpleHTTP, getResponseBody, getRequest)
tyd = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
readUTC = simpleHTTP (getRequest tyd)>>=
fmap ((!!2).head.dropWhile ("UTC"`notElem`).map words.lines). getResponseBody>>=putStrLn | 49Web scraping
| 8haskell
| tnkf7 |
def topWordCounts = { String content, int n ->
def mapCounts = [:]
content.toLowerCase().split(/\W+/).each {
mapCounts[it] = (mapCounts[it] ?: 0) + 1
}
def top = (mapCounts.sort { a, b -> b.value <=> a.value }.collect{ it })[0..<n]
println "Rank Word Frequency\n==== ==== ========="
(0..<n).each { printf ("%4d%-4s%9d\n", it+1, top[it].key, top[it].value) }
} | 50Word frequency
| 7groovy
| abm1p |
def divisors(n)
divs = [1]
divs2 = []
i = 2
while i * i <= n
if n % i == 0 then
j = (n / i).to_i
divs.append(i)
if i!= j then
divs2.append(j)
end
end
i = i + 1
end
divs2 += divs.reverse
return divs2
end
def abundant(n, divs)
return divs.sum > n
end
def semiperfect(n, divs)
if divs.length > 0 then
h = divs[0]
t = divs[1..-1]
if n < h then
return semiperfect(n, t)
else
return n == h || semiperfect(n - h, t) || semiperfect(n, t)
end
else
return false
end
end
def sieve(limit)
w = Array.new(limit, false)
i = 2
while i < limit
if not w[i] then
divs = divisors(i)
if not abundant(i, divs) then
w[i] = true
elsif semiperfect(i, divs) then
j = i
while j < limit
w[j] = true
j = j + i
end
end
end
i = i + 2
end
return w
end
def main
w = sieve(17000)
count = 0
max = 25
print % [max]
n = 2
while count < max
if not w[n] then
print n,
count = count + 1
end
n = n + 2
end
print
end
main() | 47Weird numbers
| 14ruby
| os78v |
module Main where
import Control.Category
import Data.Char
import Data.List
import Data.Ord
import System.IO
import System.Environment
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.IntMap.Strict as IM
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
frequencies :: Ord a => [a] -> Map a Integer
frequencies = foldl' (\m k -> M.insertWith (+) k 1 m) M.empty
main :: IO ()
main = do
args <- getArgs
(n,hand,filep) <- case length args of
0 -> return (10,stdin,False)
1 -> return (read $ head args,stdin,False)
_ -> let (ns:fp:_) = args
in fmap (\h -> (read ns,h,True)) (openFile fp ReadMode)
T.hGetContents hand >>=
(T.map toLower
>>> T.split isSpace
>>> filter (not <<< T.null)
>>> frequencies
>>> M.toList
>>> sortBy (comparing (Down <<< snd))
>>> take n
>>> print)
when filep (hClose hand) | 50Word frequency
| 8haskell
| 96emo |
local map = {{'t', 'H', '.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', ' ', ' ', ' ', '.'},
{' ', ' ', ' ', '.', '.', '.'},
{'.', ' ', ' ', ' ', '.'},
{'H', 't', '.', '.', ' ', '.', '.', '.', '.', '.', '.'}}
function step(map)
local next = {}
for i = 1, #map do
next[i] = {}
for j = 1, #map[i] do
next[i][j] = map[i][j]
if map[i][j] == "H" then
next[i][j] = "t"
elseif map[i][j] == "t" then
next[i][j] = "."
elseif map[i][j] == "." then
local count = ((map[i-1] or {})[j-1] == "H" and 1 or 0) +
((map[i-1] or {})[j] == "H" and 1 or 0) +
((map[i-1] or {})[j+1] == "H" and 1 or 0) +
((map[i] or {})[j-1] == "H" and 1 or 0) +
((map[i] or {})[j+1] == "H" and 1 or 0) +
((map[i+1] or {})[j-1] == "H" and 1 or 0) +
((map[i+1] or {})[j] == "H" and 1 or 0) +
((map[i+1] or {})[j+1] == "H" and 1 or 0)
if count == 1 or count == 2 then
next[i][j] = "H"
else
next[i][j] = "."
end
end
end
end
return next
end
if not not love then
local time, frameTime, size = 0, 0.25, 20
local colors = {["."] = {255, 200, 0},
["t"] = {255, 0, 0},
["H"] = {0, 0, 255}}
function love.update(dt)
time = time + dt
if time > frameTime then
time = time - frameTime
map = step(map)
end
end
function love.draw()
for i = 1, #map do
for j = 1, #map[i] do
love.graphics.setColor(colors[map[i][j]] or {0, 0, 0})
love.graphics.rectangle("fill", j*size, i*size, size, size)
end
end
end
else
for iter = 1, 10 do
print("\nstep "..iter.."\n")
for i = 1, #map do
for j = 1, #map[i] do
io.write(map[i][j])
end
io.write("\n")
end
map = step(map)
end
end | 48Wireworld
| 1lua
| 52iu6 |
import xml.dom.minidom
doc =
doc = xml.dom.minidom.parseString(doc)
for i in doc.getElementsByTagName():
print i.getAttribute() | 35XML/Input
| 3python
| guu4h |
SELECT ' SSS\ ' AS s, ' QQQ\ ' AS q, 'L\ ' AS l FROM dual
UNION ALL SELECT 'S \|', 'Q Q\ ', 'L | ' FROM dual
UNION ALL SELECT '\SSS ', 'Q Q |', 'L | ' FROM dual
UNION ALL SELECT ' \ S\', 'Q Q Q |', 'L | ' from dual
union all select ' SSS |', '\QQQ\\|', 'LLLL\' from dual
union all select ' \__\/', ' \_Q_/ ', '\___\' from dual
union all select ' ', ' \\ ', ' ' from dual; | 37Write language name in 3D ASCII
| 19sql
| 6td3m |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class WebTime{
public static void main(String[] args){
try{
URL address = new URL(
"http: | 49Web scraping
| 9java
| 8q406 |
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class WordCount {
public static void main(String[] args) throws IOException {
Path path = Paths.get("135-0.txt");
byte[] bytes = Files.readAllBytes(path);
String text = new String(bytes);
text = text.toLowerCase();
Pattern r = Pattern.compile("\\p{javaLowerCase}+");
Matcher matcher = r.matcher(text);
Map<String, Integer> freq = new HashMap<>();
while (matcher.find()) {
String word = matcher.group();
Integer current = freq.getOrDefault(word, 0);
freq.put(word, current + 1);
}
List<Map.Entry<String, Integer>> entries = freq.entrySet()
.stream()
.sorted((i1, i2) -> Integer.compare(i2.getValue(), i1.getValue()))
.limit(10)
.collect(Collectors.toList());
System.out.println("Rank Word Frequency");
System.out.println("==== ==== =========");
int rank = 1;
for (Map.Entry<String, Integer> entry : entries) {
String word = entry.getKey();
Integer count = entry.getValue();
System.out.printf("%2d %-4s %5d\n", rank++, word, count);
}
}
} | 50Word frequency
| 9java
| tnhf9 |
use Tk;
MainWindow->new();
MainLoop; | 46Window creation
| 2perl
| 3fezs |
function splittokens(s)
local res = {}
for w in s:gmatch("%S+") do
res[#res+1] = w
end
return res
end
function textwrap(text, linewidth)
if not linewidth then
linewidth = 75
end
local spaceleft = linewidth
local res = {}
local line = {}
for _, word in ipairs(splittokens(text)) do
if #word + 1 > spaceleft then
table.insert(res, table.concat(line, ' '))
line = {word}
spaceleft = linewidth - #word
else
table.insert(line, word)
spaceleft = spaceleft - (#word + 1)
end
end
table.insert(res, table.concat(line, ' '))
return table.concat(res, '\n')
end
local example1 = [[
Even today, with proportional fonts and complex layouts,
there are still cases where you need to wrap text at a
specified column. The basic task is to wrap a paragraph
of text in a simple way in your language. If there is a
way to do this that is built-in, trivial, or provided in
a standard library, show that. Otherwise implement the
minimum length greedy algorithm from Wikipedia.
]]
print(textwrap(example1))
print()
print(textwrap(example1, 60)) | 44Word wrap
| 1lua
| ph2bw |
library(XML)
str <- readLines(tc <- textConnection('<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="&
</Students>'))
close(tc)
str | 35XML/Input
| 13r
| vcc27 |
var req = new XMLHttpRequest();
req.onload = function () {
var re = /[JFMASOND].+ UTC/; | 49Web scraping
| 10javascript
| fihdg |
my @doors;
for my $pass (1 .. 100) {
for (1 .. 100) {
if (0 == $_ % $pass) {
$doors[$_] = not $doors[$_];
};
};
};
print "Door $_ is ", $doors[$_] ? "open" : "closed", "\n" for 1 .. 100; | 21100 doors
| 2perl
| t5fg |
null | 49Web scraping
| 11kotlin
| w1lek |
null | 50Word frequency
| 11kotlin
| os48z |
import Tkinter
w = Tkinter.Tk()
w.mainloop() | 46Window creation
| 3python
| 6tw3w |
win <- tktoplevel() | 46Window creation
| 13r
| fipdc |
local http = require("socket.http") | 49Web scraping
| 1lua
| xa2wz |
null | 50Word frequency
| 1lua
| i0got |
my @f = ([],(map {chomp;['',( split // ),'']} <>),[]);
for (1 .. 10) {
print join "", map {"@$_\n"} @f;
my @a = ([]);
for my $y (1 .. $
my $r = $f[$y];
my $rr = [''];
for my $x (1 .. $
my $c = $r->[$x];
push @$rr,
$c eq 'H' ? 't' :
$c eq 't' ? '.' :
$c eq '.' ? (join('', map {"@{$f[$_]}[$x-1 .. $x+1]"=~/H/g} ($y-1 .. $y+1)) =~ /^H{1,2}$/ ? 'H' : '.') :
$c;
}
push @$rr, '';
push @a, $rr;
}
@f = (@a,[]);
} | 48Wireworld
| 2perl
| 8qg0w |
require 'rexml/document'
include REXML
doc = Document.new(File.new())
doc.each_recursive do |node|
puts node.attributes[] if node.name ==
end
doc.each_element() {|node| puts node.attributes[]} | 35XML/Input
| 14ruby
| 744ri |
require 'tk'
window = TkRoot::new()
window::mainloop() | 46Window creation
| 14ruby
| m3qyj |
$desc = 'tH.........
. .
........
. .
Ht.. ......
..
tH.... .......
..
..
tH..... ......
..';
$steps = 30;
$world = array(array());
$row = 0;
$col = 0;
foreach(str_split($desc) as $i){
switch($i){
case :
$row++;
$col = 0;
$world[] = array();
break;
case '.':
$world[$row][$col] = 1;
$col++;
break;
case 'H':
$world[$row][$col] = 2;
$col++;
break;
case 't':
$world[$row][$col] = 3;
$col++;
break;
default:
$world[$row][$col] = 0;
$col++;
break;
};
};
function draw_world($world){
foreach($world as $rowc){
foreach($rowc as $cell){
switch($cell){
case 0:
echo ' ';
break;
case 1:
echo '.';
break;
case 2:
echo 'H';
break;
case 3:
echo 't';
};
};
echo ;
};
};
echo ;
draw_world($world);
for($i = 0; $i < $steps; $i++){
$old_world = $world;
foreach($world as $row => &$rowc){
foreach($rowc as $col => &$cell){
switch($cell){
case 2:
$cell = 3;
break;
case 3:
$cell = 1;
break;
case 1:
$neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col] == 2;
if($neigh_heads == 1 || $neigh_heads == 2){
$cell = 2;
};
};
};
unset($cell);
};
unset($rowc);
echo . ($i + 1) . ;
draw_world($world);
}; | 48Wireworld
| 12php
| 4vn5n |
use winit::event::{Event, WindowEvent}; | 46Window creation
| 15rust
| 96smm |
import javax.swing.JFrame
object ShowWindow{
def main(args: Array[String]){
var jf = new JFrame("Hello!")
jf.setSize(800, 600)
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
jf.setVisible(true)
}
} | 46Window creation
| 16scala
| 29olb |
my $s = "In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close-by-the-king's-castle-lay-a-great-dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.";
$s =~ s/\b\s+/ /g;
$s =~ s/\s*$/\n\n/;
my $_ = $s;
s/\s*(.{1,66})\s/$1\n/g, print;
$_ = $s;
s/\s*(.{1,25})\s/$1\n/g, print; | 44Word wrap
| 2perl
| 6tq36 |
extern crate xml; | 35XML/Input
| 15rust
| jgg72 |
val students =
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
students \ "Student" \\ "@Name" foreach println | 35XML/Input
| 16scala
| bjjk6 |
<?php
for ($i = 1; $i <= 100; $i++) {
$root = sqrt($i);
$state = ($root == ceil($root))? 'open' : 'closed';
echo ;
}
?> | 21100 doors
| 12php
| kohv |
'''
Wireworld implementation.
'''
from io import StringIO
from collections import namedtuple
from pprint import pprint as pp
import copy
WW = namedtuple('WW', 'world, w, h')
head, tail, conductor, empty = allstates = 'Ht. '
infile = StringIO('''\
tH.........
. .
...
. .
Ht.. ......\
''')
def readfile(f):
'''file > initial world configuration'''
world = [row.rstrip('\r\n') for row in f]
height = len(world)
width = max(len(row) for row in world)
nonrow = [ % (-width, ) ]
world = nonrow + \
[ % (-width, row) for row in world ] + \
nonrow
world = [list(row) for row in world]
return WW(world, width, height)
def newcell(currentworld, x, y):
istate = currentworld[y][x]
assert istate in allstates, 'Wireworld cell set to unknown value '% istate
if istate == head:
ostate = tail
elif istate == tail:
ostate = conductor
elif istate == empty:
ostate = empty
else:
n = sum( currentworld[y+dy][x+dx] == head
for dx,dy in ( (-1,-1), (-1,+0), (-1,+1),
(+0,-1), (+0,+1),
(+1,-1), (+1,+0), (+1,+1) ) )
ostate = head if 1 <= n <= 2 else conductor
return ostate
def nextgen(ww):
'compute next generation of wireworld'
world, width, height = ww
newworld = copy.deepcopy(world)
for x in range(1, width+1):
for y in range(1, height+1):
newworld[y][x] = newcell(world, x, y)
return WW(newworld, width, height)
def world2string(ww):
return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] )
ww = readfile(infile)
infile.close()
for gen in range(10):
print ( (% gen) + '=' * (ww.w-4) + '\n' )
print ( world2string(ww) )
ww = nextgen(ww) | 48Wireworld
| 3python
| osr81 |
<?php
$text = <<<ENDTXT
If there's anything you need
All you have to do is say
You know you satisfy everything in me
We shouldn't waste a single day
So don't stop me falling
It's destiny calling
A power I just can't deny
It's never changing
Can't you hear me, I'm saying
I want you for the rest of my life
Together forever and never to part
Together forever we two
And don't you know
I would move heaven and earth
To be together forever with you
ENDTXT;
$text = str_replace( PHP_EOL, , $text );
echo wordwrap( $text, 20 ), PHP_EOL, PHP_EOL;
echo wordwrap( $text, 40 ), PHP_EOL, PHP_EOL;
echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL; | 44Word wrap
| 12php
| 1kvpq |
$top = 10;
open $fh, "<", '135-0.txt';
($text = join '', <$fh>) =~ tr/A-Z/a-z/
or die "Can't open '135-0.txt': $!\n";
@matcher = (
qr/[a-z]+/,
qr/\w+/,
qr/[a-z0-9]+/,
);
for $reg (@matcher) {
print "\nTop $top using regex: " . $reg . "\n";
@matches = $text =~ /$reg/g;
my %words;
for $w (@matches) { $words{$w}++ };
$c = 0;
for $w ( sort { $words{$b} <=> $words{$a} } keys %words ) {
printf "%-7s%6d\n", $w, $words{$w};
last if ++$c >= $top;
}
} | 50Word frequency
| 2perl
| gui4e |
<?php
preg_match_all('/\w+/', file_get_contents($argv[1]), $words);
$frecuency = array_count_values($words[0]);
arsort($frecuency);
echo ;
$i = 1;
foreach ($frecuency as $word => $count) {
echo $i . . $word . . $count . ;
if ($i >= 10) {
break;
}
$i++;
} | 50Word frequency
| 12php
| n8rig |
use LWP::Simple;
my $url = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl';
get($url) =~ /<BR>(.+? UTC)/
and print "$1\n"; | 49Web scraping
| 2perl
| lmqc5 |
use std::str::FromStr;
pub enum State {
Empty,
Conductor,
ElectronTail,
ElectronHead,
}
impl State {
fn next(&self, e_nearby: usize) -> State {
match self {
State::Empty => State::Empty,
State::Conductor => {
if e_nearby == 1 || e_nearby == 2 {
State::ElectronHead
} else {
State::Conductor
}
}
State::ElectronTail => State::Conductor,
State::ElectronHead => State::ElectronTail,
}
}
}
pub struct WireWorld {
pub width: usize,
pub height: usize,
pub data: Vec<State>,
}
impl WireWorld {
pub fn new(width: usize, height: usize) -> Self {
WireWorld {
width,
height,
data: vec![State::Empty; width * height],
}
}
pub fn get(&self, x: usize, y: usize) -> Option<State> {
if x >= self.width || y >= self.height {
None
} else {
self.data.get(y * self.width + x).copied()
}
}
pub fn set(&mut self, x: usize, y: usize, state: State) {
self.data[y * self.width + x] = state;
}
fn neighbors<F>(&self, x: usize, y: usize, mut f: F) -> usize
where F: FnMut(State) -> bool
{
let (x, y) = (x as i32, y as i32);
let neighbors = [(x-1,y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)];
neighbors.iter().filter_map(|&(x, y)| self.get(x as usize, y as usize)).filter(|&s| f(s)).count()
}
pub fn next(&mut self) {
let mut next_state = vec![];
for y in 0..self.height {
for x in 0..self.width {
let e_count = self.neighbors(x, y, |e| e == State::ElectronHead);
next_state.push(self.get(x, y).unwrap().next(e_count));
}
}
self.data = next_state;
}
}
impl FromStr for WireWorld {
type Err = ();
fn from_str(s: &str) -> Result<WireWorld, ()> {
let s = s.trim();
let height = s.lines().count();
let width = s.lines().map(|l| l.trim_end().len()).max().unwrap_or(0);
let mut world = WireWorld::new(width, height);
for (y, line) in s.lines().enumerate() {
for (x, ch) in line.trim_end().chars().enumerate() {
let state = match ch {
'.' => State::Conductor,
't' => State::ElectronTail,
'H' => State::ElectronHead,
_ => State::Empty,
};
world.set(x, y, state);
}
}
Ok(world)
}
} | 48Wireworld
| 14ruby
| n8jit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.