code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
julia> x = [1, 2, 3]
julia> ptr = pointer_from_objref(x)
Ptr{Void} @0x000000010282e4a0
julia> unsafe_pointer_to_objref(ptr)
3-element Array{Int64,1}:
1
2
3 | 1,156Address of a variable | 9java | qsaxa |
(require '[clojure.java.io:as io])
(def groups
(with-open [r (io/reader wordfile)]
(group-by sort (line-seq r))))
(let [wordlists (sort-by (comp - count) (vals groups))
maxlength (count (first wordlists))]
(doseq [wordlist (take-while #(= (count %) maxlength) wordlists)]
(println wordlist)) | 1,152Anagrams | 6clojure | xsqwk |
null | 1,144Amicable pairs | 11kotlin | awi13 |
<?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password); | 1,150Active Directory/Connect | 12php | awx12 |
import ldap
l = ldap.initialize()
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s(, )
finally:
l.unbind() | 1,150Active Directory/Connect | 3python | mclyh |
e = {} | 1,155Add a variable to a class instance at runtime | 10javascript | 6yt38 |
null | 1,156Address of a variable | 11kotlin | 1ahpd |
(defn c
"kth coefficient of (x - 1)^n"
[n k]
(/ (apply *' (range n (- n k) -1))
(apply *' (range k 0 -1))
(if (and (even? k) (< k n)) -1 1)))
(defn cs
"coefficient series for (x - 1)^n, k=[0..n]"
[n]
(map #(c n %) (range (inc n))))
(defn aks? [p] (->> (cs p) rest butlast (every? #(-> % (mod... | 1,153AKS test for primes | 6clojure | 8i805 |
from __future__ import annotations
from enum import Enum
from typing import NamedTuple
from typing import Optional
class Color(Enum):
B = 0
R = 1
class Tree(NamedTuple):
color: Color
left: Optional[Tree]
value: int
right: Optional[Tree]
def insert(self, val: int) -> Tree:
return... | 1,146Algebraic data types | 3python | fz9de |
function sumDivs (n)
local sum = 1
for d = 2, math.sqrt(n) do
if n % d == 0 then
sum = sum + d
sum = sum + n / d
end
end
return sum
end
for n = 2, 20000 do
m = sumDivs(n)
if m > n then
if sumDivs(m) == n then print(n, m) end
end
end | 1,144Amicable pairs | 1lua | exnac |
use strict;
use warnings;
use Tk;
use Math::Trig qw/:pi/;
my $root = new MainWindow( -title => 'Pendulum Animation' );
my $canvas = $root->Canvas(-width => 320, -height => 200);
my $after_id;
for ($canvas) {
$_->createLine( 0, 25, 320, 25, -tags => [qw/plate/], -width => 2, -fill => 'grey50' );
$_->createOval... | 1,143Animate a pendulum | 2perl | onm8x |
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new(:host => 'ldap.example.com', :base => 'o=companyname')
ldap.authenticate('bind_dn', 'bind_pass') | 1,150Active Directory/Connect | 14ruby | c2v9k |
let conn = ldap3::LdapConn::new("ldap: | 1,150Active Directory/Connect | 15rust | lvucc |
import java.io.IOException
import org.apache.directory.api.ldap.model.exception.LdapException
import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}
object LdapConnectionDemo {
@throws[LdapException]
@throws[IOException]
def main(args: Array[String]): Unit = {
try {
val co... | 1,150Active Directory/Connect | 16scala | u4gv8 |
null | 1,155Add a variable to a class instance at runtime | 11kotlin | 08xsf |
t = {}
print(t)
f = function() end
print(f)
c = coroutine.create(function() end)
print(c)
u = io.open("/dev/null","w")
print(u)
print(_G, _ENV) | 1,156Address of a variable | 1lua | aek1v |
package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n... | 1,147Almost prime | 0go | v572m |
(ns active-object
(:import (java.util Timer TimerTask)))
(defn input [integrator k]
(send integrator assoc:k k))
(defn output [integrator]
(:s @integrator))
(defn tick [integrator t1]
(send integrator
(fn [{:keys [k s t0]:as m}]
(assoc m:s (+ s (/ (* (+ (k t1) (k t0)) (- t1 t0)) 2.0)):t0 t1... | 1,157Active object | 6clojure | l26cb |
public class almostprime
{
public static boolean kprime(int n,int k)
{
int i,div=0;
for(i=2;(i*i <= n) && (div<k);i++)
{
while(n%i==0)
{
n = n/i;
div++;
}
}
return div + ((n > 1)?1:0) == k;
}
public static void main(String[] args)
{
... | 1,147Almost prime | 7groovy | mcuy5 |
use POSIX 'fmod';
sub angle {
my($b1,$b2) = @_;
my $b = fmod( ($b2 - $b1 + 720) , 360);
$b -= 360 if $b > 180;
$b += 360 if $b < -180;
return $b;
}
@bearings = (
20, 45,
-45, 45,
-85, 90,
-95, 90,
-45, 125,
-45, 145,
29.4803, -88.6381,
-78.3251, -159.036,
-70099.74233810... | 1,142Angle difference between two bearings | 2perl | 7hqrh |
import urllib.request
from collections import defaultdict
from itertools import combinations
def getwords(url='http:
return list(set(urllib.request.urlopen(url).read().decode().split()))
def find_anagrams(words):
anagram = defaultdict(list)
for word in words:
anagram[tuple(sorted(word))].append( ... | 1,139Anagrams/Deranged anagrams | 3python | u4wvd |
package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
... | 1,158Achilles numbers | 0go | xqbwf |
empty = {}
empty.foo = 1 | 1,155Add a variable to a class instance at runtime | 1lua | 8oq0e |
#![feature(box_patterns, box_syntax)]
use self::Color::*;
use std::cmp::Ordering::*;
enum Color {R,B}
type Link<T> = Option<Box<N<T>>>;
struct N<T> {
c: Color,
l: Link<T>,
val: T,
r: Link<T>,
}
impl<T: Ord> N<T> {
fn balance(col: Color, n1: Link<T>, z: T, n2: Link<T>) -> Link<T> {
Some(b... | 1,146Algebraic data types | 15rust | 3y2z8 |
class RedBlackTree[A](implicit ord: Ordering[A]) {
sealed abstract class Color
case object R extends Color
case object B extends Color
sealed abstract class Tree {
def insert(x: A): Tree = ins(x) match {
case T(_, a, y, b) => T(B, a, y, b)
case E => E
}
def ins(x: A): Tree
... | 1,146Algebraic data types | 16scala | mc5yc |
package main
import (
"fmt"
"sync"
)
func ambStrings(ss []string) chan []string {
c := make(chan []string)
go func() {
for _, s := range ss {
c <- []string{s}
}
close(c)
}()
return c
}
func ambChain(ss []string, cIn chan []string) chan []string {
cOut :... | 1,148Amb | 0go | 4rh52 |
enum Color { case R, B }
enum Tree<A> {
case E
indirect case T(Color, Tree<A>, A, Tree<A>)
}
func balance<A>(input: (Color, Tree<A>, A, Tree<A>)) -> Tree<A> {
switch input {
case let (.B, .T(.R, .T(.R,a,x,b), y, c), z, d): return .T(.R, .T(.B,a,x,b), y, .T(.B,c,z,d))
case let (.B, .T(.R, a, x, .T(.R,b,y,c)),... | 1,146Algebraic data types | 17swift | t3cfl |
isPrime :: Integral a => a -> Bool
isPrime n = not $ any ((0 ==) . (mod n)) [2..(truncate $ sqrt $ fromIntegral n)]
primes :: [Integer]
primes = filter isPrime [2..]
isKPrime :: (Num a, Eq a) => a -> Integer -> Bool
isKPrime 1 n = isPrime n
isKPrime k n = any (isKPrime (k - 1)) sprimes
where
sprimes = map fst $... | 1,147Almost prime | 8haskell | ex8ai |
puzzlers.dict <- readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
longest.deranged.anagram <- function(dict=puzzlers.dict) {
anagram.groups <- function(word.group) {
sorted <- sapply(lapply(strsplit(word.group,""),sort),paste, collapse="")
grouped <- tapply(word.group, sorted, force, simplify=... | 1,139Anagrams/Deranged anagrams | 13r | c2p95 |
import Control.Monad
amb = id
joins left right = last left == head right
example = do
w1 <- amb ["the", "that", "a"]
w2 <- amb ["frog", "elephant", "thing"]
w3 <- amb ["walked", "treaded", "grows"]
w4 <- amb ["slowly", "quickly"]
guard (w1 `joins` w2)
guard (w2 `joins` w3)
guard (w3 `joins` w4)
pure ... | 1,148Amb | 8haskell | q0ix9 |
use strict;
use warnings;
use feature <say current_sub>;
use experimental 'signatures';
use List::AllUtils <max head uniqint>;
use ntheory <is_square_free is_power euler_phi>;
use Math::AnyNum <:overload idiv iroot ipow is_coprime>;
sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_,... | 1,158Achilles numbers | 2perl | 549u2 |
package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, sea... | 1,151Aliquot sequence classifications | 0go | q00xz |
use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; | 1,156Address of a variable | 2perl | m9zyz |
divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
data Class
= Terminating
| Perfect
| Amicable
| Sociable
| Aspiring
| Cyclic
| Nonterminating
deriving (Show)
aliquot :: (Integral a) => a -> [a]
aliquot 0 = [0]
aliquot n = n: (aliquot $ sum $ divisors n)... | 1,151Aliquot sequence classifications | 8haskell | mccyf |
package Empty;
sub new { return bless {}, shift; }
package main;
my $o = Empty->new;
$o->{'foo'} = 1; | 1,155Add a variable to a class instance at runtime | 2perl | 542u2 |
package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d... | 1,154Additive primes | 0go | wxaeg |
import pygame, sys
from pygame.locals import *
from math import sin, cos, radians
pygame.init()
WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption()
screen = pygame.display.get_surface()
screen.fill((255,255,255))
PIVOT = (WINDOWSIZE/2... | 1,143Animate a pendulum | 3python | id9of |
class E {};
$e=new E();
$e->foo=1;
$e->{} = 1;
$x = ;
$e->$x = 1; | 1,155Add a variable to a class instance at runtime | 12php | ois85 |
public class additivePrimes {
public static void main(String[] args) {
int additive_primes = 0;
for (int i = 2; i < 500; i++) {
if(isPrime(i) && isPrime(digitSum(i))){
additive_primes++;
System.out.print(i + " ");
}
}
System.ou... | 1,154Additive primes | 9java | ndoih |
public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
... | 1,147Almost prime | 9java | hbejm |
from __future__ import print_function
def getDifference(b1, b2):
r = (b2 - b1)% 360.0
if r >= 180.0:
r -= 360.0
return r
if __name__ == :
print ()
print (getDifference(20.0, 45.0))
print (getDifference(-45.0, 45.0))
print (getDifference(-85.0, 90.0))
print (getDifference(-95.0, 90.0))
print (getDiffere... | 1,142Angle difference between two bearings | 3python | jks7p |
static __typeof__(n) _n=n; LOGIC; }
ACCUMULATOR(x,1.0)
ACCUMULATOR(y,3)
ACCUMULATOR(z,'a')
int main (void) {
printf (, x(5));
printf (, x(2.3));
printf (, y(5.0));
printf (, y(3.3));
printf (, z(5));
return 0;
} | 1,159Accumulator factory | 5c | 7j2rg |
fn perfect_powers(n: u128) -> Vec<u128> {
let mut powers = Vec::<u128>::new();
let sqrt = (n as f64).sqrt() as u128;
for i in 2..=sqrt {
let mut p = i * i;
while p < n {
powers.push(p);
p *= i;
}
}
powers.sort();
powers.dedup();
powers
}
fn bs... | 1,158Achilles numbers | 15rust | 7jvrc |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
static... | 1,151Aliquot sequence classifications | 9java | fzzdv |
class empty(object):
pass
e = empty() | 1,155Add a variable to a class instance at runtime | 3python | 4gv5k |
foo = object()
address = id(foo) | 1,156Address of a variable | 3python | 9c3mf |
import Data.List (unfoldr)
primes = 2: sieve [3,5..]
where sieve (x:xs) = x: sieve (filter (\y -> y `mod` x /= 0) xs)
isPrime n = all (\p -> n `mod` p /= 0) $ takeWhile (< sqrtN) primes
where sqrtN = round . sqrt . fromIntegral $ n
digits = unfoldr f
where f 0 = Nothing
f n = let (q, r) = divMod n 1... | 1,154Additive primes | 8haskell | 6yz3k |
function almostPrime (n, k) {
var divisor = 2, count = 0
while(count < k + 1 && n != 1) {
if (n % divisor == 0) {
n = n / divisor
count = count + 1
} else {
divisor++
}
}
return count == k
}
for (var k = 1; k <= 5; k++) {
document.write("<... | 1,147Almost prime | 10javascript | aw010 |
library(DescTools)
pendulum<-function(length=5,radius=1,circle.color="white",bg.color="white"){
tseq = c(seq(0,pi,by=.1),seq(pi,0,by=-.1))
slow=.27;fast=.07
sseq = c(seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,length.out = length(tseq)/4),seq(slow,fast,length.out = length(tseq)/4),seq(fast,slow,leng... | 1,143Animate a pendulum | 13r | s83qy |
function ambRun(func) {
var choices = [];
var index;
function amb(values) {
if (values.length == 0) {
fail();
}
if (index == choices.length) {
choices.push({i: 0,
count: values.length});
}
var choice = choices[index++... | 1,148Amb | 10javascript | xsow9 |
x <- 5
y <- x
pryr::address(x)
pryr::address(y)
y <- y + 1
pryr::address(x)
pryr::address(y) | 1,156Address of a variable | 13r | 36dzt |
fun isPrime(n: Int): Boolean {
if (n <= 3) return n > 1
if (n% 2 == 0 || n% 3 == 0) return false
var i = 5
while (i * i <= n) {
if (n% i == 0 || n% (i + 2) == 0) return false
i += 6
}
return true
}
fun digitSum(n: Int): Int {
var sum = 0
var num = n
while (num > 0) {... | 1,154Additive primes | 11kotlin | s0xq7 |
def deranged?(a, b)
a.chars.zip(b.chars).all? {|char_a, char_b| char_a!= char_b}
end
def find_derangements(list)
list.combination(2) {|a,b| return a,b if deranged?(a,b)}
nil
end
require 'open-uri'
anagram = open('http:
f.read.split.group_by {|s| s.each_char.sort}
end
anagram = anagram.select{|k,list| list.s... | 1,139Anagrams/Deranged anagrams | 14ruby | 4rq5p |
sub recur (&@) {
my $f = shift;
local *recurse = $f;
$f->(@_);
}
sub fibo {
my $n = shift;
$n < 0 and die 'Negative argument';
recur {
my $m = shift;
$m < 3 ? 1 : recurse($m - 1) + recurse($m - 2);
} $n;
} | 1,138Anonymous recursion | 2perl | g704e |
class Empty
end
e = Empty.new
class << e
attr_accessor:foo
end
e.foo = 1
puts e.foo
f = Empty.new
f.foo = 1 | 1,155Add a variable to a class instance at runtime | 14ruby | r75gs |
import language.dynamics
import scala.collection.mutable.HashMap
class A extends Dynamic {
private val map = new HashMap[String, Any]
def selectDynamic(name: String): Any = {
return map(name)
}
def updateDynamic(name:String)(value: Any) = {
map(name) = value
}
} | 1,155Add a variable to a class instance at runtime | 16scala | kb7hk |
>foo = Object.new
>id = foo.object_id
> % (id << 1) | 1,156Address of a variable | 14ruby | l2ycl |
function sumdigits(n)
local sum = 0
while n > 0 do
sum = sum + n % 10
n = math.floor(n/10)
end
return sum
end
primegen:generate(nil, 500)
aprimes = primegen:filter(function(n) return primegen.tbd(sumdigits(n)) end)
print(table.concat(aprimes, " "))
print("Count:", #aprimes) | 1,154Additive primes | 1lua | 08qsd |
fun Int.k_prime(x: Int): Boolean {
var n = x
var f = 0
var p = 2
while (f < this && p * p <= n) {
while (0 == n % p) { n /= p; f++ }
p++
}
return f + (if (n > 1) 1 else 0) == this
}
fun Int.primes(n : Int) : List<Int> {
var i = 2
var list = mutableListOf<Int>()
while... | 1,147Almost prime | 11kotlin | 4rk57 |
(defn accum [n]
(let [acc (atom n)]
(fn [m] (swap! acc + m)))) | 1,159Accumulator factory | 6clojure | p1gbd |
null | 1,151Aliquot sequence classifications | 11kotlin | 8ii0q |
import Foundation
let fooKey = UnsafeMutablePointer<UInt8>.alloc(1)
class MyClass { }
let e = MyClass() | 1,155Add a variable to a class instance at runtime | 17swift | gru49 |
let v1 = vec![vec![1,2,3]; 10];
println!("Original address: {:p}", &v1);
let mut v2; | 1,156Address of a variable | 15rust | 2vmlt |
var n = 42;
say Sys.refaddr(\n); # prints the address of the variable
say Sys.refaddr(n); # prints the address of the object at which the variable points to | 1,156Address of a variable | 16scala | 54lut |
def getDifference(b1, b2)
r = (b2 - b1) % 360.0
if r >= 180.0
r -= 360.0
end
return r
end
if __FILE__ == $PROGRAM_NAME
puts
puts getDifference(20.0, 45.0)
puts getDifference(-45.0, 45.0)
puts getDifference(-85.0, 90.0)
puts getDifference(-95.0, 90.0)
puts getDifference(-45.0, 125.0)
puts getDifferenc... | 1,142Angle difference between two bearings | 14ruby | kp8hg |
null | 1,139Anagrams/Deranged anagrams | 15rust | g7s4o |
<?php
function fib($n) {
if ($n < 0)
throw new Exception('Negative numbers not allowed');
$f = function($n) {
if ($n < 2)
return 1;
else {
$g = debug_backtrace()[1]['args'][0];
return call_user_func($g, $n-1) + call_user_func($g, $n-2);
}
... | 1,138Anonymous recursion | 12php | nf5ig |
use ntheory qw/divisor_sum/;
for my $x (1..20000) {
my $y = divisor_sum($x)-$x;
say "$x $y" if $y > $x && $x == divisor_sum($y)-$y;
} | 1,144Amicable pairs | 2perl | 9lrmn |
null | 1,148Amb | 11kotlin | 7hpr4 |
package main
import (
"fmt"
"math"
"time"
) | 1,157Active object | 0go | p17bg |
class MyClass { }
func printAddress<T>(of pointer: UnsafePointer<T>) {
print(pointer)
}
func test() {
var x = 42
var y = 3.14
var z = "foo"
var obj = MyClass() | 1,156Address of a variable | 17swift | cl69t |
null | 1,147Almost prime | 1lua | g7b4j |
null | 1,142Angle difference between two bearings | 15rust | b1okx |
object DerangedAnagrams {
def groupAnagrams(words: Iterable[String]): Map[String, Set[String]] =
words.foldLeft (Map[String, Set[String]]()) { (map, word) =>
val sorted = word.sorted
val entry = map.getOrElse(sorted, Set.empty)
map + (sorted -> (entry + word))
}
def isDeranged(ss:... | 1,139Anagrams/Deranged anagrams | 16scala | jko7i |
makeAccumulator(s) => (n) => s += n; | 1,159Accumulator factory | 18dart | vu62j |
class Integrator {
interface Function {
double apply(double timeSinceStartInSeconds)
}
private final long start
private volatile boolean running
private Function func
private double t0
private double v0
private double sum
Integrator(Function func) {
this.start = Sy... | 1,157Active object | 7groovy | 7jurz |
object AngleDifference extends App {
private def getDifference(b1: Double, b2: Double) = {
val r = (b2 - b1) % 360.0
if (r < -180.0) r + 360.0 else if (r >= 180.0) r - 360.0 else r
}
println("Input in -180 to +180 range")
println(getDifference(20.0, 45.0))
println(getDifference(-45.0, 45.0))
printl... | 1,142Angle difference between two bearings | 16scala | awd1n |
module Integrator (
newIntegrator, input, output, stop,
Time, timeInterval
) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, newMVar, modifyMVar_, modifyMVar, readMVar)
import Control.Exception (evaluate)
import Data.Time (UTCTime)
import Data.Time.Clock (getCurrentTime, ... | 1,157Active object | 8haskell | ft8d1 |
package main
import "fmt"
func bc(p int) []int64 {
c := make([]int64, p+1)
r := int64(1)
for i, half := 0, p/2; i <= half; i++ {
c[i] = r
c[p-i] = r
r = r * int64(p-i) / int64(i+1)
}
for i := p - 1; i >= 0; i -= 2 {
c[i] = -c[i]
}
return c
}
func main() {
... | 1,153AKS test for primes | 0go | c2c9g |
use strict;
use warnings;
use ntheory 'is_prime';
use List::Util <sum max>;
sub pp {
my $format = ('%' . (my $cw = 1+length max @_) . 'd') x @_;
my $width = ".{@{[$cw * int 60/$cw]}}";
(sprintf($format, @_)) =~ s/($width)/$1\n/gr;
}
my($limit, @ap) = 500;
is_prime($_) and is_prime(sum(split '',$_)) and p... | 1,154Additive primes | 2perl | u52vr |
<?php
function sumDivs ($n) {
$sum = 1;
for ($d = 2; $d <= sqrt($n); $d++) {
if ($n % $d == 0) $sum += $n / $d + $d;
}
return $sum;
}
for ($n = 2; $n < 20000; $n++) {
$m = sumDivs($n);
if ($m > $n) {
if (sumDivs($m) == $n) echo $n..$m.;
}
}
?> | 1,144Amicable pairs | 12php | wqdep |
require 'tk'
$root = TkRoot.new( => )
$canvas = TkCanvas.new($root) do
width 320
height 200
create TkcLine, 0,25,320,25, 'tags' => 'plate', 'width' => 2, 'fill' => 'grey50'
create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => , 'fill' => 'grey50'
create TkcLine, 1,1,1,1, 'tags' => 'rod', 'width' ... | 1,143Animate a pendulum | 14ruby | dtlns |
function amb (set)
local workset = {}
if (#set == 0) or (type(set) ~= 'table') then return end
if #set == 1 then return set end
if #set > 2 then
local first = table.remove(set,1)
set = amb(set)
for i,v in next,first do
for j,u in next,set do
if v:byte(... | 1,148Amb | 1lua | jk171 |
public class Integrator {
public interface Function {
double apply(double timeSinceStartInSeconds);
}
private final long start;
private volatile boolean running;
private Function func;
private double t0;
private double v0;
private double sum;
public Integrator(Function fu... | 1,157Active object | 9java | 08ese |
expand p = scanl (\z i -> z * (p-i+1) `div` i) 1 [1..p]
test p | p < 2 = False
| otherwise = and [mod n p == 0 | n <- init . tail $ expand p]
printPoly [1] = "1"
printPoly p = concat [ unwords [pow i, sgn (l-i), show (p!!(i-1))]
| i <- [l-1,l-2..1] ] where
l = length p
sg... | 1,153AKS test for primes | 8haskell | papbt |
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | 1,138Anonymous recursion | 3python | rj8gq |
null | 1,143Animate a pendulum | 15rust | fz2d6 |
function Integrator(sampleIntervalMS) {
var inputF = function () { return 0.0 };
var sum = 0.0;
var t1 = new Date().getTime();
var input1 = inputF(t1 / 1000);
function update() {
var t2 = new Date().getTime();
var input2 = inputF(t2 / 1000);
var dt = (t2 - t1) / 1000;
... | 1,157Active object | 10javascript | df0nu |
import java.awt.Color
import java.util.concurrent.{Executors, TimeUnit}
import scala.swing.{Graphics2D, MainFrame, Panel, SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension
object Pendulum extends SimpleSwingApplication {
val length = 100
lazy val ui = new Panel {
import scala.math.{cos, Pi, sin... | 1,143Animate a pendulum | 16scala | 3y5zy |
null | 1,157Active object | 11kotlin | ewka4 |
use ntheory qw/divisor_sum/;
sub aliquot {
my($n, $maxterms, $maxn) = @_;
$maxterms = 16 unless defined $maxterms;
$maxn = 2**47 unless defined $maxn;
my %terms = ($n => 1);
my @allterms = ($n);
for my $term (2 .. $maxterms) {
$n = divisor_sum($n)-$n;
last if $n > $maxn;
return ("terminat... | 1,151Aliquot sequence classifications | 2perl | 4rr5d |
func angleDifference(a1: Double, a2: Double) -> Double {
let diff = (a2 - a1).truncatingRemainder(dividingBy: 360)
if diff < -180.0 {
return 360.0 + diff
} else if diff > 180.0 {
return -360.0 + diff
} else {
return diff
}
}
let testCases = [
(20.0, 45.0),
(-45, 45),
(-85, 90),
(-95, 90)... | 1,142Angle difference between two bearings | 17swift | hb0j0 |
local seconds = os.clock
local integrator = {
new = function(self, fn)
return setmetatable({fn=fn,t0=seconds(),v0=0,sum=0,nup=0},self)
end,
update = function(self)
self.t1 = seconds()
self.v1 = self.fn(self.t1)
self.sum = self.sum + (self.v0 + self.v1) * (self.t1 - self.t0) / 2
self.t0, self.... | 1,157Active object | 1lua | wxbea |
public class AksTest {
private static final long[] c = new long[64];
public static void main(String[] args) {
for (int n = 0; n < 10; n++) {
coeff(n);
show(n);
}
System.out.print("Primes:");
for (int n = 1; n < c.length; n++)
if (isPrime(n))
... | 1,153AKS test for primes | 9java | rjrg0 |
using System;
class ColumnAlignerProgram
{
delegate string Justification(string s, int width);
static string[] AlignColumns(string[] lines, Justification justification)
{
const char Separator = '$';
string[][] table = new string[lines.Length][];
int columns = 0;
for... | 1,160Align columns | 5c | ftqd3 |
var i, p, pascal, primerow, primes, show, _i;
pascal = function() {
var a;
a = [];
return function() {
var b, i;
if (a.length === 0) {
return a = [1];
} else {
b = (function() {
var _i, _ref, _results;
_results = [];
for (i = _i = 0, _ref = a.length - 1; 0 <= _ref ... | 1,153AKS test for primes | 10javascript | b1bki |
use ntheory qw/factor/;
sub almost {
my($k,$n) = @_;
my $i = 1;
map { $i++ while scalar factor($i) != $k; $i++ } 1..$n;
}
say "$_: ", join(" ", almost($_,10)) for 1..5; | 1,147Almost prime | 2perl | id3o3 |
fib2 <- function(n) {
(n >= 0) || stop("bad argument")
( function(n) if (n <= 1) 1 else Recall(n-1)+Recall(n-2) )(n)
} | 1,138Anonymous recursion | 13r | u4xvx |
def is_prime(n: int) -> bool:
if n <= 3:
return n > 1
if n% 2 == 0 or n% 3 == 0:
return False
i = 5
while i ** 2 <= n:
if n% i == 0 or n% (i + 2) == 0:
return False
i += 6
return True
def digit_sum(n: int) -> int:
sum = 0
while n > 0:
sum ... | 1,154Additive primes | 3python | 54vux |
package main
import "fmt"
func accumulator(sum interface{}) func(interface{}) interface{} {
return func(nv interface{}) interface{} {
switch s := sum.(type) {
case int:
switch n := nv.(type) {
case int:
sum = s + n
case float64:
s... | 1,159Accumulator factory | 0go | dfqne |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.