code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
$handle = fopen(, );
$missformcount = 0;
$totalcount = 0;
$dates = array();
while (!feof($handle)) {
$buffer = fgets($handle);
$line = preg_replace('/\s+/',' ',$buffer);
$line = explode(' ',trim($line));
$datepattern = '/^\d{4}-\d{2}-\d{2}$/';
$valpattern = '/^\d+\.{1}\d{3}$/';
$flagpattern = '/^[1-9]{1}$/';
if(count($line) != 49) $missformcount++;
if(!preg_match($datepattern,$line[0],$check)) $missformcount++;
else $dates[$totalcount+1] = $check[0];
$errcount = 0;
for($i=1;$i<count($line);$i++){
if($i%2!=0){
if(!preg_match($valpattern,$line[$i],$check)) $errcount++;
}else{
if(!preg_match($flagpattern,$line[$i],$check)) $errcount++;
}
}
if($errcount != 0) $missformcount++;
$totalcount++;
}
fclose ($handle);
$good = $totalcount - $missformcount;
$duplicates = array_diff_key( $dates , array_unique( $dates ));
echo 'Valid records ' . $good . ' of ' . $totalcount . ' total<br>';
echo 'Duplicates: <br>';
foreach ($duplicates as $key => $val){
echo $val . ' at Line: ' . $key . '<br>';
} | 124Text processing/2
| 12php
| zirt1 |
import sys
if in sys.stdout.encoding:
print()
else:
raise Exception() | 126Terminal control/Unicode output
| 3python
| 3ngzc |
if (any(grepl("UTF", toupper(Sys.getenv(c("LANG", "LC_ALL", "LC_CTYPE")))))) {
cat("Unicode is supported on this terminal and U+25B3 is: \u25b3\n")
} else {
cat("Unicode is not supported on this terminal.")
} | 126Terminal control/Unicode output
| 13r
| d0vnt |
if ENV.values_at(,,).compact.first.include?()
puts
else
raise
end | 126Terminal control/Unicode output
| 14ruby
| yf76n |
scala> println(s"Unicode is supported on this terminal and U+25B3 is: \u25b3")
Unicode is supported on this terminal and U+25B3 is : | 126Terminal control/Unicode output
| 16scala
| l6bcq |
int main() {
printf();
return 0;
} | 127Terminal control/Ringing the terminal bell
| 5c
| j5s70 |
typedef unsigned __int32 uint32_t;
typedef uint32_t ub4;
ub4 randrsl[256], randcnt;
static ub4 mm[256];
static ub4 aa=0, bb=0, cc=0;
void isaac()
{
register ub4 i,x,y;
cc = cc + 1;
bb = bb + cc;
for (i=0; i<256; ++i)
{
x = mm[i];
switch (i%4)
{
case 0: aa = aa^(aa<<13); break;
case 1: aa = aa^(aa>>6); break;
case 2: aa = aa^(aa<<2); break;
case 3: aa = aa^(aa>>16); break;
}
aa = mm[(i+128)%256] + aa;
mm[i] = y = mm[(x>>2)%256] + aa + bb;
randrsl[i] = bb = mm[(y>>10)%256] + x;
}
randcnt = 0;
}
{ \
a^=b<<11; d+=a; b+=c; \
b^=c>>2; e+=b; c+=d; \
c^=d<<8; f+=c; d+=e; \
d^=e>>16; g+=d; e+=f; \
e^=f<<10; h+=e; f+=g; \
f^=g>>4; a+=f; g+=h; \
g^=h<<8; b+=g; h+=a; \
h^=a>>9; c+=h; a+=b; \
}
void randinit(int flag)
{
register int i;
ub4 a,b,c,d,e,f,g,h;
aa=bb=cc=0;
a=b=c=d=e=f=g=h=0x9e3779b9;
for (i=0; i<4; ++i)
{
mix(a,b,c,d,e,f,g,h);
}
for (i=0; i<256; i+=8)
{
if (flag)
{
a+=randrsl[i ]; b+=randrsl[i+1]; c+=randrsl[i+2]; d+=randrsl[i+3];
e+=randrsl[i+4]; f+=randrsl[i+5]; g+=randrsl[i+6]; h+=randrsl[i+7];
}
mix(a,b,c,d,e,f,g,h);
mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
}
if (flag)
{
for (i=0; i<256; i+=8)
{
a+=mm[i ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3];
e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7];
mix(a,b,c,d,e,f,g,h);
mm[i ]=a; mm[i+1]=b; mm[i+2]=c; mm[i+3]=d;
mm[i+4]=e; mm[i+5]=f; mm[i+6]=g; mm[i+7]=h;
}
}
isaac();
randcnt=0;
}
ub4 iRandom()
{
ub4 r = randrsl[randcnt];
++randcnt;
if (randcnt >255) {
isaac();
randcnt = 0;
}
return r;
}
char iRandA()
{
return iRandom() % 95 + 32;
}
void iSeed(char *seed, int flag)
{
register ub4 i,m;
for (i=0; i<256; i++) mm[i]=0;
m = strlen(seed);
for (i=0; i<256; i++)
{
if (i>m) randrsl[i]=0; else randrsl[i] = seed[i];
}
randinit(flag);
}
enum ciphermode {
mEncipher, mDecipher, mNone
};
char v[MAXMSG];
char* Vernam(char *msg)
{
register ub4 i,l;
l = strlen(msg);
memset(v,'\0',l+1);
for (i=0; i<l; i++)
v[i] = iRandA() ^ msg[i];
return v;
}
char Caesar(enum ciphermode m, char ch, char shift, char modulo, char start)
{
register int n;
if (m == mDecipher) shift = -shift;
n = (ch-start) + shift;
n = n % modulo;
if (n<0) n += modulo;
return start+n;
}
char c[MAXMSG];
char* CaesarStr(enum ciphermode m, char *msg, char modulo, char start)
{
register ub4 i,l;
l = strlen(msg);
memset(c,'\0',l+1);
for (i=0; i<l; i++)
c[i] = Caesar(m, msg[i], iRandA(), modulo, start);
return c;
}
int main()
{
register ub4 n,l;
char *msg = ;
char *key = ;
char vctx[MAXMSG], vptx[MAXMSG];
char cctx[MAXMSG], cptx[MAXMSG];
l = strlen(msg);
iSeed(key,1);
strcpy(vctx, Vernam(msg));
strcpy(cctx, CaesarStr(mEncipher, msg, MOD, START));
iSeed(key,1);
strcpy(vptx, Vernam(vctx));
strcpy(cptx, CaesarStr(mDecipher,cctx, MOD, START));
printf(,msg);
printf(,key);
printf();
for (n=0; n<l; n++) printf(,vctx[n]);
printf();
printf(,vptx);
printf();
for (n=0; n<l; n++) printf(,cctx[n]);
printf();
printf(,cptx);
return 0;
} | 128The ISAAC Cipher
| 5c
| ahn11 |
float: , double: , \
long double: , unsigned int: , \
unsigned long: , unsigned long long: , \
int: , long: , long long: , \
default: )
I * (long double)(y)))
printf(FMTSPEC(i), i), printf(), printf(FMTSPEC(j), j), \
printf(, (isint(CMPPARTS(i, j))? : ))
printf(FMTSPEC(i), i), printf(, (isint(i)? : ))
static inline int isint(long double complex n)
{
return cimagl(n) == 0 && nearbyintl(creall(n)) == creall(n);
}
int main(void)
{
TEST_REAL(0);
TEST_REAL(-0);
TEST_REAL(-2);
TEST_REAL(-2.00000000000001);
TEST_REAL(5);
TEST_REAL(7.3333333333333);
TEST_REAL(3.141592653589);
TEST_REAL(-9.223372036854776e18);
TEST_REAL(5e-324);
TEST_REAL(NAN);
TEST_CMPL(6, 0);
TEST_CMPL(0, 1);
TEST_CMPL(0, 0);
TEST_CMPL(3.4, 0);
double complex test1 = 5 + 0*I,
test2 = 3.4f,
test3 = 3,
test4 = 0 + 1.2*I;
printf(, isint(test1) ? : );
printf(, isint(test2) ? : );
printf(, isint(test3) ? : );
printf(, isint(test4) ? : );
} | 129Test integerness
| 5c
| iqmo2 |
int IsPalindrome(char *Str);
int main()
{
assert(IsPalindrome());
assert(IsPalindrome());
} | 130Test a function
| 5c
| vmh2o |
(println (char 7)) | 127Terminal control/Ringing the terminal bell
| 6clojure
| 1jnpy |
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class License {
public static void main(String[] args) throws FileNotFoundException, IOException{
BufferedReader in = new BufferedReader(new FileReader(args[0]));
int max = Integer.MIN_VALUE;
LinkedList<String> dates = new LinkedList<String>();
String line;
int count = 0;
while((line = in.readLine()) != null){
if(line.startsWith("License OUT ")) count++;
if(line.startsWith("License IN ")) count--;
if(count > max){
max = count;
String date = line.split(" ")[3];
dates.clear();
dates.add(date);
}else if(count == max){
String date = line.split(" ")[3];
dates.add(date);
}
}
System.out.println("Max licenses out: "+max);
System.out.println("At time(s): "+dates);
}
} | 125Text processing/Max licenses in use
| 9java
| f85dv |
(use 'clojure.test)
(deftest test-palindrome?
(is (palindrome? "amanaplanacanalpanama"))
(is (not (palindrome? "Test 1, 2, 3")))
(run-tests) | 130Test a function
| 6clojure
| rvag2 |
var file_system = new ActiveXObject("Scripting.FileSystemObject");
var fh = file_system.openTextFile('mlijobs.txt', 1); | 125Text processing/Max licenses in use
| 10javascript
| yfj6r |
import re
import zipfile
import StringIO
def munge2(readings):
datePat = re.compile(r'\d{4}-\d{2}-\d{2}')
valuPat = re.compile(r'[-+]?\d+\.\d+')
statPat = re.compile(r'-?\d+')
allOk, totalLines = 0, 0
datestamps = set([])
for line in readings:
totalLines += 1
fields = line.split('\t')
date = fields[0]
pairs = [(fields[i],fields[i+1]) for i in range(1,len(fields),2)]
lineFormatOk = datePat.match(date) and \
all( valuPat.match(p[0]) for p in pairs ) and \
all( statPat.match(p[1]) for p in pairs )
if not lineFormatOk:
print 'Bad formatting', line
continue
if len(pairs)!=24 or any( int(p[1]) < 1 for p in pairs ):
print 'Missing values', line
continue
if date in datestamps:
print 'Duplicate datestamp', line
continue
datestamps.add(date)
allOk += 1
print 'Lines with all readings: ', allOk
print 'Total records: ', totalLines
readings = open('readings.txt','r')
munge2(readings) | 124Text processing/2
| 3python
| kgnhf |
int main()
{
int i;
printf();
printf();
for (i = 5; i; i--) {
printf(, i);
fflush(stdout);
sleep(1);
}
printf();
return 0;
} | 131Terminal control/Preserve screen
| 5c
| 9z4m1 |
null | 125Text processing/Max licenses in use
| 11kotlin
| 8wc0q |
dfr <- read.delim("d:/readings.txt", colClasses=c("character", rep(c("numeric", "integer"), 24)))
dates <- strptime(dfr[,1], "%Y-%m-%d")
dfr[which(is.na(dfr))]
dates[duplicated(dates)]
flags <- as.matrix(dfr[,seq(3,49,2)])>0
sum(apply(flags, 1, all)) | 124Text processing/2
| 13r
| rv0gj |
package main
import "fmt"
func main() {
fmt.Print("\a")
} | 127Terminal control/Ringing the terminal bell
| 0go
| f8vd0 |
println '\7' | 127Terminal control/Ringing the terminal bell
| 7groovy
| 8wm0b |
filename = "mlijobs.txt"
io.input( filename )
max_out, n_out = 0, 0
occurr_dates = {}
while true do
line = io.read( "*line" )
if line == nil then break end
if string.find( line, "OUT" ) ~= nil then
n_out = n_out + 1
if n_out > max_out then
max_out = n_out
occurr_dates = {}
occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" )
elseif n_out == max_out then
occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" )
end
else
n_out = n_out - 1
end
end
print( "Maximum licenses in use:", max_out )
print( "Occurrences:" )
for i = 1, #occurr_dates do
print( "", occurr_dates[i] )
end | 125Text processing/Max licenses in use
| 1lua
| oxl8h |
main = putStr "\a" | 127Terminal control/Ringing the terminal bell
| 8haskell
| 4le5s |
public class Bell{
public static void main(String[] args){
java.awt.Toolkit.getDefaultToolkit().beep(); | 127Terminal control/Ringing the terminal bell
| 9java
| c3h9h |
package main
import (
"fmt"
"time"
)
func main() {
fmt.Print("\033[?1049h\033[H")
fmt.Println("Alternate screen buffer\n")
s := "s"
for i := 5; i > 0; i-- {
if i == 1 {
s = ""
}
fmt.Printf("\rgoing back in%d second%s...", i, s)
time.Sleep(time.Second)
}
fmt.Print("\033[?1049l")
} | 131Terminal control/Preserve screen
| 0go
| ekoa6 |
null | 127Terminal control/Ringing the terminal bell
| 11kotlin
| 3n4z5 |
public class PreserveScreen
{
public static void main(String[] args) throws InterruptedException {
System.out.print("\033[?1049h\033[H");
System.out.println("Alternate screen buffer\n");
for (int i = 5; i > 0; i--) {
String s = (i > 1) ? "s" : "";
System.out.printf("\rgoing back in%d second%s...", i, s);
Thread.sleep(1000);
}
System.out.print("\033[?1049l");
}
} | 131Terminal control/Preserve screen
| 9java
| iq6os |
(function() {
var orig= document.body.innerHTML
document.body.innerHTML= '';
setTimeout(function() {
document.body.innerHTML= 'something';
setTimeout(function() {
document.body.innerHTML= orig;
}, 1000);
}, 1000);
})(); | 131Terminal control/Preserve screen
| 10javascript
| zilt2 |
int
main()
{
CONSOLE_SCREEN_BUFFER_INFO info;
COORD pos;
HANDLE conout;
long len;
wchar_t c;
conout = CreateFileW(L, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
0, NULL);
if (conout == INVALID_HANDLE_VALUE)
return 1;
if (GetConsoleScreenBufferInfo(conout, &info) == 0)
return 1;
pos.X = info.srWindow.Left + 3;
pos.Y = info.srWindow.Top + 6;
if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||
len <= 0)
return 1;
wprintf(L, c);
return 0;
} | 132Terminal control/Positional read
| 5c
| mtuys |
require 'set'
def munge2(readings, debug=false)
datePat = /^\d{4}-\d{2}-\d{2}/
valuPat = /^[-+]?\d+\.\d+/
statPat = /^-?\d+/
totalLines = 0
dupdate, badform, badlen, badreading = Set[], Set[], Set[], 0
datestamps = Set[[]]
for line in readings
totalLines += 1
fields = line.split(/\t/)
date = fields.shift
pairs = fields.enum_slice(2).to_a
lineFormatOk = date =~ datePat &&
pairs.all? { |x,y| x =~ valuPat && y =~ statPat }
if!lineFormatOk
puts 'Bad formatting ' + line if debug
badform << date
end
if pairs.length!= 24 ||
pairs.any? { |x,y| y.to_i < 1 }
puts 'Missing values ' + line if debug
end
if pairs.length!= 24
badlen << date
end
if pairs.any? { |x,y| y.to_i < 1 }
badreading += 1
end
if datestamps.include?(date)
puts 'Duplicate datestamp ' + line if debug
dupdate << date
end
datestamps << date
end
puts 'Duplicate dates:', dupdate.sort.map { |x| ' ' + x }
puts 'Bad format:', badform.sort.map { |x| ' ' + x }
puts 'Bad number of fields:', badlen.sort.map { |x| ' ' + x }
puts 'Records with good readings:%i =%5.2f%%' % [
totalLines-badreading, (totalLines-badreading)/totalLines.to_f*100 ]
puts
puts 'Total records: %d' % totalLines
end
open('readings.txt','r') do |readings|
munge2(readings)
end | 124Text processing/2
| 14ruby
| p7fbh |
print("\a") | 127Terminal control/Ringing the terminal bell
| 1lua
| 6dg39 |
null | 131Terminal control/Preserve screen
| 11kotlin
| q1dx1 |
print "\033[?1049h\033[H";
print "Alternate screen buffer\n";
for (my $i = 5; $i > 0; --$i) {
print "going back in $i...\n";
sleep(1);
}
print "\033[?1049l"; | 131Terminal control/Preserve screen
| 2perl
| vmj20 |
package main
import "C"
import "fmt"
func main() {
for i := 0; i < 80*25; i++ {
fmt.Print("A") | 132Terminal control/Positional read
| 0go
| ah01f |
null | 132Terminal control/Positional read
| 11kotlin
| xpiws |
package main
import "fmt"
const (
msg = "a Top Secret secret"
key = "this is my secret key"
)
func main() {
var z state
z.seed(key)
fmt.Println("Message: ", msg)
fmt.Println("Key : ", key)
fmt.Println("XOR : ", z.vernam(msg))
}
type state struct {
aa, bb, cc uint32
mm [256]uint32
randrsl [256]uint32
randcnt int
}
func (z *state) isaac() {
z.cc++
z.bb += z.cc
for i, x := range z.mm {
switch i % 4 {
case 0:
z.aa = z.aa ^ z.aa<<13
case 1:
z.aa = z.aa ^ z.aa>>6
case 2:
z.aa = z.aa ^ z.aa<<2
case 3:
z.aa = z.aa ^ z.aa>>16
}
z.aa += z.mm[(i+128)%256]
y := z.mm[x>>2%256] + z.aa + z.bb
z.mm[i] = y
z.bb = z.mm[y>>10%256] + x
z.randrsl[i] = z.bb
}
}
func (z *state) randInit() {
const gold = uint32(0x9e3779b9)
a := [8]uint32{gold, gold, gold, gold, gold, gold, gold, gold}
mix1 := func(i int, v uint32) {
a[i] ^= v
a[(i+3)%8] += a[i]
a[(i+1)%8] += a[(i+2)%8]
}
mix := func() {
mix1(0, a[1]<<11)
mix1(1, a[2]>>2)
mix1(2, a[3]<<8)
mix1(3, a[4]>>16)
mix1(4, a[5]<<10)
mix1(5, a[6]>>4)
mix1(6, a[7]<<8)
mix1(7, a[0]>>9)
}
for i := 0; i < 4; i++ {
mix()
}
for i := 0; i < 256; i += 8 {
for j, rj := range z.randrsl[i : i+8] {
a[j] += rj
}
mix()
for j, aj := range a {
z.mm[i+j] = aj
}
}
for i := 0; i < 256; i += 8 {
for j, mj := range z.mm[i : i+8] {
a[j] += mj
}
mix()
for j, aj := range a {
z.mm[i+j] = aj
}
}
z.isaac()
}
func (z *state) seed(seed string) {
for i, r := range seed {
if i == 256 {
break
}
z.randrsl[i] = uint32(r)
}
z.randInit()
}
func (z *state) random() (r uint32) {
r = z.randrsl[z.randcnt]
z.randcnt++
if z.randcnt == 256 {
z.isaac()
z.randcnt = 0
}
return
}
func (z *state) randA() byte {
return byte(z.random()%95 + 32)
}
func (z *state) vernam(msg string) string {
b := []byte(msg)
for i := range b {
b[i] ^= z.randA()
}
return fmt.Sprintf("%X", b)
} | 128The ISAAC Cipher
| 0go
| mtryi |
package main
import (
"fmt"
"math"
"math/big"
"reflect"
"strings"
"unsafe"
) | 129Test integerness
| 0go
| g2a4n |
object DataMunging2 {
import scala.io.Source
import scala.collection.immutable.{TreeMap => Map}
val pattern = """^(\d+-\d+-\d+)""" + """\s+(\d+\.\d+)\s+(-?\d+)""" * 24 + "$" r;
def main(args: Array[String]) {
val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead)
val (numFormatErrors, numValidRecords, dateMap) =
files.iterator.flatMap(file => Source fromFile file getLines ()).
foldLeft((0, 0, new Map[String, Int] withDefaultValue 0)) {
case ((nFE, nVR, dM), line) => pattern findFirstMatchIn line map (_.subgroups) match {
case Some(List(date, rawData @ _*)) =>
val allValid = (rawData map (_ toDouble) iterator) grouped 2 forall (_.last > 0)
(nFE, nVR + (if (allValid) 1 else 0), dM(date) += 1)
case None => (nFE + 1, nVR, dM)
}
}
dateMap foreach {
case (date, repetitions) if repetitions > 1 => println(date+": "+repetitions+" repetitions")
case _ =>
}
println("""|
|Valid records:%d
|Duplicated dates:%d
|Duplicated records:%d
|Data format errors:%d
|Invalid data records:%d
|Total records:%d""".stripMargin format (
numValidRecords,
dateMap filter { case (_, repetitions) => repetitions > 1 } size,
dateMap.valuesIterable filter (_ > 1) map (_ - 1) sum,
numFormatErrors,
dateMap.valuesIterable.sum - numValidRecords,
dateMap.valuesIterable.sum))
}
} | 124Text processing/2
| 16scala
| wb6es |
import time
print
print
for i in xrange(5, 0, -1):
print , i
time.sleep(1)
print | 131Terminal control/Preserve screen
| 3python
| u9hvd |
cat("\033[?1049h\033[H")
cat("Alternate screen buffer\n")
for (i in 5:1) {
cat("\rgoing back in ", i, "...", sep = "")
Sys.sleep(1)
cat("\33[2J")
}
cat("\033[?1049l") | 131Terminal control/Preserve screen
| 13r
| c3g95 |
use strict;
use warnings;
use Curses;
initscr or die;
my $win = Curses->new;
foreach my $row (0..9) {
$win->addstr( $row , 0, join('', map { chr(int(rand(50)) + 41) } (0..9)))
};
my $icol = 3 - 1;
my $irow = 6 - 1;
my $ch = $win->inch($irow,$icol);
$win->addstr( $irow, $icol+10, 'Character at column 3, row 6 = '.$ch );
$win->addstr( LINES() - 2, 2, "Press any key to exit..." );
$win->getch;
endwin; | 132Terminal control/Positional read
| 2perl
| 2yrlf |
import Data.Array (Array, (!), (//), array, elems)
import Data.Word (Word, Word32)
import Data.Bits (shift, xor)
import Data.Char (toUpper)
import Data.List (unfoldr)
import Numeric (showHex)
type IArray = Array Word32 Word32
data IsaacState = IState
{ randrsl :: IArray
, randcnt :: Word32
, mm :: IArray
, aa :: Word32
, bb :: Word32
, cc :: Word32
}
instance Show IsaacState where
show (IState _ cnt _ a b c) =
show cnt ++ " " ++ show a ++ " " ++ show b ++ " " ++ show c
toHex :: Char -> String
toHex c = showHex (fromEnum c) ""
hexify :: String -> String
hexify = map toUpper . concatMap toHex
toNum :: Char -> Word32
toNum = fromIntegral . fromEnum
toChar :: Word32 -> Char
toChar = toEnum . fromIntegral
golden :: Word32
golden = 0x9e3779b9
mix :: [Word32] -> [Word32]
mix set = foldl aux set [11, -2, 8, -16, 10, -4, 8, -9]
where
aux [a, b, c, d, e, f, g, h] x = [b + c, c, d + a_, e, f, g, h, a_]
where
a_ = a `xor` (b `shift` x)
isaac :: IsaacState -> IsaacState
isaac (IState rsl _ m a b c) = IState rsl_ 0 m_ a_ b_ c_
where
c_ = c + 1
(rsl_, m_, a_, b_) =
foldl aux (rsl, m, a, b) $ zip [0 .. 255] $ cycle [13, -6, 2, -16]
aux (rsl, m, a, b) (i, s) = (rsl_, m_, a_, b_)
where
x = m ! i
a_ = (a `xor` (a `shift` s)) + m ! ((i + 128) `mod` 256)
y = a_ + b + m ! ((x `shift` (-2)) `mod` 256)
m_ = m // [(i, y)]
b_ = x + m_ ! ((y `shift` (-10)) `mod` 256)
rsl_ = rsl // [(i, b_)]
randinit :: IsaacState -> Bool -> IsaacState
randinit state flag = isaac (IState randrsl_ 0 m 0 0 0)
where
firstSet = iterate mix (replicate 8 golden) !! 4
iter _ _ [] = []
iter flag set rsl =
let (rslH, rslT) = splitAt 8 rsl
set_ =
mix $
if flag
then zipWith (+) set rslH
else set
in set_ ++ iter flag set_ rslT
randrsl_ = randrsl state
firstPass = iter flag firstSet $ elems randrsl_
set_ = drop (256 - 8) firstPass
secondPass =
if flag
then iter True set_ firstPass
else firstPass
m = array (0, 255) $ zip [0 ..] secondPass
seed :: String -> Bool -> IsaacState
seed key flag =
let m = array (0, 255) $ zip [0 .. 255] $ repeat 0
rsl = m // zip [0 ..] (map toNum key)
state = IState rsl 0 m 0 0 0
in randinit state flag
random :: IsaacState -> (Word32, IsaacState)
random state@(IState rsl cnt m a b c) =
let r = rsl ! cnt
state_ =
if cnt + 1 > 255
then isaac $ IState rsl 0 m a b c
else IState rsl (cnt + 1) m a b c
in (r, state_)
randoms :: IsaacState -> [Word32]
randoms = unfoldr $ Just . random
randA :: IsaacState -> (Char, IsaacState)
randA state =
let (r, state_) = random state
in (toEnum $ fromIntegral $ (r `mod` 95) + 32, state_)
randAs :: IsaacState -> String
randAs = unfoldr $ Just . randA
vernam :: IsaacState -> String -> String
vernam state msg = map toChar $ zipWith xor msg_ randAs_
where
msg_ = map toNum msg
randAs_ = map toNum $ randAs state
main :: IO ()
main = do
let msg = "a Top Secret secret"
key = "this is my secret key"
st = seed key True
ver = vernam st msg
unver = vernam st ver
putStrLn $ "Message: " ++ msg
putStrLn $ "Key : " ++ key
putStrLn $ "XOR : " ++ hexify ver
putStrLn $ "XOR dcr: " ++ unver | 128The ISAAC Cipher
| 8haskell
| kg0h0 |
import Data.Decimal
import Data.Ratio
import Data.Complex | 129Test integerness
| 8haskell
| sazqk |
print "\a"; | 127Terminal control/Ringing the terminal bell
| 2perl
| p7ib0 |
use std::io::{stdout, Write};
use std::time::Duration;
fn main() {
let mut output = stdout();
print!("\x1b[?1049h\x1b[H");
println!("Alternate screen buffer");
for i in (1..=5).rev() {
print!("\rgoing back in {}...", i);
output.flush().unwrap();
std::thread::sleep(Duration::from_secs(1));
}
print!("\x1b[?1049l");
} | 131Terminal control/Preserve screen
| 15rust
| g2p4o |
int
main ()
{
printf
();
napms (5000);
curs_set (0);
printf
();
napms (5000);
printf ();
return 0;
} | 133Terminal control/Hiding the cursor
| 5c
| 4lh5t |
int main()
{
printf();
return 0;
} | 134Terminal control/Inverse video
| 5c
| 5c7uk |
import curses
from random import randint
stdscr = curses.initscr()
for rows in range(10):
line = ''.join([chr(randint(41, 90)) for i in range(10)])
stdscr.addstr(line + '\n')
icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding=)
stdscr.move(irow, icol + 10)
stdscr.addstr('Character at column 3, row 6 = ' + ch + '\n')
stdscr.getch()
curses.endwin() | 132Terminal control/Positional read
| 3python
| vm729 |
import java.math.BigDecimal;
import java.util.List;
public class TestIntegerness {
private static boolean isLong(double d) {
return isLong(d, 0.0);
}
private static boolean isLong(double d, double tolerance) {
return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static boolean isBigInteger(BigDecimal bd) {
try {
bd.toBigIntegerExact();
return true;
} catch (ArithmeticException ex) {
return false;
}
}
private static class Rational {
long num;
long denom;
Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
boolean isLong() {
return num % denom == 0;
}
@Override
public String toString() {
return String.format("%s/%s", num, denom);
}
}
private static class Complex {
double real;
double imag;
Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
boolean isLong() {
return TestIntegerness.isLong(real) && imag == 0.0;
}
@Override
public String toString() {
if (imag >= 0.0) {
return String.format("%s +%si", real, imag);
}
return String.format("%s -%si", real, imag);
}
}
public static void main(String[] args) {
List<Double> da = List.of(25.000000, 24.999999, 25.000100);
for (Double d : da) {
boolean exact = isLong(d);
System.out.printf("%.6f is%s integer%n", d, exact ? "an" : "not an");
}
System.out.println();
double tolerance = 0.00001;
System.out.printf("With a tolerance of%.5f:%n", tolerance);
for (Double d : da) {
boolean fuzzy = isLong(d, tolerance);
System.out.printf("%.6f is%s integer%n", d, fuzzy ? "an" : "not an");
}
System.out.println();
List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
for (Double f : fa) {
boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
System.out.printf("%s is%s integer%n", f, exact ? "an" : "not an");
}
System.out.println();
List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
for (Complex c : ca) {
boolean exact = c.isLong();
System.out.printf("%s is%s integer%n", c, exact ? "an" : "not an");
}
System.out.println();
List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
for (Rational r : ra) {
boolean exact = r.isLong();
System.out.printf("%s is%s integer%n", r, exact ? "an" : "not an");
}
}
} | 129Test integerness
| 9java
| 1jop2 |
package pal
import "testing"
func TestPals(t *testing.T) {
pals := []string{
"",
".",
"11",
"ere",
"ingirumimusnocteetconsumimurigni",
}
for _, s := range pals {
if !IsPal(s) {
t.Error("IsPal returned false on palindrome,", s)
}
}
}
func TestNonPals(t *testing.T) {
nps := []string{
"no",
"odd",
"sallas",
}
for _, s := range nps {
if IsPal(s) {
t.Error("IsPal returned true on non-palindrome,", s)
}
}
} | 130Test a function
| 0go
| satqa |
<?php
echo ; | 127Terminal control/Ringing the terminal bell
| 12php
| yfr61 |
print("\033[?1049h\033[H")
println("Alternate buffer!")
for (i <- 5 to 0 by -1) {
println(s"Going back in: $i")
Thread.sleep(1000)
}
print("\033[?1049l") | 131Terminal control/Preserve screen
| 16scala
| j5e7i |
public let CSI = ESC+"[" | 131Terminal control/Preserve screen
| 17swift
| 5cku8 |
package main
import (
"os"
"os/exec"
"time"
)
func main() {
tput("civis") | 133Terminal control/Hiding the cursor
| 0go
| oxt8q |
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
tput("rev")
fmt.Print("Rosetta")
tput("sgr0")
fmt.Println(" Code")
}
func tput(arg string) error {
cmd := exec.Command("tput", arg)
cmd.Stdout = os.Stdout
return cmd.Run()
} | 134Terminal control/Inverse video
| 0go
| 8wd0g |
int
main()
{
puts();
puts();
return 0;
} | 135Terminal control/Display an extended character
| 5c
| q18xc |
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
public class IsaacRandom extends Random {
private static final long serialVersionUID = 1L;
private final int[] randResult = new int[256]; | 128The ISAAC Cipher
| 9java
| 4la58 |
import Test.QuickCheck
isPalindrome :: String -> Bool
isPalindrome x = x == reverse x
instance Arbitrary Char where
arbitrary = choose ('\32', '\127')
main = do
putStr "Even palindromes: " >> quickCheck (\s -> isPalindrome (s ++ reverse s))
putStr "Odd palindromes: " >> quickCheck (\s -> not (null s) ==> isPalindrome (s ++ (tail.reverse) s))
putStr "Non-palindromes: " >> quickCheck (\i s -> not (null s) && 0 <= i && i < length s && i*2 /= length s
==> not (isPalindrome (take i s ++ "" ++ drop i s))) | 130Test a function
| 8haskell
| 9zgmo |
null | 133Terminal control/Hiding the cursor
| 11kotlin
| d06nz |
null | 134Terminal control/Inverse video
| 11kotlin
| nszij |
(println "") | 135Terminal control/Display an extended character
| 6clojure
| iqfom |
null | 129Test integerness
| 11kotlin
| j5x7r |
use strict;
my $out = 0;
my $max_out = -1;
my @max_times;
open FH, '<mlijobs.txt' or die "Can't open file: $!";
while (<FH>) {
chomp;
if (/OUT/) {
$out++;
} else {
$out--;
}
if ($out > $max_out) {
$max_out = $out;
@max_times = ();
}
if ($out == $max_out) {
push @max_times, (split)[3];
}
}
close FH;
print "Maximum simultaneous license use is $max_out at the following times:\n";
print " $_\n" foreach @max_times; | 125Text processing/Max licenses in use
| 2perl
| 4lx5d |
import static ExampleClass.pali; | 130Test a function
| 9java
| tolf9 |
print | 127Terminal control/Ringing the terminal bell
| 3python
| 1jnpc |
alarm() | 127Terminal control/Ringing the terminal bell
| 13r
| h40jj |
print "\e[?25l";
print "Enter anything, press RETURN: ";
$input = <>;
print "\e[0H\e[0J\e[?25h"; | 133Terminal control/Hiding the cursor
| 2perl
| j517f |
print "normal\n";
system "tput rev";
print "reversed\n";
system "tput sgr0";
print "normal\n"; | 134Terminal control/Inverse video
| 2perl
| 7ubrh |
static int badHrs, maxBadHrs;
static double hrsTot = 0.0;
static int rdgsTot = 0;
char bhEndDate[40];
int mungeLine( char *line, int lno, FILE *fout )
{
char date[40], *tkn;
int dHrs, flag, hrs2, hrs;
double hrsSum;
int hrsCnt = 0;
double avg;
tkn = strtok(line, );
if (tkn) {
int n = sscanf(tkn, , &date, &hrs2);
if (n<2) {
printf(, lno, tkn);
return 0;
}
hrsSum = 0.0;
while( tkn= strtok(NULL, )) {
n = sscanf(tkn,, &dHrs, &flag, &hrs);
if (n>=2) {
if (flag > 0) {
hrsSum += 1.0*hrs2 + .001*dHrs;
hrsCnt += 1;
if (maxBadHrs < badHrs) {
maxBadHrs = badHrs;
strcpy(bhEndDate, date);
}
badHrs = 0;
}
else {
badHrs += 1;
}
hrs2 = hrs;
}
else {
printf(,lno, tkn);
}
}
avg = (hrsCnt > 0)? hrsSum/hrsCnt : 0.0;
fprintf(fout, ,
date, 24-hrsCnt, hrsCnt, hrsSum/hrsCnt);
hrsTot += hrsSum;
rdgsTot += hrsCnt;
}
return 1;
}
int main()
{
FILE *infile, *outfile;
int lineNo = 0;
char line[512];
const char *ifilename = ;
outfile = fopen(, );
infile = fopen(ifilename, );
if (!infile) {
printf(, ifilename);
exit(1);
}
while (NULL != fgets(line, 512, infile)) {
lineNo += 1;
if (0 == mungeLine(line, lineNo, outfile))
printf(,lineNo);
}
fclose(infile);
fprintf(outfile, , ifilename);
fprintf(outfile, , hrsTot);
fprintf(outfile, , rdgsTot);
fprintf(outfile, , hrsTot/rdgsTot);
fprintf(outfile, , maxBadHrs);
fprintf(outfile, , bhEndDate);
fclose(outfile);
return 0;
} | 136Text processing/1
| 5c
| 3nyza |
null | 128The ISAAC Cipher
| 11kotlin
| l6hcp |
function isInt (x) return type(x) == "number" and x == math.floor(x) end
print("Value\tInteger?")
print("=====\t========")
local testCases = {2, 0, -1, 3.5, "String!", true}
for _, input in pairs(testCases) do print(input, isInt(input)) end | 129Test integerness
| 1lua
| h4qj8 |
const assert = require('assert');
describe('palindrome', () => {
const pali = require('../lib/palindrome');
describe('.check()', () => {
it('should return true on encountering a palindrome', () => {
assert.ok(pali.check('racecar'));
assert.ok(pali.check('abcba'));
assert.ok(pali.check('aa'));
assert.ok(pali.check('a'));
});
it('should return true on encountering an empty string', () => {
assert.ok(pali.check(''));
});
it('should return false on encountering a non-palindrome', () => {
assert.ok(!pali.check('alice'));
assert.ok(!pali.check('ab'));
assert.ok(!pali.check('abcdba'));
});
})
}); | 130Test a function
| 10javascript
| mt4yv |
print()
print() | 133Terminal control/Hiding the cursor
| 3python
| h4ajw |
cat("\x1b[?25l")
Sys.sleep(2)
cat("\x1b[?25h") | 133Terminal control/Hiding the cursor
| 13r
| g2k47 |
print | 134Terminal control/Inverse video
| 3python
| j5p7p |
int
main()
{
struct winsize ws;
int fd;
fd = open(, O_RDWR);
if (fd < 0)
err(1, );
if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
err(1, );
printf(, ws.ws_row, ws.ws_col);
printf(, ws.ws_xpixel, ws.ws_ypixel);
close(fd);
return 0;
} | 137Terminal control/Dimensions
| 5c
| rv7g7 |
package main
import "fmt"
func main() {
fmt.Println("")
} | 135Terminal control/Display an extended character
| 0go
| 2y5l7 |
module Main where
main = do
putStrLn ""
putStrLn "" | 135Terminal control/Display an extended character
| 8haskell
| ahx1g |
#!/usr/bin/env lua | 128The ISAAC Cipher
| 1lua
| 2ykl3 |
$handle = fopen (, );
$maxcount = 0;
$count = 0;
$times = array();
while (!feof($handle)) {
$buffer = fgets($handle);
$op = trim(substr($buffer,8,3));
switch ($op){
case 'IN':
$count--;
break;
case 'OUT':
$count++;
preg_match('/([\d|\/|_|:]+)/',$buffer,$time);
if($count>$maxcount){
$maxcount = $count;
$times = Array($time[0]);
}elseif($count == $maxcount){
$times[] = $time[0];
}
break;
}
}
fclose ($handle);
echo $maxcount . '<br>';
for($i=0;$i<count($times);$i++){
echo $times[$i] . '<br>';
} | 125Text processing/Max licenses in use
| 12php
| iq2ov |
print | 127Terminal control/Ringing the terminal bell
| 14ruby
| ekfax |
fn main() {
print!("\x07");
} | 127Terminal control/Ringing the terminal bell
| 15rust
| wbte4 |
java.awt.Toolkit.getDefaultToolkit().beep() | 127Terminal control/Ringing the terminal bell
| 16scala
| sa6qo |
require
include Curses
init_screen
begin
curs_set(1)
sleep 3
curs_set(0)
sleep 3
curs_set(1)
sleep 3
ensure
close_screen
end | 133Terminal control/Hiding the cursor
| 14ruby
| brwkq |
object Main extends App {
print("\u001B[?25l") | 133Terminal control/Hiding the cursor
| 16scala
| ek0ab |
puts | 134Terminal control/Inverse video
| 14ruby
| kgahg |
object Main extends App {
println("\u001B[7mInverse\u001B[m Normal")
} | 134Terminal control/Inverse video
| 16scala
| ahq1n |
typedef enum {
TRITTRUE,
TRITMAYBE,
TRITFALSE
} trit;
trit tritNot[3] = {TRITFALSE , TRITMAYBE, TRITTRUE};
trit tritAnd[3][3] = { {TRITTRUE, TRITMAYBE, TRITFALSE},
{TRITMAYBE, TRITMAYBE, TRITFALSE},
{TRITFALSE, TRITFALSE, TRITFALSE} };
trit tritOr[3][3] = { {TRITTRUE, TRITTRUE, TRITTRUE},
{TRITTRUE, TRITMAYBE, TRITMAYBE},
{TRITTRUE, TRITMAYBE, TRITFALSE} };
trit tritThen[3][3] = { { TRITTRUE, TRITMAYBE, TRITFALSE},
{ TRITTRUE, TRITMAYBE, TRITMAYBE},
{ TRITTRUE, TRITTRUE, TRITTRUE } };
trit tritEquiv[3][3] = { { TRITTRUE, TRITMAYBE, TRITFALSE},
{ TRITMAYBE, TRITMAYBE, TRITMAYBE},
{ TRITFALSE, TRITMAYBE, TRITTRUE } };
const char* tritString[3] = {, , };
void demo_binary_op(trit operator[3][3], const char* name)
{
trit operand1 = TRITTRUE;
trit operand2 = TRITTRUE;
printf();
for( operand1 = TRITTRUE; operand1 <= TRITFALSE; ++operand1 )
{
for( operand2 = TRITTRUE; operand2 <= TRITFALSE; ++operand2 )
{
printf(, tritString[operand1],
name,
tritString[operand2],
tritString[operator[operand1][operand2]]);
}
}
}
int main()
{
trit op1 = TRITTRUE;
trit op2 = TRITTRUE;
for( op1 = TRITTRUE; op1 <= TRITFALSE; ++op1 )
{
printf(, tritString[op1], tritString[tritNot[op1]]);
}
demo_binary_op(tritAnd, );
demo_binary_op(tritOr, );
demo_binary_op(tritThen, );
demo_binary_op(tritEquiv, );
return 0;
} | 138Ternary logic
| 5c
| 8w804 |
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
PrintStream writer = new PrintStream(System.out, true, "UTF-8");
writer.println("");
writer.println("");
}
} | 135Terminal control/Display an extended character
| 9java
| j5b7c |
null | 135Terminal control/Display an extended character
| 11kotlin
| 5crua |
(ns rosettacode.textprocessing1
(:require [clojure.string:as str]))
(defn parse-line [s]
(let [[date & data-toks] (str/split s #"\s+")]
{:date date
:hour-vals (for [[v flag] (partition 2 data-toks)]
{:val (Double. v)
:flag (Long. flag)})}))
(defn analyze-line [m]
(let [valid? (fn [rec] (pos? (:flag rec)))
data (->> (filter valid? (:hour-vals m))
(map:val))
n-vals (count data)
sum (reduce + data)]
{:date (:date m)
:n-vals n-vals
:sum (double sum)
:avg (if (zero? n-vals) 0.0 (/ sum n-vals))
:gaps (for [hr (:hour-vals m)]
{:gap? (not (valid? hr)):date (:date m)})}))
(defn print-line [m]
(println (format "%s:%d valid, sum:%7.3f, mean:%6.3f"
(:date m)
(:n-vals m)
(:sum m)
(:avg m))))
(defn process-line [s]
(let [m (parse-line s)
line-info (analyze-line m)]
(print-line line-info)
line-info))
(defn update-file-stats [file-m line-m]
(let [append (fn [a b] (reduce conj a b))]
(-> file-m
(update-in [:sum] + (:sum line-m))
(update-in [:n-vals] + (:n-vals line-m))
(update-in [:gap-recs] append (:gaps line-m)))))
(defn process-file [path]
(let [file-lines (->> (slurp path)
str/split-lines)
summary (reduce (fn [res line]
(update-file-stats res (process-line line)))
{:sum 0
:n-vals 0
:gap-recs []}
file-lines)
max-gap (->> (partition-by:gap? (:gap-recs summary))
(filter #(:gap? (first %)))
(sort-by count >)
first)]
(println (format "Sum:%f\n# Values:%d\nAvg:%f"
(:sum summary)
(:n-vals summary)
(/ (:sum summary) (:n-vals summary))))
(println (format "Max gap of%d recs started on%s"
(count max-gap)
(:date (first max-gap)))))) | 136Text processing/1
| 6clojure
| c329b |
use Math::Complex;
sub is_int {
my $number = shift;
if (ref $number eq 'Math::Complex') {
return 0 if $number->Im != 0;
$number = $number->Re;
}
return int($number) == $number;
}
for (5, 4.1, sqrt(2), sqrt(4), 1.1e10, 3.0-0.0*i, 4-3*i, 5.6+0*i) {
printf "%20s is%s an integer\n", $_, (is_int($_) ? "" : " NOT");
} | 129Test integerness
| 2perl
| to2fg |
null | 130Test a function
| 11kotlin
| ox68z |
int main()
{
int i,j;
char days[12][10] =
{
,
,
,
,
,
,
,
,
,
,
,
};
char gifts[12][33] =
{
,
,
,
,
,
,
,
,
,
,
,
};
for(i=0;i<12;i++)
{
printf(,days[i]);
for(j=i;j>=0;j--)
{
(i==0)?printf():printf(,gifts[11-j],(j!=0)?',':' ');
}
}
return 0;
} | 139The Twelve Days of Christmas
| 5c
| s1xq5 |
print(string.char(156)) | 135Terminal control/Display an extended character
| 1lua
| 4l75c |
assert( ispalindrome("ABCBA") )
assert( ispalindrome("ABCDE") ) | 130Test a function
| 1lua
| iqyot |
package main
import (
"fmt"
"os"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
w, h, err := terminal.GetSize(int(os.Stdout.Fd()))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(h, w)
} | 137Terminal control/Dimensions
| 0go
| nsdi1 |
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
)
func main() {
cmd := exec.Command("tput", "-S")
cmd.Stdin = bytes.NewBufferString("clear\ncup 5 2")
cmd.Stdout = os.Stdout
cmd.Run()
fmt.Println("Hello")
} | 140Terminal control/Cursor positioning
| 0go
| 4cv52 |
use feature 'say';
say '';
binmode STDOUT, ":utf8";
say "\N{FULLWIDTH POUND SIGN}";
say "\x{FFE1}";
say chr 0xffe1; | 135Terminal control/Display an extended character
| 2perl
| oxd8x |
null | 137Terminal control/Dimensions
| 11kotlin
| tozf0 |
null | 140Terminal control/Cursor positioning
| 11kotlin
| 7v4r4 |
print u'\u00a3' | 135Terminal control/Display an extended character
| 3python
| iqfof |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.