code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
null | 756Hello world/Line printer
| 10javascript
| 70srd |
import java.io.File
fun main(args: Array<String>) {
val text = "Hello World!\n"
File("/dev/lp0").writeText(text)
} | 756Hello world/Line printer
| 11kotlin
| 9khmh |
main() {
var bye = 'Hello world!';
print("$bye");
} | 755Hello world/Text
| 18dart
| 67734 |
(defn hash-join [table1 col1 table2 col2]
(let [hashed (group-by col1 table1)]
(flatten
(for [r table2]
(for [s (hashed (col2 r))]
(merge s r))))))
(def s '({:age 27:name "Jonah"}
{:age 18:name "Alan"}
{:age 28:name "Glory"}
{:age 18:name "Popeye"}
{:age 28:name "Alan"}))
(def r '({:nemesis "Whales":name "Jonah"}
{:nemesis "Spiders":name "Jonah"}
{:nemesis "Ghosts":name "Alan"}
{:nemesis "Zombies":name "Alan"}
{:nemesis "Buffy":name "Glory"}))
(pprint (sort-by:name (hash-join s:name r:name))) | 757Hash join
| 6clojure
| 8cm05 |
open O, ">", "/dev/lp0";
print O "Hello World!\n";
close O; | 756Hello world/Line printer
| 2perl
| w3ze6 |
$ sudo apt-get install gcc | 758Hello world/Newbie
| 5c
| cbj9c |
func func1(f: String->String) -> String { return f("a string") }
func func2(s: String) -> String { return "func2 called with " + s }
println(func1(func2)) | 754Higher-order functions
| 17swift
| 9kbmj |
<?php
file_put_contents('/dev/lp0', 'Hello world!');
?> | 756Hello world/Line printer
| 12php
| lpbcj |
$ sudo apt-get install open-cobol | 758Hello world/Newbie
| 6clojure
| 5w1uz |
package main
import "fmt"
func main() {
tableA := []struct {
value int
key string
}{
{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
{28, "Alan"},
}
tableB := []struct {
key string
value string
}{
{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
} | 757Hash join
| 0go
| cbh9g |
lp = open()
lp.write()
lp.close() | 756Hello world/Line printer
| 3python
| x63wr |
def hashJoin(table1, col1, table2, col2) {
def hashed = table1.groupBy { s -> s[col1] }
def q = [] as Set
table2.each { r ->
def join = hashed[r[col2]]
join.each { s ->
q << s.plus(r)
}
}
q
} | 757Hash join
| 7groovy
| 3r4zd |
import qualified Data.HashTable.ST.Basic as H
import Data.Hashable
import Control.Monad.ST
import Control.Monad
import Data.STRef
hashJoin :: (Eq k, Hashable k) =>
[t] -> (t -> k) -> [a] -> (a -> k) -> [(t, a)]
hashJoin xs fx ys fy = runST $ do
l <- newSTRef []
ht <- H.new
forM_ ys $ \y -> H.insert ht (fy y) =<<
(H.lookup ht (fy y) >>= \case
Nothing -> return [y]
Just v -> return (y:v))
forM_ xs $ \x -> do
H.lookup ht (fx x) >>= \case
Nothing -> return ()
Just v -> modifySTRef' l ((map (x,) v) ++)
readSTRef l
main = mapM_ print $ hashJoin
[(1, "Jonah"), (2, "Alan"), (3, "Glory"), (4, "Popeye")]
snd
[("Jonah", "Whales"), ("Jonah", "Spiders"),
("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy")]
fst | 757Hash join
| 8haskell
| pdibt |
unsigned strhashkey( const char * key, int max)
{
unsigned h=0;
unsigned hl, hr;
while(*key) {
h += *key;
hl= 0x5C5 ^ (h&0xfff00000 )>>18;
hr =(h&0x000fffff );
h = hl ^ hr ^ *key++;
}
return h % max;
}
typedef struct sHme {
KeyType key;
ValType value;
struct sHme *link;
} *MapEntry;
typedef struct he {
MapEntry first, last;
} HashElement;
HashElement hash[HASH_SIZE];
typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);
void HashAddH( KeyType key, ValType value,
KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
(*copyVal)(&m_ent->value, value);
}
else {
MapEntry last;
MapEntry hme = malloc(sizeof(struct sHme));
(*copyKey)(&hme->key, key);
(*copyVal)(&hme->value, value);
hme->link = NULL;
last = hash[hix].last;
if (last) {
last->link = hme;
}
else
hash[hix].first = hme;
hash[hix].last = hme;
}
}
int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
*val = m_ent->value;
}
return (m_ent != NULL);
}
void copyStr(const char**dest, const char *src)
{
*dest = strdup(src);
}
void copyInt( int *dest, int src)
{
*dest = src;
}
int strCompare( const char *key1, const char *key2)
{
return strcmp(key1, key2) == 0;
}
void HashAdd( KeyType key, ValType value )
{
HashAddH( key, value, ©Str, ©Int, &strhashkey, &strCompare);
}
int HashGet(ValType *val, KeyType key)
{
return HashGetH( val, key, &strhashkey, &strCompare);
}
int main()
{
static const char * keyList[] = {,,,, , };
static int valuList[] = {1,43,640, 747, 42, 42};
int ix;
for (ix=0; ix<6; ix++) {
HashAdd(keyList[ix], valuList[ix]);
}
return 0;
} | 759Hash from two arrays
| 5c
| lpjcy |
open(, ) { |f| f.puts } | 756Hello world/Line printer
| 14ruby
| smyqw |
use std::fs::OpenOptions;
use std::io::Write;
fn main() {
let file = OpenOptions::new().write(true).open("/dev/lp0").unwrap();
file.write(b"Hello, World!").unwrap();
} | 756Hello world/Line printer
| 15rust
| 09msl |
import java.awt.print.PrinterException
import scala.swing.TextArea
object LinePrinter extends App {
val (show, context) = (false, "Hello, World!")
try | 756Hello world/Line printer
| 16scala
| i2lox |
import java.util.*;
public class HashJoin {
public static void main(String[] args) {
String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"},
{"18", "Popeye"}, {"28", "Alan"}};
String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"},
{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"},
{"Bob", "foo"}};
hashJoin(table1, 1, table2, 0).stream()
.forEach(r -> System.out.println(Arrays.deepToString(r)));
}
static List<String[][]> hashJoin(String[][] records1, int idx1,
String[][] records2, int idx2) {
List<String[][]> result = new ArrayList<>();
Map<String, List<String[]>> map = new HashMap<>();
for (String[] record : records1) {
List<String[]> v = map.getOrDefault(record[idx1], new ArrayList<>());
v.add(record);
map.put(record[idx1], v);
}
for (String[] record : records2) {
List<String[]> lst = map.get(record[idx2]);
if (lst != null) {
lst.stream().forEach(r -> {
result.add(new String[][]{r, record});
});
}
}
return result;
}
} | 757Hash join
| 9java
| rsxg0 |
$ cat >hello.go | 758Hello world/Newbie
| 0go
| w3feg |
println 'Hello to the Groovy world' | 758Hello world/Newbie
| 7groovy
| bn8ky |
$ sudo apt-get install ghc | 758Hello world/Newbie
| 8haskell
| 6743k |
(() => {
'use strict'; | 757Hash join
| 10javascript
| bnoki |
(zipmap [\a \b \c] [1 2 3]) | 759Hash from two arrays
| 6clojure
| 4x15o |
javac -version | 758Hello world/Newbie
| 9java
| nvcih |
console.log("Hello, World!"); | 758Hello world/Newbie
| 10javascript
| 3r5z0 |
import Foundation
let out = NSOutputStream(toFileAtPath: "/dev/lp0", append: true)
let data = "Hello, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
out?.open()
out?.write(UnsafePointer<UInt8>(data!.bytes), maxLength: data!.length)
out?.close() | 756Hello world/Line printer
| 17swift
| qy6xg |
notepad hello.kt | 758Hello world/Newbie
| 11kotlin
| sm3q7 |
package main
import (
"fmt"
"math/big"
)
func harmonic(n int) *big.Rat {
sum := new(big.Rat)
for i := int64(1); i <= int64(n); i++ {
r := big.NewRat(1, i)
sum.Add(sum, r)
}
return sum
}
func main() {
fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
numbers := make([]int, 21)
for i := 1; i <= 20; i++ {
numbers[i-1] = i
}
numbers[20] = 100
for _, i := range numbers {
fmt.Printf("%3d:%s\n", i, harmonic(i))
}
fmt.Println("\nThe first harmonic number to exceed the following integers is:")
const limit = 10
for i, n, h := 1, 1, 0.0; i <= limit; n++ {
h += 1.0 / float64(n)
if h > float64(i) {
fmt.Printf("integer =%2d -> n =%6d -> harmonic number =%9.6f (to 6dp)\n", i, n, h)
i++
}
}
} | 760Harmonic series
| 0go
| kiqhz |
data class A(val age: Int, val name: String)
data class B(val character: String, val nemesis: String)
data class C(val rowA: A, val rowB: B)
fun hashJoin(tableA: List<A>, tableB: List<B>): List<C> {
val mm = tableB.groupBy { it.character }
val tableC = mutableListOf<C>()
for (a in tableA) {
val value = mm[a.name] ?: continue
for (b in value) tableC.add(C(a, b))
}
return tableC.toList()
}
fun main(args: Array<String>) {
val tableA = listOf(
A(27, "Jonah"),
A(18, "Alan"),
A(28, "Glory"),
A(18, "Popeye"),
A(28, "Alan")
)
val tableB = listOf(
B("Jonah", "Whales"),
B("Jonah", "Spiders"),
B("Alan", "Ghosts"),
B("Alan", "Zombies"),
B("Glory", "Buffy")
)
val tableC = hashJoin(tableA, tableB)
println("A.Age A.Name B.Character B.Nemesis")
println("----- ------ ----------- ---------")
for (c in tableC) {
print("${c.rowA.age} ${c.rowA.name.padEnd(6)} ")
println("${c.rowB.character.padEnd(6)} ${c.rowB.nemesis}")
}
} | 757Hash join
| 11kotlin
| vap21 |
int main(int argc, char *argv[]) {
(void) printf();
return EXIT_SUCCESS;
} | 761Hello world/Newline omission
| 5c
| 67v32 |
import Data.List (find)
import Data.Ratio
harmonic :: [Rational]
harmonic =
scanl1
(\a x -> a + 1 / x)
[1 ..]
main :: IO ()
main = do
putStrLn "First 20 terms:"
mapM_ putStrLn $
showRatio <$> take 20 harmonic
putStrLn "\n100th term:"
putStrLn $ showRatio (harmonic !! 99)
putStrLn ""
putStrLn "One-based indices of first terms above threshold values:"
let indexedHarmonic = zip [0 ..] harmonic
mapM_
putStrLn
$ fmap
( showFirstLimit
<*> \n -> find ((> n) . snd) indexedHarmonic
)
[1 .. 10]
showFirstLimit n (Just (i, r)) =
"Term "
<> show (succ i)
<> " is the first above "
<> show (numerator n)
showRatio :: Ratio Integer -> String
showRatio =
((<>) . show . numerator)
<*> (('/':) . show . denominator) | 760Harmonic series
| 8haskell
| nvmie |
local function recA(age, name) return { Age=age, Name=name } end
local tabA = { recA(27,"Jonah"), recA(18,"Alan"), recA(28,"Glory"), recA(18,"Popeye"), recA(28,"Alan") }
local function recB(character, nemesis) return { Character=character, Nemesis=nemesis } end
local tabB = { recB("Jonah","Whales"), recB("Jonah","Spiders"), recB("Alan","Ghosts"), recB("Alan","Zombies"), recB("Glory","Buffy") }
local function hashjoin(taba, cola, tabb, colb)
local hash, join = {}, {}
for _,rowa in pairs(taba) do
if (not hash[rowa[cola]]) then hash[rowa[cola]] = {} end
table.insert(hash[rowa[cola]], rowa)
end
for _,rowb in pairs(tabb) do
for _,rowa in pairs(hash[rowb[colb]]) do
join[#join+1] = { A=rowa, B=rowb }
end
end
return join
end
for _,row in pairs(hashjoin(tabA, "Name", tabB, "Character")) do
print(row.A.Age, row.A.Name, row.B.Character, row.B.Nemesis)
end | 757Hash join
| 1lua
| ue1vl |
(print "Goodbye, World!") | 761Hello world/Newline omission
| 6clojure
| lprcb |
io.write("Hello world, from ",_VERSION,"!\n") | 758Hello world/Newbie
| 1lua
| 096sd |
static int digsum(int n)
{
int sum = 0;
do { sum += n % 10; } while (n /= 10);
return sum;
}
int main(void)
{
int n, done, found;
for (n = 1, done = found = 0; !done; ++n) {
if (n % digsum(n) == 0) {
if (found++ < 20) printf(, n);
if (n > 1000) done = printf(, n);
}
}
return 0;
} | 762Harshad or Niven series
| 5c
| lpgcy |
use strict;
use warnings;
use feature 'say';
use Math::AnyNum ':overload';
use List::AllUtils 'firstidx';
my(@H,$n) = 0;
do { ++$n and push @H, $H[-1] + 1/$n } until $H[-1] >= 10;
shift @H;
say 'First twenty harmonic numbers as rationals:';
my $c = 0;
printf("%20s", $_) and (not ++$c%5) and print "\n" for @H[0..19];
say "\nIndex of first value (zero based):";
for my $i (1..10) {
printf " greater than%2d:%5s\n", $i, firstidx { $_ > $i } @H;
} | 760Harmonic series
| 2perl
| mh4yz |
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf(, ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf(, td);
return 0;
} | 763Handle a signal
| 5c
| 70prg |
from fractions import Fraction
def harmonic_series():
n, h = Fraction(1), Fraction(1)
while True:
yield h
h += 1 / (n + 1)
n += 1
if __name__ == '__main__':
from itertools import islice
for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)):
print(n, '/', d) | 760Harmonic series
| 3python
| 9kgmf |
HofN <- function(n) sum(1/seq_len(n))
H <- sapply(1:100000, HofN)
print(H[1:20])
print(sapply(1:10, function(x) which.max(H > x))) | 760Harmonic series
| 13r
| 3rvzt |
int main(){int a=0, b=0, c=a/b;} | 764Halt and catch fire
| 5c
| f56d3 |
(require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500)) | 763Handle a signal
| 6clojure
| pdxbd |
(defn digsum [n acc]
(if (zero? n) acc
(digsum (quot n 10) (+ acc (mod n 10)))))
(let [harshads (filter
#(zero? (mod % (digsum % 0)))
(iterate inc 1))]
(prn (take 20 harshads))
(prn (first (filter #(> % 1000) harshads)))) | 762Harshad or Niven series
| 6clojure
| 4xk5o |
use Data::Dumper qw(Dumper);
sub hashJoin {
my ($table1, $index1, $table2, $index2) = @_;
my %h;
foreach my $s (@$table1) {
push @{ $h{$s->[$index1]} }, $s;
}
map { my $r = $_;
map [$_, $r], @{ $h{$r->[$index2]} }
} @$table2;
}
@table1 = ([27, "Jonah"],
[18, "Alan"],
[28, "Glory"],
[18, "Popeye"],
[28, "Alan"]);
@table2 = (["Jonah", "Whales"],
["Jonah", "Spiders"],
["Alan", "Ghosts"],
["Alan", "Zombies"],
["Glory", "Buffy"]);
$Data::Dumper::Indent = 0;
foreach my $row (hashJoin(\@table1, 1, \@table2, 0)) {
print Dumper($row), "\n";
} | 757Hash join
| 2perl
| 09ys4 |
use num::rational::Ratio;
use num::{BigInt, FromPrimitive};
fn main() {
for n in 1..=20 {
println!("Harmonic number {} = {}", n, harmonic_number(n.into()));
}
println!("Harmonic number 100 = {}", harmonic_number(100.into()));
let max = 5;
let mut target = 1;
let mut i = 1;
while target <= max {
if harmonic_number(i.into()) > Ratio::from_integer(FromPrimitive::from_u64(target).unwrap())
{
println!("Position of first term > {} is {}", target, i);
target += 1;
}
i += 1;
}
}
fn harmonic_number(n: BigInt) -> Ratio<BigInt> {
let mut result: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(0).unwrap());
let mut i: BigInt = FromPrimitive::from_u8(1).unwrap();
let one: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u8(1).unwrap());
while i <= n {
result = &result + &one / &i;
i += 1;
}
result
} | 760Harmonic series
| 15rust
| 21jlt |
package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)} | 764Halt and catch fire
| 0go
| j8p7d |
=head1 Obtaining perl
On the majority of UNIX and UNIX-like operating systems
(Linux, Solaris, AIX, HPUX, et cetera), perl will already be installed.
Mac OS X also ships with perl.
Note that "Perl" refers to the language
while "perl" refers to the interpreter used to run Perl programs.
Windows does not ship with perl. Instead, you will have to install one of
the following perl distributions:
=over 4
=item Strawberry Perl
L<Strawberry Perl|http://strawberryperl.com/>: A 100% Open Source Perl for
Windows that is exactly the same as Perl everywhere else; this includes using
modules from CPAN, without the need for binary packages.
=item DWIM Perl for Windows
L<DWIM Perl for Windows|http://dwimperl.com/windows.html>: A 100% Open Source
Perl for Windows, based on Strawberry Perl.
It aims to include as many useful CPAN modules as possible.
=item ActiveState Perl
L<http://www.activestate.com/activeperl/downloads>
=back
Links and further instructions on installation can be found on
L<http://www.perl.org/get.html>.
Once perl is installed, the task of printing "Hello, World!" is quite simple.
From the command line, first check if your environment's C<PATH> variable
knows where to find perl.
On most systems, this can be achieved by entering C<which perl>;
if it spits out something like F</usr/bin/perl>, you're good to go!
If it tells you
which: no perl in (...)
it means you need to add perl to your environment's C<PATH> variable.
This is done on most systems by entering
export PATH=$PATH:[...]
where [...] is the full path to your perl installation (usually /usr/bin/perl).
If you do not have the C<which> command, you can probably just type C<perl>
to see if it fires up the perl interpreter.
If it does, press Ctrl+D to exit it and proceed.
Otherwise, perform the steps above to add perl to your PATH variable.
Once perl is installed, one-liners can be executed from the command line
by invoking perl with the C<-e> switch.
$ perl -e 'print "Hello, World!\n";'
To create a script file that's more permanent, it can be put in a text file.
The name can be anything, but F<.pl> is encouraged.
The
if the operating system supports it, it tells where to find the perl interpreter.
If the script is run with C<perl>, this line will be ignored--
this is for invoking the file as an executable.
=cut
print "Hello, World!\n"; | 758Hello world/Newbie
| 2perl
| uepvr |
<?php
echo 'Hello, world!';
?> | 758Hello world/Newbie
| 12php
| 8cy0m |
main = error "Instant crash" | 764Halt and catch fire
| 8haskell
| olf8p |
error(1) | 764Halt and catch fire
| 1lua
| pdwbw |
<?php
function hashJoin($table1, $index1, $table2, $index2) {
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
$table1 = array(array(27, ),
array(18, ),
array(28, ),
array(18, ),
array(28, ));
$table2 = array(array(, ),
array(, ),
array(, ),
array(, ),
array(, ),
array(, ));
foreach (hashJoin($table1, 1, $table2, 0) as $row)
print_r($row);
?> | 757Hash join
| 12php
| 5waus |
&a | 764Halt and catch fire
| 2perl
| 67c36 |
0/0 | 764Halt and catch fire
| 3python
| yjl6q |
package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; { | 763Handle a signal
| 0go
| du6ne |
package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
} | 759Hash from two arrays
| 0go
| x6fwf |
def keys = ['a','b','c']
def vals = ['aaa', 'bbb', 'ccc']
def hash = [:]
keys.eachWithIndex { key, i ->
hash[key] = vals[i]
} | 759Hash from two arrays
| 7groovy
| pd8bo |
raise | 764Halt and catch fire
| 14ruby
| 9kvmz |
fn main(){panic!("");} | 764Halt and catch fire
| 15rust
| cbu9z |
fatalError("You've met with a terrible fate, haven't you?") | 764Halt and catch fire
| 17swift
| mh2yk |
import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1) | 763Handle a signal
| 8haskell
| 5wjug |
import Data.Map
makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3] | 759Hash from two arrays
| 8haskell
| yj466 |
>>> print('hello world') | 758Hello world/Newbie
| 3python
| 5w1ux |
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took%f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
} | 763Handle a signal
| 9java
| 9kumu |
int main()
{
printf(,GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));
return 0;
} | 765GUI/Maximum window dimensions
| 5c
| 09ist |
(function(){
var count=0
secs=0
var i= setInterval( function (){
count++
secs+=0.5
console.log(count)
}, 500);
process.on('SIGINT', function() {
clearInterval(i)
console.log(secs+' seconds elapsed');
process.exit()
});
})(); | 763Handle a signal
| 10javascript
| ue7vb |
from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, ),
(18, ),
(28, ),
(18, ),
(28, )]
table2 = [(, ),
(, ),
(, ),
(, ),
(, )]
for row in hashJoin(table1, 1, table2, 0):
print(row) | 757Hash join
| 3python
| 8cm0o |
package main
import "fmt"
func main() { fmt.Print("Goodbye, World!") } | 761Hello world/Newline omission
| 0go
| pdsbg |
null | 763Handle a signal
| 11kotlin
| zg9ts |
double dist(double th1, double ph1, double th2, double ph2)
{
double dx, dy, dz;
ph1 -= ph2;
ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;
dz = sin(th1) - sin(th2);
dx = cos(ph1) * cos(th1) - cos(th2);
dy = sin(ph1) * cos(th1);
return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R;
}
int main()
{
double d = dist(36.12, -86.67, 33.94, -118.4);
printf(, d, d / 1.609344);
return 0;
} | 766Haversine formula
| 5c
| dutnv |
print "Goodbye, world" | 761Hello world/Newline omission
| 7groovy
| 70arz |
import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();
for(int i= 0; i < keys.length; i++){
hash.put(keys[i], vals[i]);
}
} | 759Hash from two arrays
| 9java
| ducn9 |
puts | 758Hello world/Newbie
| 14ruby
| gqe4q |
fn main() {
println!("Hello world!");
} | 758Hello world/Newbie
| 15rust
| rswg5 |
main = putStr "Goodbye, world" | 761Hello world/Newline omission
| 8haskell
| f59d1 |
var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
var map = {};
for(var i = 0; i < keys.length; i += 1) {
map[ keys[i] ] = values[i];
} | 759Hash from two arrays
| 10javascript
| 67538 |
scala -e 'println(\"Hello_world\")' | 758Hello world/Newbie
| 16scala
| hosja |
package main
import (
"fmt"
"github.com/go-vgo/robotgo"
)
func main() {
w, h := robotgo.GetScreenSize()
fmt.Printf("Screen size:%d x%d\n", w, h)
fpid, err := robotgo.FindIds("firefox")
if err == nil && len(fpid) > 0 {
pid := fpid[0]
robotgo.ActivePID(pid)
robotgo.MaxWindow(pid)
_, _, w, h = robotgo.GetBounds(pid)
fmt.Printf("Max usable:%d x%d\n", w, h)
}
} | 765GUI/Maximum window dimensions
| 0go
| uegvt |
def window = java.awt.GraphicsEnvironment.localGraphicsEnvironment.maximumWindowBounds
println "width: $window.width, height: $window.height" | 765GUI/Maximum window dimensions
| 7groovy
| 9k2m4 |
import Graphics.UI.Gtk
import Control.Monad (when)
import Control.Monad.Trans (liftIO)
maximumWindowDimensions :: IO ()
maximumWindowDimensions = do
initGUI
window <- windowNew
on window objectDestroy mainQuit
on window configureEvent printSize
screen <- windowGetScreen window
x <- screenGetWidth screen
y <- screenGetHeight screen
putStrLn ("The screen is " ++ show x ++ " pixels wide and " ++
show y ++ " pixels tall for an undecorated fullscreen window.")
windowMaximize window
widgetShowAll window
mainGUI
printSize :: EventM EConfigure Bool
printSize = do
w <- eventWindow
s <- liftIO $ drawWindowGetState w
when (WindowStateMaximized `elem` s) $ do
(x, y) <- eventSize
liftIO $ putStrLn ("The inner window region is now " ++ show x ++
" pixels wide and " ++ show y ++ " pixels tall.")
return True | 765GUI/Maximum window dimensions
| 8haskell
| w3sed |
my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
} | 763Handle a signal
| 2perl
| bnwk4 |
def hashJoin(table1, index1, table2, index2)
h = table1.group_by {|s| s[index1]}
h.default = []
table2.collect {|r|
h[r[index2]].collect {|s| [s, r]}
}.flatten(1)
end
table1 = [[27, ],
[18, ],
[28, ],
[18, ],
[28, ]]
table2 = [[, ],
[, ],
[, ],
[, ],
[, ]]
hashJoin(table1, 1, table2, 0).each { |row| p row } | 757Hash join
| 14ruby
| i2coh |
(defn haversine
[{lon1:longitude lat1:latitude} {lon2:longitude lat2:latitude}]
(let [R 6372.8
dlat (Math/toRadians (- lat2 lat1))
dlon (Math/toRadians (- lon2 lon1))
lat1 (Math/toRadians lat1)
lat2 (Math/toRadians lat2)
a (+ (* (Math/sin (/ dlat 2)) (Math/sin (/ dlat 2))) (* (Math/sin (/ dlon 2)) (Math/sin (/ dlon 2)) (Math/cos lat1) (Math/cos lat2)))]
(* R 2 (Math/asin (Math/sqrt a)))))
(haversine {:latitude 36.12:longitude -86.67} {:latitude 33.94:longitude -118.40}) | 766Haversine formula
| 6clojure
| 67m3q |
import java.awt.*;
import javax.swing.JFrame;
public class Test extends JFrame {
public static void main(String[] args) {
new Test();
}
Test() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
System.out.println("Physical screen size: " + screenSize);
Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());
System.out.println("Insets: " + insets);
screenSize.width -= (insets.left + insets.right);
screenSize.height -= (insets.top + insets.bottom);
System.out.println("Max available: " + screenSize);
}
} | 765GUI/Maximum window dimensions
| 9java
| ki1hm |
<?php
declare(ticks = 1);
$start = microtime(YES);
function mySigHandler() {
global $start;
$elapsed = microtime(YES) - $start;
echo ;
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000))
echo ++$n, ;
?> | 763Handle a signal
| 12php
| 67l3g |
public class HelloWorld
{
public static void main(String[] args)
{
System.out.print("Goodbye, World!");
}
} | 761Hello world/Newline omission
| 9java
| 09tse |
process.stdout.write("Goodbye, World!"); | 761Hello world/Newline omission
| 10javascript
| dumnu |
null | 759Hash from two arrays
| 11kotlin
| 093sf |
tclsh8.5 | 758Hello world/Newbie
| 17swift
| 4xa5g |
null | 765GUI/Maximum window dimensions
| 11kotlin
| gqj4d |
use std::collections::HashMap;
use std::hash::Hash; | 757Hash join
| 15rust
| nvli4 |
int main (int argc, char **argv) {
GtkWidget *window;
gtk_init(&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), );
g_signal_connect (G_OBJECT (window), , gtk_main_quit, NULL);
gtk_widget_show_all (window);
gtk_main();
return 0;
} | 767Hello world/Graphical
| 5c
| ezwav |
def join[Type](left: Seq[Seq[Type]], right: Seq[Seq[Type]]) = {
val hash = right.groupBy(_.head) withDefaultValue Seq()
left.flatMap(cols => hash(cols.last).map(cols ++ _.tail))
} | 757Hash join
| 16scala
| t4ufb |
fun main(args: Array<String>) = print("Goodbye, World!") | 761Hello world/Newline omission
| 11kotlin
| ezoa4 |
use strict;
use warnings;
use Tk;
sub get_size {
my $mw = MainWindow->new();
return ($mw->maxsize);
} | 765GUI/Maximum window dimensions
| 2perl
| nvtiw |
import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for%5.3f seconds.'% (time.time() - t1)
break
counter() | 763Handle a signal
| 3python
| pdxbm |
import tkinter as tk
root = tk.Tk()
root.state('zoomed')
root.update_idletasks()
tk.Label(root, text=(str(root.winfo_width())+ +str(root.winfo_height())),
font=(, 25)).pack()
root.mainloop() | 765GUI/Maximum window dimensions
| 3python
| duzn1 |
t1 = Time.now
catch :done do
Signal.trap('INT') do
Signal.trap('INT', 'DEFAULT')
throw :done
end
n = 0
loop do
sleep(0.5)
n += 1
puts n
end
end
tdelt = Time.now - t1
puts 'Program has run for%5.3f seconds.' % tdelt | 763Handle a signal
| 14ruby
| ats1s |
#[cfg(unix)]
fn main() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use libc::{sighandler_t, SIGINT}; | 763Handle a signal
| 15rust
| ez0aj |
import sun.misc.Signal
import sun.misc.SignalHandler
object SignalHandl extends App {
val start = System.nanoTime()
var counter = 0
Signal.handle(new Signal("INT"), new SignalHandler() {
def handle(sig: Signal) {
println(f"\nProgram execution took ${(System.nanoTime() - start) / 1e9f}%f seconds\n")
exit(0)
}
})
while (true) {
counter += 1
println(counter)
Thread.sleep(500)
}
} | 763Handle a signal
| 16scala
| qyixw |
-- setting up the test data
CREATE TABLE people (age NUMBER(3), name varchar2(30));
INSERT INTO people (age, name)
SELECT 27, 'Jonah' FROM dual UNION ALL
SELECT 18, 'Alan' FROM dual UNION ALL
SELECT 28, 'Glory' FROM dual UNION ALL
SELECT 18, 'Popeye' FROM dual UNION ALL
SELECT 28, 'Alan' FROM dual
;
CREATE TABLE nemesises (name varchar2(30), nemesis varchar2(30));
INSERT INTO nemesises (name, nemesis)
SELECT 'Jonah', 'Whales' FROM dual UNION ALL
SELECT 'Jonah', 'Spiders' FROM dual UNION ALL
SELECT 'Alan' , 'Ghosts' FROM dual UNION ALL
SELECT 'Alan' , 'Zombies' FROM dual UNION ALL
SELECT 'Glory', 'Buffy' FROM dual
; | 757Hash join
| 19sql
| 67g3m |
import 'dart:math';
class Haversine {
static final R = 6372.8; | 766Haversine formula
| 18dart
| sm8q6 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.