code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use strict; use warnings; my ($w, $h) = (9, 9); my @v = map([ (0) x ($w + 1) ], 0 .. $h); my @f = map([ (0) x ($w + 1) ], 0 .. $h); my @d = map([ (0) x ($w + 1) ], 0 .. $h); my @n; for my $i (0 .. $h) { push @{$n[$i][$_]}, [$i, $_ - 1] for 1 .. $w; push @{$n[$i][$_]}, [$i, $_ + 1] for 0 .. $w - 1; } for my $j (0 .. $w) { push @{$n[$_][$j]}, [$_ - 1, $j] for 1 .. $h; push @{$n[$_][$j]}, [$_ + 1, $j] for 0 .. $h - 1; } sub set_boundary { $f[1][1] = 1; $f[6][7] = -1; $v[1][1] = 1; $v[6][7] = -1; } sub calc_diff { my $total_diff; for my $i (0 .. $h) { for my $j (0 .. $w) { my ($p, $v) = $n[$i][$j]; $v += $v[$_->[0]][$_->[1]] for @$p; $d[$i][$j] = $v = $v[$i][$j] - $v / scalar(@$p); $total_diff += $v * $v unless $f[$i][$j]; } } $total_diff; } sub iter { my $diff = 1; while ($diff > 1e-15) { set_boundary(); $diff = calc_diff(); for my $i (0 .. $h) { for my $j (0 .. $w) { $v[$i][$j] -= $d[$i][$j]; } } } my @current = (0) x 3; for my $i (0 .. $h) { for my $j (0 .. $w) { $current[ $f[$i][$j] ] += $d[$i][$j] * scalar(@{$n[$i][$j]}); } } return ($current[1] - $current[-1]) / 2; } printf "R =%.6f\n", 2 / iter();
347Resistor mesh
2perl
vfu20
public class ReflectionGetSource { public static void main(String[] args) { new ReflectionGetSource().method1(); } public ReflectionGetSource() {} public void method1() { method2(); } public void method2() { method3(); } public void method3() { Throwable t = new Throwable(); for ( StackTraceElement ste : t.getStackTrace() ) { System.out.printf("File Name =%s%n", ste.getFileName()); System.out.printf("Class Name =%s%n", ste.getClassName()); System.out.printf("Method Name =%s%n", ste.getMethodName()); System.out.printf("Line number =%s%n%n", ste.getLineNumber()); } } }
351Reflection/Get source
9java
jm47c
function foo() {...} foo.toString();
351Reflection/Get source
10javascript
1vhp7
(defn repeat-function [f n] (dotimes [i n] (f)))
352Repeat
6clojure
co39b
int main() { rename(, ); rename(, ); rename(, ); rename(, ); return 0; }
353Rename a file
5c
r62g7
romanToArabic <- function(roman) { romanLookup <- c(I=1L, V=5L, X=10L, L=50L, C=100L, D=500L, M=1000L) rSplit <- strsplit(toupper(roman), character(0)) toArabic <- function(item) { digits <- romanLookup[item] if (length(digits) > 1L) { smaller <- (digits[-length(digits)] < digits[-1L]) digits[smaller] <- - digits[smaller] } sum(digits) } vapply(rSplit, toArabic, integer(1)) }
340Roman numerals/Decode
13r
ryagj
package main import ( "fmt" "image" "reflect" )
354Reflection/List properties
0go
5tmul
import java.lang.reflect.Field @SuppressWarnings("unused") class ListProperties { public int examplePublicField = 42 private boolean examplePrivateField = true static void main(String[] args) { ListProperties obj = new ListProperties() Class clazz = obj.class println "All public fields (including inherited):" (clazz.fields).each { Field f -> printf "%s\t%s\n", f, f.get(obj) } println() println "All declared fields (excluding inherited):" clazz.getDeclaredFields().each { Field f -> f.accessible = true printf "%s\t%s\n", f, f.get(obj) } } }
354Reflection/List properties
7groovy
cot9i
null
351Reflection/Get source
11kotlin
5tlua
debug = require("debug") function foo(bar) info = debug.getinfo(1) for k,v in pairs(info) do print(k,v) end end foo()
351Reflection/Get source
1lua
4z25c
from __future__ import annotations import asyncio import sys from typing import Optional from typing import TextIO class OutOfInkError(Exception): class Printer: def __init__(self, name: str, backup: Optional[Printer]): self.name = name self.backup = backup self.ink_level: int = 5 self.output_stream: TextIO = sys.stdout async def print(self, msg): if self.ink_level <= 0: if self.backup: await self.backup.print(msg) else: raise OutOfInkError(self.name) else: self.ink_level -= 1 self.output_stream.write(f) async def main(): reserve = Printer(, None) main = Printer(, reserve) humpty_lines = [ , , , , ] goose_lines = [ , , , , , , , , ] async def print_humpty(): for line in humpty_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print() break async def print_goose(): for line in goose_lines: try: task = asyncio.Task(main.print(line)) await task except OutOfInkError: print() break await asyncio.gather(print_goose(), print_humpty()) if __name__ == : asyncio.run(main(), debug=True)
350Rendezvous
3python
jmg7p
DIFF_THRESHOLD = 1e-40 class Fixed: FREE = 0 A = 1 B = 2 class Node: __slots__ = [, ] def __init__(self, v=0.0, f=Fixed.FREE): self.voltage = v self.fixed = f def set_boundary(m): m[1][1] = Node( 1.0, Fixed.A) m[6][7] = Node(-1.0, Fixed.B) def calc_difference(m, d): h = len(m) w = len(m[0]) total = 0.0 for i in xrange(h): for j in xrange(w): v = 0.0 n = 0 if i != 0: v += m[i-1][j].voltage; n += 1 if j != 0: v += m[i][j-1].voltage; n += 1 if i < h-1: v += m[i+1][j].voltage; n += 1 if j < w-1: v += m[i][j+1].voltage; n += 1 v = m[i][j].voltage - v / n d[i][j].voltage = v if m[i][j].fixed == Fixed.FREE: total += v ** 2 return total def iter(m): h = len(m) w = len(m[0]) difference = [[Node() for j in xrange(w)] for i in xrange(h)] while True: set_boundary(m) if calc_difference(m, difference) < DIFF_THRESHOLD: break for i, di in enumerate(difference): for j, dij in enumerate(di): m[i][j].voltage -= dij.voltage cur = [0.0] * 3 for i, di in enumerate(difference): for j, dij in enumerate(di): cur[m[i][j].fixed] += (dij.voltage * (bool(i) + bool(j) + (i < h-1) + (j < w-1))) return (cur[Fixed.A] - cur[Fixed.B]) / 2.0 def main(): w = h = 10 mesh = [[Node() for j in xrange(w)] for i in xrange(h)] print % (2 / iter(mesh)) main()
347Resistor mesh
3python
ut5vd
my @symbols = ( [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ); sub roman { my($n, $r) = (shift, ''); ($r, $n) = ('-', -$n) if $n < 0; foreach my $s (@symbols) { my($arabic, $roman) = @$s; ($r, $n) = ($r .= $roman x int($n/$arabic), $n % $arabic) if $n >= $arabic; } $r; } say roman($_) for 1..2012;
341Roman numerals/Encode
2perl
43b5d
=> (keys (ns-interns 'clojure.set)) (union map-invert join select intersection superset? index bubble-max-key subset? rename rename-keys project difference) => (keys (ns-publics 'clojure.set)) (union map-invert join select intersection superset? index subset? rename rename-keys project difference)
355Reflection/List methods
6clojure
npwik
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); System.out.println("All public fields (including inherited):"); for (Field f : clazz.getFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } System.out.println(); System.out.println("All declared fields (excluding inherited):"); for (Field f : clazz.getDeclaredFields()) { System.out.printf("%s\t%s\n", f, f.get(obj)); } } }
354Reflection/List properties
9java
bl4k3
use strict; use warnings; use Class::Inspector; print Class::Inspector->resolved_filename( 'IO::Socket::INET' ), "\n";
351Reflection/Get source
2perl
okq8x
import os os.__file__
351Reflection/Get source
3python
ibsof
(import '(java.io File)) (.renameTo (File. "input.txt") (File. "output.txt")) (.renameTo (File. "docs") (File. "mydocs")) (.renameTo (File. (str (File/separator) "input.txt")) (File. (str (File/separator) "output.txt"))) (.renameTo (File. (str (File/separator) "docs")) (File. (str (File/separator) "mydocs")))
353Rename a file
6clojure
blgkz
var obj = Object.create({ name: 'proto', proto: true, doNothing: function() {} }, { name: {value: 'obj', writable: true, configurable: true, enumerable: true}, obj: {value: true, writable: true, configurable: true, enumerable: true}, 'non-enum': {value: 'non-enumerable', writable: true, enumerable: false}, doStuff: {value: function() {}, enumerable: true} });
354Reflection/List properties
10javascript
w4he2
require 'mathn' Math.method(:sqrt).source_location Class.method(:nesting).source_location
351Reflection/Get source
14ruby
d18ns
int main() { regex_t preg; regmatch_t substmatch[1]; const char *tp = ; const char *t1 = ; const char *t2 = ; const char *ss = ; regcomp(&preg, , REG_EXTENDED); printf(, t1, (regexec(&preg, t1, 0, NULL, 0)==0) ? : , tp); printf(, t2, (regexec(&preg, t2, 0, NULL, 0)==0) ? : , tp); regfree(&preg); regcomp(&preg, , REG_EXTENDED); if ( regexec(&preg, t1, 1, substmatch, 0) == 0 ) { char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) + (strlen(t1) - substmatch[0].rm_eo) + 2); memcpy(ns, t1, substmatch[0].rm_so+1); memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss)); memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo], strlen(&t1[substmatch[0].rm_eo])); ns[ substmatch[0].rm_so + strlen(ss) + strlen(&t1[substmatch[0].rm_eo]) ] = 0; printf(, ns); free(ns); } else { printf(, t1); } regfree(&preg); return 0; }
356Regular expressions
5c
ok180
void * record(size_t bytes) { int fd; if (-1 == (fd = open(, O_RDONLY))) return 0; void *a = malloc(bytes); read(fd, a, bytes); close(fd); return a; } int play(void *buf, size_t len) { int fd; if (-1 == (fd = open(, O_WRONLY))) return 0; write(fd, buf, len); close(fd); return 1; } int main() { void *p = record(65536); play(p, 65536); return 0; }
357Record sound
5c
1v5pj
package main import ( "fmt" "image" "reflect" ) type t int
355Reflection/List methods
0go
vd32m
null
354Reflection/List properties
11kotlin
r6lgo
int repstr(char *str) { if (!str) return 0; size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; } return 0; } int main(void) { char *strs[] = { , , , , , , , , , }; size_t strslen = sizeof(strs) / sizeof(strs[0]); size_t i; for (i = 0; i < strslen; ++i) { int n = repstr(strs[i]); if (n) printf(%s\%.*s\, strs[i], n, strs[i]); else printf(%s\, strs[i]); } return 0; }
358Rep-string
5c
tewf4
function int2roman($number) { if (!is_int($number) || $number < 1) return false; $integers = array(900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1); $numerals = array('CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'); $major = intval($number / 1000) * 1000; $minor = $number - $major; $numeral = $leastSig = ''; for ($i = 0; $i < sizeof($integers); $i++) { while ($minor >= $integers[$i]) { $leastSig .= $numerals[$i]; $minor -= $integers[$i]; } } if ($number >= 1000 && $number < 40000) { if ($major >= 10000) { $numeral .= '('; while ($major >= 10000) { $numeral .= 'X'; $major -= 10000; } $numeral .= ')'; } if ($major == 9000) { $numeral .= 'M(X)'; return $numeral . $leastSig; } if ($major == 4000) { $numeral .= 'M(V)'; return $numeral . $leastSig; } if ($major >= 5000) { $numeral .= '(V)'; $major -= 5000; } while ($major >= 1000) { $numeral .= 'M'; $major -= 1000; } } if ($number >= 40000) { $major = $major/1000; $numeral .= '(' . int2roman($major) . ')'; } return $numeral . $leastSig; }
341Roman numerals/Encode
12php
ip6ov
import java.lang.reflect.Method; public class ListMethods { public int examplePublicInstanceMethod(char c, double d) { return 42; } private boolean examplePrivateInstanceMethod(String s) { return true; } public static void main(String[] args) { Class clazz = ListMethods.class; System.out.println("All public methods (including inherited):"); for (Method m : clazz.getMethods()) { System.out.println(m); } System.out.println(); System.out.println("All declared methods (excluding inherited):"); for (Method m : clazz.getDeclaredMethods()) { System.out.println(m); } } }
355Reflection/List methods
9java
h9vjm
a = 1 b = 2.0 c = "hello world" function listProperties(t) if type(t) == "table" then for k,v in pairs(t) do if type(v) ~= "function" then print(string.format("%7s:%s", type(v), k)) end end end end print("Global properties") listProperties(_G) print("Package properties") listProperties(package)
354Reflection/List properties
1lua
7y2ru
null
355Reflection/List methods
10javascript
aur10
(defn rep-string [s] (let [len (count s) first-half (subs s 0 (/ len 2)) test-group (take-while seq (iterate butlast first-half)) test-reptd (map (comp #(take len %) cycle) test-group)] (some #(= (seq s) %) test-reptd)))
358Rep-string
6clojure
m08yq
(let [s "I am a string"] (when (re-find #"string$" s) (println "Ends with 'string'.")) (when-not (re-find #"^You" s) (println "Does not start with 'You'.")) (println (clojure.string/replace s " a " " another ")) )
356Regular expressions
6clojure
teqfv
def fromRoman(roman) r = roman.upcase n = 0 until r.empty? do case when r.start_with?('M') then v = 1000; len = 1 when r.start_with?('CM') then v = 900; len = 2 when r.start_with?('D') then v = 500; len = 1 when r.start_with?('CD') then v = 400; len = 2 when r.start_with?('C') then v = 100; len = 1 when r.start_with?('XC') then v = 90; len = 2 when r.start_with?('L') then v = 50; len = 1 when r.start_with?('XL') then v = 40; len = 2 when r.start_with?('X') then v = 10; len = 1 when r.start_with?('IX') then v = 9; len = 2 when r.start_with?('V') then v = 5; len = 1 when r.start_with?('IV') then v = 4; len = 2 when r.start_with?('I') then v = 1; len = 1 else raise ArgumentError.new( + roman) end n += v r.slice!(0,len) end n end [ , , ].each {|r| p r => fromRoman(r)}
340Roman numerals/Decode
14ruby
pv0bh
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) name := "" for name == "" { fmt.Print("Enter output file name (without extension): ") scanner.Scan() name = scanner.Text() check(scanner.Err()) } name += ".wav" rate := 0 for rate < 2000 || rate > 192000 { fmt.Print("Enter sampling rate in Hz (2000 to 192000): ") scanner.Scan() input := scanner.Text() check(scanner.Err()) rate, _ = strconv.Atoi(input) } rateS := strconv.Itoa(rate) dur := 0.0 for dur < 5 || dur > 30 { fmt.Print("Enter duration in seconds (5 to 30) : ") scanner.Scan() input := scanner.Text() check(scanner.Err()) dur, _ = strconv.ParseFloat(input, 64) } durS := strconv.FormatFloat(dur, 'f', -1, 64) fmt.Println("OK, start speaking now...")
357Record sound
0go
ys864
null
355Reflection/List methods
11kotlin
4zm57
{ package Point; use Class::Spiffy -base; field 'x'; field 'y'; } { package Circle; use base qw(Point); field 'r'; } my $p1 = Point->new(x => 8, y => -5); my $c1 = Circle->new(r => 4); my $c2 = Circle->new(x => 1, y => 2, r => 3); use Data::Dumper; say Dumper $p1; say Dumper $c1; say Dumper $c2;
354Reflection/List properties
2perl
d1qnw
RegExp regexp = new RegExp(r'\w+\!'); String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}'; void main(){ String hello = 'hello hello! world world!'; String hellomodified = hello.replaceAllMapped(regexp, capitalize); print(hello); print(hellomodified); }
356Regular expressions
18dart
w47eo
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
352Repeat
0go
blrkh
import Control.Monad (replicateM_) sampleFunction :: IO () sampleFunction = putStrLn "a" main = replicateM_ 5 sampleFunction
352Repeat
8haskell
d10n4
null
357Record sound
11kotlin
con98
function helloWorld() print "Hello World" end
355Reflection/List methods
1lua
g394j
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
354Reflection/List properties
12php
jmv7z
struct RomanNumeral { symbol: &'static str, value: u32 } const NUMERALS: [RomanNumeral; 13] = [ RomanNumeral {symbol: "M", value: 1000}, RomanNumeral {symbol: "CM", value: 900}, RomanNumeral {symbol: "D", value: 500}, RomanNumeral {symbol: "CD", value: 400}, RomanNumeral {symbol: "C", value: 100}, RomanNumeral {symbol: "XC", value: 90}, RomanNumeral {symbol: "L", value: 50}, RomanNumeral {symbol: "XL", value: 40}, RomanNumeral {symbol: "X", value: 10}, RomanNumeral {symbol: "IX", value: 9}, RomanNumeral {symbol: "V", value: 5}, RomanNumeral {symbol: "IV", value: 4}, RomanNumeral {symbol: "I", value: 1} ]; fn to_hindu(roman: &str) -> u32 { match NUMERALS.iter().find(|num| roman.starts_with(num.symbol)) { Some(num) => num.value + to_hindu(&roman[num.symbol.len()..]), None => 0,
340Roman numerals/Decode
15rust
1u8pu
char * string_repeat( int n, const char * s ) { size_t slen = strlen(s); char * dest = malloc(n*slen+1); int i; char * p; for ( i=0, p = dest; i < n; ++i, p += slen ) { memcpy(p, s, slen); } *p = '\0'; return dest; } int main() { char * result = string_repeat(5, ); puts(result); free(result); return 0; }
359Repeat a string
5c
2nnlo
import java.util.function.Consumer; import java.util.stream.IntStream; public class Repeat { public static void main(String[] args) { repeat(3, (x) -> System.out.println("Example " + x)); } static void repeat (int n, Consumer<Integer> fun) { IntStream.range(0, n).forEach(i -> fun.accept(i + 1)); } }
352Repeat
9java
s7aq0
>>> u'foo'.encode('rot13') 'sbb' >>> 'sbb'.decode('rot13') u'foo'
338Rot-13
3python
rywgq
def fromRoman( r:String ) : Int = { val arabicNumerals = List("CM"->900,"M"->1000,"CD"->400,"D"->500,"XC"->90,"C"->100, "XL"->40,"L"->50,"IX"->9,"X"->10,"IV"->4,"V"->5,"I"->1) var s = r arabicNumerals.foldLeft(0){ (n,t) => { val l = s.length; s = s.replaceAll(t._1,""); val c = (l - s.length)/t._1.length
340Roman numerals/Decode
16scala
wgnes
int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR(, argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR(, start); if ((fp = fopen(argv[1], )) == NULL) ERROR(, argv[1]); fseek(fp, 0, SEEK_END); sz = ftell(fp); buf = malloc(sz + 1); rewind(fp); while ((buf[++pos] = fgetc(fp)) != EOF) { if (buf[pos] == '\n') { ++lines; if (lines == start) dest = pos + 1; if (lines == start + count) src = pos + 1; } } if (start + count > lines) { free(buf); fclose(fp); ERROR(, --lines); } memmove(buf + dest, buf + src, pos - src); freopen(argv[1], , fp); fwrite(buf, pos - src + dest, 1, fp); free(buf); fclose(fp); return 0; }
360Remove lines from a file
5c
p2lby
package Nums; use overload ('<=>' => \&compare); sub new { my $self = shift; bless [@_] } sub flip { my @a = @_; 1/$a } sub double { my @a = @_; 2*$a } sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) } my $a = Nums->new(42); print "$_\n" for %{ref ($a)."::" });
355Reflection/List methods
2perl
ibeo3
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)'% (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)__') __reBleh = re.compile('\Wbleh$') @property def reBleh(self): return self.__reBleh def __init__(self, name, *args): super(Child, self).__init__(name) self.args = args def __dir__(self): myDir = filter( lambda p: not self.__rePrivate.match(p), list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ ))) return myDir + map( lambda p: p + '_bleh', filter( lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)), myDir)) def __getattr__(self, name): if name[-5:] == '_bleh': return str(getattr(self, name[:-5])) + ' bleh' if hasattr(super(Child, chld), '__getattr__'): return super(Child, self).__getattr__(name) raise AttributeError(% (type(self).__name__, name)) def __setattr__(self, name, value): if name[-5:] == '_bleh': if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))): setattr(self, name[:-5], self.reBleh.sub('', value)) elif hasattr(super(Child, self), '__setattr__'): super(Child, self).__setattr__(name, value) elif hasattr(self, '__dict__'): self.__dict__[name] = value def __repr__(self): return '%s(%s,%s)'% (type(self).__name__, self.name, str(self.args).strip('[]()')) def doStuff(self): return (1+1.0/1e6) ** 1e6 par = Parent('par') par.parent = True dir(par) inspect.getmembers(par) chld = Child('chld', 0, 'I', 'two') chld.own = dir(chld) inspect.getmembers(chld)
354Reflection/List properties
3python
fasde
null
352Repeat
11kotlin
auh13
package main import "os" func main() { os.Rename("input.txt", "output.txt") os.Rename("docs", "mydocs") os.Rename("/input.txt", "/output.txt") os.Rename("/docs", "/mydocs") }
353Rename a file
0go
npqi1
['input.txt':'output.txt', 'docs':'mydocs'].each { src, dst -> ['.', ''].each { dir -> new File("$dir/$src").renameTo(new File("$dir/$dst")) } }
353Rename a file
7groovy
s71q1
package main import ( "fmt" "strings" )
349Reverse words in a string
0go
ok08q
import pyaudio chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) data = stream.read(chunk) print [ord(i) for i in data]
357Record sound
3python
qrjxi
<? class Foo { function bar(int $x) { } } $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo ; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
355Reflection/List methods
12php
r6cge
class Foo @@xyz = nil def initialize(name, age) @name, @age = name, age end def add_sex(sex) @sex = sex end end p foo = Foo.new(, 18) p foo.instance_variables p foo.instance_variable_defined?(:@age) p foo.instance_variable_get(:@age) p foo.instance_variable_set(:@age, 19) p foo foo.add_sex(:woman) p foo.instance_variables p foo foo.instance_variable_set(:@bar, nil) p foo.instance_variables p Foo.class_variables p Foo.class_variable_defined?(:@@xyz) p Foo.class_variable_get(:@@xyz) p Foo.class_variable_set(:@@xyz, :xyz) p Foo.class_variable_get(:@@xyz) p Foo.class_variable_set(:@@abc, 123) p Foo.class_variables
354Reflection/List properties
14ruby
zw8tw
import System.IO import System.Directory main = do renameFile "input.txt" "output.txt" renameDirectory "docs" "mydocs" renameFile "/input.txt" "/output.txt" renameDirectory "/docs" "/mydocs"
353Rename a file
8haskell
ufmv2
def text = new StringBuilder() .append('---------- Ice and Fire ------------\n') .append(' \n') .append('fire, in end will world the say Some\n') .append('ice. in say Some \n') .append('desire of tasted I\'ve what From \n') .append('fire. favor who those with hold I \n') .append(' \n') .append('... elided paragraph last ... \n') .append(' \n') .append('Frost Robert -----------------------\n').toString() text.eachLine { line -> println "$line --> ${line.split(' ').reverse().join(' ')}" }
349Reverse words in a string
7groovy
xgewl
typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; g_hash_table_add(used, GINT_TO_POINTER(0)); g_hash_table_add(used1000, GINT_TO_POINTER(0)); for (n = 1; n <= 15 || !foundDup || k < 1001; ++n) { next = a[n - 1] - n; if (next < 1 || g_hash_table_contains(used, GINT_TO_POINTER(next))) { next += 2 * n; } alreadyUsed = g_hash_table_contains(used, GINT_TO_POINTER(next)); a[n] = next; if (!alreadyUsed) { g_hash_table_add(used, GINT_TO_POINTER(next)); if (next >= 0 && next <= 1000) { g_hash_table_add(used1000, GINT_TO_POINTER(next)); } } if (n == 14) { printf(); printf(); for (i = 0; i < 15; ++i) printf(, a[i]); printf(); } if (!foundDup && alreadyUsed) { printf(, n, next); foundDup = TRUE; } k = g_hash_table_size(used1000); if (k == 1001) { printf(, n); } } g_hash_table_destroy(used); g_hash_table_destroy(used1000); free(a); return 0; }
361Recaman's sequence
5c
w4uec
import java.io.{File, IOException} import javax.sound.sampled.{AudioFileFormat, AudioFormat, AudioInputStream} import javax.sound.sampled.{AudioSystem, DataLine, LineUnavailableException, TargetDataLine} object SoundRecorder extends App {
357Record sound
16scala
npaic
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Super method' @staticmethod def supStatic(): return 'static method' class Other(object): def otherMethod(self): return 'other method' class Sub(Other, Super): def __init__(self, name, *args): super(Sub, self).__init__(name); self.rest = args; self.methods = {} def __dir__(self): return list(set( \ sum([dir(base) for base in type(self).__bases__], []) \ + type(self).__dict__.keys() \ + self.__dict__.keys() \ + self.methods.keys() \ )) def __getattr__(self, name): if name in self.methods: if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0: if self.methods[name].__code__.co_varnames[0] == 'self': return self.methods[name].__get__(self, type(self)) if self.methods[name].__code__.co_varnames[0] == 'cls': return self.methods[name].__get__(type(self), type) return self.methods[name] raise AttributeError(% (type(self).__name__, name)) def __str__(self): return % self.name def doSub(): return 'did sub stuff' @classmethod def cls(cls): return 'cls method (in Sub)' @classmethod def subCls(cls): return 'Sub method' @staticmethod def subStatic(): return 'Sub method' sup = Super('sup') sub = Sub('sub', 0, 'I', 'two') sub.methods['incr'] = lambda x: x+1 sub.methods['strs'] = lambda self, x: str(self) * x [method for method in dir(sub) if callable(getattr(sub, method))] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub] [method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)] [method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)] inspect.getmembers(sub, predicate=inspect.ismethod) map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
355Reflection/List methods
3python
npwiz
object ListProperties extends App { private val obj = new { val examplePublicField: Int = 42 private val examplePrivateField: Boolean = true } private val clazz = obj.getClass println("All public methods (including inherited):") clazz.getFields.foreach(f => println(s"${f}\t${f.get(obj)}")) println("\nAll declared fields (excluding inherited):") clazz.getDeclaredFields.foreach(f => println(s"${f}}")) }
354Reflection/List properties
16scala
m0dyc
function myFunc () print("Sure looks like a function in here...") end function rep (func, times) for count = 1, times do func() end end rep(myFunc, 4)
352Repeat
1lua
e5kac
revstr :: String -> String revstr = unwords . reverse . words revtext :: String -> String revtext = unlines . map revstr . lines test = revtext " \\n\ \fire, in end will world the say Some\n\ \ice. in say Some\n\ \desire of tasted I've what From\n\ \fire. favor who those with hold I\n\ \\n\ \... elided paragraph last ...\n\ \\n\ \Frost Robert
349Reverse words in a string
8haskell
2ncll
rot13 <- function(x) { old <- paste(letters, LETTERS, collapse="", sep="") new <- paste(substr(old, 27, 52), substr(old, 1, 26), sep="") chartr(old, new, x) } x <- "The Quick Brown Fox Jumps Over The Lazy Dog!.,:;' rot13(x) x2 <- paste(letters, LETTERS, collapse="", sep="") rot13(x2)
338Rot-13
13r
utpvx
(apply str (repeat 5 "ha"))
359Repeat a string
6clojure
g334f
(require '[clojure.java.io:as jio] '[clojure.string:as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lines))] (when-not (zero? diff) (println "WARN: You are trying to remove lines beyond EOF")) (with-open [wrt (jio/writer (str filepath ".tmp"))] (.write wrt (str/join "\n" new-lines))) (.renameTo (jio/file (str filepath ".tmp")) (jio/file filepath))))
360Remove lines from a file
6clojure
xg4wk
func addsub(x, y int) (int, int) { return x + y, x - y }
348Return multiple values
0go
a5a1f
def addSub(x,y) { [ sum: x+y, difference: x-y ] }
348Return multiple values
7groovy
hchj9
class Super CLASSNAME = 'super' def initialize(name) @name = name def self.superOwn 'super owned' end end def to_s end def doSup 'did super stuff' end def self.superClassStuff 'did super class stuff' end protected def protSup end private def privSup end end module Other def otherStuff 'did other stuff' end end class Sub < Super CLASSNAME = 'sub' attr_reader :dynamic include Other def initialize(name, *args) super(name) @rest = args; @dynamic = {} def self.subOwn 'sub owned' end end def methods(regular=true) super + @dynamic.keys end def method_missing(name, *args, &block) return super unless @dynamic.member?(name) method = @dynamic[name] if method.arity > 0 if method.parameters[0][1] ==:self args.unshift(self) end if method.lambda? args += args + [nil] * [method.arity - args.length, 0].max if method.parameters[-1][0]!= :rest args = args[0,method.arity] end end method.call(*args) else method.call end end def public_methods(all=true) super + @dynamic.keys end def respond_to?(symbol, include_all=false) @dynamic.member?(symbol) || super end def to_s end def doSub 'did sub stuff' end def self.subClassStuff 'did sub class stuff' end protected def protSub end private def privSub end end sup = Super.new('sup') sub = Sub.new('sub', 0, 'I', 'two') sub.dynamic[:incr] = proc {|i| i+1} p sub.public_methods(false) p sub.methods - Object.methods p sub.public_methods - Object.public_methods p sub.methods - sup.methods p sub.methods(false) p sub.singleton_methods
355Reflection/List methods
14ruby
faqdr
import java.io.File; public class FileRenameTest { public static boolean renameFile(String oldname, String newname) {
353Rename a file
9java
m0fym
public class ReverseWords { static final String[] lines = { " ----------- Ice and Fire ----------- ", " ", " fire, in end will world the say Some ", " ice. in say Some ", " desire of tasted I've what From ", " fire. favor who those with hold I ", " ", " ... elided paragraph last ... ", " Frost Robert ----------------------- "}; public static void main(String[] args) { for (String line : lines) { String[] words = line.split("\\s"); for (int i = words.length - 1; i >= 0; i--) System.out.printf("%s ", words[i]); System.out.println(); } } }
349Reverse words in a string
9java
6qz3z
addsub x y = (x + y, x - y)
348Return multiple values
8haskell
zxzt0
object ListMethods extends App { private val obj = new { def examplePublicInstanceMethod(c: Char, d: Double) = 42 private def examplePrivateInstanceMethod(s: String) = true } private val clazz = obj.getClass println("All public methods (including inherited):") clazz.getMethods.foreach(m => println(s"${m}")) println("\nAll declared fields (excluding inherited):") clazz.getDeclaredMethods.foreach(m => println(s"${m}}")) }
355Reflection/List methods
16scala
6qo31
package main import "fmt" import "regexp" func main() { str := "I am the original string"
356Regular expressions
0go
4zy52
var fso = new ActiveXObject("Scripting.FileSystemObject") fso.MoveFile("input.txt", "output.txt") fso.MoveFile("c:/input.txt", "c:/output.txt") fso.MoveFolder("docs", "mydocs") fso.MoveFolder("c:/docs", "c:/mydocs")
353Rename a file
10javascript
vdy25
var strReversed = "---------- Ice and Fire ------------\n\ \n\ fire, in end will world the say Some\n\ ice. in say Some\n\ desire of tasted I've what From\n\ fire. favor who those with hold I\n\ \n\ ... elided paragraph last ...\n\ \n\ Frost Robert -----------------------"; function reverseString(s) { return s.split('\n').map( function (line) { return line.split(/\s/).reverse().join(' '); } ).join('\n'); } console.log( reverseString(strReversed) );
349Reverse words in a string
10javascript
li9cf
import roman print(roman.toRoman(2022))
341Roman numerals/Encode
3python
g6p4h
import java.util.regex.*; def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" def pepper = "Peter Piper picked a peck of pickled peppers" println "=== Regular-expression String syntax (/string/) ===" def woodRE = /[Ww]o\w+d/ def piperRE = /[Pp]\w+r/ assert woodRE instanceof String && piperRE instanceof String assert (/[Ww]o\w+d/ == "[Ww]o\\w+d") && (/[Pp]\w+r/ == "[Pp]\\w+r") println ([woodRE: woodRE, piperRE: piperRE]) println () println "=== Pattern (~) operator ===" def woodPat = ~/[Ww]o\w+d/ def piperPat = ~piperRE assert woodPat instanceof Pattern && piperPat instanceof Pattern def woodList = woodchuck.split().grep(woodPat) println ([exactTokenMatches: woodList]) println ([exactTokenMatches: pepper.split().grep(piperPat)]) println () println "=== Matcher (=~) operator ===" def wwMatcher = (woodchuck =~ woodRE) def ppMatcher = (pepper =~ /[Pp]\w+r/) def wpMatcher = (woodchuck =~ /[Pp]\w+r/) assert wwMatcher instanceof Matcher && ppMatcher instanceof Matcher assert wwMatcher.toString() == woodPat.matcher(woodchuck).toString() assert ppMatcher.toString() == piperPat.matcher(pepper).toString() assert wpMatcher.toString() == piperPat.matcher(woodchuck).toString() println ([ substringMatches: wwMatcher.collect { it }]) println ([ substringMatches: ppMatcher.collect { it }]) println ([ substringMatches: wpMatcher.collect { it }]) println () println "=== Exact Match (==~) operator ===" def containsWoodRE = /.*/ + woodRE + /.*/ def containsPiperRE = /.*/ + piperRE + /.*/ def wwMatches = (woodchuck ==~ containsWoodRE) assert wwMatches instanceof Boolean def wwNotMatches = ! (woodchuck ==~ woodRE) def ppMatches = (pepper ==~ containsPiperRE) def pwNotMatches = ! (pepper ==~ containsWoodRE) def wpNotMatches = ! (woodchuck ==~ containsPiperRE) assert wwMatches && wwNotMatches && ppMatches && pwNotMatches && pwNotMatches println ("'${woodchuck}' ${wwNotMatches? 'does not': 'does'} match '${woodRE}' exactly") println ("'${woodchuck}' ${wwMatches? 'does': 'does not'} match '${containsWoodRE}' exactly")
356Regular expressions
7groovy
lifc1
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap;
348Return multiple values
9java
obo8d
struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = start; for (;; n = n->next) {if (a[i] == n->x) break; if (n->next == NULL) {n->next = malloc(sizeof(node)); n = n->next; if (n == NULL) exit(EXIT_FAILURE); n->x = a[i]; n->next = NULL; break;}}} return start;} int main(void) {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4}; for (node *n = uniq(a, 10) ; n != NULL ; n = n->next) printf(, n->x); puts(); return 0;}
362Remove duplicate elements
5c
cos9c
import Text.Regex str = "I am a string" case matchRegex (mkRegex ".*string$") str of Just _ -> putStrLn $ "ends with 'string'" Nothing -> return ()
356Regular expressions
8haskell
qrhx9
null
353Rename a file
11kotlin
te8f0
extension Int { init(romanNumerals: String) { let values = [ ( "M", 1000), ("CM", 900), ( "D", 500), ("CD", 400), ( "C", 100), ("XC", 90), ( "L", 50), ("XL", 40), ( "X", 10), ("IX", 9), ( "V", 5), ("IV", 4), ( "I", 1), ] self = 0 var raw = romanNumerals for (digit, value) in values { while raw.hasPrefix(digit) { self += value raw.removeFirst(digit.count) } } } }
340Roman numerals/Decode
17swift
b2skd
null
348Return multiple values
10javascript
twtfm
package main import ( "fmt" "strings" ) func rep(s string) int { for x := len(s) / 2; x > 0; x-- { if strings.HasPrefix(s, s[x:]) { return x } } return 0 } const m = ` 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1` func main() { for _, s := range strings.Fields(m) { if n := rep(s); n > 0 { fmt.Printf("%q %d rep-string%q\n", s, n, s[:n]) } else { fmt.Printf("%q not a rep-string\n", s) } } }
358Rep-string
0go
h9cjq
fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ") fun main() { val s = "Hey you, Bub!" println(reversedWords(s)) println() val sl = listOf( " ---------- Ice and Fire ------------ ", " ", " fire, in end will world the say Some ", " ice. in say Some ", " desire of tasted I've what From ", " fire. favor who those with hold I ", " ", " ... elided paragraph last ... ", " ", " Frost Robert ----------------------- ", ) sl.forEach { println(reversedWords(it)) } }
349Reverse words in a string
11kotlin
d1inz
as.roman(1666)
341Roman numerals/Encode
13r
vfj27
int main() { char *buffer; FILE *fh = fopen(, ); if ( fh != NULL ) { fseek(fh, 0L, SEEK_END); long s = ftell(fh); rewind(fh); buffer = malloc(s); if ( buffer != NULL ) { fread(buffer, s, 1, fh); fclose(fh); fh = NULL; fwrite(buffer, s, 1, stdout); free(buffer); } if (fh != NULL) fclose(fh); } return EXIT_SUCCESS; }
363Read entire file
5c
liscy
import Data.List (inits, maximumBy) import Data.Maybe (fromMaybe) repstring :: String -> Maybe String repstring [] = Nothing repstring [_] = Nothing repstring xs | any (`notElem` "01") xs = Nothing | otherwise = longest xs where lxs = length xs lq2 = lxs `quot` 2 subrepeat x = (x, take lxs $ concat $ repeat x) sndValid (_, ys) = ys == xs possible = map subrepeat . take lq2 . tail . inits valid = map fst . filter sndValid . possible compLength a b = compare (length a) (length b) longest ys = case valid ys of [] -> Nothing zs -> Just $ maximumBy compLength zs main :: IO () main = mapM_ processIO examples where examples = [ "1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" ] process = fromMaybe "Not a rep string" . repstring processIO xs = do putStr (xs <> ": ") putStrLn $ process xs
358Rep-string
8haskell
ibpor
null
348Return multiple values
11kotlin
xrxws
String str = "I am a string"; if (str.matches(".*string")) {
356Regular expressions
9java
p25b3
var subject = "Hello world!";
356Regular expressions
10javascript
xgjw9
sub repeat { my ($sub, $n) = @_; $sub->() for 1..$n; } sub example { print "Example\n"; } repeat(\&example, 4);
352Repeat
2perl
98zmn
os.rename( "input.txt", "output.txt" ) os.rename( "/input.txt", "/output.txt" ) os.rename( "docs", "mydocs" ) os.rename( "/docs", "/mydocs" )
353Rename a file
1lua
zwoty
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] =%d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
361Recaman's sequence
0go
co09g
typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->dim_x = x_dim; m->dim_y = y_dim; m->m_stor = TALLOC(n, EL_Type); m->mtx = TALLOC(m->dim_y, EL_Type *); for(n=0; n<y_dim; n++) { m->mtx[n] = m->m_stor+n*x_dim; } return m; } void MtxSetRow(Matrix m, int irow, EL_Type *v) { int ix; EL_Type *mr; mr = m->mtx[irow]; for(ix=0; ix<m->dim_x; ix++) mr[ix] = v[ix]; } Matrix InitMatrix( int x_dim, int y_dim, EL_Type **v) { Matrix m; int iy; m = NewMatrix(x_dim, y_dim); for (iy=0; iy<y_dim; iy++) MtxSetRow(m, iy, v[iy]); return m; } void MtxDisplay( Matrix m ) { int iy, ix; const char *sc; for (iy=0; iy<m->dim_y; iy++) { printf(); sc = ; for (ix=0; ix<m->dim_x; ix++) { printf(, sc, m->mtx[iy][ix]); sc = ; } printf(); } printf(); } void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) { int ix; EL_Type *drow, *srow; drow = m->mtx[ixrdest]; srow = m->mtx[ixrsrc]; for (ix=0; ix<m->dim_x; ix++) drow[ix] += mplr * srow[ix]; } void MtxSwapRows( Matrix m, int rix1, int rix2) { EL_Type *r1, *r2, temp; int ix; if (rix1 == rix2) return; r1 = m->mtx[rix1]; r2 = m->mtx[rix2]; for (ix=0; ix<m->dim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; } void MtxNormalizeRow( Matrix m, int rix, int lead) { int ix; EL_Type *drow; EL_Type lv; drow = m->mtx[rix]; lv = drow[lead]; for (ix=0; ix<m->dim_x; ix++) drow[ix] /= lv; } void MtxToReducedREForm(Matrix m) { int lead; int rix, iix; EL_Type lv; int rowCount = m->dim_y; lead = 0; for (rix=0; rix<rowCount; rix++) { if (lead >= m->dim_x) return; iix = rix; while (0 == MtxGet(m, iix,lead)) { iix++; if (iix == rowCount) { iix = rix; lead++; if (lead == m->dim_x) return; } } MtxSwapRows(m, iix, rix ); MtxNormalizeRow(m, rix, lead ); for (iix=0; iix<rowCount; iix++) { if ( iix != rix ) { lv = MtxGet(m, iix, lead ); MtxMulAndAddRows(m,iix, rix, -lv) ; } } lead++; } } int main() { Matrix m1; static EL_Type r1[] = {1,2,-1,-4}; static EL_Type r2[] = {2,3,-1,-11}; static EL_Type r3[] = {-2,0,-3,22}; static EL_Type *im[] = { r1, r2, r3 }; m1 = InitMatrix( 4,3, im ); printf(); MtxDisplay(m1); MtxToReducedREForm(m1); printf(); MtxDisplay(m1); return 0; }
364Reduced row echelon form
5c
zwbtx
(slurp "myfile.txt") (slurp "my-utf8-file.txt" "UTF-8")
363Read entire file
6clojure
4zn5o
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s:%s%n", s, repString(s)); } static String repString(String s) { int len = s.length(); outer: for (int part = len / 2; part > 0; part--) { int tail = len % part; if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail))) continue; for (int j = 0; j < len / part - 1; j++) { int a = j * part; int b = (j + 1) * part; int c = (j + 2) * part; if (!s.substring(a, b).equals(s.substring(b, c))) continue outer; } return s.substring(0, part); } return "none"; } }
358Rep-string
9java
xgrwy
def rot13(s) s.tr('A-Za-z', 'N-ZA-Mn-za-m') end while line = ARGF.gets print rot13(line) end
338Rot-13
14ruby
j9q7x