code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
extern crate rand;
use rand::{OsRng, Rng};
fn main() { | 376Random number generator (device)
| 15rust
| 1v0pu |
use std::f64;
const _EPS: f64 = 0.00001;
const _MIN: f64 = f64::MIN_POSITIVE;
const _MAX: f64 = f64::MAX;
#[derive(Clone)]
struct Point {
x: f64,
y: f64,
}
#[derive(Clone)]
struct Edge {
pt1: Point,
pt2: Point,
}
impl Edge {
fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge {
Edge {
pt1: Point { x: pt1.0, y: pt1.1 },
pt2: Point { x: pt2.0, y: pt2.1 },
}
}
}
struct Polygon {
edges: Vec<Edge>, | 370Ray-casting algorithm
| 15rust
| 98kmm |
(def q (make-queue))
(enqueue q 1)
(enqueue q 2)
(enqueue q 3)
(dequeue q)
(dequeue q)
(dequeue q)
(queue-empty? q) | 388Queue/Usage
| 6clojure
| c8z9b |
from __future__ import print_function
from shapely.geometry import LineString
if __name__==:
line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)])
print (line.simplify(1.0, preserve_topology=False)) | 377Ramer-Douglas-Peucker line simplification
| 3python
| g3b4h |
seed(x) = mod(950706376 * seed(x-1), 2147483647)
random(x) = seed(x) / 2147483647 | 381Random number generator (included)
| 2perl
| te3fg |
import java.security.SecureRandom
object RandomExample extends App {
new SecureRandom {
val newSeed: Long = this.nextInt().toLong * this.nextInt()
this.setSeed(newSeed) | 376Random number generator (device)
| 16scala
| w4ies |
from random import choice, shuffle
from copy import deepcopy
def rls(n):
if n <= 0:
return []
else:
symbols = list(range(n))
square = _rls(symbols)
return _shuffle_transpose_shuffle(square)
def _shuffle_transpose_shuffle(matrix):
square = deepcopy(matrix)
shuffle(square)
trans = list(zip(*square))
shuffle(trans)
return trans
def _rls(symbols):
n = len(symbols)
if n == 1:
return [symbols]
else:
sym = choice(symbols)
symbols.remove(sym)
square = _rls(symbols)
square.append(square[0].copy())
for i in range(n):
square[i].insert(i, sym)
return square
def _to_text(square):
if square:
width = max(len(str(sym)) for row in square for sym in row)
txt = '\n'.join(' '.join(f for sym in row)
for row in square)
else:
txt = ''
return txt
def _check(square):
transpose = list(zip(*square))
assert _check_rows(square) and _check_rows(transpose), \
def _check_rows(square):
if not square:
return True
set_row0 = set(square[0])
return all(len(row) == len(set(row)) and set(row) == set_row0
for row in square)
if __name__ == '__main__':
for i in [3, 3, 5, 5, 12]:
square = rls(i)
print(_to_text(square))
_check(square)
print() | 382Random Latin squares
| 3python
| r67gq |
package scala.ray_casting
case class Edge(_1: (Double, Double), _2: (Double, Double)) {
import Math._
import Double._
def raySegI(p: (Double, Double)): Boolean = {
if (_1._2 > _2._2) return Edge(_2, _1).raySegI(p)
if (p._2 == _1._2 || p._2 == _2._2) return raySegI((p._1, p._2 + epsilon))
if (p._2 > _2._2 || p._2 < _1._2 || p._1 > max(_1._1, _2._1))
return false
if (p._1 < min(_1._1, _2._1)) return true
val blue = if (abs(_1._1 - p._1) > MinValue) (p._2 - _1._2) / (p._1 - _1._1) else MaxValue
val red = if (abs(_1._1 - _2._1) > MinValue) (_2._2 - _1._2) / (_2._1 - _1._1) else MaxValue
blue >= red
}
final val epsilon = 0.00001
}
case class Figure(name: String, edges: Seq[Edge]) {
def contains(p: (Double, Double)) = edges.count(_.raySegI(p)) % 2 != 0
}
object Ray_casting extends App {
val figures = Seq(Figure("Square", Seq(((0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)),
((10.0, 10.0), (0.0, 10.0)),((0.0, 10.0), (0.0, 0.0)))),
Figure("Square hole", Seq(((0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)),
((10.0, 10.0), (0.0, 10.0)), ((0.0, 10.0), (0.0, 0.0)), ((2.5, 2.5), (7.5, 2.5)),
((7.5, 2.5), (7.5, 7.5)),((7.5, 7.5), (2.5, 7.5)), ((2.5, 7.5), (2.5, 2.5)))),
Figure("Strange", Seq(((0.0, 0.0), (2.5, 2.5)), ((2.5, 2.5), (0.0, 10.0)),
((0.0, 10.0), (2.5, 7.5)), ((2.5, 7.5), (7.5, 7.5)), ((7.5, 7.5), (10.0, 10.0)),
((10.0, 10.0), (10.0, 0.0)), ((10.0, 0.0), (2.5, 2.5)))),
Figure("Exagon", Seq(((3.0, 0.0), (7.0, 0.0)), ((7.0, 0.0), (10.0, 5.0)), ((10.0, 5.0), (7.0, 10.0)),
((7.0, 10.0), (3.0, 10.0)), ((3.0, 10.0), (0.0, 5.0)), ((0.0, 5.0), (3.0, 0.0)))))
val points = Seq((5.0, 5.0), (5.0, 8.0), (-10.0, 5.0), (0.0, 5.0), (10.0, 5.0), (8.0, 5.0), (10.0, 10.0))
println("points: " + points)
for (f <- figures) {
println("figure: " + f.name)
println(" " + f.edges)
println("result: " + (points map f.contains))
}
private implicit def to_edge(p: ((Double, Double), (Double, Double))): Edge = Edge(p._1, p._2)
} | 370Ray-casting algorithm
| 16scala
| 2n1lb |
seed(x) = mod(950706376 * seed(x-1), 2147483647)
random(x) = seed(x) / 2147483647 | 381Random number generator (included)
| 12php
| kcphv |
typedef unsigned long long u8;
typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;
u8 ranval( ranctx *x ) {
u8 e = x->a - rot(x->b, 7);
x->a = x->b ^ rot(x->c, 13);
x->b = x->c + rot(x->d, 37);
x->c = x->d + e;
x->d = e + x->a;
return x->d;
}
void raninit( ranctx *x, u8 seed ) {
u8 i;
x->a = 0xf1ea5eed, x->b = x->c = x->d = seed;
for (i=0; i<20; ++i) {
(void)ranval(x);
}
} | 381Random number generator (included)
| 3python
| zw6tt |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConfigReader {
private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" );
private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{
put( "needspeeling", false );
put( "seedsremoved", false );
}};
public static void main( final String[] args ) {
System.out.println( parseFile( args[ 0 ] ) );
}
public static Map<String, Object> parseFile( final String fileName ) {
final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader( fileName ) );
for ( String line; null != ( line = reader.readLine() ); ) {
parseLine( line, result );
}
} catch ( final IOException x ) {
throw new RuntimeException( "Oops: " + x, x );
} finally {
if ( null != reader ) try {
reader.close();
} catch ( final IOException x2 ) {
System.err.println( "Could not close " + fileName + " - " + x2 );
}
}
return result;
}
private static void parseLine( final String line, final Map<String, Object> map ) {
if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) )
return;
final Matcher matcher = LINE_PATTERN.matcher( line );
if ( ! matcher.matches() ) {
System.err.println( "Bad config line: " + line );
return;
}
final String key = matcher.group( 1 ).trim().toLowerCase();
final String value = matcher.group( 2 ).trim();
if ( "".equals( value ) ) {
map.put( key, true );
} else if ( -1 == value.indexOf( ',' ) ) {
map.put( key, value );
} else {
final String[] values = value.split( "," );
for ( int i = 0; i < values.length; i++ ) {
values[ i ] = values[ i ].trim();
}
map.put( key, Arrays.asList( values ) );
}
}
} | 374Read a configuration file
| 9java
| te2f9 |
ar = .lines.map{|line| line.split}
grouped = ar.group_by{|pair| pair.shift.to_i}
s_rnk = 1
m_rnk = o_rnk = 0
puts
grouped.each.with_index(1) do |(score, names), d_rnk|
m_rnk += names.flatten!.size
f_rnk = (s_rnk + m_rnk)/2.0
names.each do |name|
o_rnk += 1
puts .0
end
s_rnk += names.size
end | 371Ranking methods
| 14ruby
| okc8v |
strrev($string); | 366Reverse a string
| 12php
| ok585 |
mapfile < $0
printf "%s" "${MAPFILE[@]}" | 389Quine
| 4bash
| 4t95j |
#[derive(Copy, Clone)]
struct Point {
x: f64,
y: f64,
}
use std::fmt;
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
} | 377Ramer-Douglas-Peucker line simplification
| 15rust
| jma72 |
package main
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
const mean = 1.0
const stdv = .5
const n = 1000
func main() {
var list [n]float64
rand.Seed(time.Now().UnixNano())
for i := range list {
list[i] = mean + stdv*rand.NormFloat64()
} | 379Random numbers
| 0go
| fa6d0 |
?RNG
help.search("Distribution", package="stats") | 381Random number generator (included)
| 13r
| npfi2 |
function parseConfig(config) { | 374Read a configuration file
| 10javascript
| m0gyv |
object RankingMethods extends App {
case class Score(score: Int, name: String) | 371Ranking methods
| 16scala
| faud4 |
N = 5
def generate_square
perms = (1..N).to_a.permutation(N).to_a.shuffle
square = []
N.times do
square << perms.pop
perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} }
end
square
end
def print_square(square)
cell_size = N.digits.size + 1
strings = square.map!{|row| row.map!{|el| el.to_s.rjust(cell_size)}.join }
puts strings,
end
2.times{print_square( generate_square)} | 382Random Latin squares
| 14ruby
| jmh7x |
typedef struct quaternion
{
double q[4];
} quaternion_t;
quaternion_t *quaternion_new(void)
{
return malloc(sizeof(quaternion_t));
}
quaternion_t *quaternion_new_set(double q1,
double q2,
double q3,
double q4)
{
quaternion_t *q = malloc(sizeof(quaternion_t));
if (q != NULL) {
q->q[0] = q1; q->q[1] = q2; q->q[2] = q3; q->q[3] = q4;
}
return q;
}
void quaternion_copy(quaternion_t *r, quaternion_t *q)
{
size_t i;
if (r == NULL || q == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = q->q[i];
}
double quaternion_norm(quaternion_t *q)
{
size_t i;
double r = 0.0;
if (q == NULL) {
fprintf(stderr, );
return 0.0;
}
for(i = 0; i < 4; i++) r += q->q[i] * q->q[i];
return sqrt(r);
}
void quaternion_neg(quaternion_t *r, quaternion_t *q)
{
size_t i;
if (q == NULL || r == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = -q->q[i];
}
void quaternion_conj(quaternion_t *r, quaternion_t *q)
{
size_t i;
if (q == NULL || r == NULL) return;
r->q[0] = q->q[0];
for(i = 1; i < 4; i++) r->q[i] = -q->q[i];
}
void quaternion_add_d(quaternion_t *r, quaternion_t *q, double d)
{
if (q == NULL || r == NULL) return;
quaternion_copy(r, q);
r->q[0] += d;
}
void quaternion_add(quaternion_t *r, quaternion_t *a, quaternion_t *b)
{
size_t i;
if (r == NULL || a == NULL || b == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = a->q[i] + b->q[i];
}
void quaternion_mul_d(quaternion_t *r, quaternion_t *q, double d)
{
size_t i;
if (r == NULL || q == NULL) return;
for(i = 0; i < 4; i++) r->q[i] = q->q[i] * d;
}
bool quaternion_equal(quaternion_t *a, quaternion_t *b)
{
size_t i;
for(i = 0; i < 4; i++) if (a->q[i] != b->q[i]) return false;
return true;
}
void quaternion_mul(quaternion_t *r, quaternion_t *a, quaternion_t *b)
{
size_t i;
double ri = 0.0;
if (r == NULL || a == NULL || b == NULL) return;
R(0) = A(0)*B(0) - A(1)*B(1) - A(2)*B(2) - A(3)*B(3);
R(1) = A(0)*B(1) + A(1)*B(0) + A(2)*B(3) - A(3)*B(2);
R(2) = A(0)*B(2) - A(1)*B(3) + A(2)*B(0) + A(3)*B(1);
R(3) = A(0)*B(3) + A(1)*B(2) - A(2)*B(1) + A(3)*B(0);
}
void quaternion_print(quaternion_t *q)
{
if (q == NULL) return;
printf(,
q->q[0], q->q[1], q->q[2], q->q[3]);
} | 390Quaternion type
| 5c
| 8j104 |
struct Point: CustomStringConvertible {
let x: Double, y: Double
var description: String {
return "(\(x), \(y))"
}
} | 377Ramer-Douglas-Peucker line simplification
| 17swift
| r6pgg |
rnd = new Random()
result = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() } | 379Random numbers
| 7groovy
| 8hd0b |
import System.Random
pairs :: [a] -> [(a,a)]
pairs (x:y:zs) = (x,y):pairs zs
pairs _ = []
gauss mu sigma (r1,r2) =
mu + sigma * sqrt (-2 * log r1) * cos (2 * pi * r2)
gaussians :: (RandomGen g, Random a, Floating a) => Int -> g -> [a]
gaussians n g = take n $ map (gauss 1.0 0.5) $ pairs $ randoms g
result :: IO [Double]
result = getStdGen >>= \g -> return $ gaussians 1000 g | 379Random numbers
| 8haskell
| 4zj5s |
rmd(0) | 381Random number generator (included)
| 14ruby
| 6qm3t |
import scala.util.Random
object Throws extends App {
Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2)
.take(200).groupBy(identity).toList.sortBy(_._1)
.foreach {
case (a, b) => println(f"$a%2d:" + "X" * b.size)
}
} | 381Random number generator (included)
| 15rust
| ys968 |
import scala.util.Random
object Throws extends App {
Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2)
.take(200).groupBy(identity).toList.sortBy(_._1)
.foreach {
case (a, b) => println(f"$a%2d:" + "X" * b.size)
}
} | 381Random number generator (included)
| 16scala
| co293 |
package main
import (
"fmt"
"strconv"
"strings"
)
const input = "-6,-3--1,3-5,7-11,14,15,17-20"
func main() {
fmt.Println("range:", input)
var r []int
var last int
for _, part := range strings.Split(input, ",") {
if i := strings.Index(part[1:], "-"); i == -1 {
n, err := strconv.Atoi(part)
if err != nil {
fmt.Println(err)
return
}
if len(r) > 0 {
if last == n {
fmt.Println("duplicate value:", n)
return
} else if last > n {
fmt.Println("values not ordered:", last, ">", n)
return
}
}
r = append(r, n)
last = n
} else {
n1, err := strconv.Atoi(part[:i+1])
if err != nil {
fmt.Println(err)
return
}
n2, err := strconv.Atoi(part[i+2:])
if err != nil {
fmt.Println(err)
return
}
if n2 < n1+2 {
fmt.Println("invalid range:", part)
return
}
if len(r) > 0 {
if last == n1 {
fmt.Println("duplicate value:", n1)
return
} else if last > n1 {
fmt.Println("values not ordered:", last, ">", n1)
return
}
}
for i = n1; i <= n2; i++ {
r = append(r, i)
}
last = n2
}
}
fmt.Println("expanded:", r)
} | 385Range expansion
| 0go
| ohs8q |
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
data class Configuration(val map: Map<String, Any?>) {
val fullName: String by map
val favoriteFruit: String by map
val needsPeeling: Boolean by map
val otherFamily: List<String> by map
}
fun main(args: Array<String>) {
val lines = Files.readAllLines(Paths.get("src/configuration.txt"), StandardCharsets.UTF_8)
val keyValuePairs = lines.map{ it.trim() }
.filterNot { it.isEmpty() }
.filterNot(::commentedOut)
.map(::toKeyValuePair)
val configurationMap = hashMapOf<String, Any>("needsPeeling" to false)
for (pair in keyValuePairs) {
val (key, value) = pair
when (key) {
"FULLNAME" -> configurationMap.put("fullName", value)
"FAVOURITEFRUIT" -> configurationMap.put("favoriteFruit", value)
"NEEDSPEELING" -> configurationMap.put("needsPeeling", true)
"OTHERFAMILY" -> configurationMap.put("otherFamily", value.split(" , ").map { it.trim() })
else -> println("Encountered unexpected key $key=$value")
}
}
println(Configuration(configurationMap))
}
private fun commentedOut(line: String) = line.startsWith("#") || line.startsWith(";")
private fun toKeyValuePair(line: String) = line.split(Regex(" "), 2).let {
Pair(it[0], if (it.size == 1) "" else it[1])
} | 374Read a configuration file
| 11kotlin
| oky8z |
def expandRanges = { compressed ->
Eval.me('['+compressed.replaceAll(~/(\d)-/, '$1..')+']').flatten().toString()[1..-2]
} | 385Range expansion
| 7groovy
| x4awl |
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func init() {
log.SetFlags(log.Lshortfile)
}
func main() { | 383Read a file line by line
| 0go
| e5ea6 |
double[] list = new double[1000];
double mean = 1.0, std = 0.5;
Random rng = new Random();
for(int i = 0;i<list.length;i++) {
list[i] = mean + std * rng.nextGaussian();
} | 379Random numbers
| 9java
| cou9h |
function randomNormal() {
return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))
}
var a = []
for (var i=0; i < 1000; i++){
a[i] = randomNormal() / 2 + 1
} | 379Random numbers
| 10javascript
| 5t7ur |
> expandRange "-6,-3
[-6,-3,-2,-1,3,4,5,7,8,9,10,11,14,15,17,18,19,20] | 385Range expansion
| 8haskell
| 2i9ll |
new File("Test.txt").eachLine { line, lineNumber ->
println "processing line $lineNumber: $line"
} | 383Read a file line by line
| 7groovy
| kckh7 |
main = do
file <- readFile "linebyline.hs"
mapM_ putStrLn (lines file) | 383Read a file line by line
| 8haskell
| 3x3zj |
package main
import (
"fmt"
"queue"
)
func main() {
q := new(queue.Queue)
fmt.Println("empty?", q.Empty())
x := "black"
fmt.Println("push", x)
q.Push(x)
fmt.Println("empty?", q.Empty())
r, ok := q.Pop()
if ok {
fmt.Println(r, "popped")
} else {
fmt.Println("pop failed")
}
var n int
for _, x := range []string{"blue", "red", "green"} {
fmt.Println("pushing", x)
q.Push(x)
n++
}
for i := 0; i < n; i++ {
r, ok := q.Pop()
if ok {
fmt.Println(r, "popped")
} else {
fmt.Println("pop failed")
}
}
} | 388Queue/Usage
| 0go
| bcgkh |
typedef int DATA;
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->alloc) {
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) {
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
} | 391Queue/Definition
| 5c
| srkq5 |
def q = new LinkedList() | 388Queue/Usage
| 7groovy
| r32gh |
Prelude>:l fifo.hs
[1 of 1] Compiling Main ( fifo.hs, interpreted )
Ok, modules loaded: Main.
*Main> let q = emptyFifo
*Main> isEmpty q
True
*Main> let q' = push q 1
*Main> isEmpty q'
False
*Main> let q'' = foldl push q' [2..4]
*Main> let (v,q''') = pop q''
*Main> v
Just 1
*Main> let (v',q'''') = pop q'''
*Main> v'
Just 2
*Main> let (v'',q''''') = pop q''''
*Main> v''
Just 3
*Main> let (v''',q'''''') = pop q'''''
*Main> v'''
Just 4
*Main> let (v'''',q''''''') = pop q''''''
*Main> v''''
Nothing | 388Queue/Usage
| 8haskell
| dpsn4 |
package main
import "fmt"
func quickselect(list []int, k int) int {
for { | 387Quickselect algorithm
| 0go
| 2iyl7 |
null | 379Random numbers
| 11kotlin
| 3x9z5 |
import java.io.BufferedReader;
import java.io.FileReader;
public class ReadFileByLines {
private static void processLine(int lineNo, String line) { | 383Read a file line by line
| 9java
| ibios |
import Data.List (partition)
quickselect
:: Ord a
=> [a] -> Int -> a
quickselect (x:xs) k
| k < l = quickselect ys k
| k > l = quickselect zs (k - l - 1)
| otherwise = x
where
(ys, zs) = partition (< x) xs
l = length ys
main :: IO ()
main =
print
((fmap . quickselect) <*> zipWith const [0 ..] $
[9, 8, 7, 6, 5, 0, 1, 2, 3, 4]) | 387Quickselect algorithm
| 8haskell
| avh1g |
conf = {}
fp = io.open( "conf.txt", "r" )
for line in fp:lines() do
line = line:match( "%s*(.+)" )
if line and line:sub( 1, 1 ) ~= "#" and line:sub( 1, 1 ) ~= ";" then
option = line:match( "%S+" ):lower()
value = line:match( "%S*%s*(.*)" )
if not value then
conf[option] = true
else
if not value:find( "," ) then
conf[option] = value
else
value = value .. ","
conf[option] = {}
for entry in value:gmatch( "%s*(.-)," ) do
conf[option][#conf[option]+1] = entry
end
end
end
end
end
fp:close()
print( "fullname = ", conf["fullname"] )
print( "favouritefruit = ", conf["favouritefruit"] )
if conf["needspeeling"] then print( "needspeeling = true" ) else print( "needspeeling = false" ) end
if conf["seedsremoved"] then print( "seedsremoved = true" ) else print( "seedsremoved = false" ) end
if conf["otherfamily"] then
print "otherfamily:"
for _, entry in pairs( conf["otherfamily"] ) do
print( "", entry )
end
end | 374Read a configuration file
| 1lua
| ibmot |
import java.util.*;
class RangeExpander implements Iterator<Integer>, Iterable<Integer> {
private static final Pattern TOKEN_PATTERN = Pattern.compile("([+-]?\\d+)-([+-]?\\d+)");
private final Iterator<String> tokensIterator;
private boolean inRange;
private int upperRangeEndpoint;
private int nextRangeValue;
public RangeExpander(String range) {
String[] tokens = range.split("\\s*,\\s*");
this.tokensIterator = Arrays.asList(tokens).iterator();
}
@Override
public boolean hasNext() {
return hasNextRangeValue() || this.tokensIterator.hasNext();
}
private boolean hasNextRangeValue() {
return this.inRange && this.nextRangeValue <= this.upperRangeEndpoint;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
if (hasNextRangeValue()) {
return this.nextRangeValue++;
}
String token = this.tokensIterator.next();
Matcher matcher = TOKEN_PATTERN.matcher(token);
if (matcher.find()) {
this.inRange = true;
this.upperRangeEndpoint = Integer.valueOf(matcher.group(2));
this.nextRangeValue = Integer.valueOf(matcher.group(1));
return this.nextRangeValue++;
}
this.inRange = false;
return Integer.valueOf(token);
}
@Override
public Iterator<Integer> iterator() {
return this;
}
}
class RangeExpanderTest {
public static void main(String[] args) {
RangeExpander re = new RangeExpander("-6,-3--1,3-5,7-11,14,15,17-20");
for (int i : re) {
System.out.print(i + " ");
}
}
} | 385Range expansion
| 9java
| 6xt3z |
var fs = require("fs");
var readFile = function(path) {
return fs.readFileSync(path).toString();
};
console.log(readFile('file.txt')); | 383Read a file line by line
| 10javascript
| zwzt2 |
import java.util.LinkedList;
import java.util.Queue;
...
Queue<Integer> queue = new LinkedList<Integer>();
System.out.println(queue.isEmpty()); | 388Queue/Usage
| 9java
| sr1q0 |
var f = new Array();
print(f.length);
f.push(1,2); | 388Queue/Usage
| 10javascript
| nbqiy |
#!/usr/bin/env js
function main() {
print(rangeExpand('-6,-3--1,3-5,7-11,14,15,17-20'));
}
function rangeExpand(rangeExpr) {
function getFactors(term) {
var matches = term.match(/(-?[0-9]+)-(-?[0-9]+)/);
if (!matches) return {first:Number(term)};
return {first:Number(matches[1]), last:Number(matches[2])};
}
function expandTerm(term) {
var factors = getFactors(term);
if (factors.length < 2) return [factors.first];
var range = [];
for (var n = factors.first; n <= factors.last; n++) {
range.push(n);
}
return range;
}
var result = [];
var terms = rangeExpr.split(/,/);
for (var t in terms) {
result = result.concat(expandTerm(terms[t]));
}
return result;
}
main(); | 385Range expansion
| 10javascript
| lomcf |
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY)
#'user/empty-queue
user=> (def aqueue (atom empty-queue))
#'user/aqueue
user=> (empty? @aqueue)
true
user=> (swap! aqueue conj 1)
user=> (swap! aqueue into [2 3 4])
user=> (pprint @aqueue)
<-(1 2 3 4)-<
user=> (peek @aqueue)
1
user=> (pprint (pop @aqueue))
<-(2 3 4)-<
user=> (pprint @aqueue)
<-(1 2 3 4)-<
user=> (into [] @aqueue)
[1 2 3 4]
user=> (-> @aqueue rest (conj 5) pprint)
(5 2 3 4)
user=> (-> @aqueue pop (conj 5) pprint)
<-(2 3 4 5)-< | 391Queue/Definition
| 6clojure
| nbeik |
null | 388Queue/Usage
| 11kotlin
| avj13 |
import java.util.Random;
public class QuickSelect {
private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) {
E pivotVal = arr[pivot];
swap(arr, pivot, right);
int storeIndex = left;
for (int i = left; i < right; i++) {
if (arr[i].compareTo(pivotVal) < 0) {
swap(arr, i, storeIndex);
storeIndex++;
}
}
swap(arr, right, storeIndex);
return storeIndex;
}
private static <E extends Comparable<? super E>> E select(E[] arr, int n) {
int left = 0;
int right = arr.length - 1;
Random rand = new Random();
while (right >= left) {
int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left);
if (pivotIndex == n) {
return arr[pivotIndex];
} else if (pivotIndex < n) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return null;
}
private static void swap(Object[] arr, int i1, int i2) {
if (i1 != i2) {
Object temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
System.out.print(select(input, i));
if (i < 9) System.out.print(", ");
}
System.out.println();
}
} | 387Quickselect algorithm
| 9java
| jy57c |
local list = {}
for i = 1, 1000 do
list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2
end | 379Random numbers
| 1lua
| 6qc39 |
null | 383Read a file line by line
| 11kotlin
| qrqx1 |
null | 387Quickselect algorithm
| 10javascript
| 12jp7 |
q = Queue.new()
Queue.push( q, 5 )
Queue.push( q, "abc" )
while not Queue.empty( q ) do
print( Queue.pop( q ) )
end | 388Queue/Usage
| 1lua
| euhac |
null | 385Range expansion
| 11kotlin
| dponz |
input()[::-1] | 366Reverse a string
| 3python
| 4z85k |
null | 387Quickselect algorithm
| 11kotlin
| 5fcua |
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
func main() {
rf, err := rangeFormat([]int{
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39,
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("range format:", rf)
}
func rangeFormat(a []int) (string, error) {
if len(a) == 0 {
return "", nil
}
var parts []string
for n1 := 0; ; {
n2 := n1 + 1
for n2 < len(a) && a[n2] == a[n2-1]+1 {
n2++
}
s := strconv.Itoa(a[n1])
if n2 == n1+2 {
s += "," + strconv.Itoa(a[n2-1])
} else if n2 > n1+2 {
s += "-" + strconv.Itoa(a[n2-1])
}
parts = append(parts, s)
if n2 == len(a) {
break
}
if a[n2] == a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence repeats value%d", a[n2]))
}
if a[n2] < a[n2-1] {
return "", errors.New(fmt.Sprintf(
"sequence not ordered:%d <%d", a[n2], a[n2-1]))
}
n1 = n2
}
return strings.Join(parts, ","), nil
} | 386Range extraction
| 0go
| 8jx0g |
filename = "input.txt"
fp = io.open( filename, "r" )
for line in fp:lines() do
print( line )
end
fp:close() | 383Read a file line by line
| 1lua
| s7sq8 |
function partition (list, left, right, pivotIndex)
local pivotValue = list[pivotIndex]
list[pivotIndex], list[right] = list[right], list[pivotIndex]
local storeIndex = left
for i = left, right do
if list[i] < pivotValue then
list[storeIndex], list[i] = list[i], list[storeIndex]
storeIndex = storeIndex + 1
end
end
list[right], list[storeIndex] = list[storeIndex], list[right]
return storeIndex
end
function quickSelect (list, left, right, n)
local pivotIndex
while 1 do
if left == right then return list[left] end
pivotIndex = math.random(left, right)
pivotIndex = partition(list, left, right, pivotIndex)
if n == pivotIndex then
return list[n]
elseif n < pivotIndex then
right = pivotIndex - 1
else
left = pivotIndex + 1
end
end
end
math.randomseed(os.time())
local vec = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
for i = 1, 10 do print(i, quickSelect(vec, 1, #vec, i) .. " ") end | 387Quickselect algorithm
| 1lua
| 4tl5c |
def range = { s, e -> s == e ? "${s},": s == e - 1 ? "${s},${e},": "${s}-${e}," }
def compressList = { list ->
def sb, start, end
(sb, start, end) = [''<<'', list[0], list[0]]
for (i in list[1..-1]) {
(sb, start, end) = i == end + 1 ? [sb, start, i]: [sb << range(start, end), i, i]
}
(sb << range(start, end))[0..-2].toString()
}
def compressRanges = { expanded -> compressList(Eval.me('[' + expanded + ']')) } | 386Range extraction
| 7groovy
| w5pel |
static char sym[] =
printf(code, sym[0], sym[0], sym[3], sym[2], sym[2], sym[2], sym[2], sym[2], sym[3], sym[3], sym[0], sym[0], sym[0], sym[1], sym[3], code, sym[3], sym[0], sym[1], sym[0], sym[0], sym[1], sym[0], sym[0]);
return 0;
} | 389Quine
| 5c
| r3lg7 |
import Data.List (intercalate)
extractRange :: [Int] -> String
extractRange = intercalate "," . f
where f :: [Int] -> [String]
f (x1: x2: x3: xs) | x1 + 1 == x2 && x2 + 1 == x3
= (show x1 ++ '-': show xn): f xs'
where (xn, xs') = g (x3 + 1) xs
g a (n: ns) | a == n = g (a + 1) ns
| otherwise = (a - 1, n: ns)
g a [] = (a - 1, [])
f (x: xs) = show x: f xs
f [] = [] | 386Range extraction
| 8haskell
| loych |
function range(i, j)
local t = {}
for n = i, j, i<j and 1 or -1 do
t[#t+1] = n
end
return t
end
function expand_ranges(rspec)
local ptn = "([-+]?%d+)%s?-%s?([-+]?%d+)"
local t = {}
for v in string.gmatch(rspec, '[^,]+') do
local s, e = v:match(ptn)
if s == nil then
t[#t+1] = tonumber(v)
else
for i, n in ipairs(range(tonumber(s), tonumber(e))) do
t[#t+1] = n
end
end
end
return t
end
local ranges = "-6,-3 | 385Range expansion
| 1lua
| f1idp |
revstring <- function(stringtorev) {
return(
paste(
strsplit(stringtorev,"")[[1]][nchar(stringtorev):1]
,collapse="")
)
} | 366Reverse a string
| 13r
| 2nxlg |
my $fullname;
my $favouritefruit;
my $needspeeling;
my $seedsremoved;
my @otherfamily;
my $conf_definition = {
'fullname' => [ 'string', \$fullname ],
'favouritefruit' => [ 'string', \$favouritefruit ],
'needspeeling' => [ 'boolean', \$needspeeling ],
'seedsremoved' => [ 'boolean', \$seedsremoved ],
'otherfamily' => [ 'array', \@otherfamily ],
};
my $arg = shift;
my $file;
open $file, $arg or die "Can't open configuration file '$arg': $!";
read_conf_file($file, $conf_definition);
print "fullname = $fullname\n";
print "favouritefruit = $favouritefruit\n";
print "needspeeling = ", ($needspeeling ? 'true' : 'false'), "\n";
print "seedsremoved = ", ($seedsremoved ? 'true' : 'false'), "\n";
for (my $i = 0; $i < @otherfamily; ++$i) {
print "otherfamily(", $i + 1, ") = ", $otherfamily[$i], "\n";
}
sub read_conf_file {
my ($fh, $def) = @_;
local $_;
while (<$fh>) {
next if /^
next if /^;/;
next if /^$/;
chomp;
$_ =~ /^\s*(\w+)\s*(.*)$/i or die "Syntax error";
my $key = $1;
my $rest = $2;
$key =~ tr/[A-Z]/[a-z]/;
if (!exists $def->{$key}) {
die "Unknown keyword: '$key'";
}
if ($def->{$key}[0] eq 'boolean') {
if ($rest) {
die "Syntax error: extra data following boolean '$key'";
}
${$def->{$key}[1]} = 1;
next;
}
$rest =~ s/\s*$//;
$rest =~ s/^=\s*//;
if ($def->{$key}[0] eq 'string') {
${$def->{$key}[1]} = $rest;
} elsif ($def->{$key}[0] eq 'array') {
@{$def->{$key}[1]} = split /\s*,\s*/, $rest;
} else {
die "Internal error (unknown type in configuration definition)";
}
}
} | 374Read a configuration file
| 2perl
| g3a4e |
@queue = ();
push @queue, (1..5);
print shift @queue,"\n";
print "array is empty\n" unless @queue;
print $n while($n = shift @queue);
print "\n";
print "array is empty\n" unless @queue; | 388Queue/Usage
| 2perl
| 90tmn |
public class RangeExtraction {
public static void main(String[] args) {
int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39};
int len = arr.length;
int idx = 0, idx2 = 0;
while (idx < len) {
while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);
if (idx2 - idx > 2) {
System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]);
idx = idx2;
} else {
for (; idx < idx2; idx++)
System.out.printf("%s,", arr[idx]);
}
}
}
} | 386Range extraction
| 9java
| 3wdzg |
<?php
$queue = new SplQueue;
echo $queue->isEmpty()? 'true' : 'false', ;
$queue->enqueue(1);
$queue->enqueue(2);
$queue->enqueue(3);
echo $queue->dequeue(), ;
echo $queue->isEmpty()? 'true' : 'false', ;
?> | 388Queue/Usage
| 12php
| w5kep |
my @list = qw(9 8 7 6 5 0 1 2 3 4);
print join ' ', map { qselect(\@list, $_) } 1 .. 10 and print "\n";
sub qselect
{
my ($list, $k) = @_;
my $pivot = @$list[int rand @{ $list } - 1];
my @left = grep { $_ < $pivot } @$list;
my @right = grep { $_ > $pivot } @$list;
if ($k <= @left)
{
return qselect(\@left, $k);
}
elsif ($k > @left + 1)
{
return qselect(\@right, $k - @left - 1);
}
else { $pivot }
} | 387Quickselect algorithm
| 2perl
| ohx8x |
function rangeExtraction(list) {
var len = list.length;
var out = [];
var i, j;
for (i = 0; i < len; i = j + 1) { | 386Range extraction
| 10javascript
| c869j |
((fn [x] (list x (list (quote quote) x))) (quote (fn [x] (list x (list (quote quote) x))))) | 389Quine
| 6clojure
| bc4kz |
<?php
$conf = file_get_contents('parse-conf-file.txt');
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
$conf = preg_replace_callback(
'/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
function ($matches) {
$r = '';
foreach (explode(',', $matches[2]) AS $val) {
$r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
}
return $r;
},
$conf
);
$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);
$ini = parse_ini_string($conf);
echo 'Full name = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling = ', (empty($ini['NEEDSPEELING'])? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED'])? 'false' : 'true'), PHP_EOL;
echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL; | 374Read a configuration file
| 12php
| np9ig |
package main
import (
"fmt"
"math"
)
type qtn struct {
r, i, j, k float64
}
var (
q = &qtn{1, 2, 3, 4}
q1 = &qtn{2, 3, 4, 5}
q2 = &qtn{3, 4, 5, 6}
r float64 = 7
)
func main() {
fmt.Println("Inputs")
fmt.Println("q:", q)
fmt.Println("q1:", q1)
fmt.Println("q2:", q2)
fmt.Println("r:", r)
var qr qtn
fmt.Println("\nFunctions")
fmt.Println("q.norm():", q.norm())
fmt.Println("neg(q):", qr.neg(q))
fmt.Println("conj(q):", qr.conj(q))
fmt.Println("addF(q, r):", qr.addF(q, r))
fmt.Println("addQ(q1, q2):", qr.addQ(q1, q2))
fmt.Println("mulF(q, r):", qr.mulF(q, r))
fmt.Println("mulQ(q1, q2):", qr.mulQ(q1, q2))
fmt.Println("mulQ(q2, q1):", qr.mulQ(q2, q1))
}
func (q *qtn) String() string {
return fmt.Sprintf("(%g,%g,%g,%g)", q.r, q.i, q.j, q.k)
}
func (q *qtn) norm() float64 {
return math.Sqrt(q.r*q.r + q.i*q.i + q.j*q.j + q.k*q.k)
}
func (z *qtn) neg(q *qtn) *qtn {
z.r, z.i, z.j, z.k = -q.r, -q.i, -q.j, -q.k
return z
}
func (z *qtn) conj(q *qtn) *qtn {
z.r, z.i, z.j, z.k = q.r, -q.i, -q.j, -q.k
return z
}
func (z *qtn) addF(q *qtn, r float64) *qtn {
z.r, z.i, z.j, z.k = q.r+r, q.i, q.j, q.k
return z
}
func (z *qtn) addQ(q1, q2 *qtn) *qtn {
z.r, z.i, z.j, z.k = q1.r+q2.r, q1.i+q2.i, q1.j+q2.j, q1.k+q2.k
return z
}
func (z *qtn) mulF(q *qtn, r float64) *qtn {
z.r, z.i, z.j, z.k = q.r*r, q.i*r, q.j*r, q.k*r
return z
}
func (z *qtn) mulQ(q1, q2 *qtn) *qtn {
z.r, z.i, z.j, z.k =
q1.r*q2.r-q1.i*q2.i-q1.j*q2.j-q1.k*q2.k,
q1.r*q2.i+q1.i*q2.r+q1.j*q2.k-q1.k*q2.j,
q1.r*q2.j-q1.i*q2.k+q1.j*q2.r+q1.k*q2.i,
q1.r*q2.k+q1.i*q2.j-q1.j*q2.i+q1.k*q2.r
return z
} | 390Quaternion type
| 0go
| 5fyul |
import Control.Monad (join)
data Quaternion a =
Q a a a a
deriving (Show, Eq)
realQ :: Quaternion a -> a
realQ (Q r _ _ _) = r
imagQ :: Quaternion a -> [a]
imagQ (Q _ i j k) = [i, j, k]
quaternionFromScalar :: (Num a) => a -> Quaternion a
quaternionFromScalar s = Q s 0 0 0
listFromQ :: Quaternion a -> [a]
listFromQ (Q a b c d) = [a, b, c, d]
quaternionFromList :: [a] -> Quaternion a
quaternionFromList [a, b, c, d] = Q a b c d
normQ :: (RealFloat a) => Quaternion a -> a
normQ = sqrt . sum . join (zipWith (*)) . listFromQ
conjQ :: (Num a) => Quaternion a -> Quaternion a
conjQ (Q a b c d) = Q a (-b) (-c) (-d)
instance (RealFloat a) => Num (Quaternion a) where
(Q a b c d) + (Q p q r s) = Q (a + p) (b + q) (c + r) (d + s)
(Q a b c d) - (Q p q r s) = Q (a - p) (b - q) (c - r) (d - s)
(Q a b c d) * (Q p q r s) =
Q
(a * p - b * q - c * r - d * s)
(a * q + b * p + c * s - d * r)
(a * r - b * s + c * p + d * q)
(a * s + b * r - c * q + d * p)
negate (Q a b c d) = Q (-a) (-b) (-c) (-d)
abs q = quaternionFromScalar (normQ q)
signum (Q 0 0 0 0) = 0
signum q@(Q a b c d) = Q (a/n) (b/n) (c/n) (d/n) where n = normQ q
fromInteger n = quaternionFromScalar (fromInteger n)
main :: IO ()
main = do
let q, q1, q2 :: Quaternion Double
q = Q 1 2 3 4
q1 = Q 2 3 4 5
q2 = Q 3 4 5 6
print $ (Q 0 1 0 0) * (Q 0 0 1 0) * (Q 0 0 0 1)
print $ q1 * q2
print $ q2 * q1
print $ q1 * q2 == q2 * q1
print $ imagQ q | 390Quaternion type
| 8haskell
| x4hw4 |
import Queue
my_queue = Queue.Queue()
my_queue.put()
my_queue.put()
my_queue.put()
print my_queue.get()
print my_queue.get()
print my_queue.get() | 388Queue/Usage
| 3python
| c8z9q |
my $PI = 2 * atan2 1, 0;
my @nums = map {
1 + 0.5 * sqrt(-2 * log rand) * cos(2 * $PI * rand)
} 1..1000; | 379Random numbers
| 2perl
| p2wb0 |
import random
def partition(vector, left, right, pivotIndex):
pivotValue = vector[pivotIndex]
vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]
storeIndex = left
for i in range(left, right):
if vector[i] < pivotValue:
vector[storeIndex], vector[i] = vector[i], vector[storeIndex]
storeIndex += 1
vector[right], vector[storeIndex] = vector[storeIndex], vector[right]
return storeIndex
def _select(vector, left, right, k):
while True:
pivotIndex = random.randint(left, right)
pivotNewIndex = partition(vector, left, right, pivotIndex)
pivotDist = pivotNewIndex - left
if pivotDist == k:
return vector[pivotNewIndex]
elif k < pivotDist:
right = pivotNewIndex - 1
else:
k -= pivotDist + 1
left = pivotNewIndex + 1
def select(vector, k, left=None, right=None):
if left is None:
left = 0
lv1 = len(vector) - 1
if right is None:
right = lv1
assert vector and k >= 0,
assert 0 <= left <= lv1,
assert left <= right <= lv1,
return _select(vector, left, right, k)
if __name__ == '__main__':
v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
print([select(v, i) for i in range(10)]) | 387Quickselect algorithm
| 3python
| ikqof |
null | 386Range extraction
| 11kotlin
| nb0ij |
function random() {
return mt_rand() / mt_getrandmax();
}
$pi = pi();
$a = array();
for ($i = 0; $i < 1000; $i++) {
$a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);
} | 379Random numbers
| 12php
| ysl61 |
sub rangex {
map { /^(.*\d)-(.+)$/ ? $1..$2 : $_ } split /,/, shift
}
print join(',', rangex('-6,-3--1,3-5,7-11,14,15,17-20')), "\n"; | 385Range expansion
| 2perl
| jyg7f |
open(my $fh, '<', 'foobar.txt')
|| die "Could not open file: $!";
while (<$fh>)
{
chomp;
process($_);
}
close $fh; | 383Read a file line by line
| 2perl
| vdv20 |
use std::collections::VecDeque;
fn main() {
let mut queue = VecDeque::new();
queue.push_back();
queue.push_back();
while let Some(item) = queue.pop_front() {
println!(, item);
}
if queue.is_empty() {
println!();
}
} | 388Queue/Usage
| 14ruby
| 2i6lw |
def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v | 374Read a configuration file
| 3python
| r6egq |
<?php
$file = fopen(__FILE__, 'r');
while ($line = fgets($file)) {
$line = rtrim($line);
echo strrev($line) . ;
} | 383Read a file line by line
| 12php
| 0j0sp |
public class Quaternion {
private final double a, b, c, d;
public Quaternion(double a, double b, double c, double d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public Quaternion(double r) {
this(r, 0.0, 0.0, 0.0);
}
public double norm() {
return Math.sqrt(a * a + b * b + c * c + d * d);
}
public Quaternion negative() {
return new Quaternion(-a, -b, -c, -d);
}
public Quaternion conjugate() {
return new Quaternion(a, -b, -c, -d);
}
public Quaternion add(double r) {
return new Quaternion(a + r, b, c, d);
}
public static Quaternion add(Quaternion q, double r) {
return q.add(r);
}
public static Quaternion add(double r, Quaternion q) {
return q.add(r);
}
public Quaternion add(Quaternion q) {
return new Quaternion(a + q.a, b + q.b, c + q.c, d + q.d);
}
public static Quaternion add(Quaternion q1, Quaternion q2) {
return q1.add(q2);
}
public Quaternion times(double r) {
return new Quaternion(a * r, b * r, c * r, d * r);
}
public static Quaternion times(Quaternion q, double r) {
return q.times(r);
}
public static Quaternion times(double r, Quaternion q) {
return q.times(r);
}
public Quaternion times(Quaternion q) {
return new Quaternion(
a * q.a - b * q.b - c * q.c - d * q.d,
a * q.b + b * q.a + c * q.d - d * q.c,
a * q.c - b * q.d + c * q.a + d * q.b,
a * q.d + b * q.c - c * q.b + d * q.a
);
}
public static Quaternion times(Quaternion q1, Quaternion q2) {
return q1.times(q2);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Quaternion)) return false;
final Quaternion other = (Quaternion) obj;
if (Double.doubleToLongBits(this.a) != Double.doubleToLongBits(other.a)) return false;
if (Double.doubleToLongBits(this.b) != Double.doubleToLongBits(other.b)) return false;
if (Double.doubleToLongBits(this.c) != Double.doubleToLongBits(other.c)) return false;
if (Double.doubleToLongBits(this.d) != Double.doubleToLongBits(other.d)) return false;
return true;
}
@Override
public String toString() {
return String.format("%.2f +%.2fi +%.2fj +%.2fk", a, b, c, d).replaceAll("\\+ -", "- ");
}
public String toQuadruple() {
return String.format("(%.2f,%.2f,%.2f,%.2f)", a, b, c, d);
}
public static void main(String[] args) {
Quaternion q = new Quaternion(1.0, 2.0, 3.0, 4.0);
Quaternion q1 = new Quaternion(2.0, 3.0, 4.0, 5.0);
Quaternion q2 = new Quaternion(3.0, 4.0, 5.0, 6.0);
double r = 7.0;
System.out.format("q =%s%n", q);
System.out.format("q1 =%s%n", q1);
System.out.format("q2 =%s%n", q2);
System.out.format("r =%.2f%n%n", r);
System.out.format("\u2016q\u2016 =%.2f%n", q.norm());
System.out.format("-q =%s%n", q.negative());
System.out.format("q* =%s%n", q.conjugate());
System.out.format("q + r =%s%n", q.add(r));
System.out.format("q1 + q2 =%s%n", q1.add(q2));
System.out.format("q \u00d7 r =%s%n", q.times(r));
Quaternion q1q2 = q1.times(q2);
Quaternion q2q1 = q2.times(q1);
System.out.format("q1 \u00d7 q2 =%s%n", q1q2);
System.out.format("q2 \u00d7 q1 =%s%n", q2q1);
System.out.format("q1 \u00d7 q2%s q2 \u00d7 q1%n", (q1q2.equals(q2q1) ? "=" : "\u2260"));
}
} | 390Quaternion type
| 9java
| bc5k3 |
use std::collections::VecDeque;
fn main() {
let mut queue = VecDeque::new();
queue.push_back("Hello");
queue.push_back("World");
while let Some(item) = queue.pop_front() {
println!("{}", item);
}
if queue.is_empty() {
println!("Yes, it is empty!");
}
} | 388Queue/Usage
| 15rust
| vny2t |
val q=scala.collection.mutable.Queue[Int]()
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
q enqueue 1
q enqueue 2
q enqueue 3
println("queue = " + q)
println("front = " + q.front)
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty) | 388Queue/Usage
| 16scala
| 4tc50 |
function rangex($str) {
$lst = array();
foreach (explode(',', $str) as $e) {
if (strpos($e, '-', 1) !== FALSE) {
list($a, $b) = explode('-', substr($e, 1), 2);
$lst = array_merge($lst, range($e[0] . $a, $b));
} else {
$lst[] = (int) $e;
}
}
return $lst;
} | 385Range expansion
| 12php
| tanf1 |
var Quaternion = (function() { | 390Quaternion type
| 10javascript
| w5je2 |
function extractRange (rList)
local rExpr, startVal = ""
for k, v in pairs(rList) do
if rList[k + 1] == v + 1 then
if not startVal then startVal = v end
else
if startVal then
if v == startVal + 1 then
rExpr = rExpr .. startVal .. "," .. v .. ","
else
rExpr = rExpr .. startVal .. "-" .. v .. ","
end
startVal = nil
else
rExpr = rExpr .. v .. ","
end
end
end
return rExpr:sub(1, -2)
end
local intList = {
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
}
print(extractRange(intList)) | 386Range extraction
| 1lua
| dp8nq |
def quickselect(a, k)
arr = a.dup
loop do
pivot = arr.delete_at(rand(arr.length))
left, right = arr.partition { |x| x < pivot }
if k == left.length
return pivot
elsif k < left.length
arr = left
else
k = k - left.length - 1
arr = right
end
end
end
v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
p v.each_index.map { |i| quickselect(v, i) } | 387Quickselect algorithm
| 14ruby
| dp0ns |
>>> import random
>>> values = [random.gauss(1, .5) for i in range(1000)]
>>> | 379Random numbers
| 3python
| 1vxpc |
with open() as f:
for line in f:
process(line) | 383Read a file line by line
| 3python
| ufuvd |
package queue | 391Queue/Definition
| 0go
| vnz2m |
main()=>(s){print('$s(r\x22$s\x22);');}(r"main()=>(s){print('$s(r\x22$s\x22);');}"); | 389Quine
| 18dart
| 2i3lp |
null | 387Quickselect algorithm
| 15rust
| f18d6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.